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 # Reject names containing '#'; these will be cleaned up
535 # with title normalisation, but then it's too late to
537 if( strpos( $name, '#' ) !== false )
540 # Clean up name according to title rules
541 $t = Title
::newFromText( $name );
542 if( is_null( $t ) ) {
546 # Reject various classes of invalid names
547 $name = $t->getText();
549 $name = $wgAuth->getCanonicalName( $t->getText() );
551 switch ( $validate ) {
555 if ( !User
::isValidUserName( $name ) ) {
560 if ( !User
::isUsableName( $name ) ) {
565 if ( !User
::isCreatableName( $name ) ) {
570 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
576 * Count the number of edits of a user
578 * It should not be static and some day should be merged as proper member function / deprecated -- domas
580 * @param int $uid The user ID to check
584 static function edits( $uid ) {
585 wfProfileIn( __METHOD__
);
586 $dbr = wfGetDB( DB_SLAVE
);
587 // check if the user_editcount field has been initialized
588 $field = $dbr->selectField(
589 'user', 'user_editcount',
590 array( 'user_id' => $uid ),
594 if( $field === null ) { // it has not been initialized. do so.
595 $dbw = wfGetDb( DB_MASTER
);
596 $count = $dbr->selectField(
597 'revision', 'count(*)',
598 array( 'rev_user' => $uid ),
603 array( 'user_editcount' => $count ),
604 array( 'user_id' => $uid ),
610 wfProfileOut( __METHOD__
);
615 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
616 * @todo hash random numbers to improve security, like generateToken()
621 static function randomPassword() {
622 global $wgMinimalPasswordLength;
623 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
624 $l = strlen( $pwchars ) - 1;
626 $pwlength = max( 7, $wgMinimalPasswordLength );
627 $digit = mt_rand(0, $pwlength - 1);
629 for ( $i = 0; $i < $pwlength; $i++
) {
630 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
636 * Set cached properties to default. Note: this no longer clears
637 * uncached lazy-initialised properties. The constructor does that instead.
641 function loadDefaults( $name = false ) {
642 wfProfileIn( __METHOD__
);
644 global $wgCookiePrefix;
647 $this->mName
= $name;
648 $this->mRealName
= '';
649 $this->mPassword
= $this->mNewpassword
= '';
650 $this->mNewpassTime
= null;
652 $this->mOptions
= null; # Defer init
654 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
655 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
657 $this->mTouched
= '0'; # Allow any pages to be cached
660 $this->setToken(); # Random
661 $this->mEmailAuthenticated
= null;
662 $this->mEmailToken
= '';
663 $this->mEmailTokenExpires
= null;
664 $this->mRegistration
= wfTimestamp( TS_MW
);
665 $this->mGroups
= array();
667 wfProfileOut( __METHOD__
);
671 * Initialise php session
672 * @deprecated use wfSetupSession()
674 function SetupSession() {
679 * Load user data from the session or login cookie. If there are no valid
680 * credentials, initialises the user as an anon.
681 * @return true if the user is logged in, false otherwise
683 private function loadFromSession() {
684 global $wgMemc, $wgCookiePrefix;
686 if ( isset( $_SESSION['wsUserID'] ) ) {
687 if ( 0 != $_SESSION['wsUserID'] ) {
688 $sId = $_SESSION['wsUserID'];
690 $this->loadDefaults();
693 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
694 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
695 $_SESSION['wsUserID'] = $sId;
697 $this->loadDefaults();
700 if ( isset( $_SESSION['wsUserName'] ) ) {
701 $sName = $_SESSION['wsUserName'];
702 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
703 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
704 $_SESSION['wsUserName'] = $sName;
706 $this->loadDefaults();
710 $passwordCorrect = FALSE;
712 if ( !$this->loadFromId() ) {
713 # Not a valid ID, loadFromId has switched the object to anon for us
717 if ( isset( $_SESSION['wsToken'] ) ) {
718 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
720 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
721 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
724 # No session or persistent login cookie
725 $this->loadDefaults();
729 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
730 wfDebug( "Logged in from $from\n" );
733 # Invalid credentials
734 wfDebug( "Can't log in from $from, invalid credentials\n" );
735 $this->loadDefaults();
741 * Load user and user_group data from the database
742 * $this->mId must be set, this is how the user is identified.
744 * @return true if the user exists, false if the user is anonymous
747 function loadFromDatabase() {
749 $this->mId
= intval( $this->mId
);
751 /** Anonymous user */
753 $this->loadDefaults();
757 $dbr = wfGetDB( DB_MASTER
);
758 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
760 if ( $s !== false ) {
761 # Initialise user table data
762 $this->mName
= $s->user_name
;
763 $this->mRealName
= $s->user_real_name
;
764 $this->mPassword
= $s->user_password
;
765 $this->mNewpassword
= $s->user_newpassword
;
766 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $s->user_newpass_time
);
767 $this->mEmail
= $s->user_email
;
768 $this->decodeOptions( $s->user_options
);
769 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
770 $this->mToken
= $s->user_token
;
771 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
772 $this->mEmailToken
= $s->user_email_token
;
773 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $s->user_email_token_expires
);
774 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $s->user_registration
);
775 $this->mEditCount
= $s->user_editcount
;
776 $this->getEditCount(); // revalidation for nulls
779 $res = $dbr->select( 'user_groups',
781 array( 'ug_user' => $this->mId
),
783 $this->mGroups
= array();
784 while( $row = $dbr->fetchObject( $res ) ) {
785 $this->mGroups
[] = $row->ug_group
;
791 $this->loadDefaults();
797 * Clear various cached data stored in this object.
798 * @param string $reloadFrom Reload user and user_groups table data from a
799 * given source. May be "name", "id", "defaults", "session" or false for
802 function clearInstanceCache( $reloadFrom = false ) {
803 $this->mNewtalk
= -1;
804 $this->mDatePreference
= null;
805 $this->mBlockedby
= -1; # Unset
806 $this->mHash
= false;
808 $this->mRights
= null;
809 $this->mEffectiveGroups
= null;
812 $this->mDataLoaded
= false;
813 $this->mFrom
= $reloadFrom;
818 * Combine the language default options with any site-specific options
819 * and add the default language variants.
820 * Not really private cause it's called by Language class
825 static function getDefaultOptions() {
826 global $wgNamespacesToBeSearchedDefault;
828 * Site defaults will override the global/language defaults
830 global $wgDefaultUserOptions, $wgContLang;
831 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
834 * default language setting
836 $variant = $wgContLang->getPreferredVariant( false );
837 $defOpt['variant'] = $variant;
838 $defOpt['language'] = $variant;
840 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
841 $defOpt['searchNs'.$nsnum] = $val;
847 * Get a given default option value.
854 function getDefaultOption( $opt ) {
855 $defOpts = User
::getDefaultOptions();
856 if( isset( $defOpts[$opt] ) ) {
857 return $defOpts[$opt];
864 * Get a list of user toggle names
867 static function getToggles() {
869 $extraToggles = array();
870 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
871 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
876 * Get blocking information
878 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
879 * non-critical checks are done against slaves. Check when actually saving should be done against
882 function getBlockedStatus( $bFromSlave = true ) {
883 global $wgEnableSorbs, $wgProxyWhitelist;
885 if ( -1 != $this->mBlockedby
) {
886 wfDebug( "User::getBlockedStatus: already loaded.\n" );
890 wfProfileIn( __METHOD__
);
891 wfDebug( __METHOD__
.": checking...\n" );
893 $this->mBlockedby
= 0;
894 $this->mHideName
= 0;
897 if ($this->isAllowed( 'ipblock-exempt' ) ) {
898 # Exempt from all types of IP-block
903 $this->mBlock
= new Block();
904 $this->mBlock
->fromMaster( !$bFromSlave );
905 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
906 wfDebug( __METHOD__
.": Found block.\n" );
907 $this->mBlockedby
= $this->mBlock
->mBy
;
908 $this->mBlockreason
= $this->mBlock
->mReason
;
909 $this->mHideName
= $this->mBlock
->mHideName
;
910 if ( $this->isLoggedIn() ) {
911 $this->spreadBlock();
914 $this->mBlock
= null;
915 wfDebug( __METHOD__
.": No block.\n" );
919 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
922 if ( wfIsLocallyBlockedProxy( $ip ) ) {
923 $this->mBlockedby
= wfMsg( 'proxyblocker' );
924 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
928 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
929 if ( $this->inSorbsBlacklist( $ip ) ) {
930 $this->mBlockedby
= wfMsg( 'sorbs' );
931 $this->mBlockreason
= wfMsg( 'sorbsreason' );
937 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
939 wfProfileOut( __METHOD__
);
942 function inSorbsBlacklist( $ip ) {
943 global $wgEnableSorbs, $wgSorbsUrl;
945 return $wgEnableSorbs &&
946 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
949 function inDnsBlacklist( $ip, $base ) {
950 wfProfileIn( __METHOD__
);
956 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
958 for ( $i=4; $i>=1; $i-- ) {
959 $host .= $m[$i] . '.';
964 $ipList = gethostbynamel( $host );
967 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
970 wfDebug( "Requested $host, not found in $base.\n" );
974 wfProfileOut( __METHOD__
);
979 * Is this user subject to rate limiting?
983 public function isPingLimitable() {
984 global $wgRateLimitsExcludedGroups;
985 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
989 * Primitive rate limits: enforce maximum actions per time period
990 * to put a brake on flooding.
992 * Note: when using a shared cache like memcached, IP-address
993 * last-hit counters will be shared across wikis.
995 * @return bool true if a rate limiter was tripped
998 function pingLimiter( $action='edit' ) {
1000 # Call the 'PingLimiter' hook
1002 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1006 global $wgRateLimits, $wgRateLimitsExcludedGroups;
1007 if( !isset( $wgRateLimits[$action] ) ) {
1011 # Some groups shouldn't trigger the ping limiter, ever
1012 if( !$this->isPingLimitable() )
1015 global $wgMemc, $wgRateLimitLog;
1016 wfProfileIn( __METHOD__
);
1018 $limits = $wgRateLimits[$action];
1020 $id = $this->getId();
1023 if( isset( $limits['anon'] ) && $id == 0 ) {
1024 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1027 if( isset( $limits['user'] ) && $id != 0 ) {
1028 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
1030 if( $this->isNewbie() ) {
1031 if( isset( $limits['newbie'] ) && $id != 0 ) {
1032 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1034 if( isset( $limits['ip'] ) ) {
1035 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1038 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1039 $subnet = $matches[1];
1040 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1045 foreach( $keys as $key => $limit ) {
1046 list( $max, $period ) = $limit;
1047 $summary = "(limit $max in {$period}s)";
1048 $count = $wgMemc->get( $key );
1050 if( $count > $max ) {
1051 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1052 if( $wgRateLimitLog ) {
1053 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1057 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1060 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1061 $wgMemc->add( $key, 1, intval( $period ) );
1063 $wgMemc->incr( $key );
1066 wfProfileOut( __METHOD__
);
1071 * Check if user is blocked
1072 * @return bool True if blocked, false otherwise
1074 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1075 wfDebug( "User::isBlocked: enter\n" );
1076 $this->getBlockedStatus( $bFromSlave );
1077 return $this->mBlockedby
!== 0;
1081 * Check if user is blocked from editing a particular article
1083 function isBlockedFrom( $title, $bFromSlave = false ) {
1084 global $wgBlockAllowsUTEdit;
1085 wfProfileIn( __METHOD__
);
1086 wfDebug( __METHOD__
.": enter\n" );
1088 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1089 $blocked = $this->isBlocked( $bFromSlave );
1090 # If a user's name is suppressed, they cannot make edits anywhere
1091 if ( !$this->mHideName
&& $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1092 $title->getNamespace() == NS_USER_TALK
) {
1094 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1096 wfProfileOut( __METHOD__
);
1101 * Get name of blocker
1102 * @return string name of blocker
1104 function blockedBy() {
1105 $this->getBlockedStatus();
1106 return $this->mBlockedby
;
1110 * Get blocking reason
1111 * @return string Blocking reason
1113 function blockedFor() {
1114 $this->getBlockedStatus();
1115 return $this->mBlockreason
;
1119 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1127 * Set the user and reload all fields according to that ID
1128 * @deprecated use User::newFromId()
1130 function setID( $v ) {
1132 $this->clearInstanceCache( 'id' );
1136 * Get the user name, or the IP for anons
1138 function getName() {
1139 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1140 # Special case optimisation
1141 return $this->mName
;
1144 if ( $this->mName
=== false ) {
1146 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1148 return $this->mName
;
1153 * Set the user name.
1155 * This does not reload fields from the database according to the given
1156 * name. Rather, it is used to create a temporary "nonexistent user" for
1157 * later addition to the database. It can also be used to set the IP
1158 * address for an anonymous user to something other than the current
1161 * User::newFromName() has rougly the same function, when the named user
1164 function setName( $str ) {
1166 $this->mName
= $str;
1170 * Return the title dbkey form of the name, for eg user pages.
1174 function getTitleKey() {
1175 return str_replace( ' ', '_', $this->getName() );
1178 function getNewtalk() {
1181 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1182 if( $this->mNewtalk
=== -1 ) {
1183 $this->mNewtalk
= false; # reset talk page status
1185 # Check memcached separately for anons, who have no
1186 # entire User object stored in there.
1189 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1190 $newtalk = $wgMemc->get( $key );
1191 if( $newtalk != "" ) {
1192 $this->mNewtalk
= (bool)$newtalk;
1194 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
1195 $wgMemc->set( $key, (int)$this->mNewtalk
, time() +
1800 );
1198 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1202 return (bool)$this->mNewtalk
;
1206 * Return the talk page(s) this user has new messages on.
1208 function getNewMessageLinks() {
1210 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1213 if (!$this->getNewtalk())
1215 $up = $this->getUserPage();
1216 $utp = $up->getTalkPage();
1217 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1222 * Perform a user_newtalk check on current slaves; if the memcached data
1223 * is funky we don't want newtalk state to get stuck on save, as that's
1226 * @param string $field
1231 function checkNewtalk( $field, $id ) {
1232 $dbr = wfGetDB( DB_SLAVE
);
1233 $ok = $dbr->selectField( 'user_newtalk', $field,
1234 array( $field => $id ), __METHOD__
);
1235 return $ok !== false;
1240 * @param string $field
1244 function updateNewtalk( $field, $id ) {
1245 if( $this->checkNewtalk( $field, $id ) ) {
1246 wfDebug( __METHOD__
." already set ($field, $id), ignoring\n" );
1249 $dbw = wfGetDB( DB_MASTER
);
1250 $dbw->insert( 'user_newtalk',
1251 array( $field => $id ),
1254 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1259 * Clear the new messages flag for the given user
1260 * @param string $field
1264 function deleteNewtalk( $field, $id ) {
1265 if( !$this->checkNewtalk( $field, $id ) ) {
1266 wfDebug( __METHOD__
.": already gone ($field, $id), ignoring\n" );
1269 $dbw = wfGetDB( DB_MASTER
);
1270 $dbw->delete( 'user_newtalk',
1271 array( $field => $id ),
1273 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1278 * Update the 'You have new messages!' status.
1281 function setNewtalk( $val ) {
1282 if( wfReadOnly() ) {
1287 $this->mNewtalk
= $val;
1289 if( $this->isAnon() ) {
1291 $id = $this->getName();
1294 $id = $this->getId();
1298 $changed = $this->updateNewtalk( $field, $id );
1300 $changed = $this->deleteNewtalk( $field, $id );
1304 if( $this->isAnon() ) {
1305 // Anons have a separate memcached space, since
1306 // user records aren't kept for them.
1308 $key = wfMemcKey( 'newtalk', 'ip', $val );
1309 $wgMemc->set( $key, $val ?
1 : 0 );
1312 // Make sure the user page is watched, so a notification
1313 // will be sent out if enabled.
1314 $this->addWatch( $this->getTalkPage() );
1317 $this->invalidateCache();
1322 * Generate a current or new-future timestamp to be stored in the
1323 * user_touched field when we update things.
1325 private static function newTouchedTimestamp() {
1326 global $wgClockSkewFudge;
1327 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1331 * Clear user data from memcached.
1332 * Use after applying fun updates to the database; caller's
1333 * responsibility to update user_touched if appropriate.
1335 * Called implicitly from invalidateCache() and saveSettings().
1337 private function clearSharedCache() {
1340 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1345 * Immediately touch the user data cache for this account.
1346 * Updates user_touched field, and removes account data from memcached
1347 * for reload on the next hit.
1349 function invalidateCache() {
1352 $this->mTouched
= self
::newTouchedTimestamp();
1354 $dbw = wfGetDB( DB_MASTER
);
1355 $dbw->update( 'user',
1356 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1357 array( 'user_id' => $this->mId
),
1360 $this->clearSharedCache();
1364 function validateCache( $timestamp ) {
1366 return ($timestamp >= $this->mTouched
);
1370 * Encrypt a password.
1371 * It can eventuall salt a password @see User::addSalt()
1372 * @param string $p clear Password.
1373 * @return string Encrypted password.
1375 function encryptPassword( $p ) {
1377 return wfEncryptPassword( $this->mId
, $p );
1381 * Set the password and reset the random token
1382 * Calls through to authentication plugin if necessary;
1383 * will have no effect if the auth plugin refuses to
1384 * pass the change through or if the legal password
1387 * As a special case, setting the password to null
1388 * wipes it, so the account cannot be logged in until
1389 * a new password is set, for instance via e-mail.
1391 * @param string $str
1392 * @throws PasswordError on failure
1394 function setPassword( $str ) {
1397 if( $str !== null ) {
1398 if( !$wgAuth->allowPasswordChange() ) {
1399 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1402 if( !$this->isValidPassword( $str ) ) {
1403 global $wgMinimalPasswordLength;
1404 throw new PasswordError( wfMsg( 'passwordtooshort',
1405 $wgMinimalPasswordLength ) );
1409 if( !$wgAuth->setPassword( $this, $str ) ) {
1410 throw new PasswordError( wfMsg( 'externaldberror' ) );
1413 $this->setInternalPassword( $str );
1419 * Set the password and reset the random token no matter
1422 * @param string $str
1424 function setInternalPassword( $str ) {
1428 if( $str === null ) {
1429 // Save an invalid hash...
1430 $this->mPassword
= '';
1432 $this->mPassword
= $this->encryptPassword( $str );
1434 $this->mNewpassword
= '';
1435 $this->mNewpassTime
= null;
1438 * Set the random token (used for persistent authentication)
1439 * Called from loadDefaults() among other places.
1442 function setToken( $token = false ) {
1443 global $wgSecretKey, $wgProxyKey;
1446 if ( $wgSecretKey ) {
1447 $key = $wgSecretKey;
1448 } elseif ( $wgProxyKey ) {
1453 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1455 $this->mToken
= $token;
1459 function setCookiePassword( $str ) {
1461 $this->mCookiePassword
= md5( $str );
1465 * Set the password for a password reminder or new account email
1466 * Sets the user_newpass_time field if $throttle is true
1468 function setNewpassword( $str, $throttle = true ) {
1470 $this->mNewpassword
= $this->encryptPassword( $str );
1472 $this->mNewpassTime
= wfTimestampNow();
1477 * Returns true if a password reminder email has already been sent within
1478 * the last $wgPasswordReminderResendTime hours
1480 function isPasswordReminderThrottled() {
1481 global $wgPasswordReminderResendTime;
1483 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1486 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1487 return time() < $expiry;
1490 function getEmail() {
1492 return $this->mEmail
;
1495 function getEmailAuthenticationTimestamp() {
1497 return $this->mEmailAuthenticated
;
1500 function setEmail( $str ) {
1502 $this->mEmail
= $str;
1505 function getRealName() {
1507 return $this->mRealName
;
1510 function setRealName( $str ) {
1512 $this->mRealName
= $str;
1516 * @param string $oname The option to check
1517 * @param string $defaultOverride A default value returned if the option does not exist
1520 function getOption( $oname, $defaultOverride = '' ) {
1523 if ( is_null( $this->mOptions
) ) {
1524 if($defaultOverride != '') {
1525 return $defaultOverride;
1527 $this->mOptions
= User
::getDefaultOptions();
1530 if ( array_key_exists( $oname, $this->mOptions
) ) {
1531 return trim( $this->mOptions
[$oname] );
1533 return $defaultOverride;
1538 * Get the user's date preference, including some important migration for
1541 function getDatePreference() {
1542 if ( is_null( $this->mDatePreference
) ) {
1544 $value = $this->getOption( 'date' );
1545 $map = $wgLang->getDatePreferenceMigrationMap();
1546 if ( isset( $map[$value] ) ) {
1547 $value = $map[$value];
1549 $this->mDatePreference
= $value;
1551 return $this->mDatePreference
;
1555 * @param string $oname The option to check
1556 * @return bool False if the option is not selected, true if it is
1558 function getBoolOption( $oname ) {
1559 return (bool)$this->getOption( $oname );
1563 * Get an option as an integer value from the source string.
1564 * @param string $oname The option to check
1565 * @param int $default Optional value to return if option is unset/blank.
1568 function getIntOption( $oname, $default=0 ) {
1569 $val = $this->getOption( $oname );
1573 return intval( $val );
1576 function setOption( $oname, $val ) {
1578 if ( is_null( $this->mOptions
) ) {
1579 $this->mOptions
= User
::getDefaultOptions();
1581 if ( $oname == 'skin' ) {
1582 # Clear cached skin, so the new one displays immediately in Special:Preferences
1583 unset( $this->mSkin
);
1585 // Filter out any newlines that may have passed through input validation.
1586 // Newlines are used to separate items in the options blob.
1587 $val = str_replace( "\r\n", "\n", $val );
1588 $val = str_replace( "\r", "\n", $val );
1589 $val = str_replace( "\n", " ", $val );
1590 $this->mOptions
[$oname] = $val;
1593 function getRights() {
1594 if ( is_null( $this->mRights
) ) {
1595 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1597 return $this->mRights
;
1601 * Get the list of explicit group memberships this user has.
1602 * The implicit * and user groups are not included.
1603 * @return array of strings
1605 function getGroups() {
1607 return $this->mGroups
;
1611 * Get the list of implicit group memberships this user has.
1612 * This includes all explicit groups, plus 'user' if logged in
1613 * and '*' for all accounts.
1614 * @param boolean $recache Don't use the cache
1615 * @return array of strings
1617 function getEffectiveGroups( $recache = false ) {
1618 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1620 $this->mEffectiveGroups
= $this->mGroups
;
1621 $this->mEffectiveGroups
[] = '*';
1623 $this->mEffectiveGroups
[] = 'user';
1625 global $wgAutoConfirmAge, $wgAutoConfirmCount;
1627 $accountAge = time() - wfTimestampOrNull( TS_UNIX
, $this->mRegistration
);
1628 if( $accountAge >= $wgAutoConfirmAge && $this->getEditCount() >= $wgAutoConfirmCount ) {
1629 $this->mEffectiveGroups
[] = 'autoconfirmed';
1631 # Implicit group for users whose email addresses are confirmed
1632 global $wgEmailAuthentication;
1633 if( self
::isValidEmailAddr( $this->mEmail
) ) {
1634 if( $wgEmailAuthentication ) {
1635 if( $this->mEmailAuthenticated
)
1636 $this->mEffectiveGroups
[] = 'emailconfirmed';
1638 $this->mEffectiveGroups
[] = 'emailconfirmed';
1643 return $this->mEffectiveGroups
;
1646 /* Return the edit count for the user. This is where User::edits should have been */
1647 function getEditCount() {
1649 if ( !isset( $this->mEditCount
) ) {
1650 /* Populate the count, if it has not been populated yet */
1651 $this->mEditCount
= User
::edits($this->mId
);
1653 return $this->mEditCount
;
1661 * Add the user to the given group.
1662 * This takes immediate effect.
1663 * @param string $group
1665 function addGroup( $group ) {
1667 $dbw = wfGetDB( DB_MASTER
);
1668 if( $this->getId() ) {
1669 $dbw->insert( 'user_groups',
1671 'ug_user' => $this->getID(),
1672 'ug_group' => $group,
1675 array( 'IGNORE' ) );
1678 $this->mGroups
[] = $group;
1679 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1681 $this->invalidateCache();
1685 * Remove the user from the given group.
1686 * This takes immediate effect.
1687 * @param string $group
1689 function removeGroup( $group ) {
1691 $dbw = wfGetDB( DB_MASTER
);
1692 $dbw->delete( 'user_groups',
1694 'ug_user' => $this->getID(),
1695 'ug_group' => $group,
1697 'User::removeGroup' );
1699 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1700 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1702 $this->invalidateCache();
1707 * A more legible check for non-anonymousness.
1708 * Returns true if the user is not an anonymous visitor.
1712 function isLoggedIn() {
1713 return( $this->getID() != 0 );
1717 * A more legible check for anonymousness.
1718 * Returns true if the user is an anonymous visitor.
1723 return !$this->isLoggedIn();
1727 * Whether the user is a bot
1731 return $this->isAllowed( 'bot' );
1735 * Check if user is allowed to access a feature / make an action
1736 * @param string $action Action to be checked
1737 * @return boolean True: action is allowed, False: action should not be allowed
1739 function isAllowed($action='') {
1740 if ( $action === '' )
1741 // In the spirit of DWIM
1744 return in_array( $action, $this->getRights() );
1748 * Load a skin if it doesn't exist or return it
1749 * @todo FIXME : need to check the old failback system [AV]
1751 function &getSkin() {
1753 if ( ! isset( $this->mSkin
) ) {
1754 wfProfileIn( __METHOD__
);
1757 $userSkin = $this->getOption( 'skin' );
1758 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1760 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1761 wfProfileOut( __METHOD__
);
1763 return $this->mSkin
;
1767 * @param string $title Article title to look at
1771 * Check watched status of an article
1772 * @return bool True if article is watched
1774 function isWatched( $title ) {
1775 $wl = WatchedItem
::fromUserTitle( $this, $title );
1776 return $wl->isWatched();
1782 function addWatch( $title ) {
1783 $wl = WatchedItem
::fromUserTitle( $this, $title );
1785 $this->invalidateCache();
1789 * Stop watching an article
1791 function removeWatch( $title ) {
1792 $wl = WatchedItem
::fromUserTitle( $this, $title );
1794 $this->invalidateCache();
1798 * Clear the user's notification timestamp for the given title.
1799 * If e-notif e-mails are on, they will receive notification mails on
1800 * the next change of the page if it's watched etc.
1802 function clearNotification( &$title ) {
1803 global $wgUser, $wgUseEnotif;
1805 # Do nothing if the database is locked to writes
1806 if( wfReadOnly() ) {
1810 if ($title->getNamespace() == NS_USER_TALK
&&
1811 $title->getText() == $this->getName() ) {
1812 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1814 $this->setNewtalk( false );
1817 if( !$wgUseEnotif ) {
1821 if( $this->isAnon() ) {
1822 // Nothing else to do...
1826 // Only update the timestamp if the page is being watched.
1827 // The query to find out if it is watched is cached both in memcached and per-invocation,
1828 // and when it does have to be executed, it can be on a slave
1829 // If this is the user's newtalk page, we always update the timestamp
1830 if ($title->getNamespace() == NS_USER_TALK
&&
1831 $title->getText() == $wgUser->getName())
1834 } elseif ( $this->getID() == $wgUser->getID() ) {
1835 $watched = $title->userIsWatching();
1840 // If the page is watched by the user (or may be watched), update the timestamp on any
1841 // any matching rows
1843 $dbw = wfGetDB( DB_MASTER
);
1844 $dbw->update( 'watchlist',
1846 'wl_notificationtimestamp' => NULL
1847 ), array( /* WHERE */
1848 'wl_title' => $title->getDBkey(),
1849 'wl_namespace' => $title->getNamespace(),
1850 'wl_user' => $this->getID()
1851 ), 'User::clearLastVisited'
1859 * Resets all of the given user's page-change notification timestamps.
1860 * If e-notif e-mails are on, they will receive notification mails on
1861 * the next change of any watched page.
1863 * @param int $currentUser user ID number
1866 function clearAllNotifications( $currentUser ) {
1867 global $wgUseEnotif;
1868 if ( !$wgUseEnotif ) {
1869 $this->setNewtalk( false );
1872 if( $currentUser != 0 ) {
1874 $dbw = wfGetDB( DB_MASTER
);
1875 $dbw->update( 'watchlist',
1877 'wl_notificationtimestamp' => NULL
1878 ), array( /* WHERE */
1879 'wl_user' => $currentUser
1880 ), 'UserMailer::clearAll'
1883 # we also need to clear here the "you have new message" notification for the own user_talk page
1884 # This is cleared one page view later in Article::viewUpdates();
1890 * @return string Encoding options
1892 function encodeOptions() {
1894 if ( is_null( $this->mOptions
) ) {
1895 $this->mOptions
= User
::getDefaultOptions();
1898 foreach ( $this->mOptions
as $oname => $oval ) {
1899 array_push( $a, $oname.'='.$oval );
1901 $s = implode( "\n", $a );
1908 function decodeOptions( $str ) {
1909 $this->mOptions
= array();
1910 $a = explode( "\n", $str );
1911 foreach ( $a as $s ) {
1913 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1914 $this->mOptions
[$m[1]] = $m[2];
1919 function setCookies() {
1920 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1922 if ( 0 == $this->mId
) return;
1923 $exp = time() +
$wgCookieExpiration;
1925 $_SESSION['wsUserID'] = $this->mId
;
1926 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1928 $_SESSION['wsUserName'] = $this->getName();
1929 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1931 $_SESSION['wsToken'] = $this->mToken
;
1932 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1933 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1935 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1941 * Clears the cookies and session, resets the instance cache
1944 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1945 $this->clearInstanceCache( 'defaults' );
1947 $_SESSION['wsUserID'] = 0;
1949 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1950 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1952 # Remember when user logged out, to prevent seeing cached pages
1953 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1957 * Save object settings into database
1958 * @todo Only rarely do all these fields need to be set!
1960 function saveSettings() {
1962 if ( wfReadOnly() ) { return; }
1963 if ( 0 == $this->mId
) { return; }
1965 $this->mTouched
= self
::newTouchedTimestamp();
1967 $dbw = wfGetDB( DB_MASTER
);
1968 $dbw->update( 'user',
1970 'user_name' => $this->mName
,
1971 'user_password' => $this->mPassword
,
1972 'user_newpassword' => $this->mNewpassword
,
1973 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
1974 'user_real_name' => $this->mRealName
,
1975 'user_email' => $this->mEmail
,
1976 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1977 'user_options' => $this->encodeOptions(),
1978 'user_touched' => $dbw->timestamp($this->mTouched
),
1979 'user_token' => $this->mToken
1980 ), array( /* WHERE */
1981 'user_id' => $this->mId
1984 $this->clearSharedCache();
1989 * Checks if a user with the given name exists, returns the ID
1991 function idForName() {
1992 $s = trim( $this->getName() );
1993 if ( 0 == strcmp( '', $s ) ) return 0;
1995 $dbr = wfGetDB( DB_SLAVE
);
1996 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
1997 if ( $id === false ) {
2004 * Add a user to the database, return the user object
2006 * @param string $name The user's name
2007 * @param array $params Associative array of non-default parameters to save to the database:
2008 * password The user's password. Password logins will be disabled if this is omitted.
2009 * newpassword A temporary password mailed to the user
2010 * email The user's email address
2011 * email_authenticated The email authentication timestamp
2012 * real_name The user's real name
2013 * options An associative array of non-default options
2014 * token Random authentication token. Do not set.
2015 * registration Registration timestamp. Do not set.
2017 * @return User object, or null if the username already exists
2019 static function createNew( $name, $params = array() ) {
2022 if ( isset( $params['options'] ) ) {
2023 $user->mOptions
= $params['options'] +
$user->mOptions
;
2024 unset( $params['options'] );
2026 $dbw = wfGetDB( DB_MASTER
);
2027 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2029 'user_id' => $seqVal,
2030 'user_name' => $name,
2031 'user_password' => $user->mPassword
,
2032 'user_newpassword' => $user->mNewpassword
,
2033 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2034 'user_email' => $user->mEmail
,
2035 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2036 'user_real_name' => $user->mRealName
,
2037 'user_options' => $user->encodeOptions(),
2038 'user_token' => $user->mToken
,
2039 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2040 'user_editcount' => 0,
2042 foreach ( $params as $name => $value ) {
2043 $fields["user_$name"] = $value;
2045 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2046 if ( $dbw->affectedRows() ) {
2047 $newUser = User
::newFromId( $dbw->insertId() );
2055 * Add an existing user object to the database
2057 function addToDatabase() {
2059 $dbw = wfGetDB( DB_MASTER
);
2060 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2061 $dbw->insert( 'user',
2063 'user_id' => $seqVal,
2064 'user_name' => $this->mName
,
2065 'user_password' => $this->mPassword
,
2066 'user_newpassword' => $this->mNewpassword
,
2067 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2068 'user_email' => $this->mEmail
,
2069 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2070 'user_real_name' => $this->mRealName
,
2071 'user_options' => $this->encodeOptions(),
2072 'user_token' => $this->mToken
,
2073 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2074 'user_editcount' => 0,
2077 $this->mId
= $dbw->insertId();
2079 # Clear instance cache other than user table data, which is already accurate
2080 $this->clearInstanceCache();
2084 * If the (non-anonymous) user is blocked, this function will block any IP address
2085 * that they successfully log on from.
2087 function spreadBlock() {
2088 wfDebug( __METHOD__
."()\n" );
2090 if ( $this->mId
== 0 ) {
2094 $userblock = Block
::newFromDB( '', $this->mId
);
2095 if ( !$userblock ) {
2099 $userblock->doAutoblock( wfGetIp() );
2104 * Generate a string which will be different for any combination of
2105 * user options which would produce different parser output.
2106 * This will be used as part of the hash key for the parser cache,
2107 * so users will the same options can share the same cached data
2110 * Extensions which require it should install 'PageRenderingHash' hook,
2111 * which will give them a chance to modify this key based on their own
2116 function getPageRenderingHash() {
2117 global $wgContLang, $wgUseDynamicDates, $wgLang;
2119 return $this->mHash
;
2122 // stubthreshold is only included below for completeness,
2123 // it will always be 0 when this function is called by parsercache.
2125 $confstr = $this->getOption( 'math' );
2126 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2127 if ( $wgUseDynamicDates ) {
2128 $confstr .= '!' . $this->getDatePreference();
2130 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2131 $confstr .= '!' . $wgLang->getCode();
2132 $confstr .= '!' . $this->getOption( 'thumbsize' );
2133 // add in language specific options, if any
2134 $extra = $wgContLang->getExtraHashOptions();
2137 // Give a chance for extensions to modify the hash, if they have
2138 // extra options or other effects on the parser cache.
2139 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2141 // Make it a valid memcached key fragment
2142 $confstr = str_replace( ' ', '_', $confstr );
2143 $this->mHash
= $confstr;
2147 function isBlockedFromCreateAccount() {
2148 $this->getBlockedStatus();
2149 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2153 * Determine if the user is blocked from using Special:Emailuser.
2158 function isBlockedFromEmailuser() {
2159 $this->getBlockedStatus();
2160 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2163 function isAllowedToCreateAccount() {
2164 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2170 function setLoaded( $loaded ) {}
2173 * Get this user's personal page title.
2178 function getUserPage() {
2179 return Title
::makeTitle( NS_USER
, $this->getName() );
2183 * Get this user's talk page title.
2188 function getTalkPage() {
2189 $title = $this->getUserPage();
2190 return $title->getTalkPage();
2196 function getMaxID() {
2197 static $res; // cache
2199 if ( isset( $res ) )
2202 $dbr = wfGetDB( DB_SLAVE
);
2203 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2208 * Determine whether the user is a newbie. Newbies are either
2209 * anonymous IPs, or the most recently created accounts.
2210 * @return bool True if it is a newbie.
2212 function isNewbie() {
2213 return !$this->isAllowed( 'autoconfirmed' );
2217 * Check to see if the given clear-text password is one of the accepted passwords
2218 * @param string $password User password.
2219 * @return bool True if the given password is correct otherwise False.
2221 function checkPassword( $password ) {
2225 // Even though we stop people from creating passwords that
2226 // are shorter than this, doesn't mean people wont be able
2227 // to. Certain authentication plugins do NOT want to save
2228 // domain passwords in a mysql database, so we should
2229 // check this (incase $wgAuth->strict() is false).
2230 if( !$this->isValidPassword( $password ) ) {
2234 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2236 } elseif( $wgAuth->strict() ) {
2237 /* Auth plugin doesn't allow local authentication */
2240 $ep = $this->encryptPassword( $password );
2241 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2243 } elseif ( function_exists( 'iconv' ) ) {
2244 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2245 # Check for this with iconv
2246 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2247 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2255 * Check if the given clear-text password matches the temporary password
2256 * sent by e-mail for password reset operations.
2259 function checkTemporaryPassword( $plaintext ) {
2260 $hash = $this->encryptPassword( $plaintext );
2261 return $hash === $this->mNewpassword
;
2265 * Initialize (if necessary) and return a session token value
2266 * which can be used in edit forms to show that the user's
2267 * login credentials aren't being hijacked with a foreign form
2270 * @param mixed $salt - Optional function-specific data for hash.
2271 * Use a string or an array of strings.
2275 function editToken( $salt = '' ) {
2276 if( !isset( $_SESSION['wsEditToken'] ) ) {
2277 $token = $this->generateToken();
2278 $_SESSION['wsEditToken'] = $token;
2280 $token = $_SESSION['wsEditToken'];
2282 if( is_array( $salt ) ) {
2283 $salt = implode( '|', $salt );
2285 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2289 * Generate a hex-y looking random token for various uses.
2290 * Could be made more cryptographically sure if someone cares.
2293 function generateToken( $salt = '' ) {
2294 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2295 return md5( $token . $salt );
2299 * Check given value against the token value stored in the session.
2300 * A match should confirm that the form was submitted from the
2301 * user's own login session, not a form submission from a third-party
2304 * @param string $val - the input value to compare
2305 * @param string $salt - Optional function-specific data for hash
2309 function matchEditToken( $val, $salt = '' ) {
2311 $sessionToken = $this->editToken( $salt );
2312 if ( $val != $sessionToken ) {
2313 wfDebug( "User::matchEditToken: broken session data\n" );
2315 return $val == $sessionToken;
2319 * Generate a new e-mail confirmation token and send a confirmation
2320 * mail to the user's given address.
2322 * @return mixed True on success, a WikiError object on failure.
2324 function sendConfirmationMail() {
2326 $expiration = null; // gets passed-by-ref and defined in next line.
2327 $url = $this->confirmationTokenUrl( $expiration );
2328 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2329 wfMsg( 'confirmemail_body',
2333 $wgContLang->timeanddate( $expiration, false ) ) );
2337 * Send an e-mail to this user's account. Does not check for
2338 * confirmed status or validity.
2340 * @param string $subject
2341 * @param string $body
2342 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2343 * @return mixed True on success, a WikiError object on failure.
2345 function sendMail( $subject, $body, $from = null ) {
2346 if( is_null( $from ) ) {
2347 global $wgPasswordSender;
2348 $from = $wgPasswordSender;
2351 require_once( 'UserMailer.php' );
2352 $to = new MailAddress( $this );
2353 $sender = new MailAddress( $from );
2354 $error = userMailer( $to, $sender, $subject, $body );
2356 if( $error == '' ) {
2359 return new WikiError( $error );
2364 * Generate, store, and return a new e-mail confirmation code.
2365 * A hash (unsalted since it's used as a key) is stored.
2366 * @param &$expiration mixed output: accepts the expiration time
2370 function confirmationToken( &$expiration ) {
2372 $expires = $now +
7 * 24 * 60 * 60;
2373 $expiration = wfTimestamp( TS_MW
, $expires );
2375 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2376 $hash = md5( $token );
2378 $dbw = wfGetDB( DB_MASTER
);
2379 $dbw->update( 'user',
2380 array( 'user_email_token' => $hash,
2381 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2382 array( 'user_id' => $this->mId
),
2389 * Generate and store a new e-mail confirmation token, and return
2390 * the URL the user can use to confirm.
2391 * @param &$expiration mixed output: accepts the expiration time
2395 function confirmationTokenUrl( &$expiration ) {
2396 $token = $this->confirmationToken( $expiration );
2397 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2398 return $title->getFullUrl();
2402 * Mark the e-mail address confirmed and save.
2404 function confirmEmail() {
2406 $this->mEmailAuthenticated
= wfTimestampNow();
2407 $this->saveSettings();
2412 * Is this user allowed to send e-mails within limits of current
2413 * site configuration?
2416 function canSendEmail() {
2417 return $this->isEmailConfirmed();
2421 * Is this user allowed to receive e-mails within limits of current
2422 * site configuration?
2425 function canReceiveEmail() {
2426 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2430 * Is this user's e-mail address valid-looking and confirmed within
2431 * limits of the current site configuration?
2433 * If $wgEmailAuthentication is on, this may require the user to have
2434 * confirmed their address by returning a code or using a password
2435 * sent to the address from the wiki.
2439 function isEmailConfirmed() {
2440 global $wgEmailAuthentication;
2443 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2444 if( $this->isAnon() )
2446 if( !self
::isValidEmailAddr( $this->mEmail
) )
2448 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2457 * Return true if there is an outstanding request for e-mail confirmation.
2460 function isEmailConfirmationPending() {
2461 global $wgEmailAuthentication;
2462 return $wgEmailAuthentication &&
2463 !$this->isEmailConfirmed() &&
2464 $this->mEmailToken
&&
2465 $this->mEmailTokenExpires
> wfTimestamp();
2469 * @param array $groups list of groups
2470 * @return array list of permission key names for given groups combined
2473 static function getGroupPermissions( $groups ) {
2474 global $wgGroupPermissions;
2476 foreach( $groups as $group ) {
2477 if( isset( $wgGroupPermissions[$group] ) ) {
2478 $rights = array_merge( $rights,
2479 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2486 * @param string $group key name
2487 * @return string localized descriptive name for group, if provided
2490 static function getGroupName( $group ) {
2491 MessageCache
::loadAllMessages();
2492 $key = "group-$group";
2493 $name = wfMsg( $key );
2494 return $name == '' ||
wfEmptyMsg( $key, $name )
2500 * @param string $group key name
2501 * @return string localized descriptive name for member of a group, if provided
2504 static function getGroupMember( $group ) {
2505 MessageCache
::loadAllMessages();
2506 $key = "group-$group-member";
2507 $name = wfMsg( $key );
2508 return $name == '' ||
wfEmptyMsg( $key, $name )
2514 * Return the set of defined explicit groups.
2515 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2516 * groups are not included, as they are defined
2517 * automatically, not in the database.
2521 static function getAllGroups() {
2522 global $wgGroupPermissions;
2524 array_keys( $wgGroupPermissions ),
2525 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2529 * Get the title of a page describing a particular group
2531 * @param $group Name of the group
2534 static function getGroupPage( $group ) {
2535 MessageCache
::loadAllMessages();
2536 $page = wfMsgForContent( 'grouppage-' . $group );
2537 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2538 $title = Title
::newFromText( $page );
2539 if( is_object( $title ) )
2546 * Create a link to the group in HTML, if available
2548 * @param $group Name of the group
2549 * @param $text The text of the link
2552 static function makeGroupLinkHTML( $group, $text = '' ) {
2554 $text = self
::getGroupName( $group );
2556 $title = self
::getGroupPage( $group );
2559 $sk = $wgUser->getSkin();
2560 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2567 * Create a link to the group in Wikitext, if available
2569 * @param $group Name of the group
2570 * @param $text The text of the link (by default, the name of the group)
2573 static function makeGroupLinkWiki( $group, $text = '' ) {
2575 $text = self
::getGroupName( $group );
2577 $title = self
::getGroupPage( $group );
2579 $page = $title->getPrefixedText();
2580 return "[[$page|$text]]";
2587 * Increment the user's edit-count field.
2588 * Will have no effect for anonymous users.
2590 function incEditCount() {
2591 if( !$this->isAnon() ) {
2592 $dbw = wfGetDB( DB_MASTER
);
2593 $dbw->update( 'user',
2594 array( 'user_editcount=user_editcount+1' ),
2595 array( 'user_id' => $this->getId() ),
2598 // Lazy initialization check...
2599 if( $dbw->affectedRows() == 0 ) {
2600 // Pull from a slave to be less cruel to servers
2601 // Accuracy isn't the point anyway here
2602 $dbr = wfGetDB( DB_SLAVE
);
2603 $count = $dbr->selectField( 'revision',
2605 array( 'rev_user' => $this->getId() ),
2608 // Now here's a goddamn hack...
2609 if( $dbr !== $dbw ) {
2610 // If we actually have a slave server, the count is
2611 // at least one behind because the current transaction
2612 // has not been committed and replicated.
2615 // But if DB_SLAVE is selecting the master, then the
2616 // count we just read includes the revision that was
2617 // just added in the working transaction.
2620 $dbw->update( 'user',
2621 array( 'user_editcount' => $count ),
2622 array( 'user_id' => $this->getId() ),
2626 // edit count in user cache too
2627 $this->invalidateCache();