(bug 27046) Do not strip newlines following C++-style // comments. Prior to this...
[mediawiki.git] / includes / User.php
blobe336ea0c5f7f1cbb5a3807da69960ab6b563700d
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',
106 'hideuser',
107 'import',
108 'importupload',
109 'ipblock-exempt',
110 'markbotedits',
111 'minoredit',
112 'move',
113 'movefile',
114 'move-rootuserpages',
115 'move-subpages',
116 'nominornewtalk',
117 'noratelimit',
118 'override-export-depth',
119 'patrol',
120 'protect',
121 'proxyunbannable',
122 'purge',
123 'read',
124 'reupload',
125 'reupload-shared',
126 'rollback',
127 'selenium',
128 'sendemail',
129 'siteadmin',
130 'suppressionlog',
131 'suppressredirect',
132 'suppressrevision',
133 'trackback',
134 'undelete',
135 'unwatchedpages',
136 'upload',
137 'upload_by_url',
138 'userrights',
139 'userrights-interwiki',
140 'writeapi',
143 * String Cached results of getAllRights()
145 static $mAllRights = false;
147 /** @name Cache variables */
148 //@{
149 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
150 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
151 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
152 //@}
155 * Bool Whether the cache variables have been loaded.
157 var $mDataLoaded, $mAuthLoaded, $mOptionsLoaded;
160 * String Initialization data source if mDataLoaded==false. May be one of:
161 * - 'defaults' anonymous user initialised from class defaults
162 * - 'name' initialise from mName
163 * - 'id' initialise from mId
164 * - 'session' log in from cookies or session if possible
166 * Use the User::newFrom*() family of functions to set this.
168 var $mFrom;
171 * Lazy-initialized variables, invalidated with clearInstanceCache
173 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
174 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
175 $mLocked, $mHideName, $mOptions;
177 static $idCacheByName = array();
180 * Lightweight constructor for an anonymous user.
181 * Use the User::newFrom* factory functions for other kinds of users.
183 * @see newFromName()
184 * @see newFromId()
185 * @see newFromConfirmationCode()
186 * @see newFromSession()
187 * @see newFromRow()
189 function __construct() {
190 $this->clearInstanceCache( 'defaults' );
194 * Load the user table data for this object from the source given by mFrom.
196 function load() {
197 if ( $this->mDataLoaded ) {
198 return;
200 wfProfileIn( __METHOD__ );
202 # Set it now to avoid infinite recursion in accessors
203 $this->mDataLoaded = true;
205 switch ( $this->mFrom ) {
206 case 'defaults':
207 $this->loadDefaults();
208 break;
209 case 'name':
210 $this->mId = self::idFromName( $this->mName );
211 if ( !$this->mId ) {
212 # Nonexistent user placeholder object
213 $this->loadDefaults( $this->mName );
214 } else {
215 $this->loadFromId();
217 break;
218 case 'id':
219 $this->loadFromId();
220 break;
221 case 'session':
222 $this->loadFromSession();
223 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
224 break;
225 default:
226 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
228 wfProfileOut( __METHOD__ );
232 * Load user table data, given mId has already been set.
233 * @return Bool false if the ID does not exist, true otherwise
234 * @private
236 function loadFromId() {
237 global $wgMemc;
238 if ( $this->mId == 0 ) {
239 $this->loadDefaults();
240 return false;
243 # Try cache
244 $key = wfMemcKey( 'user', 'id', $this->mId );
245 $data = $wgMemc->get( $key );
246 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
247 # Object is expired, load from DB
248 $data = false;
251 if ( !$data ) {
252 wfDebug( "User: cache miss for user {$this->mId}\n" );
253 # Load from DB
254 if ( !$this->loadFromDatabase() ) {
255 # Can't load from ID, user is anonymous
256 return false;
258 $this->saveToCache();
259 } else {
260 wfDebug( "User: got user {$this->mId} from cache\n" );
261 # Restore from cache
262 foreach ( self::$mCacheVars as $name ) {
263 $this->$name = $data[$name];
266 return true;
270 * Save user data to the shared cache
272 function saveToCache() {
273 $this->load();
274 $this->loadGroups();
275 $this->loadOptions();
276 if ( $this->isAnon() ) {
277 // Anonymous users are uncached
278 return;
280 $data = array();
281 foreach ( self::$mCacheVars as $name ) {
282 $data[$name] = $this->$name;
284 $data['mVersion'] = MW_USER_VERSION;
285 $key = wfMemcKey( 'user', 'id', $this->mId );
286 global $wgMemc;
287 $wgMemc->set( $key, $data );
291 /** @name newFrom*() static factory methods */
292 //@{
295 * Static factory method for creation from username.
297 * This is slightly less efficient than newFromId(), so use newFromId() if
298 * you have both an ID and a name handy.
300 * @param $name String Username, validated by Title::newFromText()
301 * @param $validate String|Bool Validate username. Takes the same parameters as
302 * User::getCanonicalName(), except that true is accepted as an alias
303 * for 'valid', for BC.
305 * @return User object, or false if the username is invalid
306 * (e.g. if it contains illegal characters or is an IP address). If the
307 * username is not present in the database, the result will be a user object
308 * with a name, zero user ID and default settings.
310 static function newFromName( $name, $validate = 'valid' ) {
311 if ( $validate === true ) {
312 $validate = 'valid';
314 $name = self::getCanonicalName( $name, $validate );
315 if ( $name === false ) {
316 return false;
317 } else {
318 # Create unloaded user object
319 $u = new User;
320 $u->mName = $name;
321 $u->mFrom = 'name';
322 return $u;
327 * Static factory method for creation from a given user ID.
329 * @param $id Int Valid user ID
330 * @return User The corresponding User object
332 static function newFromId( $id ) {
333 $u = new User;
334 $u->mId = $id;
335 $u->mFrom = 'id';
336 return $u;
340 * Factory method to fetch whichever user has a given email confirmation code.
341 * This code is generated when an account is created or its e-mail address
342 * has changed.
344 * If the code is invalid or has expired, returns NULL.
346 * @param $code String Confirmation code
347 * @return User
349 static function newFromConfirmationCode( $code ) {
350 $dbr = wfGetDB( DB_SLAVE );
351 $id = $dbr->selectField( 'user', 'user_id', array(
352 'user_email_token' => md5( $code ),
353 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
354 ) );
355 if( $id !== false ) {
356 return User::newFromId( $id );
357 } else {
358 return null;
363 * Create a new user object using data from session or cookies. If the
364 * login credentials are invalid, the result is an anonymous user.
366 * @return User
368 static function newFromSession() {
369 $user = new User;
370 $user->mFrom = 'session';
371 return $user;
375 * Create a new user object from a user row.
376 * The row should have all fields from the user table in it.
377 * @param $row Array A row from the user table
378 * @return User
380 static function newFromRow( $row ) {
381 $user = new User;
382 $user->loadFromRow( $row );
383 return $user;
386 //@}
390 * Get the username corresponding to a given user ID
391 * @param $id Int User ID
392 * @return String The corresponding username
394 static function whoIs( $id ) {
395 $dbr = wfGetDB( DB_SLAVE );
396 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__ );
400 * Get the real name of a user given their user ID
402 * @param $id Int User ID
403 * @return String The corresponding user's real name
405 static function whoIsReal( $id ) {
406 $dbr = wfGetDB( DB_SLAVE );
407 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
411 * Get database id given a user name
412 * @param $name String Username
413 * @return Int|Null The corresponding user's ID, or null if user is nonexistent
415 static function idFromName( $name ) {
416 $nt = Title::makeTitleSafe( NS_USER, $name );
417 if( is_null( $nt ) ) {
418 # Illegal name
419 return null;
422 if ( isset( self::$idCacheByName[$name] ) ) {
423 return self::$idCacheByName[$name];
426 $dbr = wfGetDB( DB_SLAVE );
427 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
429 if ( $s === false ) {
430 $result = null;
431 } else {
432 $result = $s->user_id;
435 self::$idCacheByName[$name] = $result;
437 if ( count( self::$idCacheByName ) > 1000 ) {
438 self::$idCacheByName = array();
441 return $result;
445 * Reset the cache used in idFromName(). For use in tests.
447 public static function resetIdByNameCache() {
448 self::$idCacheByName = array();
452 * Does the string match an anonymous IPv4 address?
454 * This function exists for username validation, in order to reject
455 * usernames which are similar in form to IP addresses. Strings such
456 * as 300.300.300.300 will return true because it looks like an IP
457 * address, despite not being strictly valid.
459 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
460 * address because the usemod software would "cloak" anonymous IP
461 * addresses like this, if we allowed accounts like this to be created
462 * new users could get the old edits of these anonymous users.
464 * @param $name String to match
465 * @return Bool
467 static function isIP( $name ) {
468 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
472 * Is the input a valid username?
474 * Checks if the input is a valid username, we don't want an empty string,
475 * an IP address, anything that containins slashes (would mess up subpages),
476 * is longer than the maximum allowed username size or doesn't begin with
477 * a capital letter.
479 * @param $name String to match
480 * @return Bool
482 static function isValidUserName( $name ) {
483 global $wgContLang, $wgMaxNameChars;
485 if ( $name == ''
486 || User::isIP( $name )
487 || strpos( $name, '/' ) !== false
488 || strlen( $name ) > $wgMaxNameChars
489 || $name != $wgContLang->ucfirst( $name ) ) {
490 wfDebugLog( 'username', __METHOD__ .
491 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
492 return false;
495 // Ensure that the name can't be misresolved as a different title,
496 // such as with extra namespace keys at the start.
497 $parsed = Title::newFromText( $name );
498 if( is_null( $parsed )
499 || $parsed->getNamespace()
500 || strcmp( $name, $parsed->getPrefixedText() ) ) {
501 wfDebugLog( 'username', __METHOD__ .
502 ": '$name' invalid due to ambiguous prefixes" );
503 return false;
506 // Check an additional blacklist of troublemaker characters.
507 // Should these be merged into the title char list?
508 $unicodeBlacklist = '/[' .
509 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
510 '\x{00a0}' . # non-breaking space
511 '\x{2000}-\x{200f}' . # various whitespace
512 '\x{2028}-\x{202f}' . # breaks and control chars
513 '\x{3000}' . # ideographic space
514 '\x{e000}-\x{f8ff}' . # private use
515 ']/u';
516 if( preg_match( $unicodeBlacklist, $name ) ) {
517 wfDebugLog( 'username', __METHOD__ .
518 ": '$name' invalid due to blacklisted characters" );
519 return false;
522 return true;
526 * Usernames which fail to pass this function will be blocked
527 * from user login and new account registrations, but may be used
528 * internally by batch processes.
530 * If an account already exists in this form, login will be blocked
531 * by a failure to pass this function.
533 * @param $name String to match
534 * @return Bool
536 static function isUsableName( $name ) {
537 global $wgReservedUsernames;
538 // Must be a valid username, obviously ;)
539 if ( !self::isValidUserName( $name ) ) {
540 return false;
543 static $reservedUsernames = false;
544 if ( !$reservedUsernames ) {
545 $reservedUsernames = $wgReservedUsernames;
546 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
549 // Certain names may be reserved for batch processes.
550 foreach ( $reservedUsernames as $reserved ) {
551 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
552 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
554 if ( $reserved == $name ) {
555 return false;
558 return true;
562 * Usernames which fail to pass this function will be blocked
563 * from new account registrations, but may be used internally
564 * either by batch processes or by user accounts which have
565 * already been created.
567 * Additional blacklisting may be added here rather than in
568 * isValidUserName() to avoid disrupting existing accounts.
570 * @param $name String to match
571 * @return Bool
573 static function isCreatableName( $name ) {
574 global $wgInvalidUsernameCharacters;
576 // Ensure that the username isn't longer than 235 bytes, so that
577 // (at least for the builtin skins) user javascript and css files
578 // will work. (bug 23080)
579 if( strlen( $name ) > 235 ) {
580 wfDebugLog( 'username', __METHOD__ .
581 ": '$name' invalid due to length" );
582 return false;
585 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
586 wfDebugLog( 'username', __METHOD__ .
587 ": '$name' invalid due to wgInvalidUsernameCharacters" );
588 return false;
591 return self::isUsableName( $name );
595 * Is the input a valid password for this user?
597 * @param $password String Desired password
598 * @return Bool
600 function isValidPassword( $password ) {
601 //simple boolean wrapper for getPasswordValidity
602 return $this->getPasswordValidity( $password ) === true;
606 * Given unvalidated password input, return error message on failure.
608 * @param $password String Desired password
609 * @return mixed: true on success, string or array of error message on failure
611 function getPasswordValidity( $password ) {
612 global $wgMinimalPasswordLength, $wgContLang;
614 static $blockedLogins = array(
615 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
616 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
619 $result = false; //init $result to false for the internal checks
621 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
622 return $result;
624 if ( $result === false ) {
625 if( strlen( $password ) < $wgMinimalPasswordLength ) {
626 return 'passwordtooshort';
627 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
628 return 'password-name-match';
629 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
630 return 'password-login-forbidden';
631 } else {
632 //it seems weird returning true here, but this is because of the
633 //initialization of $result to false above. If the hook is never run or it
634 //doesn't modify $result, then we will likely get down into this if with
635 //a valid password.
636 return true;
638 } elseif( $result === true ) {
639 return true;
640 } else {
641 return $result; //the isValidPassword hook set a string $result and returned true
646 * Does a string look like an e-mail address?
648 * This validates an email address using an HTML5 specification found at:
649 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
650 * Which as of 2011-01-24 says:
652 * A valid e-mail address is a string that matches the ABNF production
653 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
654 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
655 * 3.5.
657 * This function is an implementation of the specification as requested in
658 * bug 22449.
660 * Client-side forms will use the same standard validation rules via JS or
661 * HTML 5 validation; additional restrictions can be enforced server-side
662 * by extensions via the 'isValidEmailAddr' hook.
664 * Note that this validation doesn't 100% match RFC 2822, but is believed
665 * to be liberal enough for wide use. Some invalid addresses will still
666 * pass validation here.
668 * @param $addr String E-mail address
669 * @return Bool
671 public static function isValidEmailAddr( $addr ) {
672 $result = null;
673 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
674 return $result;
677 // Please note strings below are enclosed in brackets [], this make the
678 // hyphen "-" a range indicator. Hence it is double backslashed below.
679 // See bug 26948
680 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~" ;
681 $rfc1034_ldh_str = "a-z0-9\\-" ;
683 $HTML5_email_regexp = "/
684 ^ # start of string
685 [$rfc5322_atext\\.]+ # user part which is liberal :p
686 @ # 'apostrophe'
687 [$rfc1034_ldh_str]+ # First domain part
688 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
689 $ # End of string
690 /ix" ; // case Insensitive, eXtended
692 return (bool) preg_match( $HTML5_email_regexp, $addr );
696 * Given unvalidated user input, return a canonical username, or false if
697 * the username is invalid.
698 * @param $name String User input
699 * @param $validate String|Bool type of validation to use:
700 * - false No validation
701 * - 'valid' Valid for batch processes
702 * - 'usable' Valid for batch processes and login
703 * - 'creatable' Valid for batch processes, login and account creation
705 static function getCanonicalName( $name, $validate = 'valid' ) {
706 # Force usernames to capital
707 global $wgContLang;
708 $name = $wgContLang->ucfirst( $name );
710 # Reject names containing '#'; these will be cleaned up
711 # with title normalisation, but then it's too late to
712 # check elsewhere
713 if( strpos( $name, '#' ) !== false )
714 return false;
716 # Clean up name according to title rules
717 $t = ( $validate === 'valid' ) ?
718 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
719 # Check for invalid titles
720 if( is_null( $t ) ) {
721 return false;
724 # Reject various classes of invalid names
725 global $wgAuth;
726 $name = $wgAuth->getCanonicalName( $t->getText() );
728 switch ( $validate ) {
729 case false:
730 break;
731 case 'valid':
732 if ( !User::isValidUserName( $name ) ) {
733 $name = false;
735 break;
736 case 'usable':
737 if ( !User::isUsableName( $name ) ) {
738 $name = false;
740 break;
741 case 'creatable':
742 if ( !User::isCreatableName( $name ) ) {
743 $name = false;
745 break;
746 default:
747 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
749 return $name;
753 * Count the number of edits of a user
754 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
756 * @param $uid Int User ID to check
757 * @return Int the user's edit count
759 static function edits( $uid ) {
760 wfProfileIn( __METHOD__ );
761 $dbr = wfGetDB( DB_SLAVE );
762 // check if the user_editcount field has been initialized
763 $field = $dbr->selectField(
764 'user', 'user_editcount',
765 array( 'user_id' => $uid ),
766 __METHOD__
769 if( $field === null ) { // it has not been initialized. do so.
770 $dbw = wfGetDB( DB_MASTER );
771 $count = $dbr->selectField(
772 'revision', 'count(*)',
773 array( 'rev_user' => $uid ),
774 __METHOD__
776 $dbw->update(
777 'user',
778 array( 'user_editcount' => $count ),
779 array( 'user_id' => $uid ),
780 __METHOD__
782 } else {
783 $count = $field;
785 wfProfileOut( __METHOD__ );
786 return $count;
790 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
791 * @todo hash random numbers to improve security, like generateToken()
793 * @return String new random password
795 static function randomPassword() {
796 global $wgMinimalPasswordLength;
797 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
798 $l = strlen( $pwchars ) - 1;
800 $pwlength = max( 7, $wgMinimalPasswordLength );
801 $digit = mt_rand( 0, $pwlength - 1 );
802 $np = '';
803 for ( $i = 0; $i < $pwlength; $i++ ) {
804 $np .= $i == $digit ? chr( mt_rand( 48, 57 ) ) : $pwchars{ mt_rand( 0, $l ) };
806 return $np;
810 * Set cached properties to default.
812 * @note This no longer clears uncached lazy-initialised properties;
813 * the constructor does that instead.
814 * @private
816 function loadDefaults( $name = false ) {
817 wfProfileIn( __METHOD__ );
819 global $wgRequest;
821 $this->mId = 0;
822 $this->mName = $name;
823 $this->mRealName = '';
824 $this->mPassword = $this->mNewpassword = '';
825 $this->mNewpassTime = null;
826 $this->mEmail = '';
827 $this->mOptionOverrides = null;
828 $this->mOptionsLoaded = false;
830 if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
831 $this->mTouched = wfTimestamp( TS_MW, $wgRequest->getCookie( 'LoggedOut' ) );
832 } else {
833 $this->mTouched = '0'; # Allow any pages to be cached
836 $this->setToken(); # Random
837 $this->mEmailAuthenticated = null;
838 $this->mEmailToken = '';
839 $this->mEmailTokenExpires = null;
840 $this->mRegistration = wfTimestamp( TS_MW );
841 $this->mGroups = array();
843 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
845 wfProfileOut( __METHOD__ );
849 * Load user data from the session or login cookie. If there are no valid
850 * credentials, initialises the user as an anonymous user.
851 * @return Bool True if the user is logged in, false otherwise.
853 private function loadFromSession() {
854 global $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
856 $result = null;
857 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
858 if ( $result !== null ) {
859 return $result;
862 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
863 $extUser = ExternalUser::newFromCookie();
864 if ( $extUser ) {
865 # TODO: Automatically create the user here (or probably a bit
866 # lower down, in fact)
870 if ( $wgRequest->getCookie( 'UserID' ) !== null ) {
871 $sId = intval( $wgRequest->getCookie( 'UserID' ) );
872 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
873 $this->loadDefaults(); // Possible collision!
874 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
875 cookie user ID ($sId) don't match!" );
876 return false;
878 $_SESSION['wsUserID'] = $sId;
879 } else if ( isset( $_SESSION['wsUserID'] ) ) {
880 if ( $_SESSION['wsUserID'] != 0 ) {
881 $sId = $_SESSION['wsUserID'];
882 } else {
883 $this->loadDefaults();
884 return false;
886 } else {
887 $this->loadDefaults();
888 return false;
891 if ( isset( $_SESSION['wsUserName'] ) ) {
892 $sName = $_SESSION['wsUserName'];
893 } else if ( $wgRequest->getCookie('UserName') !== null ) {
894 $sName = $wgRequest->getCookie('UserName');
895 $_SESSION['wsUserName'] = $sName;
896 } else {
897 $this->loadDefaults();
898 return false;
901 $this->mId = $sId;
902 if ( !$this->loadFromId() ) {
903 # Not a valid ID, loadFromId has switched the object to anon for us
904 return false;
907 global $wgBlockDisablesLogin;
908 if( $wgBlockDisablesLogin && $this->isBlocked() ) {
909 # User blocked and we've disabled blocked user logins
910 $this->loadDefaults();
911 return false;
914 if ( isset( $_SESSION['wsToken'] ) ) {
915 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
916 $from = 'session';
917 } else if ( $wgRequest->getCookie( 'Token' ) !== null ) {
918 $passwordCorrect = $this->mToken == $wgRequest->getCookie( 'Token' );
919 $from = 'cookie';
920 } else {
921 # No session or persistent login cookie
922 $this->loadDefaults();
923 return false;
926 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
927 $_SESSION['wsToken'] = $this->mToken;
928 wfDebug( "User: logged in from $from\n" );
929 return true;
930 } else {
931 # Invalid credentials
932 wfDebug( "User: can't log in from $from, invalid credentials\n" );
933 $this->loadDefaults();
934 return false;
939 * Load user and user_group data from the database.
940 * $this::mId must be set, this is how the user is identified.
942 * @return Bool True if the user exists, false if the user is anonymous
943 * @private
945 function loadFromDatabase() {
946 # Paranoia
947 $this->mId = intval( $this->mId );
949 /** Anonymous user */
950 if( !$this->mId ) {
951 $this->loadDefaults();
952 return false;
955 $dbr = wfGetDB( DB_MASTER );
956 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
958 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
960 if ( $s !== false ) {
961 # Initialise user table data
962 $this->loadFromRow( $s );
963 $this->mGroups = null; // deferred
964 $this->getEditCount(); // revalidation for nulls
965 return true;
966 } else {
967 # Invalid user_id
968 $this->mId = 0;
969 $this->loadDefaults();
970 return false;
975 * Initialize this object from a row from the user table.
977 * @param $row Array Row from the user table to load.
979 function loadFromRow( $row ) {
980 $this->mDataLoaded = true;
982 if ( isset( $row->user_id ) ) {
983 $this->mId = intval( $row->user_id );
985 $this->mName = $row->user_name;
986 $this->mRealName = $row->user_real_name;
987 $this->mPassword = $row->user_password;
988 $this->mNewpassword = $row->user_newpassword;
989 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
990 $this->mEmail = $row->user_email;
991 $this->decodeOptions( $row->user_options );
992 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
993 $this->mToken = $row->user_token;
994 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
995 $this->mEmailToken = $row->user_email_token;
996 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
997 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
998 $this->mEditCount = $row->user_editcount;
1002 * Load the groups from the database if they aren't already loaded.
1003 * @private
1005 function loadGroups() {
1006 if ( is_null( $this->mGroups ) ) {
1007 $dbr = wfGetDB( DB_MASTER );
1008 $res = $dbr->select( 'user_groups',
1009 array( 'ug_group' ),
1010 array( 'ug_user' => $this->mId ),
1011 __METHOD__ );
1012 $this->mGroups = array();
1013 foreach ( $res as $row ) {
1014 $this->mGroups[] = $row->ug_group;
1020 * Clear various cached data stored in this object.
1021 * @param $reloadFrom String Reload user and user_groups table data from a
1022 * given source. May be "name", "id", "defaults", "session", or false for
1023 * no reload.
1025 function clearInstanceCache( $reloadFrom = false ) {
1026 $this->mNewtalk = -1;
1027 $this->mDatePreference = null;
1028 $this->mBlockedby = -1; # Unset
1029 $this->mHash = false;
1030 $this->mSkin = null;
1031 $this->mRights = null;
1032 $this->mEffectiveGroups = null;
1033 $this->mOptions = null;
1035 if ( $reloadFrom ) {
1036 $this->mDataLoaded = false;
1037 $this->mFrom = $reloadFrom;
1042 * Combine the language default options with any site-specific options
1043 * and add the default language variants.
1045 * @return Array of String options
1047 static function getDefaultOptions() {
1048 global $wgNamespacesToBeSearchedDefault;
1050 * Site defaults will override the global/language defaults
1052 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1053 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
1056 * default language setting
1058 $variant = $wgContLang->getDefaultVariant();
1059 $defOpt['variant'] = $variant;
1060 $defOpt['language'] = $variant;
1061 foreach( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1062 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1064 $defOpt['skin'] = $wgDefaultSkin;
1066 return $defOpt;
1070 * Get a given default option value.
1072 * @param $opt String Name of option to retrieve
1073 * @return String Default option value
1075 public static function getDefaultOption( $opt ) {
1076 $defOpts = self::getDefaultOptions();
1077 if( isset( $defOpts[$opt] ) ) {
1078 return $defOpts[$opt];
1079 } else {
1080 return null;
1086 * Get blocking information
1087 * @private
1088 * @param $bFromSlave Bool Whether to check the slave database first. To
1089 * improve performance, non-critical checks are done
1090 * against slaves. Check when actually saving should be
1091 * done against master.
1093 function getBlockedStatus( $bFromSlave = true ) {
1094 global $wgProxyWhitelist, $wgUser;
1096 if ( -1 != $this->mBlockedby ) {
1097 return;
1100 wfProfileIn( __METHOD__ );
1101 wfDebug( __METHOD__.": checking...\n" );
1103 // Initialize data...
1104 // Otherwise something ends up stomping on $this->mBlockedby when
1105 // things get lazy-loaded later, causing false positive block hits
1106 // due to -1 !== 0. Probably session-related... Nothing should be
1107 // overwriting mBlockedby, surely?
1108 $this->load();
1110 $this->mBlockedby = 0;
1111 $this->mHideName = 0;
1112 $this->mAllowUsertalk = 0;
1114 # Check if we are looking at an IP or a logged-in user
1115 if ( $this->isIP( $this->getName() ) ) {
1116 $ip = $this->getName();
1117 } else {
1118 # Check if we are looking at the current user
1119 # If we don't, and the user is logged in, we don't know about
1120 # his IP / autoblock status, so ignore autoblock of current user's IP
1121 if ( $this->getID() != $wgUser->getID() ) {
1122 $ip = '';
1123 } else {
1124 # Get IP of current user
1125 $ip = wfGetIP();
1129 if ( $this->isAllowed( 'ipblock-exempt' ) ) {
1130 # Exempt from all types of IP-block
1131 $ip = '';
1134 # User/IP blocking
1135 $this->mBlock = new Block();
1136 $this->mBlock->fromMaster( !$bFromSlave );
1137 if ( $this->mBlock->load( $ip , $this->mId ) ) {
1138 wfDebug( __METHOD__ . ": Found block.\n" );
1139 $this->mBlockedby = $this->mBlock->mBy;
1140 if( $this->mBlockedby == 0 )
1141 $this->mBlockedby = $this->mBlock->mByName;
1142 $this->mBlockreason = $this->mBlock->mReason;
1143 $this->mHideName = $this->mBlock->mHideName;
1144 $this->mAllowUsertalk = $this->mBlock->mAllowUsertalk;
1145 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1146 $this->spreadBlock();
1148 } else {
1149 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1150 // apply to users. Note that the existence of $this->mBlock is not used to
1151 // check for edit blocks, $this->mBlockedby is instead.
1154 # Proxy blocking
1155 if ( !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1156 # Local list
1157 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1158 $this->mBlockedby = wfMsg( 'proxyblocker' );
1159 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1162 # DNSBL
1163 if ( !$this->mBlockedby && !$this->getID() ) {
1164 if ( $this->isDnsBlacklisted( $ip ) ) {
1165 $this->mBlockedby = wfMsg( 'sorbs' );
1166 $this->mBlockreason = wfMsg( 'sorbsreason' );
1171 # Extensions
1172 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1174 wfProfileOut( __METHOD__ );
1178 * Whether the given IP is in a DNS blacklist.
1180 * @param $ip String IP to check
1181 * @param $checkWhitelist Bool: whether to check the whitelist first
1182 * @return Bool True if blacklisted.
1184 function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1185 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1186 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1188 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1189 return false;
1191 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1192 return false;
1194 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1195 return $this->inDnsBlacklist( $ip, $urls );
1199 * Whether the given IP is in a given DNS blacklist.
1201 * @param $ip String IP to check
1202 * @param $bases String|Array of Strings: URL of the DNS blacklist
1203 * @return Bool True if blacklisted.
1205 function inDnsBlacklist( $ip, $bases ) {
1206 wfProfileIn( __METHOD__ );
1208 $found = false;
1209 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1210 if( IP::isIPv4( $ip ) ) {
1211 # Reverse IP, bug 21255
1212 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1214 foreach( (array)$bases as $base ) {
1215 # Make hostname
1216 $host = "$ipReversed.$base";
1218 # Send query
1219 $ipList = gethostbynamel( $host );
1221 if( $ipList ) {
1222 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1223 $found = true;
1224 break;
1225 } else {
1226 wfDebug( "Requested $host, not found in $base.\n" );
1231 wfProfileOut( __METHOD__ );
1232 return $found;
1236 * Is this user subject to rate limiting?
1238 * @return Bool True if rate limited
1240 public function isPingLimitable() {
1241 global $wgRateLimitsExcludedGroups;
1242 global $wgRateLimitsExcludedIPs;
1243 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1244 // Deprecated, but kept for backwards-compatibility config
1245 return false;
1247 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1248 // No other good way currently to disable rate limits
1249 // for specific IPs. :P
1250 // But this is a crappy hack and should die.
1251 return false;
1253 return !$this->isAllowed('noratelimit');
1257 * Primitive rate limits: enforce maximum actions per time period
1258 * to put a brake on flooding.
1260 * @note When using a shared cache like memcached, IP-address
1261 * last-hit counters will be shared across wikis.
1263 * @param $action String Action to enforce; 'edit' if unspecified
1264 * @return Bool True if a rate limiter was tripped
1266 function pingLimiter( $action = 'edit' ) {
1267 # Call the 'PingLimiter' hook
1268 $result = false;
1269 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1270 return $result;
1273 global $wgRateLimits;
1274 if( !isset( $wgRateLimits[$action] ) ) {
1275 return false;
1278 # Some groups shouldn't trigger the ping limiter, ever
1279 if( !$this->isPingLimitable() )
1280 return false;
1282 global $wgMemc, $wgRateLimitLog;
1283 wfProfileIn( __METHOD__ );
1285 $limits = $wgRateLimits[$action];
1286 $keys = array();
1287 $id = $this->getId();
1288 $ip = wfGetIP();
1289 $userLimit = false;
1291 if( isset( $limits['anon'] ) && $id == 0 ) {
1292 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1295 if( isset( $limits['user'] ) && $id != 0 ) {
1296 $userLimit = $limits['user'];
1298 if( $this->isNewbie() ) {
1299 if( isset( $limits['newbie'] ) && $id != 0 ) {
1300 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1302 if( isset( $limits['ip'] ) ) {
1303 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1305 $matches = array();
1306 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1307 $subnet = $matches[1];
1308 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1311 // Check for group-specific permissions
1312 // If more than one group applies, use the group with the highest limit
1313 foreach ( $this->getGroups() as $group ) {
1314 if ( isset( $limits[$group] ) ) {
1315 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1316 $userLimit = $limits[$group];
1320 // Set the user limit key
1321 if ( $userLimit !== false ) {
1322 wfDebug( __METHOD__ . ": effective user limit: $userLimit\n" );
1323 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1326 $triggered = false;
1327 foreach( $keys as $key => $limit ) {
1328 list( $max, $period ) = $limit;
1329 $summary = "(limit $max in {$period}s)";
1330 $count = $wgMemc->get( $key );
1331 // Already pinged?
1332 if( $count ) {
1333 if( $count > $max ) {
1334 wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
1335 if( $wgRateLimitLog ) {
1336 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1338 $triggered = true;
1339 } else {
1340 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1342 } else {
1343 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1344 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1346 $wgMemc->incr( $key );
1349 wfProfileOut( __METHOD__ );
1350 return $triggered;
1354 * Check if user is blocked
1356 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1357 * @return Bool True if blocked, false otherwise
1359 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1360 $this->getBlockedStatus( $bFromSlave );
1361 return $this->mBlockedby !== 0;
1365 * Check if user is blocked from editing a particular article
1367 * @param $title Title to check
1368 * @param $bFromSlave Bool whether to check the slave database instead of the master
1369 * @return Bool
1371 function isBlockedFrom( $title, $bFromSlave = false ) {
1372 global $wgBlockAllowsUTEdit;
1373 wfProfileIn( __METHOD__ );
1375 $blocked = $this->isBlocked( $bFromSlave );
1376 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1377 # If a user's name is suppressed, they cannot make edits anywhere
1378 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1379 $title->getNamespace() == NS_USER_TALK ) {
1380 $blocked = false;
1381 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1384 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1386 wfProfileOut( __METHOD__ );
1387 return $blocked;
1391 * If user is blocked, return the name of the user who placed the block
1392 * @return String name of blocker
1394 function blockedBy() {
1395 $this->getBlockedStatus();
1396 return $this->mBlockedby;
1400 * If user is blocked, return the specified reason for the block
1401 * @return String Blocking reason
1403 function blockedFor() {
1404 $this->getBlockedStatus();
1405 return $this->mBlockreason;
1409 * If user is blocked, return the ID for the block
1410 * @return Int Block ID
1412 function getBlockId() {
1413 $this->getBlockedStatus();
1414 return ( $this->mBlock ? $this->mBlock->mId : false );
1418 * Check if user is blocked on all wikis.
1419 * Do not use for actual edit permission checks!
1420 * This is intented for quick UI checks.
1422 * @param $ip String IP address, uses current client if none given
1423 * @return Bool True if blocked, false otherwise
1425 function isBlockedGlobally( $ip = '' ) {
1426 if( $this->mBlockedGlobally !== null ) {
1427 return $this->mBlockedGlobally;
1429 // User is already an IP?
1430 if( IP::isIPAddress( $this->getName() ) ) {
1431 $ip = $this->getName();
1432 } else if( !$ip ) {
1433 $ip = wfGetIP();
1435 $blocked = false;
1436 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1437 $this->mBlockedGlobally = (bool)$blocked;
1438 return $this->mBlockedGlobally;
1442 * Check if user account is locked
1444 * @return Bool True if locked, false otherwise
1446 function isLocked() {
1447 if( $this->mLocked !== null ) {
1448 return $this->mLocked;
1450 global $wgAuth;
1451 $authUser = $wgAuth->getUserInstance( $this );
1452 $this->mLocked = (bool)$authUser->isLocked();
1453 return $this->mLocked;
1457 * Check if user account is hidden
1459 * @return Bool True if hidden, false otherwise
1461 function isHidden() {
1462 if( $this->mHideName !== null ) {
1463 return $this->mHideName;
1465 $this->getBlockedStatus();
1466 if( !$this->mHideName ) {
1467 global $wgAuth;
1468 $authUser = $wgAuth->getUserInstance( $this );
1469 $this->mHideName = (bool)$authUser->isHidden();
1471 return $this->mHideName;
1475 * Get the user's ID.
1476 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1478 function getId() {
1479 if( $this->mId === null and $this->mName !== null
1480 and User::isIP( $this->mName ) ) {
1481 // Special case, we know the user is anonymous
1482 return 0;
1483 } elseif( $this->mId === null ) {
1484 // Don't load if this was initialized from an ID
1485 $this->load();
1487 return $this->mId;
1491 * Set the user and reload all fields according to a given ID
1492 * @param $v Int User ID to reload
1494 function setId( $v ) {
1495 $this->mId = $v;
1496 $this->clearInstanceCache( 'id' );
1500 * Get the user name, or the IP of an anonymous user
1501 * @return String User's name or IP address
1503 function getName() {
1504 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1505 # Special case optimisation
1506 return $this->mName;
1507 } else {
1508 $this->load();
1509 if ( $this->mName === false ) {
1510 # Clean up IPs
1511 $this->mName = IP::sanitizeIP( wfGetIP() );
1513 return $this->mName;
1518 * Set the user name.
1520 * This does not reload fields from the database according to the given
1521 * name. Rather, it is used to create a temporary "nonexistent user" for
1522 * later addition to the database. It can also be used to set the IP
1523 * address for an anonymous user to something other than the current
1524 * remote IP.
1526 * @note User::newFromName() has rougly the same function, when the named user
1527 * does not exist.
1528 * @param $str String New user name to set
1530 function setName( $str ) {
1531 $this->load();
1532 $this->mName = $str;
1536 * Get the user's name escaped by underscores.
1537 * @return String Username escaped by underscores.
1539 function getTitleKey() {
1540 return str_replace( ' ', '_', $this->getName() );
1544 * Check if the user has new messages.
1545 * @return Bool True if the user has new messages
1547 function getNewtalk() {
1548 $this->load();
1550 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1551 if( $this->mNewtalk === -1 ) {
1552 $this->mNewtalk = false; # reset talk page status
1554 # Check memcached separately for anons, who have no
1555 # entire User object stored in there.
1556 if( !$this->mId ) {
1557 global $wgMemc;
1558 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1559 $newtalk = $wgMemc->get( $key );
1560 if( strval( $newtalk ) !== '' ) {
1561 $this->mNewtalk = (bool)$newtalk;
1562 } else {
1563 // Since we are caching this, make sure it is up to date by getting it
1564 // from the master
1565 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1566 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1568 } else {
1569 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1573 return (bool)$this->mNewtalk;
1577 * Return the talk page(s) this user has new messages on.
1578 * @return Array of String page URLs
1580 function getNewMessageLinks() {
1581 $talks = array();
1582 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1583 return $talks;
1585 if( !$this->getNewtalk() )
1586 return array();
1587 $up = $this->getUserPage();
1588 $utp = $up->getTalkPage();
1589 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1593 * Internal uncached check for new messages
1595 * @see getNewtalk()
1596 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1597 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1598 * @param $fromMaster Bool true to fetch from the master, false for a slave
1599 * @return Bool True if the user has new messages
1600 * @private
1602 function checkNewtalk( $field, $id, $fromMaster = false ) {
1603 if ( $fromMaster ) {
1604 $db = wfGetDB( DB_MASTER );
1605 } else {
1606 $db = wfGetDB( DB_SLAVE );
1608 $ok = $db->selectField( 'user_newtalk', $field,
1609 array( $field => $id ), __METHOD__ );
1610 return $ok !== false;
1614 * Add or update the new messages flag
1615 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1616 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1617 * @return Bool True if successful, false otherwise
1618 * @private
1620 function updateNewtalk( $field, $id ) {
1621 $dbw = wfGetDB( DB_MASTER );
1622 $dbw->insert( 'user_newtalk',
1623 array( $field => $id ),
1624 __METHOD__,
1625 'IGNORE' );
1626 if ( $dbw->affectedRows() ) {
1627 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
1628 return true;
1629 } else {
1630 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
1631 return false;
1636 * Clear the new messages flag for the given user
1637 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1638 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1639 * @return Bool True if successful, false otherwise
1640 * @private
1642 function deleteNewtalk( $field, $id ) {
1643 $dbw = wfGetDB( DB_MASTER );
1644 $dbw->delete( 'user_newtalk',
1645 array( $field => $id ),
1646 __METHOD__ );
1647 if ( $dbw->affectedRows() ) {
1648 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
1649 return true;
1650 } else {
1651 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
1652 return false;
1657 * Update the 'You have new messages!' status.
1658 * @param $val Bool Whether the user has new messages
1660 function setNewtalk( $val ) {
1661 if( wfReadOnly() ) {
1662 return;
1665 $this->load();
1666 $this->mNewtalk = $val;
1668 if( $this->isAnon() ) {
1669 $field = 'user_ip';
1670 $id = $this->getName();
1671 } else {
1672 $field = 'user_id';
1673 $id = $this->getId();
1675 global $wgMemc;
1677 if( $val ) {
1678 $changed = $this->updateNewtalk( $field, $id );
1679 } else {
1680 $changed = $this->deleteNewtalk( $field, $id );
1683 if( $this->isAnon() ) {
1684 // Anons have a separate memcached space, since
1685 // user records aren't kept for them.
1686 $key = wfMemcKey( 'newtalk', 'ip', $id );
1687 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1689 if ( $changed ) {
1690 $this->invalidateCache();
1695 * Generate a current or new-future timestamp to be stored in the
1696 * user_touched field when we update things.
1697 * @return String Timestamp in TS_MW format
1699 private static function newTouchedTimestamp() {
1700 global $wgClockSkewFudge;
1701 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1705 * Clear user data from memcached.
1706 * Use after applying fun updates to the database; caller's
1707 * responsibility to update user_touched if appropriate.
1709 * Called implicitly from invalidateCache() and saveSettings().
1711 private function clearSharedCache() {
1712 $this->load();
1713 if( $this->mId ) {
1714 global $wgMemc;
1715 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1720 * Immediately touch the user data cache for this account.
1721 * Updates user_touched field, and removes account data from memcached
1722 * for reload on the next hit.
1724 function invalidateCache() {
1725 if( wfReadOnly() ) {
1726 return;
1728 $this->load();
1729 if( $this->mId ) {
1730 $this->mTouched = self::newTouchedTimestamp();
1732 $dbw = wfGetDB( DB_MASTER );
1733 $dbw->update( 'user',
1734 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1735 array( 'user_id' => $this->mId ),
1736 __METHOD__ );
1738 $this->clearSharedCache();
1743 * Validate the cache for this account.
1744 * @param $timestamp String A timestamp in TS_MW format
1746 function validateCache( $timestamp ) {
1747 $this->load();
1748 return ( $timestamp >= $this->mTouched );
1752 * Get the user touched timestamp
1753 * @return String timestamp
1755 function getTouched() {
1756 $this->load();
1757 return $this->mTouched;
1761 * Set the password and reset the random token.
1762 * Calls through to authentication plugin if necessary;
1763 * will have no effect if the auth plugin refuses to
1764 * pass the change through or if the legal password
1765 * checks fail.
1767 * As a special case, setting the password to null
1768 * wipes it, so the account cannot be logged in until
1769 * a new password is set, for instance via e-mail.
1771 * @param $str String New password to set
1772 * @throws PasswordError on failure
1774 function setPassword( $str ) {
1775 global $wgAuth;
1777 if( $str !== null ) {
1778 if( !$wgAuth->allowPasswordChange() ) {
1779 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1782 if( !$this->isValidPassword( $str ) ) {
1783 global $wgMinimalPasswordLength;
1784 $valid = $this->getPasswordValidity( $str );
1785 if ( is_array( $valid ) ) {
1786 $message = array_shift( $valid );
1787 $params = $valid;
1788 } else {
1789 $message = $valid;
1790 $params = array( $wgMinimalPasswordLength );
1792 throw new PasswordError( wfMsgExt( $message, array( 'parsemag' ), $params ) );
1796 if( !$wgAuth->setPassword( $this, $str ) ) {
1797 throw new PasswordError( wfMsg( 'externaldberror' ) );
1800 $this->setInternalPassword( $str );
1802 return true;
1806 * Set the password and reset the random token unconditionally.
1808 * @param $str String New password to set
1810 function setInternalPassword( $str ) {
1811 $this->load();
1812 $this->setToken();
1814 if( $str === null ) {
1815 // Save an invalid hash...
1816 $this->mPassword = '';
1817 } else {
1818 $this->mPassword = self::crypt( $str );
1820 $this->mNewpassword = '';
1821 $this->mNewpassTime = null;
1825 * Get the user's current token.
1826 * @return String Token
1828 function getToken() {
1829 $this->load();
1830 return $this->mToken;
1834 * Set the random token (used for persistent authentication)
1835 * Called from loadDefaults() among other places.
1837 * @param $token String If specified, set the token to this value
1838 * @private
1840 function setToken( $token = false ) {
1841 global $wgSecretKey, $wgProxyKey;
1842 $this->load();
1843 if ( !$token ) {
1844 if ( $wgSecretKey ) {
1845 $key = $wgSecretKey;
1846 } elseif ( $wgProxyKey ) {
1847 $key = $wgProxyKey;
1848 } else {
1849 $key = microtime();
1851 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1852 } else {
1853 $this->mToken = $token;
1858 * Set the cookie password
1860 * @param $str String New cookie password
1861 * @private
1863 function setCookiePassword( $str ) {
1864 $this->load();
1865 $this->mCookiePassword = md5( $str );
1869 * Set the password for a password reminder or new account email
1871 * @param $str String New password to set
1872 * @param $throttle Bool If true, reset the throttle timestamp to the present
1874 function setNewpassword( $str, $throttle = true ) {
1875 $this->load();
1876 $this->mNewpassword = self::crypt( $str );
1877 if ( $throttle ) {
1878 $this->mNewpassTime = wfTimestampNow();
1883 * Has password reminder email been sent within the last
1884 * $wgPasswordReminderResendTime hours?
1885 * @return Bool
1887 function isPasswordReminderThrottled() {
1888 global $wgPasswordReminderResendTime;
1889 $this->load();
1890 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1891 return false;
1893 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1894 return time() < $expiry;
1898 * Get the user's e-mail address
1899 * @return String User's email address
1901 function getEmail() {
1902 $this->load();
1903 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1904 return $this->mEmail;
1908 * Get the timestamp of the user's e-mail authentication
1909 * @return String TS_MW timestamp
1911 function getEmailAuthenticationTimestamp() {
1912 $this->load();
1913 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1914 return $this->mEmailAuthenticated;
1918 * Set the user's e-mail address
1919 * @param $str String New e-mail address
1921 function setEmail( $str ) {
1922 $this->load();
1923 $this->mEmail = $str;
1924 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1928 * Get the user's real name
1929 * @return String User's real name
1931 function getRealName() {
1932 $this->load();
1933 return $this->mRealName;
1937 * Set the user's real name
1938 * @param $str String New real name
1940 function setRealName( $str ) {
1941 $this->load();
1942 $this->mRealName = $str;
1946 * Get the user's current setting for a given option.
1948 * @param $oname String The option to check
1949 * @param $defaultOverride String A default value returned if the option does not exist
1950 * @return String User's current value for the option
1951 * @see getBoolOption()
1952 * @see getIntOption()
1954 function getOption( $oname, $defaultOverride = null ) {
1955 $this->loadOptions();
1957 if ( is_null( $this->mOptions ) ) {
1958 if($defaultOverride != '') {
1959 return $defaultOverride;
1961 $this->mOptions = User::getDefaultOptions();
1964 if ( array_key_exists( $oname, $this->mOptions ) ) {
1965 return $this->mOptions[$oname];
1966 } else {
1967 return $defaultOverride;
1972 * Get all user's options
1974 * @return array
1976 public function getOptions() {
1977 $this->loadOptions();
1978 return $this->mOptions;
1982 * Get the user's current setting for a given option, as a boolean value.
1984 * @param $oname String The option to check
1985 * @return Bool User's current value for the option
1986 * @see getOption()
1988 function getBoolOption( $oname ) {
1989 return (bool)$this->getOption( $oname );
1994 * Get the user's current setting for a given option, as a boolean value.
1996 * @param $oname String The option to check
1997 * @param $defaultOverride Int A default value returned if the option does not exist
1998 * @return Int User's current value for the option
1999 * @see getOption()
2001 function getIntOption( $oname, $defaultOverride=0 ) {
2002 $val = $this->getOption( $oname );
2003 if( $val == '' ) {
2004 $val = $defaultOverride;
2006 return intval( $val );
2010 * Set the given option for a user.
2012 * @param $oname String The option to set
2013 * @param $val mixed New value to set
2015 function setOption( $oname, $val ) {
2016 $this->load();
2017 $this->loadOptions();
2019 if ( $oname == 'skin' ) {
2020 # Clear cached skin, so the new one displays immediately in Special:Preferences
2021 $this->mSkin = null;
2024 // Explicitly NULL values should refer to defaults
2025 global $wgDefaultUserOptions;
2026 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2027 $val = $wgDefaultUserOptions[$oname];
2030 $this->mOptions[$oname] = $val;
2034 * Reset all options to the site defaults
2036 function resetOptions() {
2037 $this->mOptions = User::getDefaultOptions();
2041 * Get the user's preferred date format.
2042 * @return String User's preferred date format
2044 function getDatePreference() {
2045 // Important migration for old data rows
2046 if ( is_null( $this->mDatePreference ) ) {
2047 global $wgLang;
2048 $value = $this->getOption( 'date' );
2049 $map = $wgLang->getDatePreferenceMigrationMap();
2050 if ( isset( $map[$value] ) ) {
2051 $value = $map[$value];
2053 $this->mDatePreference = $value;
2055 return $this->mDatePreference;
2059 * Get the user preferred stub threshold
2061 function getStubThreshold() {
2062 global $wgMaxArticleSize; # Maximum article size, in Kb
2063 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2064 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2065 # If they have set an impossible value, disable the preference
2066 # so we can use the parser cache again.
2067 $threshold = 0;
2069 return $threshold;
2073 * Get the permissions this user has.
2074 * @return Array of String permission names
2076 function getRights() {
2077 if ( is_null( $this->mRights ) ) {
2078 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2079 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2080 // Force reindexation of rights when a hook has unset one of them
2081 $this->mRights = array_values( $this->mRights );
2083 return $this->mRights;
2087 * Get the list of explicit group memberships this user has.
2088 * The implicit * and user groups are not included.
2089 * @return Array of String internal group names
2091 function getGroups() {
2092 $this->load();
2093 return $this->mGroups;
2097 * Get the list of implicit group memberships this user has.
2098 * This includes all explicit groups, plus 'user' if logged in,
2099 * '*' for all accounts, and autopromoted groups
2100 * @param $recache Bool Whether to avoid the cache
2101 * @return Array of String internal group names
2103 function getEffectiveGroups( $recache = false ) {
2104 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2105 wfProfileIn( __METHOD__ );
2106 $this->mEffectiveGroups = $this->getGroups();
2107 $this->mEffectiveGroups[] = '*';
2108 if( $this->getId() ) {
2109 $this->mEffectiveGroups[] = 'user';
2111 $this->mEffectiveGroups = array_unique( array_merge(
2112 $this->mEffectiveGroups,
2113 Autopromote::getAutopromoteGroups( $this )
2114 ) );
2116 # Hook for additional groups
2117 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2119 wfProfileOut( __METHOD__ );
2121 return $this->mEffectiveGroups;
2125 * Get the user's edit count.
2126 * @return Int
2128 function getEditCount() {
2129 if( $this->getId() ) {
2130 if ( !isset( $this->mEditCount ) ) {
2131 /* Populate the count, if it has not been populated yet */
2132 $this->mEditCount = User::edits( $this->mId );
2134 return $this->mEditCount;
2135 } else {
2136 /* nil */
2137 return null;
2142 * Add the user to the given group.
2143 * This takes immediate effect.
2144 * @param $group String Name of the group to add
2146 function addGroup( $group ) {
2147 $dbw = wfGetDB( DB_MASTER );
2148 if( $this->getId() ) {
2149 $dbw->insert( 'user_groups',
2150 array(
2151 'ug_user' => $this->getID(),
2152 'ug_group' => $group,
2154 __METHOD__,
2155 array( 'IGNORE' ) );
2158 $this->loadGroups();
2159 $this->mGroups[] = $group;
2160 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2162 $this->invalidateCache();
2166 * Remove the user from the given group.
2167 * This takes immediate effect.
2168 * @param $group String Name of the group to remove
2170 function removeGroup( $group ) {
2171 $this->load();
2172 $dbw = wfGetDB( DB_MASTER );
2173 $dbw->delete( 'user_groups',
2174 array(
2175 'ug_user' => $this->getID(),
2176 'ug_group' => $group,
2177 ), __METHOD__ );
2179 $this->loadGroups();
2180 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2181 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2183 $this->invalidateCache();
2187 * Get whether the user is logged in
2188 * @return Bool
2190 function isLoggedIn() {
2191 return $this->getID() != 0;
2195 * Get whether the user is anonymous
2196 * @return Bool
2198 function isAnon() {
2199 return !$this->isLoggedIn();
2203 * Check if user is allowed to access a feature / make an action
2204 * @param $action String action to be checked
2205 * @return Boolean: True if action is allowed, else false
2207 function isAllowed( $action = '' ) {
2208 if ( $action === '' ) {
2209 return true; // In the spirit of DWIM
2211 # Patrolling may not be enabled
2212 if( $action === 'patrol' || $action === 'autopatrol' ) {
2213 global $wgUseRCPatrol, $wgUseNPPatrol;
2214 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2215 return false;
2217 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2218 # by misconfiguration: 0 == 'foo'
2219 return in_array( $action, $this->getRights(), true );
2223 * Check whether to enable recent changes patrol features for this user
2224 * @return Boolean: True or false
2226 public function useRCPatrol() {
2227 global $wgUseRCPatrol;
2228 return( $wgUseRCPatrol && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2232 * Check whether to enable new pages patrol features for this user
2233 * @return Bool True or false
2235 public function useNPPatrol() {
2236 global $wgUseRCPatrol, $wgUseNPPatrol;
2237 return( ( $wgUseRCPatrol || $wgUseNPPatrol ) && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2241 * Get the current skin, loading it if required, and setting a title
2242 * @param $t Title: the title to use in the skin
2243 * @return Skin The current skin
2244 * @todo: FIXME : need to check the old failback system [AV]
2246 function getSkin( $t = null ) {
2247 if ( $t ) {
2248 $skin = $this->createSkinObject();
2249 $skin->setTitle( $t );
2250 return $skin;
2251 } else {
2252 if ( !$this->mSkin ) {
2253 $this->mSkin = $this->createSkinObject();
2256 if ( !$this->mSkin->getTitle() ) {
2257 global $wgOut;
2258 $t = $wgOut->getTitle();
2259 $this->mSkin->setTitle($t);
2262 return $this->mSkin;
2266 // Creates a Skin object, for getSkin()
2267 private function createSkinObject() {
2268 wfProfileIn( __METHOD__ );
2270 global $wgHiddenPrefs;
2271 if( !in_array( 'skin', $wgHiddenPrefs ) ) {
2272 global $wgRequest;
2273 # get the user skin
2274 $userSkin = $this->getOption( 'skin' );
2275 $userSkin = $wgRequest->getVal( 'useskin', $userSkin );
2276 } else {
2277 # if we're not allowing users to override, then use the default
2278 global $wgDefaultSkin;
2279 $userSkin = $wgDefaultSkin;
2282 $skin = Skin::newFromKey( $userSkin );
2283 wfProfileOut( __METHOD__ );
2285 return $skin;
2289 * Check the watched status of an article.
2290 * @param $title Title of the article to look at
2291 * @return Bool
2293 function isWatched( $title ) {
2294 $wl = WatchedItem::fromUserTitle( $this, $title );
2295 return $wl->isWatched();
2299 * Watch an article.
2300 * @param $title Title of the article to look at
2302 function addWatch( $title ) {
2303 $wl = WatchedItem::fromUserTitle( $this, $title );
2304 $wl->addWatch();
2305 $this->invalidateCache();
2309 * Stop watching an article.
2310 * @param $title Title of the article to look at
2312 function removeWatch( $title ) {
2313 $wl = WatchedItem::fromUserTitle( $this, $title );
2314 $wl->removeWatch();
2315 $this->invalidateCache();
2319 * Clear the user's notification timestamp for the given title.
2320 * If e-notif e-mails are on, they will receive notification mails on
2321 * the next change of the page if it's watched etc.
2322 * @param $title Title of the article to look at
2324 function clearNotification( &$title ) {
2325 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2327 # Do nothing if the database is locked to writes
2328 if( wfReadOnly() ) {
2329 return;
2332 if( $title->getNamespace() == NS_USER_TALK &&
2333 $title->getText() == $this->getName() ) {
2334 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2335 return;
2336 $this->setNewtalk( false );
2339 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2340 return;
2343 if( $this->isAnon() ) {
2344 // Nothing else to do...
2345 return;
2348 // Only update the timestamp if the page is being watched.
2349 // The query to find out if it is watched is cached both in memcached and per-invocation,
2350 // and when it does have to be executed, it can be on a slave
2351 // If this is the user's newtalk page, we always update the timestamp
2352 if( $title->getNamespace() == NS_USER_TALK &&
2353 $title->getText() == $wgUser->getName() )
2355 $watched = true;
2356 } elseif ( $this->getId() == $wgUser->getId() ) {
2357 $watched = $title->userIsWatching();
2358 } else {
2359 $watched = true;
2362 // If the page is watched by the user (or may be watched), update the timestamp on any
2363 // any matching rows
2364 if ( $watched ) {
2365 $dbw = wfGetDB( DB_MASTER );
2366 $dbw->update( 'watchlist',
2367 array( /* SET */
2368 'wl_notificationtimestamp' => null
2369 ), array( /* WHERE */
2370 'wl_title' => $title->getDBkey(),
2371 'wl_namespace' => $title->getNamespace(),
2372 'wl_user' => $this->getID()
2373 ), __METHOD__
2379 * Resets all of the given user's page-change notification timestamps.
2380 * If e-notif e-mails are on, they will receive notification mails on
2381 * the next change of any watched page.
2383 * @param $currentUser Int User ID
2385 function clearAllNotifications( $currentUser ) {
2386 global $wgUseEnotif, $wgShowUpdatedMarker;
2387 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2388 $this->setNewtalk( false );
2389 return;
2391 if( $currentUser != 0 ) {
2392 $dbw = wfGetDB( DB_MASTER );
2393 $dbw->update( 'watchlist',
2394 array( /* SET */
2395 'wl_notificationtimestamp' => null
2396 ), array( /* WHERE */
2397 'wl_user' => $currentUser
2398 ), __METHOD__
2400 # We also need to clear here the "you have new message" notification for the own user_talk page
2401 # This is cleared one page view later in Article::viewUpdates();
2406 * Set this user's options from an encoded string
2407 * @param $str String Encoded options to import
2408 * @private
2410 function decodeOptions( $str ) {
2411 if( !$str )
2412 return;
2414 $this->mOptionsLoaded = true;
2415 $this->mOptionOverrides = array();
2417 // If an option is not set in $str, use the default value
2418 $this->mOptions = self::getDefaultOptions();
2420 $a = explode( "\n", $str );
2421 foreach ( $a as $s ) {
2422 $m = array();
2423 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2424 $this->mOptions[$m[1]] = $m[2];
2425 $this->mOptionOverrides[$m[1]] = $m[2];
2431 * Set a cookie on the user's client. Wrapper for
2432 * WebResponse::setCookie
2433 * @param $name String Name of the cookie to set
2434 * @param $value String Value to set
2435 * @param $exp Int Expiration time, as a UNIX time value;
2436 * if 0 or not specified, use the default $wgCookieExpiration
2438 protected function setCookie( $name, $value, $exp = 0 ) {
2439 global $wgRequest;
2440 $wgRequest->response()->setcookie( $name, $value, $exp );
2444 * Clear a cookie on the user's client
2445 * @param $name String Name of the cookie to clear
2447 protected function clearCookie( $name ) {
2448 $this->setCookie( $name, '', time() - 86400 );
2452 * Set the default cookies for this session on the user's client.
2454 function setCookies() {
2455 $this->load();
2456 if ( 0 == $this->mId ) return;
2457 $session = array(
2458 'wsUserID' => $this->mId,
2459 'wsToken' => $this->mToken,
2460 'wsUserName' => $this->getName()
2462 $cookies = array(
2463 'UserID' => $this->mId,
2464 'UserName' => $this->getName(),
2466 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2467 $cookies['Token'] = $this->mToken;
2468 } else {
2469 $cookies['Token'] = false;
2472 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2473 #check for null, since the hook could cause a null value
2474 if ( !is_null( $session ) && isset( $_SESSION ) ){
2475 $_SESSION = $session + $_SESSION;
2477 foreach ( $cookies as $name => $value ) {
2478 if ( $value === false ) {
2479 $this->clearCookie( $name );
2480 } else {
2481 $this->setCookie( $name, $value );
2487 * Log this user out.
2489 function logout() {
2490 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2491 $this->doLogout();
2496 * Clear the user's cookies and session, and reset the instance cache.
2497 * @private
2498 * @see logout()
2500 function doLogout() {
2501 $this->clearInstanceCache( 'defaults' );
2503 $_SESSION['wsUserID'] = 0;
2505 $this->clearCookie( 'UserID' );
2506 $this->clearCookie( 'Token' );
2508 # Remember when user logged out, to prevent seeing cached pages
2509 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2513 * Save this user's settings into the database.
2514 * @todo Only rarely do all these fields need to be set!
2516 function saveSettings() {
2517 $this->load();
2518 if ( wfReadOnly() ) { return; }
2519 if ( 0 == $this->mId ) { return; }
2521 $this->mTouched = self::newTouchedTimestamp();
2523 $dbw = wfGetDB( DB_MASTER );
2524 $dbw->update( 'user',
2525 array( /* SET */
2526 'user_name' => $this->mName,
2527 'user_password' => $this->mPassword,
2528 'user_newpassword' => $this->mNewpassword,
2529 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2530 'user_real_name' => $this->mRealName,
2531 'user_email' => $this->mEmail,
2532 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2533 'user_options' => '',
2534 'user_touched' => $dbw->timestamp( $this->mTouched ),
2535 'user_token' => $this->mToken,
2536 'user_email_token' => $this->mEmailToken,
2537 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2538 ), array( /* WHERE */
2539 'user_id' => $this->mId
2540 ), __METHOD__
2543 $this->saveOptions();
2545 wfRunHooks( 'UserSaveSettings', array( $this ) );
2546 $this->clearSharedCache();
2547 $this->getUserPage()->invalidateCache();
2551 * If only this user's username is known, and it exists, return the user ID.
2552 * @return Int
2554 function idForName() {
2555 $s = trim( $this->getName() );
2556 if ( $s === '' ) return 0;
2558 $dbr = wfGetDB( DB_SLAVE );
2559 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2560 if ( $id === false ) {
2561 $id = 0;
2563 return $id;
2567 * Add a user to the database, return the user object
2569 * @param $name String Username to add
2570 * @param $params Array of Strings Non-default parameters to save to the database:
2571 * - password The user's password. Password logins will be disabled if this is omitted.
2572 * - newpassword A temporary password mailed to the user
2573 * - email The user's email address
2574 * - email_authenticated The email authentication timestamp
2575 * - real_name The user's real name
2576 * - options An associative array of non-default options
2577 * - token Random authentication token. Do not set.
2578 * - registration Registration timestamp. Do not set.
2580 * @return User object, or null if the username already exists
2582 static function createNew( $name, $params = array() ) {
2583 $user = new User;
2584 $user->load();
2585 if ( isset( $params['options'] ) ) {
2586 $user->mOptions = $params['options'] + (array)$user->mOptions;
2587 unset( $params['options'] );
2589 $dbw = wfGetDB( DB_MASTER );
2590 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2592 $fields = array(
2593 'user_id' => $seqVal,
2594 'user_name' => $name,
2595 'user_password' => $user->mPassword,
2596 'user_newpassword' => $user->mNewpassword,
2597 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
2598 'user_email' => $user->mEmail,
2599 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2600 'user_real_name' => $user->mRealName,
2601 'user_options' => '',
2602 'user_token' => $user->mToken,
2603 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2604 'user_editcount' => 0,
2606 foreach ( $params as $name => $value ) {
2607 $fields["user_$name"] = $value;
2609 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2610 if ( $dbw->affectedRows() ) {
2611 $newUser = User::newFromId( $dbw->insertId() );
2612 } else {
2613 $newUser = null;
2615 return $newUser;
2619 * Add this existing user object to the database
2621 function addToDatabase() {
2622 $this->load();
2623 $dbw = wfGetDB( DB_MASTER );
2624 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2625 $dbw->insert( 'user',
2626 array(
2627 'user_id' => $seqVal,
2628 'user_name' => $this->mName,
2629 'user_password' => $this->mPassword,
2630 'user_newpassword' => $this->mNewpassword,
2631 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2632 'user_email' => $this->mEmail,
2633 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2634 'user_real_name' => $this->mRealName,
2635 'user_options' => '',
2636 'user_token' => $this->mToken,
2637 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2638 'user_editcount' => 0,
2639 ), __METHOD__
2641 $this->mId = $dbw->insertId();
2643 // Clear instance cache other than user table data, which is already accurate
2644 $this->clearInstanceCache();
2646 $this->saveOptions();
2650 * If this (non-anonymous) user is blocked, block any IP address
2651 * they've successfully logged in from.
2653 function spreadBlock() {
2654 wfDebug( __METHOD__ . "()\n" );
2655 $this->load();
2656 if ( $this->mId == 0 ) {
2657 return;
2660 $userblock = Block::newFromDB( '', $this->mId );
2661 if ( !$userblock ) {
2662 return;
2665 $userblock->doAutoblock( wfGetIP() );
2669 * Generate a string which will be different for any combination of
2670 * user options which would produce different parser output.
2671 * This will be used as part of the hash key for the parser cache,
2672 * so users with the same options can share the same cached data
2673 * safely.
2675 * Extensions which require it should install 'PageRenderingHash' hook,
2676 * which will give them a chance to modify this key based on their own
2677 * settings.
2679 * @deprecated @since 1.17 use the ParserOptions object to get the relevant options
2680 * @return String Page rendering hash
2682 function getPageRenderingHash() {
2683 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2684 if( $this->mHash ){
2685 return $this->mHash;
2687 wfDeprecated( __METHOD__ );
2689 // stubthreshold is only included below for completeness,
2690 // since it disables the parser cache, its value will always
2691 // be 0 when this function is called by parsercache.
2693 $confstr = $this->getOption( 'math' );
2694 $confstr .= '!' . $this->getStubThreshold();
2695 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2696 $confstr .= '!' . $this->getDatePreference();
2698 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
2699 $confstr .= '!' . $wgLang->getCode();
2700 $confstr .= '!' . $this->getOption( 'thumbsize' );
2701 // add in language specific options, if any
2702 $extra = $wgContLang->getExtraHashOptions();
2703 $confstr .= $extra;
2705 // Since the skin could be overloading link(), it should be
2706 // included here but in practice, none of our skins do that.
2708 $confstr .= $wgRenderHashAppend;
2710 // Give a chance for extensions to modify the hash, if they have
2711 // extra options or other effects on the parser cache.
2712 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2714 // Make it a valid memcached key fragment
2715 $confstr = str_replace( ' ', '_', $confstr );
2716 $this->mHash = $confstr;
2717 return $confstr;
2721 * Get whether the user is explicitly blocked from account creation.
2722 * @return Bool
2724 function isBlockedFromCreateAccount() {
2725 $this->getBlockedStatus();
2726 return $this->mBlock && $this->mBlock->mCreateAccount;
2730 * Get whether the user is blocked from using Special:Emailuser.
2731 * @return Bool
2733 function isBlockedFromEmailuser() {
2734 $this->getBlockedStatus();
2735 return $this->mBlock && $this->mBlock->mBlockEmail;
2739 * Get whether the user is allowed to create an account.
2740 * @return Bool
2742 function isAllowedToCreateAccount() {
2743 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2747 * Get this user's personal page title.
2749 * @return Title: User's personal page title
2751 function getUserPage() {
2752 return Title::makeTitle( NS_USER, $this->getName() );
2756 * Get this user's talk page title.
2758 * @return Title: User's talk page title
2760 function getTalkPage() {
2761 $title = $this->getUserPage();
2762 return $title->getTalkPage();
2766 * Get the maximum valid user ID.
2767 * @return Integer: User ID
2768 * @static
2770 function getMaxID() {
2771 static $res; // cache
2773 if ( isset( $res ) ) {
2774 return $res;
2775 } else {
2776 $dbr = wfGetDB( DB_SLAVE );
2777 return $res = $dbr->selectField( 'user', 'max(user_id)', false, __METHOD__ );
2782 * Determine whether the user is a newbie. Newbies are either
2783 * anonymous IPs, or the most recently created accounts.
2784 * @return Bool
2786 function isNewbie() {
2787 return !$this->isAllowed( 'autoconfirmed' );
2791 * Check to see if the given clear-text password is one of the accepted passwords
2792 * @param $password String: user password.
2793 * @return Boolean: True if the given password is correct, otherwise False.
2795 function checkPassword( $password ) {
2796 global $wgAuth;
2797 $this->load();
2799 // Even though we stop people from creating passwords that
2800 // are shorter than this, doesn't mean people wont be able
2801 // to. Certain authentication plugins do NOT want to save
2802 // domain passwords in a mysql database, so we should
2803 // check this (in case $wgAuth->strict() is false).
2804 if( !$this->isValidPassword( $password ) ) {
2805 return false;
2808 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2809 return true;
2810 } elseif( $wgAuth->strict() ) {
2811 /* Auth plugin doesn't allow local authentication */
2812 return false;
2813 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2814 /* Auth plugin doesn't allow local authentication for this user name */
2815 return false;
2817 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2818 return true;
2819 } elseif ( function_exists( 'iconv' ) ) {
2820 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2821 # Check for this with iconv
2822 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2823 if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
2824 return true;
2827 return false;
2831 * Check if the given clear-text password matches the temporary password
2832 * sent by e-mail for password reset operations.
2833 * @return Boolean: True if matches, false otherwise
2835 function checkTemporaryPassword( $plaintext ) {
2836 global $wgNewPasswordExpiry;
2837 if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
2838 if ( is_null( $this->mNewpassTime ) ) {
2839 return true;
2841 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
2842 return ( time() < $expiry );
2843 } else {
2844 return false;
2849 * Initialize (if necessary) and return a session token value
2850 * which can be used in edit forms to show that the user's
2851 * login credentials aren't being hijacked with a foreign form
2852 * submission.
2854 * @param $salt String|Array of Strings Optional function-specific data for hashing
2855 * @return String The new edit token
2857 function editToken( $salt = '' ) {
2858 if ( $this->isAnon() ) {
2859 return EDIT_TOKEN_SUFFIX;
2860 } else {
2861 if( !isset( $_SESSION['wsEditToken'] ) ) {
2862 $token = self::generateToken();
2863 $_SESSION['wsEditToken'] = $token;
2864 } else {
2865 $token = $_SESSION['wsEditToken'];
2867 if( is_array( $salt ) ) {
2868 $salt = implode( '|', $salt );
2870 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2875 * Generate a looking random token for various uses.
2877 * @param $salt String Optional salt value
2878 * @return String The new random token
2880 public static function generateToken( $salt = '' ) {
2881 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2882 return md5( $token . $salt );
2886 * Check given value against the token value stored in the session.
2887 * A match should confirm that the form was submitted from the
2888 * user's own login session, not a form submission from a third-party
2889 * site.
2891 * @param $val String Input value to compare
2892 * @param $salt String Optional function-specific data for hashing
2893 * @return Boolean: Whether the token matches
2895 function matchEditToken( $val, $salt = '' ) {
2896 $sessionToken = $this->editToken( $salt );
2897 if ( $val != $sessionToken ) {
2898 wfDebug( "User::matchEditToken: broken session data\n" );
2900 return $val == $sessionToken;
2904 * Check given value against the token value stored in the session,
2905 * ignoring the suffix.
2907 * @param $val String Input value to compare
2908 * @param $salt String Optional function-specific data for hashing
2909 * @return Boolean: Whether the token matches
2911 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2912 $sessionToken = $this->editToken( $salt );
2913 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2917 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2918 * mail to the user's given address.
2920 * @param $type String: message to send, either "created", "changed" or "set"
2921 * @return Status object
2923 function sendConfirmationMail( $type = 'created' ) {
2924 global $wgLang;
2925 $expiration = null; // gets passed-by-ref and defined in next line.
2926 $token = $this->confirmationToken( $expiration );
2927 $url = $this->confirmationTokenUrl( $token );
2928 $invalidateURL = $this->invalidationTokenUrl( $token );
2929 $this->saveSettings();
2931 if ( $type == 'created' || $type === false ) {
2932 $message = 'confirmemail_body';
2933 } elseif ( $type === true ) {
2934 $message = 'confirmemail_body_changed';
2935 } else {
2936 $message = 'confirmemail_body_' . $type;
2939 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2940 wfMsg( $message,
2941 wfGetIP(),
2942 $this->getName(),
2943 $url,
2944 $wgLang->timeanddate( $expiration, false ),
2945 $invalidateURL,
2946 $wgLang->date( $expiration, false ),
2947 $wgLang->time( $expiration, false ) ) );
2951 * Send an e-mail to this user's account. Does not check for
2952 * confirmed status or validity.
2954 * @param $subject String Message subject
2955 * @param $body String Message body
2956 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
2957 * @param $replyto String Reply-To address
2958 * @return Status
2960 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2961 if( is_null( $from ) ) {
2962 global $wgPasswordSender, $wgPasswordSenderName;
2963 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
2964 } else {
2965 $sender = new MailAddress( $from );
2968 $to = new MailAddress( $this );
2969 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2973 * Generate, store, and return a new e-mail confirmation code.
2974 * A hash (unsalted, since it's used as a key) is stored.
2976 * @note Call saveSettings() after calling this function to commit
2977 * this change to the database.
2979 * @param[out] &$expiration \mixed Accepts the expiration time
2980 * @return String New token
2981 * @private
2983 function confirmationToken( &$expiration ) {
2984 $now = time();
2985 $expires = $now + 7 * 24 * 60 * 60;
2986 $expiration = wfTimestamp( TS_MW, $expires );
2987 $token = self::generateToken( $this->mId . $this->mEmail . $expires );
2988 $hash = md5( $token );
2989 $this->load();
2990 $this->mEmailToken = $hash;
2991 $this->mEmailTokenExpires = $expiration;
2992 return $token;
2996 * Return a URL the user can use to confirm their email address.
2997 * @param $token String Accepts the email confirmation token
2998 * @return String New token URL
2999 * @private
3001 function confirmationTokenUrl( $token ) {
3002 return $this->getTokenUrl( 'ConfirmEmail', $token );
3006 * Return a URL the user can use to invalidate their email address.
3007 * @param $token String Accepts the email confirmation token
3008 * @return String New token URL
3009 * @private
3011 function invalidationTokenUrl( $token ) {
3012 return $this->getTokenUrl( 'Invalidateemail', $token );
3016 * Internal function to format the e-mail validation/invalidation URLs.
3017 * This uses $wgArticlePath directly as a quickie hack to use the
3018 * hardcoded English names of the Special: pages, for ASCII safety.
3020 * @note Since these URLs get dropped directly into emails, using the
3021 * short English names avoids insanely long URL-encoded links, which
3022 * also sometimes can get corrupted in some browsers/mailers
3023 * (bug 6957 with Gmail and Internet Explorer).
3025 * @param $page String Special page
3026 * @param $token String Token
3027 * @return String Formatted URL
3029 protected function getTokenUrl( $page, $token ) {
3030 global $wgArticlePath;
3031 return wfExpandUrl(
3032 str_replace(
3033 '$1',
3034 "Special:$page/$token",
3035 $wgArticlePath ) );
3039 * Mark the e-mail address confirmed.
3041 * @note Call saveSettings() after calling this function to commit the change.
3043 function confirmEmail() {
3044 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3045 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3046 return true;
3050 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3051 * address if it was already confirmed.
3053 * @note Call saveSettings() after calling this function to commit the change.
3055 function invalidateEmail() {
3056 $this->load();
3057 $this->mEmailToken = null;
3058 $this->mEmailTokenExpires = null;
3059 $this->setEmailAuthenticationTimestamp( null );
3060 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3061 return true;
3065 * Set the e-mail authentication timestamp.
3066 * @param $timestamp String TS_MW timestamp
3068 function setEmailAuthenticationTimestamp( $timestamp ) {
3069 $this->load();
3070 $this->mEmailAuthenticated = $timestamp;
3071 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
3075 * Is this user allowed to send e-mails within limits of current
3076 * site configuration?
3077 * @return Bool
3079 function canSendEmail() {
3080 global $wgEnableEmail, $wgEnableUserEmail;
3081 if( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
3082 return false;
3084 $canSend = $this->isEmailConfirmed();
3085 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3086 return $canSend;
3090 * Is this user allowed to receive e-mails within limits of current
3091 * site configuration?
3092 * @return Bool
3094 function canReceiveEmail() {
3095 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3099 * Is this user's e-mail address valid-looking and confirmed within
3100 * limits of the current site configuration?
3102 * @note If $wgEmailAuthentication is on, this may require the user to have
3103 * confirmed their address by returning a code or using a password
3104 * sent to the address from the wiki.
3106 * @return Bool
3108 function isEmailConfirmed() {
3109 global $wgEmailAuthentication;
3110 $this->load();
3111 $confirmed = true;
3112 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3113 if( $this->isAnon() )
3114 return false;
3115 if( !self::isValidEmailAddr( $this->mEmail ) )
3116 return false;
3117 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3118 return false;
3119 return true;
3120 } else {
3121 return $confirmed;
3126 * Check whether there is an outstanding request for e-mail confirmation.
3127 * @return Bool
3129 function isEmailConfirmationPending() {
3130 global $wgEmailAuthentication;
3131 return $wgEmailAuthentication &&
3132 !$this->isEmailConfirmed() &&
3133 $this->mEmailToken &&
3134 $this->mEmailTokenExpires > wfTimestamp();
3138 * Get the timestamp of account creation.
3140 * @return String|Bool Timestamp of account creation, or false for
3141 * non-existent/anonymous user accounts.
3143 public function getRegistration() {
3144 return $this->getId() > 0
3145 ? $this->mRegistration
3146 : false;
3150 * Get the timestamp of the first edit
3152 * @return String|Bool Timestamp of first edit, or false for
3153 * non-existent/anonymous user accounts.
3155 public function getFirstEditTimestamp() {
3156 if( $this->getId() == 0 ) {
3157 return false; // anons
3159 $dbr = wfGetDB( DB_SLAVE );
3160 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3161 array( 'rev_user' => $this->getId() ),
3162 __METHOD__,
3163 array( 'ORDER BY' => 'rev_timestamp ASC' )
3165 if( !$time ) {
3166 return false; // no edits
3168 return wfTimestamp( TS_MW, $time );
3172 * Get the permissions associated with a given list of groups
3174 * @param $groups Array of Strings List of internal group names
3175 * @return Array of Strings List of permission key names for given groups combined
3177 static function getGroupPermissions( $groups ) {
3178 global $wgGroupPermissions, $wgRevokePermissions;
3179 $rights = array();
3180 // grant every granted permission first
3181 foreach( $groups as $group ) {
3182 if( isset( $wgGroupPermissions[$group] ) ) {
3183 $rights = array_merge( $rights,
3184 // array_filter removes empty items
3185 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3188 // now revoke the revoked permissions
3189 foreach( $groups as $group ) {
3190 if( isset( $wgRevokePermissions[$group] ) ) {
3191 $rights = array_diff( $rights,
3192 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3195 return array_unique( $rights );
3199 * Get all the groups who have a given permission
3201 * @param $role String Role to check
3202 * @return Array of Strings List of internal group names with the given permission
3204 static function getGroupsWithPermission( $role ) {
3205 global $wgGroupPermissions;
3206 $allowedGroups = array();
3207 foreach ( $wgGroupPermissions as $group => $rights ) {
3208 if ( isset( $rights[$role] ) && $rights[$role] ) {
3209 $allowedGroups[] = $group;
3212 return $allowedGroups;
3216 * Get the localized descriptive name for a group, if it exists
3218 * @param $group String Internal group name
3219 * @return String Localized descriptive group name
3221 static function getGroupName( $group ) {
3222 $msg = wfMessage( "group-$group" );
3223 return $msg->isBlank() ? $group : $msg->text();
3227 * Get the localized descriptive name for a member of a group, if it exists
3229 * @param $group String Internal group name
3230 * @return String Localized name for group member
3232 static function getGroupMember( $group ) {
3233 $msg = wfMessage( "group-$group-member" );
3234 return $msg->isBlank() ? $group : $msg->text();
3238 * Return the set of defined explicit groups.
3239 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3240 * are not included, as they are defined automatically, not in the database.
3241 * @return Array of internal group names
3243 static function getAllGroups() {
3244 global $wgGroupPermissions, $wgRevokePermissions;
3245 return array_diff(
3246 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3247 self::getImplicitGroups()
3252 * Get a list of all available permissions.
3253 * @return Array of permission names
3255 static function getAllRights() {
3256 if ( self::$mAllRights === false ) {
3257 global $wgAvailableRights;
3258 if ( count( $wgAvailableRights ) ) {
3259 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3260 } else {
3261 self::$mAllRights = self::$mCoreRights;
3263 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3265 return self::$mAllRights;
3269 * Get a list of implicit groups
3270 * @return Array of Strings Array of internal group names
3272 public static function getImplicitGroups() {
3273 global $wgImplicitGroups;
3274 $groups = $wgImplicitGroups;
3275 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3276 return $groups;
3280 * Get the title of a page describing a particular group
3282 * @param $group String Internal group name
3283 * @return Title|Bool Title of the page if it exists, false otherwise
3285 static function getGroupPage( $group ) {
3286 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3287 if( $msg->exists() ) {
3288 $title = Title::newFromText( $msg->text() );
3289 if( is_object( $title ) )
3290 return $title;
3292 return false;
3296 * Create a link to the group in HTML, if available;
3297 * else return the group name.
3299 * @param $group String Internal name of the group
3300 * @param $text String The text of the link
3301 * @return String HTML link to the group
3303 static function makeGroupLinkHTML( $group, $text = '' ) {
3304 if( $text == '' ) {
3305 $text = self::getGroupName( $group );
3307 $title = self::getGroupPage( $group );
3308 if( $title ) {
3309 global $wgUser;
3310 $sk = $wgUser->getSkin();
3311 return $sk->link( $title, htmlspecialchars( $text ) );
3312 } else {
3313 return $text;
3318 * Create a link to the group in Wikitext, if available;
3319 * else return the group name.
3321 * @param $group String Internal name of the group
3322 * @param $text String The text of the link
3323 * @return String Wikilink to the group
3325 static function makeGroupLinkWiki( $group, $text = '' ) {
3326 if( $text == '' ) {
3327 $text = self::getGroupName( $group );
3329 $title = self::getGroupPage( $group );
3330 if( $title ) {
3331 $page = $title->getPrefixedText();
3332 return "[[$page|$text]]";
3333 } else {
3334 return $text;
3339 * Returns an array of the groups that a particular group can add/remove.
3341 * @param $group String: the group to check for whether it can add/remove
3342 * @return Array array( 'add' => array( addablegroups ),
3343 * 'remove' => array( removablegroups ),
3344 * 'add-self' => array( addablegroups to self),
3345 * 'remove-self' => array( removable groups from self) )
3347 static function changeableByGroup( $group ) {
3348 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3350 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3351 if( empty( $wgAddGroups[$group] ) ) {
3352 // Don't add anything to $groups
3353 } elseif( $wgAddGroups[$group] === true ) {
3354 // You get everything
3355 $groups['add'] = self::getAllGroups();
3356 } elseif( is_array( $wgAddGroups[$group] ) ) {
3357 $groups['add'] = $wgAddGroups[$group];
3360 // Same thing for remove
3361 if( empty( $wgRemoveGroups[$group] ) ) {
3362 } elseif( $wgRemoveGroups[$group] === true ) {
3363 $groups['remove'] = self::getAllGroups();
3364 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3365 $groups['remove'] = $wgRemoveGroups[$group];
3368 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3369 if( empty( $wgGroupsAddToSelf['user']) || $wgGroupsAddToSelf['user'] !== true ) {
3370 foreach( $wgGroupsAddToSelf as $key => $value ) {
3371 if( is_int( $key ) ) {
3372 $wgGroupsAddToSelf['user'][] = $value;
3377 if( empty( $wgGroupsRemoveFromSelf['user']) || $wgGroupsRemoveFromSelf['user'] !== true ) {
3378 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3379 if( is_int( $key ) ) {
3380 $wgGroupsRemoveFromSelf['user'][] = $value;
3385 // Now figure out what groups the user can add to him/herself
3386 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3387 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3388 // No idea WHY this would be used, but it's there
3389 $groups['add-self'] = User::getAllGroups();
3390 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3391 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3394 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3395 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3396 $groups['remove-self'] = User::getAllGroups();
3397 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3398 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3401 return $groups;
3405 * Returns an array of groups that this user can add and remove
3406 * @return Array array( 'add' => array( addablegroups ),
3407 * 'remove' => array( removablegroups ),
3408 * 'add-self' => array( addablegroups to self),
3409 * 'remove-self' => array( removable groups from self) )
3411 function changeableGroups() {
3412 if( $this->isAllowed( 'userrights' ) ) {
3413 // This group gives the right to modify everything (reverse-
3414 // compatibility with old "userrights lets you change
3415 // everything")
3416 // Using array_merge to make the groups reindexed
3417 $all = array_merge( User::getAllGroups() );
3418 return array(
3419 'add' => $all,
3420 'remove' => $all,
3421 'add-self' => array(),
3422 'remove-self' => array()
3426 // Okay, it's not so simple, we will have to go through the arrays
3427 $groups = array(
3428 'add' => array(),
3429 'remove' => array(),
3430 'add-self' => array(),
3431 'remove-self' => array()
3433 $addergroups = $this->getEffectiveGroups();
3435 foreach( $addergroups as $addergroup ) {
3436 $groups = array_merge_recursive(
3437 $groups, $this->changeableByGroup( $addergroup )
3439 $groups['add'] = array_unique( $groups['add'] );
3440 $groups['remove'] = array_unique( $groups['remove'] );
3441 $groups['add-self'] = array_unique( $groups['add-self'] );
3442 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3444 return $groups;
3448 * Increment the user's edit-count field.
3449 * Will have no effect for anonymous users.
3451 function incEditCount() {
3452 if( !$this->isAnon() ) {
3453 $dbw = wfGetDB( DB_MASTER );
3454 $dbw->update( 'user',
3455 array( 'user_editcount=user_editcount+1' ),
3456 array( 'user_id' => $this->getId() ),
3457 __METHOD__ );
3459 // Lazy initialization check...
3460 if( $dbw->affectedRows() == 0 ) {
3461 // Pull from a slave to be less cruel to servers
3462 // Accuracy isn't the point anyway here
3463 $dbr = wfGetDB( DB_SLAVE );
3464 $count = $dbr->selectField( 'revision',
3465 'COUNT(rev_user)',
3466 array( 'rev_user' => $this->getId() ),
3467 __METHOD__ );
3469 // Now here's a goddamn hack...
3470 if( $dbr !== $dbw ) {
3471 // If we actually have a slave server, the count is
3472 // at least one behind because the current transaction
3473 // has not been committed and replicated.
3474 $count++;
3475 } else {
3476 // But if DB_SLAVE is selecting the master, then the
3477 // count we just read includes the revision that was
3478 // just added in the working transaction.
3481 $dbw->update( 'user',
3482 array( 'user_editcount' => $count ),
3483 array( 'user_id' => $this->getId() ),
3484 __METHOD__ );
3487 // edit count in user cache too
3488 $this->invalidateCache();
3492 * Get the description of a given right
3494 * @param $right String Right to query
3495 * @return String Localized description of the right
3497 static function getRightDescription( $right ) {
3498 $key = "right-$right";
3499 $name = wfMsg( $key );
3500 return $name == '' || wfEmptyMsg( $key, $name )
3501 ? $right
3502 : $name;
3506 * Make an old-style password hash
3508 * @param $password String Plain-text password
3509 * @param $userId String User ID
3510 * @return String Password hash
3512 static function oldCrypt( $password, $userId ) {
3513 global $wgPasswordSalt;
3514 if ( $wgPasswordSalt ) {
3515 return md5( $userId . '-' . md5( $password ) );
3516 } else {
3517 return md5( $password );
3522 * Make a new-style password hash
3524 * @param $password String Plain-text password
3525 * @param $salt String Optional salt, may be random or the user ID.
3526 * If unspecified or false, will generate one automatically
3527 * @return String Password hash
3529 static function crypt( $password, $salt = false ) {
3530 global $wgPasswordSalt;
3532 $hash = '';
3533 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3534 return $hash;
3537 if( $wgPasswordSalt ) {
3538 if ( $salt === false ) {
3539 $salt = substr( wfGenerateToken(), 0, 8 );
3541 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3542 } else {
3543 return ':A:' . md5( $password );
3548 * Compare a password hash with a plain-text password. Requires the user
3549 * ID if there's a chance that the hash is an old-style hash.
3551 * @param $hash String Password hash
3552 * @param $password String Plain-text password to compare
3553 * @param $userId String User ID for old-style password salt
3554 * @return Boolean:
3556 static function comparePasswords( $hash, $password, $userId = false ) {
3557 $type = substr( $hash, 0, 3 );
3559 $result = false;
3560 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3561 return $result;
3564 if ( $type == ':A:' ) {
3565 # Unsalted
3566 return md5( $password ) === substr( $hash, 3 );
3567 } elseif ( $type == ':B:' ) {
3568 # Salted
3569 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3570 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3571 } else {
3572 # Old-style
3573 return self::oldCrypt( $password, $userId ) === $hash;
3578 * Add a newuser log entry for this user
3580 * @param $byEmail Boolean: account made by email?
3581 * @param $reason String: user supplied reason
3583 public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
3584 global $wgUser, $wgContLang, $wgNewUserLog;
3585 if( empty( $wgNewUserLog ) ) {
3586 return true; // disabled
3589 if( $this->getName() == $wgUser->getName() ) {
3590 $action = 'create';
3591 } else {
3592 $action = 'create2';
3593 if ( $byEmail ) {
3594 if ( $reason === '' ) {
3595 $reason = wfMsgForContent( 'newuserlog-byemail' );
3596 } else {
3597 $reason = $wgContLang->commaList( array(
3598 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
3602 $log = new LogPage( 'newusers' );
3603 $log->addEntry(
3604 $action,
3605 $this->getUserPage(),
3606 $reason,
3607 array( $this->getId() )
3609 return true;
3613 * Add an autocreate newuser log entry for this user
3614 * Used by things like CentralAuth and perhaps other authplugins.
3616 public function addNewUserLogEntryAutoCreate() {
3617 global $wgNewUserLog, $wgLogAutocreatedAccounts;
3618 if( !$wgNewUserLog || !$wgLogAutocreatedAccounts ) {
3619 return true; // disabled
3621 $log = new LogPage( 'newusers', false );
3622 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3623 return true;
3626 protected function loadOptions() {
3627 $this->load();
3628 if ( $this->mOptionsLoaded || !$this->getId() )
3629 return;
3631 $this->mOptions = self::getDefaultOptions();
3633 // Maybe load from the object
3634 if ( !is_null( $this->mOptionOverrides ) ) {
3635 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3636 foreach( $this->mOptionOverrides as $key => $value ) {
3637 $this->mOptions[$key] = $value;
3639 } else {
3640 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3641 // Load from database
3642 $dbr = wfGetDB( DB_SLAVE );
3644 $res = $dbr->select(
3645 'user_properties',
3646 '*',
3647 array( 'up_user' => $this->getId() ),
3648 __METHOD__
3651 foreach ( $res as $row ) {
3652 $this->mOptionOverrides[$row->up_property] = $row->up_value;
3653 $this->mOptions[$row->up_property] = $row->up_value;
3657 $this->mOptionsLoaded = true;
3659 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
3662 protected function saveOptions() {
3663 global $wgAllowPrefChange;
3665 $extuser = ExternalUser::newFromUser( $this );
3667 $this->loadOptions();
3668 $dbw = wfGetDB( DB_MASTER );
3670 $insert_rows = array();
3672 $saveOptions = $this->mOptions;
3674 // Allow hooks to abort, for instance to save to a global profile.
3675 // Reset options to default state before saving.
3676 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3677 return;
3679 foreach( $saveOptions as $key => $value ) {
3680 # Don't bother storing default values
3681 if ( ( is_null( self::getDefaultOption( $key ) ) &&
3682 !( $value === false || is_null($value) ) ) ||
3683 $value != self::getDefaultOption( $key ) ) {
3684 $insert_rows[] = array(
3685 'up_user' => $this->getId(),
3686 'up_property' => $key,
3687 'up_value' => $value,
3690 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3691 switch ( $wgAllowPrefChange[$key] ) {
3692 case 'local':
3693 case 'message':
3694 break;
3695 case 'semiglobal':
3696 case 'global':
3697 $extuser->setPref( $key, $value );
3702 $dbw->begin();
3703 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__ );
3704 $dbw->insert( 'user_properties', $insert_rows, __METHOD__ );
3705 $dbw->commit();
3709 * Provide an array of HTML5 attributes to put on an input element
3710 * intended for the user to enter a new password. This may include
3711 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3713 * Do *not* use this when asking the user to enter his current password!
3714 * Regardless of configuration, users may have invalid passwords for whatever
3715 * reason (e.g., they were set before requirements were tightened up).
3716 * Only use it when asking for a new password, like on account creation or
3717 * ResetPass.
3719 * Obviously, you still need to do server-side checking.
3721 * NOTE: A combination of bugs in various browsers means that this function
3722 * actually just returns array() unconditionally at the moment. May as
3723 * well keep it around for when the browser bugs get fixed, though.
3725 * FIXME : This does not belong here; put it in Html or Linker or somewhere
3727 * @return array Array of HTML attributes suitable for feeding to
3728 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3729 * That will potentially output invalid XHTML 1.0 Transitional, and will
3730 * get confused by the boolean attribute syntax used.)
3732 public static function passwordChangeInputAttribs() {
3733 global $wgMinimalPasswordLength;
3735 if ( $wgMinimalPasswordLength == 0 ) {
3736 return array();
3739 # Note that the pattern requirement will always be satisfied if the
3740 # input is empty, so we need required in all cases.
3742 # FIXME (bug 23769): This needs to not claim the password is required
3743 # if e-mail confirmation is being used. Since HTML5 input validation
3744 # is b0rked anyway in some browsers, just return nothing. When it's
3745 # re-enabled, fix this code to not output required for e-mail
3746 # registration.
3747 #$ret = array( 'required' );
3748 $ret = array();
3750 # We can't actually do this right now, because Opera 9.6 will print out
3751 # the entered password visibly in its error message! When other
3752 # browsers add support for this attribute, or Opera fixes its support,
3753 # we can add support with a version check to avoid doing this on Opera
3754 # versions where it will be a problem. Reported to Opera as
3755 # DSK-262266, but they don't have a public bug tracker for us to follow.
3757 if ( $wgMinimalPasswordLength > 1 ) {
3758 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3759 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3760 $wgMinimalPasswordLength );
3764 return $ret;
3768 * Format the user message using a hook, a template, or, failing these, a static format.
3769 * @param $subject String the subject of the message
3770 * @param $text String the content of the message
3771 * @param $signature String the signature, if provided.
3773 static protected function formatUserMessage( $subject, $text, $signature ) {
3774 if ( wfRunHooks( 'FormatUserMessage',
3775 array( $subject, &$text, $signature ) ) ) {
3777 $signature = empty($signature) ? "~~~~~" : "{$signature} ~~~~~";
3779 $template = Title::newFromText( wfMsgForContent( 'usermessage-template' ) );
3780 if ( !$template
3781 || $template->getNamespace() !== NS_TEMPLATE
3782 || !$template->exists() ) {
3783 $text = "\n== $subject ==\n\n$text\n\n-- $signature";
3784 } else {
3785 $text = '{{'. $template->getText()
3786 . " | subject=$subject | body=$text | signature=$signature }}";
3790 return $text;
3794 * Leave a user a message
3795 * @param $subject String the subject of the message
3796 * @param $text String the message to leave
3797 * @param $signature String Text to leave in the signature
3798 * @param $summary String the summary for this change, defaults to
3799 * "Leave system message."
3800 * @param $editor User The user leaving the message, defaults to
3801 * "{{MediaWiki:usermessage-editor}}"
3802 * @param $flags Int default edit flags
3804 * @return boolean true if it was successful
3806 public function leaveUserMessage( $subject, $text, $signature = "",
3807 $summary = null, $editor = null, $flags = 0 ) {
3808 if ( !isset( $summary ) ) {
3809 $summary = wfMsgForContent( 'usermessage-summary' );
3812 if ( !isset( $editor ) ) {
3813 $editor = User::newFromName( wfMsgForContent( 'usermessage-editor' ) );
3814 if ( !$editor->isLoggedIn() ) {
3815 $editor->addToDatabase();
3819 $article = new Article( $this->getTalkPage() );
3820 wfRunHooks( 'SetupUserMessageArticle',
3821 array( $this, &$article, $subject, $text, $signature, $summary, $editor ) );
3824 $text = self::formatUserMessage( $subject, $text, $signature );
3825 $flags = $article->checkFlags( $flags );
3827 if ( $flags & EDIT_UPDATE ) {
3828 $text = $article->getContent() . $text;
3831 $dbw = wfGetDB( DB_MASTER );
3832 $dbw->begin();
3834 try {
3835 $status = $article->doEdit( $text, $summary, $flags, false, $editor );
3836 } catch ( DBQueryError $e ) {
3837 $status = Status::newFatal("DB Error");
3840 if ( $status->isGood() ) {
3841 // Set newtalk with the right user ID
3842 $this->setNewtalk( true );
3843 wfRunHooks( 'AfterUserMessage',
3844 array( $this, $article, $subject, $text, $signature, $summary, $editor ) );
3845 $dbw->commit();
3846 } else {
3847 // The article was concurrently created
3848 wfDebug( __METHOD__ . ": Error ".$status->getWikiText() );
3849 $dbw->rollback();
3852 return $status->isGood();