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
21 class PasswordError
extends MWException
{
31 * A list of default user toggles, i.e. boolean user preferences that are
32 * displayed by Special:Preferences as checkboxes. This list can be
33 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
35 static public $mToggles = array(
45 'editsectiononrightclick',
57 'enotifwatchlistpages',
58 'enotifusertalkpages',
61 'shownumberswatching',
76 * List of member variables which are saved to the shared cache (memcached).
77 * Any operation which changes the corresponding database fields must
78 * call a cache-clearing function.
80 static $mCacheVars = array(
92 'mEmailAuthenticated',
102 * The cache variable declarations
104 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
105 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
106 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
109 * Whether the cache variables have been loaded
114 * Initialisation data source if mDataLoaded==false. May be one of:
115 * defaults anonymous user initialised from class defaults
116 * name initialise from mName
117 * id initialise from mId
118 * session log in from cookies or session if possible
120 * Use the User::newFrom*() family of functions to set this.
125 * Lazy-initialised variables, invalidated with clearInstanceCache
127 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
128 $mBlockreason, $mBlock, $mEffectiveGroups;
131 * Lightweight constructor for anonymous user
132 * Use the User::newFrom* factory functions for other kinds of users
135 $this->clearInstanceCache( 'defaults' );
139 * Load the user table data for this object from the source given by mFrom
142 if ( $this->mDataLoaded
) {
145 wfProfileIn( __METHOD__
);
147 # Set it now to avoid infinite recursion in accessors
148 $this->mDataLoaded
= true;
150 switch ( $this->mFrom
) {
152 $this->loadDefaults();
155 $this->mId
= self
::idFromName( $this->mName
);
157 # Nonexistent user placeholder object
158 $this->loadDefaults( $this->mName
);
167 $this->loadFromSession();
170 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
172 wfProfileOut( __METHOD__
);
176 * Load user table data given mId
177 * @return false if the ID does not exist, true otherwise
180 function loadFromId() {
182 if ( $this->mId
== 0 ) {
183 $this->loadDefaults();
188 $key = wfMemcKey( 'user', 'id', $this->mId
);
189 $data = $wgMemc->get( $key );
190 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
191 # Object is expired, load from DB
196 wfDebug( "Cache miss for user {$this->mId}\n" );
198 if ( !$this->loadFromDatabase() ) {
199 # Can't load from ID, user is anonymous
205 foreach ( self
::$mCacheVars as $name ) {
206 $data[$name] = $this->$name;
208 $data['mVersion'] = MW_USER_VERSION
;
209 $wgMemc->set( $key, $data );
211 wfDebug( "Got user {$this->mId} from cache\n" );
213 foreach ( self
::$mCacheVars as $name ) {
214 $this->$name = $data[$name];
221 * Static factory method for creation from username.
223 * This is slightly less efficient than newFromId(), so use newFromId() if
224 * you have both an ID and a name handy.
226 * @param string $name Username, validated by Title:newFromText()
227 * @param mixed $validate Validate username. Takes the same parameters as
228 * User::getCanonicalName(), except that true is accepted as an alias
229 * for 'valid', for BC.
231 * @return User object, or null if the username is invalid. If the username
232 * is not present in the database, the result will be a user object with
233 * a name, zero user ID and default settings.
236 static function newFromName( $name, $validate = 'valid' ) {
237 if ( $validate === true ) {
240 $name = self
::getCanonicalName( $name, $validate );
241 if ( $name === false ) {
244 # Create unloaded user object
252 static function newFromId( $id ) {
260 * Factory method to fetch whichever user has a given email confirmation code.
261 * This code is generated when an account is created or its e-mail address
264 * If the code is invalid or has expired, returns NULL.
266 * @param string $code
270 static function newFromConfirmationCode( $code ) {
271 $dbr = wfGetDB( DB_SLAVE
);
272 $id = $dbr->selectField( 'user', 'user_id', array(
273 'user_email_token' => md5( $code ),
274 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
276 if( $id !== false ) {
277 return User
::newFromId( $id );
284 * Create a new user object using data from session or cookies. If the
285 * login credentials are invalid, the result is an anonymous user.
290 static function newFromSession() {
292 $user->mFrom
= 'session';
297 * Get username given an id.
298 * @param integer $id Database user id
299 * @return string Nickname of a user
302 static function whoIs( $id ) {
303 $dbr = wfGetDB( DB_SLAVE
);
304 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
308 * Get real username given an id.
309 * @param integer $id Database user id
310 * @return string Realname of a user
313 static function whoIsReal( $id ) {
314 $dbr = wfGetDB( DB_SLAVE
);
315 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), 'User::whoIsReal' );
319 * Get database id given a user name
320 * @param string $name Nickname of a user
321 * @return integer|null Database user id (null: if non existent
324 static function idFromName( $name ) {
325 $nt = Title
::newFromText( $name );
326 if( is_null( $nt ) ) {
330 $dbr = wfGetDB( DB_SLAVE
);
331 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
333 if ( $s === false ) {
341 * Does the string match an anonymous IPv4 address?
343 * This function exists for username validation, in order to reject
344 * usernames which are similar in form to IP addresses. Strings such
345 * as 300.300.300.300 will return true because it looks like an IP
346 * address, despite not being strictly valid.
348 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
349 * address because the usemod software would "cloak" anonymous IP
350 * addresses like this, if we allowed accounts like this to be created
351 * new users could get the old edits of these anonymous users.
356 * @param string $name Nickname of a user
359 static function isIP( $name ) {
360 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User
::isIPv6($name);
361 /*return preg_match("/^
362 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
363 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
364 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
365 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
370 * Check if $name is an IPv6 IP.
372 static function isIPv6($name) {
374 * if it has any non-valid characters, it can't be a valid IPv6
377 if (preg_match("/[^:a-fA-F0-9]/", $name))
380 $parts = explode(":", $name);
381 if (count($parts) < 3)
383 foreach ($parts as $part) {
384 if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part))
391 * Is the input a valid username?
393 * Checks if the input is a valid username, we don't want an empty string,
394 * an IP address, anything that containins slashes (would mess up subpages),
395 * is longer than the maximum allowed username size or doesn't begin with
398 * @param string $name
402 static function isValidUserName( $name ) {
403 global $wgContLang, $wgMaxNameChars;
406 || User
::isIP( $name )
407 ||
strpos( $name, '/' ) !== false
408 ||
strlen( $name ) > $wgMaxNameChars
409 ||
$name != $wgContLang->ucfirst( $name ) )
412 // Ensure that the name can't be misresolved as a different title,
413 // such as with extra namespace keys at the start.
414 $parsed = Title
::newFromText( $name );
415 if( is_null( $parsed )
416 ||
$parsed->getNamespace()
417 ||
strcmp( $name, $parsed->getPrefixedText() ) )
420 // Check an additional blacklist of troublemaker characters.
421 // Should these be merged into the title char list?
422 $unicodeBlacklist = '/[' .
423 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
424 '\x{00a0}' . # non-breaking space
425 '\x{2000}-\x{200f}' . # various whitespace
426 '\x{2028}-\x{202f}' . # breaks and control chars
427 '\x{3000}' . # ideographic space
428 '\x{e000}-\x{f8ff}' . # private use
430 if( preg_match( $unicodeBlacklist, $name ) ) {
438 * Usernames which fail to pass this function will be blocked
439 * from user login and new account registrations, but may be used
440 * internally by batch processes.
442 * If an account already exists in this form, login will be blocked
443 * by a failure to pass this function.
445 * @param string $name
448 static function isUsableName( $name ) {
449 global $wgReservedUsernames;
451 // Must be a usable username, obviously ;)
452 self
::isValidUserName( $name ) &&
454 // Certain names may be reserved for batch processes.
455 !in_array( $name, $wgReservedUsernames );
459 * Usernames which fail to pass this function will be blocked
460 * from new account registrations, but may be used internally
461 * either by batch processes or by user accounts which have
462 * already been created.
464 * Additional character blacklisting may be added here
465 * rather than in isValidUserName() to avoid disrupting
468 * @param string $name
471 static function isCreatableName( $name ) {
473 self
::isUsableName( $name ) &&
475 // Registration-time character blacklisting...
476 strpos( $name, '@' ) === false;
480 * Is the input a valid password?
482 * @param string $password
486 static function isValidPassword( $password ) {
487 global $wgMinimalPasswordLength;
490 if( !wfRunHooks( 'isValidPassword', array( $password, &$result ) ) ) return $result;
491 if ($result === false) return false;
492 return (strlen( $password ) >= $wgMinimalPasswordLength);
496 * Does the string match roughly an email address ?
498 * There used to be a regular expression here, it got removed because it
499 * rejected valid addresses. Actually just check if there is '@' somewhere
500 * in the given address.
502 * @todo Check for RFC 2822 compilance
505 * @param string $addr email address
509 static function isValidEmailAddr ( $addr ) {
510 return ( trim( $addr ) != '' ) &&
511 (false !== strpos( $addr, '@' ) );
515 * Given unvalidated user input, return a canonical username, or false if
516 * the username is invalid.
517 * @param string $name
518 * @param mixed $validate Type of validation to use:
519 * false No validation
520 * 'valid' Valid for batch processes
521 * 'usable' Valid for batch processes and login
522 * 'creatable' Valid for batch processes, login and account creation
524 static function getCanonicalName( $name, $validate = 'valid' ) {
525 # Force usernames to capital
527 $name = $wgContLang->ucfirst( $name );
529 # Clean up name according to title rules
530 $t = Title
::newFromText( $name );
531 if( is_null( $t ) ) {
535 # Reject various classes of invalid names
536 $name = $t->getText();
538 $name = $wgAuth->getCanonicalName( $t->getText() );
540 switch ( $validate ) {
544 if ( !User
::isValidUserName( $name ) ) {
549 if ( !User
::isUsableName( $name ) ) {
554 if ( !User
::isCreatableName( $name ) ) {
559 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
565 * Count the number of edits of a user
567 * It should not be static and some day should be merged as proper member function / deprecated -- domas
569 * @param int $uid The user ID to check
573 static function edits( $uid ) {
574 wfProfileIn( __METHOD__
);
575 $dbr = wfGetDB( DB_SLAVE
);
576 // check if the user_editcount field has been initialized
577 $field = $dbr->selectField(
578 'user', 'user_editcount',
579 array( 'user_id' => $uid ),
583 if( $field === null ) { // it has not been initialized. do so.
584 $dbw = wfGetDb( DB_MASTER
);
585 $count = $dbr->selectField(
586 'revision', 'count(*)',
587 array( 'rev_user' => $uid ),
592 array( 'user_editcount' => $count ),
593 array( 'user_id' => $uid ),
599 wfProfileOut( __METHOD__
);
604 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
605 * @todo: hash random numbers to improve security, like generateToken()
610 static function randomPassword() {
611 global $wgMinimalPasswordLength;
612 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
613 $l = strlen( $pwchars ) - 1;
615 $pwlength = max( 7, $wgMinimalPasswordLength );
616 $digit = mt_rand(0, $pwlength - 1);
618 for ( $i = 0; $i < $pwlength; $i++
) {
619 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
625 * Set cached properties to default. Note: this no longer clears
626 * uncached lazy-initialised properties. The constructor does that instead.
630 function loadDefaults( $name = false ) {
631 wfProfileIn( __METHOD__
);
633 global $wgCookiePrefix;
636 $this->mName
= $name;
637 $this->mRealName
= '';
638 $this->mPassword
= $this->mNewpassword
= '';
639 $this->mNewpassTime
= null;
641 $this->mOptions
= null; # Defer init
643 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
644 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
646 $this->mTouched
= '0'; # Allow any pages to be cached
649 $this->setToken(); # Random
650 $this->mEmailAuthenticated
= null;
651 $this->mEmailToken
= '';
652 $this->mEmailTokenExpires
= null;
653 $this->mRegistration
= wfTimestamp( TS_MW
);
654 $this->mGroups
= array();
656 wfProfileOut( __METHOD__
);
660 * Initialise php session
661 * @deprecated use wfSetupSession()
663 function SetupSession() {
668 * Load user data from the session or login cookie. If there are no valid
669 * credentials, initialises the user as an anon.
670 * @return true if the user is logged in, false otherwise
674 function loadFromSession() {
675 global $wgMemc, $wgCookiePrefix;
677 if ( isset( $_SESSION['wsUserID'] ) ) {
678 if ( 0 != $_SESSION['wsUserID'] ) {
679 $sId = $_SESSION['wsUserID'];
681 $this->loadDefaults();
684 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
685 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
686 $_SESSION['wsUserID'] = $sId;
688 $this->loadDefaults();
691 if ( isset( $_SESSION['wsUserName'] ) ) {
692 $sName = $_SESSION['wsUserName'];
693 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
694 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
695 $_SESSION['wsUserName'] = $sName;
697 $this->loadDefaults();
701 $passwordCorrect = FALSE;
703 if ( !$this->loadFromId() ) {
704 # Not a valid ID, loadFromId has switched the object to anon for us
708 if ( isset( $_SESSION['wsToken'] ) ) {
709 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
711 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
712 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
715 # No session or persistent login cookie
716 $this->loadDefaults();
720 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
721 wfDebug( "Logged in from $from\n" );
724 # Invalid credentials
725 wfDebug( "Can't log in from $from, invalid credentials\n" );
726 $this->loadDefaults();
732 * Load user and user_group data from the database
733 * $this->mId must be set, this is how the user is identified.
735 * @return true if the user exists, false if the user is anonymous
738 function loadFromDatabase() {
740 $this->mId
= intval( $this->mId
);
742 /** Anonymous user */
744 $this->loadDefaults();
748 $dbr = wfGetDB( DB_MASTER
);
749 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
751 if ( $s !== false ) {
752 # Initialise user table data
753 $this->mName
= $s->user_name
;
754 $this->mRealName
= $s->user_real_name
;
755 $this->mPassword
= $s->user_password
;
756 $this->mNewpassword
= $s->user_newpassword
;
757 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $s->user_newpass_time
);
758 $this->mEmail
= $s->user_email
;
759 $this->decodeOptions( $s->user_options
);
760 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
761 $this->mToken
= $s->user_token
;
762 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
763 $this->mEmailToken
= $s->user_email_token
;
764 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $s->user_email_token_expires
);
765 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $s->user_registration
);
766 $this->mEditCount
= $s->user_editcount
;
767 $this->getEditCount(); // revalidation for nulls
770 $res = $dbr->select( 'user_groups',
772 array( 'ug_user' => $this->mId
),
774 $this->mGroups
= array();
775 while( $row = $dbr->fetchObject( $res ) ) {
776 $this->mGroups
[] = $row->ug_group
;
782 $this->loadDefaults();
788 * Clear various cached data stored in this object.
789 * @param string $reloadFrom Reload user and user_groups table data from a
790 * given source. May be "name", "id", "defaults", "session" or false for
793 function clearInstanceCache( $reloadFrom = false ) {
794 $this->mNewtalk
= -1;
795 $this->mDatePreference
= null;
796 $this->mBlockedby
= -1; # Unset
797 $this->mHash
= false;
799 $this->mRights
= null;
800 $this->mEffectiveGroups
= null;
803 $this->mDataLoaded
= false;
804 $this->mFrom
= $reloadFrom;
809 * Combine the language default options with any site-specific options
810 * and add the default language variants.
811 * Not really private cause it's called by Language class
816 static function getDefaultOptions() {
817 global $wgNamespacesToBeSearchedDefault;
819 * Site defaults will override the global/language defaults
821 global $wgDefaultUserOptions, $wgContLang;
822 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
825 * default language setting
827 $variant = $wgContLang->getPreferredVariant( false );
828 $defOpt['variant'] = $variant;
829 $defOpt['language'] = $variant;
831 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
832 $defOpt['searchNs'.$nsnum] = $val;
838 * Get a given default option value.
845 function getDefaultOption( $opt ) {
846 $defOpts = User
::getDefaultOptions();
847 if( isset( $defOpts[$opt] ) ) {
848 return $defOpts[$opt];
855 * Get a list of user toggle names
858 static function getToggles() {
860 $extraToggles = array();
861 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
862 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
867 * Get blocking information
869 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
870 * non-critical checks are done against slaves. Check when actually saving should be done against
873 function getBlockedStatus( $bFromSlave = true ) {
874 global $wgEnableSorbs, $wgProxyWhitelist;
876 if ( -1 != $this->mBlockedby
) {
877 wfDebug( "User::getBlockedStatus: already loaded.\n" );
881 wfProfileIn( __METHOD__
);
882 wfDebug( __METHOD__
.": checking...\n" );
884 $this->mBlockedby
= 0;
885 $this->mHideName
= 0;
888 if ($this->isAllowed( 'ipblock-exempt' ) ) {
889 # Exempt from all types of IP-block
894 $this->mBlock
= new Block();
895 $this->mBlock
->fromMaster( !$bFromSlave );
896 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
897 wfDebug( __METHOD__
.": Found block.\n" );
898 $this->mBlockedby
= $this->mBlock
->mBy
;
899 $this->mBlockreason
= $this->mBlock
->mReason
;
900 $this->mHideName
= $this->mBlock
->mHideName
;
901 if ( $this->isLoggedIn() ) {
902 $this->spreadBlock();
905 $this->mBlock
= null;
906 wfDebug( __METHOD__
.": No block.\n" );
910 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
913 if ( wfIsLocallyBlockedProxy( $ip ) ) {
914 $this->mBlockedby
= wfMsg( 'proxyblocker' );
915 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
919 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
920 if ( $this->inSorbsBlacklist( $ip ) ) {
921 $this->mBlockedby
= wfMsg( 'sorbs' );
922 $this->mBlockreason
= wfMsg( 'sorbsreason' );
928 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
930 wfProfileOut( __METHOD__
);
933 function inSorbsBlacklist( $ip ) {
934 global $wgEnableSorbs, $wgSorbsUrl;
936 return $wgEnableSorbs &&
937 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
940 function inDnsBlacklist( $ip, $base ) {
941 wfProfileIn( __METHOD__
);
947 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
949 for ( $i=4; $i>=1; $i-- ) {
950 $host .= $m[$i] . '.';
955 $ipList = gethostbynamel( $host );
958 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
961 wfDebug( "Requested $host, not found in $base.\n" );
965 wfProfileOut( __METHOD__
);
970 * Is this user subject to rate limiting?
974 public function isPingLimitable() {
975 global $wgRateLimitsExcludedGroups;
976 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) != array();
980 * Primitive rate limits: enforce maximum actions per time period
981 * to put a brake on flooding.
983 * Note: when using a shared cache like memcached, IP-address
984 * last-hit counters will be shared across wikis.
986 * @return bool true if a rate limiter was tripped
989 function pingLimiter( $action='edit' ) {
991 # Call the 'PingLimiter' hook
993 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
997 global $wgRateLimits, $wgRateLimitsExcludedGroups;
998 if( !isset( $wgRateLimits[$action] ) ) {
1002 # Some groups shouldn't trigger the ping limiter, ever
1003 if( !$this->isPingLimitable() )
1006 global $wgMemc, $wgRateLimitLog;
1007 wfProfileIn( __METHOD__
);
1009 $limits = $wgRateLimits[$action];
1011 $id = $this->getId();
1014 if( isset( $limits['anon'] ) && $id == 0 ) {
1015 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1018 if( isset( $limits['user'] ) && $id != 0 ) {
1019 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
1021 if( $this->isNewbie() ) {
1022 if( isset( $limits['newbie'] ) && $id != 0 ) {
1023 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1025 if( isset( $limits['ip'] ) ) {
1026 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1029 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1030 $subnet = $matches[1];
1031 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1036 foreach( $keys as $key => $limit ) {
1037 list( $max, $period ) = $limit;
1038 $summary = "(limit $max in {$period}s)";
1039 $count = $wgMemc->get( $key );
1041 if( $count > $max ) {
1042 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1043 if( $wgRateLimitLog ) {
1044 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1048 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1051 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1052 $wgMemc->add( $key, 1, intval( $period ) );
1054 $wgMemc->incr( $key );
1057 wfProfileOut( __METHOD__
);
1062 * Check if user is blocked
1063 * @return bool True if blocked, false otherwise
1065 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1066 wfDebug( "User::isBlocked: enter\n" );
1067 $this->getBlockedStatus( $bFromSlave );
1068 return $this->mBlockedby
!== 0;
1072 * Check if user is blocked from editing a particular article
1074 function isBlockedFrom( $title, $bFromSlave = false ) {
1075 global $wgBlockAllowsUTEdit;
1076 wfProfileIn( __METHOD__
);
1077 wfDebug( __METHOD__
.": enter\n" );
1079 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1080 $blocked = $this->isBlocked( $bFromSlave );
1081 # If a user's name is suppressed, they cannot make edits anywhere
1082 if ( !$this->mHideName
&& $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1083 $title->getNamespace() == NS_USER_TALK
) {
1085 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1087 wfProfileOut( __METHOD__
);
1092 * Get name of blocker
1093 * @return string name of blocker
1095 function blockedBy() {
1096 $this->getBlockedStatus();
1097 return $this->mBlockedby
;
1101 * Get blocking reason
1102 * @return string Blocking reason
1104 function blockedFor() {
1105 $this->getBlockedStatus();
1106 return $this->mBlockreason
;
1110 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1118 * Set the user and reload all fields according to that ID
1119 * @deprecated use User::newFromId()
1121 function setID( $v ) {
1123 $this->clearInstanceCache( 'id' );
1127 * Get the user name, or the IP for anons
1129 function getName() {
1130 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1131 # Special case optimisation
1132 return $this->mName
;
1135 if ( $this->mName
=== false ) {
1136 $this->mName
= wfGetIP();
1139 return IP
::sanitizeIP($this->mName
);
1144 * Set the user name.
1146 * This does not reload fields from the database according to the given
1147 * name. Rather, it is used to create a temporary "nonexistent user" for
1148 * later addition to the database. It can also be used to set the IP
1149 * address for an anonymous user to something other than the current
1152 * User::newFromName() has rougly the same function, when the named user
1155 function setName( $str ) {
1157 $this->mName
= $str;
1161 * Return the title dbkey form of the name, for eg user pages.
1165 function getTitleKey() {
1166 return str_replace( ' ', '_', $this->getName() );
1169 function getNewtalk() {
1172 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1173 if( $this->mNewtalk
=== -1 ) {
1174 $this->mNewtalk
= false; # reset talk page status
1176 # Check memcached separately for anons, who have no
1177 # entire User object stored in there.
1180 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1181 $newtalk = $wgMemc->get( $key );
1182 if( $newtalk != "" ) {
1183 $this->mNewtalk
= (bool)$newtalk;
1185 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
1186 $wgMemc->set( $key, (int)$this->mNewtalk
, time() +
1800 );
1189 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1193 return (bool)$this->mNewtalk
;
1197 * Return the talk page(s) this user has new messages on.
1199 function getNewMessageLinks() {
1201 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1204 if (!$this->getNewtalk())
1206 $up = $this->getUserPage();
1207 $utp = $up->getTalkPage();
1208 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1213 * Perform a user_newtalk check on current slaves; if the memcached data
1214 * is funky we don't want newtalk state to get stuck on save, as that's
1217 * @param string $field
1222 function checkNewtalk( $field, $id ) {
1223 $dbr = wfGetDB( DB_SLAVE
);
1224 $ok = $dbr->selectField( 'user_newtalk', $field,
1225 array( $field => $id ), __METHOD__
);
1226 return $ok !== false;
1231 * @param string $field
1235 function updateNewtalk( $field, $id ) {
1236 if( $this->checkNewtalk( $field, $id ) ) {
1237 wfDebug( __METHOD__
." already set ($field, $id), ignoring\n" );
1240 $dbw = wfGetDB( DB_MASTER
);
1241 $dbw->insert( 'user_newtalk',
1242 array( $field => $id ),
1245 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1250 * Clear the new messages flag for the given user
1251 * @param string $field
1255 function deleteNewtalk( $field, $id ) {
1256 if( !$this->checkNewtalk( $field, $id ) ) {
1257 wfDebug( __METHOD__
.": already gone ($field, $id), ignoring\n" );
1260 $dbw = wfGetDB( DB_MASTER
);
1261 $dbw->delete( 'user_newtalk',
1262 array( $field => $id ),
1264 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1269 * Update the 'You have new messages!' status.
1272 function setNewtalk( $val ) {
1273 if( wfReadOnly() ) {
1278 $this->mNewtalk
= $val;
1280 if( $this->isAnon() ) {
1282 $id = $this->getName();
1285 $id = $this->getId();
1289 $changed = $this->updateNewtalk( $field, $id );
1291 $changed = $this->deleteNewtalk( $field, $id );
1295 if( $this->isAnon() ) {
1296 // Anons have a separate memcached space, since
1297 // user records aren't kept for them.
1299 $key = wfMemcKey( 'newtalk', 'ip', $val );
1300 $wgMemc->set( $key, $val ?
1 : 0 );
1303 // Make sure the user page is watched, so a notification
1304 // will be sent out if enabled.
1305 $this->addWatch( $this->getTalkPage() );
1308 $this->invalidateCache();
1313 * Generate a current or new-future timestamp to be stored in the
1314 * user_touched field when we update things.
1316 private static function newTouchedTimestamp() {
1317 global $wgClockSkewFudge;
1318 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1322 * Clear user data from memcached.
1323 * Use after applying fun updates to the database; caller's
1324 * responsibility to update user_touched if appropriate.
1326 * Called implicitly from invalidateCache() and saveSettings().
1328 private function clearSharedCache() {
1331 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1336 * Immediately touch the user data cache for this account.
1337 * Updates user_touched field, and removes account data from memcached
1338 * for reload on the next hit.
1340 function invalidateCache() {
1343 $this->mTouched
= self
::newTouchedTimestamp();
1345 $dbw = wfGetDB( DB_MASTER
);
1346 $dbw->update( 'user',
1347 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1348 array( 'user_id' => $this->mId
),
1351 $this->clearSharedCache();
1355 function validateCache( $timestamp ) {
1357 return ($timestamp >= $this->mTouched
);
1361 * Encrypt a password.
1362 * It can eventuall salt a password @see User::addSalt()
1363 * @param string $p clear Password.
1364 * @return string Encrypted password.
1366 function encryptPassword( $p ) {
1368 return wfEncryptPassword( $this->mId
, $p );
1372 * Set the password and reset the random token
1373 * Calls through to authentication plugin if necessary;
1374 * will have no effect if the auth plugin refuses to
1375 * pass the change through or if the legal password
1378 * As a special case, setting the password to null
1379 * wipes it, so the account cannot be logged in until
1380 * a new password is set, for instance via e-mail.
1382 * @param string $str
1383 * @throws PasswordError on failure
1385 function setPassword( $str ) {
1388 if( $str !== null ) {
1389 if( !$wgAuth->allowPasswordChange() ) {
1390 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1393 if( !$this->isValidPassword( $str ) ) {
1394 global $wgMinimalPasswordLength;
1395 throw new PasswordError( wfMsg( 'passwordtooshort',
1396 $wgMinimalPasswordLength ) );
1400 if( !$wgAuth->setPassword( $this, $str ) ) {
1401 throw new PasswordError( wfMsg( 'externaldberror' ) );
1404 $this->setInternalPassword( $str );
1410 * Set the password and reset the random token no matter
1413 * @param string $str
1415 function setInternalPassword( $str ) {
1419 if( $str === null ) {
1420 // Save an invalid hash...
1421 $this->mPassword
= '';
1423 $this->mPassword
= $this->encryptPassword( $str );
1425 $this->mNewpassword
= '';
1426 $this->mNewpassTime
= null;
1429 * Set the random token (used for persistent authentication)
1430 * Called from loadDefaults() among other places.
1433 function setToken( $token = false ) {
1434 global $wgSecretKey, $wgProxyKey;
1437 if ( $wgSecretKey ) {
1438 $key = $wgSecretKey;
1439 } elseif ( $wgProxyKey ) {
1444 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1446 $this->mToken
= $token;
1450 function setCookiePassword( $str ) {
1452 $this->mCookiePassword
= md5( $str );
1456 * Set the password for a password reminder or new account email
1457 * Sets the user_newpass_time field if $throttle is true
1459 function setNewpassword( $str, $throttle = true ) {
1461 $this->mNewpassword
= $this->encryptPassword( $str );
1463 $this->mNewpassTime
= wfTimestampNow();
1468 * Returns true if a password reminder email has already been sent within
1469 * the last $wgPasswordReminderResendTime hours
1471 function isPasswordReminderThrottled() {
1472 global $wgPasswordReminderResendTime;
1474 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1477 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1478 return time() < $expiry;
1481 function getEmail() {
1483 return $this->mEmail
;
1486 function getEmailAuthenticationTimestamp() {
1488 return $this->mEmailAuthenticated
;
1491 function setEmail( $str ) {
1493 $this->mEmail
= $str;
1496 function getRealName() {
1498 return $this->mRealName
;
1501 function setRealName( $str ) {
1503 $this->mRealName
= $str;
1507 * @param string $oname The option to check
1508 * @param string $defaultOverride A default value returned if the option does not exist
1511 function getOption( $oname, $defaultOverride = '' ) {
1514 if ( is_null( $this->mOptions
) ) {
1515 if($defaultOverride != '') {
1516 return $defaultOverride;
1518 $this->mOptions
= User
::getDefaultOptions();
1521 if ( array_key_exists( $oname, $this->mOptions
) ) {
1522 return trim( $this->mOptions
[$oname] );
1524 return $defaultOverride;
1529 * Get the user's date preference, including some important migration for
1532 function getDatePreference() {
1533 if ( is_null( $this->mDatePreference
) ) {
1535 $value = $this->getOption( 'date' );
1536 $map = $wgLang->getDatePreferenceMigrationMap();
1537 if ( isset( $map[$value] ) ) {
1538 $value = $map[$value];
1540 $this->mDatePreference
= $value;
1542 return $this->mDatePreference
;
1546 * @param string $oname The option to check
1547 * @return bool False if the option is not selected, true if it is
1549 function getBoolOption( $oname ) {
1550 return (bool)$this->getOption( $oname );
1554 * Get an option as an integer value from the source string.
1555 * @param string $oname The option to check
1556 * @param int $default Optional value to return if option is unset/blank.
1559 function getIntOption( $oname, $default=0 ) {
1560 $val = $this->getOption( $oname );
1564 return intval( $val );
1567 function setOption( $oname, $val ) {
1569 if ( is_null( $this->mOptions
) ) {
1570 $this->mOptions
= User
::getDefaultOptions();
1572 if ( $oname == 'skin' ) {
1573 # Clear cached skin, so the new one displays immediately in Special:Preferences
1574 unset( $this->mSkin
);
1576 // Filter out any newlines that may have passed through input validation.
1577 // Newlines are used to separate items in the options blob.
1578 $val = str_replace( "\r\n", "\n", $val );
1579 $val = str_replace( "\r", "\n", $val );
1580 $val = str_replace( "\n", " ", $val );
1581 $this->mOptions
[$oname] = $val;
1584 function getRights() {
1585 if ( is_null( $this->mRights
) ) {
1586 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1588 return $this->mRights
;
1592 * Get the list of explicit group memberships this user has.
1593 * The implicit * and user groups are not included.
1594 * @return array of strings
1596 function getGroups() {
1598 return $this->mGroups
;
1602 * Get the list of implicit group memberships this user has.
1603 * This includes all explicit groups, plus 'user' if logged in
1604 * and '*' for all accounts.
1605 * @param boolean $recache Don't use the cache
1606 * @return array of strings
1608 function getEffectiveGroups( $recache = false ) {
1609 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1611 $this->mEffectiveGroups
= $this->mGroups
;
1612 $this->mEffectiveGroups
[] = '*';
1614 $this->mEffectiveGroups
[] = 'user';
1616 global $wgAutoConfirmAge, $wgAutoConfirmCount;
1618 $accountAge = time() - wfTimestampOrNull( TS_UNIX
, $this->mRegistration
);
1619 if( $accountAge >= $wgAutoConfirmAge && $this->getEditCount() >= $wgAutoConfirmCount ) {
1620 $this->mEffectiveGroups
[] = 'autoconfirmed';
1622 # Implicit group for users whose email addresses are confirmed
1623 global $wgEmailAuthentication;
1624 if( self
::isValidEmailAddr( $this->mEmail
) ) {
1625 if( $wgEmailAuthentication ) {
1626 if( $this->mEmailAuthenticated
)
1627 $this->mEffectiveGroups
[] = 'emailconfirmed';
1629 $this->mEffectiveGroups
[] = 'emailconfirmed';
1634 return $this->mEffectiveGroups
;
1637 /* Return the edit count for the user. This is where User::edits should have been */
1638 function getEditCount() {
1640 if ( !isset( $this->mEditCount
) ) {
1641 /* Populate the count, if it has not been populated yet */
1642 $this->mEditCount
= User
::edits($this->mId
);
1644 return $this->mEditCount
;
1652 * Add the user to the given group.
1653 * This takes immediate effect.
1656 function addGroup( $group ) {
1658 $dbw = wfGetDB( DB_MASTER
);
1659 if( $this->getId() ) {
1660 $dbw->insert( 'user_groups',
1662 'ug_user' => $this->getID(),
1663 'ug_group' => $group,
1666 array( 'IGNORE' ) );
1669 $this->mGroups
[] = $group;
1670 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1672 $this->invalidateCache();
1676 * Remove the user from the given group.
1677 * This takes immediate effect.
1680 function removeGroup( $group ) {
1682 $dbw = wfGetDB( DB_MASTER
);
1683 $dbw->delete( 'user_groups',
1685 'ug_user' => $this->getID(),
1686 'ug_group' => $group,
1688 'User::removeGroup' );
1690 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1691 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1693 $this->invalidateCache();
1698 * A more legible check for non-anonymousness.
1699 * Returns true if the user is not an anonymous visitor.
1703 function isLoggedIn() {
1704 return( $this->getID() != 0 );
1708 * A more legible check for anonymousness.
1709 * Returns true if the user is an anonymous visitor.
1714 return !$this->isLoggedIn();
1718 * Whether the user is a bot
1722 return $this->isAllowed( 'bot' );
1726 * Check if user is allowed to access a feature / make an action
1727 * @param string $action Action to be checked
1728 * @return boolean True: action is allowed, False: action should not be allowed
1730 function isAllowed($action='') {
1731 if ( $action === '' )
1732 // In the spirit of DWIM
1735 return in_array( $action, $this->getRights() );
1739 * Load a skin if it doesn't exist or return it
1740 * @todo FIXME : need to check the old failback system [AV]
1742 function &getSkin() {
1744 if ( ! isset( $this->mSkin
) ) {
1745 wfProfileIn( __METHOD__
);
1748 $userSkin = $this->getOption( 'skin' );
1749 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1751 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1752 wfProfileOut( __METHOD__
);
1754 return $this->mSkin
;
1758 * @param string $title Article title to look at
1762 * Check watched status of an article
1763 * @return bool True if article is watched
1765 function isWatched( $title ) {
1766 $wl = WatchedItem
::fromUserTitle( $this, $title );
1767 return $wl->isWatched();
1773 function addWatch( $title ) {
1774 $wl = WatchedItem
::fromUserTitle( $this, $title );
1776 $this->invalidateCache();
1780 * Stop watching an article
1782 function removeWatch( $title ) {
1783 $wl = WatchedItem
::fromUserTitle( $this, $title );
1785 $this->invalidateCache();
1789 * Clear the user's notification timestamp for the given title.
1790 * If e-notif e-mails are on, they will receive notification mails on
1791 * the next change of the page if it's watched etc.
1793 function clearNotification( &$title ) {
1794 global $wgUser, $wgUseEnotif;
1796 # Do nothing if the database is locked to writes
1797 if( wfReadOnly() ) {
1801 if ($title->getNamespace() == NS_USER_TALK
&&
1802 $title->getText() == $this->getName() ) {
1803 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1805 $this->setNewtalk( false );
1808 if( !$wgUseEnotif ) {
1812 if( $this->isAnon() ) {
1813 // Nothing else to do...
1817 // Only update the timestamp if the page is being watched.
1818 // The query to find out if it is watched is cached both in memcached and per-invocation,
1819 // and when it does have to be executed, it can be on a slave
1820 // If this is the user's newtalk page, we always update the timestamp
1821 if ($title->getNamespace() == NS_USER_TALK
&&
1822 $title->getText() == $wgUser->getName())
1825 } elseif ( $this->getID() == $wgUser->getID() ) {
1826 $watched = $title->userIsWatching();
1831 // If the page is watched by the user (or may be watched), update the timestamp on any
1832 // any matching rows
1834 $dbw = wfGetDB( DB_MASTER
);
1835 $dbw->update( 'watchlist',
1837 'wl_notificationtimestamp' => NULL
1838 ), array( /* WHERE */
1839 'wl_title' => $title->getDBkey(),
1840 'wl_namespace' => $title->getNamespace(),
1841 'wl_user' => $this->getID()
1842 ), 'User::clearLastVisited'
1850 * Resets all of the given user's page-change notification timestamps.
1851 * If e-notif e-mails are on, they will receive notification mails on
1852 * the next change of any watched page.
1854 * @param int $currentUser user ID number
1857 function clearAllNotifications( $currentUser ) {
1858 global $wgUseEnotif;
1859 if ( !$wgUseEnotif ) {
1860 $this->setNewtalk( false );
1863 if( $currentUser != 0 ) {
1865 $dbw = wfGetDB( DB_MASTER
);
1866 $dbw->update( 'watchlist',
1868 'wl_notificationtimestamp' => NULL
1869 ), array( /* WHERE */
1870 'wl_user' => $currentUser
1871 ), 'UserMailer::clearAll'
1874 # we also need to clear here the "you have new message" notification for the own user_talk page
1875 # This is cleared one page view later in Article::viewUpdates();
1881 * @return string Encoding options
1883 function encodeOptions() {
1885 if ( is_null( $this->mOptions
) ) {
1886 $this->mOptions
= User
::getDefaultOptions();
1889 foreach ( $this->mOptions
as $oname => $oval ) {
1890 array_push( $a, $oname.'='.$oval );
1892 $s = implode( "\n", $a );
1899 function decodeOptions( $str ) {
1900 $this->mOptions
= array();
1901 $a = explode( "\n", $str );
1902 foreach ( $a as $s ) {
1904 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1905 $this->mOptions
[$m[1]] = $m[2];
1910 function setCookies() {
1911 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1913 if ( 0 == $this->mId
) return;
1914 $exp = time() +
$wgCookieExpiration;
1916 $_SESSION['wsUserID'] = $this->mId
;
1917 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1919 $_SESSION['wsUserName'] = $this->getName();
1920 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1922 $_SESSION['wsToken'] = $this->mToken
;
1923 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1924 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1926 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1932 * Clears the cookies and session, resets the instance cache
1935 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1936 $this->clearInstanceCache( 'defaults' );
1938 $_SESSION['wsUserID'] = 0;
1940 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1941 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1943 # Remember when user logged out, to prevent seeing cached pages
1944 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1948 * Save object settings into database
1949 * @fixme Only rarely do all these fields need to be set!
1951 function saveSettings() {
1953 if ( wfReadOnly() ) { return; }
1954 if ( 0 == $this->mId
) { return; }
1956 $this->mTouched
= self
::newTouchedTimestamp();
1958 $dbw = wfGetDB( DB_MASTER
);
1959 $dbw->update( 'user',
1961 'user_name' => $this->mName
,
1962 'user_password' => $this->mPassword
,
1963 'user_newpassword' => $this->mNewpassword
,
1964 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
1965 'user_real_name' => $this->mRealName
,
1966 'user_email' => $this->mEmail
,
1967 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1968 'user_options' => $this->encodeOptions(),
1969 'user_touched' => $dbw->timestamp($this->mTouched
),
1970 'user_token' => $this->mToken
1971 ), array( /* WHERE */
1972 'user_id' => $this->mId
1975 $this->clearSharedCache();
1980 * Checks if a user with the given name exists, returns the ID
1982 function idForName() {
1983 $s = trim( $this->getName() );
1984 if ( 0 == strcmp( '', $s ) ) return 0;
1986 $dbr = wfGetDB( DB_SLAVE
);
1987 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
1988 if ( $id === false ) {
1995 * Add a user to the database, return the user object
1997 * @param string $name The user's name
1998 * @param array $params Associative array of non-default parameters to save to the database:
1999 * password The user's password. Password logins will be disabled if this is omitted.
2000 * newpassword A temporary password mailed to the user
2001 * email The user's email address
2002 * email_authenticated The email authentication timestamp
2003 * real_name The user's real name
2004 * options An associative array of non-default options
2005 * token Random authentication token. Do not set.
2006 * registration Registration timestamp. Do not set.
2008 * @return User object, or null if the username already exists
2010 static function createNew( $name, $params = array() ) {
2013 if ( isset( $params['options'] ) ) {
2014 $user->mOptions
= $params['options'] +
$user->mOptions
;
2015 unset( $params['options'] );
2017 $dbw = wfGetDB( DB_MASTER
);
2018 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2020 'user_id' => $seqVal,
2021 'user_name' => $name,
2022 'user_password' => $user->mPassword
,
2023 'user_newpassword' => $user->mNewpassword
,
2024 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2025 'user_email' => $user->mEmail
,
2026 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2027 'user_real_name' => $user->mRealName
,
2028 'user_options' => $user->encodeOptions(),
2029 'user_token' => $user->mToken
,
2030 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2031 'user_editcount' => 0,
2033 foreach ( $params as $name => $value ) {
2034 $fields["user_$name"] = $value;
2036 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2037 if ( $dbw->affectedRows() ) {
2038 $newUser = User
::newFromId( $dbw->insertId() );
2046 * Add an existing user object to the database
2048 function addToDatabase() {
2050 $dbw = wfGetDB( DB_MASTER
);
2051 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2052 $dbw->insert( 'user',
2054 'user_id' => $seqVal,
2055 'user_name' => $this->mName
,
2056 'user_password' => $this->mPassword
,
2057 'user_newpassword' => $this->mNewpassword
,
2058 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2059 'user_email' => $this->mEmail
,
2060 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2061 'user_real_name' => $this->mRealName
,
2062 'user_options' => $this->encodeOptions(),
2063 'user_token' => $this->mToken
,
2064 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2065 'user_editcount' => 0,
2068 $this->mId
= $dbw->insertId();
2070 # Clear instance cache other than user table data, which is already accurate
2071 $this->clearInstanceCache();
2075 * If the (non-anonymous) user is blocked, this function will block any IP address
2076 * that they successfully log on from.
2078 function spreadBlock() {
2079 wfDebug( __METHOD__
."()\n" );
2081 if ( $this->mId
== 0 ) {
2085 $userblock = Block
::newFromDB( '', $this->mId
);
2086 if ( !$userblock ) {
2090 $userblock->doAutoblock( wfGetIp() );
2095 * Generate a string which will be different for any combination of
2096 * user options which would produce different parser output.
2097 * This will be used as part of the hash key for the parser cache,
2098 * so users will the same options can share the same cached data
2101 * Extensions which require it should install 'PageRenderingHash' hook,
2102 * which will give them a chance to modify this key based on their own
2107 function getPageRenderingHash() {
2108 global $wgContLang, $wgUseDynamicDates, $wgLang;
2110 return $this->mHash
;
2113 // stubthreshold is only included below for completeness,
2114 // it will always be 0 when this function is called by parsercache.
2116 $confstr = $this->getOption( 'math' );
2117 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2118 if ( $wgUseDynamicDates ) {
2119 $confstr .= '!' . $this->getDatePreference();
2121 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2122 $confstr .= '!' . $wgLang->getCode();
2123 $confstr .= '!' . $this->getOption( 'thumbsize' );
2124 // add in language specific options, if any
2125 $extra = $wgContLang->getExtraHashOptions();
2128 // Give a chance for extensions to modify the hash, if they have
2129 // extra options or other effects on the parser cache.
2130 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2132 $this->mHash
= $confstr;
2136 function isBlockedFromCreateAccount() {
2137 $this->getBlockedStatus();
2138 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2141 function isAllowedToCreateAccount() {
2142 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2148 function setLoaded( $loaded ) {}
2151 * Get this user's personal page title.
2156 function getUserPage() {
2157 return Title
::makeTitle( NS_USER
, $this->getName() );
2161 * Get this user's talk page title.
2166 function getTalkPage() {
2167 $title = $this->getUserPage();
2168 return $title->getTalkPage();
2174 function getMaxID() {
2175 static $res; // cache
2177 if ( isset( $res ) )
2180 $dbr = wfGetDB( DB_SLAVE
);
2181 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2186 * Determine whether the user is a newbie. Newbies are either
2187 * anonymous IPs, or the most recently created accounts.
2188 * @return bool True if it is a newbie.
2190 function isNewbie() {
2191 return !$this->isAllowed( 'autoconfirmed' );
2195 * Check to see if the given clear-text password is one of the accepted passwords
2196 * @param string $password User password.
2197 * @return bool True if the given password is correct otherwise False.
2199 function checkPassword( $password ) {
2203 // Even though we stop people from creating passwords that
2204 // are shorter than this, doesn't mean people wont be able
2205 // to. Certain authentication plugins do NOT want to save
2206 // domain passwords in a mysql database, so we should
2207 // check this (incase $wgAuth->strict() is false).
2208 if( !$this->isValidPassword( $password ) ) {
2212 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2214 } elseif( $wgAuth->strict() ) {
2215 /* Auth plugin doesn't allow local authentication */
2218 $ep = $this->encryptPassword( $password );
2219 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2221 } elseif ( function_exists( 'iconv' ) ) {
2222 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2223 # Check for this with iconv
2224 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2225 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2233 * Check if the given clear-text password matches the temporary password
2234 * sent by e-mail for password reset operations.
2237 function checkTemporaryPassword( $plaintext ) {
2238 $hash = $this->encryptPassword( $plaintext );
2239 return $hash === $this->mNewpassword
;
2243 * Initialize (if necessary) and return a session token value
2244 * which can be used in edit forms to show that the user's
2245 * login credentials aren't being hijacked with a foreign form
2248 * @param mixed $salt - Optional function-specific data for hash.
2249 * Use a string or an array of strings.
2253 function editToken( $salt = '' ) {
2254 if( !isset( $_SESSION['wsEditToken'] ) ) {
2255 $token = $this->generateToken();
2256 $_SESSION['wsEditToken'] = $token;
2258 $token = $_SESSION['wsEditToken'];
2260 if( is_array( $salt ) ) {
2261 $salt = implode( '|', $salt );
2263 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2267 * Generate a hex-y looking random token for various uses.
2268 * Could be made more cryptographically sure if someone cares.
2271 function generateToken( $salt = '' ) {
2272 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2273 return md5( $token . $salt );
2277 * Check given value against the token value stored in the session.
2278 * A match should confirm that the form was submitted from the
2279 * user's own login session, not a form submission from a third-party
2282 * @param string $val - the input value to compare
2283 * @param string $salt - Optional function-specific data for hash
2287 function matchEditToken( $val, $salt = '' ) {
2289 $sessionToken = $this->editToken( $salt );
2290 if ( $val != $sessionToken ) {
2291 wfDebug( "User::matchEditToken: broken session data\n" );
2293 return $val == $sessionToken;
2297 * Generate a new e-mail confirmation token and send a confirmation
2298 * mail to the user's given address.
2300 * @return mixed True on success, a WikiError object on failure.
2302 function sendConfirmationMail() {
2304 $expiration = null; // gets passed-by-ref and defined in next line.
2305 $url = $this->confirmationTokenUrl( $expiration );
2306 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2307 wfMsg( 'confirmemail_body',
2311 $wgContLang->timeanddate( $expiration, false ) ) );
2315 * Send an e-mail to this user's account. Does not check for
2316 * confirmed status or validity.
2318 * @param string $subject
2319 * @param string $body
2320 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2321 * @return mixed True on success, a WikiError object on failure.
2323 function sendMail( $subject, $body, $from = null ) {
2324 if( is_null( $from ) ) {
2325 global $wgPasswordSender;
2326 $from = $wgPasswordSender;
2329 require_once( 'UserMailer.php' );
2330 $to = new MailAddress( $this );
2331 $sender = new MailAddress( $from );
2332 $error = userMailer( $to, $sender, $subject, $body );
2334 if( $error == '' ) {
2337 return new WikiError( $error );
2342 * Generate, store, and return a new e-mail confirmation code.
2343 * A hash (unsalted since it's used as a key) is stored.
2344 * @param &$expiration mixed output: accepts the expiration time
2348 function confirmationToken( &$expiration ) {
2350 $expires = $now +
7 * 24 * 60 * 60;
2351 $expiration = wfTimestamp( TS_MW
, $expires );
2353 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2354 $hash = md5( $token );
2356 $dbw = wfGetDB( DB_MASTER
);
2357 $dbw->update( 'user',
2358 array( 'user_email_token' => $hash,
2359 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2360 array( 'user_id' => $this->mId
),
2367 * Generate and store a new e-mail confirmation token, and return
2368 * the URL the user can use to confirm.
2369 * @param &$expiration mixed output: accepts the expiration time
2373 function confirmationTokenUrl( &$expiration ) {
2374 $token = $this->confirmationToken( $expiration );
2375 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2376 return $title->getFullUrl();
2380 * Mark the e-mail address confirmed and save.
2382 function confirmEmail() {
2384 $this->mEmailAuthenticated
= wfTimestampNow();
2385 $this->saveSettings();
2390 * Is this user allowed to send e-mails within limits of current
2391 * site configuration?
2394 function canSendEmail() {
2395 return $this->isEmailConfirmed();
2399 * Is this user allowed to receive e-mails within limits of current
2400 * site configuration?
2403 function canReceiveEmail() {
2404 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2408 * Is this user's e-mail address valid-looking and confirmed within
2409 * limits of the current site configuration?
2411 * If $wgEmailAuthentication is on, this may require the user to have
2412 * confirmed their address by returning a code or using a password
2413 * sent to the address from the wiki.
2417 function isEmailConfirmed() {
2418 global $wgEmailAuthentication;
2421 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2422 if( $this->isAnon() )
2424 if( !self
::isValidEmailAddr( $this->mEmail
) )
2426 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2435 * Return true if there is an outstanding request for e-mail confirmation.
2438 function isEmailConfirmationPending() {
2439 global $wgEmailAuthentication;
2440 return $wgEmailAuthentication &&
2441 !$this->isEmailConfirmed() &&
2442 $this->mEmailToken
&&
2443 $this->mEmailTokenExpires
> wfTimestamp();
2447 * @param array $groups list of groups
2448 * @return array list of permission key names for given groups combined
2451 static function getGroupPermissions( $groups ) {
2452 global $wgGroupPermissions;
2454 foreach( $groups as $group ) {
2455 if( isset( $wgGroupPermissions[$group] ) ) {
2456 $rights = array_merge( $rights,
2457 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2464 * @param string $group key name
2465 * @return string localized descriptive name for group, if provided
2468 static function getGroupName( $group ) {
2469 $key = "group-$group";
2470 $name = wfMsg( $key );
2471 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2479 * @param string $group key name
2480 * @return string localized descriptive name for member of a group, if provided
2483 static function getGroupMember( $group ) {
2484 $key = "group-$group-member";
2485 $name = wfMsg( $key );
2486 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2494 * Return the set of defined explicit groups.
2495 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2496 * groups are not included, as they are defined
2497 * automatically, not in the database.
2501 static function getAllGroups() {
2502 global $wgGroupPermissions;
2504 array_keys( $wgGroupPermissions ),
2505 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2509 * Get the title of a page describing a particular group
2511 * @param $group Name of the group
2514 static function getGroupPage( $group ) {
2515 $page = wfMsgForContent( 'grouppage-' . $group );
2516 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2517 $title = Title
::newFromText( $page );
2518 if( is_object( $title ) )
2525 * Create a link to the group in HTML, if available
2527 * @param $group Name of the group
2528 * @param $text The text of the link
2531 static function makeGroupLinkHTML( $group, $text = '' ) {
2533 $text = self
::getGroupName( $group );
2535 $title = self
::getGroupPage( $group );
2538 $sk = $wgUser->getSkin();
2539 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2546 * Create a link to the group in Wikitext, if available
2548 * @param $group Name of the group
2549 * @param $text The text of the link (by default, the name of the group)
2552 static function makeGroupLinkWiki( $group, $text = '' ) {
2554 $text = self
::getGroupName( $group );
2556 $title = self
::getGroupPage( $group );
2558 $page = $title->getPrefixedText();
2559 return "[[$page|$text]]";
2566 * Increment the user's edit-count field.
2567 * Will have no effect for anonymous users.
2569 function incEditCount() {
2570 if( !$this->isAnon() ) {
2571 $dbw = wfGetDB( DB_MASTER
);
2572 $dbw->update( 'user',
2573 array( 'user_editcount=user_editcount+1' ),
2574 array( 'user_id' => $this->getId() ),
2577 // Lazy initialization check...
2578 if( $dbw->affectedRows() == 0 ) {
2579 // Pull from a slave to be less cruel to servers
2580 // Accuracy isn't the point anyway here
2581 $dbr = wfGetDB( DB_SLAVE
);
2582 $count = $dbr->selectField( 'revision',
2584 array( 'rev_user' => $this->getId() ),
2587 // Now here's a goddamn hack...
2588 if( $dbr !== $dbw ) {
2589 // If we actually have a slave server, the count is
2590 // at least one behind because the current transaction
2591 // has not been committed and replicated.
2594 // But if DB_SLAVE is selecting the master, then the
2595 // count we just read includes the revision that was
2596 // just added in the working transaction.
2599 $dbw->update( 'user',
2600 array( 'user_editcount' => $count ),
2601 array( 'user_id' => $this->getId() ),
2605 // edit count in user cache too
2606 $this->invalidateCache();