Remove unused variable in ProfilerMwprof
[mediawiki.git] / includes / User.php
blob2fa684967c53c1dce8fbde7c8797845c75abf475
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * String Some punctuation to prevent editing from broken text-mangling proxies.
25 * @ingroup Constants
27 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
29 /**
30 * The User object encapsulates all of the user-specific settings (user_id,
31 * name, rights, password, email address, options, last login time). Client
32 * classes use the getXXX() functions to access these fields. These functions
33 * do all the work of determining whether the user is logged in,
34 * whether the requested option can be satisfied from cookies or
35 * whether a database query is needed. Most of the settings needed
36 * for rendering normal pages are set in the cookie to minimize use
37 * of the database.
39 class User implements IDBAccessObject {
40 /**
41 * @const int Number of characters in user_token field.
43 const TOKEN_LENGTH = 32;
45 /**
46 * Global constant made accessible as class constants so that autoloader
47 * magic can be used.
49 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
51 /**
52 * @const int Serialized record version.
54 const VERSION = 10;
56 /**
57 * Maximum items in $mWatchedItems
59 const MAX_WATCHED_ITEMS_CACHE = 100;
61 /**
62 * @var PasswordFactory Lazily loaded factory object for passwords
64 private static $mPasswordFactory = null;
66 /**
67 * Array of Strings List of member variables which are saved to the
68 * shared cache (memcached). Any operation which changes the
69 * corresponding database fields must call a cache-clearing function.
70 * @showinitializer
72 protected static $mCacheVars = array(
73 // user table
74 'mId',
75 'mName',
76 'mRealName',
77 'mEmail',
78 'mTouched',
79 'mToken',
80 'mEmailAuthenticated',
81 'mEmailToken',
82 'mEmailTokenExpires',
83 'mRegistration',
84 'mEditCount',
85 // user_groups table
86 'mGroups',
87 // user_properties table
88 'mOptionOverrides',
91 /**
92 * Array of Strings Core rights.
93 * Each of these should have a corresponding message of the form
94 * "right-$right".
95 * @showinitializer
97 protected static $mCoreRights = array(
98 'apihighlimits',
99 'autoconfirmed',
100 'autopatrol',
101 'bigdelete',
102 'block',
103 'blockemail',
104 'bot',
105 'browsearchive',
106 'createaccount',
107 'createpage',
108 'createtalk',
109 'delete',
110 'deletedhistory',
111 'deletedtext',
112 'deletelogentry',
113 'deleterevision',
114 'edit',
115 'editinterface',
116 'editprotected',
117 'editmyoptions',
118 'editmyprivateinfo',
119 'editmyusercss',
120 'editmyuserjs',
121 'editmywatchlist',
122 'editsemiprotected',
123 'editusercssjs', #deprecated
124 'editusercss',
125 'edituserjs',
126 'hideuser',
127 'import',
128 'importupload',
129 'ipblock-exempt',
130 'markbotedits',
131 'mergehistory',
132 'minoredit',
133 'move',
134 'movefile',
135 'move-categorypages',
136 'move-rootuserpages',
137 'move-subpages',
138 'nominornewtalk',
139 'noratelimit',
140 'override-export-depth',
141 'pagelang',
142 'passwordreset',
143 'patrol',
144 'patrolmarks',
145 'protect',
146 'proxyunbannable',
147 'purge',
148 'read',
149 'reupload',
150 'reupload-own',
151 'reupload-shared',
152 'rollback',
153 'sendemail',
154 'siteadmin',
155 'suppressionlog',
156 'suppressredirect',
157 'suppressrevision',
158 'unblockself',
159 'undelete',
160 'unwatchedpages',
161 'upload',
162 'upload_by_url',
163 'userrights',
164 'userrights-interwiki',
165 'viewmyprivateinfo',
166 'viewmywatchlist',
167 'viewsuppressed',
168 'writeapi',
172 * String Cached results of getAllRights()
174 protected static $mAllRights = false;
176 /** @name Cache variables */
177 //@{
178 public $mId;
180 public $mName;
182 public $mRealName;
185 * @todo Make this actually private
186 * @private
188 public $mPassword;
191 * @todo Make this actually private
192 * @private
194 public $mNewpassword;
196 public $mNewpassTime;
198 public $mEmail;
200 public $mTouched;
202 protected $mToken;
204 public $mEmailAuthenticated;
206 protected $mEmailToken;
208 protected $mEmailTokenExpires;
210 protected $mRegistration;
212 protected $mEditCount;
214 public $mGroups;
216 protected $mOptionOverrides;
218 protected $mPasswordExpires;
219 //@}
222 * Bool Whether the cache variables have been loaded.
224 //@{
225 public $mOptionsLoaded;
228 * Array with already loaded items or true if all items have been loaded.
230 protected $mLoadedItems = array();
231 //@}
234 * String Initialization data source if mLoadedItems!==true. May be one of:
235 * - 'defaults' anonymous user initialised from class defaults
236 * - 'name' initialise from mName
237 * - 'id' initialise from mId
238 * - 'session' log in from cookies or session if possible
240 * Use the User::newFrom*() family of functions to set this.
242 public $mFrom;
245 * Lazy-initialized variables, invalidated with clearInstanceCache
247 protected $mNewtalk;
249 protected $mDatePreference;
251 public $mBlockedby;
253 protected $mHash;
255 public $mRights;
257 protected $mBlockreason;
259 protected $mEffectiveGroups;
261 protected $mImplicitGroups;
263 protected $mFormerGroups;
265 protected $mBlockedGlobally;
267 protected $mLocked;
269 public $mHideName;
271 public $mOptions;
274 * @var WebRequest
276 private $mRequest;
278 /** @var Block */
279 public $mBlock;
281 /** @var bool */
282 protected $mAllowUsertalk;
284 /** @var Block */
285 private $mBlockedFromCreateAccount = false;
287 /** @var array */
288 private $mWatchedItems = array();
290 public static $idCacheByName = array();
293 * Lightweight constructor for an anonymous user.
294 * Use the User::newFrom* factory functions for other kinds of users.
296 * @see newFromName()
297 * @see newFromId()
298 * @see newFromConfirmationCode()
299 * @see newFromSession()
300 * @see newFromRow()
302 public function __construct() {
303 $this->clearInstanceCache( 'defaults' );
307 * @return string
309 public function __toString() {
310 return $this->getName();
314 * Load the user table data for this object from the source given by mFrom.
316 public function load() {
317 if ( $this->mLoadedItems === true ) {
318 return;
320 wfProfileIn( __METHOD__ );
322 // Set it now to avoid infinite recursion in accessors
323 $this->mLoadedItems = true;
325 switch ( $this->mFrom ) {
326 case 'defaults':
327 $this->loadDefaults();
328 break;
329 case 'name':
330 $this->mId = self::idFromName( $this->mName );
331 if ( !$this->mId ) {
332 // Nonexistent user placeholder object
333 $this->loadDefaults( $this->mName );
334 } else {
335 $this->loadFromId();
337 break;
338 case 'id':
339 $this->loadFromId();
340 break;
341 case 'session':
342 if ( !$this->loadFromSession() ) {
343 // Loading from session failed. Load defaults.
344 $this->loadDefaults();
346 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
347 break;
348 default:
349 wfProfileOut( __METHOD__ );
350 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
352 wfProfileOut( __METHOD__ );
356 * Load user table data, given mId has already been set.
357 * @return bool False if the ID does not exist, true otherwise
359 public function loadFromId() {
360 if ( $this->mId == 0 ) {
361 $this->loadDefaults();
362 return false;
365 // Try cache
366 $cache = $this->loadFromCache();
367 if ( !$cache ) {
368 wfDebug( "User: cache miss for user {$this->mId}\n" );
369 // Load from DB
370 if ( !$this->loadFromDatabase() ) {
371 // Can't load from ID, user is anonymous
372 return false;
374 $this->saveToCache();
377 $this->mLoadedItems = true;
379 return true;
383 * Load user data from shared cache, given mId has already been set.
385 * @return bool false if the ID does not exist or data is invalid, true otherwise
386 * @since 1.25
388 public function loadFromCache() {
389 global $wgMemc;
391 if ( $this->mId == 0 ) {
392 $this->loadDefaults();
393 return false;
396 $key = wfMemcKey( 'user', 'id', $this->mId );
397 $data = $wgMemc->get( $key );
398 if ( !is_array( $data ) || $data['mVersion'] < self::VERSION ) {
399 // Object is expired
400 return false;
403 wfDebug( "User: got user {$this->mId} from cache\n" );
405 // Restore from cache
406 foreach ( self::$mCacheVars as $name ) {
407 $this->$name = $data[$name];
410 return true;
414 * Save user data to the shared cache
416 public function saveToCache() {
417 $this->load();
418 $this->loadGroups();
419 $this->loadOptions();
420 if ( $this->isAnon() ) {
421 // Anonymous users are uncached
422 return;
424 $data = array();
425 foreach ( self::$mCacheVars as $name ) {
426 $data[$name] = $this->$name;
428 $data['mVersion'] = self::VERSION;
429 $key = wfMemcKey( 'user', 'id', $this->mId );
430 global $wgMemc;
431 $wgMemc->set( $key, $data );
434 /** @name newFrom*() static factory methods */
435 //@{
438 * Static factory method for creation from username.
440 * This is slightly less efficient than newFromId(), so use newFromId() if
441 * you have both an ID and a name handy.
443 * @param string $name Username, validated by Title::newFromText()
444 * @param string|bool $validate Validate username. Takes the same parameters as
445 * User::getCanonicalName(), except that true is accepted as an alias
446 * for 'valid', for BC.
448 * @return User|bool User object, or false if the username is invalid
449 * (e.g. if it contains illegal characters or is an IP address). If the
450 * username is not present in the database, the result will be a user object
451 * with a name, zero user ID and default settings.
453 public static function newFromName( $name, $validate = 'valid' ) {
454 if ( $validate === true ) {
455 $validate = 'valid';
457 $name = self::getCanonicalName( $name, $validate );
458 if ( $name === false ) {
459 return false;
460 } else {
461 // Create unloaded user object
462 $u = new User;
463 $u->mName = $name;
464 $u->mFrom = 'name';
465 $u->setItemLoaded( 'name' );
466 return $u;
471 * Static factory method for creation from a given user ID.
473 * @param int $id Valid user ID
474 * @return User The corresponding User object
476 public static function newFromId( $id ) {
477 $u = new User;
478 $u->mId = $id;
479 $u->mFrom = 'id';
480 $u->setItemLoaded( 'id' );
481 return $u;
485 * Factory method to fetch whichever user has a given email confirmation code.
486 * This code is generated when an account is created or its e-mail address
487 * has changed.
489 * If the code is invalid or has expired, returns NULL.
491 * @param string $code Confirmation code
492 * @return User|null
494 public static function newFromConfirmationCode( $code ) {
495 $dbr = wfGetDB( DB_SLAVE );
496 $id = $dbr->selectField( 'user', 'user_id', array(
497 'user_email_token' => md5( $code ),
498 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
499 ) );
500 if ( $id !== false ) {
501 return User::newFromId( $id );
502 } else {
503 return null;
508 * Create a new user object using data from session or cookies. If the
509 * login credentials are invalid, the result is an anonymous user.
511 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
512 * @return User
514 public static function newFromSession( WebRequest $request = null ) {
515 $user = new User;
516 $user->mFrom = 'session';
517 $user->mRequest = $request;
518 return $user;
522 * Create a new user object from a user row.
523 * The row should have the following fields from the user table in it:
524 * - either user_name or user_id to load further data if needed (or both)
525 * - user_real_name
526 * - all other fields (email, password, etc.)
527 * It is useless to provide the remaining fields if either user_id,
528 * user_name and user_real_name are not provided because the whole row
529 * will be loaded once more from the database when accessing them.
531 * @param stdClass $row A row from the user table
532 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
533 * @return User
535 public static function newFromRow( $row, $data = null ) {
536 $user = new User;
537 $user->loadFromRow( $row, $data );
538 return $user;
541 //@}
544 * Get the username corresponding to a given user ID
545 * @param int $id User ID
546 * @return string|bool The corresponding username
548 public static function whoIs( $id ) {
549 return UserCache::singleton()->getProp( $id, 'name' );
553 * Get the real name of a user given their user ID
555 * @param int $id User ID
556 * @return string|bool The corresponding user's real name
558 public static function whoIsReal( $id ) {
559 return UserCache::singleton()->getProp( $id, 'real_name' );
563 * Get database id given a user name
564 * @param string $name Username
565 * @return int|null The corresponding user's ID, or null if user is nonexistent
567 public static function idFromName( $name ) {
568 $nt = Title::makeTitleSafe( NS_USER, $name );
569 if ( is_null( $nt ) ) {
570 // Illegal name
571 return null;
574 if ( isset( self::$idCacheByName[$name] ) ) {
575 return self::$idCacheByName[$name];
578 $dbr = wfGetDB( DB_SLAVE );
579 $s = $dbr->selectRow(
580 'user',
581 array( 'user_id' ),
582 array( 'user_name' => $nt->getText() ),
583 __METHOD__
586 if ( $s === false ) {
587 $result = null;
588 } else {
589 $result = $s->user_id;
592 self::$idCacheByName[$name] = $result;
594 if ( count( self::$idCacheByName ) > 1000 ) {
595 self::$idCacheByName = array();
598 return $result;
602 * Reset the cache used in idFromName(). For use in tests.
604 public static function resetIdByNameCache() {
605 self::$idCacheByName = array();
609 * Does the string match an anonymous IPv4 address?
611 * This function exists for username validation, in order to reject
612 * usernames which are similar in form to IP addresses. Strings such
613 * as 300.300.300.300 will return true because it looks like an IP
614 * address, despite not being strictly valid.
616 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
617 * address because the usemod software would "cloak" anonymous IP
618 * addresses like this, if we allowed accounts like this to be created
619 * new users could get the old edits of these anonymous users.
621 * @param string $name Name to match
622 * @return bool
624 public static function isIP( $name ) {
625 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
626 || IP::isIPv6( $name );
630 * Is the input a valid username?
632 * Checks if the input is a valid username, we don't want an empty string,
633 * an IP address, anything that contains slashes (would mess up subpages),
634 * is longer than the maximum allowed username size or doesn't begin with
635 * a capital letter.
637 * @param string $name Name to match
638 * @return bool
640 public static function isValidUserName( $name ) {
641 global $wgContLang, $wgMaxNameChars;
643 if ( $name == ''
644 || User::isIP( $name )
645 || strpos( $name, '/' ) !== false
646 || strlen( $name ) > $wgMaxNameChars
647 || $name != $wgContLang->ucfirst( $name ) ) {
648 wfDebugLog( 'username', __METHOD__ .
649 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
650 return false;
653 // Ensure that the name can't be misresolved as a different title,
654 // such as with extra namespace keys at the start.
655 $parsed = Title::newFromText( $name );
656 if ( is_null( $parsed )
657 || $parsed->getNamespace()
658 || strcmp( $name, $parsed->getPrefixedText() ) ) {
659 wfDebugLog( 'username', __METHOD__ .
660 ": '$name' invalid due to ambiguous prefixes" );
661 return false;
664 // Check an additional blacklist of troublemaker characters.
665 // Should these be merged into the title char list?
666 $unicodeBlacklist = '/[' .
667 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
668 '\x{00a0}' . # non-breaking space
669 '\x{2000}-\x{200f}' . # various whitespace
670 '\x{2028}-\x{202f}' . # breaks and control chars
671 '\x{3000}' . # ideographic space
672 '\x{e000}-\x{f8ff}' . # private use
673 ']/u';
674 if ( preg_match( $unicodeBlacklist, $name ) ) {
675 wfDebugLog( 'username', __METHOD__ .
676 ": '$name' invalid due to blacklisted characters" );
677 return false;
680 return true;
684 * Usernames which fail to pass this function will be blocked
685 * from user login and new account registrations, but may be used
686 * internally by batch processes.
688 * If an account already exists in this form, login will be blocked
689 * by a failure to pass this function.
691 * @param string $name Name to match
692 * @return bool
694 public static function isUsableName( $name ) {
695 global $wgReservedUsernames;
696 // Must be a valid username, obviously ;)
697 if ( !self::isValidUserName( $name ) ) {
698 return false;
701 static $reservedUsernames = false;
702 if ( !$reservedUsernames ) {
703 $reservedUsernames = $wgReservedUsernames;
704 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
707 // Certain names may be reserved for batch processes.
708 foreach ( $reservedUsernames as $reserved ) {
709 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
710 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
712 if ( $reserved == $name ) {
713 return false;
716 return true;
720 * Usernames which fail to pass this function will be blocked
721 * from new account registrations, but may be used internally
722 * either by batch processes or by user accounts which have
723 * already been created.
725 * Additional blacklisting may be added here rather than in
726 * isValidUserName() to avoid disrupting existing accounts.
728 * @param string $name String to match
729 * @return bool
731 public static function isCreatableName( $name ) {
732 global $wgInvalidUsernameCharacters;
734 // Ensure that the username isn't longer than 235 bytes, so that
735 // (at least for the builtin skins) user javascript and css files
736 // will work. (bug 23080)
737 if ( strlen( $name ) > 235 ) {
738 wfDebugLog( 'username', __METHOD__ .
739 ": '$name' invalid due to length" );
740 return false;
743 // Preg yells if you try to give it an empty string
744 if ( $wgInvalidUsernameCharacters !== '' ) {
745 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
746 wfDebugLog( 'username', __METHOD__ .
747 ": '$name' invalid due to wgInvalidUsernameCharacters" );
748 return false;
752 return self::isUsableName( $name );
756 * Is the input a valid password for this user?
758 * @param string $password Desired password
759 * @return bool
761 public function isValidPassword( $password ) {
762 //simple boolean wrapper for getPasswordValidity
763 return $this->getPasswordValidity( $password ) === true;
768 * Given unvalidated password input, return error message on failure.
770 * @param string $password Desired password
771 * @return bool|string|array True on success, string or array of error message on failure
773 public function getPasswordValidity( $password ) {
774 $result = $this->checkPasswordValidity( $password );
775 if ( $result->isGood() ) {
776 return true;
777 } else {
778 $messages = array();
779 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
780 $messages[] = $error['message'];
782 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
783 $messages[] = $warning['message'];
785 if ( count( $messages ) === 1 ) {
786 return $messages[0];
788 return $messages;
793 * Check if this is a valid password for this user. Status will be good if
794 * the password is valid, or have an array of error messages if not.
796 * @param string $password Desired password
797 * @return Status
798 * @since 1.23
800 public function checkPasswordValidity( $password ) {
801 global $wgMinimalPasswordLength, $wgContLang;
803 static $blockedLogins = array(
804 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
805 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
808 $status = Status::newGood();
810 $result = false; //init $result to false for the internal checks
812 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
813 $status->error( $result );
814 return $status;
817 if ( $result === false ) {
818 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
819 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
820 return $status;
821 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
822 $status->error( 'password-name-match' );
823 return $status;
824 } elseif ( isset( $blockedLogins[$this->getName()] )
825 && $password == $blockedLogins[$this->getName()]
827 $status->error( 'password-login-forbidden' );
828 return $status;
829 } else {
830 //it seems weird returning a Good status here, but this is because of the
831 //initialization of $result to false above. If the hook is never run or it
832 //doesn't modify $result, then we will likely get down into this if with
833 //a valid password.
834 return $status;
836 } elseif ( $result === true ) {
837 return $status;
838 } else {
839 $status->error( $result );
840 return $status; //the isValidPassword hook set a string $result and returned true
845 * Expire a user's password
846 * @since 1.23
847 * @param int $ts Optional timestamp to convert, default 0 for the current time
849 public function expirePassword( $ts = 0 ) {
850 $this->loadPasswords();
851 $timestamp = wfTimestamp( TS_MW, $ts );
852 $this->mPasswordExpires = $timestamp;
853 $this->saveSettings();
857 * Clear the password expiration for a user
858 * @since 1.23
859 * @param bool $load Ensure user object is loaded first
861 public function resetPasswordExpiration( $load = true ) {
862 global $wgPasswordExpirationDays;
863 if ( $load ) {
864 $this->load();
866 $newExpire = null;
867 if ( $wgPasswordExpirationDays ) {
868 $newExpire = wfTimestamp(
869 TS_MW,
870 time() + ( $wgPasswordExpirationDays * 24 * 3600 )
873 // Give extensions a chance to force an expiration
874 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
875 $this->mPasswordExpires = $newExpire;
879 * Check if the user's password is expired.
880 * TODO: Put this and password length into a PasswordPolicy object
881 * @since 1.23
882 * @return string|bool The expiration type, or false if not expired
883 * hard: A password change is required to login
884 * soft: Allow login, but encourage password change
885 * false: Password is not expired
887 public function getPasswordExpired() {
888 global $wgPasswordExpireGrace;
889 $expired = false;
890 $now = wfTimestamp();
891 $expiration = $this->getPasswordExpireDate();
892 $expUnix = wfTimestamp( TS_UNIX, $expiration );
893 if ( $expiration !== null && $expUnix < $now ) {
894 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
896 return $expired;
900 * Get this user's password expiration date. Since this may be using
901 * the cached User object, we assume that whatever mechanism is setting
902 * the expiration date is also expiring the User cache.
903 * @since 1.23
904 * @return string|bool The datestamp of the expiration, or null if not set
906 public function getPasswordExpireDate() {
907 $this->load();
908 return $this->mPasswordExpires;
912 * Given unvalidated user input, return a canonical username, or false if
913 * the username is invalid.
914 * @param string $name User input
915 * @param string|bool $validate Type of validation to use:
916 * - false No validation
917 * - 'valid' Valid for batch processes
918 * - 'usable' Valid for batch processes and login
919 * - 'creatable' Valid for batch processes, login and account creation
921 * @throws MWException
922 * @return bool|string
924 public static function getCanonicalName( $name, $validate = 'valid' ) {
925 // Force usernames to capital
926 global $wgContLang;
927 $name = $wgContLang->ucfirst( $name );
929 # Reject names containing '#'; these will be cleaned up
930 # with title normalisation, but then it's too late to
931 # check elsewhere
932 if ( strpos( $name, '#' ) !== false ) {
933 return false;
936 // Clean up name according to title rules,
937 // but only when validation is requested (bug 12654)
938 $t = ( $validate !== false ) ?
939 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
940 // Check for invalid titles
941 if ( is_null( $t ) ) {
942 return false;
945 // Reject various classes of invalid names
946 global $wgAuth;
947 $name = $wgAuth->getCanonicalName( $t->getText() );
949 switch ( $validate ) {
950 case false:
951 break;
952 case 'valid':
953 if ( !User::isValidUserName( $name ) ) {
954 $name = false;
956 break;
957 case 'usable':
958 if ( !User::isUsableName( $name ) ) {
959 $name = false;
961 break;
962 case 'creatable':
963 if ( !User::isCreatableName( $name ) ) {
964 $name = false;
966 break;
967 default:
968 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
970 return $name;
974 * Count the number of edits of a user
976 * @param int $uid User ID to check
977 * @return int The user's edit count
979 * @deprecated since 1.21 in favour of User::getEditCount
981 public static function edits( $uid ) {
982 wfDeprecated( __METHOD__, '1.21' );
983 $user = self::newFromId( $uid );
984 return $user->getEditCount();
988 * Return a random password.
990 * @return string New random password
992 public static function randomPassword() {
993 global $wgMinimalPasswordLength;
994 // Decide the final password length based on our min password length,
995 // stopping at a minimum of 10 chars.
996 $length = max( 10, $wgMinimalPasswordLength );
997 // Multiply by 1.25 to get the number of hex characters we need
998 $length = $length * 1.25;
999 // Generate random hex chars
1000 $hex = MWCryptRand::generateHex( $length );
1001 // Convert from base 16 to base 32 to get a proper password like string
1002 return wfBaseConvert( $hex, 16, 32 );
1006 * Set cached properties to default.
1008 * @note This no longer clears uncached lazy-initialised properties;
1009 * the constructor does that instead.
1011 * @param string|bool $name
1013 public function loadDefaults( $name = false ) {
1014 wfProfileIn( __METHOD__ );
1016 $passwordFactory = self::getPasswordFactory();
1018 $this->mId = 0;
1019 $this->mName = $name;
1020 $this->mRealName = '';
1021 $this->mPassword = $passwordFactory->newFromCiphertext( null );
1022 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
1023 $this->mNewpassTime = null;
1024 $this->mEmail = '';
1025 $this->mOptionOverrides = null;
1026 $this->mOptionsLoaded = false;
1028 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1029 if ( $loggedOut !== null ) {
1030 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1031 } else {
1032 $this->mTouched = '1'; # Allow any pages to be cached
1035 $this->mToken = null; // Don't run cryptographic functions till we need a token
1036 $this->mEmailAuthenticated = null;
1037 $this->mEmailToken = '';
1038 $this->mEmailTokenExpires = null;
1039 $this->mPasswordExpires = null;
1040 $this->resetPasswordExpiration( false );
1041 $this->mRegistration = wfTimestamp( TS_MW );
1042 $this->mGroups = array();
1044 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1046 wfProfileOut( __METHOD__ );
1050 * Return whether an item has been loaded.
1052 * @param string $item Item to check. Current possibilities:
1053 * - id
1054 * - name
1055 * - realname
1056 * @param string $all 'all' to check if the whole object has been loaded
1057 * or any other string to check if only the item is available (e.g.
1058 * for optimisation)
1059 * @return bool
1061 public function isItemLoaded( $item, $all = 'all' ) {
1062 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1063 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1067 * Set that an item has been loaded
1069 * @param string $item
1071 protected function setItemLoaded( $item ) {
1072 if ( is_array( $this->mLoadedItems ) ) {
1073 $this->mLoadedItems[$item] = true;
1078 * Load user data from the session or login cookie.
1079 * @return bool True if the user is logged in, false otherwise.
1081 private function loadFromSession() {
1082 $result = null;
1083 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1084 if ( $result !== null ) {
1085 return $result;
1088 $request = $this->getRequest();
1090 $cookieId = $request->getCookie( 'UserID' );
1091 $sessId = $request->getSessionData( 'wsUserID' );
1093 if ( $cookieId !== null ) {
1094 $sId = intval( $cookieId );
1095 if ( $sessId !== null && $cookieId != $sessId ) {
1096 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1097 cookie user ID ($sId) don't match!" );
1098 return false;
1100 $request->setSessionData( 'wsUserID', $sId );
1101 } elseif ( $sessId !== null && $sessId != 0 ) {
1102 $sId = $sessId;
1103 } else {
1104 return false;
1107 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1108 $sName = $request->getSessionData( 'wsUserName' );
1109 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1110 $sName = $request->getCookie( 'UserName' );
1111 $request->setSessionData( 'wsUserName', $sName );
1112 } else {
1113 return false;
1116 $proposedUser = User::newFromId( $sId );
1117 if ( !$proposedUser->isLoggedIn() ) {
1118 // Not a valid ID
1119 return false;
1122 global $wgBlockDisablesLogin;
1123 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1124 // User blocked and we've disabled blocked user logins
1125 return false;
1128 if ( $request->getSessionData( 'wsToken' ) ) {
1129 $passwordCorrect =
1130 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1131 $from = 'session';
1132 } elseif ( $request->getCookie( 'Token' ) ) {
1133 # Get the token from DB/cache and clean it up to remove garbage padding.
1134 # This deals with historical problems with bugs and the default column value.
1135 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1136 // Make comparison in constant time (bug 61346)
1137 $passwordCorrect = strlen( $token )
1138 && hash_equals( $token, $request->getCookie( 'Token' ) );
1139 $from = 'cookie';
1140 } else {
1141 // No session or persistent login cookie
1142 return false;
1145 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1146 $this->loadFromUserObject( $proposedUser );
1147 $request->setSessionData( 'wsToken', $this->mToken );
1148 wfDebug( "User: logged in from $from\n" );
1149 return true;
1150 } else {
1151 // Invalid credentials
1152 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1153 return false;
1158 * Load user and user_group data from the database.
1159 * $this->mId must be set, this is how the user is identified.
1161 * @param int $flags Supports User::READ_LOCKING
1162 * @return bool True if the user exists, false if the user is anonymous
1164 public function loadFromDatabase( $flags = 0 ) {
1165 // Paranoia
1166 $this->mId = intval( $this->mId );
1168 // Anonymous user
1169 if ( !$this->mId ) {
1170 $this->loadDefaults();
1171 return false;
1174 $dbr = wfGetDB( DB_MASTER );
1175 $s = $dbr->selectRow(
1176 'user',
1177 self::selectFields(),
1178 array( 'user_id' => $this->mId ),
1179 __METHOD__,
1180 ( $flags & self::READ_LOCKING == self::READ_LOCKING )
1181 ? array( 'LOCK IN SHARE MODE' )
1182 : array()
1185 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1187 if ( $s !== false ) {
1188 // Initialise user table data
1189 $this->loadFromRow( $s );
1190 $this->mGroups = null; // deferred
1191 $this->getEditCount(); // revalidation for nulls
1192 return true;
1193 } else {
1194 // Invalid user_id
1195 $this->mId = 0;
1196 $this->loadDefaults();
1197 return false;
1202 * Initialize this object from a row from the user table.
1204 * @param stdClass $row Row from the user table to load.
1205 * @param array $data Further user data to load into the object
1207 * user_groups Array with groups out of the user_groups table
1208 * user_properties Array with properties out of the user_properties table
1210 public function loadFromRow( $row, $data = null ) {
1211 $all = true;
1212 $passwordFactory = self::getPasswordFactory();
1214 $this->mGroups = null; // deferred
1216 if ( isset( $row->user_name ) ) {
1217 $this->mName = $row->user_name;
1218 $this->mFrom = 'name';
1219 $this->setItemLoaded( 'name' );
1220 } else {
1221 $all = false;
1224 if ( isset( $row->user_real_name ) ) {
1225 $this->mRealName = $row->user_real_name;
1226 $this->setItemLoaded( 'realname' );
1227 } else {
1228 $all = false;
1231 if ( isset( $row->user_id ) ) {
1232 $this->mId = intval( $row->user_id );
1233 $this->mFrom = 'id';
1234 $this->setItemLoaded( 'id' );
1235 } else {
1236 $all = false;
1239 if ( isset( $row->user_editcount ) ) {
1240 $this->mEditCount = $row->user_editcount;
1241 } else {
1242 $all = false;
1245 if ( isset( $row->user_password ) ) {
1246 // Check for *really* old password hashes that don't even have a type
1247 // The old hash format was just an md5 hex hash, with no type information
1248 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
1249 $row->user_password = ":A:{$this->mId}:{$row->user_password}";
1252 try {
1253 $this->mPassword = $passwordFactory->newFromCiphertext( $row->user_password );
1254 } catch ( PasswordError $e ) {
1255 wfDebug( 'Invalid password hash found in database.' );
1256 $this->mPassword = $passwordFactory->newFromCiphertext( null );
1259 try {
1260 $this->mNewpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
1261 } catch ( PasswordError $e ) {
1262 wfDebug( 'Invalid password hash found in database.' );
1263 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
1266 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1267 $this->mPasswordExpires = wfTimestampOrNull( TS_MW, $row->user_password_expires );
1270 if ( isset( $row->user_email ) ) {
1271 $this->mEmail = $row->user_email;
1272 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1273 $this->mToken = $row->user_token;
1274 if ( $this->mToken == '' ) {
1275 $this->mToken = null;
1277 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1278 $this->mEmailToken = $row->user_email_token;
1279 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1280 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1281 } else {
1282 $all = false;
1285 if ( $all ) {
1286 $this->mLoadedItems = true;
1289 if ( is_array( $data ) ) {
1290 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1291 $this->mGroups = $data['user_groups'];
1293 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1294 $this->loadOptions( $data['user_properties'] );
1300 * Load the data for this user object from another user object.
1302 * @param User $user
1304 protected function loadFromUserObject( $user ) {
1305 $user->load();
1306 $user->loadGroups();
1307 $user->loadOptions();
1308 foreach ( self::$mCacheVars as $var ) {
1309 $this->$var = $user->$var;
1314 * Load the groups from the database if they aren't already loaded.
1316 private function loadGroups() {
1317 if ( is_null( $this->mGroups ) ) {
1318 $dbr = wfGetDB( DB_MASTER );
1319 $res = $dbr->select( 'user_groups',
1320 array( 'ug_group' ),
1321 array( 'ug_user' => $this->mId ),
1322 __METHOD__ );
1323 $this->mGroups = array();
1324 foreach ( $res as $row ) {
1325 $this->mGroups[] = $row->ug_group;
1331 * Load the user's password hashes from the database
1333 * This is usually called in a scenario where the actual User object was
1334 * loaded from the cache, and then password comparison needs to be performed.
1335 * Password hashes are not stored in memcached.
1337 * @since 1.24
1339 private function loadPasswords() {
1340 if ( $this->getId() !== 0 && ( $this->mPassword === null || $this->mNewpassword === null ) ) {
1341 $this->loadFromRow( wfGetDB( DB_MASTER )->selectRow(
1342 'user',
1343 array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ),
1344 array( 'user_id' => $this->getId() ),
1345 __METHOD__
1346 ) );
1351 * Add the user to the group if he/she meets given criteria.
1353 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1354 * possible to remove manually via Special:UserRights. In such case it
1355 * will not be re-added automatically. The user will also not lose the
1356 * group if they no longer meet the criteria.
1358 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1360 * @return array Array of groups the user has been promoted to.
1362 * @see $wgAutopromoteOnce
1364 public function addAutopromoteOnceGroups( $event ) {
1365 global $wgAutopromoteOnceLogInRC, $wgAuth;
1367 $toPromote = array();
1368 if ( $this->getId() ) {
1369 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1370 if ( count( $toPromote ) ) {
1371 $oldGroups = $this->getGroups(); // previous groups
1373 foreach ( $toPromote as $group ) {
1374 $this->addGroup( $group );
1376 // update groups in external authentication database
1377 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1379 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1381 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1382 $logEntry->setPerformer( $this );
1383 $logEntry->setTarget( $this->getUserPage() );
1384 $logEntry->setParameters( array(
1385 '4::oldgroups' => $oldGroups,
1386 '5::newgroups' => $newGroups,
1387 ) );
1388 $logid = $logEntry->insert();
1389 if ( $wgAutopromoteOnceLogInRC ) {
1390 $logEntry->publish( $logid );
1394 return $toPromote;
1398 * Clear various cached data stored in this object. The cache of the user table
1399 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1401 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1402 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1404 public function clearInstanceCache( $reloadFrom = false ) {
1405 $this->mNewtalk = -1;
1406 $this->mDatePreference = null;
1407 $this->mBlockedby = -1; # Unset
1408 $this->mHash = false;
1409 $this->mRights = null;
1410 $this->mEffectiveGroups = null;
1411 $this->mImplicitGroups = null;
1412 $this->mGroups = null;
1413 $this->mOptions = null;
1414 $this->mOptionsLoaded = false;
1415 $this->mEditCount = null;
1417 if ( $reloadFrom ) {
1418 $this->mLoadedItems = array();
1419 $this->mFrom = $reloadFrom;
1424 * Combine the language default options with any site-specific options
1425 * and add the default language variants.
1427 * @return array Array of String options
1429 public static function getDefaultOptions() {
1430 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1432 static $defOpt = null;
1433 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1434 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1435 // mid-request and see that change reflected in the return value of this function.
1436 // Which is insane and would never happen during normal MW operation
1437 return $defOpt;
1440 $defOpt = $wgDefaultUserOptions;
1441 // Default language setting
1442 $defOpt['language'] = $wgContLang->getCode();
1443 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1444 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1446 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1447 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1449 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1451 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1453 return $defOpt;
1457 * Get a given default option value.
1459 * @param string $opt Name of option to retrieve
1460 * @return string Default option value
1462 public static function getDefaultOption( $opt ) {
1463 $defOpts = self::getDefaultOptions();
1464 if ( isset( $defOpts[$opt] ) ) {
1465 return $defOpts[$opt];
1466 } else {
1467 return null;
1472 * Get blocking information
1473 * @param bool $bFromSlave Whether to check the slave database first.
1474 * To improve performance, non-critical checks are done against slaves.
1475 * Check when actually saving should be done against master.
1477 private function getBlockedStatus( $bFromSlave = true ) {
1478 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1480 if ( -1 != $this->mBlockedby ) {
1481 return;
1484 wfProfileIn( __METHOD__ );
1485 wfDebug( __METHOD__ . ": checking...\n" );
1487 // Initialize data...
1488 // Otherwise something ends up stomping on $this->mBlockedby when
1489 // things get lazy-loaded later, causing false positive block hits
1490 // due to -1 !== 0. Probably session-related... Nothing should be
1491 // overwriting mBlockedby, surely?
1492 $this->load();
1494 # We only need to worry about passing the IP address to the Block generator if the
1495 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1496 # know which IP address they're actually coming from
1497 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1498 $ip = $this->getRequest()->getIP();
1499 } else {
1500 $ip = null;
1503 // User/IP blocking
1504 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1506 // Proxy blocking
1507 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1508 && !in_array( $ip, $wgProxyWhitelist )
1510 // Local list
1511 if ( self::isLocallyBlockedProxy( $ip ) ) {
1512 $block = new Block;
1513 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1514 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1515 $block->setTarget( $ip );
1516 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1517 $block = new Block;
1518 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1519 $block->mReason = wfMessage( 'sorbsreason' )->text();
1520 $block->setTarget( $ip );
1524 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1525 if ( !$block instanceof Block
1526 && $wgApplyIpBlocksToXff
1527 && $ip !== null
1528 && !$this->isAllowed( 'proxyunbannable' )
1529 && !in_array( $ip, $wgProxyWhitelist )
1531 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1532 $xff = array_map( 'trim', explode( ',', $xff ) );
1533 $xff = array_diff( $xff, array( $ip ) );
1534 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1535 $block = Block::chooseBlock( $xffblocks, $xff );
1536 if ( $block instanceof Block ) {
1537 # Mangle the reason to alert the user that the block
1538 # originated from matching the X-Forwarded-For header.
1539 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1543 if ( $block instanceof Block ) {
1544 wfDebug( __METHOD__ . ": Found block.\n" );
1545 $this->mBlock = $block;
1546 $this->mBlockedby = $block->getByName();
1547 $this->mBlockreason = $block->mReason;
1548 $this->mHideName = $block->mHideName;
1549 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1550 } else {
1551 $this->mBlockedby = '';
1552 $this->mHideName = 0;
1553 $this->mAllowUsertalk = false;
1556 // Extensions
1557 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1559 wfProfileOut( __METHOD__ );
1563 * Whether the given IP is in a DNS blacklist.
1565 * @param string $ip IP to check
1566 * @param bool $checkWhitelist Whether to check the whitelist first
1567 * @return bool True if blacklisted.
1569 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1570 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1572 if ( !$wgEnableDnsBlacklist ) {
1573 return false;
1576 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1577 return false;
1580 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1584 * Whether the given IP is in a given DNS blacklist.
1586 * @param string $ip IP to check
1587 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1588 * @return bool True if blacklisted.
1590 public function inDnsBlacklist( $ip, $bases ) {
1591 wfProfileIn( __METHOD__ );
1593 $found = false;
1594 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1595 if ( IP::isIPv4( $ip ) ) {
1596 // Reverse IP, bug 21255
1597 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1599 foreach ( (array)$bases as $base ) {
1600 // Make hostname
1601 // If we have an access key, use that too (ProjectHoneypot, etc.)
1602 if ( is_array( $base ) ) {
1603 if ( count( $base ) >= 2 ) {
1604 // Access key is 1, base URL is 0
1605 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1606 } else {
1607 $host = "$ipReversed.{$base[0]}";
1609 } else {
1610 $host = "$ipReversed.$base";
1613 // Send query
1614 $ipList = gethostbynamel( $host );
1616 if ( $ipList ) {
1617 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1618 $found = true;
1619 break;
1620 } else {
1621 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1626 wfProfileOut( __METHOD__ );
1627 return $found;
1631 * Check if an IP address is in the local proxy list
1633 * @param string $ip
1635 * @return bool
1637 public static function isLocallyBlockedProxy( $ip ) {
1638 global $wgProxyList;
1640 if ( !$wgProxyList ) {
1641 return false;
1643 wfProfileIn( __METHOD__ );
1645 if ( !is_array( $wgProxyList ) ) {
1646 // Load from the specified file
1647 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1650 if ( !is_array( $wgProxyList ) ) {
1651 $ret = false;
1652 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1653 $ret = true;
1654 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1655 // Old-style flipped proxy list
1656 $ret = true;
1657 } else {
1658 $ret = false;
1660 wfProfileOut( __METHOD__ );
1661 return $ret;
1665 * Is this user subject to rate limiting?
1667 * @return bool True if rate limited
1669 public function isPingLimitable() {
1670 global $wgRateLimitsExcludedIPs;
1671 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1672 // No other good way currently to disable rate limits
1673 // for specific IPs. :P
1674 // But this is a crappy hack and should die.
1675 return false;
1677 return !$this->isAllowed( 'noratelimit' );
1681 * Primitive rate limits: enforce maximum actions per time period
1682 * to put a brake on flooding.
1684 * The method generates both a generic profiling point and a per action one
1685 * (suffix being "-$action".
1687 * @note When using a shared cache like memcached, IP-address
1688 * last-hit counters will be shared across wikis.
1690 * @param string $action Action to enforce; 'edit' if unspecified
1691 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1692 * @return bool True if a rate limiter was tripped
1694 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1695 // Call the 'PingLimiter' hook
1696 $result = false;
1697 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1698 return $result;
1701 global $wgRateLimits;
1702 if ( !isset( $wgRateLimits[$action] ) ) {
1703 return false;
1706 // Some groups shouldn't trigger the ping limiter, ever
1707 if ( !$this->isPingLimitable() ) {
1708 return false;
1711 global $wgMemc;
1712 wfProfileIn( __METHOD__ );
1713 wfProfileIn( __METHOD__ . '-' . $action );
1715 $limits = $wgRateLimits[$action];
1716 $keys = array();
1717 $id = $this->getId();
1718 $userLimit = false;
1720 if ( isset( $limits['anon'] ) && $id == 0 ) {
1721 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1724 if ( isset( $limits['user'] ) && $id != 0 ) {
1725 $userLimit = $limits['user'];
1727 if ( $this->isNewbie() ) {
1728 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1729 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1731 if ( isset( $limits['ip'] ) ) {
1732 $ip = $this->getRequest()->getIP();
1733 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1735 if ( isset( $limits['subnet'] ) ) {
1736 $ip = $this->getRequest()->getIP();
1737 $matches = array();
1738 $subnet = false;
1739 if ( IP::isIPv6( $ip ) ) {
1740 $parts = IP::parseRange( "$ip/64" );
1741 $subnet = $parts[0];
1742 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1743 // IPv4
1744 $subnet = $matches[1];
1746 if ( $subnet !== false ) {
1747 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1751 // Check for group-specific permissions
1752 // If more than one group applies, use the group with the highest limit
1753 foreach ( $this->getGroups() as $group ) {
1754 if ( isset( $limits[$group] ) ) {
1755 if ( $userLimit === false
1756 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1758 $userLimit = $limits[$group];
1762 // Set the user limit key
1763 if ( $userLimit !== false ) {
1764 list( $max, $period ) = $userLimit;
1765 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1766 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1769 $triggered = false;
1770 foreach ( $keys as $key => $limit ) {
1771 list( $max, $period ) = $limit;
1772 $summary = "(limit $max in {$period}s)";
1773 $count = $wgMemc->get( $key );
1774 // Already pinged?
1775 if ( $count ) {
1776 if ( $count >= $max ) {
1777 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1778 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1779 $triggered = true;
1780 } else {
1781 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1783 } else {
1784 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1785 if ( $incrBy > 0 ) {
1786 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1789 if ( $incrBy > 0 ) {
1790 $wgMemc->incr( $key, $incrBy );
1794 wfProfileOut( __METHOD__ . '-' . $action );
1795 wfProfileOut( __METHOD__ );
1796 return $triggered;
1800 * Check if user is blocked
1802 * @param bool $bFromSlave Whether to check the slave database instead of
1803 * the master. Hacked from false due to horrible probs on site.
1804 * @return bool True if blocked, false otherwise
1806 public function isBlocked( $bFromSlave = true ) {
1807 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1811 * Get the block affecting the user, or null if the user is not blocked
1813 * @param bool $bFromSlave Whether to check the slave database instead of the master
1814 * @return Block|null
1816 public function getBlock( $bFromSlave = true ) {
1817 $this->getBlockedStatus( $bFromSlave );
1818 return $this->mBlock instanceof Block ? $this->mBlock : null;
1822 * Check if user is blocked from editing a particular article
1824 * @param Title $title Title to check
1825 * @param bool $bFromSlave Whether to check the slave database instead of the master
1826 * @return bool
1828 public function isBlockedFrom( $title, $bFromSlave = false ) {
1829 global $wgBlockAllowsUTEdit;
1830 wfProfileIn( __METHOD__ );
1832 $blocked = $this->isBlocked( $bFromSlave );
1833 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1834 // If a user's name is suppressed, they cannot make edits anywhere
1835 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1836 && $title->getNamespace() == NS_USER_TALK ) {
1837 $blocked = false;
1838 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1841 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1843 wfProfileOut( __METHOD__ );
1844 return $blocked;
1848 * If user is blocked, return the name of the user who placed the block
1849 * @return string Name of blocker
1851 public function blockedBy() {
1852 $this->getBlockedStatus();
1853 return $this->mBlockedby;
1857 * If user is blocked, return the specified reason for the block
1858 * @return string Blocking reason
1860 public function blockedFor() {
1861 $this->getBlockedStatus();
1862 return $this->mBlockreason;
1866 * If user is blocked, return the ID for the block
1867 * @return int Block ID
1869 public function getBlockId() {
1870 $this->getBlockedStatus();
1871 return ( $this->mBlock ? $this->mBlock->getId() : false );
1875 * Check if user is blocked on all wikis.
1876 * Do not use for actual edit permission checks!
1877 * This is intended for quick UI checks.
1879 * @param string $ip IP address, uses current client if none given
1880 * @return bool True if blocked, false otherwise
1882 public function isBlockedGlobally( $ip = '' ) {
1883 if ( $this->mBlockedGlobally !== null ) {
1884 return $this->mBlockedGlobally;
1886 // User is already an IP?
1887 if ( IP::isIPAddress( $this->getName() ) ) {
1888 $ip = $this->getName();
1889 } elseif ( !$ip ) {
1890 $ip = $this->getRequest()->getIP();
1892 $blocked = false;
1893 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1894 $this->mBlockedGlobally = (bool)$blocked;
1895 return $this->mBlockedGlobally;
1899 * Check if user account is locked
1901 * @return bool True if locked, false otherwise
1903 public function isLocked() {
1904 if ( $this->mLocked !== null ) {
1905 return $this->mLocked;
1907 global $wgAuth;
1908 $authUser = $wgAuth->getUserInstance( $this );
1909 $this->mLocked = (bool)$authUser->isLocked();
1910 return $this->mLocked;
1914 * Check if user account is hidden
1916 * @return bool True if hidden, false otherwise
1918 public function isHidden() {
1919 if ( $this->mHideName !== null ) {
1920 return $this->mHideName;
1922 $this->getBlockedStatus();
1923 if ( !$this->mHideName ) {
1924 global $wgAuth;
1925 $authUser = $wgAuth->getUserInstance( $this );
1926 $this->mHideName = (bool)$authUser->isHidden();
1928 return $this->mHideName;
1932 * Get the user's ID.
1933 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1935 public function getId() {
1936 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1937 // Special case, we know the user is anonymous
1938 return 0;
1939 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1940 // Don't load if this was initialized from an ID
1941 $this->load();
1943 return $this->mId;
1947 * Set the user and reload all fields according to a given ID
1948 * @param int $v User ID to reload
1950 public function setId( $v ) {
1951 $this->mId = $v;
1952 $this->clearInstanceCache( 'id' );
1956 * Get the user name, or the IP of an anonymous user
1957 * @return string User's name or IP address
1959 public function getName() {
1960 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1961 // Special case optimisation
1962 return $this->mName;
1963 } else {
1964 $this->load();
1965 if ( $this->mName === false ) {
1966 // Clean up IPs
1967 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1969 return $this->mName;
1974 * Set the user name.
1976 * This does not reload fields from the database according to the given
1977 * name. Rather, it is used to create a temporary "nonexistent user" for
1978 * later addition to the database. It can also be used to set the IP
1979 * address for an anonymous user to something other than the current
1980 * remote IP.
1982 * @note User::newFromName() has roughly the same function, when the named user
1983 * does not exist.
1984 * @param string $str New user name to set
1986 public function setName( $str ) {
1987 $this->load();
1988 $this->mName = $str;
1992 * Get the user's name escaped by underscores.
1993 * @return string Username escaped by underscores.
1995 public function getTitleKey() {
1996 return str_replace( ' ', '_', $this->getName() );
2000 * Check if the user has new messages.
2001 * @return bool True if the user has new messages
2003 public function getNewtalk() {
2004 $this->load();
2006 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2007 if ( $this->mNewtalk === -1 ) {
2008 $this->mNewtalk = false; # reset talk page status
2010 // Check memcached separately for anons, who have no
2011 // entire User object stored in there.
2012 if ( !$this->mId ) {
2013 global $wgDisableAnonTalk;
2014 if ( $wgDisableAnonTalk ) {
2015 // Anon newtalk disabled by configuration.
2016 $this->mNewtalk = false;
2017 } else {
2018 global $wgMemc;
2019 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
2020 $newtalk = $wgMemc->get( $key );
2021 if ( strval( $newtalk ) !== '' ) {
2022 $this->mNewtalk = (bool)$newtalk;
2023 } else {
2024 // Since we are caching this, make sure it is up to date by getting it
2025 // from the master
2026 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
2027 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
2030 } else {
2031 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2035 return (bool)$this->mNewtalk;
2039 * Return the data needed to construct links for new talk page message
2040 * alerts. If there are new messages, this will return an associative array
2041 * with the following data:
2042 * wiki: The database name of the wiki
2043 * link: Root-relative link to the user's talk page
2044 * rev: The last talk page revision that the user has seen or null. This
2045 * is useful for building diff links.
2046 * If there are no new messages, it returns an empty array.
2047 * @note This function was designed to accomodate multiple talk pages, but
2048 * currently only returns a single link and revision.
2049 * @return array
2051 public function getNewMessageLinks() {
2052 $talks = array();
2053 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2054 return $talks;
2055 } elseif ( !$this->getNewtalk() ) {
2056 return array();
2058 $utp = $this->getTalkPage();
2059 $dbr = wfGetDB( DB_SLAVE );
2060 // Get the "last viewed rev" timestamp from the oldest message notification
2061 $timestamp = $dbr->selectField( 'user_newtalk',
2062 'MIN(user_last_timestamp)',
2063 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2064 __METHOD__ );
2065 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2066 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2070 * Get the revision ID for the last talk page revision viewed by the talk
2071 * page owner.
2072 * @return int|null Revision ID or null
2074 public function getNewMessageRevisionId() {
2075 $newMessageRevisionId = null;
2076 $newMessageLinks = $this->getNewMessageLinks();
2077 if ( $newMessageLinks ) {
2078 // Note: getNewMessageLinks() never returns more than a single link
2079 // and it is always for the same wiki, but we double-check here in
2080 // case that changes some time in the future.
2081 if ( count( $newMessageLinks ) === 1
2082 && $newMessageLinks[0]['wiki'] === wfWikiID()
2083 && $newMessageLinks[0]['rev']
2085 $newMessageRevision = $newMessageLinks[0]['rev'];
2086 $newMessageRevisionId = $newMessageRevision->getId();
2089 return $newMessageRevisionId;
2093 * Internal uncached check for new messages
2095 * @see getNewtalk()
2096 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2097 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2098 * @param bool $fromMaster True to fetch from the master, false for a slave
2099 * @return bool True if the user has new messages
2101 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2102 if ( $fromMaster ) {
2103 $db = wfGetDB( DB_MASTER );
2104 } else {
2105 $db = wfGetDB( DB_SLAVE );
2107 $ok = $db->selectField( 'user_newtalk', $field,
2108 array( $field => $id ), __METHOD__ );
2109 return $ok !== false;
2113 * Add or update the new messages flag
2114 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2115 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2116 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2117 * @return bool True if successful, false otherwise
2119 protected function updateNewtalk( $field, $id, $curRev = null ) {
2120 // Get timestamp of the talk page revision prior to the current one
2121 $prevRev = $curRev ? $curRev->getPrevious() : false;
2122 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2123 // Mark the user as having new messages since this revision
2124 $dbw = wfGetDB( DB_MASTER );
2125 $dbw->insert( 'user_newtalk',
2126 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2127 __METHOD__,
2128 'IGNORE' );
2129 if ( $dbw->affectedRows() ) {
2130 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2131 return true;
2132 } else {
2133 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2134 return false;
2139 * Clear the new messages flag for the given user
2140 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2141 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2142 * @return bool True if successful, false otherwise
2144 protected function deleteNewtalk( $field, $id ) {
2145 $dbw = wfGetDB( DB_MASTER );
2146 $dbw->delete( 'user_newtalk',
2147 array( $field => $id ),
2148 __METHOD__ );
2149 if ( $dbw->affectedRows() ) {
2150 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2151 return true;
2152 } else {
2153 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2154 return false;
2159 * Update the 'You have new messages!' status.
2160 * @param bool $val Whether the user has new messages
2161 * @param Revision $curRev New, as yet unseen revision of the user talk
2162 * page. Ignored if null or !$val.
2164 public function setNewtalk( $val, $curRev = null ) {
2165 if ( wfReadOnly() ) {
2166 return;
2169 $this->load();
2170 $this->mNewtalk = $val;
2172 if ( $this->isAnon() ) {
2173 $field = 'user_ip';
2174 $id = $this->getName();
2175 } else {
2176 $field = 'user_id';
2177 $id = $this->getId();
2179 global $wgMemc;
2181 if ( $val ) {
2182 $changed = $this->updateNewtalk( $field, $id, $curRev );
2183 } else {
2184 $changed = $this->deleteNewtalk( $field, $id );
2187 if ( $this->isAnon() ) {
2188 // Anons have a separate memcached space, since
2189 // user records aren't kept for them.
2190 $key = wfMemcKey( 'newtalk', 'ip', $id );
2191 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
2193 if ( $changed ) {
2194 $this->invalidateCache();
2199 * Generate a current or new-future timestamp to be stored in the
2200 * user_touched field when we update things.
2201 * @return string Timestamp in TS_MW format
2203 private static function newTouchedTimestamp() {
2204 global $wgClockSkewFudge;
2205 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2209 * Clear user data from memcached.
2210 * Use after applying fun updates to the database; caller's
2211 * responsibility to update user_touched if appropriate.
2213 * Called implicitly from invalidateCache() and saveSettings().
2215 public function clearSharedCache() {
2216 $this->load();
2217 if ( $this->mId ) {
2218 global $wgMemc;
2219 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2224 * Immediately touch the user data cache for this account.
2225 * Updates user_touched field, and removes account data from memcached
2226 * for reload on the next hit.
2228 public function invalidateCache() {
2229 if ( wfReadOnly() ) {
2230 return;
2232 $this->load();
2233 if ( $this->mId ) {
2234 $this->mTouched = self::newTouchedTimestamp();
2236 $dbw = wfGetDB( DB_MASTER );
2237 $userid = $this->mId;
2238 $touched = $this->mTouched;
2239 $method = __METHOD__;
2240 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2241 // Prevent contention slams by checking user_touched first
2242 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2243 $needsPurge = $dbw->selectField( 'user', '1',
2244 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2245 if ( $needsPurge ) {
2246 $dbw->update( 'user',
2247 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2248 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2249 $method
2252 } );
2253 $this->clearSharedCache();
2258 * Validate the cache for this account.
2259 * @param string $timestamp A timestamp in TS_MW format
2260 * @return bool
2262 public function validateCache( $timestamp ) {
2263 $this->load();
2264 return ( $timestamp >= $this->mTouched );
2268 * Get the user touched timestamp
2269 * @return string Timestamp
2271 public function getTouched() {
2272 $this->load();
2273 return $this->mTouched;
2277 * @return Password
2278 * @since 1.24
2280 public function getPassword() {
2281 $this->loadPasswords();
2283 return $this->mPassword;
2287 * @return Password
2288 * @since 1.24
2290 public function getTemporaryPassword() {
2291 $this->loadPasswords();
2293 return $this->mNewpassword;
2297 * Set the password and reset the random token.
2298 * Calls through to authentication plugin if necessary;
2299 * will have no effect if the auth plugin refuses to
2300 * pass the change through or if the legal password
2301 * checks fail.
2303 * As a special case, setting the password to null
2304 * wipes it, so the account cannot be logged in until
2305 * a new password is set, for instance via e-mail.
2307 * @param string $str New password to set
2308 * @throws PasswordError On failure
2310 * @return bool
2312 public function setPassword( $str ) {
2313 global $wgAuth;
2315 $this->loadPasswords();
2317 if ( $str !== null ) {
2318 if ( !$wgAuth->allowPasswordChange() ) {
2319 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2322 if ( !$this->isValidPassword( $str ) ) {
2323 global $wgMinimalPasswordLength;
2324 $valid = $this->getPasswordValidity( $str );
2325 if ( is_array( $valid ) ) {
2326 $message = array_shift( $valid );
2327 $params = $valid;
2328 } else {
2329 $message = $valid;
2330 $params = array( $wgMinimalPasswordLength );
2332 throw new PasswordError( wfMessage( $message, $params )->text() );
2336 if ( !$wgAuth->setPassword( $this, $str ) ) {
2337 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2340 $this->setInternalPassword( $str );
2342 return true;
2346 * Set the password and reset the random token unconditionally.
2348 * @param string|null $str New password to set or null to set an invalid
2349 * password hash meaning that the user will not be able to log in
2350 * through the web interface.
2352 public function setInternalPassword( $str ) {
2353 $this->setToken();
2355 $passwordFactory = self::getPasswordFactory();
2356 $this->mPassword = $passwordFactory->newFromPlaintext( $str );
2358 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
2359 $this->mNewpassTime = null;
2363 * Get the user's current token.
2364 * @param bool $forceCreation Force the generation of a new token if the
2365 * user doesn't have one (default=true for backwards compatibility).
2366 * @return string Token
2368 public function getToken( $forceCreation = true ) {
2369 $this->load();
2370 if ( !$this->mToken && $forceCreation ) {
2371 $this->setToken();
2373 return $this->mToken;
2377 * Set the random token (used for persistent authentication)
2378 * Called from loadDefaults() among other places.
2380 * @param string|bool $token If specified, set the token to this value
2382 public function setToken( $token = false ) {
2383 $this->load();
2384 if ( !$token ) {
2385 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2386 } else {
2387 $this->mToken = $token;
2392 * Set the password for a password reminder or new account email
2394 * @param string $str New password to set or null to set an invalid
2395 * password hash meaning that the user will not be able to use it
2396 * @param bool $throttle If true, reset the throttle timestamp to the present
2398 public function setNewpassword( $str, $throttle = true ) {
2399 $this->loadPasswords();
2401 $this->mNewpassword = self::getPasswordFactory()->newFromPlaintext( $str );
2402 if ( $str === null ) {
2403 $this->mNewpassTime = null;
2404 } elseif ( $throttle ) {
2405 $this->mNewpassTime = wfTimestampNow();
2410 * Has password reminder email been sent within the last
2411 * $wgPasswordReminderResendTime hours?
2412 * @return bool
2414 public function isPasswordReminderThrottled() {
2415 global $wgPasswordReminderResendTime;
2416 $this->load();
2417 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2418 return false;
2420 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2421 return time() < $expiry;
2425 * Get the user's e-mail address
2426 * @return string User's email address
2428 public function getEmail() {
2429 $this->load();
2430 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2431 return $this->mEmail;
2435 * Get the timestamp of the user's e-mail authentication
2436 * @return string TS_MW timestamp
2438 public function getEmailAuthenticationTimestamp() {
2439 $this->load();
2440 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2441 return $this->mEmailAuthenticated;
2445 * Set the user's e-mail address
2446 * @param string $str New e-mail address
2448 public function setEmail( $str ) {
2449 $this->load();
2450 if ( $str == $this->mEmail ) {
2451 return;
2453 $this->invalidateEmail();
2454 $this->mEmail = $str;
2455 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2459 * Set the user's e-mail address and a confirmation mail if needed.
2461 * @since 1.20
2462 * @param string $str New e-mail address
2463 * @return Status
2465 public function setEmailWithConfirmation( $str ) {
2466 global $wgEnableEmail, $wgEmailAuthentication;
2468 if ( !$wgEnableEmail ) {
2469 return Status::newFatal( 'emaildisabled' );
2472 $oldaddr = $this->getEmail();
2473 if ( $str === $oldaddr ) {
2474 return Status::newGood( true );
2477 $this->setEmail( $str );
2479 if ( $str !== '' && $wgEmailAuthentication ) {
2480 // Send a confirmation request to the new address if needed
2481 $type = $oldaddr != '' ? 'changed' : 'set';
2482 $result = $this->sendConfirmationMail( $type );
2483 if ( $result->isGood() ) {
2484 // Say the the caller that a confirmation mail has been sent
2485 $result->value = 'eauth';
2487 } else {
2488 $result = Status::newGood( true );
2491 return $result;
2495 * Get the user's real name
2496 * @return string User's real name
2498 public function getRealName() {
2499 if ( !$this->isItemLoaded( 'realname' ) ) {
2500 $this->load();
2503 return $this->mRealName;
2507 * Set the user's real name
2508 * @param string $str New real name
2510 public function setRealName( $str ) {
2511 $this->load();
2512 $this->mRealName = $str;
2516 * Get the user's current setting for a given option.
2518 * @param string $oname The option to check
2519 * @param string $defaultOverride A default value returned if the option does not exist
2520 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2521 * @return string User's current value for the option
2522 * @see getBoolOption()
2523 * @see getIntOption()
2525 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2526 global $wgHiddenPrefs;
2527 $this->loadOptions();
2529 # We want 'disabled' preferences to always behave as the default value for
2530 # users, even if they have set the option explicitly in their settings (ie they
2531 # set it, and then it was disabled removing their ability to change it). But
2532 # we don't want to erase the preferences in the database in case the preference
2533 # is re-enabled again. So don't touch $mOptions, just override the returned value
2534 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2535 return self::getDefaultOption( $oname );
2538 if ( array_key_exists( $oname, $this->mOptions ) ) {
2539 return $this->mOptions[$oname];
2540 } else {
2541 return $defaultOverride;
2546 * Get all user's options
2548 * @return array
2550 public function getOptions() {
2551 global $wgHiddenPrefs;
2552 $this->loadOptions();
2553 $options = $this->mOptions;
2555 # We want 'disabled' preferences to always behave as the default value for
2556 # users, even if they have set the option explicitly in their settings (ie they
2557 # set it, and then it was disabled removing their ability to change it). But
2558 # we don't want to erase the preferences in the database in case the preference
2559 # is re-enabled again. So don't touch $mOptions, just override the returned value
2560 foreach ( $wgHiddenPrefs as $pref ) {
2561 $default = self::getDefaultOption( $pref );
2562 if ( $default !== null ) {
2563 $options[$pref] = $default;
2567 return $options;
2571 * Get the user's current setting for a given option, as a boolean value.
2573 * @param string $oname The option to check
2574 * @return bool User's current value for the option
2575 * @see getOption()
2577 public function getBoolOption( $oname ) {
2578 return (bool)$this->getOption( $oname );
2582 * Get the user's current setting for a given option, as an integer value.
2584 * @param string $oname The option to check
2585 * @param int $defaultOverride A default value returned if the option does not exist
2586 * @return int User's current value for the option
2587 * @see getOption()
2589 public function getIntOption( $oname, $defaultOverride = 0 ) {
2590 $val = $this->getOption( $oname );
2591 if ( $val == '' ) {
2592 $val = $defaultOverride;
2594 return intval( $val );
2598 * Set the given option for a user.
2600 * You need to call saveSettings() to actually write to the database.
2602 * @param string $oname The option to set
2603 * @param mixed $val New value to set
2605 public function setOption( $oname, $val ) {
2606 $this->loadOptions();
2608 // Explicitly NULL values should refer to defaults
2609 if ( is_null( $val ) ) {
2610 $val = self::getDefaultOption( $oname );
2613 $this->mOptions[$oname] = $val;
2617 * Get a token stored in the preferences (like the watchlist one),
2618 * resetting it if it's empty (and saving changes).
2620 * @param string $oname The option name to retrieve the token from
2621 * @return string|bool User's current value for the option, or false if this option is disabled.
2622 * @see resetTokenFromOption()
2623 * @see getOption()
2625 public function getTokenFromOption( $oname ) {
2626 global $wgHiddenPrefs;
2627 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2628 return false;
2631 $token = $this->getOption( $oname );
2632 if ( !$token ) {
2633 $token = $this->resetTokenFromOption( $oname );
2634 $this->saveSettings();
2636 return $token;
2640 * Reset a token stored in the preferences (like the watchlist one).
2641 * *Does not* save user's preferences (similarly to setOption()).
2643 * @param string $oname The option name to reset the token in
2644 * @return string|bool New token value, or false if this option is disabled.
2645 * @see getTokenFromOption()
2646 * @see setOption()
2648 public function resetTokenFromOption( $oname ) {
2649 global $wgHiddenPrefs;
2650 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2651 return false;
2654 $token = MWCryptRand::generateHex( 40 );
2655 $this->setOption( $oname, $token );
2656 return $token;
2660 * Return a list of the types of user options currently returned by
2661 * User::getOptionKinds().
2663 * Currently, the option kinds are:
2664 * - 'registered' - preferences which are registered in core MediaWiki or
2665 * by extensions using the UserGetDefaultOptions hook.
2666 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2667 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2668 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2669 * be used by user scripts.
2670 * - 'special' - "preferences" that are not accessible via User::getOptions
2671 * or User::setOptions.
2672 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2673 * These are usually legacy options, removed in newer versions.
2675 * The API (and possibly others) use this function to determine the possible
2676 * option types for validation purposes, so make sure to update this when a
2677 * new option kind is added.
2679 * @see User::getOptionKinds
2680 * @return array Option kinds
2682 public static function listOptionKinds() {
2683 return array(
2684 'registered',
2685 'registered-multiselect',
2686 'registered-checkmatrix',
2687 'userjs',
2688 'special',
2689 'unused'
2694 * Return an associative array mapping preferences keys to the kind of a preference they're
2695 * used for. Different kinds are handled differently when setting or reading preferences.
2697 * See User::listOptionKinds for the list of valid option types that can be provided.
2699 * @see User::listOptionKinds
2700 * @param IContextSource $context
2701 * @param array $options Assoc. array with options keys to check as keys.
2702 * Defaults to $this->mOptions.
2703 * @return array The key => kind mapping data
2705 public function getOptionKinds( IContextSource $context, $options = null ) {
2706 $this->loadOptions();
2707 if ( $options === null ) {
2708 $options = $this->mOptions;
2711 $prefs = Preferences::getPreferences( $this, $context );
2712 $mapping = array();
2714 // Pull out the "special" options, so they don't get converted as
2715 // multiselect or checkmatrix.
2716 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2717 foreach ( $specialOptions as $name => $value ) {
2718 unset( $prefs[$name] );
2721 // Multiselect and checkmatrix options are stored in the database with
2722 // one key per option, each having a boolean value. Extract those keys.
2723 $multiselectOptions = array();
2724 foreach ( $prefs as $name => $info ) {
2725 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2726 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2727 $opts = HTMLFormField::flattenOptions( $info['options'] );
2728 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2730 foreach ( $opts as $value ) {
2731 $multiselectOptions["$prefix$value"] = true;
2734 unset( $prefs[$name] );
2737 $checkmatrixOptions = array();
2738 foreach ( $prefs as $name => $info ) {
2739 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2740 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2741 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2742 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2743 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2745 foreach ( $columns as $column ) {
2746 foreach ( $rows as $row ) {
2747 $checkmatrixOptions["$prefix$column-$row"] = true;
2751 unset( $prefs[$name] );
2755 // $value is ignored
2756 foreach ( $options as $key => $value ) {
2757 if ( isset( $prefs[$key] ) ) {
2758 $mapping[$key] = 'registered';
2759 } elseif ( isset( $multiselectOptions[$key] ) ) {
2760 $mapping[$key] = 'registered-multiselect';
2761 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2762 $mapping[$key] = 'registered-checkmatrix';
2763 } elseif ( isset( $specialOptions[$key] ) ) {
2764 $mapping[$key] = 'special';
2765 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2766 $mapping[$key] = 'userjs';
2767 } else {
2768 $mapping[$key] = 'unused';
2772 return $mapping;
2776 * Reset certain (or all) options to the site defaults
2778 * The optional parameter determines which kinds of preferences will be reset.
2779 * Supported values are everything that can be reported by getOptionKinds()
2780 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2782 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2783 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2784 * for backwards-compatibility.
2785 * @param IContextSource|null $context Context source used when $resetKinds
2786 * does not contain 'all', passed to getOptionKinds().
2787 * Defaults to RequestContext::getMain() when null.
2789 public function resetOptions(
2790 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2791 IContextSource $context = null
2793 $this->load();
2794 $defaultOptions = self::getDefaultOptions();
2796 if ( !is_array( $resetKinds ) ) {
2797 $resetKinds = array( $resetKinds );
2800 if ( in_array( 'all', $resetKinds ) ) {
2801 $newOptions = $defaultOptions;
2802 } else {
2803 if ( $context === null ) {
2804 $context = RequestContext::getMain();
2807 $optionKinds = $this->getOptionKinds( $context );
2808 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2809 $newOptions = array();
2811 // Use default values for the options that should be deleted, and
2812 // copy old values for the ones that shouldn't.
2813 foreach ( $this->mOptions as $key => $value ) {
2814 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2815 if ( array_key_exists( $key, $defaultOptions ) ) {
2816 $newOptions[$key] = $defaultOptions[$key];
2818 } else {
2819 $newOptions[$key] = $value;
2824 wfRunHooks( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions, $resetKinds ) );
2826 $this->mOptions = $newOptions;
2827 $this->mOptionsLoaded = true;
2831 * Get the user's preferred date format.
2832 * @return string User's preferred date format
2834 public function getDatePreference() {
2835 // Important migration for old data rows
2836 if ( is_null( $this->mDatePreference ) ) {
2837 global $wgLang;
2838 $value = $this->getOption( 'date' );
2839 $map = $wgLang->getDatePreferenceMigrationMap();
2840 if ( isset( $map[$value] ) ) {
2841 $value = $map[$value];
2843 $this->mDatePreference = $value;
2845 return $this->mDatePreference;
2849 * Determine based on the wiki configuration and the user's options,
2850 * whether this user must be over HTTPS no matter what.
2852 * @return bool
2854 public function requiresHTTPS() {
2855 global $wgSecureLogin;
2856 if ( !$wgSecureLogin ) {
2857 return false;
2858 } else {
2859 $https = $this->getBoolOption( 'prefershttps' );
2860 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2861 if ( $https ) {
2862 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2864 return $https;
2869 * Get the user preferred stub threshold
2871 * @return int
2873 public function getStubThreshold() {
2874 global $wgMaxArticleSize; # Maximum article size, in Kb
2875 $threshold = $this->getIntOption( 'stubthreshold' );
2876 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2877 // If they have set an impossible value, disable the preference
2878 // so we can use the parser cache again.
2879 $threshold = 0;
2881 return $threshold;
2885 * Get the permissions this user has.
2886 * @return array Array of String permission names
2888 public function getRights() {
2889 if ( is_null( $this->mRights ) ) {
2890 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2891 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2892 // Force reindexation of rights when a hook has unset one of them
2893 $this->mRights = array_values( array_unique( $this->mRights ) );
2895 return $this->mRights;
2899 * Get the list of explicit group memberships this user has.
2900 * The implicit * and user groups are not included.
2901 * @return array Array of String internal group names
2903 public function getGroups() {
2904 $this->load();
2905 $this->loadGroups();
2906 return $this->mGroups;
2910 * Get the list of implicit group memberships this user has.
2911 * This includes all explicit groups, plus 'user' if logged in,
2912 * '*' for all accounts, and autopromoted groups
2913 * @param bool $recache Whether to avoid the cache
2914 * @return array Array of String internal group names
2916 public function getEffectiveGroups( $recache = false ) {
2917 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2918 wfProfileIn( __METHOD__ );
2919 $this->mEffectiveGroups = array_unique( array_merge(
2920 $this->getGroups(), // explicit groups
2921 $this->getAutomaticGroups( $recache ) // implicit groups
2922 ) );
2923 // Hook for additional groups
2924 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2925 // Force reindexation of groups when a hook has unset one of them
2926 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2927 wfProfileOut( __METHOD__ );
2929 return $this->mEffectiveGroups;
2933 * Get the list of implicit group memberships this user has.
2934 * This includes 'user' if logged in, '*' for all accounts,
2935 * and autopromoted groups
2936 * @param bool $recache Whether to avoid the cache
2937 * @return array Array of String internal group names
2939 public function getAutomaticGroups( $recache = false ) {
2940 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2941 wfProfileIn( __METHOD__ );
2942 $this->mImplicitGroups = array( '*' );
2943 if ( $this->getId() ) {
2944 $this->mImplicitGroups[] = 'user';
2946 $this->mImplicitGroups = array_unique( array_merge(
2947 $this->mImplicitGroups,
2948 Autopromote::getAutopromoteGroups( $this )
2949 ) );
2951 if ( $recache ) {
2952 // Assure data consistency with rights/groups,
2953 // as getEffectiveGroups() depends on this function
2954 $this->mEffectiveGroups = null;
2956 wfProfileOut( __METHOD__ );
2958 return $this->mImplicitGroups;
2962 * Returns the groups the user has belonged to.
2964 * The user may still belong to the returned groups. Compare with getGroups().
2966 * The function will not return groups the user had belonged to before MW 1.17
2968 * @return array Names of the groups the user has belonged to.
2970 public function getFormerGroups() {
2971 if ( is_null( $this->mFormerGroups ) ) {
2972 $dbr = wfGetDB( DB_MASTER );
2973 $res = $dbr->select( 'user_former_groups',
2974 array( 'ufg_group' ),
2975 array( 'ufg_user' => $this->mId ),
2976 __METHOD__ );
2977 $this->mFormerGroups = array();
2978 foreach ( $res as $row ) {
2979 $this->mFormerGroups[] = $row->ufg_group;
2982 return $this->mFormerGroups;
2986 * Get the user's edit count.
2987 * @return int|null Null for anonymous users
2989 public function getEditCount() {
2990 if ( !$this->getId() ) {
2991 return null;
2994 if ( $this->mEditCount === null ) {
2995 /* Populate the count, if it has not been populated yet */
2996 wfProfileIn( __METHOD__ );
2997 $dbr = wfGetDB( DB_SLAVE );
2998 // check if the user_editcount field has been initialized
2999 $count = $dbr->selectField(
3000 'user', 'user_editcount',
3001 array( 'user_id' => $this->mId ),
3002 __METHOD__
3005 if ( $count === null ) {
3006 // it has not been initialized. do so.
3007 $count = $this->initEditCount();
3009 $this->mEditCount = $count;
3010 wfProfileOut( __METHOD__ );
3012 return (int)$this->mEditCount;
3016 * Add the user to the given group.
3017 * This takes immediate effect.
3018 * @param string $group Name of the group to add
3020 public function addGroup( $group ) {
3021 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
3022 $dbw = wfGetDB( DB_MASTER );
3023 if ( $this->getId() ) {
3024 $dbw->insert( 'user_groups',
3025 array(
3026 'ug_user' => $this->getID(),
3027 'ug_group' => $group,
3029 __METHOD__,
3030 array( 'IGNORE' ) );
3033 $this->loadGroups();
3034 $this->mGroups[] = $group;
3035 // In case loadGroups was not called before, we now have the right twice.
3036 // Get rid of the duplicate.
3037 $this->mGroups = array_unique( $this->mGroups );
3039 // Refresh the groups caches, and clear the rights cache so it will be
3040 // refreshed on the next call to $this->getRights().
3041 $this->getEffectiveGroups( true );
3042 $this->mRights = null;
3044 $this->invalidateCache();
3048 * Remove the user from the given group.
3049 * This takes immediate effect.
3050 * @param string $group Name of the group to remove
3052 public function removeGroup( $group ) {
3053 $this->load();
3054 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3055 $dbw = wfGetDB( DB_MASTER );
3056 $dbw->delete( 'user_groups',
3057 array(
3058 'ug_user' => $this->getID(),
3059 'ug_group' => $group,
3060 ), __METHOD__ );
3061 // Remember that the user was in this group
3062 $dbw->insert( 'user_former_groups',
3063 array(
3064 'ufg_user' => $this->getID(),
3065 'ufg_group' => $group,
3067 __METHOD__,
3068 array( 'IGNORE' ) );
3070 $this->loadGroups();
3071 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3073 // Refresh the groups caches, and clear the rights cache so it will be
3074 // refreshed on the next call to $this->getRights().
3075 $this->getEffectiveGroups( true );
3076 $this->mRights = null;
3078 $this->invalidateCache();
3082 * Get whether the user is logged in
3083 * @return bool
3085 public function isLoggedIn() {
3086 return $this->getID() != 0;
3090 * Get whether the user is anonymous
3091 * @return bool
3093 public function isAnon() {
3094 return !$this->isLoggedIn();
3098 * Check if user is allowed to access a feature / make an action
3100 * @param string $permissions,... Permissions to test
3101 * @return bool True if user is allowed to perform *any* of the given actions
3103 public function isAllowedAny( /*...*/ ) {
3104 $permissions = func_get_args();
3105 foreach ( $permissions as $permission ) {
3106 if ( $this->isAllowed( $permission ) ) {
3107 return true;
3110 return false;
3115 * @param string $permissions,... Permissions to test
3116 * @return bool True if the user is allowed to perform *all* of the given actions
3118 public function isAllowedAll( /*...*/ ) {
3119 $permissions = func_get_args();
3120 foreach ( $permissions as $permission ) {
3121 if ( !$this->isAllowed( $permission ) ) {
3122 return false;
3125 return true;
3129 * Internal mechanics of testing a permission
3130 * @param string $action
3131 * @return bool
3133 public function isAllowed( $action = '' ) {
3134 if ( $action === '' ) {
3135 return true; // In the spirit of DWIM
3137 // Patrolling may not be enabled
3138 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3139 global $wgUseRCPatrol, $wgUseNPPatrol;
3140 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3141 return false;
3144 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3145 // by misconfiguration: 0 == 'foo'
3146 return in_array( $action, $this->getRights(), true );
3150 * Check whether to enable recent changes patrol features for this user
3151 * @return bool True or false
3153 public function useRCPatrol() {
3154 global $wgUseRCPatrol;
3155 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3159 * Check whether to enable new pages patrol features for this user
3160 * @return bool True or false
3162 public function useNPPatrol() {
3163 global $wgUseRCPatrol, $wgUseNPPatrol;
3164 return (
3165 ( $wgUseRCPatrol || $wgUseNPPatrol )
3166 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3171 * Get the WebRequest object to use with this object
3173 * @return WebRequest
3175 public function getRequest() {
3176 if ( $this->mRequest ) {
3177 return $this->mRequest;
3178 } else {
3179 global $wgRequest;
3180 return $wgRequest;
3185 * Get the current skin, loading it if required
3186 * @return Skin The current skin
3187 * @todo FIXME: Need to check the old failback system [AV]
3188 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3190 public function getSkin() {
3191 wfDeprecated( __METHOD__, '1.18' );
3192 return RequestContext::getMain()->getSkin();
3196 * Get a WatchedItem for this user and $title.
3198 * @since 1.22 $checkRights parameter added
3199 * @param Title $title
3200 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3201 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3202 * @return WatchedItem
3204 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3205 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3207 if ( isset( $this->mWatchedItems[$key] ) ) {
3208 return $this->mWatchedItems[$key];
3211 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3212 $this->mWatchedItems = array();
3215 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3216 return $this->mWatchedItems[$key];
3220 * Check the watched status of an article.
3221 * @since 1.22 $checkRights parameter added
3222 * @param Title $title Title of the article to look at
3223 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3224 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3225 * @return bool
3227 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3228 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3232 * Watch an article.
3233 * @since 1.22 $checkRights parameter added
3234 * @param Title $title Title of the article to look at
3235 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3236 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3238 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3239 $this->getWatchedItem( $title, $checkRights )->addWatch();
3240 $this->invalidateCache();
3244 * Stop watching an article.
3245 * @since 1.22 $checkRights parameter added
3246 * @param Title $title Title of the article to look at
3247 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3248 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3250 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3251 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3252 $this->invalidateCache();
3256 * Clear the user's notification timestamp for the given title.
3257 * If e-notif e-mails are on, they will receive notification mails on
3258 * the next change of the page if it's watched etc.
3259 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3260 * @param Title $title Title of the article to look at
3261 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3263 public function clearNotification( &$title, $oldid = 0 ) {
3264 global $wgUseEnotif, $wgShowUpdatedMarker;
3266 // Do nothing if the database is locked to writes
3267 if ( wfReadOnly() ) {
3268 return;
3271 // Do nothing if not allowed to edit the watchlist
3272 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3273 return;
3276 // If we're working on user's talk page, we should update the talk page message indicator
3277 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3278 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3279 return;
3282 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3284 if ( !$oldid || !$nextid ) {
3285 // If we're looking at the latest revision, we should definitely clear it
3286 $this->setNewtalk( false );
3287 } else {
3288 // Otherwise we should update its revision, if it's present
3289 if ( $this->getNewtalk() ) {
3290 // Naturally the other one won't clear by itself
3291 $this->setNewtalk( false );
3292 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3297 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3298 return;
3301 if ( $this->isAnon() ) {
3302 // Nothing else to do...
3303 return;
3306 // Only update the timestamp if the page is being watched.
3307 // The query to find out if it is watched is cached both in memcached and per-invocation,
3308 // and when it does have to be executed, it can be on a slave
3309 // If this is the user's newtalk page, we always update the timestamp
3310 $force = '';
3311 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3312 $force = 'force';
3315 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3319 * Resets all of the given user's page-change notification timestamps.
3320 * If e-notif e-mails are on, they will receive notification mails on
3321 * the next change of any watched page.
3322 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3324 public function clearAllNotifications() {
3325 if ( wfReadOnly() ) {
3326 return;
3329 // Do nothing if not allowed to edit the watchlist
3330 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3331 return;
3334 global $wgUseEnotif, $wgShowUpdatedMarker;
3335 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3336 $this->setNewtalk( false );
3337 return;
3339 $id = $this->getId();
3340 if ( $id != 0 ) {
3341 $dbw = wfGetDB( DB_MASTER );
3342 $dbw->update( 'watchlist',
3343 array( /* SET */ 'wl_notificationtimestamp' => null ),
3344 array( /* WHERE */ 'wl_user' => $id ),
3345 __METHOD__
3347 // We also need to clear here the "you have new message" notification for the own user_talk page;
3348 // it's cleared one page view later in WikiPage::doViewUpdates().
3353 * Set a cookie on the user's client. Wrapper for
3354 * WebResponse::setCookie
3355 * @param string $name Name of the cookie to set
3356 * @param string $value Value to set
3357 * @param int $exp Expiration time, as a UNIX time value;
3358 * if 0 or not specified, use the default $wgCookieExpiration
3359 * @param bool $secure
3360 * true: Force setting the secure attribute when setting the cookie
3361 * false: Force NOT setting the secure attribute when setting the cookie
3362 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3363 * @param array $params Array of options sent passed to WebResponse::setcookie()
3365 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3366 $params['secure'] = $secure;
3367 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3371 * Clear a cookie on the user's client
3372 * @param string $name Name of the cookie to clear
3373 * @param bool $secure
3374 * true: Force setting the secure attribute when setting the cookie
3375 * false: Force NOT setting the secure attribute when setting the cookie
3376 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3377 * @param array $params Array of options sent passed to WebResponse::setcookie()
3379 protected function clearCookie( $name, $secure = null, $params = array() ) {
3380 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3384 * Set the default cookies for this session on the user's client.
3386 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3387 * is passed.
3388 * @param bool $secure Whether to force secure/insecure cookies or use default
3389 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3391 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3392 if ( $request === null ) {
3393 $request = $this->getRequest();
3396 $this->load();
3397 if ( 0 == $this->mId ) {
3398 return;
3400 if ( !$this->mToken ) {
3401 // When token is empty or NULL generate a new one and then save it to the database
3402 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3403 // Simply by setting every cell in the user_token column to NULL and letting them be
3404 // regenerated as users log back into the wiki.
3405 $this->setToken();
3406 $this->saveSettings();
3408 $session = array(
3409 'wsUserID' => $this->mId,
3410 'wsToken' => $this->mToken,
3411 'wsUserName' => $this->getName()
3413 $cookies = array(
3414 'UserID' => $this->mId,
3415 'UserName' => $this->getName(),
3417 if ( $rememberMe ) {
3418 $cookies['Token'] = $this->mToken;
3419 } else {
3420 $cookies['Token'] = false;
3423 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3425 foreach ( $session as $name => $value ) {
3426 $request->setSessionData( $name, $value );
3428 foreach ( $cookies as $name => $value ) {
3429 if ( $value === false ) {
3430 $this->clearCookie( $name );
3431 } else {
3432 $this->setCookie( $name, $value, 0, $secure );
3437 * If wpStickHTTPS was selected, also set an insecure cookie that
3438 * will cause the site to redirect the user to HTTPS, if they access
3439 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3440 * as the one set by centralauth (bug 53538). Also set it to session, or
3441 * standard time setting, based on if rememberme was set.
3443 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3444 $this->setCookie(
3445 'forceHTTPS',
3446 'true',
3447 $rememberMe ? 0 : null,
3448 false,
3449 array( 'prefix' => '' ) // no prefix
3455 * Log this user out.
3457 public function logout() {
3458 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3459 $this->doLogout();
3464 * Clear the user's cookies and session, and reset the instance cache.
3465 * @see logout()
3467 public function doLogout() {
3468 $this->clearInstanceCache( 'defaults' );
3470 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3472 $this->clearCookie( 'UserID' );
3473 $this->clearCookie( 'Token' );
3474 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3476 // Remember when user logged out, to prevent seeing cached pages
3477 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3481 * Save this user's settings into the database.
3482 * @todo Only rarely do all these fields need to be set!
3484 public function saveSettings() {
3485 global $wgAuth;
3487 $this->load();
3488 $this->loadPasswords();
3489 if ( wfReadOnly() ) {
3490 return;
3492 if ( 0 == $this->mId ) {
3493 return;
3496 $this->mTouched = self::newTouchedTimestamp();
3497 if ( !$wgAuth->allowSetLocalPassword() ) {
3498 $this->mPassword = self::getPasswordFactory()->newFromCiphertext( null );
3501 $dbw = wfGetDB( DB_MASTER );
3502 $dbw->update( 'user',
3503 array( /* SET */
3504 'user_name' => $this->mName,
3505 'user_password' => $this->mPassword->toString(),
3506 'user_newpassword' => $this->mNewpassword->toString(),
3507 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3508 'user_real_name' => $this->mRealName,
3509 'user_email' => $this->mEmail,
3510 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3511 'user_touched' => $dbw->timestamp( $this->mTouched ),
3512 'user_token' => strval( $this->mToken ),
3513 'user_email_token' => $this->mEmailToken,
3514 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3515 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3516 ), array( /* WHERE */
3517 'user_id' => $this->mId
3518 ), __METHOD__
3521 $this->saveOptions();
3523 wfRunHooks( 'UserSaveSettings', array( $this ) );
3524 $this->clearSharedCache();
3525 $this->getUserPage()->invalidateCache();
3529 * If only this user's username is known, and it exists, return the user ID.
3530 * @return int
3532 public function idForName() {
3533 $s = trim( $this->getName() );
3534 if ( $s === '' ) {
3535 return 0;
3538 $dbr = wfGetDB( DB_SLAVE );
3539 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3540 if ( $id === false ) {
3541 $id = 0;
3543 return $id;
3547 * Add a user to the database, return the user object
3549 * @param string $name Username to add
3550 * @param array $params Array of Strings Non-default parameters to save to
3551 * the database as user_* fields:
3552 * - password: The user's password hash. Password logins will be disabled
3553 * if this is omitted.
3554 * - newpassword: Hash for a temporary password that has been mailed to
3555 * the user.
3556 * - email: The user's email address.
3557 * - email_authenticated: The email authentication timestamp.
3558 * - real_name: The user's real name.
3559 * - options: An associative array of non-default options.
3560 * - token: Random authentication token. Do not set.
3561 * - registration: Registration timestamp. Do not set.
3563 * @return User|null User object, or null if the username already exists.
3565 public static function createNew( $name, $params = array() ) {
3566 $user = new User;
3567 $user->load();
3568 $user->loadPasswords();
3569 $user->setToken(); // init token
3570 if ( isset( $params['options'] ) ) {
3571 $user->mOptions = $params['options'] + (array)$user->mOptions;
3572 unset( $params['options'] );
3574 $dbw = wfGetDB( DB_MASTER );
3575 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3577 $fields = array(
3578 'user_id' => $seqVal,
3579 'user_name' => $name,
3580 'user_password' => $user->mPassword->toString(),
3581 'user_newpassword' => $user->mNewpassword->toString(),
3582 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3583 'user_email' => $user->mEmail,
3584 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3585 'user_real_name' => $user->mRealName,
3586 'user_token' => strval( $user->mToken ),
3587 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3588 'user_editcount' => 0,
3589 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3591 foreach ( $params as $name => $value ) {
3592 $fields["user_$name"] = $value;
3594 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3595 if ( $dbw->affectedRows() ) {
3596 $newUser = User::newFromId( $dbw->insertId() );
3597 } else {
3598 $newUser = null;
3600 return $newUser;
3604 * Add this existing user object to the database. If the user already
3605 * exists, a fatal status object is returned, and the user object is
3606 * initialised with the data from the database.
3608 * Previously, this function generated a DB error due to a key conflict
3609 * if the user already existed. Many extension callers use this function
3610 * in code along the lines of:
3612 * $user = User::newFromName( $name );
3613 * if ( !$user->isLoggedIn() ) {
3614 * $user->addToDatabase();
3616 * // do something with $user...
3618 * However, this was vulnerable to a race condition (bug 16020). By
3619 * initialising the user object if the user exists, we aim to support this
3620 * calling sequence as far as possible.
3622 * Note that if the user exists, this function will acquire a write lock,
3623 * so it is still advisable to make the call conditional on isLoggedIn(),
3624 * and to commit the transaction after calling.
3626 * @throws MWException
3627 * @return Status
3629 public function addToDatabase() {
3630 $this->load();
3631 $this->loadPasswords();
3632 if ( !$this->mToken ) {
3633 $this->setToken(); // init token
3636 $this->mTouched = self::newTouchedTimestamp();
3638 $dbw = wfGetDB( DB_MASTER );
3639 $inWrite = $dbw->writesOrCallbacksPending();
3640 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3641 $dbw->insert( 'user',
3642 array(
3643 'user_id' => $seqVal,
3644 'user_name' => $this->mName,
3645 'user_password' => $this->mPassword->toString(),
3646 'user_newpassword' => $this->mNewpassword->toString(),
3647 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3648 'user_email' => $this->mEmail,
3649 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3650 'user_real_name' => $this->mRealName,
3651 'user_token' => strval( $this->mToken ),
3652 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3653 'user_editcount' => 0,
3654 'user_touched' => $dbw->timestamp( $this->mTouched ),
3655 ), __METHOD__,
3656 array( 'IGNORE' )
3658 if ( !$dbw->affectedRows() ) {
3659 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3660 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3661 if ( $inWrite ) {
3662 // Can't commit due to pending writes that may need atomicity.
3663 // This may cause some lock contention unlike the case below.
3664 $options = array( 'LOCK IN SHARE MODE' );
3665 $flags = self::READ_LOCKING;
3666 } else {
3667 // Often, this case happens early in views before any writes when
3668 // using CentralAuth. It's should be OK to commit and break the snapshot.
3669 $dbw->commit( __METHOD__, 'flush' );
3670 $options = array();
3671 $flags = 0;
3673 $this->mId = $dbw->selectField( 'user', 'user_id',
3674 array( 'user_name' => $this->mName ), __METHOD__, $options );
3675 $loaded = false;
3676 if ( $this->mId ) {
3677 if ( $this->loadFromDatabase( $flags ) ) {
3678 $loaded = true;
3681 if ( !$loaded ) {
3682 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3683 "to insert user '{$this->mName}' row, but it was not present in select!" );
3685 return Status::newFatal( 'userexists' );
3687 $this->mId = $dbw->insertId();
3689 // Clear instance cache other than user table data, which is already accurate
3690 $this->clearInstanceCache();
3692 $this->saveOptions();
3693 return Status::newGood();
3697 * If this user is logged-in and blocked,
3698 * block any IP address they've successfully logged in from.
3699 * @return bool A block was spread
3701 public function spreadAnyEditBlock() {
3702 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3703 return $this->spreadBlock();
3705 return false;
3709 * If this (non-anonymous) user is blocked,
3710 * block the IP address they've successfully logged in from.
3711 * @return bool A block was spread
3713 protected function spreadBlock() {
3714 wfDebug( __METHOD__ . "()\n" );
3715 $this->load();
3716 if ( $this->mId == 0 ) {
3717 return false;
3720 $userblock = Block::newFromTarget( $this->getName() );
3721 if ( !$userblock ) {
3722 return false;
3725 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3729 * Get whether the user is explicitly blocked from account creation.
3730 * @return bool|Block
3732 public function isBlockedFromCreateAccount() {
3733 $this->getBlockedStatus();
3734 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3735 return $this->mBlock;
3738 # bug 13611: if the IP address the user is trying to create an account from is
3739 # blocked with createaccount disabled, prevent new account creation there even
3740 # when the user is logged in
3741 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3742 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3744 return $this->mBlockedFromCreateAccount instanceof Block
3745 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3746 ? $this->mBlockedFromCreateAccount
3747 : false;
3751 * Get whether the user is blocked from using Special:Emailuser.
3752 * @return bool
3754 public function isBlockedFromEmailuser() {
3755 $this->getBlockedStatus();
3756 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3760 * Get whether the user is allowed to create an account.
3761 * @return bool
3763 public function isAllowedToCreateAccount() {
3764 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3768 * Get this user's personal page title.
3770 * @return Title User's personal page title
3772 public function getUserPage() {
3773 return Title::makeTitle( NS_USER, $this->getName() );
3777 * Get this user's talk page title.
3779 * @return Title User's talk page title
3781 public function getTalkPage() {
3782 $title = $this->getUserPage();
3783 return $title->getTalkPage();
3787 * Determine whether the user is a newbie. Newbies are either
3788 * anonymous IPs, or the most recently created accounts.
3789 * @return bool
3791 public function isNewbie() {
3792 return !$this->isAllowed( 'autoconfirmed' );
3796 * Check to see if the given clear-text password is one of the accepted passwords
3797 * @param string $password User password
3798 * @return bool True if the given password is correct, otherwise False
3800 public function checkPassword( $password ) {
3801 global $wgAuth, $wgLegacyEncoding;
3803 $section = new ProfileSection( __METHOD__ );
3805 $this->loadPasswords();
3807 // Certain authentication plugins do NOT want to save
3808 // domain passwords in a mysql database, so we should
3809 // check this (in case $wgAuth->strict() is false).
3810 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3811 return true;
3812 } elseif ( $wgAuth->strict() ) {
3813 // Auth plugin doesn't allow local authentication
3814 return false;
3815 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3816 // Auth plugin doesn't allow local authentication for this user name
3817 return false;
3820 if ( !$this->mPassword->equals( $password ) ) {
3821 if ( $wgLegacyEncoding ) {
3822 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3823 // Check for this with iconv
3824 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3825 if ( $cp1252Password === $password || !$this->mPassword->equals( $cp1252Password ) ) {
3826 return false;
3828 } else {
3829 return false;
3833 $passwordFactory = self::getPasswordFactory();
3834 if ( $passwordFactory->needsUpdate( $this->mPassword ) ) {
3835 $this->mPassword = $passwordFactory->newFromPlaintext( $password );
3836 $this->saveSettings();
3839 return true;
3843 * Check if the given clear-text password matches the temporary password
3844 * sent by e-mail for password reset operations.
3846 * @param string $plaintext
3848 * @return bool True if matches, false otherwise
3850 public function checkTemporaryPassword( $plaintext ) {
3851 global $wgNewPasswordExpiry;
3853 $this->load();
3854 $this->loadPasswords();
3855 if ( $this->mNewpassword->equals( $plaintext ) ) {
3856 if ( is_null( $this->mNewpassTime ) ) {
3857 return true;
3859 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3860 return ( time() < $expiry );
3861 } else {
3862 return false;
3867 * Alias for getEditToken.
3868 * @deprecated since 1.19, use getEditToken instead.
3870 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3871 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3872 * @return string The new edit token
3874 public function editToken( $salt = '', $request = null ) {
3875 wfDeprecated( __METHOD__, '1.19' );
3876 return $this->getEditToken( $salt, $request );
3880 * Initialize (if necessary) and return a session token value
3881 * which can be used in edit forms to show that the user's
3882 * login credentials aren't being hijacked with a foreign form
3883 * submission.
3885 * @since 1.19
3887 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3888 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3889 * @return string The new edit token
3891 public function getEditToken( $salt = '', $request = null ) {
3892 if ( $request == null ) {
3893 $request = $this->getRequest();
3896 if ( $this->isAnon() ) {
3897 return self::EDIT_TOKEN_SUFFIX;
3898 } else {
3899 $token = $request->getSessionData( 'wsEditToken' );
3900 if ( $token === null ) {
3901 $token = MWCryptRand::generateHex( 32 );
3902 $request->setSessionData( 'wsEditToken', $token );
3904 if ( is_array( $salt ) ) {
3905 $salt = implode( '|', $salt );
3907 return md5( $token . $salt ) . self::EDIT_TOKEN_SUFFIX;
3912 * Generate a looking random token for various uses.
3914 * @return string The new random token
3915 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3916 * wfRandomString for pseudo-randomness.
3918 public static function generateToken() {
3919 return MWCryptRand::generateHex( 32 );
3923 * Check given value against the token value stored in the session.
3924 * A match should confirm that the form was submitted from the
3925 * user's own login session, not a form submission from a third-party
3926 * site.
3928 * @param string $val Input value to compare
3929 * @param string $salt Optional function-specific data for hashing
3930 * @param WebRequest|null $request Object to use or null to use $wgRequest
3931 * @return bool Whether the token matches
3933 public function matchEditToken( $val, $salt = '', $request = null ) {
3934 $sessionToken = $this->getEditToken( $salt, $request );
3935 if ( $val != $sessionToken ) {
3936 wfDebug( "User::matchEditToken: broken session data\n" );
3939 return $val == $sessionToken;
3943 * Check given value against the token value stored in the session,
3944 * ignoring the suffix.
3946 * @param string $val Input value to compare
3947 * @param string $salt Optional function-specific data for hashing
3948 * @param WebRequest|null $request Object to use or null to use $wgRequest
3949 * @return bool Whether the token matches
3951 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3952 $sessionToken = $this->getEditToken( $salt, $request );
3953 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3957 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3958 * mail to the user's given address.
3960 * @param string $type Message to send, either "created", "changed" or "set"
3961 * @return Status
3963 public function sendConfirmationMail( $type = 'created' ) {
3964 global $wgLang;
3965 $expiration = null; // gets passed-by-ref and defined in next line.
3966 $token = $this->confirmationToken( $expiration );
3967 $url = $this->confirmationTokenUrl( $token );
3968 $invalidateURL = $this->invalidationTokenUrl( $token );
3969 $this->saveSettings();
3971 if ( $type == 'created' || $type === false ) {
3972 $message = 'confirmemail_body';
3973 } elseif ( $type === true ) {
3974 $message = 'confirmemail_body_changed';
3975 } else {
3976 // Messages: confirmemail_body_changed, confirmemail_body_set
3977 $message = 'confirmemail_body_' . $type;
3980 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3981 wfMessage( $message,
3982 $this->getRequest()->getIP(),
3983 $this->getName(),
3984 $url,
3985 $wgLang->timeanddate( $expiration, false ),
3986 $invalidateURL,
3987 $wgLang->date( $expiration, false ),
3988 $wgLang->time( $expiration, false ) )->text() );
3992 * Send an e-mail to this user's account. Does not check for
3993 * confirmed status or validity.
3995 * @param string $subject Message subject
3996 * @param string $body Message body
3997 * @param string $from Optional From address; if unspecified, default
3998 * $wgPasswordSender will be used.
3999 * @param string $replyto Reply-To address
4000 * @return Status
4002 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4003 if ( is_null( $from ) ) {
4004 global $wgPasswordSender;
4005 $sender = new MailAddress( $wgPasswordSender,
4006 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4007 } else {
4008 $sender = MailAddress::newFromUser( $from );
4011 $to = MailAddress::newFromUser( $this );
4012 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
4016 * Generate, store, and return a new e-mail confirmation code.
4017 * A hash (unsalted, since it's used as a key) is stored.
4019 * @note Call saveSettings() after calling this function to commit
4020 * this change to the database.
4022 * @param string &$expiration Accepts the expiration time
4023 * @return string New token
4025 protected function confirmationToken( &$expiration ) {
4026 global $wgUserEmailConfirmationTokenExpiry;
4027 $now = time();
4028 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4029 $expiration = wfTimestamp( TS_MW, $expires );
4030 $this->load();
4031 $token = MWCryptRand::generateHex( 32 );
4032 $hash = md5( $token );
4033 $this->mEmailToken = $hash;
4034 $this->mEmailTokenExpires = $expiration;
4035 return $token;
4039 * Return a URL the user can use to confirm their email address.
4040 * @param string $token Accepts the email confirmation token
4041 * @return string New token URL
4043 protected function confirmationTokenUrl( $token ) {
4044 return $this->getTokenUrl( 'ConfirmEmail', $token );
4048 * Return a URL the user can use to invalidate their email address.
4049 * @param string $token Accepts the email confirmation token
4050 * @return string New token URL
4052 protected function invalidationTokenUrl( $token ) {
4053 return $this->getTokenUrl( 'InvalidateEmail', $token );
4057 * Internal function to format the e-mail validation/invalidation URLs.
4058 * This uses a quickie hack to use the
4059 * hardcoded English names of the Special: pages, for ASCII safety.
4061 * @note Since these URLs get dropped directly into emails, using the
4062 * short English names avoids insanely long URL-encoded links, which
4063 * also sometimes can get corrupted in some browsers/mailers
4064 * (bug 6957 with Gmail and Internet Explorer).
4066 * @param string $page Special page
4067 * @param string $token Token
4068 * @return string Formatted URL
4070 protected function getTokenUrl( $page, $token ) {
4071 // Hack to bypass localization of 'Special:'
4072 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4073 return $title->getCanonicalURL();
4077 * Mark the e-mail address confirmed.
4079 * @note Call saveSettings() after calling this function to commit the change.
4081 * @return bool
4083 public function confirmEmail() {
4084 // Check if it's already confirmed, so we don't touch the database
4085 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4086 if ( !$this->isEmailConfirmed() ) {
4087 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4088 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4090 return true;
4094 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4095 * address if it was already confirmed.
4097 * @note Call saveSettings() after calling this function to commit the change.
4098 * @return bool Returns true
4100 public function invalidateEmail() {
4101 $this->load();
4102 $this->mEmailToken = null;
4103 $this->mEmailTokenExpires = null;
4104 $this->setEmailAuthenticationTimestamp( null );
4105 $this->mEmail = '';
4106 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4107 return true;
4111 * Set the e-mail authentication timestamp.
4112 * @param string $timestamp TS_MW timestamp
4114 public function setEmailAuthenticationTimestamp( $timestamp ) {
4115 $this->load();
4116 $this->mEmailAuthenticated = $timestamp;
4117 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4121 * Is this user allowed to send e-mails within limits of current
4122 * site configuration?
4123 * @return bool
4125 public function canSendEmail() {
4126 global $wgEnableEmail, $wgEnableUserEmail;
4127 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4128 return false;
4130 $canSend = $this->isEmailConfirmed();
4131 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4132 return $canSend;
4136 * Is this user allowed to receive e-mails within limits of current
4137 * site configuration?
4138 * @return bool
4140 public function canReceiveEmail() {
4141 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4145 * Is this user's e-mail address valid-looking and confirmed within
4146 * limits of the current site configuration?
4148 * @note If $wgEmailAuthentication is on, this may require the user to have
4149 * confirmed their address by returning a code or using a password
4150 * sent to the address from the wiki.
4152 * @return bool
4154 public function isEmailConfirmed() {
4155 global $wgEmailAuthentication;
4156 $this->load();
4157 $confirmed = true;
4158 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4159 if ( $this->isAnon() ) {
4160 return false;
4162 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4163 return false;
4165 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4166 return false;
4168 return true;
4169 } else {
4170 return $confirmed;
4175 * Check whether there is an outstanding request for e-mail confirmation.
4176 * @return bool
4178 public function isEmailConfirmationPending() {
4179 global $wgEmailAuthentication;
4180 return $wgEmailAuthentication &&
4181 !$this->isEmailConfirmed() &&
4182 $this->mEmailToken &&
4183 $this->mEmailTokenExpires > wfTimestamp();
4187 * Get the timestamp of account creation.
4189 * @return string|bool|null Timestamp of account creation, false for
4190 * non-existent/anonymous user accounts, or null if existing account
4191 * but information is not in database.
4193 public function getRegistration() {
4194 if ( $this->isAnon() ) {
4195 return false;
4197 $this->load();
4198 return $this->mRegistration;
4202 * Get the timestamp of the first edit
4204 * @return string|bool Timestamp of first edit, or false for
4205 * non-existent/anonymous user accounts.
4207 public function getFirstEditTimestamp() {
4208 if ( $this->getId() == 0 ) {
4209 return false; // anons
4211 $dbr = wfGetDB( DB_SLAVE );
4212 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4213 array( 'rev_user' => $this->getId() ),
4214 __METHOD__,
4215 array( 'ORDER BY' => 'rev_timestamp ASC' )
4217 if ( !$time ) {
4218 return false; // no edits
4220 return wfTimestamp( TS_MW, $time );
4224 * Get the permissions associated with a given list of groups
4226 * @param array $groups Array of Strings List of internal group names
4227 * @return array Array of Strings List of permission key names for given groups combined
4229 public static function getGroupPermissions( $groups ) {
4230 global $wgGroupPermissions, $wgRevokePermissions;
4231 $rights = array();
4232 // grant every granted permission first
4233 foreach ( $groups as $group ) {
4234 if ( isset( $wgGroupPermissions[$group] ) ) {
4235 $rights = array_merge( $rights,
4236 // array_filter removes empty items
4237 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4240 // now revoke the revoked permissions
4241 foreach ( $groups as $group ) {
4242 if ( isset( $wgRevokePermissions[$group] ) ) {
4243 $rights = array_diff( $rights,
4244 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4247 return array_unique( $rights );
4251 * Get all the groups who have a given permission
4253 * @param string $role Role to check
4254 * @return array Array of Strings List of internal group names with the given permission
4256 public static function getGroupsWithPermission( $role ) {
4257 global $wgGroupPermissions;
4258 $allowedGroups = array();
4259 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4260 if ( self::groupHasPermission( $group, $role ) ) {
4261 $allowedGroups[] = $group;
4264 return $allowedGroups;
4268 * Check, if the given group has the given permission
4270 * If you're wanting to check whether all users have a permission, use
4271 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4272 * from anyone.
4274 * @since 1.21
4275 * @param string $group Group to check
4276 * @param string $role Role to check
4277 * @return bool
4279 public static function groupHasPermission( $group, $role ) {
4280 global $wgGroupPermissions, $wgRevokePermissions;
4281 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4282 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4286 * Check if all users have the given permission
4288 * @since 1.22
4289 * @param string $right Right to check
4290 * @return bool
4292 public static function isEveryoneAllowed( $right ) {
4293 global $wgGroupPermissions, $wgRevokePermissions;
4294 static $cache = array();
4296 // Use the cached results, except in unit tests which rely on
4297 // being able change the permission mid-request
4298 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4299 return $cache[$right];
4302 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4303 $cache[$right] = false;
4304 return false;
4307 // If it's revoked anywhere, then everyone doesn't have it
4308 foreach ( $wgRevokePermissions as $rights ) {
4309 if ( isset( $rights[$right] ) && $rights[$right] ) {
4310 $cache[$right] = false;
4311 return false;
4315 // Allow extensions (e.g. OAuth) to say false
4316 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4317 $cache[$right] = false;
4318 return false;
4321 $cache[$right] = true;
4322 return true;
4326 * Get the localized descriptive name for a group, if it exists
4328 * @param string $group Internal group name
4329 * @return string Localized descriptive group name
4331 public static function getGroupName( $group ) {
4332 $msg = wfMessage( "group-$group" );
4333 return $msg->isBlank() ? $group : $msg->text();
4337 * Get the localized descriptive name for a member of a group, if it exists
4339 * @param string $group Internal group name
4340 * @param string $username Username for gender (since 1.19)
4341 * @return string Localized name for group member
4343 public static function getGroupMember( $group, $username = '#' ) {
4344 $msg = wfMessage( "group-$group-member", $username );
4345 return $msg->isBlank() ? $group : $msg->text();
4349 * Return the set of defined explicit groups.
4350 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4351 * are not included, as they are defined automatically, not in the database.
4352 * @return array Array of internal group names
4354 public static function getAllGroups() {
4355 global $wgGroupPermissions, $wgRevokePermissions;
4356 return array_diff(
4357 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4358 self::getImplicitGroups()
4363 * Get a list of all available permissions.
4364 * @return array Array of permission names
4366 public static function getAllRights() {
4367 if ( self::$mAllRights === false ) {
4368 global $wgAvailableRights;
4369 if ( count( $wgAvailableRights ) ) {
4370 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4371 } else {
4372 self::$mAllRights = self::$mCoreRights;
4374 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4376 return self::$mAllRights;
4380 * Get a list of implicit groups
4381 * @return array Array of Strings Array of internal group names
4383 public static function getImplicitGroups() {
4384 global $wgImplicitGroups;
4386 $groups = $wgImplicitGroups;
4387 # Deprecated, use $wgImplictGroups instead
4388 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4390 return $groups;
4394 * Get the title of a page describing a particular group
4396 * @param string $group Internal group name
4397 * @return Title|bool Title of the page if it exists, false otherwise
4399 public static function getGroupPage( $group ) {
4400 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4401 if ( $msg->exists() ) {
4402 $title = Title::newFromText( $msg->text() );
4403 if ( is_object( $title ) ) {
4404 return $title;
4407 return false;
4411 * Create a link to the group in HTML, if available;
4412 * else return the group name.
4414 * @param string $group Internal name of the group
4415 * @param string $text The text of the link
4416 * @return string HTML link to the group
4418 public static function makeGroupLinkHTML( $group, $text = '' ) {
4419 if ( $text == '' ) {
4420 $text = self::getGroupName( $group );
4422 $title = self::getGroupPage( $group );
4423 if ( $title ) {
4424 return Linker::link( $title, htmlspecialchars( $text ) );
4425 } else {
4426 return $text;
4431 * Create a link to the group in Wikitext, if available;
4432 * else return the group name.
4434 * @param string $group Internal name of the group
4435 * @param string $text The text of the link
4436 * @return string Wikilink to the group
4438 public static function makeGroupLinkWiki( $group, $text = '' ) {
4439 if ( $text == '' ) {
4440 $text = self::getGroupName( $group );
4442 $title = self::getGroupPage( $group );
4443 if ( $title ) {
4444 $page = $title->getPrefixedText();
4445 return "[[$page|$text]]";
4446 } else {
4447 return $text;
4452 * Returns an array of the groups that a particular group can add/remove.
4454 * @param string $group The group to check for whether it can add/remove
4455 * @return array Array( 'add' => array( addablegroups ),
4456 * 'remove' => array( removablegroups ),
4457 * 'add-self' => array( addablegroups to self),
4458 * 'remove-self' => array( removable groups from self) )
4460 public static function changeableByGroup( $group ) {
4461 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4463 $groups = array(
4464 'add' => array(),
4465 'remove' => array(),
4466 'add-self' => array(),
4467 'remove-self' => array()
4470 if ( empty( $wgAddGroups[$group] ) ) {
4471 // Don't add anything to $groups
4472 } elseif ( $wgAddGroups[$group] === true ) {
4473 // You get everything
4474 $groups['add'] = self::getAllGroups();
4475 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4476 $groups['add'] = $wgAddGroups[$group];
4479 // Same thing for remove
4480 if ( empty( $wgRemoveGroups[$group] ) ) {
4481 } elseif ( $wgRemoveGroups[$group] === true ) {
4482 $groups['remove'] = self::getAllGroups();
4483 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4484 $groups['remove'] = $wgRemoveGroups[$group];
4487 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4488 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4489 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4490 if ( is_int( $key ) ) {
4491 $wgGroupsAddToSelf['user'][] = $value;
4496 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4497 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4498 if ( is_int( $key ) ) {
4499 $wgGroupsRemoveFromSelf['user'][] = $value;
4504 // Now figure out what groups the user can add to him/herself
4505 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4506 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4507 // No idea WHY this would be used, but it's there
4508 $groups['add-self'] = User::getAllGroups();
4509 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4510 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4513 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4514 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4515 $groups['remove-self'] = User::getAllGroups();
4516 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4517 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4520 return $groups;
4524 * Returns an array of groups that this user can add and remove
4525 * @return array Array( 'add' => array( addablegroups ),
4526 * 'remove' => array( removablegroups ),
4527 * 'add-self' => array( addablegroups to self),
4528 * 'remove-self' => array( removable groups from self) )
4530 public function changeableGroups() {
4531 if ( $this->isAllowed( 'userrights' ) ) {
4532 // This group gives the right to modify everything (reverse-
4533 // compatibility with old "userrights lets you change
4534 // everything")
4535 // Using array_merge to make the groups reindexed
4536 $all = array_merge( User::getAllGroups() );
4537 return array(
4538 'add' => $all,
4539 'remove' => $all,
4540 'add-self' => array(),
4541 'remove-self' => array()
4545 // Okay, it's not so simple, we will have to go through the arrays
4546 $groups = array(
4547 'add' => array(),
4548 'remove' => array(),
4549 'add-self' => array(),
4550 'remove-self' => array()
4552 $addergroups = $this->getEffectiveGroups();
4554 foreach ( $addergroups as $addergroup ) {
4555 $groups = array_merge_recursive(
4556 $groups, $this->changeableByGroup( $addergroup )
4558 $groups['add'] = array_unique( $groups['add'] );
4559 $groups['remove'] = array_unique( $groups['remove'] );
4560 $groups['add-self'] = array_unique( $groups['add-self'] );
4561 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4563 return $groups;
4567 * Increment the user's edit-count field.
4568 * Will have no effect for anonymous users.
4570 public function incEditCount() {
4571 if ( !$this->isAnon() ) {
4572 $dbw = wfGetDB( DB_MASTER );
4573 $dbw->update(
4574 'user',
4575 array( 'user_editcount=user_editcount+1' ),
4576 array( 'user_id' => $this->getId() ),
4577 __METHOD__
4580 // Lazy initialization check...
4581 if ( $dbw->affectedRows() == 0 ) {
4582 // Now here's a goddamn hack...
4583 $dbr = wfGetDB( DB_SLAVE );
4584 if ( $dbr !== $dbw ) {
4585 // If we actually have a slave server, the count is
4586 // at least one behind because the current transaction
4587 // has not been committed and replicated.
4588 $this->initEditCount( 1 );
4589 } else {
4590 // But if DB_SLAVE is selecting the master, then the
4591 // count we just read includes the revision that was
4592 // just added in the working transaction.
4593 $this->initEditCount();
4597 // edit count in user cache too
4598 $this->invalidateCache();
4602 * Initialize user_editcount from data out of the revision table
4604 * @param int $add Edits to add to the count from the revision table
4605 * @return int Number of edits
4607 protected function initEditCount( $add = 0 ) {
4608 // Pull from a slave to be less cruel to servers
4609 // Accuracy isn't the point anyway here
4610 $dbr = wfGetDB( DB_SLAVE );
4611 $count = (int)$dbr->selectField(
4612 'revision',
4613 'COUNT(rev_user)',
4614 array( 'rev_user' => $this->getId() ),
4615 __METHOD__
4617 $count = $count + $add;
4619 $dbw = wfGetDB( DB_MASTER );
4620 $dbw->update(
4621 'user',
4622 array( 'user_editcount' => $count ),
4623 array( 'user_id' => $this->getId() ),
4624 __METHOD__
4627 return $count;
4631 * Get the description of a given right
4633 * @param string $right Right to query
4634 * @return string Localized description of the right
4636 public static function getRightDescription( $right ) {
4637 $key = "right-$right";
4638 $msg = wfMessage( $key );
4639 return $msg->isBlank() ? $right : $msg->text();
4643 * Make a new-style password hash
4645 * @param string $password Plain-text password
4646 * @param bool|string $salt Optional salt, may be random or the user ID.
4647 * If unspecified or false, will generate one automatically
4648 * @return string Password hash
4649 * @deprecated since 1.24, use Password class
4651 public static function crypt( $password, $salt = false ) {
4652 wfDeprecated( __METHOD__, '1.24' );
4653 $hash = self::getPasswordFactory()->newFromPlaintext( $password );
4654 return $hash->toString();
4658 * Compare a password hash with a plain-text password. Requires the user
4659 * ID if there's a chance that the hash is an old-style hash.
4661 * @param string $hash Password hash
4662 * @param string $password Plain-text password to compare
4663 * @param string|bool $userId User ID for old-style password salt
4665 * @return bool
4666 * @deprecated since 1.24, use Password class
4668 public static function comparePasswords( $hash, $password, $userId = false ) {
4669 wfDeprecated( __METHOD__, '1.24' );
4671 // Check for *really* old password hashes that don't even have a type
4672 // The old hash format was just an md5 hex hash, with no type information
4673 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4674 global $wgPasswordSalt;
4675 if ( $wgPasswordSalt ) {
4676 $password = ":B:{$userId}:{$hash}";
4677 } else {
4678 $password = ":A:{$hash}";
4682 $hash = self::getPasswordFactory()->newFromCiphertext( $hash );
4683 return $hash->equals( $password );
4687 * Add a newuser log entry for this user.
4688 * Before 1.19 the return value was always true.
4690 * @param string|bool $action Account creation type.
4691 * - String, one of the following values:
4692 * - 'create' for an anonymous user creating an account for himself.
4693 * This will force the action's performer to be the created user itself,
4694 * no matter the value of $wgUser
4695 * - 'create2' for a logged in user creating an account for someone else
4696 * - 'byemail' when the created user will receive its password by e-mail
4697 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4698 * - Boolean means whether the account was created by e-mail (deprecated):
4699 * - true will be converted to 'byemail'
4700 * - false will be converted to 'create' if this object is the same as
4701 * $wgUser and to 'create2' otherwise
4703 * @param string $reason User supplied reason
4705 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4707 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4708 global $wgUser, $wgNewUserLog;
4709 if ( empty( $wgNewUserLog ) ) {
4710 return true; // disabled
4713 if ( $action === true ) {
4714 $action = 'byemail';
4715 } elseif ( $action === false ) {
4716 if ( $this->getName() == $wgUser->getName() ) {
4717 $action = 'create';
4718 } else {
4719 $action = 'create2';
4723 if ( $action === 'create' || $action === 'autocreate' ) {
4724 $performer = $this;
4725 } else {
4726 $performer = $wgUser;
4729 $logEntry = new ManualLogEntry( 'newusers', $action );
4730 $logEntry->setPerformer( $performer );
4731 $logEntry->setTarget( $this->getUserPage() );
4732 $logEntry->setComment( $reason );
4733 $logEntry->setParameters( array(
4734 '4::userid' => $this->getId(),
4735 ) );
4736 $logid = $logEntry->insert();
4738 if ( $action !== 'autocreate' ) {
4739 $logEntry->publish( $logid );
4742 return (int)$logid;
4746 * Add an autocreate newuser log entry for this user
4747 * Used by things like CentralAuth and perhaps other authplugins.
4748 * Consider calling addNewUserLogEntry() directly instead.
4750 * @return bool
4752 public function addNewUserLogEntryAutoCreate() {
4753 $this->addNewUserLogEntry( 'autocreate' );
4755 return true;
4759 * Load the user options either from cache, the database or an array
4761 * @param array $data Rows for the current user out of the user_properties table
4763 protected function loadOptions( $data = null ) {
4764 global $wgContLang;
4766 $this->load();
4768 if ( $this->mOptionsLoaded ) {
4769 return;
4772 $this->mOptions = self::getDefaultOptions();
4774 if ( !$this->getId() ) {
4775 // For unlogged-in users, load language/variant options from request.
4776 // There's no need to do it for logged-in users: they can set preferences,
4777 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4778 // so don't override user's choice (especially when the user chooses site default).
4779 $variant = $wgContLang->getDefaultVariant();
4780 $this->mOptions['variant'] = $variant;
4781 $this->mOptions['language'] = $variant;
4782 $this->mOptionsLoaded = true;
4783 return;
4786 // Maybe load from the object
4787 if ( !is_null( $this->mOptionOverrides ) ) {
4788 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4789 foreach ( $this->mOptionOverrides as $key => $value ) {
4790 $this->mOptions[$key] = $value;
4792 } else {
4793 if ( !is_array( $data ) ) {
4794 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4795 // Load from database
4796 $dbr = wfGetDB( DB_SLAVE );
4798 $res = $dbr->select(
4799 'user_properties',
4800 array( 'up_property', 'up_value' ),
4801 array( 'up_user' => $this->getId() ),
4802 __METHOD__
4805 $this->mOptionOverrides = array();
4806 $data = array();
4807 foreach ( $res as $row ) {
4808 $data[$row->up_property] = $row->up_value;
4811 foreach ( $data as $property => $value ) {
4812 $this->mOptionOverrides[$property] = $value;
4813 $this->mOptions[$property] = $value;
4817 $this->mOptionsLoaded = true;
4819 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4823 * Saves the non-default options for this user, as previously set e.g. via
4824 * setOption(), in the database's "user_properties" (preferences) table.
4825 * Usually used via saveSettings().
4827 protected function saveOptions() {
4828 $this->loadOptions();
4830 // Not using getOptions(), to keep hidden preferences in database
4831 $saveOptions = $this->mOptions;
4833 // Allow hooks to abort, for instance to save to a global profile.
4834 // Reset options to default state before saving.
4835 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4836 return;
4839 $userId = $this->getId();
4841 $insert_rows = array(); // all the new preference rows
4842 foreach ( $saveOptions as $key => $value ) {
4843 // Don't bother storing default values
4844 $defaultOption = self::getDefaultOption( $key );
4845 if ( ( $defaultOption === null && $value !== false && $value !== null )
4846 || $value != $defaultOption
4848 $insert_rows[] = array(
4849 'up_user' => $userId,
4850 'up_property' => $key,
4851 'up_value' => $value,
4856 $dbw = wfGetDB( DB_MASTER );
4858 $res = $dbw->select( 'user_properties',
4859 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ );
4861 // Find prior rows that need to be removed or updated. These rows will
4862 // all be deleted (the later so that INSERT IGNORE applies the new values).
4863 $keysDelete = array();
4864 foreach ( $res as $row ) {
4865 if ( !isset( $saveOptions[$row->up_property] )
4866 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
4868 $keysDelete[] = $row->up_property;
4872 if ( count( $keysDelete ) ) {
4873 // Do the DELETE by PRIMARY KEY for prior rows.
4874 // In the past a very large portion of calls to this function are for setting
4875 // 'rememberpassword' for new accounts (a preference that has since been removed).
4876 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4877 // caused gap locks on [max user ID,+infinity) which caused high contention since
4878 // updates would pile up on each other as they are for higher (newer) user IDs.
4879 // It might not be necessary these days, but it shouldn't hurt either.
4880 $dbw->delete( 'user_properties',
4881 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ );
4883 // Insert the new preference rows
4884 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4888 * Lazily instantiate and return a factory object for making passwords
4890 * @return PasswordFactory
4892 public static function getPasswordFactory() {
4893 if ( self::$mPasswordFactory === null ) {
4894 self::$mPasswordFactory = new PasswordFactory();
4895 self::$mPasswordFactory->init( RequestContext::getMain()->getConfig() );
4898 return self::$mPasswordFactory;
4902 * Provide an array of HTML5 attributes to put on an input element
4903 * intended for the user to enter a new password. This may include
4904 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4906 * Do *not* use this when asking the user to enter his current password!
4907 * Regardless of configuration, users may have invalid passwords for whatever
4908 * reason (e.g., they were set before requirements were tightened up).
4909 * Only use it when asking for a new password, like on account creation or
4910 * ResetPass.
4912 * Obviously, you still need to do server-side checking.
4914 * NOTE: A combination of bugs in various browsers means that this function
4915 * actually just returns array() unconditionally at the moment. May as
4916 * well keep it around for when the browser bugs get fixed, though.
4918 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4920 * @return array Array of HTML attributes suitable for feeding to
4921 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4922 * That will get confused by the boolean attribute syntax used.)
4924 public static function passwordChangeInputAttribs() {
4925 global $wgMinimalPasswordLength;
4927 if ( $wgMinimalPasswordLength == 0 ) {
4928 return array();
4931 # Note that the pattern requirement will always be satisfied if the
4932 # input is empty, so we need required in all cases.
4934 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4935 # if e-mail confirmation is being used. Since HTML5 input validation
4936 # is b0rked anyway in some browsers, just return nothing. When it's
4937 # re-enabled, fix this code to not output required for e-mail
4938 # registration.
4939 #$ret = array( 'required' );
4940 $ret = array();
4942 # We can't actually do this right now, because Opera 9.6 will print out
4943 # the entered password visibly in its error message! When other
4944 # browsers add support for this attribute, or Opera fixes its support,
4945 # we can add support with a version check to avoid doing this on Opera
4946 # versions where it will be a problem. Reported to Opera as
4947 # DSK-262266, but they don't have a public bug tracker for us to follow.
4949 if ( $wgMinimalPasswordLength > 1 ) {
4950 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4951 $ret['title'] = wfMessage( 'passwordtooshort' )
4952 ->numParams( $wgMinimalPasswordLength )->text();
4956 return $ret;
4960 * Return the list of user fields that should be selected to create
4961 * a new user object.
4962 * @return array
4964 public static function selectFields() {
4965 return array(
4966 'user_id',
4967 'user_name',
4968 'user_real_name',
4969 'user_email',
4970 'user_touched',
4971 'user_token',
4972 'user_email_authenticated',
4973 'user_email_token',
4974 'user_email_token_expires',
4975 'user_registration',
4976 'user_editcount',
4981 * Factory function for fatal permission-denied errors
4983 * @since 1.22
4984 * @param string $permission User right required
4985 * @return Status
4987 static function newFatalPermissionDeniedStatus( $permission ) {
4988 global $wgLang;
4990 $groups = array_map(
4991 array( 'User', 'makeGroupLinkWiki' ),
4992 User::getGroupsWithPermission( $permission )
4995 if ( $groups ) {
4996 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4997 } else {
4998 return Status::newFatal( 'badaccess-group0' );