* Remove @static from the last few places it's left in core. Please don't use this...
[mediawiki.git] / includes / User.php
blob81c772833163c8dcc0891fccf57978d845e1de57
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
4 * @file
5 */
7 /**
8 * Int Number of characters in user_token field.
9 * @ingroup Constants
11 define( 'USER_TOKEN_LENGTH', 32 );
13 /**
14 * Int Serialized record version.
15 * @ingroup Constants
17 define( 'MW_USER_VERSION', 8 );
19 /**
20 * String Some punctuation to prevent editing from broken text-mangling proxies.
21 * @ingroup Constants
23 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
25 /**
26 * Thrown by User::setPassword() on error.
27 * @ingroup Exception
29 class PasswordError extends MWException {
30 // NOP
33 /**
34 * The User object encapsulates all of the user-specific settings (user_id,
35 * name, rights, password, email address, options, last login time). Client
36 * classes use the getXXX() functions to access these fields. These functions
37 * do all the work of determining whether the user is logged in,
38 * whether the requested option can be satisfied from cookies or
39 * whether a database query is needed. Most of the settings needed
40 * for rendering normal pages are set in the cookie to minimize use
41 * of the database.
43 class User {
44 /**
45 * Global constants made accessible as class constants so that autoloader
46 * magic can be used.
48 const USER_TOKEN_LENGTH = USER_TOKEN_LENGTH;
49 const MW_USER_VERSION = MW_USER_VERSION;
50 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
52 /**
53 * Array of Strings List of member variables which are saved to the
54 * shared cache (memcached). Any operation which changes the
55 * corresponding database fields must call a cache-clearing function.
56 * @showinitializer
58 static $mCacheVars = array(
59 // user table
60 'mId',
61 'mName',
62 'mRealName',
63 'mPassword',
64 'mNewpassword',
65 'mNewpassTime',
66 'mEmail',
67 'mTouched',
68 'mToken',
69 'mEmailAuthenticated',
70 'mEmailToken',
71 'mEmailTokenExpires',
72 'mRegistration',
73 'mEditCount',
74 // user_group table
75 'mGroups',
76 // user_properties table
77 'mOptionOverrides',
80 /**
81 * Array of Strings Core rights.
82 * Each of these should have a corresponding message of the form
83 * "right-$right".
84 * @showinitializer
86 static $mCoreRights = array(
87 'apihighlimits',
88 'autoconfirmed',
89 'autopatrol',
90 'bigdelete',
91 'block',
92 'blockemail',
93 'bot',
94 'browsearchive',
95 'createaccount',
96 'createpage',
97 'createtalk',
98 'delete',
99 'deletedhistory',
100 'deletedtext',
101 'deleterevision',
102 'disableaccount',
103 'edit',
104 'editinterface',
105 'editusercssjs', #deprecated
106 'editusercss',
107 'edituserjs',
108 'hideuser',
109 'import',
110 'importupload',
111 'ipblock-exempt',
112 'markbotedits',
113 'mergehistory',
114 'minoredit',
115 'move',
116 'movefile',
117 'move-rootuserpages',
118 'move-subpages',
119 'nominornewtalk',
120 'noratelimit',
121 'override-export-depth',
122 'patrol',
123 'protect',
124 'proxyunbannable',
125 'purge',
126 'read',
127 'reupload',
128 'reupload-shared',
129 'rollback',
130 'selenium',
131 'sendemail',
132 'siteadmin',
133 'suppressionlog',
134 'suppressredirect',
135 'suppressrevision',
136 'trackback',
137 'unblockself',
138 'undelete',
139 'unwatchedpages',
140 'upload',
141 'upload_by_url',
142 'userrights',
143 'userrights-interwiki',
144 'writeapi',
147 * String Cached results of getAllRights()
149 static $mAllRights = false;
151 /** @name Cache variables */
152 //@{
153 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
154 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
155 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
156 //@}
159 * Bool Whether the cache variables have been loaded.
161 //@{
162 var $mOptionsLoaded;
163 private $mLoadedItems = array();
164 //@}
167 * String Initialization data source if mLoadedItems!==true. May be one of:
168 * - 'defaults' anonymous user initialised from class defaults
169 * - 'name' initialise from mName
170 * - 'id' initialise from mId
171 * - 'session' log in from cookies or session if possible
173 * Use the User::newFrom*() family of functions to set this.
175 var $mFrom;
178 * Lazy-initialized variables, invalidated with clearInstanceCache
180 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
181 $mBlockreason, $mEffectiveGroups, $mBlockedGlobally,
182 $mLocked, $mHideName, $mOptions;
185 * @var Skin
187 var $mSkin;
190 * @var Block
192 var $mBlock;
194 static $idCacheByName = array();
197 * Lightweight constructor for an anonymous user.
198 * Use the User::newFrom* factory functions for other kinds of users.
200 * @see newFromName()
201 * @see newFromId()
202 * @see newFromConfirmationCode()
203 * @see newFromSession()
204 * @see newFromRow()
206 function __construct() {
207 $this->clearInstanceCache( 'defaults' );
210 function __toString(){
211 return $this->getName();
215 * Load the user table data for this object from the source given by mFrom.
217 function load() {
218 if ( $this->mLoadedItems === true ) {
219 return;
221 wfProfileIn( __METHOD__ );
223 # Set it now to avoid infinite recursion in accessors
224 $this->mLoadedItems = true;
226 switch ( $this->mFrom ) {
227 case 'defaults':
228 $this->loadDefaults();
229 break;
230 case 'name':
231 $this->mId = self::idFromName( $this->mName );
232 if ( !$this->mId ) {
233 # Nonexistent user placeholder object
234 $this->loadDefaults( $this->mName );
235 } else {
236 $this->loadFromId();
238 break;
239 case 'id':
240 $this->loadFromId();
241 break;
242 case 'session':
243 $this->loadFromSession();
244 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
245 break;
246 default:
247 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
249 wfProfileOut( __METHOD__ );
253 * Load user table data, given mId has already been set.
254 * @return Bool false if the ID does not exist, true otherwise
255 * @private
257 function loadFromId() {
258 global $wgMemc;
259 if ( $this->mId == 0 ) {
260 $this->loadDefaults();
261 return false;
264 # Try cache
265 $key = wfMemcKey( 'user', 'id', $this->mId );
266 $data = $wgMemc->get( $key );
267 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
268 # Object is expired, load from DB
269 $data = false;
272 if ( !$data ) {
273 wfDebug( "User: cache miss for user {$this->mId}\n" );
274 # Load from DB
275 if ( !$this->loadFromDatabase() ) {
276 # Can't load from ID, user is anonymous
277 return false;
279 $this->saveToCache();
280 } else {
281 wfDebug( "User: got user {$this->mId} from cache\n" );
282 # Restore from cache
283 foreach ( self::$mCacheVars as $name ) {
284 $this->$name = $data[$name];
287 return true;
291 * Save user data to the shared cache
293 function saveToCache() {
294 $this->load();
295 $this->loadGroups();
296 $this->loadOptions();
297 if ( $this->isAnon() ) {
298 // Anonymous users are uncached
299 return;
301 $data = array();
302 foreach ( self::$mCacheVars as $name ) {
303 $data[$name] = $this->$name;
305 $data['mVersion'] = MW_USER_VERSION;
306 $key = wfMemcKey( 'user', 'id', $this->mId );
307 global $wgMemc;
308 $wgMemc->set( $key, $data );
312 /** @name newFrom*() static factory methods */
313 //@{
316 * Static factory method for creation from username.
318 * This is slightly less efficient than newFromId(), so use newFromId() if
319 * you have both an ID and a name handy.
321 * @param $name String Username, validated by Title::newFromText()
322 * @param $validate String|Bool Validate username. Takes the same parameters as
323 * User::getCanonicalName(), except that true is accepted as an alias
324 * for 'valid', for BC.
326 * @return User object, or false if the username is invalid
327 * (e.g. if it contains illegal characters or is an IP address). If the
328 * username is not present in the database, the result will be a user object
329 * with a name, zero user ID and default settings.
331 static function newFromName( $name, $validate = 'valid' ) {
332 if ( $validate === true ) {
333 $validate = 'valid';
335 $name = self::getCanonicalName( $name, $validate );
336 if ( $name === false ) {
337 return false;
338 } else {
339 # Create unloaded user object
340 $u = new User;
341 $u->mName = $name;
342 $u->mFrom = 'name';
343 $u->setItemLoaded( 'name' );
344 return $u;
349 * Static factory method for creation from a given user ID.
351 * @param $id Int Valid user ID
352 * @return User The corresponding User object
354 static function newFromId( $id ) {
355 $u = new User;
356 $u->mId = $id;
357 $u->mFrom = 'id';
358 $u->setItemLoaded( 'id' );
359 return $u;
363 * Factory method to fetch whichever user has a given email confirmation code.
364 * This code is generated when an account is created or its e-mail address
365 * has changed.
367 * If the code is invalid or has expired, returns NULL.
369 * @param $code String Confirmation code
370 * @return User
372 static function newFromConfirmationCode( $code ) {
373 $dbr = wfGetDB( DB_SLAVE );
374 $id = $dbr->selectField( 'user', 'user_id', array(
375 'user_email_token' => md5( $code ),
376 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
377 ) );
378 if( $id !== false ) {
379 return User::newFromId( $id );
380 } else {
381 return null;
386 * Create a new user object using data from session or cookies. If the
387 * login credentials are invalid, the result is an anonymous user.
389 * @return User
391 static function newFromSession() {
392 $user = new User;
393 $user->mFrom = 'session';
394 return $user;
398 * Create a new user object from a user row.
399 * The row should have the following fields from the user table in it:
400 * - either user_name or user_id to load further data if needed (or both)
401 * - user_real_name
402 * - all other fields (email, password, etc.)
403 * It is useless to provide the remaining fields if either user_id,
404 * user_name and user_real_name are not provided because the whole row
405 * will be loaded once more from the database when accessing them.
407 * @param $row Array A row from the user table
408 * @return User
410 static function newFromRow( $row ) {
411 $user = new User;
412 $user->loadFromRow( $row );
413 return $user;
416 //@}
420 * Get the username corresponding to a given user ID
421 * @param $id Int User ID
422 * @return String The corresponding username
424 static function whoIs( $id ) {
425 $dbr = wfGetDB( DB_SLAVE );
426 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__ );
430 * Get the real name of a user given their user ID
432 * @param $id Int User ID
433 * @return String The corresponding user's real name
435 static function whoIsReal( $id ) {
436 $dbr = wfGetDB( DB_SLAVE );
437 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
441 * Get database id given a user name
442 * @param $name String Username
443 * @return Int|Null The corresponding user's ID, or null if user is nonexistent
445 static function idFromName( $name ) {
446 $nt = Title::makeTitleSafe( NS_USER, $name );
447 if( is_null( $nt ) ) {
448 # Illegal name
449 return null;
452 if ( isset( self::$idCacheByName[$name] ) ) {
453 return self::$idCacheByName[$name];
456 $dbr = wfGetDB( DB_SLAVE );
457 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
459 if ( $s === false ) {
460 $result = null;
461 } else {
462 $result = $s->user_id;
465 self::$idCacheByName[$name] = $result;
467 if ( count( self::$idCacheByName ) > 1000 ) {
468 self::$idCacheByName = array();
471 return $result;
475 * Reset the cache used in idFromName(). For use in tests.
477 public static function resetIdByNameCache() {
478 self::$idCacheByName = array();
482 * Does the string match an anonymous IPv4 address?
484 * This function exists for username validation, in order to reject
485 * usernames which are similar in form to IP addresses. Strings such
486 * as 300.300.300.300 will return true because it looks like an IP
487 * address, despite not being strictly valid.
489 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
490 * address because the usemod software would "cloak" anonymous IP
491 * addresses like this, if we allowed accounts like this to be created
492 * new users could get the old edits of these anonymous users.
494 * @param $name String to match
495 * @return Bool
497 static function isIP( $name ) {
498 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
502 * Is the input a valid username?
504 * Checks if the input is a valid username, we don't want an empty string,
505 * an IP address, anything that containins slashes (would mess up subpages),
506 * is longer than the maximum allowed username size or doesn't begin with
507 * a capital letter.
509 * @param $name String to match
510 * @return Bool
512 static function isValidUserName( $name ) {
513 global $wgContLang, $wgMaxNameChars;
515 if ( $name == ''
516 || User::isIP( $name )
517 || strpos( $name, '/' ) !== false
518 || strlen( $name ) > $wgMaxNameChars
519 || $name != $wgContLang->ucfirst( $name ) ) {
520 wfDebugLog( 'username', __METHOD__ .
521 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
522 return false;
525 // Ensure that the name can't be misresolved as a different title,
526 // such as with extra namespace keys at the start.
527 $parsed = Title::newFromText( $name );
528 if( is_null( $parsed )
529 || $parsed->getNamespace()
530 || strcmp( $name, $parsed->getPrefixedText() ) ) {
531 wfDebugLog( 'username', __METHOD__ .
532 ": '$name' invalid due to ambiguous prefixes" );
533 return false;
536 // Check an additional blacklist of troublemaker characters.
537 // Should these be merged into the title char list?
538 $unicodeBlacklist = '/[' .
539 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
540 '\x{00a0}' . # non-breaking space
541 '\x{2000}-\x{200f}' . # various whitespace
542 '\x{2028}-\x{202f}' . # breaks and control chars
543 '\x{3000}' . # ideographic space
544 '\x{e000}-\x{f8ff}' . # private use
545 ']/u';
546 if( preg_match( $unicodeBlacklist, $name ) ) {
547 wfDebugLog( 'username', __METHOD__ .
548 ": '$name' invalid due to blacklisted characters" );
549 return false;
552 return true;
556 * Usernames which fail to pass this function will be blocked
557 * from user login and new account registrations, but may be used
558 * internally by batch processes.
560 * If an account already exists in this form, login will be blocked
561 * by a failure to pass this function.
563 * @param $name String to match
564 * @return Bool
566 static function isUsableName( $name ) {
567 global $wgReservedUsernames;
568 // Must be a valid username, obviously ;)
569 if ( !self::isValidUserName( $name ) ) {
570 return false;
573 static $reservedUsernames = false;
574 if ( !$reservedUsernames ) {
575 $reservedUsernames = $wgReservedUsernames;
576 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
579 // Certain names may be reserved for batch processes.
580 foreach ( $reservedUsernames as $reserved ) {
581 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
582 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
584 if ( $reserved == $name ) {
585 return false;
588 return true;
592 * Usernames which fail to pass this function will be blocked
593 * from new account registrations, but may be used internally
594 * either by batch processes or by user accounts which have
595 * already been created.
597 * Additional blacklisting may be added here rather than in
598 * isValidUserName() to avoid disrupting existing accounts.
600 * @param $name String to match
601 * @return Bool
603 static function isCreatableName( $name ) {
604 global $wgInvalidUsernameCharacters;
606 // Ensure that the username isn't longer than 235 bytes, so that
607 // (at least for the builtin skins) user javascript and css files
608 // will work. (bug 23080)
609 if( strlen( $name ) > 235 ) {
610 wfDebugLog( 'username', __METHOD__ .
611 ": '$name' invalid due to length" );
612 return false;
615 // Preg yells if you try to give it an empty string
616 if( $wgInvalidUsernameCharacters !== '' ) {
617 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
618 wfDebugLog( 'username', __METHOD__ .
619 ": '$name' invalid due to wgInvalidUsernameCharacters" );
620 return false;
624 return self::isUsableName( $name );
628 * Is the input a valid password for this user?
630 * @param $password String Desired password
631 * @return Bool
633 function isValidPassword( $password ) {
634 //simple boolean wrapper for getPasswordValidity
635 return $this->getPasswordValidity( $password ) === true;
639 * Given unvalidated password input, return error message on failure.
641 * @param $password String Desired password
642 * @return mixed: true on success, string or array of error message on failure
644 function getPasswordValidity( $password ) {
645 global $wgMinimalPasswordLength, $wgContLang;
647 static $blockedLogins = array(
648 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
649 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
652 $result = false; //init $result to false for the internal checks
654 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
655 return $result;
657 if ( $result === false ) {
658 if( strlen( $password ) < $wgMinimalPasswordLength ) {
659 return 'passwordtooshort';
660 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
661 return 'password-name-match';
662 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
663 return 'password-login-forbidden';
664 } else {
665 //it seems weird returning true here, but this is because of the
666 //initialization of $result to false above. If the hook is never run or it
667 //doesn't modify $result, then we will likely get down into this if with
668 //a valid password.
669 return true;
671 } elseif( $result === true ) {
672 return true;
673 } else {
674 return $result; //the isValidPassword hook set a string $result and returned true
679 * Does a string look like an e-mail address?
681 * This validates an email address using an HTML5 specification found at:
682 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
683 * Which as of 2011-01-24 says:
685 * A valid e-mail address is a string that matches the ABNF production
686 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
687 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
688 * 3.5.
690 * This function is an implementation of the specification as requested in
691 * bug 22449.
693 * Client-side forms will use the same standard validation rules via JS or
694 * HTML 5 validation; additional restrictions can be enforced server-side
695 * by extensions via the 'isValidEmailAddr' hook.
697 * Note that this validation doesn't 100% match RFC 2822, but is believed
698 * to be liberal enough for wide use. Some invalid addresses will still
699 * pass validation here.
701 * @param $addr String E-mail address
702 * @return Bool
703 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
705 public static function isValidEmailAddr( $addr ) {
706 return Sanitizer::validateEmail( $addr );
710 * Given unvalidated user input, return a canonical username, or false if
711 * the username is invalid.
712 * @param $name String User input
713 * @param $validate String|Bool type of validation to use:
714 * - false No validation
715 * - 'valid' Valid for batch processes
716 * - 'usable' Valid for batch processes and login
717 * - 'creatable' Valid for batch processes, login and account creation
719 static function getCanonicalName( $name, $validate = 'valid' ) {
720 # Force usernames to capital
721 global $wgContLang;
722 $name = $wgContLang->ucfirst( $name );
724 # Reject names containing '#'; these will be cleaned up
725 # with title normalisation, but then it's too late to
726 # check elsewhere
727 if( strpos( $name, '#' ) !== false )
728 return false;
730 # Clean up name according to title rules
731 $t = ( $validate === 'valid' ) ?
732 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
733 # Check for invalid titles
734 if( is_null( $t ) ) {
735 return false;
738 # Reject various classes of invalid names
739 global $wgAuth;
740 $name = $wgAuth->getCanonicalName( $t->getText() );
742 switch ( $validate ) {
743 case false:
744 break;
745 case 'valid':
746 if ( !User::isValidUserName( $name ) ) {
747 $name = false;
749 break;
750 case 'usable':
751 if ( !User::isUsableName( $name ) ) {
752 $name = false;
754 break;
755 case 'creatable':
756 if ( !User::isCreatableName( $name ) ) {
757 $name = false;
759 break;
760 default:
761 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
763 return $name;
767 * Count the number of edits of a user
768 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
770 * @param $uid Int User ID to check
771 * @return Int the user's edit count
773 static function edits( $uid ) {
774 wfProfileIn( __METHOD__ );
775 $dbr = wfGetDB( DB_SLAVE );
776 // check if the user_editcount field has been initialized
777 $field = $dbr->selectField(
778 'user', 'user_editcount',
779 array( 'user_id' => $uid ),
780 __METHOD__
783 if( $field === null ) { // it has not been initialized. do so.
784 $dbw = wfGetDB( DB_MASTER );
785 $count = $dbr->selectField(
786 'revision', 'count(*)',
787 array( 'rev_user' => $uid ),
788 __METHOD__
790 $dbw->update(
791 'user',
792 array( 'user_editcount' => $count ),
793 array( 'user_id' => $uid ),
794 __METHOD__
796 } else {
797 $count = $field;
799 wfProfileOut( __METHOD__ );
800 return $count;
804 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
805 * @todo hash random numbers to improve security, like generateToken()
807 * @return String new random password
809 static function randomPassword() {
810 global $wgMinimalPasswordLength;
811 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
812 $l = strlen( $pwchars ) - 1;
814 $pwlength = max( 7, $wgMinimalPasswordLength );
815 $digit = mt_rand( 0, $pwlength - 1 );
816 $np = '';
817 for ( $i = 0; $i < $pwlength; $i++ ) {
818 $np .= $i == $digit ? chr( mt_rand( 48, 57 ) ) : $pwchars[ mt_rand( 0, $l ) ];
820 return $np;
824 * Set cached properties to default.
826 * @note This no longer clears uncached lazy-initialised properties;
827 * the constructor does that instead.
828 * @private
830 function loadDefaults( $name = false ) {
831 wfProfileIn( __METHOD__ );
833 global $wgRequest;
835 $this->mId = 0;
836 $this->mName = $name;
837 $this->mRealName = '';
838 $this->mPassword = $this->mNewpassword = '';
839 $this->mNewpassTime = null;
840 $this->mEmail = '';
841 $this->mOptionOverrides = null;
842 $this->mOptionsLoaded = false;
844 if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
845 $this->mTouched = wfTimestamp( TS_MW, $wgRequest->getCookie( 'LoggedOut' ) );
846 } else {
847 $this->mTouched = '0'; # Allow any pages to be cached
850 $this->setToken(); # Random
851 $this->mEmailAuthenticated = null;
852 $this->mEmailToken = '';
853 $this->mEmailTokenExpires = null;
854 $this->mRegistration = wfTimestamp( TS_MW );
855 $this->mGroups = array();
857 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
859 wfProfileOut( __METHOD__ );
863 * Return whether an item has been loaded.
865 * @param $item String: item to check. Current possibilities:
866 * - id
867 * - name
868 * - realname
869 * @param $all String: 'all' to check if the whole object has been loaded
870 * or any other string to check if only the item is available (e.g.
871 * for optimisation)
872 * @return Boolean
874 public function isItemLoaded( $item, $all = 'all' ) {
875 return ( $this->mLoadedItems === true && $all === 'all' ) ||
876 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
880 * Set that an item has been loaded
882 * @param $item String
884 private function setItemLoaded( $item ) {
885 if ( is_array( $this->mLoadedItems ) ) {
886 $this->mLoadedItems[$item] = true;
891 * Load user data from the session or login cookie. If there are no valid
892 * credentials, initialises the user as an anonymous user.
893 * @return Bool True if the user is logged in, false otherwise.
895 private function loadFromSession() {
896 global $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
898 $result = null;
899 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
900 if ( $result !== null ) {
901 return $result;
904 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
905 $extUser = ExternalUser::newFromCookie();
906 if ( $extUser ) {
907 # TODO: Automatically create the user here (or probably a bit
908 # lower down, in fact)
912 $cookieId = $wgRequest->getCookie( 'UserID' );
913 $sessId = $wgRequest->getSessionData( 'wsUserID' );
915 if ( $cookieId !== null ) {
916 $sId = intval( $cookieId );
917 if( $sessId !== null && $cookieId != $sessId ) {
918 $this->loadDefaults(); // Possible collision!
919 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
920 cookie user ID ($sId) don't match!" );
921 return false;
923 $wgRequest->setSessionData( 'wsUserID', $sId );
924 } else if ( $sessId !== null && $sessId != 0 ) {
925 $sId = $sessId;
926 } else {
927 $this->loadDefaults();
928 return false;
931 if ( $wgRequest->getSessionData( 'wsUserName' ) !== null ) {
932 $sName = $wgRequest->getSessionData( 'wsUserName' );
933 } else if ( $wgRequest->getCookie( 'UserName' ) !== null ) {
934 $sName = $wgRequest->getCookie( 'UserName' );
935 $wgRequest->setSessionData( 'wsUserName', $sName );
936 } else {
937 $this->loadDefaults();
938 return false;
941 $proposedUser = User::newFromId( $sId );
942 if ( !$proposedUser->isLoggedIn() ) {
943 # Not a valid ID
944 $this->loadDefaults();
945 return false;
948 global $wgBlockDisablesLogin;
949 if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
950 # User blocked and we've disabled blocked user logins
951 $this->loadDefaults();
952 return false;
955 if ( $wgRequest->getSessionData( 'wsToken' ) !== null ) {
956 $passwordCorrect = $proposedUser->getToken() === $wgRequest->getSessionData( 'wsToken' );
957 $from = 'session';
958 } else if ( $wgRequest->getCookie( 'Token' ) !== null ) {
959 $passwordCorrect = $proposedUser->getToken() === $wgRequest->getCookie( 'Token' );
960 $from = 'cookie';
961 } else {
962 # No session or persistent login cookie
963 $this->loadDefaults();
964 return false;
967 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
968 $this->loadFromUserObject( $proposedUser );
969 $wgRequest->setSessionData( 'wsToken', $this->mToken );
970 wfDebug( "User: logged in from $from\n" );
971 return true;
972 } else {
973 # Invalid credentials
974 wfDebug( "User: can't log in from $from, invalid credentials\n" );
975 $this->loadDefaults();
976 return false;
981 * Load user and user_group data from the database.
982 * $this->mId must be set, this is how the user is identified.
984 * @return Bool True if the user exists, false if the user is anonymous
985 * @private
987 function loadFromDatabase() {
988 # Paranoia
989 $this->mId = intval( $this->mId );
991 /** Anonymous user */
992 if( !$this->mId ) {
993 $this->loadDefaults();
994 return false;
997 $dbr = wfGetDB( DB_MASTER );
998 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
1000 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1002 if ( $s !== false ) {
1003 # Initialise user table data
1004 $this->loadFromRow( $s );
1005 $this->mGroups = null; // deferred
1006 $this->getEditCount(); // revalidation for nulls
1007 return true;
1008 } else {
1009 # Invalid user_id
1010 $this->mId = 0;
1011 $this->loadDefaults();
1012 return false;
1017 * Initialize this object from a row from the user table.
1019 * @param $row Array Row from the user table to load.
1021 function loadFromRow( $row ) {
1022 $all = true;
1024 if ( isset( $row->user_name ) ) {
1025 $this->mName = $row->user_name;
1026 $this->mFrom = 'name';
1027 $this->setItemLoaded( 'name' );
1028 } else {
1029 $all = false;
1032 if ( isset( $row->user_real_name ) ) {
1033 $this->mRealName = $row->user_real_name;
1034 $this->setItemLoaded( 'realname' );
1035 } else {
1036 $all = false;
1039 if ( isset( $row->user_id ) ) {
1040 $this->mId = intval( $row->user_id );
1041 $this->mFrom = 'id';
1042 $this->setItemLoaded( 'id' );
1043 } else {
1044 $all = false;
1047 if ( isset( $row->user_password ) ) {
1048 $this->mPassword = $row->user_password;
1049 $this->mNewpassword = $row->user_newpassword;
1050 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1051 $this->mEmail = $row->user_email;
1052 $this->decodeOptions( $row->user_options );
1053 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
1054 $this->mToken = $row->user_token;
1055 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1056 $this->mEmailToken = $row->user_email_token;
1057 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1058 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1059 $this->mEditCount = $row->user_editcount;
1060 } else {
1061 $all = false;
1064 if ( $all ) {
1065 $this->mLoadedItems = true;
1070 * Load the data for this user object from another user object.
1072 * @param $user User
1074 protected function loadFromUserObject( $user ) {
1075 $user->load();
1076 $user->loadGroups();
1077 $user->loadOptions();
1078 foreach ( self::$mCacheVars as $var ) {
1079 $this->$var = $user->$var;
1084 * Load the groups from the database if they aren't already loaded.
1085 * @private
1087 function loadGroups() {
1088 if ( is_null( $this->mGroups ) ) {
1089 $dbr = wfGetDB( DB_MASTER );
1090 $res = $dbr->select( 'user_groups',
1091 array( 'ug_group' ),
1092 array( 'ug_user' => $this->mId ),
1093 __METHOD__ );
1094 $this->mGroups = array();
1095 foreach ( $res as $row ) {
1096 $this->mGroups[] = $row->ug_group;
1102 * Clear various cached data stored in this object.
1103 * @param $reloadFrom String Reload user and user_groups table data from a
1104 * given source. May be "name", "id", "defaults", "session", or false for
1105 * no reload.
1107 function clearInstanceCache( $reloadFrom = false ) {
1108 $this->mNewtalk = -1;
1109 $this->mDatePreference = null;
1110 $this->mBlockedby = -1; # Unset
1111 $this->mHash = false;
1112 $this->mSkin = null;
1113 $this->mRights = null;
1114 $this->mEffectiveGroups = null;
1115 $this->mOptions = null;
1117 if ( $reloadFrom ) {
1118 $this->mLoadedItems = array();
1119 $this->mFrom = $reloadFrom;
1124 * Combine the language default options with any site-specific options
1125 * and add the default language variants.
1127 * @return Array of String options
1129 static function getDefaultOptions() {
1130 global $wgNamespacesToBeSearchedDefault;
1132 * Site defaults will override the global/language defaults
1134 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1135 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
1138 * default language setting
1140 $variant = $wgContLang->getDefaultVariant();
1141 $defOpt['variant'] = $variant;
1142 $defOpt['language'] = $variant;
1143 foreach( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1144 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1146 $defOpt['skin'] = $wgDefaultSkin;
1148 return $defOpt;
1152 * Get a given default option value.
1154 * @param $opt String Name of option to retrieve
1155 * @return String Default option value
1157 public static function getDefaultOption( $opt ) {
1158 $defOpts = self::getDefaultOptions();
1159 if( isset( $defOpts[$opt] ) ) {
1160 return $defOpts[$opt];
1161 } else {
1162 return null;
1168 * Get blocking information
1169 * @private
1170 * @param $bFromSlave Bool Whether to check the slave database first. To
1171 * improve performance, non-critical checks are done
1172 * against slaves. Check when actually saving should be
1173 * done against master.
1175 function getBlockedStatus( $bFromSlave = true ) {
1176 global $wgProxyWhitelist, $wgUser;
1178 if ( -1 != $this->mBlockedby ) {
1179 return;
1182 wfProfileIn( __METHOD__ );
1183 wfDebug( __METHOD__.": checking...\n" );
1185 // Initialize data...
1186 // Otherwise something ends up stomping on $this->mBlockedby when
1187 // things get lazy-loaded later, causing false positive block hits
1188 // due to -1 !== 0. Probably session-related... Nothing should be
1189 // overwriting mBlockedby, surely?
1190 $this->load();
1192 $this->mBlockedby = 0;
1193 $this->mHideName = 0;
1194 $this->mAllowUsertalk = 0;
1196 # We only need to worry about passing the IP address to the Block generator if the
1197 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1198 # know which IP address they're actually coming from
1199 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1200 $ip = wfGetIP();
1201 } else {
1202 $ip = null;
1205 # User/IP blocking
1206 $this->mBlock = Block::newFromTarget( $this->getName(), $ip, !$bFromSlave );
1207 if ( $this->mBlock instanceof Block ) {
1208 wfDebug( __METHOD__ . ": Found block.\n" );
1209 $this->mBlockedby = $this->mBlock->getBlocker()->getName();
1210 $this->mBlockreason = $this->mBlock->mReason;
1211 $this->mHideName = $this->mBlock->mHideName;
1212 $this->mAllowUsertalk = !$this->mBlock->prevents( 'editownusertalk' );
1213 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1214 $this->spreadBlock();
1218 # Proxy blocking
1219 if ( !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1220 # Local list
1221 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1222 $this->mBlockedby = wfMsg( 'proxyblocker' );
1223 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1226 # DNSBL
1227 if ( !$this->mBlockedby && !$this->getID() ) {
1228 if ( $this->isDnsBlacklisted( $ip ) ) {
1229 $this->mBlockedby = wfMsg( 'sorbs' );
1230 $this->mBlockreason = wfMsg( 'sorbsreason' );
1235 # Extensions
1236 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1238 wfProfileOut( __METHOD__ );
1242 * Whether the given IP is in a DNS blacklist.
1244 * @param $ip String IP to check
1245 * @param $checkWhitelist Bool: whether to check the whitelist first
1246 * @return Bool True if blacklisted.
1248 function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1249 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1250 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1252 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1253 return false;
1255 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1256 return false;
1258 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1259 return $this->inDnsBlacklist( $ip, $urls );
1263 * Whether the given IP is in a given DNS blacklist.
1265 * @param $ip String IP to check
1266 * @param $bases String|Array of Strings: URL of the DNS blacklist
1267 * @return Bool True if blacklisted.
1269 function inDnsBlacklist( $ip, $bases ) {
1270 wfProfileIn( __METHOD__ );
1272 $found = false;
1273 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1274 if( IP::isIPv4( $ip ) ) {
1275 # Reverse IP, bug 21255
1276 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1278 foreach( (array)$bases as $base ) {
1279 # Make hostname
1280 $host = "$ipReversed.$base";
1282 # Send query
1283 $ipList = gethostbynamel( $host );
1285 if( $ipList ) {
1286 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1287 $found = true;
1288 break;
1289 } else {
1290 wfDebug( "Requested $host, not found in $base.\n" );
1295 wfProfileOut( __METHOD__ );
1296 return $found;
1300 * Is this user subject to rate limiting?
1302 * @return Bool True if rate limited
1304 public function isPingLimitable() {
1305 global $wgRateLimitsExcludedIPs;
1306 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1307 // No other good way currently to disable rate limits
1308 // for specific IPs. :P
1309 // But this is a crappy hack and should die.
1310 return false;
1312 return !$this->isAllowed('noratelimit');
1316 * Primitive rate limits: enforce maximum actions per time period
1317 * to put a brake on flooding.
1319 * @note When using a shared cache like memcached, IP-address
1320 * last-hit counters will be shared across wikis.
1322 * @param $action String Action to enforce; 'edit' if unspecified
1323 * @return Bool True if a rate limiter was tripped
1325 function pingLimiter( $action = 'edit' ) {
1326 # Call the 'PingLimiter' hook
1327 $result = false;
1328 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1329 return $result;
1332 global $wgRateLimits;
1333 if( !isset( $wgRateLimits[$action] ) ) {
1334 return false;
1337 # Some groups shouldn't trigger the ping limiter, ever
1338 if( !$this->isPingLimitable() )
1339 return false;
1341 global $wgMemc, $wgRateLimitLog;
1342 wfProfileIn( __METHOD__ );
1344 $limits = $wgRateLimits[$action];
1345 $keys = array();
1346 $id = $this->getId();
1347 $ip = wfGetIP();
1348 $userLimit = false;
1350 if( isset( $limits['anon'] ) && $id == 0 ) {
1351 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1354 if( isset( $limits['user'] ) && $id != 0 ) {
1355 $userLimit = $limits['user'];
1357 if( $this->isNewbie() ) {
1358 if( isset( $limits['newbie'] ) && $id != 0 ) {
1359 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1361 if( isset( $limits['ip'] ) ) {
1362 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1364 $matches = array();
1365 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1366 $subnet = $matches[1];
1367 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1370 // Check for group-specific permissions
1371 // If more than one group applies, use the group with the highest limit
1372 foreach ( $this->getGroups() as $group ) {
1373 if ( isset( $limits[$group] ) ) {
1374 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1375 $userLimit = $limits[$group];
1379 // Set the user limit key
1380 if ( $userLimit !== false ) {
1381 wfDebug( __METHOD__ . ": effective user limit: $userLimit\n" );
1382 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1385 $triggered = false;
1386 foreach( $keys as $key => $limit ) {
1387 list( $max, $period ) = $limit;
1388 $summary = "(limit $max in {$period}s)";
1389 $count = $wgMemc->get( $key );
1390 // Already pinged?
1391 if( $count ) {
1392 if( $count > $max ) {
1393 wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
1394 if( $wgRateLimitLog ) {
1395 @file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND );
1397 $triggered = true;
1398 } else {
1399 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1401 } else {
1402 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1403 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1405 $wgMemc->incr( $key );
1408 wfProfileOut( __METHOD__ );
1409 return $triggered;
1413 * Check if user is blocked
1415 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1416 * @return Bool True if blocked, false otherwise
1418 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1419 $this->getBlockedStatus( $bFromSlave );
1420 return $this->mBlock instanceof Block && $this->mBlock->prevents( 'edit' );
1424 * Check if user is blocked from editing a particular article
1426 * @param $title Title to check
1427 * @param $bFromSlave Bool whether to check the slave database instead of the master
1428 * @return Bool
1430 function isBlockedFrom( $title, $bFromSlave = false ) {
1431 global $wgBlockAllowsUTEdit;
1432 wfProfileIn( __METHOD__ );
1434 $blocked = $this->isBlocked( $bFromSlave );
1435 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1436 # If a user's name is suppressed, they cannot make edits anywhere
1437 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1438 $title->getNamespace() == NS_USER_TALK ) {
1439 $blocked = false;
1440 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1443 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1445 wfProfileOut( __METHOD__ );
1446 return $blocked;
1450 * If user is blocked, return the name of the user who placed the block
1451 * @return String name of blocker
1453 function blockedBy() {
1454 $this->getBlockedStatus();
1455 return $this->mBlockedby;
1459 * If user is blocked, return the specified reason for the block
1460 * @return String Blocking reason
1462 function blockedFor() {
1463 $this->getBlockedStatus();
1464 return $this->mBlockreason;
1468 * If user is blocked, return the ID for the block
1469 * @return Int Block ID
1471 function getBlockId() {
1472 $this->getBlockedStatus();
1473 return ( $this->mBlock ? $this->mBlock->getId() : false );
1477 * Check if user is blocked on all wikis.
1478 * Do not use for actual edit permission checks!
1479 * This is intented for quick UI checks.
1481 * @param $ip String IP address, uses current client if none given
1482 * @return Bool True if blocked, false otherwise
1484 function isBlockedGlobally( $ip = '' ) {
1485 if( $this->mBlockedGlobally !== null ) {
1486 return $this->mBlockedGlobally;
1488 // User is already an IP?
1489 if( IP::isIPAddress( $this->getName() ) ) {
1490 $ip = $this->getName();
1491 } else if( !$ip ) {
1492 $ip = wfGetIP();
1494 $blocked = false;
1495 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1496 $this->mBlockedGlobally = (bool)$blocked;
1497 return $this->mBlockedGlobally;
1501 * Check if user account is locked
1503 * @return Bool True if locked, false otherwise
1505 function isLocked() {
1506 if( $this->mLocked !== null ) {
1507 return $this->mLocked;
1509 global $wgAuth;
1510 $authUser = $wgAuth->getUserInstance( $this );
1511 $this->mLocked = (bool)$authUser->isLocked();
1512 return $this->mLocked;
1516 * Check if user account is hidden
1518 * @return Bool True if hidden, false otherwise
1520 function isHidden() {
1521 if( $this->mHideName !== null ) {
1522 return $this->mHideName;
1524 $this->getBlockedStatus();
1525 if( !$this->mHideName ) {
1526 global $wgAuth;
1527 $authUser = $wgAuth->getUserInstance( $this );
1528 $this->mHideName = (bool)$authUser->isHidden();
1530 return $this->mHideName;
1534 * Get the user's ID.
1535 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1537 function getId() {
1538 if( $this->mId === null && $this->mName !== null
1539 && User::isIP( $this->mName ) ) {
1540 // Special case, we know the user is anonymous
1541 return 0;
1542 } elseif( !$this->isItemLoaded( 'id' ) ) {
1543 // Don't load if this was initialized from an ID
1544 $this->load();
1546 return $this->mId;
1550 * Set the user and reload all fields according to a given ID
1551 * @param $v Int User ID to reload
1553 function setId( $v ) {
1554 $this->mId = $v;
1555 $this->clearInstanceCache( 'id' );
1559 * Get the user name, or the IP of an anonymous user
1560 * @return String User's name or IP address
1562 function getName() {
1563 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1564 # Special case optimisation
1565 return $this->mName;
1566 } else {
1567 $this->load();
1568 if ( $this->mName === false ) {
1569 # Clean up IPs
1570 $this->mName = IP::sanitizeIP( wfGetIP() );
1572 return $this->mName;
1577 * Set the user name.
1579 * This does not reload fields from the database according to the given
1580 * name. Rather, it is used to create a temporary "nonexistent user" for
1581 * later addition to the database. It can also be used to set the IP
1582 * address for an anonymous user to something other than the current
1583 * remote IP.
1585 * @note User::newFromName() has rougly the same function, when the named user
1586 * does not exist.
1587 * @param $str String New user name to set
1589 function setName( $str ) {
1590 $this->load();
1591 $this->mName = $str;
1595 * Get the user's name escaped by underscores.
1596 * @return String Username escaped by underscores.
1598 function getTitleKey() {
1599 return str_replace( ' ', '_', $this->getName() );
1603 * Check if the user has new messages.
1604 * @return Bool True if the user has new messages
1606 function getNewtalk() {
1607 $this->load();
1609 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1610 if( $this->mNewtalk === -1 ) {
1611 $this->mNewtalk = false; # reset talk page status
1613 # Check memcached separately for anons, who have no
1614 # entire User object stored in there.
1615 if( !$this->mId ) {
1616 global $wgMemc;
1617 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1618 $newtalk = $wgMemc->get( $key );
1619 if( strval( $newtalk ) !== '' ) {
1620 $this->mNewtalk = (bool)$newtalk;
1621 } else {
1622 // Since we are caching this, make sure it is up to date by getting it
1623 // from the master
1624 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1625 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1627 } else {
1628 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1632 return (bool)$this->mNewtalk;
1636 * Return the talk page(s) this user has new messages on.
1637 * @return Array of String page URLs
1639 function getNewMessageLinks() {
1640 $talks = array();
1641 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1642 return $talks;
1644 if( !$this->getNewtalk() )
1645 return array();
1646 $up = $this->getUserPage();
1647 $utp = $up->getTalkPage();
1648 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1652 * Internal uncached check for new messages
1654 * @see getNewtalk()
1655 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1656 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1657 * @param $fromMaster Bool true to fetch from the master, false for a slave
1658 * @return Bool True if the user has new messages
1660 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1661 if ( $fromMaster ) {
1662 $db = wfGetDB( DB_MASTER );
1663 } else {
1664 $db = wfGetDB( DB_SLAVE );
1666 $ok = $db->selectField( 'user_newtalk', $field,
1667 array( $field => $id ), __METHOD__ );
1668 return $ok !== false;
1672 * Add or update the new messages flag
1673 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1674 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1675 * @return Bool True if successful, false otherwise
1677 protected function updateNewtalk( $field, $id ) {
1678 $dbw = wfGetDB( DB_MASTER );
1679 $dbw->insert( 'user_newtalk',
1680 array( $field => $id ),
1681 __METHOD__,
1682 'IGNORE' );
1683 if ( $dbw->affectedRows() ) {
1684 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
1685 return true;
1686 } else {
1687 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
1688 return false;
1693 * Clear the new messages flag for the given user
1694 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1695 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1696 * @return Bool True if successful, false otherwise
1698 protected function deleteNewtalk( $field, $id ) {
1699 $dbw = wfGetDB( DB_MASTER );
1700 $dbw->delete( 'user_newtalk',
1701 array( $field => $id ),
1702 __METHOD__ );
1703 if ( $dbw->affectedRows() ) {
1704 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
1705 return true;
1706 } else {
1707 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
1708 return false;
1713 * Update the 'You have new messages!' status.
1714 * @param $val Bool Whether the user has new messages
1716 function setNewtalk( $val ) {
1717 if( wfReadOnly() ) {
1718 return;
1721 $this->load();
1722 $this->mNewtalk = $val;
1724 if( $this->isAnon() ) {
1725 $field = 'user_ip';
1726 $id = $this->getName();
1727 } else {
1728 $field = 'user_id';
1729 $id = $this->getId();
1731 global $wgMemc;
1733 if( $val ) {
1734 $changed = $this->updateNewtalk( $field, $id );
1735 } else {
1736 $changed = $this->deleteNewtalk( $field, $id );
1739 if( $this->isAnon() ) {
1740 // Anons have a separate memcached space, since
1741 // user records aren't kept for them.
1742 $key = wfMemcKey( 'newtalk', 'ip', $id );
1743 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1745 if ( $changed ) {
1746 $this->invalidateCache();
1751 * Generate a current or new-future timestamp to be stored in the
1752 * user_touched field when we update things.
1753 * @return String Timestamp in TS_MW format
1755 private static function newTouchedTimestamp() {
1756 global $wgClockSkewFudge;
1757 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1761 * Clear user data from memcached.
1762 * Use after applying fun updates to the database; caller's
1763 * responsibility to update user_touched if appropriate.
1765 * Called implicitly from invalidateCache() and saveSettings().
1767 private function clearSharedCache() {
1768 $this->load();
1769 if( $this->mId ) {
1770 global $wgMemc;
1771 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1776 * Immediately touch the user data cache for this account.
1777 * Updates user_touched field, and removes account data from memcached
1778 * for reload on the next hit.
1780 function invalidateCache() {
1781 if( wfReadOnly() ) {
1782 return;
1784 $this->load();
1785 if( $this->mId ) {
1786 $this->mTouched = self::newTouchedTimestamp();
1788 $dbw = wfGetDB( DB_MASTER );
1789 $dbw->update( 'user',
1790 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1791 array( 'user_id' => $this->mId ),
1792 __METHOD__ );
1794 $this->clearSharedCache();
1799 * Validate the cache for this account.
1800 * @param $timestamp String A timestamp in TS_MW format
1802 function validateCache( $timestamp ) {
1803 $this->load();
1804 return ( $timestamp >= $this->mTouched );
1808 * Get the user touched timestamp
1809 * @return String timestamp
1811 function getTouched() {
1812 $this->load();
1813 return $this->mTouched;
1817 * Set the password and reset the random token.
1818 * Calls through to authentication plugin if necessary;
1819 * will have no effect if the auth plugin refuses to
1820 * pass the change through or if the legal password
1821 * checks fail.
1823 * As a special case, setting the password to null
1824 * wipes it, so the account cannot be logged in until
1825 * a new password is set, for instance via e-mail.
1827 * @param $str String New password to set
1828 * @throws PasswordError on failure
1830 function setPassword( $str ) {
1831 global $wgAuth;
1833 if( $str !== null ) {
1834 if( !$wgAuth->allowPasswordChange() ) {
1835 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1838 if( !$this->isValidPassword( $str ) ) {
1839 global $wgMinimalPasswordLength;
1840 $valid = $this->getPasswordValidity( $str );
1841 if ( is_array( $valid ) ) {
1842 $message = array_shift( $valid );
1843 $params = $valid;
1844 } else {
1845 $message = $valid;
1846 $params = array( $wgMinimalPasswordLength );
1848 throw new PasswordError( wfMsgExt( $message, array( 'parsemag' ), $params ) );
1852 if( !$wgAuth->setPassword( $this, $str ) ) {
1853 throw new PasswordError( wfMsg( 'externaldberror' ) );
1856 $this->setInternalPassword( $str );
1858 return true;
1862 * Set the password and reset the random token unconditionally.
1864 * @param $str String New password to set
1866 function setInternalPassword( $str ) {
1867 $this->load();
1868 $this->setToken();
1870 if( $str === null ) {
1871 // Save an invalid hash...
1872 $this->mPassword = '';
1873 } else {
1874 $this->mPassword = self::crypt( $str );
1876 $this->mNewpassword = '';
1877 $this->mNewpassTime = null;
1881 * Get the user's current token.
1882 * @return String Token
1884 function getToken() {
1885 $this->load();
1886 return $this->mToken;
1890 * Set the random token (used for persistent authentication)
1891 * Called from loadDefaults() among other places.
1893 * @param $token String If specified, set the token to this value
1894 * @private
1896 function setToken( $token = false ) {
1897 global $wgSecretKey, $wgProxyKey;
1898 $this->load();
1899 if ( !$token ) {
1900 if ( $wgSecretKey ) {
1901 $key = $wgSecretKey;
1902 } elseif ( $wgProxyKey ) {
1903 $key = $wgProxyKey;
1904 } else {
1905 $key = microtime();
1907 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1908 } else {
1909 $this->mToken = $token;
1914 * Set the cookie password
1916 * @param $str String New cookie password
1917 * @private
1919 function setCookiePassword( $str ) {
1920 $this->load();
1921 $this->mCookiePassword = md5( $str );
1925 * Set the password for a password reminder or new account email
1927 * @param $str String New password to set
1928 * @param $throttle Bool If true, reset the throttle timestamp to the present
1930 function setNewpassword( $str, $throttle = true ) {
1931 $this->load();
1932 $this->mNewpassword = self::crypt( $str );
1933 if ( $throttle ) {
1934 $this->mNewpassTime = wfTimestampNow();
1939 * Has password reminder email been sent within the last
1940 * $wgPasswordReminderResendTime hours?
1941 * @return Bool
1943 function isPasswordReminderThrottled() {
1944 global $wgPasswordReminderResendTime;
1945 $this->load();
1946 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1947 return false;
1949 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1950 return time() < $expiry;
1954 * Get the user's e-mail address
1955 * @return String User's email address
1957 function getEmail() {
1958 $this->load();
1959 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1960 return $this->mEmail;
1964 * Get the timestamp of the user's e-mail authentication
1965 * @return String TS_MW timestamp
1967 function getEmailAuthenticationTimestamp() {
1968 $this->load();
1969 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1970 return $this->mEmailAuthenticated;
1974 * Set the user's e-mail address
1975 * @param $str String New e-mail address
1977 function setEmail( $str ) {
1978 $this->load();
1979 $this->mEmail = $str;
1980 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1984 * Get the user's real name
1985 * @return String User's real name
1987 function getRealName() {
1988 if ( !$this->isItemLoaded( 'realname' ) ) {
1989 $this->load();
1992 return $this->mRealName;
1996 * Set the user's real name
1997 * @param $str String New real name
1999 function setRealName( $str ) {
2000 $this->load();
2001 $this->mRealName = $str;
2005 * Get the user's current setting for a given option.
2007 * @param $oname String The option to check
2008 * @param $defaultOverride String A default value returned if the option does not exist
2009 * @param $ignoreHidden Bool = whether to ignore the effects of $wgHiddenPrefs
2010 * @return String User's current value for the option
2011 * @see getBoolOption()
2012 * @see getIntOption()
2014 function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2015 global $wgHiddenPrefs;
2016 $this->loadOptions();
2018 if ( is_null( $this->mOptions ) ) {
2019 if($defaultOverride != '') {
2020 return $defaultOverride;
2022 $this->mOptions = User::getDefaultOptions();
2025 # We want 'disabled' preferences to always behave as the default value for
2026 # users, even if they have set the option explicitly in their settings (ie they
2027 # set it, and then it was disabled removing their ability to change it). But
2028 # we don't want to erase the preferences in the database in case the preference
2029 # is re-enabled again. So don't touch $mOptions, just override the returned value
2030 if( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ){
2031 return self::getDefaultOption( $oname );
2034 if ( array_key_exists( $oname, $this->mOptions ) ) {
2035 return $this->mOptions[$oname];
2036 } else {
2037 return $defaultOverride;
2042 * Get all user's options
2044 * @return array
2046 public function getOptions() {
2047 global $wgHiddenPrefs;
2048 $this->loadOptions();
2049 $options = $this->mOptions;
2051 # We want 'disabled' preferences to always behave as the default value for
2052 # users, even if they have set the option explicitly in their settings (ie they
2053 # set it, and then it was disabled removing their ability to change it). But
2054 # we don't want to erase the preferences in the database in case the preference
2055 # is re-enabled again. So don't touch $mOptions, just override the returned value
2056 foreach( $wgHiddenPrefs as $pref ){
2057 $default = self::getDefaultOption( $pref );
2058 if( $default !== null ){
2059 $options[$pref] = $default;
2063 return $options;
2067 * Get the user's current setting for a given option, as a boolean value.
2069 * @param $oname String The option to check
2070 * @return Bool User's current value for the option
2071 * @see getOption()
2073 function getBoolOption( $oname ) {
2074 return (bool)$this->getOption( $oname );
2079 * Get the user's current setting for a given option, as a boolean value.
2081 * @param $oname String The option to check
2082 * @param $defaultOverride Int A default value returned if the option does not exist
2083 * @return Int User's current value for the option
2084 * @see getOption()
2086 function getIntOption( $oname, $defaultOverride=0 ) {
2087 $val = $this->getOption( $oname );
2088 if( $val == '' ) {
2089 $val = $defaultOverride;
2091 return intval( $val );
2095 * Set the given option for a user.
2097 * @param $oname String The option to set
2098 * @param $val mixed New value to set
2100 function setOption( $oname, $val ) {
2101 $this->load();
2102 $this->loadOptions();
2104 if ( $oname == 'skin' ) {
2105 # Clear cached skin, so the new one displays immediately in Special:Preferences
2106 $this->mSkin = null;
2109 // Explicitly NULL values should refer to defaults
2110 global $wgDefaultUserOptions;
2111 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2112 $val = $wgDefaultUserOptions[$oname];
2115 $this->mOptions[$oname] = $val;
2119 * Reset all options to the site defaults
2121 function resetOptions() {
2122 $this->mOptions = self::getDefaultOptions();
2126 * Get the user's preferred date format.
2127 * @return String User's preferred date format
2129 function getDatePreference() {
2130 // Important migration for old data rows
2131 if ( is_null( $this->mDatePreference ) ) {
2132 global $wgLang;
2133 $value = $this->getOption( 'date' );
2134 $map = $wgLang->getDatePreferenceMigrationMap();
2135 if ( isset( $map[$value] ) ) {
2136 $value = $map[$value];
2138 $this->mDatePreference = $value;
2140 return $this->mDatePreference;
2144 * Get the user preferred stub threshold
2146 function getStubThreshold() {
2147 global $wgMaxArticleSize; # Maximum article size, in Kb
2148 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2149 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2150 # If they have set an impossible value, disable the preference
2151 # so we can use the parser cache again.
2152 $threshold = 0;
2154 return $threshold;
2158 * Get the permissions this user has.
2159 * @return Array of String permission names
2161 function getRights() {
2162 if ( is_null( $this->mRights ) ) {
2163 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2164 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2165 // Force reindexation of rights when a hook has unset one of them
2166 $this->mRights = array_values( $this->mRights );
2168 return $this->mRights;
2172 * Get the list of explicit group memberships this user has.
2173 * The implicit * and user groups are not included.
2174 * @return Array of String internal group names
2176 function getGroups() {
2177 $this->load();
2178 return $this->mGroups;
2182 * Get the list of implicit group memberships this user has.
2183 * This includes all explicit groups, plus 'user' if logged in,
2184 * '*' for all accounts, and autopromoted groups
2185 * @param $recache Bool Whether to avoid the cache
2186 * @return Array of String internal group names
2188 function getEffectiveGroups( $recache = false ) {
2189 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2190 wfProfileIn( __METHOD__ );
2191 $this->mEffectiveGroups = $this->getGroups();
2192 $this->mEffectiveGroups[] = '*';
2193 if( $this->getId() ) {
2194 $this->mEffectiveGroups[] = 'user';
2196 $this->mEffectiveGroups = array_unique( array_merge(
2197 $this->mEffectiveGroups,
2198 Autopromote::getAutopromoteGroups( $this )
2199 ) );
2201 # Hook for additional groups
2202 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2204 wfProfileOut( __METHOD__ );
2206 return $this->mEffectiveGroups;
2210 * Get the user's edit count.
2211 * @return Int
2213 function getEditCount() {
2214 if( $this->getId() ) {
2215 if ( !isset( $this->mEditCount ) ) {
2216 /* Populate the count, if it has not been populated yet */
2217 $this->mEditCount = User::edits( $this->mId );
2219 return $this->mEditCount;
2220 } else {
2221 /* nil */
2222 return null;
2227 * Add the user to the given group.
2228 * This takes immediate effect.
2229 * @param $group String Name of the group to add
2231 function addGroup( $group ) {
2232 if( wfRunHooks( 'UserAddGroup', array( &$this, &$group ) ) ) {
2233 $dbw = wfGetDB( DB_MASTER );
2234 if( $this->getId() ) {
2235 $dbw->insert( 'user_groups',
2236 array(
2237 'ug_user' => $this->getID(),
2238 'ug_group' => $group,
2240 __METHOD__,
2241 array( 'IGNORE' ) );
2244 $this->loadGroups();
2245 $this->mGroups[] = $group;
2246 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2248 $this->invalidateCache();
2252 * Remove the user from the given group.
2253 * This takes immediate effect.
2254 * @param $group String Name of the group to remove
2256 function removeGroup( $group ) {
2257 $this->load();
2258 if( wfRunHooks( 'UserRemoveGroup', array( &$this, &$group ) ) ) {
2259 $dbw = wfGetDB( DB_MASTER );
2260 $dbw->delete( 'user_groups',
2261 array(
2262 'ug_user' => $this->getID(),
2263 'ug_group' => $group,
2264 ), __METHOD__ );
2266 $this->loadGroups();
2267 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2268 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2270 $this->invalidateCache();
2274 * Get whether the user is logged in
2275 * @return Bool
2277 function isLoggedIn() {
2278 return $this->getID() != 0;
2282 * Get whether the user is anonymous
2283 * @return Bool
2285 function isAnon() {
2286 return !$this->isLoggedIn();
2290 * Check if user is allowed to access a feature / make an action
2291 * @param varargs String permissions to test
2292 * @return Boolean: True if user is allowed to perform *any* of the given actions
2294 public function isAllowedAny( /*...*/ ){
2295 $permissions = func_get_args();
2296 foreach( $permissions as $permission ){
2297 if( $this->isAllowed( $permission ) ){
2298 return true;
2301 return false;
2305 * @param varargs String
2306 * @return bool True if the user is allowed to perform *all* of the given actions
2308 public function isAllowedAll( /*...*/ ){
2309 $permissions = func_get_args();
2310 foreach( $permissions as $permission ){
2311 if( !$this->isAllowed( $permission ) ){
2312 return false;
2315 return true;
2319 * Internal mechanics of testing a permission
2320 * @param $action String
2321 * @return bool
2323 public function isAllowed( $action = '' ) {
2324 if ( $action === '' ) {
2325 return true; // In the spirit of DWIM
2327 # Patrolling may not be enabled
2328 if( $action === 'patrol' || $action === 'autopatrol' ) {
2329 global $wgUseRCPatrol, $wgUseNPPatrol;
2330 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2331 return false;
2333 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2334 # by misconfiguration: 0 == 'foo'
2335 return in_array( $action, $this->getRights(), true );
2339 * Check whether to enable recent changes patrol features for this user
2340 * @return Boolean: True or false
2342 public function useRCPatrol() {
2343 global $wgUseRCPatrol;
2344 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2348 * Check whether to enable new pages patrol features for this user
2349 * @return Bool True or false
2351 public function useNPPatrol() {
2352 global $wgUseRCPatrol, $wgUseNPPatrol;
2353 return( ( $wgUseRCPatrol || $wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
2357 * Get the current skin, loading it if required
2358 * @return Skin The current skin
2359 * @todo FIXME: Need to check the old failback system [AV]
2360 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2362 function getSkin() {
2363 return RequestContext::getMain()->getSkin();
2367 * Check the watched status of an article.
2368 * @param $title Title of the article to look at
2369 * @return Bool
2371 function isWatched( $title ) {
2372 $wl = WatchedItem::fromUserTitle( $this, $title );
2373 return $wl->isWatched();
2377 * Watch an article.
2378 * @param $title Title of the article to look at
2380 function addWatch( $title ) {
2381 $wl = WatchedItem::fromUserTitle( $this, $title );
2382 $wl->addWatch();
2383 $this->invalidateCache();
2387 * Stop watching an article.
2388 * @param $title Title of the article to look at
2390 function removeWatch( $title ) {
2391 $wl = WatchedItem::fromUserTitle( $this, $title );
2392 $wl->removeWatch();
2393 $this->invalidateCache();
2397 * Clear the user's notification timestamp for the given title.
2398 * If e-notif e-mails are on, they will receive notification mails on
2399 * the next change of the page if it's watched etc.
2400 * @param $title Title of the article to look at
2402 function clearNotification( &$title ) {
2403 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2405 # Do nothing if the database is locked to writes
2406 if( wfReadOnly() ) {
2407 return;
2410 if( $title->getNamespace() == NS_USER_TALK &&
2411 $title->getText() == $this->getName() ) {
2412 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2413 return;
2414 $this->setNewtalk( false );
2417 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2418 return;
2421 if( $this->isAnon() ) {
2422 // Nothing else to do...
2423 return;
2426 // Only update the timestamp if the page is being watched.
2427 // The query to find out if it is watched is cached both in memcached and per-invocation,
2428 // and when it does have to be executed, it can be on a slave
2429 // If this is the user's newtalk page, we always update the timestamp
2430 if( $title->getNamespace() == NS_USER_TALK &&
2431 $title->getText() == $wgUser->getName() )
2433 $watched = true;
2434 } elseif ( $this->getId() == $wgUser->getId() ) {
2435 $watched = $title->userIsWatching();
2436 } else {
2437 $watched = true;
2440 // If the page is watched by the user (or may be watched), update the timestamp on any
2441 // any matching rows
2442 if ( $watched ) {
2443 $dbw = wfGetDB( DB_MASTER );
2444 $dbw->update( 'watchlist',
2445 array( /* SET */
2446 'wl_notificationtimestamp' => null
2447 ), array( /* WHERE */
2448 'wl_title' => $title->getDBkey(),
2449 'wl_namespace' => $title->getNamespace(),
2450 'wl_user' => $this->getID()
2451 ), __METHOD__
2457 * Resets all of the given user's page-change notification timestamps.
2458 * If e-notif e-mails are on, they will receive notification mails on
2459 * the next change of any watched page.
2461 * @param $currentUser Int User ID
2463 function clearAllNotifications( $currentUser ) {
2464 global $wgUseEnotif, $wgShowUpdatedMarker;
2465 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2466 $this->setNewtalk( false );
2467 return;
2469 if( $currentUser != 0 ) {
2470 $dbw = wfGetDB( DB_MASTER );
2471 $dbw->update( 'watchlist',
2472 array( /* SET */
2473 'wl_notificationtimestamp' => null
2474 ), array( /* WHERE */
2475 'wl_user' => $currentUser
2476 ), __METHOD__
2478 # We also need to clear here the "you have new message" notification for the own user_talk page
2479 # This is cleared one page view later in Article::viewUpdates();
2484 * Set this user's options from an encoded string
2485 * @param $str String Encoded options to import
2486 * @private
2488 function decodeOptions( $str ) {
2489 if( !$str )
2490 return;
2492 $this->mOptionsLoaded = true;
2493 $this->mOptionOverrides = array();
2495 // If an option is not set in $str, use the default value
2496 $this->mOptions = self::getDefaultOptions();
2498 $a = explode( "\n", $str );
2499 foreach ( $a as $s ) {
2500 $m = array();
2501 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2502 $this->mOptions[$m[1]] = $m[2];
2503 $this->mOptionOverrides[$m[1]] = $m[2];
2509 * Set a cookie on the user's client. Wrapper for
2510 * WebResponse::setCookie
2511 * @param $name String Name of the cookie to set
2512 * @param $value String Value to set
2513 * @param $exp Int Expiration time, as a UNIX time value;
2514 * if 0 or not specified, use the default $wgCookieExpiration
2516 protected function setCookie( $name, $value, $exp = 0 ) {
2517 global $wgRequest;
2518 $wgRequest->response()->setcookie( $name, $value, $exp );
2522 * Clear a cookie on the user's client
2523 * @param $name String Name of the cookie to clear
2525 protected function clearCookie( $name ) {
2526 $this->setCookie( $name, '', time() - 86400 );
2530 * Set the default cookies for this session on the user's client.
2532 * @param $request WebRequest object to use; $wgRequest will be used if null
2533 * is passed.
2535 function setCookies( $request = null ) {
2536 if ( $request === null ) {
2537 global $wgRequest;
2538 $request = $wgRequest;
2541 $this->load();
2542 if ( 0 == $this->mId ) return;
2543 $session = array(
2544 'wsUserID' => $this->mId,
2545 'wsToken' => $this->mToken,
2546 'wsUserName' => $this->getName()
2548 $cookies = array(
2549 'UserID' => $this->mId,
2550 'UserName' => $this->getName(),
2552 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2553 $cookies['Token'] = $this->mToken;
2554 } else {
2555 $cookies['Token'] = false;
2558 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2560 foreach ( $session as $name => $value ) {
2561 $request->setSessionData( $name, $value );
2563 foreach ( $cookies as $name => $value ) {
2564 if ( $value === false ) {
2565 $this->clearCookie( $name );
2566 } else {
2567 $this->setCookie( $name, $value );
2573 * Log this user out.
2575 function logout() {
2576 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2577 $this->doLogout();
2582 * Clear the user's cookies and session, and reset the instance cache.
2583 * @private
2584 * @see logout()
2586 function doLogout() {
2587 global $wgRequest;
2589 $this->clearInstanceCache( 'defaults' );
2591 $wgRequest->setSessionData( 'wsUserID', 0 );
2593 $this->clearCookie( 'UserID' );
2594 $this->clearCookie( 'Token' );
2596 # Remember when user logged out, to prevent seeing cached pages
2597 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2601 * Save this user's settings into the database.
2602 * @todo Only rarely do all these fields need to be set!
2604 function saveSettings() {
2605 $this->load();
2606 if ( wfReadOnly() ) { return; }
2607 if ( 0 == $this->mId ) { return; }
2609 $this->mTouched = self::newTouchedTimestamp();
2611 $dbw = wfGetDB( DB_MASTER );
2612 $dbw->update( 'user',
2613 array( /* SET */
2614 'user_name' => $this->mName,
2615 'user_password' => $this->mPassword,
2616 'user_newpassword' => $this->mNewpassword,
2617 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2618 'user_real_name' => $this->mRealName,
2619 'user_email' => $this->mEmail,
2620 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2621 'user_options' => '',
2622 'user_touched' => $dbw->timestamp( $this->mTouched ),
2623 'user_token' => $this->mToken,
2624 'user_email_token' => $this->mEmailToken,
2625 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2626 ), array( /* WHERE */
2627 'user_id' => $this->mId
2628 ), __METHOD__
2631 $this->saveOptions();
2633 wfRunHooks( 'UserSaveSettings', array( $this ) );
2634 $this->clearSharedCache();
2635 $this->getUserPage()->invalidateCache();
2639 * If only this user's username is known, and it exists, return the user ID.
2640 * @return Int
2642 function idForName() {
2643 $s = trim( $this->getName() );
2644 if ( $s === '' ) return 0;
2646 $dbr = wfGetDB( DB_SLAVE );
2647 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2648 if ( $id === false ) {
2649 $id = 0;
2651 return $id;
2655 * Add a user to the database, return the user object
2657 * @param $name String Username to add
2658 * @param $params Array of Strings Non-default parameters to save to the database as user_* fields:
2659 * - password The user's password hash. Password logins will be disabled if this is omitted.
2660 * - newpassword Hash for a temporary password that has been mailed to the user
2661 * - email The user's email address
2662 * - email_authenticated The email authentication timestamp
2663 * - real_name The user's real name
2664 * - options An associative array of non-default options
2665 * - token Random authentication token. Do not set.
2666 * - registration Registration timestamp. Do not set.
2668 * @return User object, or null if the username already exists
2670 static function createNew( $name, $params = array() ) {
2671 $user = new User;
2672 $user->load();
2673 if ( isset( $params['options'] ) ) {
2674 $user->mOptions = $params['options'] + (array)$user->mOptions;
2675 unset( $params['options'] );
2677 $dbw = wfGetDB( DB_MASTER );
2678 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2680 $fields = array(
2681 'user_id' => $seqVal,
2682 'user_name' => $name,
2683 'user_password' => $user->mPassword,
2684 'user_newpassword' => $user->mNewpassword,
2685 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
2686 'user_email' => $user->mEmail,
2687 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2688 'user_real_name' => $user->mRealName,
2689 'user_options' => '',
2690 'user_token' => $user->mToken,
2691 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2692 'user_editcount' => 0,
2694 foreach ( $params as $name => $value ) {
2695 $fields["user_$name"] = $value;
2697 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2698 if ( $dbw->affectedRows() ) {
2699 $newUser = User::newFromId( $dbw->insertId() );
2700 } else {
2701 $newUser = null;
2703 return $newUser;
2707 * Add this existing user object to the database
2709 function addToDatabase() {
2710 $this->load();
2711 $dbw = wfGetDB( DB_MASTER );
2712 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2713 $dbw->insert( 'user',
2714 array(
2715 'user_id' => $seqVal,
2716 'user_name' => $this->mName,
2717 'user_password' => $this->mPassword,
2718 'user_newpassword' => $this->mNewpassword,
2719 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2720 'user_email' => $this->mEmail,
2721 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2722 'user_real_name' => $this->mRealName,
2723 'user_options' => '',
2724 'user_token' => $this->mToken,
2725 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2726 'user_editcount' => 0,
2727 ), __METHOD__
2729 $this->mId = $dbw->insertId();
2731 // Clear instance cache other than user table data, which is already accurate
2732 $this->clearInstanceCache();
2734 $this->saveOptions();
2738 * If this (non-anonymous) user is blocked, block any IP address
2739 * they've successfully logged in from.
2741 function spreadBlock() {
2742 wfDebug( __METHOD__ . "()\n" );
2743 $this->load();
2744 if ( $this->mId == 0 ) {
2745 return;
2748 $userblock = Block::newFromTarget( $this->getName() );
2749 if ( !$userblock ) {
2750 return;
2753 $userblock->doAutoblock( wfGetIP() );
2757 * Generate a string which will be different for any combination of
2758 * user options which would produce different parser output.
2759 * This will be used as part of the hash key for the parser cache,
2760 * so users with the same options can share the same cached data
2761 * safely.
2763 * Extensions which require it should install 'PageRenderingHash' hook,
2764 * which will give them a chance to modify this key based on their own
2765 * settings.
2767 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
2768 * @return String Page rendering hash
2770 function getPageRenderingHash() {
2771 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2772 if( $this->mHash ){
2773 return $this->mHash;
2775 wfDeprecated( __METHOD__ );
2777 // stubthreshold is only included below for completeness,
2778 // since it disables the parser cache, its value will always
2779 // be 0 when this function is called by parsercache.
2781 $confstr = $this->getOption( 'math' );
2782 $confstr .= '!' . $this->getStubThreshold();
2783 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2784 $confstr .= '!' . $this->getDatePreference();
2786 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
2787 $confstr .= '!' . $wgLang->getCode();
2788 $confstr .= '!' . $this->getOption( 'thumbsize' );
2789 // add in language specific options, if any
2790 $extra = $wgContLang->getExtraHashOptions();
2791 $confstr .= $extra;
2793 // Since the skin could be overloading link(), it should be
2794 // included here but in practice, none of our skins do that.
2796 $confstr .= $wgRenderHashAppend;
2798 // Give a chance for extensions to modify the hash, if they have
2799 // extra options or other effects on the parser cache.
2800 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2802 // Make it a valid memcached key fragment
2803 $confstr = str_replace( ' ', '_', $confstr );
2804 $this->mHash = $confstr;
2805 return $confstr;
2809 * Get whether the user is explicitly blocked from account creation.
2810 * @return Bool|Block
2812 function isBlockedFromCreateAccount() {
2813 $this->getBlockedStatus();
2814 if( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ){
2815 return $this->mBlock;
2818 # bug 13611: if the IP address the user is trying to create an account from is
2819 # blocked with createaccount disabled, prevent new account creation there even
2820 # when the user is logged in
2821 static $accBlock = false;
2822 if( $accBlock === false ){
2823 $accBlock = Block::newFromTarget( null, wfGetIP() );
2825 return $accBlock instanceof Block && $accBlock->prevents( 'createaccount' )
2826 ? $accBlock
2827 : false;
2831 * Get whether the user is blocked from using Special:Emailuser.
2832 * @return Bool
2834 function isBlockedFromEmailuser() {
2835 $this->getBlockedStatus();
2836 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
2840 * Get whether the user is allowed to create an account.
2841 * @return Bool
2843 function isAllowedToCreateAccount() {
2844 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2848 * Get this user's personal page title.
2850 * @return Title: User's personal page title
2852 function getUserPage() {
2853 return Title::makeTitle( NS_USER, $this->getName() );
2857 * Get this user's talk page title.
2859 * @return Title: User's talk page title
2861 function getTalkPage() {
2862 $title = $this->getUserPage();
2863 return $title->getTalkPage();
2867 * Determine whether the user is a newbie. Newbies are either
2868 * anonymous IPs, or the most recently created accounts.
2869 * @return Bool
2871 function isNewbie() {
2872 return !$this->isAllowed( 'autoconfirmed' );
2876 * Check to see if the given clear-text password is one of the accepted passwords
2877 * @param $password String: user password.
2878 * @return Boolean: True if the given password is correct, otherwise False.
2880 function checkPassword( $password ) {
2881 global $wgAuth, $wgLegacyEncoding;
2882 $this->load();
2884 // Even though we stop people from creating passwords that
2885 // are shorter than this, doesn't mean people wont be able
2886 // to. Certain authentication plugins do NOT want to save
2887 // domain passwords in a mysql database, so we should
2888 // check this (in case $wgAuth->strict() is false).
2889 if( !$this->isValidPassword( $password ) ) {
2890 return false;
2893 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2894 return true;
2895 } elseif( $wgAuth->strict() ) {
2896 /* Auth plugin doesn't allow local authentication */
2897 return false;
2898 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2899 /* Auth plugin doesn't allow local authentication for this user name */
2900 return false;
2902 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2903 return true;
2904 } elseif ( $wgLegacyEncoding ) {
2905 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2906 # Check for this with iconv
2907 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2908 if ( $cp1252Password != $password &&
2909 self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) )
2911 return true;
2914 return false;
2918 * Check if the given clear-text password matches the temporary password
2919 * sent by e-mail for password reset operations.
2920 * @return Boolean: True if matches, false otherwise
2922 function checkTemporaryPassword( $plaintext ) {
2923 global $wgNewPasswordExpiry;
2925 $this->load();
2926 if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
2927 if ( is_null( $this->mNewpassTime ) ) {
2928 return true;
2930 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
2931 return ( time() < $expiry );
2932 } else {
2933 return false;
2938 * Initialize (if necessary) and return a session token value
2939 * which can be used in edit forms to show that the user's
2940 * login credentials aren't being hijacked with a foreign form
2941 * submission.
2943 * @param $salt String|Array of Strings Optional function-specific data for hashing
2944 * @param $request WebRequest object to use or null to use $wgRequest
2945 * @return String The new edit token
2947 function editToken( $salt = '', $request = null ) {
2948 if ( $request == null ) {
2949 global $wgRequest;
2950 $request = $wgRequest;
2953 if ( $this->isAnon() ) {
2954 return EDIT_TOKEN_SUFFIX;
2955 } else {
2956 $token = $request->getSessionData( 'wsEditToken' );
2957 if ( $token === null ) {
2958 $token = self::generateToken();
2959 $request->setSessionData( 'wsEditToken', $token );
2961 if( is_array( $salt ) ) {
2962 $salt = implode( '|', $salt );
2964 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2969 * Generate a looking random token for various uses.
2971 * @param $salt String Optional salt value
2972 * @return String The new random token
2974 public static function generateToken( $salt = '' ) {
2975 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2976 return md5( $token . $salt );
2980 * Check given value against the token value stored in the session.
2981 * A match should confirm that the form was submitted from the
2982 * user's own login session, not a form submission from a third-party
2983 * site.
2985 * @param $val String Input value to compare
2986 * @param $salt String Optional function-specific data for hashing
2987 * @param $request WebRequest object to use or null to use $wgRequest
2988 * @return Boolean: Whether the token matches
2990 function matchEditToken( $val, $salt = '', $request = null ) {
2991 $sessionToken = $this->editToken( $salt, $request );
2992 if ( $val != $sessionToken ) {
2993 wfDebug( "User::matchEditToken: broken session data\n" );
2995 return $val == $sessionToken;
2999 * Check given value against the token value stored in the session,
3000 * ignoring the suffix.
3002 * @param $val String Input value to compare
3003 * @param $salt String Optional function-specific data for hashing
3004 * @param $request WebRequest object to use or null to use $wgRequest
3005 * @return Boolean: Whether the token matches
3007 function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3008 $sessionToken = $this->editToken( $salt, $request );
3009 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3013 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3014 * mail to the user's given address.
3016 * @param $type String: message to send, either "created", "changed" or "set"
3017 * @return Status object
3019 function sendConfirmationMail( $type = 'created' ) {
3020 global $wgLang;
3021 $expiration = null; // gets passed-by-ref and defined in next line.
3022 $token = $this->confirmationToken( $expiration );
3023 $url = $this->confirmationTokenUrl( $token );
3024 $invalidateURL = $this->invalidationTokenUrl( $token );
3025 $this->saveSettings();
3027 if ( $type == 'created' || $type === false ) {
3028 $message = 'confirmemail_body';
3029 } elseif ( $type === true ) {
3030 $message = 'confirmemail_body_changed';
3031 } else {
3032 $message = 'confirmemail_body_' . $type;
3035 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
3036 wfMsg( $message,
3037 wfGetIP(),
3038 $this->getName(),
3039 $url,
3040 $wgLang->timeanddate( $expiration, false ),
3041 $invalidateURL,
3042 $wgLang->date( $expiration, false ),
3043 $wgLang->time( $expiration, false ) ) );
3047 * Send an e-mail to this user's account. Does not check for
3048 * confirmed status or validity.
3050 * @param $subject String Message subject
3051 * @param $body String Message body
3052 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
3053 * @param $replyto String Reply-To address
3054 * @return Status
3056 function sendMail( $subject, $body, $from = null, $replyto = null ) {
3057 if( is_null( $from ) ) {
3058 global $wgPasswordSender, $wgPasswordSenderName;
3059 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3060 } else {
3061 $sender = new MailAddress( $from );
3064 $to = new MailAddress( $this );
3065 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3069 * Generate, store, and return a new e-mail confirmation code.
3070 * A hash (unsalted, since it's used as a key) is stored.
3072 * @note Call saveSettings() after calling this function to commit
3073 * this change to the database.
3075 * @param[out] &$expiration \mixed Accepts the expiration time
3076 * @return String New token
3077 * @private
3079 function confirmationToken( &$expiration ) {
3080 global $wgUserEmailConfirmationTokenExpiry;
3081 $now = time();
3082 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3083 $expiration = wfTimestamp( TS_MW, $expires );
3084 $token = self::generateToken( $this->mId . $this->mEmail . $expires );
3085 $hash = md5( $token );
3086 $this->load();
3087 $this->mEmailToken = $hash;
3088 $this->mEmailTokenExpires = $expiration;
3089 return $token;
3093 * Return a URL the user can use to confirm their email address.
3094 * @param $token String Accepts the email confirmation token
3095 * @return String New token URL
3096 * @private
3098 function confirmationTokenUrl( $token ) {
3099 return $this->getTokenUrl( 'ConfirmEmail', $token );
3103 * Return a URL the user can use to invalidate their email address.
3104 * @param $token String Accepts the email confirmation token
3105 * @return String New token URL
3106 * @private
3108 function invalidationTokenUrl( $token ) {
3109 return $this->getTokenUrl( 'Invalidateemail', $token );
3113 * Internal function to format the e-mail validation/invalidation URLs.
3114 * This uses $wgArticlePath directly as a quickie hack to use the
3115 * hardcoded English names of the Special: pages, for ASCII safety.
3117 * @note Since these URLs get dropped directly into emails, using the
3118 * short English names avoids insanely long URL-encoded links, which
3119 * also sometimes can get corrupted in some browsers/mailers
3120 * (bug 6957 with Gmail and Internet Explorer).
3122 * @param $page String Special page
3123 * @param $token String Token
3124 * @return String Formatted URL
3126 protected function getTokenUrl( $page, $token ) {
3127 global $wgArticlePath;
3128 return wfExpandUrl(
3129 str_replace(
3130 '$1',
3131 "Special:$page/$token",
3132 $wgArticlePath ) );
3136 * Mark the e-mail address confirmed.
3138 * @note Call saveSettings() after calling this function to commit the change.
3140 function confirmEmail() {
3141 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3142 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3143 return true;
3147 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3148 * address if it was already confirmed.
3150 * @note Call saveSettings() after calling this function to commit the change.
3152 function invalidateEmail() {
3153 $this->load();
3154 $this->mEmailToken = null;
3155 $this->mEmailTokenExpires = null;
3156 $this->setEmailAuthenticationTimestamp( null );
3157 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3158 return true;
3162 * Set the e-mail authentication timestamp.
3163 * @param $timestamp String TS_MW timestamp
3165 function setEmailAuthenticationTimestamp( $timestamp ) {
3166 $this->load();
3167 $this->mEmailAuthenticated = $timestamp;
3168 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
3172 * Is this user allowed to send e-mails within limits of current
3173 * site configuration?
3174 * @return Bool
3176 function canSendEmail() {
3177 global $wgEnableEmail, $wgEnableUserEmail;
3178 if( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
3179 return false;
3181 $canSend = $this->isEmailConfirmed();
3182 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3183 return $canSend;
3187 * Is this user allowed to receive e-mails within limits of current
3188 * site configuration?
3189 * @return Bool
3191 function canReceiveEmail() {
3192 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3196 * Is this user's e-mail address valid-looking and confirmed within
3197 * limits of the current site configuration?
3199 * @note If $wgEmailAuthentication is on, this may require the user to have
3200 * confirmed their address by returning a code or using a password
3201 * sent to the address from the wiki.
3203 * @return Bool
3205 function isEmailConfirmed() {
3206 global $wgEmailAuthentication;
3207 $this->load();
3208 $confirmed = true;
3209 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3210 if( $this->isAnon() )
3211 return false;
3212 if( !self::isValidEmailAddr( $this->mEmail ) )
3213 return false;
3214 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3215 return false;
3216 return true;
3217 } else {
3218 return $confirmed;
3223 * Check whether there is an outstanding request for e-mail confirmation.
3224 * @return Bool
3226 function isEmailConfirmationPending() {
3227 global $wgEmailAuthentication;
3228 return $wgEmailAuthentication &&
3229 !$this->isEmailConfirmed() &&
3230 $this->mEmailToken &&
3231 $this->mEmailTokenExpires > wfTimestamp();
3235 * Get the timestamp of account creation.
3237 * @return String|Bool Timestamp of account creation, or false for
3238 * non-existent/anonymous user accounts.
3240 public function getRegistration() {
3241 if ( $this->isAnon() ) {
3242 return false;
3244 $this->load();
3245 return $this->mRegistration;
3249 * Get the timestamp of the first edit
3251 * @return String|Bool Timestamp of first edit, or false for
3252 * non-existent/anonymous user accounts.
3254 public function getFirstEditTimestamp() {
3255 if( $this->getId() == 0 ) {
3256 return false; // anons
3258 $dbr = wfGetDB( DB_SLAVE );
3259 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3260 array( 'rev_user' => $this->getId() ),
3261 __METHOD__,
3262 array( 'ORDER BY' => 'rev_timestamp ASC' )
3264 if( !$time ) {
3265 return false; // no edits
3267 return wfTimestamp( TS_MW, $time );
3271 * Get the permissions associated with a given list of groups
3273 * @param $groups Array of Strings List of internal group names
3274 * @return Array of Strings List of permission key names for given groups combined
3276 static function getGroupPermissions( $groups ) {
3277 global $wgGroupPermissions, $wgRevokePermissions;
3278 $rights = array();
3279 // grant every granted permission first
3280 foreach( $groups as $group ) {
3281 if( isset( $wgGroupPermissions[$group] ) ) {
3282 $rights = array_merge( $rights,
3283 // array_filter removes empty items
3284 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3287 // now revoke the revoked permissions
3288 foreach( $groups as $group ) {
3289 if( isset( $wgRevokePermissions[$group] ) ) {
3290 $rights = array_diff( $rights,
3291 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3294 return array_unique( $rights );
3298 * Get all the groups who have a given permission
3300 * @param $role String Role to check
3301 * @return Array of Strings List of internal group names with the given permission
3303 static function getGroupsWithPermission( $role ) {
3304 global $wgGroupPermissions;
3305 $allowedGroups = array();
3306 foreach ( $wgGroupPermissions as $group => $rights ) {
3307 if ( isset( $rights[$role] ) && $rights[$role] ) {
3308 $allowedGroups[] = $group;
3311 return $allowedGroups;
3315 * Get the localized descriptive name for a group, if it exists
3317 * @param $group String Internal group name
3318 * @return String Localized descriptive group name
3320 static function getGroupName( $group ) {
3321 $msg = wfMessage( "group-$group" );
3322 return $msg->isBlank() ? $group : $msg->text();
3326 * Get the localized descriptive name for a member of a group, if it exists
3328 * @param $group String Internal group name
3329 * @return String Localized name for group member
3331 static function getGroupMember( $group ) {
3332 $msg = wfMessage( "group-$group-member" );
3333 return $msg->isBlank() ? $group : $msg->text();
3337 * Return the set of defined explicit groups.
3338 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3339 * are not included, as they are defined automatically, not in the database.
3340 * @return Array of internal group names
3342 static function getAllGroups() {
3343 global $wgGroupPermissions, $wgRevokePermissions;
3344 return array_diff(
3345 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3346 self::getImplicitGroups()
3351 * Get a list of all available permissions.
3352 * @return Array of permission names
3354 static function getAllRights() {
3355 if ( self::$mAllRights === false ) {
3356 global $wgAvailableRights;
3357 if ( count( $wgAvailableRights ) ) {
3358 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3359 } else {
3360 self::$mAllRights = self::$mCoreRights;
3362 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3364 return self::$mAllRights;
3368 * Get a list of implicit groups
3369 * @return Array of Strings Array of internal group names
3371 public static function getImplicitGroups() {
3372 global $wgImplicitGroups;
3373 $groups = $wgImplicitGroups;
3374 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3375 return $groups;
3379 * Get the title of a page describing a particular group
3381 * @param $group String Internal group name
3382 * @return Title|Bool Title of the page if it exists, false otherwise
3384 static function getGroupPage( $group ) {
3385 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3386 if( $msg->exists() ) {
3387 $title = Title::newFromText( $msg->text() );
3388 if( is_object( $title ) )
3389 return $title;
3391 return false;
3395 * Create a link to the group in HTML, if available;
3396 * else return the group name.
3398 * @param $group String Internal name of the group
3399 * @param $text String The text of the link
3400 * @return String HTML link to the group
3402 static function makeGroupLinkHTML( $group, $text = '' ) {
3403 if( $text == '' ) {
3404 $text = self::getGroupName( $group );
3406 $title = self::getGroupPage( $group );
3407 if( $title ) {
3408 global $wgUser;
3409 $sk = $wgUser->getSkin();
3410 return $sk->link( $title, htmlspecialchars( $text ) );
3411 } else {
3412 return $text;
3417 * Create a link to the group in Wikitext, if available;
3418 * else return the group name.
3420 * @param $group String Internal name of the group
3421 * @param $text String The text of the link
3422 * @return String Wikilink to the group
3424 static function makeGroupLinkWiki( $group, $text = '' ) {
3425 if( $text == '' ) {
3426 $text = self::getGroupName( $group );
3428 $title = self::getGroupPage( $group );
3429 if( $title ) {
3430 $page = $title->getPrefixedText();
3431 return "[[$page|$text]]";
3432 } else {
3433 return $text;
3438 * Returns an array of the groups that a particular group can add/remove.
3440 * @param $group String: the group to check for whether it can add/remove
3441 * @return Array array( 'add' => array( addablegroups ),
3442 * 'remove' => array( removablegroups ),
3443 * 'add-self' => array( addablegroups to self),
3444 * 'remove-self' => array( removable groups from self) )
3446 static function changeableByGroup( $group ) {
3447 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3449 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3450 if( empty( $wgAddGroups[$group] ) ) {
3451 // Don't add anything to $groups
3452 } elseif( $wgAddGroups[$group] === true ) {
3453 // You get everything
3454 $groups['add'] = self::getAllGroups();
3455 } elseif( is_array( $wgAddGroups[$group] ) ) {
3456 $groups['add'] = $wgAddGroups[$group];
3459 // Same thing for remove
3460 if( empty( $wgRemoveGroups[$group] ) ) {
3461 } elseif( $wgRemoveGroups[$group] === true ) {
3462 $groups['remove'] = self::getAllGroups();
3463 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3464 $groups['remove'] = $wgRemoveGroups[$group];
3467 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3468 if( empty( $wgGroupsAddToSelf['user']) || $wgGroupsAddToSelf['user'] !== true ) {
3469 foreach( $wgGroupsAddToSelf as $key => $value ) {
3470 if( is_int( $key ) ) {
3471 $wgGroupsAddToSelf['user'][] = $value;
3476 if( empty( $wgGroupsRemoveFromSelf['user']) || $wgGroupsRemoveFromSelf['user'] !== true ) {
3477 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3478 if( is_int( $key ) ) {
3479 $wgGroupsRemoveFromSelf['user'][] = $value;
3484 // Now figure out what groups the user can add to him/herself
3485 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3486 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3487 // No idea WHY this would be used, but it's there
3488 $groups['add-self'] = User::getAllGroups();
3489 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3490 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3493 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3494 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3495 $groups['remove-self'] = User::getAllGroups();
3496 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3497 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3500 return $groups;
3504 * Returns an array of groups that this user can add and remove
3505 * @return Array array( 'add' => array( addablegroups ),
3506 * 'remove' => array( removablegroups ),
3507 * 'add-self' => array( addablegroups to self),
3508 * 'remove-self' => array( removable groups from self) )
3510 function changeableGroups() {
3511 if( $this->isAllowed( 'userrights' ) ) {
3512 // This group gives the right to modify everything (reverse-
3513 // compatibility with old "userrights lets you change
3514 // everything")
3515 // Using array_merge to make the groups reindexed
3516 $all = array_merge( User::getAllGroups() );
3517 return array(
3518 'add' => $all,
3519 'remove' => $all,
3520 'add-self' => array(),
3521 'remove-self' => array()
3525 // Okay, it's not so simple, we will have to go through the arrays
3526 $groups = array(
3527 'add' => array(),
3528 'remove' => array(),
3529 'add-self' => array(),
3530 'remove-self' => array()
3532 $addergroups = $this->getEffectiveGroups();
3534 foreach( $addergroups as $addergroup ) {
3535 $groups = array_merge_recursive(
3536 $groups, $this->changeableByGroup( $addergroup )
3538 $groups['add'] = array_unique( $groups['add'] );
3539 $groups['remove'] = array_unique( $groups['remove'] );
3540 $groups['add-self'] = array_unique( $groups['add-self'] );
3541 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3543 return $groups;
3547 * Increment the user's edit-count field.
3548 * Will have no effect for anonymous users.
3550 function incEditCount() {
3551 if( !$this->isAnon() ) {
3552 $dbw = wfGetDB( DB_MASTER );
3553 $dbw->update( 'user',
3554 array( 'user_editcount=user_editcount+1' ),
3555 array( 'user_id' => $this->getId() ),
3556 __METHOD__ );
3558 // Lazy initialization check...
3559 if( $dbw->affectedRows() == 0 ) {
3560 // Pull from a slave to be less cruel to servers
3561 // Accuracy isn't the point anyway here
3562 $dbr = wfGetDB( DB_SLAVE );
3563 $count = $dbr->selectField( 'revision',
3564 'COUNT(rev_user)',
3565 array( 'rev_user' => $this->getId() ),
3566 __METHOD__ );
3568 // Now here's a goddamn hack...
3569 if( $dbr !== $dbw ) {
3570 // If we actually have a slave server, the count is
3571 // at least one behind because the current transaction
3572 // has not been committed and replicated.
3573 $count++;
3574 } else {
3575 // But if DB_SLAVE is selecting the master, then the
3576 // count we just read includes the revision that was
3577 // just added in the working transaction.
3580 $dbw->update( 'user',
3581 array( 'user_editcount' => $count ),
3582 array( 'user_id' => $this->getId() ),
3583 __METHOD__ );
3586 // edit count in user cache too
3587 $this->invalidateCache();
3591 * Get the description of a given right
3593 * @param $right String Right to query
3594 * @return String Localized description of the right
3596 static function getRightDescription( $right ) {
3597 $key = "right-$right";
3598 $msg = wfMessage( $key );
3599 return $msg->isBlank() ? $right : $msg->text();
3603 * Make an old-style password hash
3605 * @param $password String Plain-text password
3606 * @param $userId String User ID
3607 * @return String Password hash
3609 static function oldCrypt( $password, $userId ) {
3610 global $wgPasswordSalt;
3611 if ( $wgPasswordSalt ) {
3612 return md5( $userId . '-' . md5( $password ) );
3613 } else {
3614 return md5( $password );
3619 * Make a new-style password hash
3621 * @param $password String Plain-text password
3622 * @param $salt String Optional salt, may be random or the user ID.
3623 * If unspecified or false, will generate one automatically
3624 * @return String Password hash
3626 static function crypt( $password, $salt = false ) {
3627 global $wgPasswordSalt;
3629 $hash = '';
3630 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3631 return $hash;
3634 if( $wgPasswordSalt ) {
3635 if ( $salt === false ) {
3636 $salt = substr( wfGenerateToken(), 0, 8 );
3638 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3639 } else {
3640 return ':A:' . md5( $password );
3645 * Compare a password hash with a plain-text password. Requires the user
3646 * ID if there's a chance that the hash is an old-style hash.
3648 * @param $hash String Password hash
3649 * @param $password String Plain-text password to compare
3650 * @param $userId String User ID for old-style password salt
3651 * @return Boolean:
3653 static function comparePasswords( $hash, $password, $userId = false ) {
3654 $type = substr( $hash, 0, 3 );
3656 $result = false;
3657 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3658 return $result;
3661 if ( $type == ':A:' ) {
3662 # Unsalted
3663 return md5( $password ) === substr( $hash, 3 );
3664 } elseif ( $type == ':B:' ) {
3665 # Salted
3666 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3667 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3668 } else {
3669 # Old-style
3670 return self::oldCrypt( $password, $userId ) === $hash;
3675 * Add a newuser log entry for this user
3677 * @param $byEmail Boolean: account made by email?
3678 * @param $reason String: user supplied reason
3680 * @return true
3682 public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
3683 global $wgUser, $wgContLang, $wgNewUserLog;
3684 if( empty( $wgNewUserLog ) ) {
3685 return true; // disabled
3688 if( $this->getName() == $wgUser->getName() ) {
3689 $action = 'create';
3690 } else {
3691 $action = 'create2';
3692 if ( $byEmail ) {
3693 if ( $reason === '' ) {
3694 $reason = wfMsgForContent( 'newuserlog-byemail' );
3695 } else {
3696 $reason = $wgContLang->commaList( array(
3697 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
3701 $log = new LogPage( 'newusers' );
3702 $log->addEntry(
3703 $action,
3704 $this->getUserPage(),
3705 $reason,
3706 array( $this->getId() )
3708 return true;
3712 * Add an autocreate newuser log entry for this user
3713 * Used by things like CentralAuth and perhaps other authplugins.
3715 * @return true
3717 public function addNewUserLogEntryAutoCreate() {
3718 global $wgNewUserLog;
3719 if( !$wgNewUserLog ) {
3720 return true; // disabled
3722 $log = new LogPage( 'newusers', false );
3723 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3724 return true;
3727 protected function loadOptions() {
3728 $this->load();
3729 if ( $this->mOptionsLoaded || !$this->getId() )
3730 return;
3732 $this->mOptions = self::getDefaultOptions();
3734 // Maybe load from the object
3735 if ( !is_null( $this->mOptionOverrides ) ) {
3736 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3737 foreach( $this->mOptionOverrides as $key => $value ) {
3738 $this->mOptions[$key] = $value;
3740 } else {
3741 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3742 // Load from database
3743 $dbr = wfGetDB( DB_SLAVE );
3745 $res = $dbr->select(
3746 'user_properties',
3747 '*',
3748 array( 'up_user' => $this->getId() ),
3749 __METHOD__
3752 foreach ( $res as $row ) {
3753 $this->mOptionOverrides[$row->up_property] = $row->up_value;
3754 $this->mOptions[$row->up_property] = $row->up_value;
3758 $this->mOptionsLoaded = true;
3760 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
3763 protected function saveOptions() {
3764 global $wgAllowPrefChange;
3766 $extuser = ExternalUser::newFromUser( $this );
3768 $this->loadOptions();
3769 $dbw = wfGetDB( DB_MASTER );
3771 $insert_rows = array();
3773 $saveOptions = $this->mOptions;
3775 // Allow hooks to abort, for instance to save to a global profile.
3776 // Reset options to default state before saving.
3777 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3778 return;
3780 foreach( $saveOptions as $key => $value ) {
3781 # Don't bother storing default values
3782 if ( ( is_null( self::getDefaultOption( $key ) ) &&
3783 !( $value === false || is_null($value) ) ) ||
3784 $value != self::getDefaultOption( $key ) ) {
3785 $insert_rows[] = array(
3786 'up_user' => $this->getId(),
3787 'up_property' => $key,
3788 'up_value' => $value,
3791 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3792 switch ( $wgAllowPrefChange[$key] ) {
3793 case 'local':
3794 case 'message':
3795 break;
3796 case 'semiglobal':
3797 case 'global':
3798 $extuser->setPref( $key, $value );
3803 $dbw->begin();
3804 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__ );
3805 $dbw->insert( 'user_properties', $insert_rows, __METHOD__ );
3806 $dbw->commit();
3810 * Provide an array of HTML5 attributes to put on an input element
3811 * intended for the user to enter a new password. This may include
3812 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3814 * Do *not* use this when asking the user to enter his current password!
3815 * Regardless of configuration, users may have invalid passwords for whatever
3816 * reason (e.g., they were set before requirements were tightened up).
3817 * Only use it when asking for a new password, like on account creation or
3818 * ResetPass.
3820 * Obviously, you still need to do server-side checking.
3822 * NOTE: A combination of bugs in various browsers means that this function
3823 * actually just returns array() unconditionally at the moment. May as
3824 * well keep it around for when the browser bugs get fixed, though.
3826 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
3828 * @return array Array of HTML attributes suitable for feeding to
3829 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3830 * That will potentially output invalid XHTML 1.0 Transitional, and will
3831 * get confused by the boolean attribute syntax used.)
3833 public static function passwordChangeInputAttribs() {
3834 global $wgMinimalPasswordLength;
3836 if ( $wgMinimalPasswordLength == 0 ) {
3837 return array();
3840 # Note that the pattern requirement will always be satisfied if the
3841 # input is empty, so we need required in all cases.
3843 # @todo FIXME: Bug 23769: This needs to not claim the password is required
3844 # if e-mail confirmation is being used. Since HTML5 input validation
3845 # is b0rked anyway in some browsers, just return nothing. When it's
3846 # re-enabled, fix this code to not output required for e-mail
3847 # registration.
3848 #$ret = array( 'required' );
3849 $ret = array();
3851 # We can't actually do this right now, because Opera 9.6 will print out
3852 # the entered password visibly in its error message! When other
3853 # browsers add support for this attribute, or Opera fixes its support,
3854 # we can add support with a version check to avoid doing this on Opera
3855 # versions where it will be a problem. Reported to Opera as
3856 # DSK-262266, but they don't have a public bug tracker for us to follow.
3858 if ( $wgMinimalPasswordLength > 1 ) {
3859 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3860 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3861 $wgMinimalPasswordLength );
3865 return $ret;