Follwup r75575, honour table prefixes. Bad Roan ;)
[mediawiki.git] / includes / User.php
blob40a41ed4f8637c696c53f8df722e401a84cb5401
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 * Does the string match an anonymous IPv4 address?
447 * This function exists for username validation, in order to reject
448 * usernames which are similar in form to IP addresses. Strings such
449 * as 300.300.300.300 will return true because it looks like an IP
450 * address, despite not being strictly valid.
452 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
453 * address because the usemod software would "cloak" anonymous IP
454 * addresses like this, if we allowed accounts like this to be created
455 * new users could get the old edits of these anonymous users.
457 * @param $name String to match
458 * @return Bool
460 static function isIP( $name ) {
461 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
465 * Is the input a valid username?
467 * Checks if the input is a valid username, we don't want an empty string,
468 * an IP address, anything that containins slashes (would mess up subpages),
469 * is longer than the maximum allowed username size or doesn't begin with
470 * a capital letter.
472 * @param $name String to match
473 * @return Bool
475 static function isValidUserName( $name ) {
476 global $wgContLang, $wgMaxNameChars;
478 if ( $name == ''
479 || User::isIP( $name )
480 || strpos( $name, '/' ) !== false
481 || strlen( $name ) > $wgMaxNameChars
482 || $name != $wgContLang->ucfirst( $name ) ) {
483 wfDebugLog( 'username', __METHOD__ .
484 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
485 return false;
488 // Ensure that the name can't be misresolved as a different title,
489 // such as with extra namespace keys at the start.
490 $parsed = Title::newFromText( $name );
491 if( is_null( $parsed )
492 || $parsed->getNamespace()
493 || strcmp( $name, $parsed->getPrefixedText() ) ) {
494 wfDebugLog( 'username', __METHOD__ .
495 ": '$name' invalid due to ambiguous prefixes" );
496 return false;
499 // Check an additional blacklist of troublemaker characters.
500 // Should these be merged into the title char list?
501 $unicodeBlacklist = '/[' .
502 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
503 '\x{00a0}' . # non-breaking space
504 '\x{2000}-\x{200f}' . # various whitespace
505 '\x{2028}-\x{202f}' . # breaks and control chars
506 '\x{3000}' . # ideographic space
507 '\x{e000}-\x{f8ff}' . # private use
508 ']/u';
509 if( preg_match( $unicodeBlacklist, $name ) ) {
510 wfDebugLog( 'username', __METHOD__ .
511 ": '$name' invalid due to blacklisted characters" );
512 return false;
515 return true;
519 * Usernames which fail to pass this function will be blocked
520 * from user login and new account registrations, but may be used
521 * internally by batch processes.
523 * If an account already exists in this form, login will be blocked
524 * by a failure to pass this function.
526 * @param $name String to match
527 * @return Bool
529 static function isUsableName( $name ) {
530 global $wgReservedUsernames;
531 // Must be a valid username, obviously ;)
532 if ( !self::isValidUserName( $name ) ) {
533 return false;
536 static $reservedUsernames = false;
537 if ( !$reservedUsernames ) {
538 $reservedUsernames = $wgReservedUsernames;
539 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
542 // Certain names may be reserved for batch processes.
543 foreach ( $reservedUsernames as $reserved ) {
544 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
545 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
547 if ( $reserved == $name ) {
548 return false;
551 return true;
555 * Usernames which fail to pass this function will be blocked
556 * from new account registrations, but may be used internally
557 * either by batch processes or by user accounts which have
558 * already been created.
560 * Additional blacklisting may be added here rather than in
561 * isValidUserName() to avoid disrupting existing accounts.
563 * @param $name String to match
564 * @return Bool
566 static function isCreatableName( $name ) {
567 global $wgInvalidUsernameCharacters;
569 // Ensure that the username isn't longer than 235 bytes, so that
570 // (at least for the builtin skins) user javascript and css files
571 // will work. (bug 23080)
572 if( strlen( $name ) > 235 ) {
573 wfDebugLog( 'username', __METHOD__ .
574 ": '$name' invalid due to length" );
575 return false;
578 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
579 wfDebugLog( 'username', __METHOD__ .
580 ": '$name' invalid due to wgInvalidUsernameCharacters" );
581 return false;
584 return self::isUsableName( $name );
588 * Is the input a valid password for this user?
590 * @param $password String Desired password
591 * @return Bool
593 function isValidPassword( $password ) {
594 //simple boolean wrapper for getPasswordValidity
595 return $this->getPasswordValidity( $password ) === true;
599 * Given unvalidated password input, return error message on failure.
601 * @param $password String Desired password
602 * @return mixed: true on success, string of error message on failure
604 function getPasswordValidity( $password ) {
605 global $wgMinimalPasswordLength, $wgContLang;
607 static $blockedLogins = array(
608 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
609 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
612 $result = false; //init $result to false for the internal checks
614 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
615 return $result;
617 if ( $result === false ) {
618 if( strlen( $password ) < $wgMinimalPasswordLength ) {
619 return 'passwordtooshort';
620 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
621 return 'password-name-match';
622 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
623 return 'password-login-forbidden';
624 } else {
625 //it seems weird returning true here, but this is because of the
626 //initialization of $result to false above. If the hook is never run or it
627 //doesn't modify $result, then we will likely get down into this if with
628 //a valid password.
629 return true;
631 } elseif( $result === true ) {
632 return true;
633 } else {
634 return $result; //the isValidPassword hook set a string $result and returned true
639 * Does a string look like an e-mail address?
641 * There used to be a regular expression here, it got removed because it
642 * rejected valid addresses. Actually just check if there is '@' somewhere
643 * in the given address.
645 * @todo Check for RFC 2822 compilance (bug 959)
647 * @param $addr String E-mail address
648 * @return Bool
650 public static function isValidEmailAddr( $addr ) {
651 $result = null;
652 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
653 return $result;
655 $rfc5322_atext = "a-z0-9!#$%&'*+-\/=?^_`{|}~" ;
656 $rfc1034_ldh_str = "a-z0-9-" ;
658 $HTML5_email_regexp = "/
659 ^ # start of string
660 [$rfc5322_atext\\.]+ # user part which is liberal :p
661 @ # 'apostrophe'
662 [$rfc1034_ldh_str]+ # First domain part
663 (\\.[$rfc1034_ldh_str]+)+ # Following part prefixed with a dot
664 $ # End of string
665 /ix" ; // case Insensitive, eXtended
667 return (bool) preg_match( $HTML5_email_regexp, $addr );
671 * Given unvalidated user input, return a canonical username, or false if
672 * the username is invalid.
673 * @param $name String User input
674 * @param $validate String|Bool type of validation to use:
675 * - false No validation
676 * - 'valid' Valid for batch processes
677 * - 'usable' Valid for batch processes and login
678 * - 'creatable' Valid for batch processes, login and account creation
680 static function getCanonicalName( $name, $validate = 'valid' ) {
681 # Force usernames to capital
682 global $wgContLang;
683 $name = $wgContLang->ucfirst( $name );
685 # Reject names containing '#'; these will be cleaned up
686 # with title normalisation, but then it's too late to
687 # check elsewhere
688 if( strpos( $name, '#' ) !== false )
689 return false;
691 # Clean up name according to title rules
692 $t = ( $validate === 'valid' ) ?
693 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
694 # Check for invalid titles
695 if( is_null( $t ) ) {
696 return false;
699 # Reject various classes of invalid names
700 global $wgAuth;
701 $name = $wgAuth->getCanonicalName( $t->getText() );
703 switch ( $validate ) {
704 case false:
705 break;
706 case 'valid':
707 if ( !User::isValidUserName( $name ) ) {
708 $name = false;
710 break;
711 case 'usable':
712 if ( !User::isUsableName( $name ) ) {
713 $name = false;
715 break;
716 case 'creatable':
717 if ( !User::isCreatableName( $name ) ) {
718 $name = false;
720 break;
721 default:
722 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
724 return $name;
728 * Count the number of edits of a user
729 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
731 * @param $uid Int User ID to check
732 * @return Int the user's edit count
734 static function edits( $uid ) {
735 wfProfileIn( __METHOD__ );
736 $dbr = wfGetDB( DB_SLAVE );
737 // check if the user_editcount field has been initialized
738 $field = $dbr->selectField(
739 'user', 'user_editcount',
740 array( 'user_id' => $uid ),
741 __METHOD__
744 if( $field === null ) { // it has not been initialized. do so.
745 $dbw = wfGetDB( DB_MASTER );
746 $count = $dbr->selectField(
747 'revision', 'count(*)',
748 array( 'rev_user' => $uid ),
749 __METHOD__
751 $dbw->update(
752 'user',
753 array( 'user_editcount' => $count ),
754 array( 'user_id' => $uid ),
755 __METHOD__
757 } else {
758 $count = $field;
760 wfProfileOut( __METHOD__ );
761 return $count;
765 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
766 * @todo hash random numbers to improve security, like generateToken()
768 * @return String new random password
770 static function randomPassword() {
771 global $wgMinimalPasswordLength;
772 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
773 $l = strlen( $pwchars ) - 1;
775 $pwlength = max( 7, $wgMinimalPasswordLength );
776 $digit = mt_rand( 0, $pwlength - 1 );
777 $np = '';
778 for ( $i = 0; $i < $pwlength; $i++ ) {
779 $np .= $i == $digit ? chr( mt_rand( 48, 57 ) ) : $pwchars{ mt_rand( 0, $l ) };
781 return $np;
785 * Set cached properties to default.
787 * @note This no longer clears uncached lazy-initialised properties;
788 * the constructor does that instead.
789 * @private
791 function loadDefaults( $name = false ) {
792 wfProfileIn( __METHOD__ );
794 global $wgRequest;
796 $this->mId = 0;
797 $this->mName = $name;
798 $this->mRealName = '';
799 $this->mPassword = $this->mNewpassword = '';
800 $this->mNewpassTime = null;
801 $this->mEmail = '';
802 $this->mOptionOverrides = null;
803 $this->mOptionsLoaded = false;
805 if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
806 $this->mTouched = wfTimestamp( TS_MW, $wgRequest->getCookie( 'LoggedOut' ) );
807 } else {
808 $this->mTouched = '0'; # Allow any pages to be cached
811 $this->setToken(); # Random
812 $this->mEmailAuthenticated = null;
813 $this->mEmailToken = '';
814 $this->mEmailTokenExpires = null;
815 $this->mRegistration = wfTimestamp( TS_MW );
816 $this->mGroups = array();
818 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
820 wfProfileOut( __METHOD__ );
824 * Load user data from the session or login cookie. If there are no valid
825 * credentials, initialises the user as an anonymous user.
826 * @return Bool True if the user is logged in, false otherwise.
828 private function loadFromSession() {
829 global $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
831 $result = null;
832 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
833 if ( $result !== null ) {
834 return $result;
837 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
838 $extUser = ExternalUser::newFromCookie();
839 if ( $extUser ) {
840 # TODO: Automatically create the user here (or probably a bit
841 # lower down, in fact)
845 if ( $wgRequest->getCookie( 'UserID' ) !== null ) {
846 $sId = intval( $wgRequest->getCookie( 'UserID' ) );
847 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
848 $this->loadDefaults(); // Possible collision!
849 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
850 cookie user ID ($sId) don't match!" );
851 return false;
853 $_SESSION['wsUserID'] = $sId;
854 } else if ( isset( $_SESSION['wsUserID'] ) ) {
855 if ( $_SESSION['wsUserID'] != 0 ) {
856 $sId = $_SESSION['wsUserID'];
857 } else {
858 $this->loadDefaults();
859 return false;
861 } else {
862 $this->loadDefaults();
863 return false;
866 if ( isset( $_SESSION['wsUserName'] ) ) {
867 $sName = $_SESSION['wsUserName'];
868 } else if ( $wgRequest->getCookie('UserName') !== null ) {
869 $sName = $wgRequest->getCookie('UserName');
870 $_SESSION['wsUserName'] = $sName;
871 } else {
872 $this->loadDefaults();
873 return false;
876 $this->mId = $sId;
877 if ( !$this->loadFromId() ) {
878 # Not a valid ID, loadFromId has switched the object to anon for us
879 return false;
882 global $wgBlockDisablesLogin;
883 if( $wgBlockDisablesLogin && $this->isBlocked() ) {
884 # User blocked and we've disabled blocked user logins
885 $this->loadDefaults();
886 return false;
889 if ( isset( $_SESSION['wsToken'] ) ) {
890 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
891 $from = 'session';
892 } else if ( $wgRequest->getCookie( 'Token' ) !== null ) {
893 $passwordCorrect = $this->mToken == $wgRequest->getCookie( 'Token' );
894 $from = 'cookie';
895 } else {
896 # No session or persistent login cookie
897 $this->loadDefaults();
898 return false;
901 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
902 $_SESSION['wsToken'] = $this->mToken;
903 wfDebug( "User: logged in from $from\n" );
904 return true;
905 } else {
906 # Invalid credentials
907 wfDebug( "User: can't log in from $from, invalid credentials\n" );
908 $this->loadDefaults();
909 return false;
914 * Load user and user_group data from the database.
915 * $this::mId must be set, this is how the user is identified.
917 * @return Bool True if the user exists, false if the user is anonymous
918 * @private
920 function loadFromDatabase() {
921 # Paranoia
922 $this->mId = intval( $this->mId );
924 /** Anonymous user */
925 if( !$this->mId ) {
926 $this->loadDefaults();
927 return false;
930 $dbr = wfGetDB( DB_MASTER );
931 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
933 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
935 if ( $s !== false ) {
936 # Initialise user table data
937 $this->loadFromRow( $s );
938 $this->mGroups = null; // deferred
939 $this->getEditCount(); // revalidation for nulls
940 return true;
941 } else {
942 # Invalid user_id
943 $this->mId = 0;
944 $this->loadDefaults();
945 return false;
950 * Initialize this object from a row from the user table.
952 * @param $row Array Row from the user table to load.
954 function loadFromRow( $row ) {
955 $this->mDataLoaded = true;
957 if ( isset( $row->user_id ) ) {
958 $this->mId = intval( $row->user_id );
960 $this->mName = $row->user_name;
961 $this->mRealName = $row->user_real_name;
962 $this->mPassword = $row->user_password;
963 $this->mNewpassword = $row->user_newpassword;
964 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
965 $this->mEmail = $row->user_email;
966 $this->decodeOptions( $row->user_options );
967 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
968 $this->mToken = $row->user_token;
969 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
970 $this->mEmailToken = $row->user_email_token;
971 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
972 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
973 $this->mEditCount = $row->user_editcount;
977 * Load the groups from the database if they aren't already loaded.
978 * @private
980 function loadGroups() {
981 if ( is_null( $this->mGroups ) ) {
982 $dbr = wfGetDB( DB_MASTER );
983 $res = $dbr->select( 'user_groups',
984 array( 'ug_group' ),
985 array( 'ug_user' => $this->mId ),
986 __METHOD__ );
987 $this->mGroups = array();
988 foreach ( $res as $row ) {
989 $this->mGroups[] = $row->ug_group;
995 * Clear various cached data stored in this object.
996 * @param $reloadFrom String Reload user and user_groups table data from a
997 * given source. May be "name", "id", "defaults", "session", or false for
998 * no reload.
1000 function clearInstanceCache( $reloadFrom = false ) {
1001 $this->mNewtalk = -1;
1002 $this->mDatePreference = null;
1003 $this->mBlockedby = -1; # Unset
1004 $this->mHash = false;
1005 $this->mSkin = null;
1006 $this->mRights = null;
1007 $this->mEffectiveGroups = null;
1008 $this->mOptions = null;
1010 if ( $reloadFrom ) {
1011 $this->mDataLoaded = false;
1012 $this->mFrom = $reloadFrom;
1017 * Combine the language default options with any site-specific options
1018 * and add the default language variants.
1020 * @return Array of String options
1022 static function getDefaultOptions() {
1023 global $wgNamespacesToBeSearchedDefault;
1025 * Site defaults will override the global/language defaults
1027 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1028 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
1031 * default language setting
1033 $variant = $wgContLang->getDefaultVariant();
1034 $defOpt['variant'] = $variant;
1035 $defOpt['language'] = $variant;
1036 foreach( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1037 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1039 $defOpt['skin'] = $wgDefaultSkin;
1041 return $defOpt;
1045 * Get a given default option value.
1047 * @param $opt String Name of option to retrieve
1048 * @return String Default option value
1050 public static function getDefaultOption( $opt ) {
1051 $defOpts = self::getDefaultOptions();
1052 if( isset( $defOpts[$opt] ) ) {
1053 return $defOpts[$opt];
1054 } else {
1055 return null;
1061 * Get blocking information
1062 * @private
1063 * @param $bFromSlave Bool Whether to check the slave database first. To
1064 * improve performance, non-critical checks are done
1065 * against slaves. Check when actually saving should be
1066 * done against master.
1068 function getBlockedStatus( $bFromSlave = true ) {
1069 global $wgProxyWhitelist, $wgUser;
1071 if ( -1 != $this->mBlockedby ) {
1072 return;
1075 wfProfileIn( __METHOD__ );
1076 wfDebug( __METHOD__.": checking...\n" );
1078 // Initialize data...
1079 // Otherwise something ends up stomping on $this->mBlockedby when
1080 // things get lazy-loaded later, causing false positive block hits
1081 // due to -1 !== 0. Probably session-related... Nothing should be
1082 // overwriting mBlockedby, surely?
1083 $this->load();
1085 $this->mBlockedby = 0;
1086 $this->mHideName = 0;
1087 $this->mAllowUsertalk = 0;
1089 # Check if we are looking at an IP or a logged-in user
1090 if ( $this->isIP( $this->getName() ) ) {
1091 $ip = $this->getName();
1092 } else {
1093 # Check if we are looking at the current user
1094 # If we don't, and the user is logged in, we don't know about
1095 # his IP / autoblock status, so ignore autoblock of current user's IP
1096 if ( $this->getID() != $wgUser->getID() ) {
1097 $ip = '';
1098 } else {
1099 # Get IP of current user
1100 $ip = wfGetIP();
1104 if ( $this->isAllowed( 'ipblock-exempt' ) ) {
1105 # Exempt from all types of IP-block
1106 $ip = '';
1109 # User/IP blocking
1110 $this->mBlock = new Block();
1111 $this->mBlock->fromMaster( !$bFromSlave );
1112 if ( $this->mBlock->load( $ip , $this->mId ) ) {
1113 wfDebug( __METHOD__ . ": Found block.\n" );
1114 $this->mBlockedby = $this->mBlock->mBy;
1115 if( $this->mBlockedby == 0 )
1116 $this->mBlockedby = $this->mBlock->mByName;
1117 $this->mBlockreason = $this->mBlock->mReason;
1118 $this->mHideName = $this->mBlock->mHideName;
1119 $this->mAllowUsertalk = $this->mBlock->mAllowUsertalk;
1120 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1121 $this->spreadBlock();
1123 } else {
1124 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1125 // apply to users. Note that the existence of $this->mBlock is not used to
1126 // check for edit blocks, $this->mBlockedby is instead.
1129 # Proxy blocking
1130 if ( !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1131 # Local list
1132 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1133 $this->mBlockedby = wfMsg( 'proxyblocker' );
1134 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1137 # DNSBL
1138 if ( !$this->mBlockedby && !$this->getID() ) {
1139 if ( $this->isDnsBlacklisted( $ip ) ) {
1140 $this->mBlockedby = wfMsg( 'sorbs' );
1141 $this->mBlockreason = wfMsg( 'sorbsreason' );
1146 # Extensions
1147 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1149 wfProfileOut( __METHOD__ );
1153 * Whether the given IP is in a DNS blacklist.
1155 * @param $ip String IP to check
1156 * @param $checkWhitelist Bool: whether to check the whitelist first
1157 * @return Bool True if blacklisted.
1159 function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1160 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1161 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1163 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1164 return false;
1166 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1167 return false;
1169 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1170 return $this->inDnsBlacklist( $ip, $urls );
1174 * Whether the given IP is in a given DNS blacklist.
1176 * @param $ip String IP to check
1177 * @param $bases String|Array of Strings: URL of the DNS blacklist
1178 * @return Bool True if blacklisted.
1180 function inDnsBlacklist( $ip, $bases ) {
1181 wfProfileIn( __METHOD__ );
1183 $found = false;
1184 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1185 if( IP::isIPv4( $ip ) ) {
1186 # Reverse IP, bug 21255
1187 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1189 foreach( (array)$bases as $base ) {
1190 # Make hostname
1191 $host = "$ipReversed.$base";
1193 # Send query
1194 $ipList = gethostbynamel( $host );
1196 if( $ipList ) {
1197 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1198 $found = true;
1199 break;
1200 } else {
1201 wfDebug( "Requested $host, not found in $base.\n" );
1206 wfProfileOut( __METHOD__ );
1207 return $found;
1211 * Is this user subject to rate limiting?
1213 * @return Bool True if rate limited
1215 public function isPingLimitable() {
1216 global $wgRateLimitsExcludedGroups;
1217 global $wgRateLimitsExcludedIPs;
1218 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1219 // Deprecated, but kept for backwards-compatibility config
1220 return false;
1222 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1223 // No other good way currently to disable rate limits
1224 // for specific IPs. :P
1225 // But this is a crappy hack and should die.
1226 return false;
1228 return !$this->isAllowed('noratelimit');
1232 * Primitive rate limits: enforce maximum actions per time period
1233 * to put a brake on flooding.
1235 * @note When using a shared cache like memcached, IP-address
1236 * last-hit counters will be shared across wikis.
1238 * @param $action String Action to enforce; 'edit' if unspecified
1239 * @return Bool True if a rate limiter was tripped
1241 function pingLimiter( $action = 'edit' ) {
1242 # Call the 'PingLimiter' hook
1243 $result = false;
1244 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1245 return $result;
1248 global $wgRateLimits;
1249 if( !isset( $wgRateLimits[$action] ) ) {
1250 return false;
1253 # Some groups shouldn't trigger the ping limiter, ever
1254 if( !$this->isPingLimitable() )
1255 return false;
1257 global $wgMemc, $wgRateLimitLog;
1258 wfProfileIn( __METHOD__ );
1260 $limits = $wgRateLimits[$action];
1261 $keys = array();
1262 $id = $this->getId();
1263 $ip = wfGetIP();
1264 $userLimit = false;
1266 if( isset( $limits['anon'] ) && $id == 0 ) {
1267 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1270 if( isset( $limits['user'] ) && $id != 0 ) {
1271 $userLimit = $limits['user'];
1273 if( $this->isNewbie() ) {
1274 if( isset( $limits['newbie'] ) && $id != 0 ) {
1275 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1277 if( isset( $limits['ip'] ) ) {
1278 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1280 $matches = array();
1281 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1282 $subnet = $matches[1];
1283 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1286 // Check for group-specific permissions
1287 // If more than one group applies, use the group with the highest limit
1288 foreach ( $this->getGroups() as $group ) {
1289 if ( isset( $limits[$group] ) ) {
1290 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1291 $userLimit = $limits[$group];
1295 // Set the user limit key
1296 if ( $userLimit !== false ) {
1297 wfDebug( __METHOD__ . ": effective user limit: $userLimit\n" );
1298 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1301 $triggered = false;
1302 foreach( $keys as $key => $limit ) {
1303 list( $max, $period ) = $limit;
1304 $summary = "(limit $max in {$period}s)";
1305 $count = $wgMemc->get( $key );
1306 // Already pinged?
1307 if( $count ) {
1308 if( $count > $max ) {
1309 wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
1310 if( $wgRateLimitLog ) {
1311 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1313 $triggered = true;
1314 } else {
1315 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1317 } else {
1318 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1319 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1321 $wgMemc->incr( $key );
1324 wfProfileOut( __METHOD__ );
1325 return $triggered;
1329 * Check if user is blocked
1331 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1332 * @return Bool True if blocked, false otherwise
1334 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1335 $this->getBlockedStatus( $bFromSlave );
1336 return $this->mBlockedby !== 0;
1340 * Check if user is blocked from editing a particular article
1342 * @param $title Title to check
1343 * @param $bFromSlave Bool whether to check the slave database instead of the master
1344 * @return Bool
1346 function isBlockedFrom( $title, $bFromSlave = false ) {
1347 global $wgBlockAllowsUTEdit;
1348 wfProfileIn( __METHOD__ );
1350 $blocked = $this->isBlocked( $bFromSlave );
1351 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1352 # If a user's name is suppressed, they cannot make edits anywhere
1353 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1354 $title->getNamespace() == NS_USER_TALK ) {
1355 $blocked = false;
1356 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1359 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1361 wfProfileOut( __METHOD__ );
1362 return $blocked;
1366 * If user is blocked, return the name of the user who placed the block
1367 * @return String name of blocker
1369 function blockedBy() {
1370 $this->getBlockedStatus();
1371 return $this->mBlockedby;
1375 * If user is blocked, return the specified reason for the block
1376 * @return String Blocking reason
1378 function blockedFor() {
1379 $this->getBlockedStatus();
1380 return $this->mBlockreason;
1384 * If user is blocked, return the ID for the block
1385 * @return Int Block ID
1387 function getBlockId() {
1388 $this->getBlockedStatus();
1389 return ( $this->mBlock ? $this->mBlock->mId : false );
1393 * Check if user is blocked on all wikis.
1394 * Do not use for actual edit permission checks!
1395 * This is intented for quick UI checks.
1397 * @param $ip String IP address, uses current client if none given
1398 * @return Bool True if blocked, false otherwise
1400 function isBlockedGlobally( $ip = '' ) {
1401 if( $this->mBlockedGlobally !== null ) {
1402 return $this->mBlockedGlobally;
1404 // User is already an IP?
1405 if( IP::isIPAddress( $this->getName() ) ) {
1406 $ip = $this->getName();
1407 } else if( !$ip ) {
1408 $ip = wfGetIP();
1410 $blocked = false;
1411 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1412 $this->mBlockedGlobally = (bool)$blocked;
1413 return $this->mBlockedGlobally;
1417 * Check if user account is locked
1419 * @return Bool True if locked, false otherwise
1421 function isLocked() {
1422 if( $this->mLocked !== null ) {
1423 return $this->mLocked;
1425 global $wgAuth;
1426 $authUser = $wgAuth->getUserInstance( $this );
1427 $this->mLocked = (bool)$authUser->isLocked();
1428 return $this->mLocked;
1432 * Check if user account is hidden
1434 * @return Bool True if hidden, false otherwise
1436 function isHidden() {
1437 if( $this->mHideName !== null ) {
1438 return $this->mHideName;
1440 $this->getBlockedStatus();
1441 if( !$this->mHideName ) {
1442 global $wgAuth;
1443 $authUser = $wgAuth->getUserInstance( $this );
1444 $this->mHideName = (bool)$authUser->isHidden();
1446 return $this->mHideName;
1450 * Get the user's ID.
1451 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1453 function getId() {
1454 if( $this->mId === null and $this->mName !== null
1455 and User::isIP( $this->mName ) ) {
1456 // Special case, we know the user is anonymous
1457 return 0;
1458 } elseif( $this->mId === null ) {
1459 // Don't load if this was initialized from an ID
1460 $this->load();
1462 return $this->mId;
1466 * Set the user and reload all fields according to a given ID
1467 * @param $v Int User ID to reload
1469 function setId( $v ) {
1470 $this->mId = $v;
1471 $this->clearInstanceCache( 'id' );
1475 * Get the user name, or the IP of an anonymous user
1476 * @return String User's name or IP address
1478 function getName() {
1479 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1480 # Special case optimisation
1481 return $this->mName;
1482 } else {
1483 $this->load();
1484 if ( $this->mName === false ) {
1485 # Clean up IPs
1486 $this->mName = IP::sanitizeIP( wfGetIP() );
1488 return $this->mName;
1493 * Set the user name.
1495 * This does not reload fields from the database according to the given
1496 * name. Rather, it is used to create a temporary "nonexistent user" for
1497 * later addition to the database. It can also be used to set the IP
1498 * address for an anonymous user to something other than the current
1499 * remote IP.
1501 * @note User::newFromName() has rougly the same function, when the named user
1502 * does not exist.
1503 * @param $str String New user name to set
1505 function setName( $str ) {
1506 $this->load();
1507 $this->mName = $str;
1511 * Get the user's name escaped by underscores.
1512 * @return String Username escaped by underscores.
1514 function getTitleKey() {
1515 return str_replace( ' ', '_', $this->getName() );
1519 * Check if the user has new messages.
1520 * @return Bool True if the user has new messages
1522 function getNewtalk() {
1523 $this->load();
1525 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1526 if( $this->mNewtalk === -1 ) {
1527 $this->mNewtalk = false; # reset talk page status
1529 # Check memcached separately for anons, who have no
1530 # entire User object stored in there.
1531 if( !$this->mId ) {
1532 global $wgMemc;
1533 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1534 $newtalk = $wgMemc->get( $key );
1535 if( strval( $newtalk ) !== '' ) {
1536 $this->mNewtalk = (bool)$newtalk;
1537 } else {
1538 // Since we are caching this, make sure it is up to date by getting it
1539 // from the master
1540 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1541 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1543 } else {
1544 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1548 return (bool)$this->mNewtalk;
1552 * Return the talk page(s) this user has new messages on.
1553 * @return Array of String page URLs
1555 function getNewMessageLinks() {
1556 $talks = array();
1557 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1558 return $talks;
1560 if( !$this->getNewtalk() )
1561 return array();
1562 $up = $this->getUserPage();
1563 $utp = $up->getTalkPage();
1564 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1568 * Internal uncached check for new messages
1570 * @see getNewtalk()
1571 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1572 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1573 * @param $fromMaster Bool true to fetch from the master, false for a slave
1574 * @return Bool True if the user has new messages
1575 * @private
1577 function checkNewtalk( $field, $id, $fromMaster = false ) {
1578 if ( $fromMaster ) {
1579 $db = wfGetDB( DB_MASTER );
1580 } else {
1581 $db = wfGetDB( DB_SLAVE );
1583 $ok = $db->selectField( 'user_newtalk', $field,
1584 array( $field => $id ), __METHOD__ );
1585 return $ok !== false;
1589 * Add or update the new messages flag
1590 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1591 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1592 * @return Bool True if successful, false otherwise
1593 * @private
1595 function updateNewtalk( $field, $id ) {
1596 $dbw = wfGetDB( DB_MASTER );
1597 $dbw->insert( 'user_newtalk',
1598 array( $field => $id ),
1599 __METHOD__,
1600 'IGNORE' );
1601 if ( $dbw->affectedRows() ) {
1602 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
1603 return true;
1604 } else {
1605 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
1606 return false;
1611 * Clear the new messages flag for the given user
1612 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1613 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1614 * @return Bool True if successful, false otherwise
1615 * @private
1617 function deleteNewtalk( $field, $id ) {
1618 $dbw = wfGetDB( DB_MASTER );
1619 $dbw->delete( 'user_newtalk',
1620 array( $field => $id ),
1621 __METHOD__ );
1622 if ( $dbw->affectedRows() ) {
1623 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
1624 return true;
1625 } else {
1626 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
1627 return false;
1632 * Update the 'You have new messages!' status.
1633 * @param $val Bool Whether the user has new messages
1635 function setNewtalk( $val ) {
1636 if( wfReadOnly() ) {
1637 return;
1640 $this->load();
1641 $this->mNewtalk = $val;
1643 if( $this->isAnon() ) {
1644 $field = 'user_ip';
1645 $id = $this->getName();
1646 } else {
1647 $field = 'user_id';
1648 $id = $this->getId();
1650 global $wgMemc;
1652 if( $val ) {
1653 $changed = $this->updateNewtalk( $field, $id );
1654 } else {
1655 $changed = $this->deleteNewtalk( $field, $id );
1658 if( $this->isAnon() ) {
1659 // Anons have a separate memcached space, since
1660 // user records aren't kept for them.
1661 $key = wfMemcKey( 'newtalk', 'ip', $id );
1662 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1664 if ( $changed ) {
1665 $this->invalidateCache();
1670 * Generate a current or new-future timestamp to be stored in the
1671 * user_touched field when we update things.
1672 * @return String Timestamp in TS_MW format
1674 private static function newTouchedTimestamp() {
1675 global $wgClockSkewFudge;
1676 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1680 * Clear user data from memcached.
1681 * Use after applying fun updates to the database; caller's
1682 * responsibility to update user_touched if appropriate.
1684 * Called implicitly from invalidateCache() and saveSettings().
1686 private function clearSharedCache() {
1687 $this->load();
1688 if( $this->mId ) {
1689 global $wgMemc;
1690 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1695 * Immediately touch the user data cache for this account.
1696 * Updates user_touched field, and removes account data from memcached
1697 * for reload on the next hit.
1699 function invalidateCache() {
1700 if( wfReadOnly() ) {
1701 return;
1703 $this->load();
1704 if( $this->mId ) {
1705 $this->mTouched = self::newTouchedTimestamp();
1707 $dbw = wfGetDB( DB_MASTER );
1708 $dbw->update( 'user',
1709 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1710 array( 'user_id' => $this->mId ),
1711 __METHOD__ );
1713 $this->clearSharedCache();
1718 * Validate the cache for this account.
1719 * @param $timestamp String A timestamp in TS_MW format
1721 function validateCache( $timestamp ) {
1722 $this->load();
1723 return ( $timestamp >= $this->mTouched );
1727 * Get the user touched timestamp
1728 * @return String timestamp
1730 function getTouched() {
1731 $this->load();
1732 return $this->mTouched;
1736 * Set the password and reset the random token.
1737 * Calls through to authentication plugin if necessary;
1738 * will have no effect if the auth plugin refuses to
1739 * pass the change through or if the legal password
1740 * checks fail.
1742 * As a special case, setting the password to null
1743 * wipes it, so the account cannot be logged in until
1744 * a new password is set, for instance via e-mail.
1746 * @param $str String New password to set
1747 * @throws PasswordError on failure
1749 function setPassword( $str ) {
1750 global $wgAuth;
1752 if( $str !== null ) {
1753 if( !$wgAuth->allowPasswordChange() ) {
1754 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1757 if( !$this->isValidPassword( $str ) ) {
1758 global $wgMinimalPasswordLength;
1759 $valid = $this->getPasswordValidity( $str );
1760 throw new PasswordError( wfMsgExt( $valid, array( 'parsemag' ),
1761 $wgMinimalPasswordLength ) );
1765 if( !$wgAuth->setPassword( $this, $str ) ) {
1766 throw new PasswordError( wfMsg( 'externaldberror' ) );
1769 $this->setInternalPassword( $str );
1771 return true;
1775 * Set the password and reset the random token unconditionally.
1777 * @param $str String New password to set
1779 function setInternalPassword( $str ) {
1780 $this->load();
1781 $this->setToken();
1783 if( $str === null ) {
1784 // Save an invalid hash...
1785 $this->mPassword = '';
1786 } else {
1787 $this->mPassword = self::crypt( $str );
1789 $this->mNewpassword = '';
1790 $this->mNewpassTime = null;
1794 * Get the user's current token.
1795 * @return String Token
1797 function getToken() {
1798 $this->load();
1799 return $this->mToken;
1803 * Set the random token (used for persistent authentication)
1804 * Called from loadDefaults() among other places.
1806 * @param $token String If specified, set the token to this value
1807 * @private
1809 function setToken( $token = false ) {
1810 global $wgSecretKey, $wgProxyKey;
1811 $this->load();
1812 if ( !$token ) {
1813 if ( $wgSecretKey ) {
1814 $key = $wgSecretKey;
1815 } elseif ( $wgProxyKey ) {
1816 $key = $wgProxyKey;
1817 } else {
1818 $key = microtime();
1820 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1821 } else {
1822 $this->mToken = $token;
1827 * Set the cookie password
1829 * @param $str String New cookie password
1830 * @private
1832 function setCookiePassword( $str ) {
1833 $this->load();
1834 $this->mCookiePassword = md5( $str );
1838 * Set the password for a password reminder or new account email
1840 * @param $str String New password to set
1841 * @param $throttle Bool If true, reset the throttle timestamp to the present
1843 function setNewpassword( $str, $throttle = true ) {
1844 $this->load();
1845 $this->mNewpassword = self::crypt( $str );
1846 if ( $throttle ) {
1847 $this->mNewpassTime = wfTimestampNow();
1852 * Has password reminder email been sent within the last
1853 * $wgPasswordReminderResendTime hours?
1854 * @return Bool
1856 function isPasswordReminderThrottled() {
1857 global $wgPasswordReminderResendTime;
1858 $this->load();
1859 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1860 return false;
1862 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1863 return time() < $expiry;
1867 * Get the user's e-mail address
1868 * @return String User's email address
1870 function getEmail() {
1871 $this->load();
1872 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1873 return $this->mEmail;
1877 * Get the timestamp of the user's e-mail authentication
1878 * @return String TS_MW timestamp
1880 function getEmailAuthenticationTimestamp() {
1881 $this->load();
1882 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1883 return $this->mEmailAuthenticated;
1887 * Set the user's e-mail address
1888 * @param $str String New e-mail address
1890 function setEmail( $str ) {
1891 $this->load();
1892 $this->mEmail = $str;
1893 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1897 * Get the user's real name
1898 * @return String User's real name
1900 function getRealName() {
1901 $this->load();
1902 return $this->mRealName;
1906 * Set the user's real name
1907 * @param $str String New real name
1909 function setRealName( $str ) {
1910 $this->load();
1911 $this->mRealName = $str;
1915 * Get the user's current setting for a given option.
1917 * @param $oname String The option to check
1918 * @param $defaultOverride String A default value returned if the option does not exist
1919 * @return String User's current value for the option
1920 * @see getBoolOption()
1921 * @see getIntOption()
1923 function getOption( $oname, $defaultOverride = null ) {
1924 $this->loadOptions();
1926 if ( is_null( $this->mOptions ) ) {
1927 if($defaultOverride != '') {
1928 return $defaultOverride;
1930 $this->mOptions = User::getDefaultOptions();
1933 if ( array_key_exists( $oname, $this->mOptions ) ) {
1934 return $this->mOptions[$oname];
1935 } else {
1936 return $defaultOverride;
1941 * Get all user's options
1943 * @return array
1945 public function getOptions() {
1946 $this->loadOptions();
1947 return $this->mOptions;
1951 * Get the user's current setting for a given option, as a boolean value.
1953 * @param $oname String The option to check
1954 * @return Bool User's current value for the option
1955 * @see getOption()
1957 function getBoolOption( $oname ) {
1958 return (bool)$this->getOption( $oname );
1963 * Get the user's current setting for a given option, as a boolean value.
1965 * @param $oname String The option to check
1966 * @param $defaultOverride Int A default value returned if the option does not exist
1967 * @return Int User's current value for the option
1968 * @see getOption()
1970 function getIntOption( $oname, $defaultOverride=0 ) {
1971 $val = $this->getOption( $oname );
1972 if( $val == '' ) {
1973 $val = $defaultOverride;
1975 return intval( $val );
1979 * Set the given option for a user.
1981 * @param $oname String The option to set
1982 * @param $val mixed New value to set
1984 function setOption( $oname, $val ) {
1985 $this->load();
1986 $this->loadOptions();
1988 if ( $oname == 'skin' ) {
1989 # Clear cached skin, so the new one displays immediately in Special:Preferences
1990 $this->mSkin = null;
1993 // Explicitly NULL values should refer to defaults
1994 global $wgDefaultUserOptions;
1995 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
1996 $val = $wgDefaultUserOptions[$oname];
1999 $this->mOptions[$oname] = $val;
2003 * Reset all options to the site defaults
2005 function resetOptions() {
2006 $this->mOptions = User::getDefaultOptions();
2010 * Get the user's preferred date format.
2011 * @return String User's preferred date format
2013 function getDatePreference() {
2014 // Important migration for old data rows
2015 if ( is_null( $this->mDatePreference ) ) {
2016 global $wgLang;
2017 $value = $this->getOption( 'date' );
2018 $map = $wgLang->getDatePreferenceMigrationMap();
2019 if ( isset( $map[$value] ) ) {
2020 $value = $map[$value];
2022 $this->mDatePreference = $value;
2024 return $this->mDatePreference;
2028 * Get the user preferred stub threshold
2030 function getStubThreshold() {
2031 global $wgMaxArticleSize; # Maximum article size, in Kb
2032 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2033 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2034 # If they have set an impossible value, disable the preference
2035 # so we can use the parser cache again.
2036 $threshold = 0;
2038 return $threshold;
2042 * Get the permissions this user has.
2043 * @return Array of String permission names
2045 function getRights() {
2046 if ( is_null( $this->mRights ) ) {
2047 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2048 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2049 // Force reindexation of rights when a hook has unset one of them
2050 $this->mRights = array_values( $this->mRights );
2052 return $this->mRights;
2056 * Get the list of explicit group memberships this user has.
2057 * The implicit * and user groups are not included.
2058 * @return Array of String internal group names
2060 function getGroups() {
2061 $this->load();
2062 return $this->mGroups;
2066 * Get the list of implicit group memberships this user has.
2067 * This includes all explicit groups, plus 'user' if logged in,
2068 * '*' for all accounts, and autopromoted groups
2069 * @param $recache Bool Whether to avoid the cache
2070 * @return Array of String internal group names
2072 function getEffectiveGroups( $recache = false ) {
2073 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2074 wfProfileIn( __METHOD__ );
2075 $this->mEffectiveGroups = $this->getGroups();
2076 $this->mEffectiveGroups[] = '*';
2077 if( $this->getId() ) {
2078 $this->mEffectiveGroups[] = 'user';
2080 $this->mEffectiveGroups = array_unique( array_merge(
2081 $this->mEffectiveGroups,
2082 Autopromote::getAutopromoteGroups( $this )
2083 ) );
2085 # Hook for additional groups
2086 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2088 wfProfileOut( __METHOD__ );
2090 return $this->mEffectiveGroups;
2094 * Get the user's edit count.
2095 * @return Int
2097 function getEditCount() {
2098 if( $this->getId() ) {
2099 if ( !isset( $this->mEditCount ) ) {
2100 /* Populate the count, if it has not been populated yet */
2101 $this->mEditCount = User::edits( $this->mId );
2103 return $this->mEditCount;
2104 } else {
2105 /* nil */
2106 return null;
2111 * Add the user to the given group.
2112 * This takes immediate effect.
2113 * @param $group String Name of the group to add
2115 function addGroup( $group ) {
2116 $dbw = wfGetDB( DB_MASTER );
2117 if( $this->getId() ) {
2118 $dbw->insert( 'user_groups',
2119 array(
2120 'ug_user' => $this->getID(),
2121 'ug_group' => $group,
2123 __METHOD__,
2124 array( 'IGNORE' ) );
2127 $this->loadGroups();
2128 $this->mGroups[] = $group;
2129 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2131 $this->invalidateCache();
2135 * Remove the user from the given group.
2136 * This takes immediate effect.
2137 * @param $group String Name of the group to remove
2139 function removeGroup( $group ) {
2140 $this->load();
2141 $dbw = wfGetDB( DB_MASTER );
2142 $dbw->delete( 'user_groups',
2143 array(
2144 'ug_user' => $this->getID(),
2145 'ug_group' => $group,
2146 ), __METHOD__ );
2148 $this->loadGroups();
2149 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2150 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2152 $this->invalidateCache();
2156 * Get whether the user is logged in
2157 * @return Bool
2159 function isLoggedIn() {
2160 return $this->getID() != 0;
2164 * Get whether the user is anonymous
2165 * @return Bool
2167 function isAnon() {
2168 return !$this->isLoggedIn();
2172 * Check if user is allowed to access a feature / make an action
2173 * @param $action String action to be checked
2174 * @return Boolean: True if action is allowed, else false
2176 function isAllowed( $action = '' ) {
2177 if ( $action === '' ) {
2178 return true; // In the spirit of DWIM
2180 # Patrolling may not be enabled
2181 if( $action === 'patrol' || $action === 'autopatrol' ) {
2182 global $wgUseRCPatrol, $wgUseNPPatrol;
2183 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2184 return false;
2186 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2187 # by misconfiguration: 0 == 'foo'
2188 return in_array( $action, $this->getRights(), true );
2192 * Check whether to enable recent changes patrol features for this user
2193 * @return Boolean: True or false
2195 public function useRCPatrol() {
2196 global $wgUseRCPatrol;
2197 return( $wgUseRCPatrol && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2201 * Check whether to enable new pages patrol features for this user
2202 * @return Bool True or false
2204 public function useNPPatrol() {
2205 global $wgUseRCPatrol, $wgUseNPPatrol;
2206 return( ( $wgUseRCPatrol || $wgUseNPPatrol ) && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2210 * Get the current skin, loading it if required, and setting a title
2211 * @param $t Title: the title to use in the skin
2212 * @return Skin The current skin
2213 * @todo: FIXME : need to check the old failback system [AV]
2215 function getSkin( $t = null ) {
2216 if ( $t ) {
2217 $skin = $this->createSkinObject();
2218 $skin->setTitle( $t );
2219 return $skin;
2220 } else {
2221 if ( !$this->mSkin ) {
2222 $this->mSkin = $this->createSkinObject();
2225 if ( !$this->mSkin->getTitle() ) {
2226 global $wgOut;
2227 $t = $wgOut->getTitle();
2228 $this->mSkin->setTitle($t);
2231 return $this->mSkin;
2235 // Creates a Skin object, for getSkin()
2236 private function createSkinObject() {
2237 wfProfileIn( __METHOD__ );
2239 global $wgHiddenPrefs;
2240 if( !in_array( 'skin', $wgHiddenPrefs ) ) {
2241 global $wgRequest;
2242 # get the user skin
2243 $userSkin = $this->getOption( 'skin' );
2244 $userSkin = $wgRequest->getVal( 'useskin', $userSkin );
2245 } else {
2246 # if we're not allowing users to override, then use the default
2247 global $wgDefaultSkin;
2248 $userSkin = $wgDefaultSkin;
2251 $skin = Skin::newFromKey( $userSkin );
2252 wfProfileOut( __METHOD__ );
2254 return $skin;
2258 * Check the watched status of an article.
2259 * @param $title Title of the article to look at
2260 * @return Bool
2262 function isWatched( $title ) {
2263 $wl = WatchedItem::fromUserTitle( $this, $title );
2264 return $wl->isWatched();
2268 * Watch an article.
2269 * @param $title Title of the article to look at
2271 function addWatch( $title ) {
2272 $wl = WatchedItem::fromUserTitle( $this, $title );
2273 $wl->addWatch();
2274 $this->invalidateCache();
2278 * Stop watching an article.
2279 * @param $title Title of the article to look at
2281 function removeWatch( $title ) {
2282 $wl = WatchedItem::fromUserTitle( $this, $title );
2283 $wl->removeWatch();
2284 $this->invalidateCache();
2288 * Clear the user's notification timestamp for the given title.
2289 * If e-notif e-mails are on, they will receive notification mails on
2290 * the next change of the page if it's watched etc.
2291 * @param $title Title of the article to look at
2293 function clearNotification( &$title ) {
2294 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2296 # Do nothing if the database is locked to writes
2297 if( wfReadOnly() ) {
2298 return;
2301 if( $title->getNamespace() == NS_USER_TALK &&
2302 $title->getText() == $this->getName() ) {
2303 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2304 return;
2305 $this->setNewtalk( false );
2308 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2309 return;
2312 if( $this->isAnon() ) {
2313 // Nothing else to do...
2314 return;
2317 // Only update the timestamp if the page is being watched.
2318 // The query to find out if it is watched is cached both in memcached and per-invocation,
2319 // and when it does have to be executed, it can be on a slave
2320 // If this is the user's newtalk page, we always update the timestamp
2321 if( $title->getNamespace() == NS_USER_TALK &&
2322 $title->getText() == $wgUser->getName() )
2324 $watched = true;
2325 } elseif ( $this->getId() == $wgUser->getId() ) {
2326 $watched = $title->userIsWatching();
2327 } else {
2328 $watched = true;
2331 // If the page is watched by the user (or may be watched), update the timestamp on any
2332 // any matching rows
2333 if ( $watched ) {
2334 $dbw = wfGetDB( DB_MASTER );
2335 $dbw->update( 'watchlist',
2336 array( /* SET */
2337 'wl_notificationtimestamp' => null
2338 ), array( /* WHERE */
2339 'wl_title' => $title->getDBkey(),
2340 'wl_namespace' => $title->getNamespace(),
2341 'wl_user' => $this->getID()
2342 ), __METHOD__
2348 * Resets all of the given user's page-change notification timestamps.
2349 * If e-notif e-mails are on, they will receive notification mails on
2350 * the next change of any watched page.
2352 * @param $currentUser Int User ID
2354 function clearAllNotifications( $currentUser ) {
2355 global $wgUseEnotif, $wgShowUpdatedMarker;
2356 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2357 $this->setNewtalk( false );
2358 return;
2360 if( $currentUser != 0 ) {
2361 $dbw = wfGetDB( DB_MASTER );
2362 $dbw->update( 'watchlist',
2363 array( /* SET */
2364 'wl_notificationtimestamp' => null
2365 ), array( /* WHERE */
2366 'wl_user' => $currentUser
2367 ), __METHOD__
2369 # We also need to clear here the "you have new message" notification for the own user_talk page
2370 # This is cleared one page view later in Article::viewUpdates();
2375 * Set this user's options from an encoded string
2376 * @param $str String Encoded options to import
2377 * @private
2379 function decodeOptions( $str ) {
2380 if( !$str )
2381 return;
2383 $this->mOptionsLoaded = true;
2384 $this->mOptionOverrides = array();
2386 // If an option is not set in $str, use the default value
2387 $this->mOptions = self::getDefaultOptions();
2389 $a = explode( "\n", $str );
2390 foreach ( $a as $s ) {
2391 $m = array();
2392 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2393 $this->mOptions[$m[1]] = $m[2];
2394 $this->mOptionOverrides[$m[1]] = $m[2];
2400 * Set a cookie on the user's client. Wrapper for
2401 * WebResponse::setCookie
2402 * @param $name String Name of the cookie to set
2403 * @param $value String Value to set
2404 * @param $exp Int Expiration time, as a UNIX time value;
2405 * if 0 or not specified, use the default $wgCookieExpiration
2407 protected function setCookie( $name, $value, $exp = 0 ) {
2408 global $wgRequest;
2409 $wgRequest->response()->setcookie( $name, $value, $exp );
2413 * Clear a cookie on the user's client
2414 * @param $name String Name of the cookie to clear
2416 protected function clearCookie( $name ) {
2417 $this->setCookie( $name, '', time() - 86400 );
2421 * Set the default cookies for this session on the user's client.
2423 function setCookies() {
2424 $this->load();
2425 if ( 0 == $this->mId ) return;
2426 $session = array(
2427 'wsUserID' => $this->mId,
2428 'wsToken' => $this->mToken,
2429 'wsUserName' => $this->getName()
2431 $cookies = array(
2432 'UserID' => $this->mId,
2433 'UserName' => $this->getName(),
2435 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2436 $cookies['Token'] = $this->mToken;
2437 } else {
2438 $cookies['Token'] = false;
2441 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2442 #check for null, since the hook could cause a null value
2443 if ( !is_null( $session ) && isset( $_SESSION ) ){
2444 $_SESSION = $session + $_SESSION;
2446 foreach ( $cookies as $name => $value ) {
2447 if ( $value === false ) {
2448 $this->clearCookie( $name );
2449 } else {
2450 $this->setCookie( $name, $value );
2456 * Log this user out.
2458 function logout() {
2459 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2460 $this->doLogout();
2465 * Clear the user's cookies and session, and reset the instance cache.
2466 * @private
2467 * @see logout()
2469 function doLogout() {
2470 $this->clearInstanceCache( 'defaults' );
2472 $_SESSION['wsUserID'] = 0;
2474 $this->clearCookie( 'UserID' );
2475 $this->clearCookie( 'Token' );
2477 # Remember when user logged out, to prevent seeing cached pages
2478 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2482 * Save this user's settings into the database.
2483 * @todo Only rarely do all these fields need to be set!
2485 function saveSettings() {
2486 $this->load();
2487 if ( wfReadOnly() ) { return; }
2488 if ( 0 == $this->mId ) { return; }
2490 $this->mTouched = self::newTouchedTimestamp();
2492 $dbw = wfGetDB( DB_MASTER );
2493 $dbw->update( 'user',
2494 array( /* SET */
2495 'user_name' => $this->mName,
2496 'user_password' => $this->mPassword,
2497 'user_newpassword' => $this->mNewpassword,
2498 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2499 'user_real_name' => $this->mRealName,
2500 'user_email' => $this->mEmail,
2501 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2502 'user_options' => '',
2503 'user_touched' => $dbw->timestamp( $this->mTouched ),
2504 'user_token' => $this->mToken,
2505 'user_email_token' => $this->mEmailToken,
2506 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2507 ), array( /* WHERE */
2508 'user_id' => $this->mId
2509 ), __METHOD__
2512 $this->saveOptions();
2514 wfRunHooks( 'UserSaveSettings', array( $this ) );
2515 $this->clearSharedCache();
2516 $this->getUserPage()->invalidateCache();
2520 * If only this user's username is known, and it exists, return the user ID.
2521 * @return Int
2523 function idForName() {
2524 $s = trim( $this->getName() );
2525 if ( $s === '' ) return 0;
2527 $dbr = wfGetDB( DB_SLAVE );
2528 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2529 if ( $id === false ) {
2530 $id = 0;
2532 return $id;
2536 * Add a user to the database, return the user object
2538 * @param $name String Username to add
2539 * @param $params Array of Strings Non-default parameters to save to the database:
2540 * - password The user's password. Password logins will be disabled if this is omitted.
2541 * - newpassword A temporary password mailed to the user
2542 * - email The user's email address
2543 * - email_authenticated The email authentication timestamp
2544 * - real_name The user's real name
2545 * - options An associative array of non-default options
2546 * - token Random authentication token. Do not set.
2547 * - registration Registration timestamp. Do not set.
2549 * @return User object, or null if the username already exists
2551 static function createNew( $name, $params = array() ) {
2552 $user = new User;
2553 $user->load();
2554 if ( isset( $params['options'] ) ) {
2555 $user->mOptions = $params['options'] + (array)$user->mOptions;
2556 unset( $params['options'] );
2558 $dbw = wfGetDB( DB_MASTER );
2559 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2561 $fields = array(
2562 'user_id' => $seqVal,
2563 'user_name' => $name,
2564 'user_password' => $user->mPassword,
2565 'user_newpassword' => $user->mNewpassword,
2566 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
2567 'user_email' => $user->mEmail,
2568 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2569 'user_real_name' => $user->mRealName,
2570 'user_options' => '',
2571 'user_token' => $user->mToken,
2572 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2573 'user_editcount' => 0,
2575 foreach ( $params as $name => $value ) {
2576 $fields["user_$name"] = $value;
2578 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2579 if ( $dbw->affectedRows() ) {
2580 $newUser = User::newFromId( $dbw->insertId() );
2581 } else {
2582 $newUser = null;
2584 return $newUser;
2588 * Add this existing user object to the database
2590 function addToDatabase() {
2591 $this->load();
2592 $dbw = wfGetDB( DB_MASTER );
2593 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2594 $dbw->insert( 'user',
2595 array(
2596 'user_id' => $seqVal,
2597 'user_name' => $this->mName,
2598 'user_password' => $this->mPassword,
2599 'user_newpassword' => $this->mNewpassword,
2600 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2601 'user_email' => $this->mEmail,
2602 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2603 'user_real_name' => $this->mRealName,
2604 'user_options' => '',
2605 'user_token' => $this->mToken,
2606 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2607 'user_editcount' => 0,
2608 ), __METHOD__
2610 $this->mId = $dbw->insertId();
2612 // Clear instance cache other than user table data, which is already accurate
2613 $this->clearInstanceCache();
2615 $this->saveOptions();
2619 * If this (non-anonymous) user is blocked, block any IP address
2620 * they've successfully logged in from.
2622 function spreadBlock() {
2623 wfDebug( __METHOD__ . "()\n" );
2624 $this->load();
2625 if ( $this->mId == 0 ) {
2626 return;
2629 $userblock = Block::newFromDB( '', $this->mId );
2630 if ( !$userblock ) {
2631 return;
2634 $userblock->doAutoblock( wfGetIP() );
2638 * Generate a string which will be different for any combination of
2639 * user options which would produce different parser output.
2640 * This will be used as part of the hash key for the parser cache,
2641 * so users with the same options can share the same cached data
2642 * safely.
2644 * Extensions which require it should install 'PageRenderingHash' hook,
2645 * which will give them a chance to modify this key based on their own
2646 * settings.
2648 * @deprecated @since 1.17 use the ParserOptions object to get the relevant options
2649 * @return String Page rendering hash
2651 function getPageRenderingHash() {
2652 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2653 if( $this->mHash ){
2654 return $this->mHash;
2656 wfDeprecated( __METHOD__ );
2658 // stubthreshold is only included below for completeness,
2659 // since it disables the parser cache, its value will always
2660 // be 0 when this function is called by parsercache.
2662 $confstr = $this->getOption( 'math' );
2663 $confstr .= '!' . $this->getStubThreshold();
2664 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2665 $confstr .= '!' . $this->getDatePreference();
2667 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
2668 $confstr .= '!' . $wgLang->getCode();
2669 $confstr .= '!' . $this->getOption( 'thumbsize' );
2670 // add in language specific options, if any
2671 $extra = $wgContLang->getExtraHashOptions();
2672 $confstr .= $extra;
2674 // Since the skin could be overloading link(), it should be
2675 // included here but in practice, none of our skins do that.
2677 $confstr .= $wgRenderHashAppend;
2679 // Give a chance for extensions to modify the hash, if they have
2680 // extra options or other effects on the parser cache.
2681 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2683 // Make it a valid memcached key fragment
2684 $confstr = str_replace( ' ', '_', $confstr );
2685 $this->mHash = $confstr;
2686 return $confstr;
2690 * Get whether the user is explicitly blocked from account creation.
2691 * @return Bool
2693 function isBlockedFromCreateAccount() {
2694 $this->getBlockedStatus();
2695 return $this->mBlock && $this->mBlock->mCreateAccount;
2699 * Get whether the user is blocked from using Special:Emailuser.
2700 * @return Bool
2702 function isBlockedFromEmailuser() {
2703 $this->getBlockedStatus();
2704 return $this->mBlock && $this->mBlock->mBlockEmail;
2708 * Get whether the user is allowed to create an account.
2709 * @return Bool
2711 function isAllowedToCreateAccount() {
2712 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2716 * Get this user's personal page title.
2718 * @return Title: User's personal page title
2720 function getUserPage() {
2721 return Title::makeTitle( NS_USER, $this->getName() );
2725 * Get this user's talk page title.
2727 * @return Title: User's talk page title
2729 function getTalkPage() {
2730 $title = $this->getUserPage();
2731 return $title->getTalkPage();
2735 * Get the maximum valid user ID.
2736 * @return Integer: User ID
2737 * @static
2739 function getMaxID() {
2740 static $res; // cache
2742 if ( isset( $res ) ) {
2743 return $res;
2744 } else {
2745 $dbr = wfGetDB( DB_SLAVE );
2746 return $res = $dbr->selectField( 'user', 'max(user_id)', false, __METHOD__ );
2751 * Determine whether the user is a newbie. Newbies are either
2752 * anonymous IPs, or the most recently created accounts.
2753 * @return Bool
2755 function isNewbie() {
2756 return !$this->isAllowed( 'autoconfirmed' );
2760 * Check to see if the given clear-text password is one of the accepted passwords
2761 * @param $password String: user password.
2762 * @return Boolean: True if the given password is correct, otherwise False.
2764 function checkPassword( $password ) {
2765 global $wgAuth;
2766 $this->load();
2768 // Even though we stop people from creating passwords that
2769 // are shorter than this, doesn't mean people wont be able
2770 // to. Certain authentication plugins do NOT want to save
2771 // domain passwords in a mysql database, so we should
2772 // check this (in case $wgAuth->strict() is false).
2773 if( !$this->isValidPassword( $password ) ) {
2774 return false;
2777 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2778 return true;
2779 } elseif( $wgAuth->strict() ) {
2780 /* Auth plugin doesn't allow local authentication */
2781 return false;
2782 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2783 /* Auth plugin doesn't allow local authentication for this user name */
2784 return false;
2786 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2787 return true;
2788 } elseif ( function_exists( 'iconv' ) ) {
2789 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2790 # Check for this with iconv
2791 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2792 if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
2793 return true;
2796 return false;
2800 * Check if the given clear-text password matches the temporary password
2801 * sent by e-mail for password reset operations.
2802 * @return Boolean: True if matches, false otherwise
2804 function checkTemporaryPassword( $plaintext ) {
2805 global $wgNewPasswordExpiry;
2806 if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
2807 if ( is_null( $this->mNewpassTime ) ) {
2808 return true;
2810 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
2811 return ( time() < $expiry );
2812 } else {
2813 return false;
2818 * Initialize (if necessary) and return a session token value
2819 * which can be used in edit forms to show that the user's
2820 * login credentials aren't being hijacked with a foreign form
2821 * submission.
2823 * @param $salt String|Array of Strings Optional function-specific data for hashing
2824 * @return String The new edit token
2826 function editToken( $salt = '' ) {
2827 if ( $this->isAnon() ) {
2828 return EDIT_TOKEN_SUFFIX;
2829 } else {
2830 if( !isset( $_SESSION['wsEditToken'] ) ) {
2831 $token = self::generateToken();
2832 $_SESSION['wsEditToken'] = $token;
2833 } else {
2834 $token = $_SESSION['wsEditToken'];
2836 if( is_array( $salt ) ) {
2837 $salt = implode( '|', $salt );
2839 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2844 * Generate a looking random token for various uses.
2846 * @param $salt String Optional salt value
2847 * @return String The new random token
2849 public static function generateToken( $salt = '' ) {
2850 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2851 return md5( $token . $salt );
2855 * Check given value against the token value stored in the session.
2856 * A match should confirm that the form was submitted from the
2857 * user's own login session, not a form submission from a third-party
2858 * site.
2860 * @param $val String Input value to compare
2861 * @param $salt String Optional function-specific data for hashing
2862 * @return Boolean: Whether the token matches
2864 function matchEditToken( $val, $salt = '' ) {
2865 $sessionToken = $this->editToken( $salt );
2866 if ( $val != $sessionToken ) {
2867 wfDebug( "User::matchEditToken: broken session data\n" );
2869 return $val == $sessionToken;
2873 * Check given value against the token value stored in the session,
2874 * ignoring the suffix.
2876 * @param $val String Input value to compare
2877 * @param $salt String Optional function-specific data for hashing
2878 * @return Boolean: Whether the token matches
2880 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2881 $sessionToken = $this->editToken( $salt );
2882 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2886 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2887 * mail to the user's given address.
2889 * @param $changed Boolean: whether the adress changed
2890 * @return Status object
2892 function sendConfirmationMail( $changed = false ) {
2893 global $wgLang;
2894 $expiration = null; // gets passed-by-ref and defined in next line.
2895 $token = $this->confirmationToken( $expiration );
2896 $url = $this->confirmationTokenUrl( $token );
2897 $invalidateURL = $this->invalidationTokenUrl( $token );
2898 $this->saveSettings();
2900 $message = $changed ? 'confirmemail_body_changed' : 'confirmemail_body';
2901 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2902 wfMsg( $message,
2903 wfGetIP(),
2904 $this->getName(),
2905 $url,
2906 $wgLang->timeanddate( $expiration, false ),
2907 $invalidateURL,
2908 $wgLang->date( $expiration, false ),
2909 $wgLang->time( $expiration, false ) ) );
2913 * Send an e-mail to this user's account. Does not check for
2914 * confirmed status or validity.
2916 * @param $subject String Message subject
2917 * @param $body String Message body
2918 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
2919 * @param $replyto String Reply-To address
2920 * @return Status
2922 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2923 if( is_null( $from ) ) {
2924 global $wgPasswordSender, $wgPasswordSenderName;
2925 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
2926 } else {
2927 $sender = new MailAddress( $from );
2930 $to = new MailAddress( $this );
2931 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2935 * Generate, store, and return a new e-mail confirmation code.
2936 * A hash (unsalted, since it's used as a key) is stored.
2938 * @note Call saveSettings() after calling this function to commit
2939 * this change to the database.
2941 * @param[out] &$expiration \mixed Accepts the expiration time
2942 * @return String New token
2943 * @private
2945 function confirmationToken( &$expiration ) {
2946 $now = time();
2947 $expires = $now + 7 * 24 * 60 * 60;
2948 $expiration = wfTimestamp( TS_MW, $expires );
2949 $token = self::generateToken( $this->mId . $this->mEmail . $expires );
2950 $hash = md5( $token );
2951 $this->load();
2952 $this->mEmailToken = $hash;
2953 $this->mEmailTokenExpires = $expiration;
2954 return $token;
2958 * Return a URL the user can use to confirm their email address.
2959 * @param $token String Accepts the email confirmation token
2960 * @return String New token URL
2961 * @private
2963 function confirmationTokenUrl( $token ) {
2964 return $this->getTokenUrl( 'ConfirmEmail', $token );
2968 * Return a URL the user can use to invalidate their email address.
2969 * @param $token String Accepts the email confirmation token
2970 * @return String New token URL
2971 * @private
2973 function invalidationTokenUrl( $token ) {
2974 return $this->getTokenUrl( 'Invalidateemail', $token );
2978 * Internal function to format the e-mail validation/invalidation URLs.
2979 * This uses $wgArticlePath directly as a quickie hack to use the
2980 * hardcoded English names of the Special: pages, for ASCII safety.
2982 * @note Since these URLs get dropped directly into emails, using the
2983 * short English names avoids insanely long URL-encoded links, which
2984 * also sometimes can get corrupted in some browsers/mailers
2985 * (bug 6957 with Gmail and Internet Explorer).
2987 * @param $page String Special page
2988 * @param $token String Token
2989 * @return String Formatted URL
2991 protected function getTokenUrl( $page, $token ) {
2992 global $wgArticlePath;
2993 return wfExpandUrl(
2994 str_replace(
2995 '$1',
2996 "Special:$page/$token",
2997 $wgArticlePath ) );
3001 * Mark the e-mail address confirmed.
3003 * @note Call saveSettings() after calling this function to commit the change.
3005 function confirmEmail() {
3006 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3007 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3008 return true;
3012 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3013 * address if it was already confirmed.
3015 * @note Call saveSettings() after calling this function to commit the change.
3017 function invalidateEmail() {
3018 $this->load();
3019 $this->mEmailToken = null;
3020 $this->mEmailTokenExpires = null;
3021 $this->setEmailAuthenticationTimestamp( null );
3022 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3023 return true;
3027 * Set the e-mail authentication timestamp.
3028 * @param $timestamp String TS_MW timestamp
3030 function setEmailAuthenticationTimestamp( $timestamp ) {
3031 $this->load();
3032 $this->mEmailAuthenticated = $timestamp;
3033 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
3037 * Is this user allowed to send e-mails within limits of current
3038 * site configuration?
3039 * @return Bool
3041 function canSendEmail() {
3042 global $wgEnableEmail, $wgEnableUserEmail;
3043 if( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
3044 return false;
3046 $canSend = $this->isEmailConfirmed();
3047 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3048 return $canSend;
3052 * Is this user allowed to receive e-mails within limits of current
3053 * site configuration?
3054 * @return Bool
3056 function canReceiveEmail() {
3057 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3061 * Is this user's e-mail address valid-looking and confirmed within
3062 * limits of the current site configuration?
3064 * @note If $wgEmailAuthentication is on, this may require the user to have
3065 * confirmed their address by returning a code or using a password
3066 * sent to the address from the wiki.
3068 * @return Bool
3070 function isEmailConfirmed() {
3071 global $wgEmailAuthentication;
3072 $this->load();
3073 $confirmed = true;
3074 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3075 if( $this->isAnon() )
3076 return false;
3077 if( !self::isValidEmailAddr( $this->mEmail ) )
3078 return false;
3079 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3080 return false;
3081 return true;
3082 } else {
3083 return $confirmed;
3088 * Check whether there is an outstanding request for e-mail confirmation.
3089 * @return Bool
3091 function isEmailConfirmationPending() {
3092 global $wgEmailAuthentication;
3093 return $wgEmailAuthentication &&
3094 !$this->isEmailConfirmed() &&
3095 $this->mEmailToken &&
3096 $this->mEmailTokenExpires > wfTimestamp();
3100 * Get the timestamp of account creation.
3102 * @return String|Bool Timestamp of account creation, or false for
3103 * non-existent/anonymous user accounts.
3105 public function getRegistration() {
3106 return $this->getId() > 0
3107 ? $this->mRegistration
3108 : false;
3112 * Get the timestamp of the first edit
3114 * @return String|Bool Timestamp of first edit, or false for
3115 * non-existent/anonymous user accounts.
3117 public function getFirstEditTimestamp() {
3118 if( $this->getId() == 0 ) {
3119 return false; // anons
3121 $dbr = wfGetDB( DB_SLAVE );
3122 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3123 array( 'rev_user' => $this->getId() ),
3124 __METHOD__,
3125 array( 'ORDER BY' => 'rev_timestamp ASC' )
3127 if( !$time ) {
3128 return false; // no edits
3130 return wfTimestamp( TS_MW, $time );
3134 * Get the permissions associated with a given list of groups
3136 * @param $groups Array of Strings List of internal group names
3137 * @return Array of Strings List of permission key names for given groups combined
3139 static function getGroupPermissions( $groups ) {
3140 global $wgGroupPermissions, $wgRevokePermissions;
3141 $rights = array();
3142 // grant every granted permission first
3143 foreach( $groups as $group ) {
3144 if( isset( $wgGroupPermissions[$group] ) ) {
3145 $rights = array_merge( $rights,
3146 // array_filter removes empty items
3147 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3150 // now revoke the revoked permissions
3151 foreach( $groups as $group ) {
3152 if( isset( $wgRevokePermissions[$group] ) ) {
3153 $rights = array_diff( $rights,
3154 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3157 return array_unique( $rights );
3161 * Get all the groups who have a given permission
3163 * @param $role String Role to check
3164 * @return Array of Strings List of internal group names with the given permission
3166 static function getGroupsWithPermission( $role ) {
3167 global $wgGroupPermissions;
3168 $allowedGroups = array();
3169 foreach ( $wgGroupPermissions as $group => $rights ) {
3170 if ( isset( $rights[$role] ) && $rights[$role] ) {
3171 $allowedGroups[] = $group;
3174 return $allowedGroups;
3178 * Get the localized descriptive name for a group, if it exists
3180 * @param $group String Internal group name
3181 * @return String Localized descriptive group name
3183 static function getGroupName( $group ) {
3184 $key = "group-$group";
3185 $name = wfMsg( $key );
3186 return $name == '' || wfEmptyMsg( $key, $name )
3187 ? $group
3188 : $name;
3192 * Get the localized descriptive name for a member of a group, if it exists
3194 * @param $group String Internal group name
3195 * @return String Localized name for group member
3197 static function getGroupMember( $group ) {
3198 $key = "group-$group-member";
3199 $name = wfMsg( $key );
3200 return $name == '' || wfEmptyMsg( $key, $name )
3201 ? $group
3202 : $name;
3206 * Return the set of defined explicit groups.
3207 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3208 * are not included, as they are defined automatically, not in the database.
3209 * @return Array of internal group names
3211 static function getAllGroups() {
3212 global $wgGroupPermissions, $wgRevokePermissions;
3213 return array_diff(
3214 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3215 self::getImplicitGroups()
3220 * Get a list of all available permissions.
3221 * @return Array of permission names
3223 static function getAllRights() {
3224 if ( self::$mAllRights === false ) {
3225 global $wgAvailableRights;
3226 if ( count( $wgAvailableRights ) ) {
3227 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3228 } else {
3229 self::$mAllRights = self::$mCoreRights;
3231 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3233 return self::$mAllRights;
3237 * Get a list of implicit groups
3238 * @return Array of Strings Array of internal group names
3240 public static function getImplicitGroups() {
3241 global $wgImplicitGroups;
3242 $groups = $wgImplicitGroups;
3243 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3244 return $groups;
3248 * Get the title of a page describing a particular group
3250 * @param $group String Internal group name
3251 * @return Title|Bool Title of the page if it exists, false otherwise
3253 static function getGroupPage( $group ) {
3254 $page = wfMsgForContent( 'grouppage-' . $group );
3255 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3256 $title = Title::newFromText( $page );
3257 if( is_object( $title ) )
3258 return $title;
3260 return false;
3264 * Create a link to the group in HTML, if available;
3265 * else return the group name.
3267 * @param $group String Internal name of the group
3268 * @param $text String The text of the link
3269 * @return String HTML link to the group
3271 static function makeGroupLinkHTML( $group, $text = '' ) {
3272 if( $text == '' ) {
3273 $text = self::getGroupName( $group );
3275 $title = self::getGroupPage( $group );
3276 if( $title ) {
3277 global $wgUser;
3278 $sk = $wgUser->getSkin();
3279 return $sk->link( $title, htmlspecialchars( $text ) );
3280 } else {
3281 return $text;
3286 * Create a link to the group in Wikitext, if available;
3287 * else return the group name.
3289 * @param $group String Internal name of the group
3290 * @param $text String The text of the link
3291 * @return String Wikilink to the group
3293 static function makeGroupLinkWiki( $group, $text = '' ) {
3294 if( $text == '' ) {
3295 $text = self::getGroupName( $group );
3297 $title = self::getGroupPage( $group );
3298 if( $title ) {
3299 $page = $title->getPrefixedText();
3300 return "[[$page|$text]]";
3301 } else {
3302 return $text;
3307 * Returns an array of the groups that a particular group can add/remove.
3309 * @param $group String: the group to check for whether it can add/remove
3310 * @return Array array( 'add' => array( addablegroups ),
3311 * 'remove' => array( removablegroups ),
3312 * 'add-self' => array( addablegroups to self),
3313 * 'remove-self' => array( removable groups from self) )
3315 static function changeableByGroup( $group ) {
3316 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3318 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3319 if( empty( $wgAddGroups[$group] ) ) {
3320 // Don't add anything to $groups
3321 } elseif( $wgAddGroups[$group] === true ) {
3322 // You get everything
3323 $groups['add'] = self::getAllGroups();
3324 } elseif( is_array( $wgAddGroups[$group] ) ) {
3325 $groups['add'] = $wgAddGroups[$group];
3328 // Same thing for remove
3329 if( empty( $wgRemoveGroups[$group] ) ) {
3330 } elseif( $wgRemoveGroups[$group] === true ) {
3331 $groups['remove'] = self::getAllGroups();
3332 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3333 $groups['remove'] = $wgRemoveGroups[$group];
3336 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3337 if( empty( $wgGroupsAddToSelf['user']) || $wgGroupsAddToSelf['user'] !== true ) {
3338 foreach( $wgGroupsAddToSelf as $key => $value ) {
3339 if( is_int( $key ) ) {
3340 $wgGroupsAddToSelf['user'][] = $value;
3345 if( empty( $wgGroupsRemoveFromSelf['user']) || $wgGroupsRemoveFromSelf['user'] !== true ) {
3346 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3347 if( is_int( $key ) ) {
3348 $wgGroupsRemoveFromSelf['user'][] = $value;
3353 // Now figure out what groups the user can add to him/herself
3354 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3355 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3356 // No idea WHY this would be used, but it's there
3357 $groups['add-self'] = User::getAllGroups();
3358 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3359 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3362 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3363 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3364 $groups['remove-self'] = User::getAllGroups();
3365 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3366 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3369 return $groups;
3373 * Returns an array of groups that this user can add and remove
3374 * @return Array array( 'add' => array( addablegroups ),
3375 * 'remove' => array( removablegroups ),
3376 * 'add-self' => array( addablegroups to self),
3377 * 'remove-self' => array( removable groups from self) )
3379 function changeableGroups() {
3380 if( $this->isAllowed( 'userrights' ) ) {
3381 // This group gives the right to modify everything (reverse-
3382 // compatibility with old "userrights lets you change
3383 // everything")
3384 // Using array_merge to make the groups reindexed
3385 $all = array_merge( User::getAllGroups() );
3386 return array(
3387 'add' => $all,
3388 'remove' => $all,
3389 'add-self' => array(),
3390 'remove-self' => array()
3394 // Okay, it's not so simple, we will have to go through the arrays
3395 $groups = array(
3396 'add' => array(),
3397 'remove' => array(),
3398 'add-self' => array(),
3399 'remove-self' => array()
3401 $addergroups = $this->getEffectiveGroups();
3403 foreach( $addergroups as $addergroup ) {
3404 $groups = array_merge_recursive(
3405 $groups, $this->changeableByGroup( $addergroup )
3407 $groups['add'] = array_unique( $groups['add'] );
3408 $groups['remove'] = array_unique( $groups['remove'] );
3409 $groups['add-self'] = array_unique( $groups['add-self'] );
3410 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3412 return $groups;
3416 * Increment the user's edit-count field.
3417 * Will have no effect for anonymous users.
3419 function incEditCount() {
3420 if( !$this->isAnon() ) {
3421 $dbw = wfGetDB( DB_MASTER );
3422 $dbw->update( 'user',
3423 array( 'user_editcount=user_editcount+1' ),
3424 array( 'user_id' => $this->getId() ),
3425 __METHOD__ );
3427 // Lazy initialization check...
3428 if( $dbw->affectedRows() == 0 ) {
3429 // Pull from a slave to be less cruel to servers
3430 // Accuracy isn't the point anyway here
3431 $dbr = wfGetDB( DB_SLAVE );
3432 $count = $dbr->selectField( 'revision',
3433 'COUNT(rev_user)',
3434 array( 'rev_user' => $this->getId() ),
3435 __METHOD__ );
3437 // Now here's a goddamn hack...
3438 if( $dbr !== $dbw ) {
3439 // If we actually have a slave server, the count is
3440 // at least one behind because the current transaction
3441 // has not been committed and replicated.
3442 $count++;
3443 } else {
3444 // But if DB_SLAVE is selecting the master, then the
3445 // count we just read includes the revision that was
3446 // just added in the working transaction.
3449 $dbw->update( 'user',
3450 array( 'user_editcount' => $count ),
3451 array( 'user_id' => $this->getId() ),
3452 __METHOD__ );
3455 // edit count in user cache too
3456 $this->invalidateCache();
3460 * Get the description of a given right
3462 * @param $right String Right to query
3463 * @return String Localized description of the right
3465 static function getRightDescription( $right ) {
3466 $key = "right-$right";
3467 $name = wfMsg( $key );
3468 return $name == '' || wfEmptyMsg( $key, $name )
3469 ? $right
3470 : $name;
3474 * Make an old-style password hash
3476 * @param $password String Plain-text password
3477 * @param $userId String User ID
3478 * @return String Password hash
3480 static function oldCrypt( $password, $userId ) {
3481 global $wgPasswordSalt;
3482 if ( $wgPasswordSalt ) {
3483 return md5( $userId . '-' . md5( $password ) );
3484 } else {
3485 return md5( $password );
3490 * Make a new-style password hash
3492 * @param $password String Plain-text password
3493 * @param $salt String Optional salt, may be random or the user ID.
3494 * If unspecified or false, will generate one automatically
3495 * @return String Password hash
3497 static function crypt( $password, $salt = false ) {
3498 global $wgPasswordSalt;
3500 $hash = '';
3501 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3502 return $hash;
3505 if( $wgPasswordSalt ) {
3506 if ( $salt === false ) {
3507 $salt = substr( wfGenerateToken(), 0, 8 );
3509 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3510 } else {
3511 return ':A:' . md5( $password );
3516 * Compare a password hash with a plain-text password. Requires the user
3517 * ID if there's a chance that the hash is an old-style hash.
3519 * @param $hash String Password hash
3520 * @param $password String Plain-text password to compare
3521 * @param $userId String User ID for old-style password salt
3522 * @return Boolean:
3524 static function comparePasswords( $hash, $password, $userId = false ) {
3525 $type = substr( $hash, 0, 3 );
3527 $result = false;
3528 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3529 return $result;
3532 if ( $type == ':A:' ) {
3533 # Unsalted
3534 return md5( $password ) === substr( $hash, 3 );
3535 } elseif ( $type == ':B:' ) {
3536 # Salted
3537 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3538 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3539 } else {
3540 # Old-style
3541 return self::oldCrypt( $password, $userId ) === $hash;
3546 * Add a newuser log entry for this user
3548 * @param $byEmail Boolean: account made by email?
3549 * @param $reason String: user supplied reason
3551 public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
3552 global $wgUser, $wgContLang, $wgNewUserLog;
3553 if( empty( $wgNewUserLog ) ) {
3554 return true; // disabled
3557 if( $this->getName() == $wgUser->getName() ) {
3558 $action = 'create';
3559 } else {
3560 $action = 'create2';
3561 if ( $byEmail ) {
3562 if ( $reason === '' ) {
3563 $reason = wfMsgForContent( 'newuserlog-byemail' );
3564 } else {
3565 $reason = $wgContLang->commaList( array(
3566 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
3570 $log = new LogPage( 'newusers' );
3571 $log->addEntry(
3572 $action,
3573 $this->getUserPage(),
3574 $reason,
3575 array( $this->getId() )
3577 return true;
3581 * Add an autocreate newuser log entry for this user
3582 * Used by things like CentralAuth and perhaps other authplugins.
3584 public function addNewUserLogEntryAutoCreate() {
3585 global $wgNewUserLog, $wgLogAutocreatedAccounts;
3586 if( !$wgNewUserLog || !$wgLogAutocreatedAccounts ) {
3587 return true; // disabled
3589 $log = new LogPage( 'newusers', false );
3590 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3591 return true;
3594 protected function loadOptions() {
3595 $this->load();
3596 if ( $this->mOptionsLoaded || !$this->getId() )
3597 return;
3599 $this->mOptions = self::getDefaultOptions();
3601 // Maybe load from the object
3602 if ( !is_null( $this->mOptionOverrides ) ) {
3603 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3604 foreach( $this->mOptionOverrides as $key => $value ) {
3605 $this->mOptions[$key] = $value;
3607 } else {
3608 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3609 // Load from database
3610 $dbr = wfGetDB( DB_SLAVE );
3612 $res = $dbr->select(
3613 'user_properties',
3614 '*',
3615 array( 'up_user' => $this->getId() ),
3616 __METHOD__
3619 foreach ( $res as $row ) {
3620 $this->mOptionOverrides[$row->up_property] = $row->up_value;
3621 $this->mOptions[$row->up_property] = $row->up_value;
3625 $this->mOptionsLoaded = true;
3627 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
3630 protected function saveOptions() {
3631 global $wgAllowPrefChange;
3633 $extuser = ExternalUser::newFromUser( $this );
3635 $this->loadOptions();
3636 $dbw = wfGetDB( DB_MASTER );
3638 $insert_rows = array();
3640 $saveOptions = $this->mOptions;
3642 // Allow hooks to abort, for instance to save to a global profile.
3643 // Reset options to default state before saving.
3644 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3645 return;
3647 foreach( $saveOptions as $key => $value ) {
3648 # Don't bother storing default values
3649 if ( ( is_null( self::getDefaultOption( $key ) ) &&
3650 !( $value === false || is_null($value) ) ) ||
3651 $value != self::getDefaultOption( $key ) ) {
3652 $insert_rows[] = array(
3653 'up_user' => $this->getId(),
3654 'up_property' => $key,
3655 'up_value' => $value,
3658 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3659 switch ( $wgAllowPrefChange[$key] ) {
3660 case 'local':
3661 case 'message':
3662 break;
3663 case 'semiglobal':
3664 case 'global':
3665 $extuser->setPref( $key, $value );
3670 $dbw->begin();
3671 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__ );
3672 $dbw->insert( 'user_properties', $insert_rows, __METHOD__ );
3673 $dbw->commit();
3677 * Provide an array of HTML5 attributes to put on an input element
3678 * intended for the user to enter a new password. This may include
3679 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3681 * Do *not* use this when asking the user to enter his current password!
3682 * Regardless of configuration, users may have invalid passwords for whatever
3683 * reason (e.g., they were set before requirements were tightened up).
3684 * Only use it when asking for a new password, like on account creation or
3685 * ResetPass.
3687 * Obviously, you still need to do server-side checking.
3689 * NOTE: A combination of bugs in various browsers means that this function
3690 * actually just returns array() unconditionally at the moment. May as
3691 * well keep it around for when the browser bugs get fixed, though.
3693 * FIXME : This does not belong here; put it in Html or Linker or somewhere
3695 * @return array Array of HTML attributes suitable for feeding to
3696 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3697 * That will potentially output invalid XHTML 1.0 Transitional, and will
3698 * get confused by the boolean attribute syntax used.)
3700 public static function passwordChangeInputAttribs() {
3701 global $wgMinimalPasswordLength;
3703 if ( $wgMinimalPasswordLength == 0 ) {
3704 return array();
3707 # Note that the pattern requirement will always be satisfied if the
3708 # input is empty, so we need required in all cases.
3710 # FIXME (bug 23769): This needs to not claim the password is required
3711 # if e-mail confirmation is being used. Since HTML5 input validation
3712 # is b0rked anyway in some browsers, just return nothing. When it's
3713 # re-enabled, fix this code to not output required for e-mail
3714 # registration.
3715 #$ret = array( 'required' );
3716 $ret = array();
3718 # We can't actually do this right now, because Opera 9.6 will print out
3719 # the entered password visibly in its error message! When other
3720 # browsers add support for this attribute, or Opera fixes its support,
3721 # we can add support with a version check to avoid doing this on Opera
3722 # versions where it will be a problem. Reported to Opera as
3723 # DSK-262266, but they don't have a public bug tracker for us to follow.
3725 if ( $wgMinimalPasswordLength > 1 ) {
3726 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3727 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3728 $wgMinimalPasswordLength );
3732 return $ret;
3736 * Format the user message using a hook, a template, or, failing these, a static format.
3737 * @param $subject String the subject of the message
3738 * @param $text String the content of the message
3739 * @param $signature String the signature, if provided.
3741 static protected function formatUserMessage( $subject, $text, $signature ) {
3742 if ( wfRunHooks( 'FormatUserMessage',
3743 array( $subject, &$text, $signature ) ) ) {
3745 $signature = empty($signature) ? "~~~~~" : "{$signature} ~~~~~";
3747 $template = Title::newFromText( wfMsgForContent( 'usermessage-template' ) );
3748 if ( !$template
3749 || $template->getNamespace() !== NS_TEMPLATE
3750 || !$template->exists() ) {
3751 $text = "\n== $subject ==\n\n$text\n\n-- $signature";
3752 } else {
3753 $text = '{{'. $template->getText()
3754 . " | subject=$subject | body=$text | signature=$signature }}";
3758 return $text;
3762 * Leave a user a message
3763 * @param $subject String the subject of the message
3764 * @param $text String the message to leave
3765 * @param $signature String Text to leave in the signature
3766 * @param $summary String the summary for this change, defaults to
3767 * "Leave system message."
3768 * @param $editor User The user leaving the message, defaults to
3769 * "{{MediaWiki:usermessage-editor}}"
3770 * @param $flags Int default edit flags
3772 * @return boolean true if it was successful
3774 public function leaveUserMessage( $subject, $text, $signature = "",
3775 $summary = null, $editor = null, $flags = 0 ) {
3776 if ( !isset( $summary ) ) {
3777 $summary = wfMsgForContent( 'usermessage-summary' );
3780 if ( !isset( $editor ) ) {
3781 $editor = User::newFromName( wfMsgForContent( 'usermessage-editor' ) );
3782 if ( !$editor->isLoggedIn() ) {
3783 $editor->addToDatabase();
3787 $article = new Article( $this->getTalkPage() );
3788 wfRunHooks( 'SetupUserMessageArticle',
3789 array( $this, &$article, $subject, $text, $signature, $summary, $editor ) );
3792 $text = self::formatUserMessage( $subject, $text, $signature );
3793 $flags = $article->checkFlags( $flags );
3795 if ( $flags & EDIT_UPDATE ) {
3796 $text = $article->getContent() . $text;
3799 $dbw = wfGetDB( DB_MASTER );
3800 $dbw->begin();
3802 try {
3803 $status = $article->doEdit( $text, $summary, $flags, false, $editor );
3804 } catch ( DBQueryError $e ) {
3805 $status = Status::newFatal("DB Error");
3808 if ( $status->isGood() ) {
3809 // Set newtalk with the right user ID
3810 $this->setNewtalk( true );
3811 wfRunHooks( 'AfterUserMessage',
3812 array( $this, $article, $summary, $text, $signature, $summary, $editor ) );
3813 $dbw->commit();
3814 } else {
3815 // The article was concurrently created
3816 wfDebug( __METHOD__ . ": Error ".$status->getWikiText() );
3817 $dbw->rollback();
3820 return $status->isGood();