(bug 15831) Modern skin RTL support is bugous
[mediawiki.git] / includes / User.php
blob64aebdd46c741a0e8db41e801bc25b35d6c31df7
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
4 * @file
5 */
7 /**
8 * \type{\int} Number of characters in user_token field.
9 * @ingroup Constants
11 define( 'USER_TOKEN_LENGTH', 32 );
13 /**
14 * \type{\int} Serialized record version.
15 * @ingroup Constants
17 define( 'MW_USER_VERSION', 6 );
19 /**
20 * \type{\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 {
45 /**
46 * \type{\arrayof{\string}} A list of default user toggles, i.e., boolean user
47 * preferences that are displayed by Special:Preferences as checkboxes.
48 * This list can be extended via the UserToggles hook or by
49 * $wgContLang::getExtraUserToggles().
50 * @showinitializer
52 public static $mToggles = array(
53 'highlightbroken',
54 'justify',
55 'hideminor',
56 'extendwatchlist',
57 'usenewrc',
58 'numberheadings',
59 'showtoolbar',
60 'editondblclick',
61 'editsection',
62 'editsectiononrightclick',
63 'showtoc',
64 'rememberpassword',
65 'editwidth',
66 'watchcreations',
67 'watchdefault',
68 'watchmoves',
69 'watchdeletion',
70 'minordefault',
71 'previewontop',
72 'previewonfirst',
73 'nocache',
74 'enotifwatchlistpages',
75 'enotifusertalkpages',
76 'enotifminoredits',
77 'enotifrevealaddr',
78 'shownumberswatching',
79 'fancysig',
80 'externaleditor',
81 'externaldiff',
82 'showjumplinks',
83 'uselivepreview',
84 'forceeditsummary',
85 'watchlisthideminor',
86 'watchlisthidebots',
87 'watchlisthideown',
88 'watchlisthideanons',
89 'watchlisthideliu',
90 'ccmeonemails',
91 'diffonly',
92 'showhiddencats',
93 'noconvertlink',
96 /**
97 * \type{\arrayof{\string}} List of member variables which are saved to the
98 * shared cache (memcached). Any operation which changes the
99 * corresponding database fields must call a cache-clearing function.
100 * @showinitializer
102 static $mCacheVars = array(
103 // user table
104 'mId',
105 'mName',
106 'mRealName',
107 'mPassword',
108 'mNewpassword',
109 'mNewpassTime',
110 'mEmail',
111 'mOptions',
112 'mTouched',
113 'mToken',
114 'mEmailAuthenticated',
115 'mEmailToken',
116 'mEmailTokenExpires',
117 'mRegistration',
118 'mEditCount',
119 // user_group table
120 'mGroups',
124 * \type{\arrayof{\string}} Core rights.
125 * Each of these should have a corresponding message of the form
126 * "right-$right".
127 * @showinitializer
129 static $mCoreRights = array(
130 'apihighlimits',
131 'autoconfirmed',
132 'autopatrol',
133 'bigdelete',
134 'block',
135 'blockemail',
136 'bot',
137 'browsearchive',
138 'createaccount',
139 'createpage',
140 'createtalk',
141 'delete',
142 'deletedhistory',
143 'edit',
144 'editinterface',
145 'editusercssjs',
146 'import',
147 'importupload',
148 'ipblock-exempt',
149 'markbotedits',
150 'minoredit',
151 'move',
152 'nominornewtalk',
153 'noratelimit',
154 'patrol',
155 'protect',
156 'proxyunbannable',
157 'purge',
158 'read',
159 'reupload',
160 'reupload-shared',
161 'rollback',
162 'siteadmin',
163 'suppressredirect',
164 'trackback',
165 'undelete',
166 'unwatchedpages',
167 'upload',
168 'upload_by_url',
169 'userrights',
172 * \type{\string} Cached results of getAllRights()
174 static $mAllRights = false;
176 /** @name Cache variables */
177 //@{
178 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
179 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
180 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
181 //@}
184 * \type{\bool} Whether the cache variables have been loaded.
186 var $mDataLoaded, $mAuthLoaded;
189 * \type{\string} Initialization data source if mDataLoaded==false. May be one of:
190 * - 'defaults' anonymous user initialised from class defaults
191 * - 'name' initialise from mName
192 * - 'id' initialise from mId
193 * - 'session' log in from cookies or session if possible
195 * Use the User::newFrom*() family of functions to set this.
197 var $mFrom;
199 /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
200 //@{
201 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
202 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
203 $mLocked, $mHideName;
204 //@}
207 * Lightweight constructor for an anonymous user.
208 * Use the User::newFrom* factory functions for other kinds of users.
210 * @see newFromName()
211 * @see newFromId()
212 * @see newFromConfirmationCode()
213 * @see newFromSession()
214 * @see newFromRow()
216 function User() {
217 $this->clearInstanceCache( 'defaults' );
221 * Load the user table data for this object from the source given by mFrom.
223 function load() {
224 if ( $this->mDataLoaded ) {
225 return;
227 wfProfileIn( __METHOD__ );
229 # Set it now to avoid infinite recursion in accessors
230 $this->mDataLoaded = true;
232 switch ( $this->mFrom ) {
233 case 'defaults':
234 $this->loadDefaults();
235 break;
236 case 'name':
237 $this->mId = self::idFromName( $this->mName );
238 if ( !$this->mId ) {
239 # Nonexistent user placeholder object
240 $this->loadDefaults( $this->mName );
241 } else {
242 $this->loadFromId();
244 break;
245 case 'id':
246 $this->loadFromId();
247 break;
248 case 'session':
249 $this->loadFromSession();
250 break;
251 default:
252 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
254 wfProfileOut( __METHOD__ );
258 * Load user table data, given mId has already been set.
259 * @return \type{\bool} false if the ID does not exist, true otherwise
260 * @private
262 function loadFromId() {
263 global $wgMemc;
264 if ( $this->mId == 0 ) {
265 $this->loadDefaults();
266 return false;
269 # Try cache
270 $key = wfMemcKey( 'user', 'id', $this->mId );
271 $data = $wgMemc->get( $key );
272 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
273 # Object is expired, load from DB
274 $data = false;
277 if ( !$data ) {
278 wfDebug( "Cache miss for user {$this->mId}\n" );
279 # Load from DB
280 if ( !$this->loadFromDatabase() ) {
281 # Can't load from ID, user is anonymous
282 return false;
284 $this->saveToCache();
285 } else {
286 wfDebug( "Got user {$this->mId} from cache\n" );
287 # Restore from cache
288 foreach ( self::$mCacheVars as $name ) {
289 $this->$name = $data[$name];
292 return true;
296 * Save user data to the shared cache
298 function saveToCache() {
299 $this->load();
300 $this->loadGroups();
301 if ( $this->isAnon() ) {
302 // Anonymous users are uncached
303 return;
305 $data = array();
306 foreach ( self::$mCacheVars as $name ) {
307 $data[$name] = $this->$name;
309 $data['mVersion'] = MW_USER_VERSION;
310 $key = wfMemcKey( 'user', 'id', $this->mId );
311 global $wgMemc;
312 $wgMemc->set( $key, $data );
316 /** @name newFrom*() static factory methods */
317 //@{
320 * Static factory method for creation from username.
322 * This is slightly less efficient than newFromId(), so use newFromId() if
323 * you have both an ID and a name handy.
325 * @param $name \type{\string} Username, validated by Title::newFromText()
326 * @param $validate \type{\mixed} Validate username. Takes the same parameters as
327 * User::getCanonicalName(), except that true is accepted as an alias
328 * for 'valid', for BC.
330 * @return \type{User} The User object, or null if the username is invalid. If the
331 * username is not present in the database, the result will be a user object
332 * with a name, zero user ID and default settings.
334 static function newFromName( $name, $validate = 'valid' ) {
335 if ( $validate === true ) {
336 $validate = 'valid';
338 $name = self::getCanonicalName( $name, $validate );
339 if ( $name === false ) {
340 return null;
341 } else {
342 # Create unloaded user object
343 $u = new User;
344 $u->mName = $name;
345 $u->mFrom = 'name';
346 return $u;
351 * Static factory method for creation from a given user ID.
353 * @param $id \type{\int} Valid user ID
354 * @return \type{User} The corresponding User object
356 static function newFromId( $id ) {
357 $u = new User;
358 $u->mId = $id;
359 $u->mFrom = 'id';
360 return $u;
364 * Factory method to fetch whichever user has a given email confirmation code.
365 * This code is generated when an account is created or its e-mail address
366 * has changed.
368 * If the code is invalid or has expired, returns NULL.
370 * @param $code \type{\string} Confirmation code
371 * @return \type{User}
373 static function newFromConfirmationCode( $code ) {
374 $dbr = wfGetDB( DB_SLAVE );
375 $id = $dbr->selectField( 'user', 'user_id', array(
376 'user_email_token' => md5( $code ),
377 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
378 ) );
379 if( $id !== false ) {
380 return User::newFromId( $id );
381 } else {
382 return null;
387 * Create a new user object using data from session or cookies. If the
388 * login credentials are invalid, the result is an anonymous user.
390 * @return \type{User}
392 static function newFromSession() {
393 $user = new User;
394 $user->mFrom = 'session';
395 return $user;
399 * Create a new user object from a user row.
400 * The row should have all fields from the user table in it.
401 * @param $row array A row from the user table
402 * @return \type{User}
404 static function newFromRow( $row ) {
405 $user = new User;
406 $user->loadFromRow( $row );
407 return $user;
410 //@}
414 * Get the username corresponding to a given user ID
415 * @param $id \type{\int} %User ID
416 * @return \type{\string} The corresponding username
418 static function whoIs( $id ) {
419 $dbr = wfGetDB( DB_SLAVE );
420 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
424 * Get the real name of a user given their user ID
426 * @param $id \type{\int} %User ID
427 * @return \type{\string} The corresponding user's real name
429 static function whoIsReal( $id ) {
430 $dbr = wfGetDB( DB_SLAVE );
431 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
435 * Get database id given a user name
436 * @param $name \type{\string} Username
437 * @return \twotypes{\int,\null} The corresponding user's ID, or null if user is nonexistent
438 * @static
440 static function idFromName( $name ) {
441 $nt = Title::newFromText( $name );
442 if( is_null( $nt ) ) {
443 # Illegal name
444 return null;
446 $dbr = wfGetDB( DB_SLAVE );
447 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
449 if ( $s === false ) {
450 return 0;
451 } else {
452 return $s->user_id;
457 * Does the string match an anonymous IPv4 address?
459 * This function exists for username validation, in order to reject
460 * usernames which are similar in form to IP addresses. Strings such
461 * as 300.300.300.300 will return true because it looks like an IP
462 * address, despite not being strictly valid.
464 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
465 * address because the usemod software would "cloak" anonymous IP
466 * addresses like this, if we allowed accounts like this to be created
467 * new users could get the old edits of these anonymous users.
469 * @param $name \type{\string} String to match
470 * @return \type{\bool} True or false
472 static function isIP( $name ) {
473 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
477 * Is the input a valid username?
479 * Checks if the input is a valid username, we don't want an empty string,
480 * an IP address, anything that containins slashes (would mess up subpages),
481 * is longer than the maximum allowed username size or doesn't begin with
482 * a capital letter.
484 * @param $name \type{\string} String to match
485 * @return \type{\bool} True or false
487 static function isValidUserName( $name ) {
488 global $wgContLang, $wgMaxNameChars;
490 if ( $name == ''
491 || User::isIP( $name )
492 || strpos( $name, '/' ) !== false
493 || strlen( $name ) > $wgMaxNameChars
494 || $name != $wgContLang->ucfirst( $name ) ) {
495 wfDebugLog( 'username', __METHOD__ .
496 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
497 return false;
500 // Ensure that the name can't be misresolved as a different title,
501 // such as with extra namespace keys at the start.
502 $parsed = Title::newFromText( $name );
503 if( is_null( $parsed )
504 || $parsed->getNamespace()
505 || strcmp( $name, $parsed->getPrefixedText() ) ) {
506 wfDebugLog( 'username', __METHOD__ .
507 ": '$name' invalid due to ambiguous prefixes" );
508 return false;
511 // Check an additional blacklist of troublemaker characters.
512 // Should these be merged into the title char list?
513 $unicodeBlacklist = '/[' .
514 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
515 '\x{00a0}' . # non-breaking space
516 '\x{2000}-\x{200f}' . # various whitespace
517 '\x{2028}-\x{202f}' . # breaks and control chars
518 '\x{3000}' . # ideographic space
519 '\x{e000}-\x{f8ff}' . # private use
520 ']/u';
521 if( preg_match( $unicodeBlacklist, $name ) ) {
522 wfDebugLog( 'username', __METHOD__ .
523 ": '$name' invalid due to blacklisted characters" );
524 return false;
527 return true;
531 * Usernames which fail to pass this function will be blocked
532 * from user login and new account registrations, but may be used
533 * internally by batch processes.
535 * If an account already exists in this form, login will be blocked
536 * by a failure to pass this function.
538 * @param $name \type{\string} String to match
539 * @return \type{\bool} True or false
541 static function isUsableName( $name ) {
542 global $wgReservedUsernames;
543 // Must be a valid username, obviously ;)
544 if ( !self::isValidUserName( $name ) ) {
545 return false;
548 static $reservedUsernames = false;
549 if ( !$reservedUsernames ) {
550 $reservedUsernames = $wgReservedUsernames;
551 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
554 // Certain names may be reserved for batch processes.
555 foreach ( $reservedUsernames as $reserved ) {
556 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
557 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
559 if ( $reserved == $name ) {
560 return false;
563 return true;
567 * Usernames which fail to pass this function will be blocked
568 * from new account registrations, but may be used internally
569 * either by batch processes or by user accounts which have
570 * already been created.
572 * Additional character blacklisting may be added here
573 * rather than in isValidUserName() to avoid disrupting
574 * existing accounts.
576 * @param $name \type{\string} String to match
577 * @return \type{\bool} True or false
579 static function isCreatableName( $name ) {
580 return
581 self::isUsableName( $name ) &&
583 // Registration-time character blacklisting...
584 strpos( $name, '@' ) === false;
588 * Is the input a valid password for this user?
590 * @param $password \type{\string} Desired password
591 * @return \type{\bool} True or false
593 function isValidPassword( $password ) {
594 global $wgMinimalPasswordLength, $wgContLang;
596 $result = null;
597 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
598 return $result;
599 if( $result === false )
600 return false;
602 // Password needs to be long enough, and can't be the same as the username
603 return strlen( $password ) >= $wgMinimalPasswordLength
604 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName );
608 * Does a string look like an e-mail address?
610 * There used to be a regular expression here, it got removed because it
611 * rejected valid addresses. Actually just check if there is '@' somewhere
612 * in the given address.
614 * @todo Check for RFC 2822 compilance (bug 959)
616 * @param $addr \type{\string} E-mail address
617 * @return \type{\bool} True or false
619 public static function isValidEmailAddr( $addr ) {
620 $result = null;
621 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
622 return $result;
625 return strpos( $addr, '@' ) !== false;
629 * Given unvalidated user input, return a canonical username, or false if
630 * the username is invalid.
631 * @param $name \type{\string} User input
632 * @param $validate \twotypes{\string,\bool} Type of validation to use:
633 * - false No validation
634 * - 'valid' Valid for batch processes
635 * - 'usable' Valid for batch processes and login
636 * - 'creatable' Valid for batch processes, login and account creation
638 static function getCanonicalName( $name, $validate = 'valid' ) {
639 # Force usernames to capital
640 global $wgContLang;
641 $name = $wgContLang->ucfirst( $name );
643 # Reject names containing '#'; these will be cleaned up
644 # with title normalisation, but then it's too late to
645 # check elsewhere
646 if( strpos( $name, '#' ) !== false )
647 return false;
649 # Clean up name according to title rules
650 $t = ($validate === 'valid') ?
651 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
652 # Check for invalid titles
653 if( is_null( $t ) ) {
654 return false;
657 # Reject various classes of invalid names
658 $name = $t->getText();
659 global $wgAuth;
660 $name = $wgAuth->getCanonicalName( $t->getText() );
662 switch ( $validate ) {
663 case false:
664 break;
665 case 'valid':
666 if ( !User::isValidUserName( $name ) ) {
667 $name = false;
669 break;
670 case 'usable':
671 if ( !User::isUsableName( $name ) ) {
672 $name = false;
674 break;
675 case 'creatable':
676 if ( !User::isCreatableName( $name ) ) {
677 $name = false;
679 break;
680 default:
681 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__ );
683 return $name;
687 * Count the number of edits of a user
688 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
690 * @param $uid \type{\int} %User ID to check
691 * @return \type{\int} The user's edit count
693 static function edits( $uid ) {
694 wfProfileIn( __METHOD__ );
695 $dbr = wfGetDB( DB_SLAVE );
696 // check if the user_editcount field has been initialized
697 $field = $dbr->selectField(
698 'user', 'user_editcount',
699 array( 'user_id' => $uid ),
700 __METHOD__
703 if( $field === null ) { // it has not been initialized. do so.
704 $dbw = wfGetDB( DB_MASTER );
705 $count = $dbr->selectField(
706 'revision', 'count(*)',
707 array( 'rev_user' => $uid ),
708 __METHOD__
710 $dbw->update(
711 'user',
712 array( 'user_editcount' => $count ),
713 array( 'user_id' => $uid ),
714 __METHOD__
716 } else {
717 $count = $field;
719 wfProfileOut( __METHOD__ );
720 return $count;
724 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
725 * @todo hash random numbers to improve security, like generateToken()
727 * @return \type{\string} New random password
729 static function randomPassword() {
730 global $wgMinimalPasswordLength;
731 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
732 $l = strlen( $pwchars ) - 1;
734 $pwlength = max( 7, $wgMinimalPasswordLength );
735 $digit = mt_rand(0, $pwlength - 1);
736 $np = '';
737 for ( $i = 0; $i < $pwlength; $i++ ) {
738 $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
740 return $np;
744 * Set cached properties to default.
746 * @note This no longer clears uncached lazy-initialised properties;
747 * the constructor does that instead.
748 * @private
750 function loadDefaults( $name = false ) {
751 wfProfileIn( __METHOD__ );
753 global $wgCookiePrefix;
755 $this->mId = 0;
756 $this->mName = $name;
757 $this->mRealName = '';
758 $this->mPassword = $this->mNewpassword = '';
759 $this->mNewpassTime = null;
760 $this->mEmail = '';
761 $this->mOptions = null; # Defer init
763 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
764 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
765 } else {
766 $this->mTouched = '0'; # Allow any pages to be cached
769 $this->setToken(); # Random
770 $this->mEmailAuthenticated = null;
771 $this->mEmailToken = '';
772 $this->mEmailTokenExpires = null;
773 $this->mRegistration = wfTimestamp( TS_MW );
774 $this->mGroups = array();
776 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
778 wfProfileOut( __METHOD__ );
782 * @deprecated Use wfSetupSession().
784 function SetupSession() {
785 wfDeprecated( __METHOD__ );
786 wfSetupSession();
790 * Load user data from the session or login cookie. If there are no valid
791 * credentials, initialises the user as an anonymous user.
792 * @return \type{\bool} True if the user is logged in, false otherwise.
794 private function loadFromSession() {
795 global $wgMemc, $wgCookiePrefix;
797 $result = null;
798 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
799 if ( $result !== null ) {
800 return $result;
803 if ( isset( $_SESSION['wsUserID'] ) ) {
804 if ( 0 != $_SESSION['wsUserID'] ) {
805 $sId = $_SESSION['wsUserID'];
806 } else {
807 $this->loadDefaults();
808 return false;
810 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
811 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
812 $_SESSION['wsUserID'] = $sId;
813 } else {
814 $this->loadDefaults();
815 return false;
817 if ( isset( $_SESSION['wsUserName'] ) ) {
818 $sName = $_SESSION['wsUserName'];
819 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
820 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
821 $_SESSION['wsUserName'] = $sName;
822 } else {
823 $this->loadDefaults();
824 return false;
827 $passwordCorrect = FALSE;
828 $this->mId = $sId;
829 if ( !$this->loadFromId() ) {
830 # Not a valid ID, loadFromId has switched the object to anon for us
831 return false;
834 if ( isset( $_SESSION['wsToken'] ) ) {
835 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
836 $from = 'session';
837 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
838 $passwordCorrect = $this->mToken == $_COOKIE["{$wgCookiePrefix}Token"];
839 $from = 'cookie';
840 } else {
841 # No session or persistent login cookie
842 $this->loadDefaults();
843 return false;
846 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
847 $_SESSION['wsToken'] = $this->mToken;
848 wfDebug( "Logged in from $from\n" );
849 return true;
850 } else {
851 # Invalid credentials
852 wfDebug( "Can't log in from $from, invalid credentials\n" );
853 $this->loadDefaults();
854 return false;
859 * Load user and user_group data from the database.
860 * $this::mId must be set, this is how the user is identified.
862 * @return \type{\bool} True if the user exists, false if the user is anonymous
863 * @private
865 function loadFromDatabase() {
866 # Paranoia
867 $this->mId = intval( $this->mId );
869 /** Anonymous user */
870 if( !$this->mId ) {
871 $this->loadDefaults();
872 return false;
875 $dbr = wfGetDB( DB_MASTER );
876 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
878 if ( $s !== false ) {
879 # Initialise user table data
880 $this->loadFromRow( $s );
881 $this->mGroups = null; // deferred
882 $this->getEditCount(); // revalidation for nulls
883 return true;
884 } else {
885 # Invalid user_id
886 $this->mId = 0;
887 $this->loadDefaults();
888 return false;
893 * Initialize this object from a row from the user table.
895 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
897 function loadFromRow( $row ) {
898 $this->mDataLoaded = true;
900 if ( isset( $row->user_id ) ) {
901 $this->mId = $row->user_id;
903 $this->mName = $row->user_name;
904 $this->mRealName = $row->user_real_name;
905 $this->mPassword = $row->user_password;
906 $this->mNewpassword = $row->user_newpassword;
907 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
908 $this->mEmail = $row->user_email;
909 $this->decodeOptions( $row->user_options );
910 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
911 $this->mToken = $row->user_token;
912 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
913 $this->mEmailToken = $row->user_email_token;
914 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
915 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
916 $this->mEditCount = $row->user_editcount;
920 * Load the groups from the database if they aren't already loaded.
921 * @private
923 function loadGroups() {
924 if ( is_null( $this->mGroups ) ) {
925 $dbr = wfGetDB( DB_MASTER );
926 $res = $dbr->select( 'user_groups',
927 array( 'ug_group' ),
928 array( 'ug_user' => $this->mId ),
929 __METHOD__ );
930 $this->mGroups = array();
931 while( $row = $dbr->fetchObject( $res ) ) {
932 $this->mGroups[] = $row->ug_group;
938 * Clear various cached data stored in this object.
939 * @param $reloadFrom \type{\string} Reload user and user_groups table data from a
940 * given source. May be "name", "id", "defaults", "session", or false for
941 * no reload.
943 function clearInstanceCache( $reloadFrom = false ) {
944 $this->mNewtalk = -1;
945 $this->mDatePreference = null;
946 $this->mBlockedby = -1; # Unset
947 $this->mHash = false;
948 $this->mSkin = null;
949 $this->mRights = null;
950 $this->mEffectiveGroups = null;
952 if ( $reloadFrom ) {
953 $this->mDataLoaded = false;
954 $this->mFrom = $reloadFrom;
959 * Combine the language default options with any site-specific options
960 * and add the default language variants.
962 * @return \type{\arrayof{\string}} Array of options
964 static function getDefaultOptions() {
965 global $wgNamespacesToBeSearchedDefault;
967 * Site defaults will override the global/language defaults
969 global $wgDefaultUserOptions, $wgContLang;
970 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
973 * default language setting
975 $variant = $wgContLang->getPreferredVariant( false );
976 $defOpt['variant'] = $variant;
977 $defOpt['language'] = $variant;
979 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
980 $defOpt['searchNs'.$nsnum] = $val;
982 return $defOpt;
986 * Get a given default option value.
988 * @param $opt \type{\string} Name of option to retrieve
989 * @return \type{\string} Default option value
991 public static function getDefaultOption( $opt ) {
992 $defOpts = self::getDefaultOptions();
993 if( isset( $defOpts[$opt] ) ) {
994 return $defOpts[$opt];
995 } else {
996 return '';
1001 * Get a list of user toggle names
1002 * @return \type{\arrayof{\string}} Array of user toggle names
1004 static function getToggles() {
1005 global $wgContLang;
1006 $extraToggles = array();
1007 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1008 return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1013 * Get blocking information
1014 * @private
1015 * @param $bFromSlave \type{\bool} Whether to check the slave database first. To
1016 * improve performance, non-critical checks are done
1017 * against slaves. Check when actually saving should be
1018 * done against master.
1020 function getBlockedStatus( $bFromSlave = true ) {
1021 global $wgEnableSorbs, $wgProxyWhitelist;
1023 if ( -1 != $this->mBlockedby ) {
1024 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1025 return;
1028 wfProfileIn( __METHOD__ );
1029 wfDebug( __METHOD__.": checking...\n" );
1031 // Initialize data...
1032 // Otherwise something ends up stomping on $this->mBlockedby when
1033 // things get lazy-loaded later, causing false positive block hits
1034 // due to -1 !== 0. Probably session-related... Nothing should be
1035 // overwriting mBlockedby, surely?
1036 $this->load();
1038 $this->mBlockedby = 0;
1039 $this->mHideName = 0;
1040 $this->mAllowUsertalk = 0;
1041 $ip = wfGetIP();
1043 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1044 # Exempt from all types of IP-block
1045 $ip = '';
1048 # User/IP blocking
1049 $this->mBlock = new Block();
1050 $this->mBlock->fromMaster( !$bFromSlave );
1051 if ( $this->mBlock->load( $ip , $this->mId ) ) {
1052 wfDebug( __METHOD__.": Found block.\n" );
1053 $this->mBlockedby = $this->mBlock->mBy;
1054 $this->mBlockreason = $this->mBlock->mReason;
1055 $this->mHideName = $this->mBlock->mHideName;
1056 $this->mAllowUsertalk = $this->mBlock->mAllowUsertalk;
1057 if ( $this->isLoggedIn() ) {
1058 $this->spreadBlock();
1060 } else {
1061 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1062 // apply to users. Note that the existence of $this->mBlock is not used to
1063 // check for edit blocks, $this->mBlockedby is instead.
1066 # Proxy blocking
1067 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1068 # Local list
1069 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1070 $this->mBlockedby = wfMsg( 'proxyblocker' );
1071 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1074 # DNSBL
1075 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
1076 if ( $this->inSorbsBlacklist( $ip ) ) {
1077 $this->mBlockedby = wfMsg( 'sorbs' );
1078 $this->mBlockreason = wfMsg( 'sorbsreason' );
1083 # Extensions
1084 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1086 wfProfileOut( __METHOD__ );
1090 * Whether the given IP is in the SORBS blacklist.
1092 * @param $ip \type{\string} IP to check
1093 * @return \type{\bool} True if blacklisted
1095 function inSorbsBlacklist( $ip ) {
1096 global $wgEnableSorbs, $wgSorbsUrl;
1098 return $wgEnableSorbs &&
1099 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1103 * Whether the given IP is in a given DNS blacklist.
1105 * @param $ip \type{\string} IP to check
1106 * @param $base \type{\string} URL of the DNS blacklist
1107 * @return \type{\bool} True if blacklisted
1109 function inDnsBlacklist( $ip, $base ) {
1110 wfProfileIn( __METHOD__ );
1112 $found = false;
1113 $host = '';
1114 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1115 if( IP::isIPv4($ip) ) {
1116 # Make hostname
1117 $host = "$ip.$base";
1119 # Send query
1120 $ipList = gethostbynamel( $host );
1122 if( $ipList ) {
1123 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1124 $found = true;
1125 } else {
1126 wfDebug( "Requested $host, not found in $base.\n" );
1130 wfProfileOut( __METHOD__ );
1131 return $found;
1135 * Is this user subject to rate limiting?
1137 * @return \type{\bool} True if rate limited
1139 public function isPingLimitable() {
1140 global $wgRateLimitsExcludedGroups;
1141 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1142 // Deprecated, but kept for backwards-compatibility config
1143 return false;
1145 return !$this->isAllowed('noratelimit');
1149 * Primitive rate limits: enforce maximum actions per time period
1150 * to put a brake on flooding.
1152 * @note When using a shared cache like memcached, IP-address
1153 * last-hit counters will be shared across wikis.
1155 * @param $action \type{\string} Action to enforce; 'edit' if unspecified
1156 * @return \type{\bool} True if a rate limiter was tripped
1158 function pingLimiter( $action='edit' ) {
1160 # Call the 'PingLimiter' hook
1161 $result = false;
1162 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1163 return $result;
1166 global $wgRateLimits;
1167 if( !isset( $wgRateLimits[$action] ) ) {
1168 return false;
1171 # Some groups shouldn't trigger the ping limiter, ever
1172 if( !$this->isPingLimitable() )
1173 return false;
1175 global $wgMemc, $wgRateLimitLog;
1176 wfProfileIn( __METHOD__ );
1178 $limits = $wgRateLimits[$action];
1179 $keys = array();
1180 $id = $this->getId();
1181 $ip = wfGetIP();
1182 $userLimit = false;
1184 if( isset( $limits['anon'] ) && $id == 0 ) {
1185 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1188 if( isset( $limits['user'] ) && $id != 0 ) {
1189 $userLimit = $limits['user'];
1191 if( $this->isNewbie() ) {
1192 if( isset( $limits['newbie'] ) && $id != 0 ) {
1193 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1195 if( isset( $limits['ip'] ) ) {
1196 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1198 $matches = array();
1199 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1200 $subnet = $matches[1];
1201 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1204 // Check for group-specific permissions
1205 // If more than one group applies, use the group with the highest limit
1206 foreach ( $this->getGroups() as $group ) {
1207 if ( isset( $limits[$group] ) ) {
1208 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1209 $userLimit = $limits[$group];
1213 // Set the user limit key
1214 if ( $userLimit !== false ) {
1215 wfDebug( __METHOD__.": effective user limit: $userLimit\n" );
1216 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1219 $triggered = false;
1220 foreach( $keys as $key => $limit ) {
1221 list( $max, $period ) = $limit;
1222 $summary = "(limit $max in {$period}s)";
1223 $count = $wgMemc->get( $key );
1224 if( $count ) {
1225 if( $count > $max ) {
1226 wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
1227 if( $wgRateLimitLog ) {
1228 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1230 $triggered = true;
1231 } else {
1232 wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
1234 } else {
1235 wfDebug( __METHOD__.": adding record for $key $summary\n" );
1236 $wgMemc->add( $key, 1, intval( $period ) );
1238 $wgMemc->incr( $key );
1241 wfProfileOut( __METHOD__ );
1242 return $triggered;
1246 * Check if user is blocked
1248 * @param $bFromSlave \type{\bool} Whether to check the slave database instead of the master
1249 * @return \type{\bool} True if blocked, false otherwise
1251 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1252 wfDebug( "User::isBlocked: enter\n" );
1253 $this->getBlockedStatus( $bFromSlave );
1254 return $this->mBlockedby !== 0;
1258 * Check if user is blocked from editing a particular article
1260 * @param $title \type{\string} Title to check
1261 * @param $bFromSlave \type{\bool} Whether to check the slave database instead of the master
1262 * @return \type{\bool} True if blocked, false otherwise
1264 function isBlockedFrom( $title, $bFromSlave = false ) {
1265 global $wgBlockAllowsUTEdit;
1266 wfProfileIn( __METHOD__ );
1267 wfDebug( __METHOD__.": enter\n" );
1269 wfDebug( __METHOD__.": asking isBlocked()\n" );
1270 $blocked = $this->isBlocked( $bFromSlave );
1271 $allowUsertalk = ($wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false);
1272 # If a user's name is suppressed, they cannot make edits anywhere
1273 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1274 $title->getNamespace() == NS_USER_TALK ) {
1275 $blocked = false;
1276 wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1278 wfProfileOut( __METHOD__ );
1279 return $blocked;
1283 * If user is blocked, return the name of the user who placed the block
1284 * @return \type{\string} name of blocker
1286 function blockedBy() {
1287 $this->getBlockedStatus();
1288 return $this->mBlockedby;
1292 * If user is blocked, return the specified reason for the block
1293 * @return \type{\string} Blocking reason
1295 function blockedFor() {
1296 $this->getBlockedStatus();
1297 return $this->mBlockreason;
1301 * Check if user is blocked on all wikis.
1302 * Do not use for actual edit permission checks!
1303 * This is intented for quick UI checks.
1305 * @param $ip \type{\string} IP address, uses current client if none given
1306 * @return \type{\bool} True if blocked, false otherwise
1308 function isBlockedGlobally( $ip = '' ) {
1309 if( $this->mBlockedGlobally !== null ) {
1310 return $this->mBlockedGlobally;
1312 // User is already an IP?
1313 if( IP::isIPAddress( $this->getName() ) ) {
1314 $ip = $this->getName();
1315 } else if( !$ip ) {
1316 $ip = wfGetIP();
1318 $blocked = false;
1319 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1320 $this->mBlockedGlobally = (bool)$blocked;
1321 return $this->mBlockedGlobally;
1325 * Check if user account is locked
1327 * @return \type{\bool} True if locked, false otherwise
1329 function isLocked() {
1330 if( $this->mLocked !== null ) {
1331 return $this->mLocked;
1333 global $wgAuth;
1334 $authUser = $wgAuth->getUserInstance( $this );
1335 $this->mLocked = (bool)$authUser->isLocked();
1336 return $this->mLocked;
1340 * Check if user account is hidden
1342 * @return \type{\bool} True if hidden, false otherwise
1344 function isHidden() {
1345 if( $this->mHideName !== null ) {
1346 return $this->mHideName;
1348 $this->getBlockedStatus();
1349 if( !$this->mHideName ) {
1350 global $wgAuth;
1351 $authUser = $wgAuth->getUserInstance( $this );
1352 $this->mHideName = (bool)$authUser->isHidden();
1354 return $this->mHideName;
1358 * Get the user's ID.
1359 * @return \type{\int} The user's ID; 0 if the user is anonymous or nonexistent
1361 function getId() {
1362 if( $this->mId === null and $this->mName !== null
1363 and User::isIP( $this->mName ) ) {
1364 // Special case, we know the user is anonymous
1365 return 0;
1366 } elseif( $this->mId === null ) {
1367 // Don't load if this was initialized from an ID
1368 $this->load();
1370 return $this->mId;
1374 * Set the user and reload all fields according to a given ID
1375 * @param $v \type{\int} %User ID to reload
1377 function setId( $v ) {
1378 $this->mId = $v;
1379 $this->clearInstanceCache( 'id' );
1383 * Get the user name, or the IP of an anonymous user
1384 * @return \type{\string} User's name or IP address
1386 function getName() {
1387 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1388 # Special case optimisation
1389 return $this->mName;
1390 } else {
1391 $this->load();
1392 if ( $this->mName === false ) {
1393 # Clean up IPs
1394 $this->mName = IP::sanitizeIP( wfGetIP() );
1396 return $this->mName;
1401 * Set the user name.
1403 * This does not reload fields from the database according to the given
1404 * name. Rather, it is used to create a temporary "nonexistent user" for
1405 * later addition to the database. It can also be used to set the IP
1406 * address for an anonymous user to something other than the current
1407 * remote IP.
1409 * @note User::newFromName() has rougly the same function, when the named user
1410 * does not exist.
1411 * @param $str \type{\string} New user name to set
1413 function setName( $str ) {
1414 $this->load();
1415 $this->mName = $str;
1419 * Get the user's name escaped by underscores.
1420 * @return \type{\string} Username escaped by underscores
1422 function getTitleKey() {
1423 return str_replace( ' ', '_', $this->getName() );
1427 * Check if the user has new messages.
1428 * @return \type{\bool} True if the user has new messages
1430 function getNewtalk() {
1431 $this->load();
1433 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1434 if( $this->mNewtalk === -1 ) {
1435 $this->mNewtalk = false; # reset talk page status
1437 # Check memcached separately for anons, who have no
1438 # entire User object stored in there.
1439 if( !$this->mId ) {
1440 global $wgMemc;
1441 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1442 $newtalk = $wgMemc->get( $key );
1443 if( strval( $newtalk ) !== '' ) {
1444 $this->mNewtalk = (bool)$newtalk;
1445 } else {
1446 // Since we are caching this, make sure it is up to date by getting it
1447 // from the master
1448 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1449 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1451 } else {
1452 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1456 return (bool)$this->mNewtalk;
1460 * Return the talk page(s) this user has new messages on.
1461 * @return \type{\arrayof{\string}} Array of page URLs
1463 function getNewMessageLinks() {
1464 $talks = array();
1465 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1466 return $talks;
1468 if (!$this->getNewtalk())
1469 return array();
1470 $up = $this->getUserPage();
1471 $utp = $up->getTalkPage();
1472 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1477 * Internal uncached check for new messages
1479 * @see getNewtalk()
1480 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1481 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1482 * @param $fromMaster \type{\bool} true to fetch from the master, false for a slave
1483 * @return \type{\bool} True if the user has new messages
1484 * @private
1486 function checkNewtalk( $field, $id, $fromMaster = false ) {
1487 if ( $fromMaster ) {
1488 $db = wfGetDB( DB_MASTER );
1489 } else {
1490 $db = wfGetDB( DB_SLAVE );
1492 $ok = $db->selectField( 'user_newtalk', $field,
1493 array( $field => $id ), __METHOD__ );
1494 return $ok !== false;
1498 * Add or update the new messages flag
1499 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1500 * @param $id \twotypes{string,\int} User's IP address for anonymous users, %User ID otherwise
1501 * @return \type{\bool} True if successful, false otherwise
1502 * @private
1504 function updateNewtalk( $field, $id ) {
1505 $dbw = wfGetDB( DB_MASTER );
1506 $dbw->insert( 'user_newtalk',
1507 array( $field => $id ),
1508 __METHOD__,
1509 'IGNORE' );
1510 if ( $dbw->affectedRows() ) {
1511 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1512 return true;
1513 } else {
1514 wfDebug( __METHOD__." already set ($field, $id)\n" );
1515 return false;
1520 * Clear the new messages flag for the given user
1521 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1522 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1523 * @return \type{\bool} True if successful, false otherwise
1524 * @private
1526 function deleteNewtalk( $field, $id ) {
1527 $dbw = wfGetDB( DB_MASTER );
1528 $dbw->delete( 'user_newtalk',
1529 array( $field => $id ),
1530 __METHOD__ );
1531 if ( $dbw->affectedRows() ) {
1532 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1533 return true;
1534 } else {
1535 wfDebug( __METHOD__.": already gone ($field, $id)\n" );
1536 return false;
1541 * Update the 'You have new messages!' status.
1542 * @param $val \type{\bool} Whether the user has new messages
1544 function setNewtalk( $val ) {
1545 if( wfReadOnly() ) {
1546 return;
1549 $this->load();
1550 $this->mNewtalk = $val;
1552 if( $this->isAnon() ) {
1553 $field = 'user_ip';
1554 $id = $this->getName();
1555 } else {
1556 $field = 'user_id';
1557 $id = $this->getId();
1559 global $wgMemc;
1561 if( $val ) {
1562 $changed = $this->updateNewtalk( $field, $id );
1563 } else {
1564 $changed = $this->deleteNewtalk( $field, $id );
1567 if( $this->isAnon() ) {
1568 // Anons have a separate memcached space, since
1569 // user records aren't kept for them.
1570 $key = wfMemcKey( 'newtalk', 'ip', $id );
1571 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1573 if ( $changed ) {
1574 $this->invalidateCache();
1579 * Generate a current or new-future timestamp to be stored in the
1580 * user_touched field when we update things.
1581 * @return \type{\string} Timestamp in TS_MW format
1583 private static function newTouchedTimestamp() {
1584 global $wgClockSkewFudge;
1585 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1589 * Clear user data from memcached.
1590 * Use after applying fun updates to the database; caller's
1591 * responsibility to update user_touched if appropriate.
1593 * Called implicitly from invalidateCache() and saveSettings().
1595 private function clearSharedCache() {
1596 if( $this->mId ) {
1597 global $wgMemc;
1598 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1603 * Immediately touch the user data cache for this account.
1604 * Updates user_touched field, and removes account data from memcached
1605 * for reload on the next hit.
1607 function invalidateCache() {
1608 $this->load();
1609 if( $this->mId ) {
1610 $this->mTouched = self::newTouchedTimestamp();
1612 $dbw = wfGetDB( DB_MASTER );
1613 $dbw->update( 'user',
1614 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1615 array( 'user_id' => $this->mId ),
1616 __METHOD__ );
1618 $this->clearSharedCache();
1623 * Validate the cache for this account.
1624 * @param $timestamp \type{\string} A timestamp in TS_MW format
1626 function validateCache( $timestamp ) {
1627 $this->load();
1628 return ($timestamp >= $this->mTouched);
1632 * Get the user touched timestamp
1634 function getTouched() {
1635 $this->load();
1636 return $this->mTouched;
1640 * Set the password and reset the random token.
1641 * Calls through to authentication plugin if necessary;
1642 * will have no effect if the auth plugin refuses to
1643 * pass the change through or if the legal password
1644 * checks fail.
1646 * As a special case, setting the password to null
1647 * wipes it, so the account cannot be logged in until
1648 * a new password is set, for instance via e-mail.
1650 * @param $str \type{\string} New password to set
1651 * @throws PasswordError on failure
1653 function setPassword( $str ) {
1654 global $wgAuth;
1656 if( $str !== null ) {
1657 if( !$wgAuth->allowPasswordChange() ) {
1658 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1661 if( !$this->isValidPassword( $str ) ) {
1662 global $wgMinimalPasswordLength;
1663 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1664 $wgMinimalPasswordLength ) );
1668 if( !$wgAuth->setPassword( $this, $str ) ) {
1669 throw new PasswordError( wfMsg( 'externaldberror' ) );
1672 $this->setInternalPassword( $str );
1674 return true;
1678 * Set the password and reset the random token unconditionally.
1680 * @param $str \type{\string} New password to set
1682 function setInternalPassword( $str ) {
1683 $this->load();
1684 $this->setToken();
1686 if( $str === null ) {
1687 // Save an invalid hash...
1688 $this->mPassword = '';
1689 } else {
1690 $this->mPassword = self::crypt( $str );
1692 $this->mNewpassword = '';
1693 $this->mNewpassTime = null;
1697 * Get the user's current token.
1698 * @return \type{\string} Token
1700 function getToken() {
1701 $this->load();
1702 return $this->mToken;
1706 * Set the random token (used for persistent authentication)
1707 * Called from loadDefaults() among other places.
1709 * @param $token \type{\string} If specified, set the token to this value
1710 * @private
1712 function setToken( $token = false ) {
1713 global $wgSecretKey, $wgProxyKey;
1714 $this->load();
1715 if ( !$token ) {
1716 if ( $wgSecretKey ) {
1717 $key = $wgSecretKey;
1718 } elseif ( $wgProxyKey ) {
1719 $key = $wgProxyKey;
1720 } else {
1721 $key = microtime();
1723 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1724 } else {
1725 $this->mToken = $token;
1730 * Set the cookie password
1732 * @param $str \type{\string} New cookie password
1733 * @private
1735 function setCookiePassword( $str ) {
1736 $this->load();
1737 $this->mCookiePassword = md5( $str );
1741 * Set the password for a password reminder or new account email
1743 * @param $str \type{\string} New password to set
1744 * @param $throttle \type{\bool} If true, reset the throttle timestamp to the present
1746 function setNewpassword( $str, $throttle = true ) {
1747 $this->load();
1748 $this->mNewpassword = self::crypt( $str );
1749 if ( $throttle ) {
1750 $this->mNewpassTime = wfTimestampNow();
1755 * Has password reminder email been sent within the last
1756 * $wgPasswordReminderResendTime hours?
1757 * @return \type{\bool} True or false
1759 function isPasswordReminderThrottled() {
1760 global $wgPasswordReminderResendTime;
1761 $this->load();
1762 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1763 return false;
1765 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1766 return time() < $expiry;
1770 * Get the user's e-mail address
1771 * @return \type{\string} User's e-mail address
1773 function getEmail() {
1774 $this->load();
1775 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1776 return $this->mEmail;
1780 * Get the timestamp of the user's e-mail authentication
1781 * @return \type{\string} TS_MW timestamp
1783 function getEmailAuthenticationTimestamp() {
1784 $this->load();
1785 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1786 return $this->mEmailAuthenticated;
1790 * Set the user's e-mail address
1791 * @param $str \type{\string} New e-mail address
1793 function setEmail( $str ) {
1794 $this->load();
1795 $this->mEmail = $str;
1796 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1800 * Get the user's real name
1801 * @return \type{\string} User's real name
1803 function getRealName() {
1804 $this->load();
1805 return $this->mRealName;
1809 * Set the user's real name
1810 * @param $str \type{\string} New real name
1812 function setRealName( $str ) {
1813 $this->load();
1814 $this->mRealName = $str;
1818 * Get the user's current setting for a given option.
1820 * @param $oname \type{\string} The option to check
1821 * @param $defaultOverride \type{\string} A default value returned if the option does not exist
1822 * @return \type{\string} User's current value for the option
1823 * @see getBoolOption()
1824 * @see getIntOption()
1826 function getOption( $oname, $defaultOverride = '' ) {
1827 $this->load();
1829 if ( is_null( $this->mOptions ) ) {
1830 if($defaultOverride != '') {
1831 return $defaultOverride;
1833 $this->mOptions = User::getDefaultOptions();
1836 if ( array_key_exists( $oname, $this->mOptions ) ) {
1837 return trim( $this->mOptions[$oname] );
1838 } else {
1839 return $defaultOverride;
1844 * Get the user's current setting for a given option, as a boolean value.
1846 * @param $oname \type{\string} The option to check
1847 * @return \type{\bool} User's current value for the option
1848 * @see getOption()
1850 function getBoolOption( $oname ) {
1851 return (bool)$this->getOption( $oname );
1856 * Get the user's current setting for a given option, as a boolean value.
1858 * @param $oname \type{\string} The option to check
1859 * @param $defaultOverride \type{\int} A default value returned if the option does not exist
1860 * @return \type{\int} User's current value for the option
1861 * @see getOption()
1863 function getIntOption( $oname, $defaultOverride=0 ) {
1864 $val = $this->getOption( $oname );
1865 if( $val == '' ) {
1866 $val = $defaultOverride;
1868 return intval( $val );
1872 * Set the given option for a user.
1874 * @param $oname \type{\string} The option to set
1875 * @param $val \type{\mixed} New value to set
1877 function setOption( $oname, $val ) {
1878 $this->load();
1879 if ( is_null( $this->mOptions ) ) {
1880 $this->mOptions = User::getDefaultOptions();
1882 if ( $oname == 'skin' ) {
1883 # Clear cached skin, so the new one displays immediately in Special:Preferences
1884 unset( $this->mSkin );
1886 // Filter out any newlines that may have passed through input validation.
1887 // Newlines are used to separate items in the options blob.
1888 if( $val ) {
1889 $val = str_replace( "\r\n", "\n", $val );
1890 $val = str_replace( "\r", "\n", $val );
1891 $val = str_replace( "\n", " ", $val );
1893 // Explicitly NULL values should refer to defaults
1894 global $wgDefaultUserOptions;
1895 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1896 $val = $wgDefaultUserOptions[$oname];
1898 $this->mOptions[$oname] = $val;
1902 * Get the user's preferred date format.
1903 * @return \type{\string} User's preferred date format
1905 function getDatePreference() {
1906 // Important migration for old data rows
1907 if ( is_null( $this->mDatePreference ) ) {
1908 global $wgLang;
1909 $value = $this->getOption( 'date' );
1910 $map = $wgLang->getDatePreferenceMigrationMap();
1911 if ( isset( $map[$value] ) ) {
1912 $value = $map[$value];
1914 $this->mDatePreference = $value;
1916 return $this->mDatePreference;
1920 * Get the permissions this user has.
1921 * @return \type{\arrayof{\string}} Array of permission names
1923 function getRights() {
1924 if ( is_null( $this->mRights ) ) {
1925 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1926 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
1927 // Force reindexation of rights when a hook has unset one of them
1928 $this->mRights = array_values( $this->mRights );
1930 return $this->mRights;
1934 * Get the list of explicit group memberships this user has.
1935 * The implicit * and user groups are not included.
1936 * @return \type{\arrayof{\string}} Array of internal group names
1938 function getGroups() {
1939 $this->load();
1940 return $this->mGroups;
1944 * Get the list of implicit group memberships this user has.
1945 * This includes all explicit groups, plus 'user' if logged in,
1946 * '*' for all accounts and autopromoted groups
1948 * @param $recache \type{\bool} Whether to avoid the cache
1949 * @return \type{\arrayof{\string}} Array of internal group names
1951 function getEffectiveGroups( $recache = false ) {
1952 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1953 $this->mEffectiveGroups = $this->getGroups();
1954 $this->mEffectiveGroups[] = '*';
1955 if( $this->getId() ) {
1956 $this->mEffectiveGroups[] = 'user';
1958 $this->mEffectiveGroups = array_unique( array_merge(
1959 $this->mEffectiveGroups,
1960 Autopromote::getAutopromoteGroups( $this )
1961 ) );
1963 # Hook for additional groups
1964 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
1967 return $this->mEffectiveGroups;
1971 * Get the user's edit count.
1972 * @return \type{\int} User's edit count
1974 function getEditCount() {
1975 if ($this->mId) {
1976 if ( !isset( $this->mEditCount ) ) {
1977 /* Populate the count, if it has not been populated yet */
1978 $this->mEditCount = User::edits($this->mId);
1980 return $this->mEditCount;
1981 } else {
1982 /* nil */
1983 return null;
1988 * Add the user to the given group.
1989 * This takes immediate effect.
1990 * @param $group \type{\string} Name of the group to add
1992 function addGroup( $group ) {
1993 $dbw = wfGetDB( DB_MASTER );
1994 if( $this->getId() ) {
1995 $dbw->insert( 'user_groups',
1996 array(
1997 'ug_user' => $this->getID(),
1998 'ug_group' => $group,
2000 'User::addGroup',
2001 array( 'IGNORE' ) );
2004 $this->loadGroups();
2005 $this->mGroups[] = $group;
2006 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2008 $this->invalidateCache();
2012 * Remove the user from the given group.
2013 * This takes immediate effect.
2014 * @param $group \type{\string} Name of the group to remove
2016 function removeGroup( $group ) {
2017 $this->load();
2018 $dbw = wfGetDB( DB_MASTER );
2019 $dbw->delete( 'user_groups',
2020 array(
2021 'ug_user' => $this->getID(),
2022 'ug_group' => $group,
2024 'User::removeGroup' );
2026 $this->loadGroups();
2027 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2028 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2030 $this->invalidateCache();
2035 * Get whether the user is logged in
2036 * @return \type{\bool} True or false
2038 function isLoggedIn() {
2039 return $this->getID() != 0;
2043 * Get whether the user is anonymous
2044 * @return \type{\bool} True or false
2046 function isAnon() {
2047 return !$this->isLoggedIn();
2051 * Get whether the user is a bot
2052 * @return \type{\bool} True or false
2053 * @deprecated
2055 function isBot() {
2056 wfDeprecated( __METHOD__ );
2057 return $this->isAllowed( 'bot' );
2061 * Check if user is allowed to access a feature / make an action
2062 * @param $action \type{\string} action to be checked
2063 * @return \type{\bool} True if action is allowed, else false
2065 function isAllowed($action='') {
2066 if ( $action === '' )
2067 // In the spirit of DWIM
2068 return true;
2070 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2071 # by misconfiguration: 0 == 'foo'
2072 return in_array( $action, $this->getRights(), true );
2076 * Check whether to enable recent changes patrol features for this user
2077 * @return \type{\bool} True or false
2079 public function useRCPatrol() {
2080 global $wgUseRCPatrol;
2081 return( $wgUseRCPatrol && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
2085 * Check whether to enable new pages patrol features for this user
2086 * @return \type{\bool} True or false
2088 public function useNPPatrol() {
2089 global $wgUseRCPatrol, $wgUseNPPatrol;
2090 return( ($wgUseRCPatrol || $wgUseNPPatrol) && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
2094 * Get the current skin, loading it if required
2095 * @return \type{Skin} Current skin
2096 * @todo FIXME : need to check the old failback system [AV]
2098 function &getSkin() {
2099 global $wgRequest;
2100 if ( ! isset( $this->mSkin ) ) {
2101 wfProfileIn( __METHOD__ );
2103 # get the user skin
2104 $userSkin = $this->getOption( 'skin' );
2105 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2107 $this->mSkin =& Skin::newFromKey( $userSkin );
2108 wfProfileOut( __METHOD__ );
2110 return $this->mSkin;
2114 * Check the watched status of an article.
2115 * @param $title \type{Title} Title of the article to look at
2116 * @return \type{\bool} True if article is watched
2118 function isWatched( $title ) {
2119 $wl = WatchedItem::fromUserTitle( $this, $title );
2120 return $wl->isWatched();
2124 * Watch an article.
2125 * @param $title \type{Title} Title of the article to look at
2127 function addWatch( $title ) {
2128 $wl = WatchedItem::fromUserTitle( $this, $title );
2129 $wl->addWatch();
2130 $this->invalidateCache();
2134 * Stop watching an article.
2135 * @param $title \type{Title} Title of the article to look at
2137 function removeWatch( $title ) {
2138 $wl = WatchedItem::fromUserTitle( $this, $title );
2139 $wl->removeWatch();
2140 $this->invalidateCache();
2144 * Clear the user's notification timestamp for the given title.
2145 * If e-notif e-mails are on, they will receive notification mails on
2146 * the next change of the page if it's watched etc.
2147 * @param $title \type{Title} Title of the article to look at
2149 function clearNotification( &$title ) {
2150 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2152 # Do nothing if the database is locked to writes
2153 if( wfReadOnly() ) {
2154 return;
2157 if ($title->getNamespace() == NS_USER_TALK &&
2158 $title->getText() == $this->getName() ) {
2159 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2160 return;
2161 $this->setNewtalk( false );
2164 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2165 return;
2168 if( $this->isAnon() ) {
2169 // Nothing else to do...
2170 return;
2173 // Only update the timestamp if the page is being watched.
2174 // The query to find out if it is watched is cached both in memcached and per-invocation,
2175 // and when it does have to be executed, it can be on a slave
2176 // If this is the user's newtalk page, we always update the timestamp
2177 if ($title->getNamespace() == NS_USER_TALK &&
2178 $title->getText() == $wgUser->getName())
2180 $watched = true;
2181 } elseif ( $this->getId() == $wgUser->getId() ) {
2182 $watched = $title->userIsWatching();
2183 } else {
2184 $watched = true;
2187 // If the page is watched by the user (or may be watched), update the timestamp on any
2188 // any matching rows
2189 if ( $watched ) {
2190 $dbw = wfGetDB( DB_MASTER );
2191 $dbw->update( 'watchlist',
2192 array( /* SET */
2193 'wl_notificationtimestamp' => NULL
2194 ), array( /* WHERE */
2195 'wl_title' => $title->getDBkey(),
2196 'wl_namespace' => $title->getNamespace(),
2197 'wl_user' => $this->getID()
2198 ), __METHOD__
2204 * Resets all of the given user's page-change notification timestamps.
2205 * If e-notif e-mails are on, they will receive notification mails on
2206 * the next change of any watched page.
2208 * @param $currentUser \type{\int} %User ID
2210 function clearAllNotifications( $currentUser ) {
2211 global $wgUseEnotif, $wgShowUpdatedMarker;
2212 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2213 $this->setNewtalk( false );
2214 return;
2216 if( $currentUser != 0 ) {
2217 $dbw = wfGetDB( DB_MASTER );
2218 $dbw->update( 'watchlist',
2219 array( /* SET */
2220 'wl_notificationtimestamp' => NULL
2221 ), array( /* WHERE */
2222 'wl_user' => $currentUser
2223 ), __METHOD__
2225 # We also need to clear here the "you have new message" notification for the own user_talk page
2226 # This is cleared one page view later in Article::viewUpdates();
2231 * Encode this user's options as a string
2232 * @return \type{\string} Encoded options
2233 * @private
2235 function encodeOptions() {
2236 $this->load();
2237 if ( is_null( $this->mOptions ) ) {
2238 $this->mOptions = User::getDefaultOptions();
2240 $a = array();
2241 foreach ( $this->mOptions as $oname => $oval ) {
2242 array_push( $a, $oname.'='.$oval );
2244 $s = implode( "\n", $a );
2245 return $s;
2249 * Set this user's options from an encoded string
2250 * @param $str \type{\string} Encoded options to import
2251 * @private
2253 function decodeOptions( $str ) {
2254 $this->mOptions = array();
2255 $a = explode( "\n", $str );
2256 foreach ( $a as $s ) {
2257 $m = array();
2258 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2259 $this->mOptions[$m[1]] = $m[2];
2265 * Set a cookie on the user's client. Wrapper for
2266 * WebResponse::setCookie
2268 protected function setCookie( $name, $value, $exp=0 ) {
2269 global $wgRequest;
2270 $wgRequest->response()->setcookie( $name, $value, $exp );
2274 * Clear a cookie on the user's client
2275 * @param $name \type{\string} Name of the cookie to clear
2277 protected function clearCookie( $name ) {
2278 $this->setCookie( $name, '', time() - 86400 );
2282 * Set the default cookies for this session on the user's client.
2284 function setCookies() {
2285 $this->load();
2286 if ( 0 == $this->mId ) return;
2287 $session = array(
2288 'wsUserID' => $this->mId,
2289 'wsToken' => $this->mToken,
2290 'wsUserName' => $this->getName()
2292 $cookies = array(
2293 'UserID' => $this->mId,
2294 'UserName' => $this->getName(),
2296 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2297 $cookies['Token'] = $this->mToken;
2298 } else {
2299 $cookies['Token'] = false;
2302 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2303 $_SESSION = $session + $_SESSION;
2304 foreach ( $cookies as $name => $value ) {
2305 if ( $value === false ) {
2306 $this->clearCookie( $name );
2307 } else {
2308 $this->setCookie( $name, $value );
2314 * Log this user out.
2316 function logout() {
2317 global $wgUser;
2318 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2319 $this->doLogout();
2324 * Clear the user's cookies and session, and reset the instance cache.
2325 * @private
2326 * @see logout()
2328 function doLogout() {
2329 $this->clearInstanceCache( 'defaults' );
2331 $_SESSION['wsUserID'] = 0;
2333 $this->clearCookie( 'UserID' );
2334 $this->clearCookie( 'Token' );
2336 # Remember when user logged out, to prevent seeing cached pages
2337 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2341 * Save this user's settings into the database.
2342 * @todo Only rarely do all these fields need to be set!
2344 function saveSettings() {
2345 $this->load();
2346 if ( wfReadOnly() ) { return; }
2347 if ( 0 == $this->mId ) { return; }
2349 $this->mTouched = self::newTouchedTimestamp();
2351 $dbw = wfGetDB( DB_MASTER );
2352 $dbw->update( 'user',
2353 array( /* SET */
2354 'user_name' => $this->mName,
2355 'user_password' => $this->mPassword,
2356 'user_newpassword' => $this->mNewpassword,
2357 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2358 'user_real_name' => $this->mRealName,
2359 'user_email' => $this->mEmail,
2360 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2361 'user_options' => $this->encodeOptions(),
2362 'user_touched' => $dbw->timestamp($this->mTouched),
2363 'user_token' => $this->mToken,
2364 'user_email_token' => $this->mEmailToken,
2365 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2366 ), array( /* WHERE */
2367 'user_id' => $this->mId
2368 ), __METHOD__
2370 wfRunHooks( 'UserSaveSettings', array( $this ) );
2371 $this->clearSharedCache();
2375 * If only this user's username is known, and it exists, return the user ID.
2377 function idForName() {
2378 $s = trim( $this->getName() );
2379 if ( $s === '' ) return 0;
2381 $dbr = wfGetDB( DB_SLAVE );
2382 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2383 if ( $id === false ) {
2384 $id = 0;
2386 return $id;
2390 * Add a user to the database, return the user object
2392 * @param $name \type{\string} Username to add
2393 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2394 * - password The user's password. Password logins will be disabled if this is omitted.
2395 * - newpassword A temporary password mailed to the user
2396 * - email The user's email address
2397 * - email_authenticated The email authentication timestamp
2398 * - real_name The user's real name
2399 * - options An associative array of non-default options
2400 * - token Random authentication token. Do not set.
2401 * - registration Registration timestamp. Do not set.
2403 * @return \type{User} A new User object, or null if the username already exists
2405 static function createNew( $name, $params = array() ) {
2406 $user = new User;
2407 $user->load();
2408 if ( isset( $params['options'] ) ) {
2409 $user->mOptions = $params['options'] + $user->mOptions;
2410 unset( $params['options'] );
2412 $dbw = wfGetDB( DB_MASTER );
2413 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2414 $fields = array(
2415 'user_id' => $seqVal,
2416 'user_name' => $name,
2417 'user_password' => $user->mPassword,
2418 'user_newpassword' => $user->mNewpassword,
2419 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
2420 'user_email' => $user->mEmail,
2421 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2422 'user_real_name' => $user->mRealName,
2423 'user_options' => $user->encodeOptions(),
2424 'user_token' => $user->mToken,
2425 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2426 'user_editcount' => 0,
2428 foreach ( $params as $name => $value ) {
2429 $fields["user_$name"] = $value;
2431 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2432 if ( $dbw->affectedRows() ) {
2433 $newUser = User::newFromId( $dbw->insertId() );
2434 } else {
2435 $newUser = null;
2437 return $newUser;
2441 * Add this existing user object to the database
2443 function addToDatabase() {
2444 $this->load();
2445 $dbw = wfGetDB( DB_MASTER );
2446 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2447 $dbw->insert( 'user',
2448 array(
2449 'user_id' => $seqVal,
2450 'user_name' => $this->mName,
2451 'user_password' => $this->mPassword,
2452 'user_newpassword' => $this->mNewpassword,
2453 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
2454 'user_email' => $this->mEmail,
2455 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2456 'user_real_name' => $this->mRealName,
2457 'user_options' => $this->encodeOptions(),
2458 'user_token' => $this->mToken,
2459 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2460 'user_editcount' => 0,
2461 ), __METHOD__
2463 $this->mId = $dbw->insertId();
2465 // Clear instance cache other than user table data, which is already accurate
2466 $this->clearInstanceCache();
2470 * If this (non-anonymous) user is blocked, block any IP address
2471 * they've successfully logged in from.
2473 function spreadBlock() {
2474 wfDebug( __METHOD__."()\n" );
2475 $this->load();
2476 if ( $this->mId == 0 ) {
2477 return;
2480 $userblock = Block::newFromDB( '', $this->mId );
2481 if ( !$userblock ) {
2482 return;
2485 $userblock->doAutoblock( wfGetIp() );
2490 * Generate a string which will be different for any combination of
2491 * user options which would produce different parser output.
2492 * This will be used as part of the hash key for the parser cache,
2493 * so users will the same options can share the same cached data
2494 * safely.
2496 * Extensions which require it should install 'PageRenderingHash' hook,
2497 * which will give them a chance to modify this key based on their own
2498 * settings.
2500 * @return \type{\string} Page rendering hash
2502 function getPageRenderingHash() {
2503 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2504 if( $this->mHash ){
2505 return $this->mHash;
2508 // stubthreshold is only included below for completeness,
2509 // it will always be 0 when this function is called by parsercache.
2511 $confstr = $this->getOption( 'math' );
2512 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2513 if ( $wgUseDynamicDates ) {
2514 $confstr .= '!' . $this->getDatePreference();
2516 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2517 $confstr .= '!' . $wgLang->getCode();
2518 $confstr .= '!' . $this->getOption( 'thumbsize' );
2519 // add in language specific options, if any
2520 $extra = $wgContLang->getExtraHashOptions();
2521 $confstr .= $extra;
2523 $confstr .= $wgRenderHashAppend;
2525 // Give a chance for extensions to modify the hash, if they have
2526 // extra options or other effects on the parser cache.
2527 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2529 // Make it a valid memcached key fragment
2530 $confstr = str_replace( ' ', '_', $confstr );
2531 $this->mHash = $confstr;
2532 return $confstr;
2536 * Get whether the user is explicitly blocked from account creation.
2537 * @return \type{\bool} True if blocked
2539 function isBlockedFromCreateAccount() {
2540 $this->getBlockedStatus();
2541 return $this->mBlock && $this->mBlock->mCreateAccount;
2545 * Get whether the user is blocked from using Special:Emailuser.
2546 * @return \type{\bool} True if blocked
2548 function isBlockedFromEmailuser() {
2549 $this->getBlockedStatus();
2550 return $this->mBlock && $this->mBlock->mBlockEmail;
2554 * Get whether the user is allowed to create an account.
2555 * @return \type{\bool} True if allowed
2557 function isAllowedToCreateAccount() {
2558 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2562 * @deprecated
2564 function setLoaded( $loaded ) {
2565 wfDeprecated( __METHOD__ );
2569 * Get this user's personal page title.
2571 * @return \type{Title} User's personal page title
2573 function getUserPage() {
2574 return Title::makeTitle( NS_USER, $this->getName() );
2578 * Get this user's talk page title.
2580 * @return \type{Title} User's talk page title
2582 function getTalkPage() {
2583 $title = $this->getUserPage();
2584 return $title->getTalkPage();
2588 * Get the maximum valid user ID.
2589 * @return \type{\int} %User ID
2590 * @static
2592 function getMaxID() {
2593 static $res; // cache
2595 if ( isset( $res ) )
2596 return $res;
2597 else {
2598 $dbr = wfGetDB( DB_SLAVE );
2599 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2604 * Determine whether the user is a newbie. Newbies are either
2605 * anonymous IPs, or the most recently created accounts.
2606 * @return \type{\bool} True if the user is a newbie
2608 function isNewbie() {
2609 return !$this->isAllowed( 'autoconfirmed' );
2613 * Is the user active? We check to see if they've made at least
2614 * X number of edits in the last Y days.
2616 * @return \type{\bool} True if the user is active, false if not.
2618 public function isActiveEditor() {
2619 global $wgActiveUserEditCount, $wgActiveUserDays;
2620 $dbr = wfGetDB( DB_SLAVE );
2622 // Stolen without shame from RC
2623 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2624 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime % 86400 );
2625 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2627 $res = $dbr->select( 'revision', '1',
2628 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2629 __METHOD__,
2630 array('LIMIT' => $wgActiveUserEditCount ) );
2632 $count = $dbr->numRows($res);
2633 $dbr->freeResult($res);
2635 return $count == $wgActiveUserEditCount;
2639 * Check to see if the given clear-text password is one of the accepted passwords
2640 * @param $password \type{\string} user password.
2641 * @return \type{\bool} True if the given password is correct, otherwise False.
2643 function checkPassword( $password ) {
2644 global $wgAuth;
2645 $this->load();
2647 // Even though we stop people from creating passwords that
2648 // are shorter than this, doesn't mean people wont be able
2649 // to. Certain authentication plugins do NOT want to save
2650 // domain passwords in a mysql database, so we should
2651 // check this (incase $wgAuth->strict() is false).
2652 if( !$this->isValidPassword( $password ) ) {
2653 return false;
2656 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2657 return true;
2658 } elseif( $wgAuth->strict() ) {
2659 /* Auth plugin doesn't allow local authentication */
2660 return false;
2661 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2662 /* Auth plugin doesn't allow local authentication for this user name */
2663 return false;
2665 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2666 return true;
2667 } elseif ( function_exists( 'iconv' ) ) {
2668 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2669 # Check for this with iconv
2670 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2671 if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
2672 return true;
2675 return false;
2679 * Check if the given clear-text password matches the temporary password
2680 * sent by e-mail for password reset operations.
2681 * @return \type{\bool} True if matches, false otherwise
2683 function checkTemporaryPassword( $plaintext ) {
2684 return self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() );
2688 * Initialize (if necessary) and return a session token value
2689 * which can be used in edit forms to show that the user's
2690 * login credentials aren't being hijacked with a foreign form
2691 * submission.
2693 * @param $salt \twotypes{\string,\arrayof{\string}} Optional function-specific data for hashing
2694 * @return \type{\string} The new edit token
2696 function editToken( $salt = '' ) {
2697 if ( $this->isAnon() ) {
2698 return EDIT_TOKEN_SUFFIX;
2699 } else {
2700 if( !isset( $_SESSION['wsEditToken'] ) ) {
2701 $token = $this->generateToken();
2702 $_SESSION['wsEditToken'] = $token;
2703 } else {
2704 $token = $_SESSION['wsEditToken'];
2706 if( is_array( $salt ) ) {
2707 $salt = implode( '|', $salt );
2709 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2714 * Generate a looking random token for various uses.
2716 * @param $salt \type{\string} Optional salt value
2717 * @return \type{\string} The new random token
2719 function generateToken( $salt = '' ) {
2720 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2721 return md5( $token . $salt );
2725 * Check given value against the token value stored in the session.
2726 * A match should confirm that the form was submitted from the
2727 * user's own login session, not a form submission from a third-party
2728 * site.
2730 * @param $val \type{\string} Input value to compare
2731 * @param $salt \type{\string} Optional function-specific data for hashing
2732 * @return \type{\bool} Whether the token matches
2734 function matchEditToken( $val, $salt = '' ) {
2735 $sessionToken = $this->editToken( $salt );
2736 if ( $val != $sessionToken ) {
2737 wfDebug( "User::matchEditToken: broken session data\n" );
2739 return $val == $sessionToken;
2743 * Check given value against the token value stored in the session,
2744 * ignoring the suffix.
2746 * @param $val \type{\string} Input value to compare
2747 * @param $salt \type{\string} Optional function-specific data for hashing
2748 * @return \type{\bool} Whether the token matches
2750 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2751 $sessionToken = $this->editToken( $salt );
2752 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2756 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2757 * mail to the user's given address.
2759 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure.
2761 function sendConfirmationMail() {
2762 global $wgLang;
2763 $expiration = null; // gets passed-by-ref and defined in next line.
2764 $token = $this->confirmationToken( $expiration );
2765 $url = $this->confirmationTokenUrl( $token );
2766 $invalidateURL = $this->invalidationTokenUrl( $token );
2767 $this->saveSettings();
2769 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2770 wfMsg( 'confirmemail_body',
2771 wfGetIP(),
2772 $this->getName(),
2773 $url,
2774 $wgLang->timeanddate( $expiration, false ),
2775 $invalidateURL ) );
2779 * Send an e-mail to this user's account. Does not check for
2780 * confirmed status or validity.
2782 * @param $subject \type{\string} Message subject
2783 * @param $body \type{\string} Message body
2784 * @param $from \type{\string} Optional From address; if unspecified, default $wgPasswordSender will be used
2785 * @param $replyto \type{\string} Reply-to address
2786 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure
2788 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2789 if( is_null( $from ) ) {
2790 global $wgPasswordSender;
2791 $from = $wgPasswordSender;
2794 $to = new MailAddress( $this );
2795 $sender = new MailAddress( $from );
2796 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2800 * Generate, store, and return a new e-mail confirmation code.
2801 * A hash (unsalted, since it's used as a key) is stored.
2803 * @note Call saveSettings() after calling this function to commit
2804 * this change to the database.
2806 * @param[out] &$expiration \type{\mixed} Accepts the expiration time
2807 * @return \type{\string} New token
2808 * @private
2810 function confirmationToken( &$expiration ) {
2811 $now = time();
2812 $expires = $now + 7 * 24 * 60 * 60;
2813 $expiration = wfTimestamp( TS_MW, $expires );
2814 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2815 $hash = md5( $token );
2816 $this->load();
2817 $this->mEmailToken = $hash;
2818 $this->mEmailTokenExpires = $expiration;
2819 return $token;
2823 * Return a URL the user can use to confirm their email address.
2824 * @param $token \type{\string} Accepts the email confirmation token
2825 * @return \type{\string} New token URL
2826 * @private
2828 function confirmationTokenUrl( $token ) {
2829 return $this->getTokenUrl( 'ConfirmEmail', $token );
2832 * Return a URL the user can use to invalidate their email address.
2834 * @param $token \type{\string} Accepts the email confirmation token
2835 * @return \type{\string} New token URL
2836 * @private
2838 function invalidationTokenUrl( $token ) {
2839 return $this->getTokenUrl( 'Invalidateemail', $token );
2843 * Internal function to format the e-mail validation/invalidation URLs.
2844 * This uses $wgArticlePath directly as a quickie hack to use the
2845 * hardcoded English names of the Special: pages, for ASCII safety.
2847 * @note Since these URLs get dropped directly into emails, using the
2848 * short English names avoids insanely long URL-encoded links, which
2849 * also sometimes can get corrupted in some browsers/mailers
2850 * (bug 6957 with Gmail and Internet Explorer).
2852 * @param $page \type{\string} Special page
2853 * @param $token \type{\string} Token
2854 * @return \type{\string} Formatted URL
2856 protected function getTokenUrl( $page, $token ) {
2857 global $wgArticlePath;
2858 return wfExpandUrl(
2859 str_replace(
2860 '$1',
2861 "Special:$page/$token",
2862 $wgArticlePath ) );
2866 * Mark the e-mail address confirmed.
2868 * @note Call saveSettings() after calling this function to commit the change.
2870 function confirmEmail() {
2871 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2872 return true;
2876 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2877 * address if it was already confirmed.
2879 * @note Call saveSettings() after calling this function to commit the change.
2881 function invalidateEmail() {
2882 $this->load();
2883 $this->mEmailToken = null;
2884 $this->mEmailTokenExpires = null;
2885 $this->setEmailAuthenticationTimestamp( null );
2886 return true;
2890 * Set the e-mail authentication timestamp.
2891 * @param $timestamp \type{\string} TS_MW timestamp
2893 function setEmailAuthenticationTimestamp( $timestamp ) {
2894 $this->load();
2895 $this->mEmailAuthenticated = $timestamp;
2896 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2900 * Is this user allowed to send e-mails within limits of current
2901 * site configuration?
2902 * @return \type{\bool} True if allowed
2904 function canSendEmail() {
2905 $canSend = $this->isEmailConfirmed();
2906 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2907 return $canSend;
2911 * Is this user allowed to receive e-mails within limits of current
2912 * site configuration?
2913 * @return \type{\bool} True if allowed
2915 function canReceiveEmail() {
2916 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2920 * Is this user's e-mail address valid-looking and confirmed within
2921 * limits of the current site configuration?
2923 * @note If $wgEmailAuthentication is on, this may require the user to have
2924 * confirmed their address by returning a code or using a password
2925 * sent to the address from the wiki.
2927 * @return \type{\bool} True if confirmed
2929 function isEmailConfirmed() {
2930 global $wgEmailAuthentication;
2931 $this->load();
2932 $confirmed = true;
2933 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2934 if( $this->isAnon() )
2935 return false;
2936 if( !self::isValidEmailAddr( $this->mEmail ) )
2937 return false;
2938 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2939 return false;
2940 return true;
2941 } else {
2942 return $confirmed;
2947 * Check whether there is an outstanding request for e-mail confirmation.
2948 * @return \type{\bool} True if pending
2950 function isEmailConfirmationPending() {
2951 global $wgEmailAuthentication;
2952 return $wgEmailAuthentication &&
2953 !$this->isEmailConfirmed() &&
2954 $this->mEmailToken &&
2955 $this->mEmailTokenExpires > wfTimestamp();
2959 * Get the timestamp of account creation.
2961 * @return \twotypes{\string,\bool} string Timestamp of account creation, or false for
2962 * non-existent/anonymous user accounts.
2964 public function getRegistration() {
2965 return $this->mId > 0
2966 ? $this->mRegistration
2967 : false;
2971 * Get the permissions associated with a given list of groups
2973 * @param $groups \type{\arrayof{\string}} List of internal group names
2974 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
2976 static function getGroupPermissions( $groups ) {
2977 global $wgGroupPermissions;
2978 $rights = array();
2979 foreach( $groups as $group ) {
2980 if( isset( $wgGroupPermissions[$group] ) ) {
2981 $rights = array_merge( $rights,
2982 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2985 return $rights;
2989 * Get all the groups who have a given permission
2991 * @param $role \type{\string} Role to check
2992 * @return \type{\arrayof{\string}} List of internal group names with the given permission
2994 static function getGroupsWithPermission( $role ) {
2995 global $wgGroupPermissions;
2996 $allowedGroups = array();
2997 foreach ( $wgGroupPermissions as $group => $rights ) {
2998 if ( isset( $rights[$role] ) && $rights[$role] ) {
2999 $allowedGroups[] = $group;
3002 return $allowedGroups;
3006 * Get the localized descriptive name for a group, if it exists
3008 * @param $group \type{\string} Internal group name
3009 * @return \type{\string} Localized descriptive group name
3011 static function getGroupName( $group ) {
3012 global $wgMessageCache;
3013 $wgMessageCache->loadAllMessages();
3014 $key = "group-$group";
3015 $name = wfMsg( $key );
3016 return $name == '' || wfEmptyMsg( $key, $name )
3017 ? $group
3018 : $name;
3022 * Get the localized descriptive name for a member of a group, if it exists
3024 * @param $group \type{\string} Internal group name
3025 * @return \type{\string} Localized name for group member
3027 static function getGroupMember( $group ) {
3028 global $wgMessageCache;
3029 $wgMessageCache->loadAllMessages();
3030 $key = "group-$group-member";
3031 $name = wfMsg( $key );
3032 return $name == '' || wfEmptyMsg( $key, $name )
3033 ? $group
3034 : $name;
3038 * Return the set of defined explicit groups.
3039 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3040 * are not included, as they are defined automatically, not in the database.
3041 * @return \type{\arrayof{\string}} Array of internal group names
3043 static function getAllGroups() {
3044 global $wgGroupPermissions;
3045 return array_diff(
3046 array_keys( $wgGroupPermissions ),
3047 self::getImplicitGroups()
3052 * Get a list of all available permissions.
3053 * @return \type{\arrayof{\string}} Array of permission names
3055 static function getAllRights() {
3056 if ( self::$mAllRights === false ) {
3057 global $wgAvailableRights;
3058 if ( count( $wgAvailableRights ) ) {
3059 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3060 } else {
3061 self::$mAllRights = self::$mCoreRights;
3063 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3065 return self::$mAllRights;
3069 * Get a list of implicit groups
3070 * @return \type{\arrayof{\string}} Array of internal group names
3072 public static function getImplicitGroups() {
3073 global $wgImplicitGroups;
3074 $groups = $wgImplicitGroups;
3075 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3076 return $groups;
3080 * Get the title of a page describing a particular group
3082 * @param $group \type{\string} Internal group name
3083 * @return \twotypes{Title,\bool} Title of the page if it exists, false otherwise
3085 static function getGroupPage( $group ) {
3086 global $wgMessageCache;
3087 $wgMessageCache->loadAllMessages();
3088 $page = wfMsgForContent( 'grouppage-' . $group );
3089 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3090 $title = Title::newFromText( $page );
3091 if( is_object( $title ) )
3092 return $title;
3094 return false;
3098 * Create a link to the group in HTML, if available;
3099 * else return the group name.
3101 * @param $group \type{\string} Internal name of the group
3102 * @param $text \type{\string} The text of the link
3103 * @return \type{\string} HTML link to the group
3105 static function makeGroupLinkHTML( $group, $text = '' ) {
3106 if( $text == '' ) {
3107 $text = self::getGroupName( $group );
3109 $title = self::getGroupPage( $group );
3110 if( $title ) {
3111 global $wgUser;
3112 $sk = $wgUser->getSkin();
3113 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3114 } else {
3115 return $text;
3120 * Create a link to the group in Wikitext, if available;
3121 * else return the group name.
3123 * @param $group \type{\string} Internal name of the group
3124 * @param $text \type{\string} The text of the link
3125 * @return \type{\string} Wikilink to the group
3127 static function makeGroupLinkWiki( $group, $text = '' ) {
3128 if( $text == '' ) {
3129 $text = self::getGroupName( $group );
3131 $title = self::getGroupPage( $group );
3132 if( $title ) {
3133 $page = $title->getPrefixedText();
3134 return "[[$page|$text]]";
3135 } else {
3136 return $text;
3141 * Increment the user's edit-count field.
3142 * Will have no effect for anonymous users.
3144 function incEditCount() {
3145 if( !$this->isAnon() ) {
3146 $dbw = wfGetDB( DB_MASTER );
3147 $dbw->update( 'user',
3148 array( 'user_editcount=user_editcount+1' ),
3149 array( 'user_id' => $this->getId() ),
3150 __METHOD__ );
3152 // Lazy initialization check...
3153 if( $dbw->affectedRows() == 0 ) {
3154 // Pull from a slave to be less cruel to servers
3155 // Accuracy isn't the point anyway here
3156 $dbr = wfGetDB( DB_SLAVE );
3157 $count = $dbr->selectField( 'revision',
3158 'COUNT(rev_user)',
3159 array( 'rev_user' => $this->getId() ),
3160 __METHOD__ );
3162 // Now here's a goddamn hack...
3163 if( $dbr !== $dbw ) {
3164 // If we actually have a slave server, the count is
3165 // at least one behind because the current transaction
3166 // has not been committed and replicated.
3167 $count++;
3168 } else {
3169 // But if DB_SLAVE is selecting the master, then the
3170 // count we just read includes the revision that was
3171 // just added in the working transaction.
3174 $dbw->update( 'user',
3175 array( 'user_editcount' => $count ),
3176 array( 'user_id' => $this->getId() ),
3177 __METHOD__ );
3180 // edit count in user cache too
3181 $this->invalidateCache();
3185 * Get the description of a given right
3187 * @param $right \type{\string} Right to query
3188 * @return \type{\string} Localized description of the right
3190 static function getRightDescription( $right ) {
3191 global $wgMessageCache;
3192 $wgMessageCache->loadAllMessages();
3193 $key = "right-$right";
3194 $name = wfMsg( $key );
3195 return $name == '' || wfEmptyMsg( $key, $name )
3196 ? $right
3197 : $name;
3201 * Make an old-style password hash
3203 * @param $password \type{\string} Plain-text password
3204 * @param $userId \type{\string} %User ID
3205 * @return \type{\string} Password hash
3207 static function oldCrypt( $password, $userId ) {
3208 global $wgPasswordSalt;
3209 if ( $wgPasswordSalt ) {
3210 return md5( $userId . '-' . md5( $password ) );
3211 } else {
3212 return md5( $password );
3217 * Make a new-style password hash
3219 * @param $password \type{\string} Plain-text password
3220 * @param $salt \type{\string} Optional salt, may be random or the user ID.
3221 * If unspecified or false, will generate one automatically
3222 * @return \type{\string} Password hash
3224 static function crypt( $password, $salt = false ) {
3225 global $wgPasswordSalt;
3227 if($wgPasswordSalt) {
3228 if ( $salt === false ) {
3229 $salt = substr( wfGenerateToken(), 0, 8 );
3231 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3232 } else {
3233 return ':A:' . md5( $password);
3238 * Compare a password hash with a plain-text password. Requires the user
3239 * ID if there's a chance that the hash is an old-style hash.
3241 * @param $hash \type{\string} Password hash
3242 * @param $password \type{\string} Plain-text password to compare
3243 * @param $userId \type{\string} %User ID for old-style password salt
3244 * @return \type{\bool} True if matches, false otherwise
3246 static function comparePasswords( $hash, $password, $userId = false ) {
3247 $m = false;
3248 $type = substr( $hash, 0, 3 );
3249 if ( $type == ':A:' ) {
3250 # Unsalted
3251 return md5( $password ) === substr( $hash, 3 );
3252 } elseif ( $type == ':B:' ) {
3253 # Salted
3254 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3255 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3256 } else {
3257 # Old-style
3258 return self::oldCrypt( $password, $userId ) === $hash;
3263 * Add a newuser log entry for this user
3264 * @param bool $byEmail, account made by email?
3266 public function addNewUserLogEntry( $byEmail = false ) {
3267 global $wgUser, $wgContLang, $wgNewUserLog;
3268 if( empty($wgNewUserLog) ) {
3269 return true; // disabled
3271 $talk = $wgContLang->getFormattedNsText( NS_TALK );
3272 if( $this->getName() == $wgUser->getName() ) {
3273 $action = 'create';
3274 $message = '';
3275 } else {
3276 $action = 'create2';
3277 $message = $byEmail ? wfMsgForContent( 'newuserlog-byemail' ) : '';
3279 $log = new LogPage( 'newusers' );
3280 $log->addEntry( $action, $this->getUserPage(), $message, array( $this->getId() ) );
3281 return true;
3285 * Add an autocreate newuser log entry for this user
3286 * Used by things like CentralAuth and perhaps other authplugins.
3288 public function addNewUserLogEntryAutoCreate() {
3289 global $wgNewUserLog;
3290 if( empty($wgNewUserLog) ) {
3291 return true; // disabled
3293 $log = new LogPage( 'newusers', false );
3294 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3295 return true;