7 # Number of characters in user_token field
8 define( 'USER_TOKEN_LENGTH', 32 );
10 # Serialized record version
11 define( 'MW_USER_VERSION', 5 );
13 # Some punctuation to prevent editing from broken text-mangling proxies.
14 # FIXME: this is embedded unescaped into HTML attributes in various
15 # places, so we can't safely include ' or " even though we really should.
16 define( 'EDIT_TOKEN_SUFFIX', '\\' );
19 * Thrown by User::setPassword() on error
20 * @addtogroup Exception
22 class PasswordError
extends MWException
{
27 * The User object encapsulates all of the user-specific settings (user_id,
28 * name, rights, password, email address, options, last login time). Client
29 * classes use the getXXX() functions to access these fields. These functions
30 * do all the work of determining whether the user is logged in,
31 * whether the requested option can be satisfied from cookies or
32 * whether a database query is needed. Most of the settings needed
33 * for rendering normal pages are set in the cookie to minimize use
39 * A list of default user toggles, i.e. boolean user preferences that are
40 * displayed by Special:Preferences as checkboxes. This list can be
41 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
43 static public $mToggles = array(
53 'editsectiononrightclick',
65 'enotifwatchlistpages',
66 'enotifusertalkpages',
69 'shownumberswatching',
84 * List of member variables which are saved to the shared cache (memcached).
85 * Any operation which changes the corresponding database fields must
86 * call a cache-clearing function.
88 static $mCacheVars = array(
100 'mEmailAuthenticated',
102 'mEmailTokenExpires',
110 * The cache variable declarations
112 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
113 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
114 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
117 * Whether the cache variables have been loaded
122 * Initialisation data source if mDataLoaded==false. May be one of:
123 * defaults anonymous user initialised from class defaults
124 * name initialise from mName
125 * id initialise from mId
126 * session log in from cookies or session if possible
128 * Use the User::newFrom*() family of functions to set this.
133 * Lazy-initialised variables, invalidated with clearInstanceCache
135 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
136 $mBlockreason, $mBlock, $mEffectiveGroups;
139 * Lightweight constructor for anonymous user
140 * Use the User::newFrom* factory functions for other kinds of users
143 $this->clearInstanceCache( 'defaults' );
147 * Load the user table data for this object from the source given by mFrom
150 if ( $this->mDataLoaded
) {
153 wfProfileIn( __METHOD__
);
155 # Set it now to avoid infinite recursion in accessors
156 $this->mDataLoaded
= true;
158 switch ( $this->mFrom
) {
160 $this->loadDefaults();
163 $this->mId
= self
::idFromName( $this->mName
);
165 # Nonexistent user placeholder object
166 $this->loadDefaults( $this->mName
);
175 $this->loadFromSession();
178 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
180 wfProfileOut( __METHOD__
);
184 * Load user table data given mId
185 * @return false if the ID does not exist, true otherwise
188 function loadFromId() {
190 if ( $this->mId
== 0 ) {
191 $this->loadDefaults();
196 $key = wfMemcKey( 'user', 'id', $this->mId
);
197 $data = $wgMemc->get( $key );
198 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
199 # Object is expired, load from DB
204 wfDebug( "Cache miss for user {$this->mId}\n" );
206 if ( !$this->loadFromDatabase() ) {
207 # Can't load from ID, user is anonymous
213 foreach ( self
::$mCacheVars as $name ) {
214 $data[$name] = $this->$name;
216 $data['mVersion'] = MW_USER_VERSION
;
217 $wgMemc->set( $key, $data );
219 wfDebug( "Got user {$this->mId} from cache\n" );
221 foreach ( self
::$mCacheVars as $name ) {
222 $this->$name = $data[$name];
229 * Static factory method for creation from username.
231 * This is slightly less efficient than newFromId(), so use newFromId() if
232 * you have both an ID and a name handy.
234 * @param string $name Username, validated by Title:newFromText()
235 * @param mixed $validate Validate username. Takes the same parameters as
236 * User::getCanonicalName(), except that true is accepted as an alias
237 * for 'valid', for BC.
239 * @return User object, or null if the username is invalid. If the username
240 * is not present in the database, the result will be a user object with
241 * a name, zero user ID and default settings.
244 static function newFromName( $name, $validate = 'valid' ) {
245 if ( $validate === true ) {
248 $name = self
::getCanonicalName( $name, $validate );
249 if ( $name === false ) {
252 # Create unloaded user object
260 static function newFromId( $id ) {
268 * Factory method to fetch whichever user has a given email confirmation code.
269 * This code is generated when an account is created or its e-mail address
272 * If the code is invalid or has expired, returns NULL.
274 * @param string $code
278 static function newFromConfirmationCode( $code ) {
279 $dbr = wfGetDB( DB_SLAVE
);
280 $id = $dbr->selectField( 'user', 'user_id', array(
281 'user_email_token' => md5( $code ),
282 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
284 if( $id !== false ) {
285 return User
::newFromId( $id );
292 * Create a new user object using data from session or cookies. If the
293 * login credentials are invalid, the result is an anonymous user.
298 static function newFromSession() {
300 $user->mFrom
= 'session';
305 * Get username given an id.
306 * @param integer $id Database user id
307 * @return string Nickname of a user
310 static function whoIs( $id ) {
311 $dbr = wfGetDB( DB_SLAVE
);
312 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
316 * Get real username given an id.
317 * @param integer $id Database user id
318 * @return string Realname of a user
321 static function whoIsReal( $id ) {
322 $dbr = wfGetDB( DB_SLAVE
);
323 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), 'User::whoIsReal' );
327 * Get database id given a user name
328 * @param string $name Nickname of a user
329 * @return integer|null Database user id (null: if non existent
332 static function idFromName( $name ) {
333 $nt = Title
::newFromText( $name );
334 if( is_null( $nt ) ) {
338 $dbr = wfGetDB( DB_SLAVE
);
339 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
341 if ( $s === false ) {
349 * Does the string match an anonymous IPv4 address?
351 * This function exists for username validation, in order to reject
352 * usernames which are similar in form to IP addresses. Strings such
353 * as 300.300.300.300 will return true because it looks like an IP
354 * address, despite not being strictly valid.
356 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
357 * address because the usemod software would "cloak" anonymous IP
358 * addresses like this, if we allowed accounts like this to be created
359 * new users could get the old edits of these anonymous users.
362 * @param string $name Nickname of a user
365 static function isIP( $name ) {
366 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User
::isIPv6($name);
367 /*return preg_match("/^
368 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
369 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
370 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
371 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
376 * Check if $name is an IPv6 IP.
378 static function isIPv6($name) {
380 * if it has any non-valid characters, it can't be a valid IPv6
383 if (preg_match("/[^:a-fA-F0-9]/", $name))
386 $parts = explode(":", $name);
387 if (count($parts) < 3)
389 foreach ($parts as $part) {
390 if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part))
397 * Is the input a valid username?
399 * Checks if the input is a valid username, we don't want an empty string,
400 * an IP address, anything that containins slashes (would mess up subpages),
401 * is longer than the maximum allowed username size or doesn't begin with
404 * @param string $name
408 static function isValidUserName( $name ) {
409 global $wgContLang, $wgMaxNameChars;
412 || User
::isIP( $name )
413 ||
strpos( $name, '/' ) !== false
414 ||
strlen( $name ) > $wgMaxNameChars
415 ||
$name != $wgContLang->ucfirst( $name ) )
418 // Ensure that the name can't be misresolved as a different title,
419 // such as with extra namespace keys at the start.
420 $parsed = Title
::newFromText( $name );
421 if( is_null( $parsed )
422 ||
$parsed->getNamespace()
423 ||
strcmp( $name, $parsed->getPrefixedText() ) )
426 // Check an additional blacklist of troublemaker characters.
427 // Should these be merged into the title char list?
428 $unicodeBlacklist = '/[' .
429 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
430 '\x{00a0}' . # non-breaking space
431 '\x{2000}-\x{200f}' . # various whitespace
432 '\x{2028}-\x{202f}' . # breaks and control chars
433 '\x{3000}' . # ideographic space
434 '\x{e000}-\x{f8ff}' . # private use
436 if( preg_match( $unicodeBlacklist, $name ) ) {
444 * Usernames which fail to pass this function will be blocked
445 * from user login and new account registrations, but may be used
446 * internally by batch processes.
448 * If an account already exists in this form, login will be blocked
449 * by a failure to pass this function.
451 * @param string $name
454 static function isUsableName( $name ) {
455 global $wgReservedUsernames;
457 // Must be a usable username, obviously ;)
458 self
::isValidUserName( $name ) &&
460 // Certain names may be reserved for batch processes.
461 !in_array( $name, $wgReservedUsernames );
465 * Usernames which fail to pass this function will be blocked
466 * from new account registrations, but may be used internally
467 * either by batch processes or by user accounts which have
468 * already been created.
470 * Additional character blacklisting may be added here
471 * rather than in isValidUserName() to avoid disrupting
474 * @param string $name
477 static function isCreatableName( $name ) {
479 self
::isUsableName( $name ) &&
481 // Registration-time character blacklisting...
482 strpos( $name, '@' ) === false;
486 * Is the input a valid password?
488 * @param string $password
491 function isValidPassword( $password ) {
492 global $wgMinimalPasswordLength, $wgContLang;
495 if( !wfRunHooks( 'isValidPassword', array( $password, &$result ) ) ) return $result;
496 if ($result === false) return false;
497 return (strlen( $password ) >= $wgMinimalPasswordLength) &&
498 ($wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
));
502 * Does the string match roughly an email address ?
504 * There used to be a regular expression here, it got removed because it
505 * rejected valid addresses. Actually just check if there is '@' somewhere
506 * in the given address.
508 * @todo Check for RFC 2822 compilance (bug 959)
510 * @param string $addr email address
514 static function isValidEmailAddr ( $addr ) {
515 return ( trim( $addr ) != '' ) &&
516 (false !== strpos( $addr, '@' ) );
520 * Given unvalidated user input, return a canonical username, or false if
521 * the username is invalid.
522 * @param string $name
523 * @param mixed $validate Type of validation to use:
524 * false No validation
525 * 'valid' Valid for batch processes
526 * 'usable' Valid for batch processes and login
527 * 'creatable' Valid for batch processes, login and account creation
529 static function getCanonicalName( $name, $validate = 'valid' ) {
530 # Force usernames to capital
532 $name = $wgContLang->ucfirst( $name );
534 # Clean up name according to title rules
535 $t = Title
::newFromText( $name );
536 if( is_null( $t ) ) {
540 # Reject various classes of invalid names
541 $name = $t->getText();
543 $name = $wgAuth->getCanonicalName( $t->getText() );
545 switch ( $validate ) {
549 if ( !User
::isValidUserName( $name ) ) {
554 if ( !User
::isUsableName( $name ) ) {
559 if ( !User
::isCreatableName( $name ) ) {
564 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
570 * Count the number of edits of a user
572 * It should not be static and some day should be merged as proper member function / deprecated -- domas
574 * @param int $uid The user ID to check
578 static function edits( $uid ) {
579 wfProfileIn( __METHOD__
);
580 $dbr = wfGetDB( DB_SLAVE
);
581 // check if the user_editcount field has been initialized
582 $field = $dbr->selectField(
583 'user', 'user_editcount',
584 array( 'user_id' => $uid ),
588 if( $field === null ) { // it has not been initialized. do so.
589 $dbw = wfGetDb( DB_MASTER
);
590 $count = $dbr->selectField(
591 'revision', 'count(*)',
592 array( 'rev_user' => $uid ),
597 array( 'user_editcount' => $count ),
598 array( 'user_id' => $uid ),
604 wfProfileOut( __METHOD__
);
609 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
610 * @todo hash random numbers to improve security, like generateToken()
615 static function randomPassword() {
616 global $wgMinimalPasswordLength;
617 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
618 $l = strlen( $pwchars ) - 1;
620 $pwlength = max( 7, $wgMinimalPasswordLength );
621 $digit = mt_rand(0, $pwlength - 1);
623 for ( $i = 0; $i < $pwlength; $i++
) {
624 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
630 * Set cached properties to default. Note: this no longer clears
631 * uncached lazy-initialised properties. The constructor does that instead.
635 function loadDefaults( $name = false ) {
636 wfProfileIn( __METHOD__
);
638 global $wgCookiePrefix;
641 $this->mName
= $name;
642 $this->mRealName
= '';
643 $this->mPassword
= $this->mNewpassword
= '';
644 $this->mNewpassTime
= null;
646 $this->mOptions
= null; # Defer init
648 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
649 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
651 $this->mTouched
= '0'; # Allow any pages to be cached
654 $this->setToken(); # Random
655 $this->mEmailAuthenticated
= null;
656 $this->mEmailToken
= '';
657 $this->mEmailTokenExpires
= null;
658 $this->mRegistration
= wfTimestamp( TS_MW
);
659 $this->mGroups
= array();
661 wfProfileOut( __METHOD__
);
665 * Initialise php session
666 * @deprecated use wfSetupSession()
668 function SetupSession() {
673 * Load user data from the session or login cookie. If there are no valid
674 * credentials, initialises the user as an anon.
675 * @return true if the user is logged in, false otherwise
677 private function loadFromSession() {
678 global $wgMemc, $wgCookiePrefix;
680 if ( isset( $_SESSION['wsUserID'] ) ) {
681 if ( 0 != $_SESSION['wsUserID'] ) {
682 $sId = $_SESSION['wsUserID'];
684 $this->loadDefaults();
687 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
688 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
689 $_SESSION['wsUserID'] = $sId;
691 $this->loadDefaults();
694 if ( isset( $_SESSION['wsUserName'] ) ) {
695 $sName = $_SESSION['wsUserName'];
696 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
697 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
698 $_SESSION['wsUserName'] = $sName;
700 $this->loadDefaults();
704 $passwordCorrect = FALSE;
706 if ( !$this->loadFromId() ) {
707 # Not a valid ID, loadFromId has switched the object to anon for us
711 if ( isset( $_SESSION['wsToken'] ) ) {
712 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
714 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
715 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
718 # No session or persistent login cookie
719 $this->loadDefaults();
723 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
724 wfDebug( "Logged in from $from\n" );
727 # Invalid credentials
728 wfDebug( "Can't log in from $from, invalid credentials\n" );
729 $this->loadDefaults();
735 * Load user and user_group data from the database
736 * $this->mId must be set, this is how the user is identified.
738 * @return true if the user exists, false if the user is anonymous
741 function loadFromDatabase() {
743 $this->mId
= intval( $this->mId
);
745 /** Anonymous user */
747 $this->loadDefaults();
751 $dbr = wfGetDB( DB_MASTER
);
752 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
754 if ( $s !== false ) {
755 # Initialise user table data
756 $this->mName
= $s->user_name
;
757 $this->mRealName
= $s->user_real_name
;
758 $this->mPassword
= $s->user_password
;
759 $this->mNewpassword
= $s->user_newpassword
;
760 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $s->user_newpass_time
);
761 $this->mEmail
= $s->user_email
;
762 $this->decodeOptions( $s->user_options
);
763 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
764 $this->mToken
= $s->user_token
;
765 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
766 $this->mEmailToken
= $s->user_email_token
;
767 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $s->user_email_token_expires
);
768 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $s->user_registration
);
769 $this->mEditCount
= $s->user_editcount
;
770 $this->getEditCount(); // revalidation for nulls
773 $res = $dbr->select( 'user_groups',
775 array( 'ug_user' => $this->mId
),
777 $this->mGroups
= array();
778 while( $row = $dbr->fetchObject( $res ) ) {
779 $this->mGroups
[] = $row->ug_group
;
785 $this->loadDefaults();
791 * Clear various cached data stored in this object.
792 * @param string $reloadFrom Reload user and user_groups table data from a
793 * given source. May be "name", "id", "defaults", "session" or false for
796 function clearInstanceCache( $reloadFrom = false ) {
797 $this->mNewtalk
= -1;
798 $this->mDatePreference
= null;
799 $this->mBlockedby
= -1; # Unset
800 $this->mHash
= false;
802 $this->mRights
= null;
803 $this->mEffectiveGroups
= null;
806 $this->mDataLoaded
= false;
807 $this->mFrom
= $reloadFrom;
812 * Combine the language default options with any site-specific options
813 * and add the default language variants.
814 * Not really private cause it's called by Language class
819 static function getDefaultOptions() {
820 global $wgNamespacesToBeSearchedDefault;
822 * Site defaults will override the global/language defaults
824 global $wgDefaultUserOptions, $wgContLang;
825 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
828 * default language setting
830 $variant = $wgContLang->getPreferredVariant( false );
831 $defOpt['variant'] = $variant;
832 $defOpt['language'] = $variant;
834 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
835 $defOpt['searchNs'.$nsnum] = $val;
841 * Get a given default option value.
848 function getDefaultOption( $opt ) {
849 $defOpts = User
::getDefaultOptions();
850 if( isset( $defOpts[$opt] ) ) {
851 return $defOpts[$opt];
858 * Get a list of user toggle names
861 static function getToggles() {
863 $extraToggles = array();
864 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
865 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
870 * Get blocking information
872 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
873 * non-critical checks are done against slaves. Check when actually saving should be done against
876 function getBlockedStatus( $bFromSlave = true ) {
877 global $wgEnableSorbs, $wgProxyWhitelist;
879 if ( -1 != $this->mBlockedby
) {
880 wfDebug( "User::getBlockedStatus: already loaded.\n" );
884 wfProfileIn( __METHOD__
);
885 wfDebug( __METHOD__
.": checking...\n" );
887 $this->mBlockedby
= 0;
888 $this->mHideName
= 0;
891 if ($this->isAllowed( 'ipblock-exempt' ) ) {
892 # Exempt from all types of IP-block
897 $this->mBlock
= new Block();
898 $this->mBlock
->fromMaster( !$bFromSlave );
899 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
900 wfDebug( __METHOD__
.": Found block.\n" );
901 $this->mBlockedby
= $this->mBlock
->mBy
;
902 $this->mBlockreason
= $this->mBlock
->mReason
;
903 $this->mHideName
= $this->mBlock
->mHideName
;
904 if ( $this->isLoggedIn() ) {
905 $this->spreadBlock();
908 $this->mBlock
= null;
909 wfDebug( __METHOD__
.": No block.\n" );
913 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
916 if ( wfIsLocallyBlockedProxy( $ip ) ) {
917 $this->mBlockedby
= wfMsg( 'proxyblocker' );
918 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
922 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
923 if ( $this->inSorbsBlacklist( $ip ) ) {
924 $this->mBlockedby
= wfMsg( 'sorbs' );
925 $this->mBlockreason
= wfMsg( 'sorbsreason' );
931 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
933 wfProfileOut( __METHOD__
);
936 function inSorbsBlacklist( $ip ) {
937 global $wgEnableSorbs, $wgSorbsUrl;
939 return $wgEnableSorbs &&
940 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
943 function inDnsBlacklist( $ip, $base ) {
944 wfProfileIn( __METHOD__
);
950 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
952 for ( $i=4; $i>=1; $i-- ) {
953 $host .= $m[$i] . '.';
958 $ipList = gethostbynamel( $host );
961 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
964 wfDebug( "Requested $host, not found in $base.\n" );
968 wfProfileOut( __METHOD__
);
973 * Is this user subject to rate limiting?
977 public function isPingLimitable() {
978 global $wgRateLimitsExcludedGroups;
979 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
983 * Primitive rate limits: enforce maximum actions per time period
984 * to put a brake on flooding.
986 * Note: when using a shared cache like memcached, IP-address
987 * last-hit counters will be shared across wikis.
989 * @return bool true if a rate limiter was tripped
992 function pingLimiter( $action='edit' ) {
994 # Call the 'PingLimiter' hook
996 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1000 global $wgRateLimits, $wgRateLimitsExcludedGroups;
1001 if( !isset( $wgRateLimits[$action] ) ) {
1005 # Some groups shouldn't trigger the ping limiter, ever
1006 if( !$this->isPingLimitable() )
1009 global $wgMemc, $wgRateLimitLog;
1010 wfProfileIn( __METHOD__
);
1012 $limits = $wgRateLimits[$action];
1014 $id = $this->getId();
1017 if( isset( $limits['anon'] ) && $id == 0 ) {
1018 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1021 if( isset( $limits['user'] ) && $id != 0 ) {
1022 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
1024 if( $this->isNewbie() ) {
1025 if( isset( $limits['newbie'] ) && $id != 0 ) {
1026 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1028 if( isset( $limits['ip'] ) ) {
1029 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1032 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1033 $subnet = $matches[1];
1034 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1039 foreach( $keys as $key => $limit ) {
1040 list( $max, $period ) = $limit;
1041 $summary = "(limit $max in {$period}s)";
1042 $count = $wgMemc->get( $key );
1044 if( $count > $max ) {
1045 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1046 if( $wgRateLimitLog ) {
1047 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1051 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1054 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1055 $wgMemc->add( $key, 1, intval( $period ) );
1057 $wgMemc->incr( $key );
1060 wfProfileOut( __METHOD__
);
1065 * Check if user is blocked
1066 * @return bool True if blocked, false otherwise
1068 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1069 wfDebug( "User::isBlocked: enter\n" );
1070 $this->getBlockedStatus( $bFromSlave );
1071 return $this->mBlockedby
!== 0;
1075 * Check if user is blocked from editing a particular article
1077 function isBlockedFrom( $title, $bFromSlave = false ) {
1078 global $wgBlockAllowsUTEdit;
1079 wfProfileIn( __METHOD__
);
1080 wfDebug( __METHOD__
.": enter\n" );
1082 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1083 $blocked = $this->isBlocked( $bFromSlave );
1084 # If a user's name is suppressed, they cannot make edits anywhere
1085 if ( !$this->mHideName
&& $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1086 $title->getNamespace() == NS_USER_TALK
) {
1088 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1090 wfProfileOut( __METHOD__
);
1095 * Get name of blocker
1096 * @return string name of blocker
1098 function blockedBy() {
1099 $this->getBlockedStatus();
1100 return $this->mBlockedby
;
1104 * Get blocking reason
1105 * @return string Blocking reason
1107 function blockedFor() {
1108 $this->getBlockedStatus();
1109 return $this->mBlockreason
;
1113 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1121 * Set the user and reload all fields according to that ID
1122 * @deprecated use User::newFromId()
1124 function setID( $v ) {
1126 $this->clearInstanceCache( 'id' );
1130 * Get the user name, or the IP for anons
1132 function getName() {
1133 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1134 # Special case optimisation
1135 return $this->mName
;
1138 if ( $this->mName
=== false ) {
1140 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1142 return $this->mName
;
1147 * Set the user name.
1149 * This does not reload fields from the database according to the given
1150 * name. Rather, it is used to create a temporary "nonexistent user" for
1151 * later addition to the database. It can also be used to set the IP
1152 * address for an anonymous user to something other than the current
1155 * User::newFromName() has rougly the same function, when the named user
1158 function setName( $str ) {
1160 $this->mName
= $str;
1164 * Return the title dbkey form of the name, for eg user pages.
1168 function getTitleKey() {
1169 return str_replace( ' ', '_', $this->getName() );
1172 function getNewtalk() {
1175 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1176 if( $this->mNewtalk
=== -1 ) {
1177 $this->mNewtalk
= false; # reset talk page status
1179 # Check memcached separately for anons, who have no
1180 # entire User object stored in there.
1183 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1184 $newtalk = $wgMemc->get( $key );
1185 if( $newtalk != "" ) {
1186 $this->mNewtalk
= (bool)$newtalk;
1188 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
1189 $wgMemc->set( $key, (int)$this->mNewtalk
, time() +
1800 );
1192 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1196 return (bool)$this->mNewtalk
;
1200 * Return the talk page(s) this user has new messages on.
1202 function getNewMessageLinks() {
1204 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1207 if (!$this->getNewtalk())
1209 $up = $this->getUserPage();
1210 $utp = $up->getTalkPage();
1211 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1216 * Perform a user_newtalk check on current slaves; if the memcached data
1217 * is funky we don't want newtalk state to get stuck on save, as that's
1220 * @param string $field
1225 function checkNewtalk( $field, $id ) {
1226 $dbr = wfGetDB( DB_SLAVE
);
1227 $ok = $dbr->selectField( 'user_newtalk', $field,
1228 array( $field => $id ), __METHOD__
);
1229 return $ok !== false;
1234 * @param string $field
1238 function updateNewtalk( $field, $id ) {
1239 if( $this->checkNewtalk( $field, $id ) ) {
1240 wfDebug( __METHOD__
." already set ($field, $id), ignoring\n" );
1243 $dbw = wfGetDB( DB_MASTER
);
1244 $dbw->insert( 'user_newtalk',
1245 array( $field => $id ),
1248 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1253 * Clear the new messages flag for the given user
1254 * @param string $field
1258 function deleteNewtalk( $field, $id ) {
1259 if( !$this->checkNewtalk( $field, $id ) ) {
1260 wfDebug( __METHOD__
.": already gone ($field, $id), ignoring\n" );
1263 $dbw = wfGetDB( DB_MASTER
);
1264 $dbw->delete( 'user_newtalk',
1265 array( $field => $id ),
1267 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1272 * Update the 'You have new messages!' status.
1275 function setNewtalk( $val ) {
1276 if( wfReadOnly() ) {
1281 $this->mNewtalk
= $val;
1283 if( $this->isAnon() ) {
1285 $id = $this->getName();
1288 $id = $this->getId();
1292 $changed = $this->updateNewtalk( $field, $id );
1294 $changed = $this->deleteNewtalk( $field, $id );
1298 if( $this->isAnon() ) {
1299 // Anons have a separate memcached space, since
1300 // user records aren't kept for them.
1302 $key = wfMemcKey( 'newtalk', 'ip', $val );
1303 $wgMemc->set( $key, $val ?
1 : 0 );
1306 // Make sure the user page is watched, so a notification
1307 // will be sent out if enabled.
1308 $this->addWatch( $this->getTalkPage() );
1311 $this->invalidateCache();
1316 * Generate a current or new-future timestamp to be stored in the
1317 * user_touched field when we update things.
1319 private static function newTouchedTimestamp() {
1320 global $wgClockSkewFudge;
1321 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1325 * Clear user data from memcached.
1326 * Use after applying fun updates to the database; caller's
1327 * responsibility to update user_touched if appropriate.
1329 * Called implicitly from invalidateCache() and saveSettings().
1331 private function clearSharedCache() {
1334 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1339 * Immediately touch the user data cache for this account.
1340 * Updates user_touched field, and removes account data from memcached
1341 * for reload on the next hit.
1343 function invalidateCache() {
1346 $this->mTouched
= self
::newTouchedTimestamp();
1348 $dbw = wfGetDB( DB_MASTER
);
1349 $dbw->update( 'user',
1350 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1351 array( 'user_id' => $this->mId
),
1354 $this->clearSharedCache();
1358 function validateCache( $timestamp ) {
1360 return ($timestamp >= $this->mTouched
);
1364 * Encrypt a password.
1365 * It can eventuall salt a password @see User::addSalt()
1366 * @param string $p clear Password.
1367 * @return string Encrypted password.
1369 function encryptPassword( $p ) {
1371 return wfEncryptPassword( $this->mId
, $p );
1375 * Set the password and reset the random token
1376 * Calls through to authentication plugin if necessary;
1377 * will have no effect if the auth plugin refuses to
1378 * pass the change through or if the legal password
1381 * As a special case, setting the password to null
1382 * wipes it, so the account cannot be logged in until
1383 * a new password is set, for instance via e-mail.
1385 * @param string $str
1386 * @throws PasswordError on failure
1388 function setPassword( $str ) {
1391 if( $str !== null ) {
1392 if( !$wgAuth->allowPasswordChange() ) {
1393 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1396 if( !$this->isValidPassword( $str ) ) {
1397 global $wgMinimalPasswordLength;
1398 throw new PasswordError( wfMsg( 'passwordtooshort',
1399 $wgMinimalPasswordLength ) );
1403 if( !$wgAuth->setPassword( $this, $str ) ) {
1404 throw new PasswordError( wfMsg( 'externaldberror' ) );
1407 $this->setInternalPassword( $str );
1413 * Set the password and reset the random token no matter
1416 * @param string $str
1418 function setInternalPassword( $str ) {
1422 if( $str === null ) {
1423 // Save an invalid hash...
1424 $this->mPassword
= '';
1426 $this->mPassword
= $this->encryptPassword( $str );
1428 $this->mNewpassword
= '';
1429 $this->mNewpassTime
= null;
1432 * Set the random token (used for persistent authentication)
1433 * Called from loadDefaults() among other places.
1436 function setToken( $token = false ) {
1437 global $wgSecretKey, $wgProxyKey;
1440 if ( $wgSecretKey ) {
1441 $key = $wgSecretKey;
1442 } elseif ( $wgProxyKey ) {
1447 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1449 $this->mToken
= $token;
1453 function setCookiePassword( $str ) {
1455 $this->mCookiePassword
= md5( $str );
1459 * Set the password for a password reminder or new account email
1460 * Sets the user_newpass_time field if $throttle is true
1462 function setNewpassword( $str, $throttle = true ) {
1464 $this->mNewpassword
= $this->encryptPassword( $str );
1466 $this->mNewpassTime
= wfTimestampNow();
1471 * Returns true if a password reminder email has already been sent within
1472 * the last $wgPasswordReminderResendTime hours
1474 function isPasswordReminderThrottled() {
1475 global $wgPasswordReminderResendTime;
1477 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1480 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1481 return time() < $expiry;
1484 function getEmail() {
1486 return $this->mEmail
;
1489 function getEmailAuthenticationTimestamp() {
1491 return $this->mEmailAuthenticated
;
1494 function setEmail( $str ) {
1496 $this->mEmail
= $str;
1499 function getRealName() {
1501 return $this->mRealName
;
1504 function setRealName( $str ) {
1506 $this->mRealName
= $str;
1510 * @param string $oname The option to check
1511 * @param string $defaultOverride A default value returned if the option does not exist
1514 function getOption( $oname, $defaultOverride = '' ) {
1517 if ( is_null( $this->mOptions
) ) {
1518 if($defaultOverride != '') {
1519 return $defaultOverride;
1521 $this->mOptions
= User
::getDefaultOptions();
1524 if ( array_key_exists( $oname, $this->mOptions
) ) {
1525 return trim( $this->mOptions
[$oname] );
1527 return $defaultOverride;
1532 * Get the user's date preference, including some important migration for
1535 function getDatePreference() {
1536 if ( is_null( $this->mDatePreference
) ) {
1538 $value = $this->getOption( 'date' );
1539 $map = $wgLang->getDatePreferenceMigrationMap();
1540 if ( isset( $map[$value] ) ) {
1541 $value = $map[$value];
1543 $this->mDatePreference
= $value;
1545 return $this->mDatePreference
;
1549 * @param string $oname The option to check
1550 * @return bool False if the option is not selected, true if it is
1552 function getBoolOption( $oname ) {
1553 return (bool)$this->getOption( $oname );
1557 * Get an option as an integer value from the source string.
1558 * @param string $oname The option to check
1559 * @param int $default Optional value to return if option is unset/blank.
1562 function getIntOption( $oname, $default=0 ) {
1563 $val = $this->getOption( $oname );
1567 return intval( $val );
1570 function setOption( $oname, $val ) {
1572 if ( is_null( $this->mOptions
) ) {
1573 $this->mOptions
= User
::getDefaultOptions();
1575 if ( $oname == 'skin' ) {
1576 # Clear cached skin, so the new one displays immediately in Special:Preferences
1577 unset( $this->mSkin
);
1579 // Filter out any newlines that may have passed through input validation.
1580 // Newlines are used to separate items in the options blob.
1581 $val = str_replace( "\r\n", "\n", $val );
1582 $val = str_replace( "\r", "\n", $val );
1583 $val = str_replace( "\n", " ", $val );
1584 $this->mOptions
[$oname] = $val;
1587 function getRights() {
1588 if ( is_null( $this->mRights
) ) {
1589 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1591 return $this->mRights
;
1595 * Get the list of explicit group memberships this user has.
1596 * The implicit * and user groups are not included.
1597 * @return array of strings
1599 function getGroups() {
1601 return $this->mGroups
;
1605 * Get the list of implicit group memberships this user has.
1606 * This includes all explicit groups, plus 'user' if logged in
1607 * and '*' for all accounts.
1608 * @param boolean $recache Don't use the cache
1609 * @return array of strings
1611 function getEffectiveGroups( $recache = false ) {
1612 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1614 $this->mEffectiveGroups
= $this->mGroups
;
1615 $this->mEffectiveGroups
[] = '*';
1617 $this->mEffectiveGroups
[] = 'user';
1619 global $wgAutoConfirmAge, $wgAutoConfirmCount;
1621 $accountAge = time() - wfTimestampOrNull( TS_UNIX
, $this->mRegistration
);
1622 if( $accountAge >= $wgAutoConfirmAge && $this->getEditCount() >= $wgAutoConfirmCount ) {
1623 $this->mEffectiveGroups
[] = 'autoconfirmed';
1625 # Implicit group for users whose email addresses are confirmed
1626 global $wgEmailAuthentication;
1627 if( self
::isValidEmailAddr( $this->mEmail
) ) {
1628 if( $wgEmailAuthentication ) {
1629 if( $this->mEmailAuthenticated
)
1630 $this->mEffectiveGroups
[] = 'emailconfirmed';
1632 $this->mEffectiveGroups
[] = 'emailconfirmed';
1637 return $this->mEffectiveGroups
;
1640 /* Return the edit count for the user. This is where User::edits should have been */
1641 function getEditCount() {
1643 if ( !isset( $this->mEditCount
) ) {
1644 /* Populate the count, if it has not been populated yet */
1645 $this->mEditCount
= User
::edits($this->mId
);
1647 return $this->mEditCount
;
1655 * Add the user to the given group.
1656 * This takes immediate effect.
1657 * @param string $group
1659 function addGroup( $group ) {
1661 $dbw = wfGetDB( DB_MASTER
);
1662 if( $this->getId() ) {
1663 $dbw->insert( 'user_groups',
1665 'ug_user' => $this->getID(),
1666 'ug_group' => $group,
1669 array( 'IGNORE' ) );
1672 $this->mGroups
[] = $group;
1673 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1675 $this->invalidateCache();
1679 * Remove the user from the given group.
1680 * This takes immediate effect.
1681 * @param string $group
1683 function removeGroup( $group ) {
1685 $dbw = wfGetDB( DB_MASTER
);
1686 $dbw->delete( 'user_groups',
1688 'ug_user' => $this->getID(),
1689 'ug_group' => $group,
1691 'User::removeGroup' );
1693 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1694 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1696 $this->invalidateCache();
1701 * A more legible check for non-anonymousness.
1702 * Returns true if the user is not an anonymous visitor.
1706 function isLoggedIn() {
1707 return( $this->getID() != 0 );
1711 * A more legible check for anonymousness.
1712 * Returns true if the user is an anonymous visitor.
1717 return !$this->isLoggedIn();
1721 * Whether the user is a bot
1725 return $this->isAllowed( 'bot' );
1729 * Check if user is allowed to access a feature / make an action
1730 * @param string $action Action to be checked
1731 * @return boolean True: action is allowed, False: action should not be allowed
1733 function isAllowed($action='') {
1734 if ( $action === '' )
1735 // In the spirit of DWIM
1738 return in_array( $action, $this->getRights() );
1742 * Load a skin if it doesn't exist or return it
1743 * @todo FIXME : need to check the old failback system [AV]
1745 function &getSkin() {
1747 if ( ! isset( $this->mSkin
) ) {
1748 wfProfileIn( __METHOD__
);
1751 $userSkin = $this->getOption( 'skin' );
1752 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1754 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1755 wfProfileOut( __METHOD__
);
1757 return $this->mSkin
;
1761 * @param string $title Article title to look at
1765 * Check watched status of an article
1766 * @return bool True if article is watched
1768 function isWatched( $title ) {
1769 $wl = WatchedItem
::fromUserTitle( $this, $title );
1770 return $wl->isWatched();
1776 function addWatch( $title ) {
1777 $wl = WatchedItem
::fromUserTitle( $this, $title );
1779 $this->invalidateCache();
1783 * Stop watching an article
1785 function removeWatch( $title ) {
1786 $wl = WatchedItem
::fromUserTitle( $this, $title );
1788 $this->invalidateCache();
1792 * Clear the user's notification timestamp for the given title.
1793 * If e-notif e-mails are on, they will receive notification mails on
1794 * the next change of the page if it's watched etc.
1796 function clearNotification( &$title ) {
1797 global $wgUser, $wgUseEnotif;
1799 # Do nothing if the database is locked to writes
1800 if( wfReadOnly() ) {
1804 if ($title->getNamespace() == NS_USER_TALK
&&
1805 $title->getText() == $this->getName() ) {
1806 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1808 $this->setNewtalk( false );
1811 if( !$wgUseEnotif ) {
1815 if( $this->isAnon() ) {
1816 // Nothing else to do...
1820 // Only update the timestamp if the page is being watched.
1821 // The query to find out if it is watched is cached both in memcached and per-invocation,
1822 // and when it does have to be executed, it can be on a slave
1823 // If this is the user's newtalk page, we always update the timestamp
1824 if ($title->getNamespace() == NS_USER_TALK
&&
1825 $title->getText() == $wgUser->getName())
1828 } elseif ( $this->getID() == $wgUser->getID() ) {
1829 $watched = $title->userIsWatching();
1834 // If the page is watched by the user (or may be watched), update the timestamp on any
1835 // any matching rows
1837 $dbw = wfGetDB( DB_MASTER
);
1838 $dbw->update( 'watchlist',
1840 'wl_notificationtimestamp' => NULL
1841 ), array( /* WHERE */
1842 'wl_title' => $title->getDBkey(),
1843 'wl_namespace' => $title->getNamespace(),
1844 'wl_user' => $this->getID()
1845 ), 'User::clearLastVisited'
1853 * Resets all of the given user's page-change notification timestamps.
1854 * If e-notif e-mails are on, they will receive notification mails on
1855 * the next change of any watched page.
1857 * @param int $currentUser user ID number
1860 function clearAllNotifications( $currentUser ) {
1861 global $wgUseEnotif;
1862 if ( !$wgUseEnotif ) {
1863 $this->setNewtalk( false );
1866 if( $currentUser != 0 ) {
1868 $dbw = wfGetDB( DB_MASTER
);
1869 $dbw->update( 'watchlist',
1871 'wl_notificationtimestamp' => NULL
1872 ), array( /* WHERE */
1873 'wl_user' => $currentUser
1874 ), 'UserMailer::clearAll'
1877 # we also need to clear here the "you have new message" notification for the own user_talk page
1878 # This is cleared one page view later in Article::viewUpdates();
1884 * @return string Encoding options
1886 function encodeOptions() {
1888 if ( is_null( $this->mOptions
) ) {
1889 $this->mOptions
= User
::getDefaultOptions();
1892 foreach ( $this->mOptions
as $oname => $oval ) {
1893 array_push( $a, $oname.'='.$oval );
1895 $s = implode( "\n", $a );
1902 function decodeOptions( $str ) {
1903 $this->mOptions
= array();
1904 $a = explode( "\n", $str );
1905 foreach ( $a as $s ) {
1907 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1908 $this->mOptions
[$m[1]] = $m[2];
1913 function setCookies() {
1914 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1916 if ( 0 == $this->mId
) return;
1917 $exp = time() +
$wgCookieExpiration;
1919 $_SESSION['wsUserID'] = $this->mId
;
1920 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1922 $_SESSION['wsUserName'] = $this->getName();
1923 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1925 $_SESSION['wsToken'] = $this->mToken
;
1926 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1927 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1929 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1935 * Clears the cookies and session, resets the instance cache
1938 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1939 $this->clearInstanceCache( 'defaults' );
1941 $_SESSION['wsUserID'] = 0;
1943 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1944 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1946 # Remember when user logged out, to prevent seeing cached pages
1947 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1951 * Save object settings into database
1952 * @todo Only rarely do all these fields need to be set!
1954 function saveSettings() {
1956 if ( wfReadOnly() ) { return; }
1957 if ( 0 == $this->mId
) { return; }
1959 $this->mTouched
= self
::newTouchedTimestamp();
1961 $dbw = wfGetDB( DB_MASTER
);
1962 $dbw->update( 'user',
1964 'user_name' => $this->mName
,
1965 'user_password' => $this->mPassword
,
1966 'user_newpassword' => $this->mNewpassword
,
1967 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
1968 'user_real_name' => $this->mRealName
,
1969 'user_email' => $this->mEmail
,
1970 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1971 'user_options' => $this->encodeOptions(),
1972 'user_touched' => $dbw->timestamp($this->mTouched
),
1973 'user_token' => $this->mToken
1974 ), array( /* WHERE */
1975 'user_id' => $this->mId
1978 $this->clearSharedCache();
1983 * Checks if a user with the given name exists, returns the ID
1985 function idForName() {
1986 $s = trim( $this->getName() );
1987 if ( 0 == strcmp( '', $s ) ) return 0;
1989 $dbr = wfGetDB( DB_SLAVE
);
1990 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
1991 if ( $id === false ) {
1998 * Add a user to the database, return the user object
2000 * @param string $name The user's name
2001 * @param array $params Associative array of non-default parameters to save to the database:
2002 * password The user's password. Password logins will be disabled if this is omitted.
2003 * newpassword A temporary password mailed to the user
2004 * email The user's email address
2005 * email_authenticated The email authentication timestamp
2006 * real_name The user's real name
2007 * options An associative array of non-default options
2008 * token Random authentication token. Do not set.
2009 * registration Registration timestamp. Do not set.
2011 * @return User object, or null if the username already exists
2013 static function createNew( $name, $params = array() ) {
2016 if ( isset( $params['options'] ) ) {
2017 $user->mOptions
= $params['options'] +
$user->mOptions
;
2018 unset( $params['options'] );
2020 $dbw = wfGetDB( DB_MASTER
);
2021 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2023 'user_id' => $seqVal,
2024 'user_name' => $name,
2025 'user_password' => $user->mPassword
,
2026 'user_newpassword' => $user->mNewpassword
,
2027 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2028 'user_email' => $user->mEmail
,
2029 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2030 'user_real_name' => $user->mRealName
,
2031 'user_options' => $user->encodeOptions(),
2032 'user_token' => $user->mToken
,
2033 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2034 'user_editcount' => 0,
2036 foreach ( $params as $name => $value ) {
2037 $fields["user_$name"] = $value;
2039 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2040 if ( $dbw->affectedRows() ) {
2041 $newUser = User
::newFromId( $dbw->insertId() );
2049 * Add an existing user object to the database
2051 function addToDatabase() {
2053 $dbw = wfGetDB( DB_MASTER
);
2054 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2055 $dbw->insert( 'user',
2057 'user_id' => $seqVal,
2058 'user_name' => $this->mName
,
2059 'user_password' => $this->mPassword
,
2060 'user_newpassword' => $this->mNewpassword
,
2061 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2062 'user_email' => $this->mEmail
,
2063 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2064 'user_real_name' => $this->mRealName
,
2065 'user_options' => $this->encodeOptions(),
2066 'user_token' => $this->mToken
,
2067 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2068 'user_editcount' => 0,
2071 $this->mId
= $dbw->insertId();
2073 # Clear instance cache other than user table data, which is already accurate
2074 $this->clearInstanceCache();
2078 * If the (non-anonymous) user is blocked, this function will block any IP address
2079 * that they successfully log on from.
2081 function spreadBlock() {
2082 wfDebug( __METHOD__
."()\n" );
2084 if ( $this->mId
== 0 ) {
2088 $userblock = Block
::newFromDB( '', $this->mId
);
2089 if ( !$userblock ) {
2093 $userblock->doAutoblock( wfGetIp() );
2098 * Generate a string which will be different for any combination of
2099 * user options which would produce different parser output.
2100 * This will be used as part of the hash key for the parser cache,
2101 * so users will the same options can share the same cached data
2104 * Extensions which require it should install 'PageRenderingHash' hook,
2105 * which will give them a chance to modify this key based on their own
2110 function getPageRenderingHash() {
2111 global $wgContLang, $wgUseDynamicDates, $wgLang;
2113 return $this->mHash
;
2116 // stubthreshold is only included below for completeness,
2117 // it will always be 0 when this function is called by parsercache.
2119 $confstr = $this->getOption( 'math' );
2120 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2121 if ( $wgUseDynamicDates ) {
2122 $confstr .= '!' . $this->getDatePreference();
2124 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2125 $confstr .= '!' . $wgLang->getCode();
2126 $confstr .= '!' . $this->getOption( 'thumbsize' );
2127 // add in language specific options, if any
2128 $extra = $wgContLang->getExtraHashOptions();
2131 // Give a chance for extensions to modify the hash, if they have
2132 // extra options or other effects on the parser cache.
2133 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2135 // Make it a valid memcached key fragment
2136 $confstr = str_replace( ' ', '_', $confstr );
2137 $this->mHash
= $confstr;
2141 function isBlockedFromCreateAccount() {
2142 $this->getBlockedStatus();
2143 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2146 function isAllowedToCreateAccount() {
2147 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2153 function setLoaded( $loaded ) {}
2156 * Get this user's personal page title.
2161 function getUserPage() {
2162 return Title
::makeTitle( NS_USER
, $this->getName() );
2166 * Get this user's talk page title.
2171 function getTalkPage() {
2172 $title = $this->getUserPage();
2173 return $title->getTalkPage();
2179 function getMaxID() {
2180 static $res; // cache
2182 if ( isset( $res ) )
2185 $dbr = wfGetDB( DB_SLAVE
);
2186 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2191 * Determine whether the user is a newbie. Newbies are either
2192 * anonymous IPs, or the most recently created accounts.
2193 * @return bool True if it is a newbie.
2195 function isNewbie() {
2196 return !$this->isAllowed( 'autoconfirmed' );
2200 * Check to see if the given clear-text password is one of the accepted passwords
2201 * @param string $password User password.
2202 * @return bool True if the given password is correct otherwise False.
2204 function checkPassword( $password ) {
2208 // Even though we stop people from creating passwords that
2209 // are shorter than this, doesn't mean people wont be able
2210 // to. Certain authentication plugins do NOT want to save
2211 // domain passwords in a mysql database, so we should
2212 // check this (incase $wgAuth->strict() is false).
2213 if( !$this->isValidPassword( $password ) ) {
2217 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2219 } elseif( $wgAuth->strict() ) {
2220 /* Auth plugin doesn't allow local authentication */
2223 $ep = $this->encryptPassword( $password );
2224 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2226 } elseif ( function_exists( 'iconv' ) ) {
2227 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2228 # Check for this with iconv
2229 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2230 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2238 * Check if the given clear-text password matches the temporary password
2239 * sent by e-mail for password reset operations.
2242 function checkTemporaryPassword( $plaintext ) {
2243 $hash = $this->encryptPassword( $plaintext );
2244 return $hash === $this->mNewpassword
;
2248 * Initialize (if necessary) and return a session token value
2249 * which can be used in edit forms to show that the user's
2250 * login credentials aren't being hijacked with a foreign form
2253 * @param mixed $salt - Optional function-specific data for hash.
2254 * Use a string or an array of strings.
2258 function editToken( $salt = '' ) {
2259 if( !isset( $_SESSION['wsEditToken'] ) ) {
2260 $token = $this->generateToken();
2261 $_SESSION['wsEditToken'] = $token;
2263 $token = $_SESSION['wsEditToken'];
2265 if( is_array( $salt ) ) {
2266 $salt = implode( '|', $salt );
2268 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2272 * Generate a hex-y looking random token for various uses.
2273 * Could be made more cryptographically sure if someone cares.
2276 function generateToken( $salt = '' ) {
2277 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2278 return md5( $token . $salt );
2282 * Check given value against the token value stored in the session.
2283 * A match should confirm that the form was submitted from the
2284 * user's own login session, not a form submission from a third-party
2287 * @param string $val - the input value to compare
2288 * @param string $salt - Optional function-specific data for hash
2292 function matchEditToken( $val, $salt = '' ) {
2294 $sessionToken = $this->editToken( $salt );
2295 if ( $val != $sessionToken ) {
2296 wfDebug( "User::matchEditToken: broken session data\n" );
2298 return $val == $sessionToken;
2302 * Generate a new e-mail confirmation token and send a confirmation
2303 * mail to the user's given address.
2305 * @return mixed True on success, a WikiError object on failure.
2307 function sendConfirmationMail() {
2309 $expiration = null; // gets passed-by-ref and defined in next line.
2310 $url = $this->confirmationTokenUrl( $expiration );
2311 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2312 wfMsg( 'confirmemail_body',
2316 $wgContLang->timeanddate( $expiration, false ) ) );
2320 * Send an e-mail to this user's account. Does not check for
2321 * confirmed status or validity.
2323 * @param string $subject
2324 * @param string $body
2325 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2326 * @return mixed True on success, a WikiError object on failure.
2328 function sendMail( $subject, $body, $from = null ) {
2329 if( is_null( $from ) ) {
2330 global $wgPasswordSender;
2331 $from = $wgPasswordSender;
2334 require_once( 'UserMailer.php' );
2335 $to = new MailAddress( $this );
2336 $sender = new MailAddress( $from );
2337 $error = userMailer( $to, $sender, $subject, $body );
2339 if( $error == '' ) {
2342 return new WikiError( $error );
2347 * Generate, store, and return a new e-mail confirmation code.
2348 * A hash (unsalted since it's used as a key) is stored.
2349 * @param &$expiration mixed output: accepts the expiration time
2353 function confirmationToken( &$expiration ) {
2355 $expires = $now +
7 * 24 * 60 * 60;
2356 $expiration = wfTimestamp( TS_MW
, $expires );
2358 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2359 $hash = md5( $token );
2361 $dbw = wfGetDB( DB_MASTER
);
2362 $dbw->update( 'user',
2363 array( 'user_email_token' => $hash,
2364 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2365 array( 'user_id' => $this->mId
),
2372 * Generate and store a new e-mail confirmation token, and return
2373 * the URL the user can use to confirm.
2374 * @param &$expiration mixed output: accepts the expiration time
2378 function confirmationTokenUrl( &$expiration ) {
2379 $token = $this->confirmationToken( $expiration );
2380 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2381 return $title->getFullUrl();
2385 * Mark the e-mail address confirmed and save.
2387 function confirmEmail() {
2389 $this->mEmailAuthenticated
= wfTimestampNow();
2390 $this->saveSettings();
2395 * Is this user allowed to send e-mails within limits of current
2396 * site configuration?
2399 function canSendEmail() {
2400 return $this->isEmailConfirmed();
2404 * Is this user allowed to receive e-mails within limits of current
2405 * site configuration?
2408 function canReceiveEmail() {
2409 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2413 * Is this user's e-mail address valid-looking and confirmed within
2414 * limits of the current site configuration?
2416 * If $wgEmailAuthentication is on, this may require the user to have
2417 * confirmed their address by returning a code or using a password
2418 * sent to the address from the wiki.
2422 function isEmailConfirmed() {
2423 global $wgEmailAuthentication;
2426 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2427 if( $this->isAnon() )
2429 if( !self
::isValidEmailAddr( $this->mEmail
) )
2431 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2440 * Return true if there is an outstanding request for e-mail confirmation.
2443 function isEmailConfirmationPending() {
2444 global $wgEmailAuthentication;
2445 return $wgEmailAuthentication &&
2446 !$this->isEmailConfirmed() &&
2447 $this->mEmailToken
&&
2448 $this->mEmailTokenExpires
> wfTimestamp();
2452 * @param array $groups list of groups
2453 * @return array list of permission key names for given groups combined
2456 static function getGroupPermissions( $groups ) {
2457 global $wgGroupPermissions;
2459 foreach( $groups as $group ) {
2460 if( isset( $wgGroupPermissions[$group] ) ) {
2461 $rights = array_merge( $rights,
2462 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2469 * @param string $group key name
2470 * @return string localized descriptive name for group, if provided
2473 static function getGroupName( $group ) {
2474 MessageCache
::loadAllMessages();
2475 $key = "group-$group";
2476 $name = wfMsg( $key );
2477 return $name == '' ||
wfEmptyMsg( $key, $name )
2483 * @param string $group key name
2484 * @return string localized descriptive name for member of a group, if provided
2487 static function getGroupMember( $group ) {
2488 MessageCache
::loadAllMessages();
2489 $key = "group-$group-member";
2490 $name = wfMsg( $key );
2491 return $name == '' ||
wfEmptyMsg( $key, $name )
2497 * Return the set of defined explicit groups.
2498 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2499 * groups are not included, as they are defined
2500 * automatically, not in the database.
2504 static function getAllGroups() {
2505 global $wgGroupPermissions;
2507 array_keys( $wgGroupPermissions ),
2508 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2512 * Get the title of a page describing a particular group
2514 * @param $group Name of the group
2517 static function getGroupPage( $group ) {
2518 MessageCache
::loadAllMessages();
2519 $page = wfMsgForContent( 'grouppage-' . $group );
2520 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2521 $title = Title
::newFromText( $page );
2522 if( is_object( $title ) )
2529 * Create a link to the group in HTML, if available
2531 * @param $group Name of the group
2532 * @param $text The text of the link
2535 static function makeGroupLinkHTML( $group, $text = '' ) {
2537 $text = self
::getGroupName( $group );
2539 $title = self
::getGroupPage( $group );
2542 $sk = $wgUser->getSkin();
2543 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2550 * Create a link to the group in Wikitext, if available
2552 * @param $group Name of the group
2553 * @param $text The text of the link (by default, the name of the group)
2556 static function makeGroupLinkWiki( $group, $text = '' ) {
2558 $text = self
::getGroupName( $group );
2560 $title = self
::getGroupPage( $group );
2562 $page = $title->getPrefixedText();
2563 return "[[$page|$text]]";
2570 * Increment the user's edit-count field.
2571 * Will have no effect for anonymous users.
2573 function incEditCount() {
2574 if( !$this->isAnon() ) {
2575 $dbw = wfGetDB( DB_MASTER
);
2576 $dbw->update( 'user',
2577 array( 'user_editcount=user_editcount+1' ),
2578 array( 'user_id' => $this->getId() ),
2581 // Lazy initialization check...
2582 if( $dbw->affectedRows() == 0 ) {
2583 // Pull from a slave to be less cruel to servers
2584 // Accuracy isn't the point anyway here
2585 $dbr = wfGetDB( DB_SLAVE
);
2586 $count = $dbr->selectField( 'revision',
2588 array( 'rev_user' => $this->getId() ),
2591 // Now here's a goddamn hack...
2592 if( $dbr !== $dbw ) {
2593 // If we actually have a slave server, the count is
2594 // at least one behind because the current transaction
2595 // has not been committed and replicated.
2598 // But if DB_SLAVE is selecting the master, then the
2599 // count we just read includes the revision that was
2600 // just added in the working transaction.
2603 $dbw->update( 'user',
2604 array( 'user_editcount' => $count ),
2605 array( 'user_id' => $this->getId() ),
2609 // edit count in user cache too
2610 $this->invalidateCache();