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);
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 * Is the input a valid username?
372 * Checks if the input is a valid username, we don't want an empty string,
373 * an IP address, anything that containins slashes (would mess up subpages),
374 * is longer than the maximum allowed username size or doesn't begin with
377 * @param string $name
381 static function isValidUserName( $name ) {
382 global $wgContLang, $wgMaxNameChars;
385 || User
::isIP( $name )
386 ||
strpos( $name, '/' ) !== false
387 ||
strlen( $name ) > $wgMaxNameChars
388 ||
$name != $wgContLang->ucfirst( $name ) )
391 // Ensure that the name can't be misresolved as a different title,
392 // such as with extra namespace keys at the start.
393 $parsed = Title
::newFromText( $name );
394 if( is_null( $parsed )
395 ||
$parsed->getNamespace()
396 ||
strcmp( $name, $parsed->getPrefixedText() ) )
399 // Check an additional blacklist of troublemaker characters.
400 // Should these be merged into the title char list?
401 $unicodeBlacklist = '/[' .
402 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
403 '\x{00a0}' . # non-breaking space
404 '\x{2000}-\x{200f}' . # various whitespace
405 '\x{2028}-\x{202f}' . # breaks and control chars
406 '\x{3000}' . # ideographic space
407 '\x{e000}-\x{f8ff}' . # private use
409 if( preg_match( $unicodeBlacklist, $name ) ) {
417 * Usernames which fail to pass this function will be blocked
418 * from user login and new account registrations, but may be used
419 * internally by batch processes.
421 * If an account already exists in this form, login will be blocked
422 * by a failure to pass this function.
424 * @param string $name
427 static function isUsableName( $name ) {
428 global $wgReservedUsernames;
430 // Must be a usable username, obviously ;)
431 self
::isValidUserName( $name ) &&
433 // Certain names may be reserved for batch processes.
434 !in_array( $name, $wgReservedUsernames );
438 * Usernames which fail to pass this function will be blocked
439 * from new account registrations, but may be used internally
440 * either by batch processes or by user accounts which have
441 * already been created.
443 * Additional character blacklisting may be added here
444 * rather than in isValidUserName() to avoid disrupting
447 * @param string $name
450 static function isCreatableName( $name ) {
452 self
::isUsableName( $name ) &&
454 // Registration-time character blacklisting...
455 strpos( $name, '@' ) === false;
459 * Is the input a valid password?
461 * @param string $password
465 static function isValidPassword( $password ) {
466 global $wgMinimalPasswordLength;
467 return strlen( $password ) >= $wgMinimalPasswordLength;
471 * Does the string match roughly an email address ?
473 * There used to be a regular expression here, it got removed because it
474 * rejected valid addresses. Actually just check if there is '@' somewhere
475 * in the given address.
477 * @todo Check for RFC 2822 compilance
480 * @param string $addr email address
484 static function isValidEmailAddr ( $addr ) {
485 return ( trim( $addr ) != '' ) &&
486 (false !== strpos( $addr, '@' ) );
490 * Given unvalidated user input, return a canonical username, or false if
491 * the username is invalid.
492 * @param string $name
493 * @param mixed $validate Type of validation to use:
494 * false No validation
495 * 'valid' Valid for batch processes
496 * 'usable' Valid for batch processes and login
497 * 'creatable' Valid for batch processes, login and account creation
499 static function getCanonicalName( $name, $validate = 'valid' ) {
500 # Force usernames to capital
502 $name = $wgContLang->ucfirst( $name );
504 # Clean up name according to title rules
505 $t = Title
::newFromText( $name );
506 if( is_null( $t ) ) {
510 # Reject various classes of invalid names
511 $name = $t->getText();
513 $name = $wgAuth->getCanonicalName( $t->getText() );
515 switch ( $validate ) {
519 if ( !User
::isValidUserName( $name ) ) {
524 if ( !User
::isUsableName( $name ) ) {
529 if ( !User
::isCreatableName( $name ) ) {
534 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
540 * Count the number of edits of a user
542 * It should not be static and some day should be merged as proper member function / deprecated -- domas
544 * @param int $uid The user ID to check
548 static function edits( $uid ) {
549 wfProfileIn( __METHOD__
);
550 $dbr = wfGetDB( DB_SLAVE
);
551 // check if the user_editcount field has been initialized
552 $field = $dbr->selectField(
553 'user', 'user_editcount',
554 array( 'user_id' => $uid ),
558 if( $field === null ) { // it has not been initialized. do so.
559 $dbw = wfGetDb( DB_MASTER
);
560 $count = $dbr->selectField(
561 'revision', 'count(*)',
562 array( 'rev_user' => $uid ),
567 array( 'user_editcount' => $count ),
568 array( 'user_id' => $uid ),
574 wfProfileOut( __METHOD__
);
579 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
580 * @todo: hash random numbers to improve security, like generateToken()
585 static function randomPassword() {
586 global $wgMinimalPasswordLength;
587 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
588 $l = strlen( $pwchars ) - 1;
590 $pwlength = max( 7, $wgMinimalPasswordLength );
591 $digit = mt_rand(0, $pwlength - 1);
593 for ( $i = 0; $i < $pwlength; $i++
) {
594 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
600 * Set cached properties to default. Note: this no longer clears
601 * uncached lazy-initialised properties. The constructor does that instead.
605 function loadDefaults( $name = false ) {
606 wfProfileIn( __METHOD__
);
608 global $wgCookiePrefix;
611 $this->mName
= $name;
612 $this->mRealName
= '';
613 $this->mPassword
= $this->mNewpassword
= '';
614 $this->mNewpassTime
= null;
616 $this->mOptions
= null; # Defer init
618 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
619 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
621 $this->mTouched
= '0'; # Allow any pages to be cached
624 $this->setToken(); # Random
625 $this->mEmailAuthenticated
= null;
626 $this->mEmailToken
= '';
627 $this->mEmailTokenExpires
= null;
628 $this->mRegistration
= wfTimestamp( TS_MW
);
629 $this->mGroups
= array();
631 wfProfileOut( __METHOD__
);
635 * Initialise php session
636 * @deprecated use wfSetupSession()
638 function SetupSession() {
643 * Load user data from the session or login cookie. If there are no valid
644 * credentials, initialises the user as an anon.
645 * @return true if the user is logged in, false otherwise
649 function loadFromSession() {
650 global $wgMemc, $wgCookiePrefix;
652 if ( isset( $_SESSION['wsUserID'] ) ) {
653 if ( 0 != $_SESSION['wsUserID'] ) {
654 $sId = $_SESSION['wsUserID'];
656 $this->loadDefaults();
659 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
660 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
661 $_SESSION['wsUserID'] = $sId;
663 $this->loadDefaults();
666 if ( isset( $_SESSION['wsUserName'] ) ) {
667 $sName = $_SESSION['wsUserName'];
668 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
669 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
670 $_SESSION['wsUserName'] = $sName;
672 $this->loadDefaults();
676 $passwordCorrect = FALSE;
678 if ( !$this->loadFromId() ) {
679 # Not a valid ID, loadFromId has switched the object to anon for us
683 if ( isset( $_SESSION['wsToken'] ) ) {
684 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
686 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
687 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
690 # No session or persistent login cookie
691 $this->loadDefaults();
695 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
696 wfDebug( "Logged in from $from\n" );
699 # Invalid credentials
700 wfDebug( "Can't log in from $from, invalid credentials\n" );
701 $this->loadDefaults();
707 * Load user and user_group data from the database
708 * $this->mId must be set, this is how the user is identified.
710 * @return true if the user exists, false if the user is anonymous
713 function loadFromDatabase() {
715 $this->mId
= intval( $this->mId
);
717 /** Anonymous user */
719 $this->loadDefaults();
723 $dbr = wfGetDB( DB_MASTER
);
724 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
726 if ( $s !== false ) {
727 # Initialise user table data
728 $this->mName
= $s->user_name
;
729 $this->mRealName
= $s->user_real_name
;
730 $this->mPassword
= $s->user_password
;
731 $this->mNewpassword
= $s->user_newpassword
;
732 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $s->user_newpass_time
);
733 $this->mEmail
= $s->user_email
;
734 $this->decodeOptions( $s->user_options
);
735 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
736 $this->mToken
= $s->user_token
;
737 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
738 $this->mEmailToken
= $s->user_email_token
;
739 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $s->user_email_token_expires
);
740 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $s->user_registration
);
741 $this->mEditCount
= $s->user_editcount
;
742 $this->getEditCount(); // revalidation for nulls
745 $res = $dbr->select( 'user_groups',
747 array( 'ug_user' => $this->mId
),
749 $this->mGroups
= array();
750 while( $row = $dbr->fetchObject( $res ) ) {
751 $this->mGroups
[] = $row->ug_group
;
757 $this->loadDefaults();
763 * Clear various cached data stored in this object.
764 * @param string $reloadFrom Reload user and user_groups table data from a
765 * given source. May be "name", "id", "defaults", "session" or false for
768 function clearInstanceCache( $reloadFrom = false ) {
769 $this->mNewtalk
= -1;
770 $this->mDatePreference
= null;
771 $this->mBlockedby
= -1; # Unset
772 $this->mHash
= false;
774 $this->mRights
= null;
775 $this->mEffectiveGroups
= null;
778 $this->mDataLoaded
= false;
779 $this->mFrom
= $reloadFrom;
784 * Combine the language default options with any site-specific options
785 * and add the default language variants.
786 * Not really private cause it's called by Language class
791 static function getDefaultOptions() {
792 global $wgNamespacesToBeSearchedDefault;
794 * Site defaults will override the global/language defaults
796 global $wgDefaultUserOptions, $wgContLang;
797 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
800 * default language setting
802 $variant = $wgContLang->getPreferredVariant( false );
803 $defOpt['variant'] = $variant;
804 $defOpt['language'] = $variant;
806 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
807 $defOpt['searchNs'.$nsnum] = $val;
813 * Get a given default option value.
820 function getDefaultOption( $opt ) {
821 $defOpts = User
::getDefaultOptions();
822 if( isset( $defOpts[$opt] ) ) {
823 return $defOpts[$opt];
830 * Get a list of user toggle names
833 static function getToggles() {
835 $extraToggles = array();
836 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
837 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
842 * Get blocking information
844 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
845 * non-critical checks are done against slaves. Check when actually saving should be done against
848 function getBlockedStatus( $bFromSlave = true ) {
849 global $wgEnableSorbs, $wgProxyWhitelist;
851 if ( -1 != $this->mBlockedby
) {
852 wfDebug( "User::getBlockedStatus: already loaded.\n" );
856 wfProfileIn( __METHOD__
);
857 wfDebug( __METHOD__
.": checking...\n" );
859 $this->mBlockedby
= 0;
862 if ($this->isAllowed( 'ipblock-exempt' ) ) {
863 # Exempt from all types of IP-block
868 $this->mBlock
= new Block();
869 $this->mBlock
->fromMaster( !$bFromSlave );
870 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
871 wfDebug( __METHOD__
.": Found block.\n" );
872 $this->mBlockedby
= $this->mBlock
->mBy
;
873 $this->mBlockreason
= $this->mBlock
->mReason
;
874 if ( $this->isLoggedIn() ) {
875 $this->spreadBlock();
878 $this->mBlock
= null;
879 wfDebug( __METHOD__
.": No block.\n" );
883 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
886 if ( wfIsLocallyBlockedProxy( $ip ) ) {
887 $this->mBlockedby
= wfMsg( 'proxyblocker' );
888 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
892 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
893 if ( $this->inSorbsBlacklist( $ip ) ) {
894 $this->mBlockedby
= wfMsg( 'sorbs' );
895 $this->mBlockreason
= wfMsg( 'sorbsreason' );
901 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
903 wfProfileOut( __METHOD__
);
906 function inSorbsBlacklist( $ip ) {
907 global $wgEnableSorbs, $wgSorbsUrl;
909 return $wgEnableSorbs &&
910 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
913 function inDnsBlacklist( $ip, $base ) {
914 wfProfileIn( __METHOD__
);
920 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
922 for ( $i=4; $i>=1; $i-- ) {
923 $host .= $m[$i] . '.';
928 $ipList = gethostbynamel( $host );
931 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
934 wfDebug( "Requested $host, not found in $base.\n" );
938 wfProfileOut( __METHOD__
);
943 * Primitive rate limits: enforce maximum actions per time period
944 * to put a brake on flooding.
946 * Note: when using a shared cache like memcached, IP-address
947 * last-hit counters will be shared across wikis.
949 * @return bool true if a rate limiter was tripped
952 function pingLimiter( $action='edit' ) {
954 # Call the 'PingLimiter' hook
956 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
960 global $wgRateLimits, $wgRateLimitsExcludedGroups;
961 if( !isset( $wgRateLimits[$action] ) ) {
965 # Some groups shouldn't trigger the ping limiter, ever
966 foreach( $this->getGroups() as $group ) {
967 if( array_search( $group, $wgRateLimitsExcludedGroups ) !== false )
971 global $wgMemc, $wgRateLimitLog;
972 wfProfileIn( __METHOD__
);
974 $limits = $wgRateLimits[$action];
976 $id = $this->getId();
979 if( isset( $limits['anon'] ) && $id == 0 ) {
980 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
983 if( isset( $limits['user'] ) && $id != 0 ) {
984 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
986 if( $this->isNewbie() ) {
987 if( isset( $limits['newbie'] ) && $id != 0 ) {
988 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
990 if( isset( $limits['ip'] ) ) {
991 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
994 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
995 $subnet = $matches[1];
996 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1001 foreach( $keys as $key => $limit ) {
1002 list( $max, $period ) = $limit;
1003 $summary = "(limit $max in {$period}s)";
1004 $count = $wgMemc->get( $key );
1006 if( $count > $max ) {
1007 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1008 if( $wgRateLimitLog ) {
1009 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1013 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1016 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1017 $wgMemc->add( $key, 1, intval( $period ) );
1019 $wgMemc->incr( $key );
1022 wfProfileOut( __METHOD__
);
1027 * Check if user is blocked
1028 * @return bool True if blocked, false otherwise
1030 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1031 wfDebug( "User::isBlocked: enter\n" );
1032 $this->getBlockedStatus( $bFromSlave );
1033 return $this->mBlockedby
!== 0;
1037 * Check if user is blocked from editing a particular article
1039 function isBlockedFrom( $title, $bFromSlave = false ) {
1040 global $wgBlockAllowsUTEdit;
1041 wfProfileIn( __METHOD__
);
1042 wfDebug( __METHOD__
.": enter\n" );
1044 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1045 $title->getNamespace() == NS_USER_TALK
)
1048 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1050 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1051 $blocked = $this->isBlocked( $bFromSlave );
1053 wfProfileOut( __METHOD__
);
1058 * Get name of blocker
1059 * @return string name of blocker
1061 function blockedBy() {
1062 $this->getBlockedStatus();
1063 return $this->mBlockedby
;
1067 * Get blocking reason
1068 * @return string Blocking reason
1070 function blockedFor() {
1071 $this->getBlockedStatus();
1072 return $this->mBlockreason
;
1076 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1084 * Set the user and reload all fields according to that ID
1085 * @deprecated use User::newFromId()
1087 function setID( $v ) {
1089 $this->clearInstanceCache( 'id' );
1093 * Get the user name, or the IP for anons
1095 function getName() {
1096 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1097 # Special case optimisation
1098 return $this->mName
;
1101 if ( $this->mName
=== false ) {
1102 $this->mName
= wfGetIP();
1104 return $this->mName
;
1109 * Set the user name.
1111 * This does not reload fields from the database according to the given
1112 * name. Rather, it is used to create a temporary "nonexistent user" for
1113 * later addition to the database. It can also be used to set the IP
1114 * address for an anonymous user to something other than the current
1117 * User::newFromName() has rougly the same function, when the named user
1120 function setName( $str ) {
1122 $this->mName
= $str;
1126 * Return the title dbkey form of the name, for eg user pages.
1130 function getTitleKey() {
1131 return str_replace( ' ', '_', $this->getName() );
1134 function getNewtalk() {
1137 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1138 if( $this->mNewtalk
=== -1 ) {
1139 $this->mNewtalk
= false; # reset talk page status
1141 # Check memcached separately for anons, who have no
1142 # entire User object stored in there.
1145 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1146 $newtalk = $wgMemc->get( $key );
1147 if( $newtalk != "" ) {
1148 $this->mNewtalk
= (bool)$newtalk;
1150 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
1151 $wgMemc->set( $key, (int)$this->mNewtalk
, time() +
1800 );
1154 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1158 return (bool)$this->mNewtalk
;
1162 * Return the talk page(s) this user has new messages on.
1164 function getNewMessageLinks() {
1166 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1169 if (!$this->getNewtalk())
1171 $up = $this->getUserPage();
1172 $utp = $up->getTalkPage();
1173 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1178 * Perform a user_newtalk check on current slaves; if the memcached data
1179 * is funky we don't want newtalk state to get stuck on save, as that's
1182 * @param string $field
1187 function checkNewtalk( $field, $id ) {
1188 $dbr = wfGetDB( DB_SLAVE
);
1189 $ok = $dbr->selectField( 'user_newtalk', $field,
1190 array( $field => $id ), __METHOD__
);
1191 return $ok !== false;
1196 * @param string $field
1200 function updateNewtalk( $field, $id ) {
1201 if( $this->checkNewtalk( $field, $id ) ) {
1202 wfDebug( __METHOD__
." already set ($field, $id), ignoring\n" );
1205 $dbw = wfGetDB( DB_MASTER
);
1206 $dbw->insert( 'user_newtalk',
1207 array( $field => $id ),
1210 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1215 * Clear the new messages flag for the given user
1216 * @param string $field
1220 function deleteNewtalk( $field, $id ) {
1221 if( !$this->checkNewtalk( $field, $id ) ) {
1222 wfDebug( __METHOD__
.": already gone ($field, $id), ignoring\n" );
1225 $dbw = wfGetDB( DB_MASTER
);
1226 $dbw->delete( 'user_newtalk',
1227 array( $field => $id ),
1229 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1234 * Update the 'You have new messages!' status.
1237 function setNewtalk( $val ) {
1238 if( wfReadOnly() ) {
1243 $this->mNewtalk
= $val;
1245 if( $this->isAnon() ) {
1247 $id = $this->getName();
1250 $id = $this->getId();
1254 $changed = $this->updateNewtalk( $field, $id );
1256 $changed = $this->deleteNewtalk( $field, $id );
1260 if( $this->isAnon() ) {
1261 // Anons have a separate memcached space, since
1262 // user records aren't kept for them.
1264 $key = wfMemcKey( 'newtalk', 'ip', $val );
1265 $wgMemc->set( $key, $val ?
1 : 0 );
1268 // Make sure the user page is watched, so a notification
1269 // will be sent out if enabled.
1270 $this->addWatch( $this->getTalkPage() );
1273 $this->invalidateCache();
1278 * Generate a current or new-future timestamp to be stored in the
1279 * user_touched field when we update things.
1281 private static function newTouchedTimestamp() {
1282 global $wgClockSkewFudge;
1283 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1287 * Clear user data from memcached.
1288 * Use after applying fun updates to the database; caller's
1289 * responsibility to update user_touched if appropriate.
1291 * Called implicitly from invalidateCache() and saveSettings().
1293 private function clearSharedCache() {
1296 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1301 * Immediately touch the user data cache for this account.
1302 * Updates user_touched field, and removes account data from memcached
1303 * for reload on the next hit.
1305 function invalidateCache() {
1308 $this->mTouched
= self
::newTouchedTimestamp();
1310 $dbw = wfGetDB( DB_MASTER
);
1311 $dbw->update( 'user',
1312 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1313 array( 'user_id' => $this->mId
),
1316 $this->clearSharedCache();
1320 function validateCache( $timestamp ) {
1322 return ($timestamp >= $this->mTouched
);
1326 * Encrypt a password.
1327 * It can eventuall salt a password @see User::addSalt()
1328 * @param string $p clear Password.
1329 * @return string Encrypted password.
1331 function encryptPassword( $p ) {
1333 return wfEncryptPassword( $this->mId
, $p );
1337 * Set the password and reset the random token
1338 * Calls through to authentication plugin if necessary;
1339 * will have no effect if the auth plugin refuses to
1340 * pass the change through or if the legal password
1343 * As a special case, setting the password to null
1344 * wipes it, so the account cannot be logged in until
1345 * a new password is set, for instance via e-mail.
1347 * @param string $str
1348 * @throws PasswordError on failure
1350 function setPassword( $str ) {
1353 if( $str !== null ) {
1354 if( !$wgAuth->allowPasswordChange() ) {
1355 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1358 if( !$this->isValidPassword( $str ) ) {
1359 global $wgMinimalPasswordLength;
1360 throw new PasswordError( wfMsg( 'passwordtooshort',
1361 $wgMinimalPasswordLength ) );
1365 if( !$wgAuth->setPassword( $this, $str ) ) {
1366 throw new PasswordError( wfMsg( 'externaldberror' ) );
1372 if( $str === null ) {
1373 // Save an invalid hash...
1374 $this->mPassword
= '';
1376 $this->mPassword
= $this->encryptPassword( $str );
1378 $this->mNewpassword
= '';
1379 $this->mNewpassTime
= null;
1385 * Set the random token (used for persistent authentication)
1386 * Called from loadDefaults() among other places.
1389 function setToken( $token = false ) {
1390 global $wgSecretKey, $wgProxyKey;
1393 if ( $wgSecretKey ) {
1394 $key = $wgSecretKey;
1395 } elseif ( $wgProxyKey ) {
1400 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1402 $this->mToken
= $token;
1406 function setCookiePassword( $str ) {
1408 $this->mCookiePassword
= md5( $str );
1412 * Set the password for a password reminder or new account email
1413 * Sets the user_newpass_time field if $throttle is true
1415 function setNewpassword( $str, $throttle = true ) {
1417 $this->mNewpassword
= $this->encryptPassword( $str );
1419 $this->mNewpassTime
= wfTimestampNow();
1424 * Returns true if a password reminder email has already been sent within
1425 * the last $wgPasswordReminderResendTime hours
1427 function isPasswordReminderThrottled() {
1428 global $wgPasswordReminderResendTime;
1430 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1433 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1434 return time() < $expiry;
1437 function getEmail() {
1439 return $this->mEmail
;
1442 function getEmailAuthenticationTimestamp() {
1444 return $this->mEmailAuthenticated
;
1447 function setEmail( $str ) {
1449 $this->mEmail
= $str;
1452 function getRealName() {
1454 return $this->mRealName
;
1457 function setRealName( $str ) {
1459 $this->mRealName
= $str;
1463 * @param string $oname The option to check
1464 * @param string $defaultOverride A default value returned if the option does not exist
1467 function getOption( $oname, $defaultOverride = '' ) {
1470 if ( is_null( $this->mOptions
) ) {
1471 if($defaultOverride != '') {
1472 return $defaultOverride;
1474 $this->mOptions
= User
::getDefaultOptions();
1477 if ( array_key_exists( $oname, $this->mOptions
) ) {
1478 return trim( $this->mOptions
[$oname] );
1480 return $defaultOverride;
1485 * Get the user's date preference, including some important migration for
1488 function getDatePreference() {
1489 if ( is_null( $this->mDatePreference
) ) {
1491 $value = $this->getOption( 'date' );
1492 $map = $wgLang->getDatePreferenceMigrationMap();
1493 if ( isset( $map[$value] ) ) {
1494 $value = $map[$value];
1496 $this->mDatePreference
= $value;
1498 return $this->mDatePreference
;
1502 * @param string $oname The option to check
1503 * @return bool False if the option is not selected, true if it is
1505 function getBoolOption( $oname ) {
1506 return (bool)$this->getOption( $oname );
1510 * Get an option as an integer value from the source string.
1511 * @param string $oname The option to check
1512 * @param int $default Optional value to return if option is unset/blank.
1515 function getIntOption( $oname, $default=0 ) {
1516 $val = $this->getOption( $oname );
1520 return intval( $val );
1523 function setOption( $oname, $val ) {
1525 if ( is_null( $this->mOptions
) ) {
1526 $this->mOptions
= User
::getDefaultOptions();
1528 if ( $oname == 'skin' ) {
1529 # Clear cached skin, so the new one displays immediately in Special:Preferences
1530 unset( $this->mSkin
);
1532 // Filter out any newlines that may have passed through input validation.
1533 // Newlines are used to separate items in the options blob.
1534 $val = str_replace( "\r\n", "\n", $val );
1535 $val = str_replace( "\r", "\n", $val );
1536 $val = str_replace( "\n", " ", $val );
1537 $this->mOptions
[$oname] = $val;
1540 function getRights() {
1541 if ( is_null( $this->mRights
) ) {
1542 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1544 return $this->mRights
;
1548 * Get the list of explicit group memberships this user has.
1549 * The implicit * and user groups are not included.
1550 * @return array of strings
1552 function getGroups() {
1554 return $this->mGroups
;
1558 * Get the list of implicit group memberships this user has.
1559 * This includes all explicit groups, plus 'user' if logged in
1560 * and '*' for all accounts.
1561 * @param boolean $recache Don't use the cache
1562 * @return array of strings
1564 function getEffectiveGroups( $recache = false ) {
1565 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1567 $this->mEffectiveGroups
= $this->mGroups
;
1568 $this->mEffectiveGroups
[] = '*';
1570 $this->mEffectiveGroups
[] = 'user';
1572 global $wgAutoConfirmAge, $wgAutoConfirmCount;
1574 $accountAge = time() - wfTimestampOrNull( TS_UNIX
, $this->mRegistration
);
1575 if( $accountAge >= $wgAutoConfirmAge && $this->getEditCount() >= $wgAutoConfirmCount ) {
1576 $this->mEffectiveGroups
[] = 'autoconfirmed';
1578 # Implicit group for users whose email addresses are confirmed
1579 global $wgEmailAuthentication;
1580 if( self
::isValidEmailAddr( $this->mEmail
) ) {
1581 if( $wgEmailAuthentication ) {
1582 if( $this->mEmailAuthenticated
)
1583 $this->mEffectiveGroups
[] = 'emailconfirmed';
1585 $this->mEffectiveGroups
[] = 'emailconfirmed';
1590 return $this->mEffectiveGroups
;
1593 /* Return the edit count for the user. This is where User::edits should have been */
1594 function getEditCount() {
1596 if ( !isset( $this->mEditCount
) ) {
1597 /* Populate the count, if it has not been populated yet */
1598 $this->mEditCount
= User
::edits($this->mId
);
1600 return $this->mEditCount
;
1608 * Add the user to the given group.
1609 * This takes immediate effect.
1612 function addGroup( $group ) {
1614 $dbw = wfGetDB( DB_MASTER
);
1615 if( $this->getId() ) {
1616 $dbw->insert( 'user_groups',
1618 'ug_user' => $this->getID(),
1619 'ug_group' => $group,
1622 array( 'IGNORE' ) );
1625 $this->mGroups
[] = $group;
1626 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1628 $this->invalidateCache();
1632 * Remove the user from the given group.
1633 * This takes immediate effect.
1636 function removeGroup( $group ) {
1638 $dbw = wfGetDB( DB_MASTER
);
1639 $dbw->delete( 'user_groups',
1641 'ug_user' => $this->getID(),
1642 'ug_group' => $group,
1644 'User::removeGroup' );
1646 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1647 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1649 $this->invalidateCache();
1654 * A more legible check for non-anonymousness.
1655 * Returns true if the user is not an anonymous visitor.
1659 function isLoggedIn() {
1660 return( $this->getID() != 0 );
1664 * A more legible check for anonymousness.
1665 * Returns true if the user is an anonymous visitor.
1670 return !$this->isLoggedIn();
1674 * Whether the user is a bot
1678 return $this->isAllowed( 'bot' );
1682 * Check if user is allowed to access a feature / make an action
1683 * @param string $action Action to be checked
1684 * @return boolean True: action is allowed, False: action should not be allowed
1686 function isAllowed($action='') {
1687 if ( $action === '' )
1688 // In the spirit of DWIM
1691 return in_array( $action, $this->getRights() );
1695 * Load a skin if it doesn't exist or return it
1696 * @todo FIXME : need to check the old failback system [AV]
1698 function &getSkin() {
1700 if ( ! isset( $this->mSkin
) ) {
1701 wfProfileIn( __METHOD__
);
1704 $userSkin = $this->getOption( 'skin' );
1705 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1707 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1708 wfProfileOut( __METHOD__
);
1710 return $this->mSkin
;
1714 * @param string $title Article title to look at
1718 * Check watched status of an article
1719 * @return bool True if article is watched
1721 function isWatched( $title ) {
1722 $wl = WatchedItem
::fromUserTitle( $this, $title );
1723 return $wl->isWatched();
1729 function addWatch( $title ) {
1730 $wl = WatchedItem
::fromUserTitle( $this, $title );
1732 $this->invalidateCache();
1736 * Stop watching an article
1738 function removeWatch( $title ) {
1739 $wl = WatchedItem
::fromUserTitle( $this, $title );
1741 $this->invalidateCache();
1745 * Clear the user's notification timestamp for the given title.
1746 * If e-notif e-mails are on, they will receive notification mails on
1747 * the next change of the page if it's watched etc.
1749 function clearNotification( &$title ) {
1750 global $wgUser, $wgUseEnotif;
1752 # Do nothing if the database is locked to writes
1753 if( wfReadOnly() ) {
1757 if ($title->getNamespace() == NS_USER_TALK
&&
1758 $title->getText() == $this->getName() ) {
1759 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1761 $this->setNewtalk( false );
1764 if( !$wgUseEnotif ) {
1768 if( $this->isAnon() ) {
1769 // Nothing else to do...
1773 // Only update the timestamp if the page is being watched.
1774 // The query to find out if it is watched is cached both in memcached and per-invocation,
1775 // and when it does have to be executed, it can be on a slave
1776 // If this is the user's newtalk page, we always update the timestamp
1777 if ($title->getNamespace() == NS_USER_TALK
&&
1778 $title->getText() == $wgUser->getName())
1781 } elseif ( $this->getID() == $wgUser->getID() ) {
1782 $watched = $title->userIsWatching();
1787 // If the page is watched by the user (or may be watched), update the timestamp on any
1788 // any matching rows
1790 $dbw = wfGetDB( DB_MASTER
);
1791 $dbw->update( 'watchlist',
1793 'wl_notificationtimestamp' => NULL
1794 ), array( /* WHERE */
1795 'wl_title' => $title->getDBkey(),
1796 'wl_namespace' => $title->getNamespace(),
1797 'wl_user' => $this->getID()
1798 ), 'User::clearLastVisited'
1806 * Resets all of the given user's page-change notification timestamps.
1807 * If e-notif e-mails are on, they will receive notification mails on
1808 * the next change of any watched page.
1810 * @param int $currentUser user ID number
1813 function clearAllNotifications( $currentUser ) {
1814 global $wgUseEnotif;
1815 if ( !$wgUseEnotif ) {
1816 $this->setNewtalk( false );
1819 if( $currentUser != 0 ) {
1821 $dbw = wfGetDB( DB_MASTER
);
1822 $dbw->update( 'watchlist',
1824 'wl_notificationtimestamp' => NULL
1825 ), array( /* WHERE */
1826 'wl_user' => $currentUser
1827 ), 'UserMailer::clearAll'
1830 # we also need to clear here the "you have new message" notification for the own user_talk page
1831 # This is cleared one page view later in Article::viewUpdates();
1837 * @return string Encoding options
1839 function encodeOptions() {
1841 if ( is_null( $this->mOptions
) ) {
1842 $this->mOptions
= User
::getDefaultOptions();
1845 foreach ( $this->mOptions
as $oname => $oval ) {
1846 array_push( $a, $oname.'='.$oval );
1848 $s = implode( "\n", $a );
1855 function decodeOptions( $str ) {
1856 $this->mOptions
= array();
1857 $a = explode( "\n", $str );
1858 foreach ( $a as $s ) {
1860 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1861 $this->mOptions
[$m[1]] = $m[2];
1866 function setCookies() {
1867 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1869 if ( 0 == $this->mId
) return;
1870 $exp = time() +
$wgCookieExpiration;
1872 $_SESSION['wsUserID'] = $this->mId
;
1873 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1875 $_SESSION['wsUserName'] = $this->getName();
1876 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1878 $_SESSION['wsToken'] = $this->mToken
;
1879 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1880 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1882 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1888 * Clears the cookies and session, resets the instance cache
1891 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1892 $this->clearInstanceCache( 'defaults' );
1894 $_SESSION['wsUserID'] = 0;
1896 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1897 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1899 # Remember when user logged out, to prevent seeing cached pages
1900 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1904 * Save object settings into database
1905 * @fixme Only rarely do all these fields need to be set!
1907 function saveSettings() {
1909 if ( wfReadOnly() ) { return; }
1910 if ( 0 == $this->mId
) { return; }
1912 $this->mTouched
= self
::newTouchedTimestamp();
1914 $dbw = wfGetDB( DB_MASTER
);
1915 $dbw->update( 'user',
1917 'user_name' => $this->mName
,
1918 'user_password' => $this->mPassword
,
1919 'user_newpassword' => $this->mNewpassword
,
1920 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
1921 'user_real_name' => $this->mRealName
,
1922 'user_email' => $this->mEmail
,
1923 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1924 'user_options' => $this->encodeOptions(),
1925 'user_touched' => $dbw->timestamp($this->mTouched
),
1926 'user_token' => $this->mToken
1927 ), array( /* WHERE */
1928 'user_id' => $this->mId
1931 $this->clearSharedCache();
1936 * Checks if a user with the given name exists, returns the ID
1938 function idForName() {
1939 $s = trim( $this->getName() );
1940 if ( 0 == strcmp( '', $s ) ) return 0;
1942 $dbr = wfGetDB( DB_SLAVE
);
1943 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
1944 if ( $id === false ) {
1951 * Add a user to the database, return the user object
1953 * @param string $name The user's name
1954 * @param array $params Associative array of non-default parameters to save to the database:
1955 * password The user's password. Password logins will be disabled if this is omitted.
1956 * newpassword A temporary password mailed to the user
1957 * email The user's email address
1958 * email_authenticated The email authentication timestamp
1959 * real_name The user's real name
1960 * options An associative array of non-default options
1961 * token Random authentication token. Do not set.
1962 * registration Registration timestamp. Do not set.
1964 * @return User object, or null if the username already exists
1966 static function createNew( $name, $params = array() ) {
1969 if ( isset( $params['options'] ) ) {
1970 $user->mOptions
= $params['options'] +
$user->mOptions
;
1971 unset( $params['options'] );
1973 $dbw = wfGetDB( DB_MASTER
);
1974 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1976 'user_id' => $seqVal,
1977 'user_name' => $name,
1978 'user_password' => $user->mPassword
,
1979 'user_newpassword' => $user->mNewpassword
,
1980 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
1981 'user_email' => $user->mEmail
,
1982 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
1983 'user_real_name' => $user->mRealName
,
1984 'user_options' => $user->encodeOptions(),
1985 'user_token' => $user->mToken
,
1986 'user_registration' => $dbw->timestamp( $user->mRegistration
),
1987 'user_editcount' => 0,
1989 foreach ( $params as $name => $value ) {
1990 $fields["user_$name"] = $value;
1992 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
1993 if ( $dbw->affectedRows() ) {
1994 $newUser = User
::newFromId( $dbw->insertId() );
2002 * Add an existing user object to the database
2004 function addToDatabase() {
2006 $dbw = wfGetDB( DB_MASTER
);
2007 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2008 $dbw->insert( 'user',
2010 'user_id' => $seqVal,
2011 'user_name' => $this->mName
,
2012 'user_password' => $this->mPassword
,
2013 'user_newpassword' => $this->mNewpassword
,
2014 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2015 'user_email' => $this->mEmail
,
2016 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2017 'user_real_name' => $this->mRealName
,
2018 'user_options' => $this->encodeOptions(),
2019 'user_token' => $this->mToken
,
2020 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2021 'user_editcount' => 0,
2024 $this->mId
= $dbw->insertId();
2026 # Clear instance cache other than user table data, which is already accurate
2027 $this->clearInstanceCache();
2031 * If the (non-anonymous) user is blocked, this function will block any IP address
2032 * that they successfully log on from.
2034 function spreadBlock() {
2035 wfDebug( __METHOD__
."()\n" );
2037 if ( $this->mId
== 0 ) {
2041 $userblock = Block
::newFromDB( '', $this->mId
);
2042 if ( !$userblock ) {
2046 $userblock->doAutoblock( wfGetIp() );
2051 * Generate a string which will be different for any combination of
2052 * user options which would produce different parser output.
2053 * This will be used as part of the hash key for the parser cache,
2054 * so users will the same options can share the same cached data
2057 * Extensions which require it should install 'PageRenderingHash' hook,
2058 * which will give them a chance to modify this key based on their own
2063 function getPageRenderingHash() {
2064 global $wgContLang, $wgUseDynamicDates, $wgLang;
2066 return $this->mHash
;
2069 // stubthreshold is only included below for completeness,
2070 // it will always be 0 when this function is called by parsercache.
2072 $confstr = $this->getOption( 'math' );
2073 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2074 if ( $wgUseDynamicDates ) {
2075 $confstr .= '!' . $this->getDatePreference();
2077 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2078 $confstr .= '!' . $wgLang->getCode();
2079 $confstr .= '!' . $this->getOption( 'thumbsize' );
2080 // add in language specific options, if any
2081 $extra = $wgContLang->getExtraHashOptions();
2084 // Give a chance for extensions to modify the hash, if they have
2085 // extra options or other effects on the parser cache.
2086 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2088 $this->mHash
= $confstr;
2092 function isBlockedFromCreateAccount() {
2093 $this->getBlockedStatus();
2094 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2097 function isAllowedToCreateAccount() {
2098 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2104 function setLoaded( $loaded ) {}
2107 * Get this user's personal page title.
2112 function getUserPage() {
2113 return Title
::makeTitle( NS_USER
, $this->getName() );
2117 * Get this user's talk page title.
2122 function getTalkPage() {
2123 $title = $this->getUserPage();
2124 return $title->getTalkPage();
2130 function getMaxID() {
2131 static $res; // cache
2133 if ( isset( $res ) )
2136 $dbr = wfGetDB( DB_SLAVE
);
2137 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2142 * Determine whether the user is a newbie. Newbies are either
2143 * anonymous IPs, or the most recently created accounts.
2144 * @return bool True if it is a newbie.
2146 function isNewbie() {
2147 return !$this->isAllowed( 'autoconfirmed' );
2151 * Check to see if the given clear-text password is one of the accepted passwords
2152 * @param string $password User password.
2153 * @return bool True if the given password is correct otherwise False.
2155 function checkPassword( $password ) {
2159 // Even though we stop people from creating passwords that
2160 // are shorter than this, doesn't mean people wont be able
2161 // to. Certain authentication plugins do NOT want to save
2162 // domain passwords in a mysql database, so we should
2163 // check this (incase $wgAuth->strict() is false).
2164 if( !$this->isValidPassword( $password ) ) {
2168 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2170 } elseif( $wgAuth->strict() ) {
2171 /* Auth plugin doesn't allow local authentication */
2174 $ep = $this->encryptPassword( $password );
2175 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2177 } elseif ( function_exists( 'iconv' ) ) {
2178 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2179 # Check for this with iconv
2180 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2181 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2189 * Check if the given clear-text password matches the temporary password
2190 * sent by e-mail for password reset operations.
2193 function checkTemporaryPassword( $plaintext ) {
2194 $hash = $this->encryptPassword( $plaintext );
2195 return $hash === $this->mNewpassword
;
2199 * Initialize (if necessary) and return a session token value
2200 * which can be used in edit forms to show that the user's
2201 * login credentials aren't being hijacked with a foreign form
2204 * @param mixed $salt - Optional function-specific data for hash.
2205 * Use a string or an array of strings.
2209 function editToken( $salt = '' ) {
2210 if( !isset( $_SESSION['wsEditToken'] ) ) {
2211 $token = $this->generateToken();
2212 $_SESSION['wsEditToken'] = $token;
2214 $token = $_SESSION['wsEditToken'];
2216 if( is_array( $salt ) ) {
2217 $salt = implode( '|', $salt );
2219 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2223 * Generate a hex-y looking random token for various uses.
2224 * Could be made more cryptographically sure if someone cares.
2227 function generateToken( $salt = '' ) {
2228 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2229 return md5( $token . $salt );
2233 * Check given value against the token value stored in the session.
2234 * A match should confirm that the form was submitted from the
2235 * user's own login session, not a form submission from a third-party
2238 * @param string $val - the input value to compare
2239 * @param string $salt - Optional function-specific data for hash
2243 function matchEditToken( $val, $salt = '' ) {
2245 $sessionToken = $this->editToken( $salt );
2246 if ( $val != $sessionToken ) {
2247 wfDebug( "User::matchEditToken: broken session data\n" );
2249 return $val == $sessionToken;
2253 * Generate a new e-mail confirmation token and send a confirmation
2254 * mail to the user's given address.
2256 * @return mixed True on success, a WikiError object on failure.
2258 function sendConfirmationMail() {
2260 $expiration = null; // gets passed-by-ref and defined in next line.
2261 $url = $this->confirmationTokenUrl( $expiration );
2262 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2263 wfMsg( 'confirmemail_body',
2267 $wgContLang->timeanddate( $expiration, false ) ) );
2271 * Send an e-mail to this user's account. Does not check for
2272 * confirmed status or validity.
2274 * @param string $subject
2275 * @param string $body
2276 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2277 * @return mixed True on success, a WikiError object on failure.
2279 function sendMail( $subject, $body, $from = null ) {
2280 if( is_null( $from ) ) {
2281 global $wgPasswordSender;
2282 $from = $wgPasswordSender;
2285 require_once( 'UserMailer.php' );
2286 $to = new MailAddress( $this );
2287 $sender = new MailAddress( $from );
2288 $error = userMailer( $to, $sender, $subject, $body );
2290 if( $error == '' ) {
2293 return new WikiError( $error );
2298 * Generate, store, and return a new e-mail confirmation code.
2299 * A hash (unsalted since it's used as a key) is stored.
2300 * @param &$expiration mixed output: accepts the expiration time
2304 function confirmationToken( &$expiration ) {
2306 $expires = $now +
7 * 24 * 60 * 60;
2307 $expiration = wfTimestamp( TS_MW
, $expires );
2309 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2310 $hash = md5( $token );
2312 $dbw = wfGetDB( DB_MASTER
);
2313 $dbw->update( 'user',
2314 array( 'user_email_token' => $hash,
2315 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2316 array( 'user_id' => $this->mId
),
2323 * Generate and store a new e-mail confirmation token, and return
2324 * the URL the user can use to confirm.
2325 * @param &$expiration mixed output: accepts the expiration time
2329 function confirmationTokenUrl( &$expiration ) {
2330 $token = $this->confirmationToken( $expiration );
2331 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2332 return $title->getFullUrl();
2336 * Mark the e-mail address confirmed and save.
2338 function confirmEmail() {
2340 $this->mEmailAuthenticated
= wfTimestampNow();
2341 $this->saveSettings();
2346 * Is this user allowed to send e-mails within limits of current
2347 * site configuration?
2350 function canSendEmail() {
2351 return $this->isEmailConfirmed();
2355 * Is this user allowed to receive e-mails within limits of current
2356 * site configuration?
2359 function canReceiveEmail() {
2360 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2364 * Is this user's e-mail address valid-looking and confirmed within
2365 * limits of the current site configuration?
2367 * If $wgEmailAuthentication is on, this may require the user to have
2368 * confirmed their address by returning a code or using a password
2369 * sent to the address from the wiki.
2373 function isEmailConfirmed() {
2374 global $wgEmailAuthentication;
2377 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2378 if( $this->isAnon() )
2380 if( !self
::isValidEmailAddr( $this->mEmail
) )
2382 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2391 * Return true if there is an outstanding request for e-mail confirmation.
2394 function isEmailConfirmationPending() {
2395 global $wgEmailAuthentication;
2396 return $wgEmailAuthentication &&
2397 !$this->isEmailConfirmed() &&
2398 $this->mEmailToken
&&
2399 $this->mEmailTokenExpires
> wfTimestamp();
2403 * @param array $groups list of groups
2404 * @return array list of permission key names for given groups combined
2407 static function getGroupPermissions( $groups ) {
2408 global $wgGroupPermissions;
2410 foreach( $groups as $group ) {
2411 if( isset( $wgGroupPermissions[$group] ) ) {
2412 $rights = array_merge( $rights,
2413 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2420 * @param string $group key name
2421 * @return string localized descriptive name for group, if provided
2424 static function getGroupName( $group ) {
2425 $key = "group-$group";
2426 $name = wfMsg( $key );
2427 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2435 * @param string $group key name
2436 * @return string localized descriptive name for member of a group, if provided
2439 static function getGroupMember( $group ) {
2440 $key = "group-$group-member";
2441 $name = wfMsg( $key );
2442 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2450 * Return the set of defined explicit groups.
2451 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2452 * groups are not included, as they are defined
2453 * automatically, not in the database.
2457 static function getAllGroups() {
2458 global $wgGroupPermissions;
2460 array_keys( $wgGroupPermissions ),
2461 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2465 * Get the title of a page describing a particular group
2467 * @param $group Name of the group
2470 static function getGroupPage( $group ) {
2471 $page = wfMsgForContent( 'grouppage-' . $group );
2472 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2473 $title = Title
::newFromText( $page );
2474 if( is_object( $title ) )
2481 * Create a link to the group in HTML, if available
2483 * @param $group Name of the group
2484 * @param $text The text of the link
2487 static function makeGroupLinkHTML( $group, $text = '' ) {
2489 $text = self
::getGroupName( $group );
2491 $title = self
::getGroupPage( $group );
2494 $sk = $wgUser->getSkin();
2495 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2502 * Create a link to the group in Wikitext, if available
2504 * @param $group Name of the group
2505 * @param $text The text of the link (by default, the name of the group)
2508 static function makeGroupLinkWiki( $group, $text = '' ) {
2510 $text = self
::getGroupName( $group );
2512 $title = self
::getGroupPage( $group );
2514 $page = $title->getPrefixedText();
2515 return "[[$page|$text]]";
2522 * Increment the user's edit-count field.
2523 * Will have no effect for anonymous users.
2525 function incEditCount() {
2526 if( !$this->isAnon() ) {
2527 $dbw = wfGetDB( DB_MASTER
);
2528 $dbw->update( 'user',
2529 array( 'user_editcount=user_editcount+1' ),
2530 array( 'user_id' => $this->getId() ),
2533 // Lazy initialization check...
2534 if( $dbw->affectedRows() == 0 ) {
2535 // Pull from a slave to be less cruel to servers
2536 // Accuracy isn't the point anyway here
2537 $dbr = wfGetDB( DB_SLAVE
);
2538 $count = $dbr->selectField( 'revision',
2540 array( 'rev_user' => $this->getId() ),
2543 // Now here's a goddamn hack...
2544 if( $dbr !== $dbw ) {
2545 // If we actually have a slave server, the count is
2546 // at least one behind because the current transaction
2547 // has not been committed and replicated.
2550 // But if DB_SLAVE is selecting the master, then the
2551 // count we just read includes the revision that was
2552 // just added in the working transaction.
2555 $dbw->update( 'user',
2556 array( 'user_editcount' => $count ),
2557 array( 'user_id' => $this->getId() ),
2561 // edit count in user cache too
2562 $this->invalidateCache();