7 # Number of characters in user_token field
8 define( 'USER_TOKEN_LENGTH', 32 );
10 # Serialized record version
11 define( 'MW_USER_VERSION', 4 );
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 );
191 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
192 # Object is expired, load from DB
197 wfDebug( "Cache miss for user {$this->mId}\n" );
199 if ( !$this->loadFromDatabase() ) {
200 # Can't load from ID, user is anonymous
206 foreach ( self
::$mCacheVars as $name ) {
207 $data[$name] = $this->$name;
209 $data['mVersion'] = MW_USER_VERSION
;
210 $wgMemc->set( $key, $data );
212 wfDebug( "Got user {$this->mId} from cache\n" );
214 foreach ( self
::$mCacheVars as $name ) {
215 $this->$name = $data[$name];
222 * Static factory method for creation from username.
224 * This is slightly less efficient than newFromId(), so use newFromId() if
225 * you have both an ID and a name handy.
227 * @param string $name Username, validated by Title:newFromText()
228 * @param mixed $validate Validate username. Takes the same parameters as
229 * User::getCanonicalName(), except that true is accepted as an alias
230 * for 'valid', for BC.
232 * @return User object, or null if the username is invalid. If the username
233 * is not present in the database, the result will be a user object with
234 * a name, zero user ID and default settings.
237 static function newFromName( $name, $validate = 'valid' ) {
238 if ( $validate === true ) {
241 $name = self
::getCanonicalName( $name, $validate );
242 if ( $name === false ) {
245 # Create unloaded user object
253 static function newFromId( $id ) {
261 * Factory method to fetch whichever user has a given email confirmation code.
262 * This code is generated when an account is created or its e-mail address
265 * If the code is invalid or has expired, returns NULL.
267 * @param string $code
271 static function newFromConfirmationCode( $code ) {
272 $dbr =& wfGetDB( DB_SLAVE
);
273 $id = $dbr->selectField( 'user', 'user_id', array(
274 'user_email_token' => md5( $code ),
275 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
277 if( $id !== false ) {
278 return User
::newFromId( $id );
285 * Create a new user object using data from session or cookies. If the
286 * login credentials are invalid, the result is an anonymous user.
291 static function newFromSession() {
293 $user->mFrom
= 'session';
298 * Get username given an id.
299 * @param integer $id Database user id
300 * @return string Nickname of a user
303 static function whoIs( $id ) {
304 $dbr =& wfGetDB( DB_SLAVE
);
305 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
309 * Get real username given an id.
310 * @param integer $id Database user id
311 * @return string Realname of a user
314 static function whoIsReal( $id ) {
315 $dbr =& wfGetDB( DB_SLAVE
);
316 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), 'User::whoIsReal' );
320 * Get database id given a user name
321 * @param string $name Nickname of a user
322 * @return integer|null Database user id (null: if non existent
325 static function idFromName( $name ) {
326 $nt = Title
::newFromText( $name );
327 if( is_null( $nt ) ) {
331 $dbr =& wfGetDB( DB_SLAVE
);
332 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
334 if ( $s === false ) {
342 * Does the string match an anonymous IPv4 address?
344 * This function exists for username validation, in order to reject
345 * usernames which are similar in form to IP addresses. Strings such
346 * as 300.300.300.300 will return true because it looks like an IP
347 * address, despite not being strictly valid.
349 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
350 * address because the usemod software would "cloak" anonymous IP
351 * addresses like this, if we allowed accounts like this to be created
352 * new users could get the old edits of these anonymous users.
357 * @param string $name Nickname of a user
360 static function isIP( $name ) {
361 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name);
362 /*return preg_match("/^
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]))\.
366 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
371 * Is the input a valid username?
373 * Checks if the input is a valid username, we don't want an empty string,
374 * an IP address, anything that containins slashes (would mess up subpages),
375 * is longer than the maximum allowed username size or doesn't begin with
378 * @param string $name
382 static function isValidUserName( $name ) {
383 global $wgContLang, $wgMaxNameChars;
386 || User
::isIP( $name )
387 ||
strpos( $name, '/' ) !== false
388 ||
strlen( $name ) > $wgMaxNameChars
389 ||
$name != $wgContLang->ucfirst( $name ) )
392 // Ensure that the name can't be misresolved as a different title,
393 // such as with extra namespace keys at the start.
394 $parsed = Title
::newFromText( $name );
395 if( is_null( $parsed )
396 ||
$parsed->getNamespace()
397 ||
strcmp( $name, $parsed->getPrefixedText() ) )
400 // Check an additional blacklist of troublemaker characters.
401 // Should these be merged into the title char list?
402 $unicodeBlacklist = '/[' .
403 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
404 '\x{00a0}' . # non-breaking space
405 '\x{2000}-\x{200f}' . # various whitespace
406 '\x{2028}-\x{202f}' . # breaks and control chars
407 '\x{3000}' . # ideographic space
408 '\x{e000}-\x{f8ff}' . # private use
410 if( preg_match( $unicodeBlacklist, $name ) ) {
418 * Usernames which fail to pass this function will be blocked
419 * from user login and new account registrations, but may be used
420 * internally by batch processes.
422 * If an account already exists in this form, login will be blocked
423 * by a failure to pass this function.
425 * @param string $name
428 static function isUsableName( $name ) {
429 global $wgReservedUsernames;
431 // Must be a usable username, obviously ;)
432 self
::isValidUserName( $name ) &&
434 // Certain names may be reserved for batch processes.
435 !in_array( $name, $wgReservedUsernames );
439 * Usernames which fail to pass this function will be blocked
440 * from new account registrations, but may be used internally
441 * either by batch processes or by user accounts which have
442 * already been created.
444 * Additional character blacklisting may be added here
445 * rather than in isValidUserName() to avoid disrupting
448 * @param string $name
451 static function isCreatableName( $name ) {
453 self
::isUsableName( $name ) &&
455 // Registration-time character blacklisting...
456 strpos( $name, '@' ) === false;
460 * Is the input a valid password?
462 * @param string $password
466 static function isValidPassword( $password ) {
467 global $wgMinimalPasswordLength;
468 return strlen( $password ) >= $wgMinimalPasswordLength;
472 * Does the string match roughly an email address ?
474 * There used to be a regular expression here, it got removed because it
475 * rejected valid addresses. Actually just check if there is '@' somewhere
476 * in the given address.
478 * @todo Check for RFC 2822 compilance
481 * @param string $addr email address
485 static function isValidEmailAddr ( $addr ) {
486 return ( trim( $addr ) != '' ) &&
487 (false !== strpos( $addr, '@' ) );
491 * Given unvalidated user input, return a canonical username, or false if
492 * the username is invalid.
493 * @param string $name
494 * @param mixed $validate Type of validation to use:
495 * false No validation
496 * 'valid' Valid for batch processes
497 * 'usable' Valid for batch processes and login
498 * 'creatable' Valid for batch processes, login and account creation
500 static function getCanonicalName( $name, $validate = 'valid' ) {
501 # Force usernames to capital
503 $name = $wgContLang->ucfirst( $name );
505 # Clean up name according to title rules
506 $t = Title
::newFromText( $name );
507 if( is_null( $t ) ) {
511 # Reject various classes of invalid names
512 $name = $t->getText();
514 $name = $wgAuth->getCanonicalName( $t->getText() );
516 switch ( $validate ) {
520 if ( !User
::isValidUserName( $name ) ) {
525 if ( !User
::isUsableName( $name ) ) {
530 if ( !User
::isCreatableName( $name ) ) {
535 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
541 * Count the number of edits of a user
543 * @param int $uid The user ID to check
547 static function edits( $uid ) {
548 wfProfileIn( __METHOD__
);
549 $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
);
743 $res = $dbr->select( 'user_groups',
745 array( 'ug_user' => $this->mId
),
747 $this->mGroups
= array();
748 while( $row = $dbr->fetchObject( $res ) ) {
749 $this->mGroups
[] = $row->ug_group
;
755 $this->loadDefaults();
761 * Clear various cached data stored in this object.
762 * @param string $reloadFrom Reload user and user_groups table data from a
763 * given source. May be "name", "id", "defaults", "session" or false for
766 function clearInstanceCache( $reloadFrom = false ) {
767 $this->mNewtalk
= -1;
768 $this->mDatePreference
= null;
769 $this->mBlockedby
= -1; # Unset
770 $this->mHash
= false;
772 $this->mRights
= null;
773 $this->mEffectiveGroups
= null;
776 $this->mDataLoaded
= false;
777 $this->mFrom
= $reloadFrom;
782 * Combine the language default options with any site-specific options
783 * and add the default language variants.
784 * Not really private cause it's called by Language class
789 static function getDefaultOptions() {
790 global $wgNamespacesToBeSearchedDefault;
792 * Site defaults will override the global/language defaults
794 global $wgDefaultUserOptions, $wgContLang;
795 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
798 * default language setting
800 $variant = $wgContLang->getPreferredVariant( false );
801 $defOpt['variant'] = $variant;
802 $defOpt['language'] = $variant;
804 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
805 $defOpt['searchNs'.$nsnum] = $val;
811 * Get a given default option value.
818 function getDefaultOption( $opt ) {
819 $defOpts = User
::getDefaultOptions();
820 if( isset( $defOpts[$opt] ) ) {
821 return $defOpts[$opt];
828 * Get a list of user toggle names
831 static function getToggles() {
833 $extraToggles = array();
834 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
835 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
840 * Get blocking information
842 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
843 * non-critical checks are done against slaves. Check when actually saving should be done against
846 function getBlockedStatus( $bFromSlave = true ) {
847 global $wgEnableSorbs, $wgProxyWhitelist;
849 if ( -1 != $this->mBlockedby
) {
850 wfDebug( "User::getBlockedStatus: already loaded.\n" );
854 wfProfileIn( __METHOD__
);
855 wfDebug( __METHOD__
.": checking...\n" );
857 $this->mBlockedby
= 0;
860 if ($this->isAllowed( 'ipblock-exempt' ) ) {
861 # Exempt from all types of IP-block
866 $this->mBlock
= new Block();
867 $this->mBlock
->fromMaster( !$bFromSlave );
868 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
869 wfDebug( __METHOD__
.": Found block.\n" );
870 $this->mBlockedby
= $this->mBlock
->mBy
;
871 $this->mBlockreason
= $this->mBlock
->mReason
;
872 if ( $this->isLoggedIn() ) {
873 $this->spreadBlock();
876 $this->mBlock
= null;
877 wfDebug( __METHOD__
.": No block.\n" );
881 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
884 if ( wfIsLocallyBlockedProxy( $ip ) ) {
885 $this->mBlockedby
= wfMsg( 'proxyblocker' );
886 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
890 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
891 if ( $this->inSorbsBlacklist( $ip ) ) {
892 $this->mBlockedby
= wfMsg( 'sorbs' );
893 $this->mBlockreason
= wfMsg( 'sorbsreason' );
899 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
901 wfProfileOut( __METHOD__
);
904 function inSorbsBlacklist( $ip ) {
905 global $wgEnableSorbs, $wgSorbsUrl;
907 return $wgEnableSorbs &&
908 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
911 function inDnsBlacklist( $ip, $base ) {
912 wfProfileIn( __METHOD__
);
918 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
920 for ( $i=4; $i>=1; $i-- ) {
921 $host .= $m[$i] . '.';
926 $ipList = gethostbynamel( $host );
929 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
932 wfDebug( "Requested $host, not found in $base.\n" );
936 wfProfileOut( __METHOD__
);
941 * Primitive rate limits: enforce maximum actions per time period
942 * to put a brake on flooding.
944 * Note: when using a shared cache like memcached, IP-address
945 * last-hit counters will be shared across wikis.
947 * @return bool true if a rate limiter was tripped
950 function pingLimiter( $action='edit' ) {
952 # Call the 'PingLimiter' hook
954 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
958 global $wgRateLimits, $wgRateLimitsExcludedGroups;
959 if( !isset( $wgRateLimits[$action] ) ) {
963 # Some groups shouldn't trigger the ping limiter, ever
964 foreach( $this->getGroups() as $group ) {
965 if( array_search( $group, $wgRateLimitsExcludedGroups ) !== false )
969 global $wgMemc, $wgRateLimitLog;
970 wfProfileIn( __METHOD__
);
972 $limits = $wgRateLimits[$action];
974 $id = $this->getId();
977 if( isset( $limits['anon'] ) && $id == 0 ) {
978 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
981 if( isset( $limits['user'] ) && $id != 0 ) {
982 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
984 if( $this->isNewbie() ) {
985 if( isset( $limits['newbie'] ) && $id != 0 ) {
986 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
988 if( isset( $limits['ip'] ) ) {
989 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
992 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
993 $subnet = $matches[1];
994 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
999 foreach( $keys as $key => $limit ) {
1000 list( $max, $period ) = $limit;
1001 $summary = "(limit $max in {$period}s)";
1002 $count = $wgMemc->get( $key );
1004 if( $count > $max ) {
1005 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1006 if( $wgRateLimitLog ) {
1007 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1011 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1014 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1015 $wgMemc->add( $key, 1, intval( $period ) );
1017 $wgMemc->incr( $key );
1020 wfProfileOut( __METHOD__
);
1025 * Check if user is blocked
1026 * @return bool True if blocked, false otherwise
1028 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1029 wfDebug( "User::isBlocked: enter\n" );
1030 $this->getBlockedStatus( $bFromSlave );
1031 return $this->mBlockedby
!== 0;
1035 * Check if user is blocked from editing a particular article
1037 function isBlockedFrom( $title, $bFromSlave = false ) {
1038 global $wgBlockAllowsUTEdit;
1039 wfProfileIn( __METHOD__
);
1040 wfDebug( __METHOD__
.": enter\n" );
1042 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1043 $title->getNamespace() == NS_USER_TALK
)
1046 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1048 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1049 $blocked = $this->isBlocked( $bFromSlave );
1051 wfProfileOut( __METHOD__
);
1056 * Get name of blocker
1057 * @return string name of blocker
1059 function blockedBy() {
1060 $this->getBlockedStatus();
1061 return $this->mBlockedby
;
1065 * Get blocking reason
1066 * @return string Blocking reason
1068 function blockedFor() {
1069 $this->getBlockedStatus();
1070 return $this->mBlockreason
;
1074 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1082 * Set the user and reload all fields according to that ID
1083 * @deprecated use User::newFromId()
1085 function setID( $v ) {
1087 $this->clearInstanceCache( 'id' );
1091 * Get the user name, or the IP for anons
1093 function getName() {
1094 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1095 # Special case optimisation
1096 return $this->mName
;
1099 if ( $this->mName
=== false ) {
1100 $this->mName
= wfGetIP();
1102 return $this->mName
;
1107 * Set the user name.
1109 * This does not reload fields from the database according to the given
1110 * name. Rather, it is used to create a temporary "nonexistent user" for
1111 * later addition to the database. It can also be used to set the IP
1112 * address for an anonymous user to something other than the current
1115 * User::newFromName() has rougly the same function, when the named user
1118 function setName( $str ) {
1120 $this->mName
= $str;
1124 * Return the title dbkey form of the name, for eg user pages.
1128 function getTitleKey() {
1129 return str_replace( ' ', '_', $this->getName() );
1132 function getNewtalk() {
1135 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1136 if( $this->mNewtalk
=== -1 ) {
1137 $this->mNewtalk
= false; # reset talk page status
1139 # Check memcached separately for anons, who have no
1140 # entire User object stored in there.
1143 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1144 $newtalk = $wgMemc->get( $key );
1145 if( $newtalk != "" ) {
1146 $this->mNewtalk
= (bool)$newtalk;
1148 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
1149 $wgMemc->set( $key, (int)$this->mNewtalk
, time() +
1800 );
1152 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1156 return (bool)$this->mNewtalk
;
1160 * Return the talk page(s) this user has new messages on.
1162 function getNewMessageLinks() {
1164 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1167 if (!$this->getNewtalk())
1169 $up = $this->getUserPage();
1170 $utp = $up->getTalkPage();
1171 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1176 * Perform a user_newtalk check on current slaves; if the memcached data
1177 * is funky we don't want newtalk state to get stuck on save, as that's
1180 * @param string $field
1185 function checkNewtalk( $field, $id ) {
1186 $dbr =& wfGetDB( DB_SLAVE
);
1187 $ok = $dbr->selectField( 'user_newtalk', $field,
1188 array( $field => $id ), __METHOD__
);
1189 return $ok !== false;
1194 * @param string $field
1198 function updateNewtalk( $field, $id ) {
1199 if( $this->checkNewtalk( $field, $id ) ) {
1200 wfDebug( __METHOD__
." already set ($field, $id), ignoring\n" );
1203 $dbw =& wfGetDB( DB_MASTER
);
1204 $dbw->insert( 'user_newtalk',
1205 array( $field => $id ),
1208 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1213 * Clear the new messages flag for the given user
1214 * @param string $field
1218 function deleteNewtalk( $field, $id ) {
1219 if( !$this->checkNewtalk( $field, $id ) ) {
1220 wfDebug( __METHOD__
.": already gone ($field, $id), ignoring\n" );
1223 $dbw =& wfGetDB( DB_MASTER
);
1224 $dbw->delete( 'user_newtalk',
1225 array( $field => $id ),
1227 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1232 * Update the 'You have new messages!' status.
1235 function setNewtalk( $val ) {
1236 if( wfReadOnly() ) {
1241 $this->mNewtalk
= $val;
1243 if( $this->isAnon() ) {
1245 $id = $this->getName();
1248 $id = $this->getId();
1252 $changed = $this->updateNewtalk( $field, $id );
1254 $changed = $this->deleteNewtalk( $field, $id );
1258 if( $this->isAnon() ) {
1259 // Anons have a separate memcached space, since
1260 // user records aren't kept for them.
1262 $key = wfMemcKey( 'newtalk', 'ip', $val );
1263 $wgMemc->set( $key, $val ?
1 : 0 );
1266 // Make sure the user page is watched, so a notification
1267 // will be sent out if enabled.
1268 $this->addWatch( $this->getTalkPage() );
1271 $this->invalidateCache();
1276 * Generate a current or new-future timestamp to be stored in the
1277 * user_touched field when we update things.
1279 private static function newTouchedTimestamp() {
1280 global $wgClockSkewFudge;
1281 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1285 * Clear user data from memcached.
1286 * Use after applying fun updates to the database; caller's
1287 * responsibility to update user_touched if appropriate.
1289 * Called implicitly from invalidateCache() and saveSettings().
1291 private function clearSharedCache() {
1294 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1299 * Immediately touch the user data cache for this account.
1300 * Updates user_touched field, and removes account data from memcached
1301 * for reload on the next hit.
1303 function invalidateCache() {
1306 $this->mTouched
= self
::newTouchedTimestamp();
1308 $dbw =& wfGetDB( DB_MASTER
);
1309 $dbw->update( 'user',
1310 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1311 array( 'user_id' => $this->mId
),
1314 $this->clearSharedCache();
1318 function validateCache( $timestamp ) {
1320 return ($timestamp >= $this->mTouched
);
1324 * Encrypt a password.
1325 * It can eventuall salt a password @see User::addSalt()
1326 * @param string $p clear Password.
1327 * @return string Encrypted password.
1329 function encryptPassword( $p ) {
1331 return wfEncryptPassword( $this->mId
, $p );
1335 * Set the password and reset the random token
1336 * Calls through to authentication plugin if necessary;
1337 * will have no effect if the auth plugin refuses to
1338 * pass the change through or if the legal password
1341 * As a special case, setting the password to null
1342 * wipes it, so the account cannot be logged in until
1343 * a new password is set, for instance via e-mail.
1345 * @param string $str
1346 * @throws PasswordError on failure
1348 function setPassword( $str ) {
1351 if( $str !== null ) {
1352 if( !$wgAuth->allowPasswordChange() ) {
1353 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1356 if( !$this->isValidPassword( $str ) ) {
1357 global $wgMinimalPasswordLength;
1358 throw new PasswordError( wfMsg( 'passwordtooshort',
1359 $wgMinimalPasswordLength ) );
1363 if( !$wgAuth->setPassword( $this, $str ) ) {
1364 throw new PasswordError( wfMsg( 'externaldberror' ) );
1370 if( $str === null ) {
1371 // Save an invalid hash...
1372 $this->mPassword
= '';
1374 $this->mPassword
= $this->encryptPassword( $str );
1376 $this->mNewpassword
= '';
1377 $this->mNewpassTime
= null;
1383 * Set the random token (used for persistent authentication)
1384 * Called from loadDefaults() among other places.
1387 function setToken( $token = false ) {
1388 global $wgSecretKey, $wgProxyKey;
1391 if ( $wgSecretKey ) {
1392 $key = $wgSecretKey;
1393 } elseif ( $wgProxyKey ) {
1398 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1400 $this->mToken
= $token;
1404 function setCookiePassword( $str ) {
1406 $this->mCookiePassword
= md5( $str );
1410 * Set the password for a password reminder or new account email
1411 * Sets the user_newpass_time field if $throttle is true
1413 function setNewpassword( $str, $throttle = true ) {
1415 $this->mNewpassword
= $this->encryptPassword( $str );
1417 $this->mNewpassTime
= wfTimestampNow();
1422 * Returns true if a password reminder email has already been sent within
1423 * the last $wgPasswordReminderResendTime hours
1425 function isPasswordReminderThrottled() {
1426 global $wgPasswordReminderResendTime;
1428 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1431 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1432 return time() < $expiry;
1435 function getEmail() {
1437 return $this->mEmail
;
1440 function getEmailAuthenticationTimestamp() {
1442 return $this->mEmailAuthenticated
;
1445 function setEmail( $str ) {
1447 $this->mEmail
= $str;
1450 function getRealName() {
1452 return $this->mRealName
;
1455 function setRealName( $str ) {
1457 $this->mRealName
= $str;
1461 * @param string $oname The option to check
1462 * @param string $defaultOverride A default value returned if the option does not exist
1465 function getOption( $oname, $defaultOverride = '' ) {
1468 if ( is_null( $this->mOptions
) ) {
1469 if($defaultOverride != '') {
1470 return $defaultOverride;
1472 $this->mOptions
= User
::getDefaultOptions();
1475 if ( array_key_exists( $oname, $this->mOptions
) ) {
1476 return trim( $this->mOptions
[$oname] );
1478 return $defaultOverride;
1483 * Get the user's date preference, including some important migration for
1486 function getDatePreference() {
1487 if ( is_null( $this->mDatePreference
) ) {
1489 $value = $this->getOption( 'date' );
1490 $map = $wgLang->getDatePreferenceMigrationMap();
1491 if ( isset( $map[$value] ) ) {
1492 $value = $map[$value];
1494 $this->mDatePreference
= $value;
1496 return $this->mDatePreference
;
1500 * @param string $oname The option to check
1501 * @return bool False if the option is not selected, true if it is
1503 function getBoolOption( $oname ) {
1504 return (bool)$this->getOption( $oname );
1508 * Get an option as an integer value from the source string.
1509 * @param string $oname The option to check
1510 * @param int $default Optional value to return if option is unset/blank.
1513 function getIntOption( $oname, $default=0 ) {
1514 $val = $this->getOption( $oname );
1518 return intval( $val );
1521 function setOption( $oname, $val ) {
1523 if ( is_null( $this->mOptions
) ) {
1524 $this->mOptions
= User
::getDefaultOptions();
1526 if ( $oname == 'skin' ) {
1527 # Clear cached skin, so the new one displays immediately in Special:Preferences
1528 unset( $this->mSkin
);
1530 // Filter out any newlines that may have passed through input validation.
1531 // Newlines are used to separate items in the options blob.
1532 $val = str_replace( "\r\n", "\n", $val );
1533 $val = str_replace( "\r", "\n", $val );
1534 $val = str_replace( "\n", " ", $val );
1535 $this->mOptions
[$oname] = $val;
1538 function getRights() {
1539 if ( is_null( $this->mRights
) ) {
1540 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1542 return $this->mRights
;
1546 * Get the list of explicit group memberships this user has.
1547 * The implicit * and user groups are not included.
1548 * @return array of strings
1550 function getGroups() {
1552 return $this->mGroups
;
1556 * Get the list of implicit group memberships this user has.
1557 * This includes all explicit groups, plus 'user' if logged in
1558 * and '*' for all accounts.
1559 * @param boolean $recache Don't use the cache
1560 * @return array of strings
1562 function getEffectiveGroups( $recache = false ) {
1563 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1565 $this->mEffectiveGroups
= $this->mGroups
;
1566 $this->mEffectiveGroups
[] = '*';
1568 $this->mEffectiveGroups
[] = 'user';
1570 global $wgAutoConfirmAge, $wgAutoConfirmCount;
1572 $accountAge = time() - wfTimestampOrNull( TS_UNIX
, $this->mRegistration
);
1573 $accountEditCount = User
::edits( $this->mId
);
1574 if( $accountAge >= $wgAutoConfirmAge && $accountEditCount >= $wgAutoConfirmCount ) {
1575 $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
;
1594 * Add the user to the given group.
1595 * This takes immediate effect.
1598 function addGroup( $group ) {
1600 $dbw =& wfGetDB( DB_MASTER
);
1601 if( $this->getId() ) {
1602 $dbw->insert( 'user_groups',
1604 'ug_user' => $this->getID(),
1605 'ug_group' => $group,
1608 array( 'IGNORE' ) );
1611 $this->mGroups
[] = $group;
1612 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1614 $this->invalidateCache();
1618 * Remove the user from the given group.
1619 * This takes immediate effect.
1622 function removeGroup( $group ) {
1624 $dbw =& wfGetDB( DB_MASTER
);
1625 $dbw->delete( 'user_groups',
1627 'ug_user' => $this->getID(),
1628 'ug_group' => $group,
1630 'User::removeGroup' );
1632 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1633 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1635 $this->invalidateCache();
1640 * A more legible check for non-anonymousness.
1641 * Returns true if the user is not an anonymous visitor.
1645 function isLoggedIn() {
1646 return( $this->getID() != 0 );
1650 * A more legible check for anonymousness.
1651 * Returns true if the user is an anonymous visitor.
1656 return !$this->isLoggedIn();
1660 * Whether the user is a bot
1664 return $this->isAllowed( 'bot' );
1668 * Check if user is allowed to access a feature / make an action
1669 * @param string $action Action to be checked
1670 * @return boolean True: action is allowed, False: action should not be allowed
1672 function isAllowed($action='') {
1673 if ( $action === '' )
1674 // In the spirit of DWIM
1677 return in_array( $action, $this->getRights() );
1681 * Load a skin if it doesn't exist or return it
1682 * @todo FIXME : need to check the old failback system [AV]
1684 function &getSkin() {
1686 if ( ! isset( $this->mSkin
) ) {
1687 wfProfileIn( __METHOD__
);
1690 $userSkin = $this->getOption( 'skin' );
1691 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1693 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1694 wfProfileOut( __METHOD__
);
1696 return $this->mSkin
;
1700 * @param string $title Article title to look at
1704 * Check watched status of an article
1705 * @return bool True if article is watched
1707 function isWatched( $title ) {
1708 $wl = WatchedItem
::fromUserTitle( $this, $title );
1709 return $wl->isWatched();
1715 function addWatch( $title ) {
1716 $wl = WatchedItem
::fromUserTitle( $this, $title );
1718 $this->invalidateCache();
1722 * Stop watching an article
1724 function removeWatch( $title ) {
1725 $wl = WatchedItem
::fromUserTitle( $this, $title );
1727 $this->invalidateCache();
1731 * Clear the user's notification timestamp for the given title.
1732 * If e-notif e-mails are on, they will receive notification mails on
1733 * the next change of the page if it's watched etc.
1735 function clearNotification( &$title ) {
1736 global $wgUser, $wgUseEnotif;
1738 # Do nothing if the database is locked to writes
1739 if( wfReadOnly() ) {
1743 if ($title->getNamespace() == NS_USER_TALK
&&
1744 $title->getText() == $this->getName() ) {
1745 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1747 $this->setNewtalk( false );
1750 if( !$wgUseEnotif ) {
1754 if( $this->isAnon() ) {
1755 // Nothing else to do...
1759 // Only update the timestamp if the page is being watched.
1760 // The query to find out if it is watched is cached both in memcached and per-invocation,
1761 // and when it does have to be executed, it can be on a slave
1762 // If this is the user's newtalk page, we always update the timestamp
1763 if ($title->getNamespace() == NS_USER_TALK
&&
1764 $title->getText() == $wgUser->getName())
1767 } elseif ( $this->getID() == $wgUser->getID() ) {
1768 $watched = $title->userIsWatching();
1773 // If the page is watched by the user (or may be watched), update the timestamp on any
1774 // any matching rows
1776 $dbw =& wfGetDB( DB_MASTER
);
1777 $dbw->update( 'watchlist',
1779 'wl_notificationtimestamp' => NULL
1780 ), array( /* WHERE */
1781 'wl_title' => $title->getDBkey(),
1782 'wl_namespace' => $title->getNamespace(),
1783 'wl_user' => $this->getID()
1784 ), 'User::clearLastVisited'
1792 * Resets all of the given user's page-change notification timestamps.
1793 * If e-notif e-mails are on, they will receive notification mails on
1794 * the next change of any watched page.
1796 * @param int $currentUser user ID number
1799 function clearAllNotifications( $currentUser ) {
1800 global $wgUseEnotif;
1801 if ( !$wgUseEnotif ) {
1802 $this->setNewtalk( false );
1805 if( $currentUser != 0 ) {
1807 $dbw =& wfGetDB( DB_MASTER
);
1808 $dbw->update( 'watchlist',
1810 'wl_notificationtimestamp' => NULL
1811 ), array( /* WHERE */
1812 'wl_user' => $currentUser
1813 ), 'UserMailer::clearAll'
1816 # we also need to clear here the "you have new message" notification for the own user_talk page
1817 # This is cleared one page view later in Article::viewUpdates();
1823 * @return string Encoding options
1825 function encodeOptions() {
1827 if ( is_null( $this->mOptions
) ) {
1828 $this->mOptions
= User
::getDefaultOptions();
1831 foreach ( $this->mOptions
as $oname => $oval ) {
1832 array_push( $a, $oname.'='.$oval );
1834 $s = implode( "\n", $a );
1841 function decodeOptions( $str ) {
1842 $this->mOptions
= array();
1843 $a = explode( "\n", $str );
1844 foreach ( $a as $s ) {
1846 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1847 $this->mOptions
[$m[1]] = $m[2];
1852 function setCookies() {
1853 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1855 if ( 0 == $this->mId
) return;
1856 $exp = time() +
$wgCookieExpiration;
1858 $_SESSION['wsUserID'] = $this->mId
;
1859 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1861 $_SESSION['wsUserName'] = $this->getName();
1862 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1864 $_SESSION['wsToken'] = $this->mToken
;
1865 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1866 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1868 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1874 * Clears the cookies and session, resets the instance cache
1877 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1878 $this->clearInstanceCache( 'defaults' );
1880 $_SESSION['wsUserID'] = 0;
1882 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1883 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1885 # Remember when user logged out, to prevent seeing cached pages
1886 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1890 * Save object settings into database
1891 * @fixme Only rarely do all these fields need to be set!
1893 function saveSettings() {
1895 if ( wfReadOnly() ) { return; }
1896 if ( 0 == $this->mId
) { return; }
1898 $this->mTouched
= self
::newTouchedTimestamp();
1900 $dbw =& wfGetDB( DB_MASTER
);
1901 $dbw->update( 'user',
1903 'user_name' => $this->mName
,
1904 'user_password' => $this->mPassword
,
1905 'user_newpassword' => $this->mNewpassword
,
1906 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
1907 'user_real_name' => $this->mRealName
,
1908 'user_email' => $this->mEmail
,
1909 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1910 'user_options' => $this->encodeOptions(),
1911 'user_touched' => $dbw->timestamp($this->mTouched
),
1912 'user_token' => $this->mToken
1913 ), array( /* WHERE */
1914 'user_id' => $this->mId
1917 $this->clearSharedCache();
1922 * Checks if a user with the given name exists, returns the ID
1924 function idForName() {
1925 $s = trim( $this->getName() );
1926 if ( 0 == strcmp( '', $s ) ) return 0;
1928 $dbr =& wfGetDB( DB_SLAVE
);
1929 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
1930 if ( $id === false ) {
1937 * Add a user to the database, return the user object
1939 * @param string $name The user's name
1940 * @param array $params Associative array of non-default parameters to save to the database:
1941 * password The user's password. Password logins will be disabled if this is omitted.
1942 * newpassword A temporary password mailed to the user
1943 * email The user's email address
1944 * email_authenticated The email authentication timestamp
1945 * real_name The user's real name
1946 * options An associative array of non-default options
1947 * token Random authentication token. Do not set.
1948 * registration Registration timestamp. Do not set.
1950 * @return User object, or null if the username already exists
1952 static function createNew( $name, $params = array() ) {
1955 if ( isset( $params['options'] ) ) {
1956 $user->mOptions
= $params['options'] +
$user->mOptions
;
1957 unset( $params['options'] );
1959 $dbw =& wfGetDB( DB_MASTER
);
1960 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1962 'user_id' => $seqVal,
1963 'user_name' => $name,
1964 'user_password' => $user->mPassword
,
1965 'user_newpassword' => $user->mNewpassword
,
1966 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
1967 'user_email' => $user->mEmail
,
1968 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
1969 'user_real_name' => $user->mRealName
,
1970 'user_options' => $user->encodeOptions(),
1971 'user_token' => $user->mToken
,
1972 'user_registration' => $dbw->timestamp( $user->mRegistration
),
1973 'user_editcount' => 0,
1975 foreach ( $params as $name => $value ) {
1976 $fields["user_$name"] = $value;
1978 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
1979 if ( $dbw->affectedRows() ) {
1980 $newUser = User
::newFromId( $dbw->insertId() );
1988 * Add an existing user object to the database
1990 function addToDatabase() {
1992 $dbw =& wfGetDB( DB_MASTER
);
1993 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1994 $dbw->insert( 'user',
1996 'user_id' => $seqVal,
1997 'user_name' => $this->mName
,
1998 'user_password' => $this->mPassword
,
1999 'user_newpassword' => $this->mNewpassword
,
2000 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2001 'user_email' => $this->mEmail
,
2002 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2003 'user_real_name' => $this->mRealName
,
2004 'user_options' => $this->encodeOptions(),
2005 'user_token' => $this->mToken
,
2006 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2007 'user_editcount' => 0,
2010 $this->mId
= $dbw->insertId();
2012 # Clear instance cache other than user table data, which is already accurate
2013 $this->clearInstanceCache();
2017 * If the (non-anonymous) user is blocked, this function will block any IP address
2018 * that they successfully log on from.
2020 function spreadBlock() {
2021 wfDebug( __METHOD__
."()\n" );
2023 if ( $this->mId
== 0 ) {
2027 $userblock = Block
::newFromDB( '', $this->mId
);
2028 if ( !$userblock ) {
2032 $userblock->doAutoblock( wfGetIp() );
2037 * Generate a string which will be different for any combination of
2038 * user options which would produce different parser output.
2039 * This will be used as part of the hash key for the parser cache,
2040 * so users will the same options can share the same cached data
2043 * Extensions which require it should install 'PageRenderingHash' hook,
2044 * which will give them a chance to modify this key based on their own
2049 function getPageRenderingHash() {
2050 global $wgContLang, $wgUseDynamicDates, $wgLang;
2052 return $this->mHash
;
2055 // stubthreshold is only included below for completeness,
2056 // it will always be 0 when this function is called by parsercache.
2058 $confstr = $this->getOption( 'math' );
2059 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2060 if ( $wgUseDynamicDates ) {
2061 $confstr .= '!' . $this->getDatePreference();
2063 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2064 $confstr .= '!' . $wgLang->getCode();
2065 $confstr .= '!' . $this->getOption( 'thumbsize' );
2066 // add in language specific options, if any
2067 $extra = $wgContLang->getExtraHashOptions();
2070 // Give a chance for extensions to modify the hash, if they have
2071 // extra options or other effects on the parser cache.
2072 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2074 $this->mHash
= $confstr;
2078 function isBlockedFromCreateAccount() {
2079 $this->getBlockedStatus();
2080 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2083 function isAllowedToCreateAccount() {
2084 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2090 function setLoaded( $loaded ) {}
2093 * Get this user's personal page title.
2098 function getUserPage() {
2099 return Title
::makeTitle( NS_USER
, $this->getName() );
2103 * Get this user's talk page title.
2108 function getTalkPage() {
2109 $title = $this->getUserPage();
2110 return $title->getTalkPage();
2116 function getMaxID() {
2117 static $res; // cache
2119 if ( isset( $res ) )
2122 $dbr =& wfGetDB( DB_SLAVE
);
2123 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2128 * Determine whether the user is a newbie. Newbies are either
2129 * anonymous IPs, or the most recently created accounts.
2130 * @return bool True if it is a newbie.
2132 function isNewbie() {
2133 return !$this->isAllowed( 'autoconfirmed' );
2137 * Check to see if the given clear-text password is one of the accepted passwords
2138 * @param string $password User password.
2139 * @return bool True if the given password is correct otherwise False.
2141 function checkPassword( $password ) {
2145 // Even though we stop people from creating passwords that
2146 // are shorter than this, doesn't mean people wont be able
2147 // to. Certain authentication plugins do NOT want to save
2148 // domain passwords in a mysql database, so we should
2149 // check this (incase $wgAuth->strict() is false).
2150 if( !$this->isValidPassword( $password ) ) {
2154 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2156 } elseif( $wgAuth->strict() ) {
2157 /* Auth plugin doesn't allow local authentication */
2160 $ep = $this->encryptPassword( $password );
2161 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2163 } elseif ( function_exists( 'iconv' ) ) {
2164 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2165 # Check for this with iconv
2166 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2167 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2175 * Check if the given clear-text password matches the temporary password
2176 * sent by e-mail for password reset operations.
2179 function checkTemporaryPassword( $plaintext ) {
2180 $hash = $this->encryptPassword( $plaintext );
2181 return $hash === $this->mNewpassword
;
2185 * Initialize (if necessary) and return a session token value
2186 * which can be used in edit forms to show that the user's
2187 * login credentials aren't being hijacked with a foreign form
2190 * @param mixed $salt - Optional function-specific data for hash.
2191 * Use a string or an array of strings.
2195 function editToken( $salt = '' ) {
2196 if( !isset( $_SESSION['wsEditToken'] ) ) {
2197 $token = $this->generateToken();
2198 $_SESSION['wsEditToken'] = $token;
2200 $token = $_SESSION['wsEditToken'];
2202 if( is_array( $salt ) ) {
2203 $salt = implode( '|', $salt );
2205 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2209 * Generate a hex-y looking random token for various uses.
2210 * Could be made more cryptographically sure if someone cares.
2213 function generateToken( $salt = '' ) {
2214 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2215 return md5( $token . $salt );
2219 * Check given value against the token value stored in the session.
2220 * A match should confirm that the form was submitted from the
2221 * user's own login session, not a form submission from a third-party
2224 * @param string $val - the input value to compare
2225 * @param string $salt - Optional function-specific data for hash
2229 function matchEditToken( $val, $salt = '' ) {
2231 $sessionToken = $this->editToken( $salt );
2232 if ( $val != $sessionToken ) {
2233 wfDebug( "User::matchEditToken: broken session data\n" );
2235 return $val == $sessionToken;
2239 * Generate a new e-mail confirmation token and send a confirmation
2240 * mail to the user's given address.
2242 * @return mixed True on success, a WikiError object on failure.
2244 function sendConfirmationMail() {
2246 $expiration = null; // gets passed-by-ref and defined in next line.
2247 $url = $this->confirmationTokenUrl( $expiration );
2248 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2249 wfMsg( 'confirmemail_body',
2253 $wgContLang->timeanddate( $expiration, false ) ) );
2257 * Send an e-mail to this user's account. Does not check for
2258 * confirmed status or validity.
2260 * @param string $subject
2261 * @param string $body
2262 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2263 * @return mixed True on success, a WikiError object on failure.
2265 function sendMail( $subject, $body, $from = null ) {
2266 if( is_null( $from ) ) {
2267 global $wgPasswordSender;
2268 $from = $wgPasswordSender;
2271 require_once( 'UserMailer.php' );
2272 $to = new MailAddress( $this );
2273 $sender = new MailAddress( $from );
2274 $error = userMailer( $to, $sender, $subject, $body );
2276 if( $error == '' ) {
2279 return new WikiError( $error );
2284 * Generate, store, and return a new e-mail confirmation code.
2285 * A hash (unsalted since it's used as a key) is stored.
2286 * @param &$expiration mixed output: accepts the expiration time
2290 function confirmationToken( &$expiration ) {
2292 $expires = $now +
7 * 24 * 60 * 60;
2293 $expiration = wfTimestamp( TS_MW
, $expires );
2295 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2296 $hash = md5( $token );
2298 $dbw =& wfGetDB( DB_MASTER
);
2299 $dbw->update( 'user',
2300 array( 'user_email_token' => $hash,
2301 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2302 array( 'user_id' => $this->mId
),
2309 * Generate and store a new e-mail confirmation token, and return
2310 * the URL the user can use to confirm.
2311 * @param &$expiration mixed output: accepts the expiration time
2315 function confirmationTokenUrl( &$expiration ) {
2316 $token = $this->confirmationToken( $expiration );
2317 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2318 return $title->getFullUrl();
2322 * Mark the e-mail address confirmed and save.
2324 function confirmEmail() {
2326 $this->mEmailAuthenticated
= wfTimestampNow();
2327 $this->saveSettings();
2332 * Is this user allowed to send e-mails within limits of current
2333 * site configuration?
2336 function canSendEmail() {
2337 return $this->isEmailConfirmed();
2341 * Is this user allowed to receive e-mails within limits of current
2342 * site configuration?
2345 function canReceiveEmail() {
2346 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2350 * Is this user's e-mail address valid-looking and confirmed within
2351 * limits of the current site configuration?
2353 * If $wgEmailAuthentication is on, this may require the user to have
2354 * confirmed their address by returning a code or using a password
2355 * sent to the address from the wiki.
2359 function isEmailConfirmed() {
2360 global $wgEmailAuthentication;
2363 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2364 if( $this->isAnon() )
2366 if( !self
::isValidEmailAddr( $this->mEmail
) )
2368 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2377 * Return true if there is an outstanding request for e-mail confirmation.
2380 function isEmailConfirmationPending() {
2381 global $wgEmailAuthentication;
2382 return $wgEmailAuthentication &&
2383 !$this->isEmailConfirmed() &&
2384 $this->mEmailToken
&&
2385 $this->mEmailTokenExpires
> wfTimestamp();
2389 * @param array $groups list of groups
2390 * @return array list of permission key names for given groups combined
2393 static function getGroupPermissions( $groups ) {
2394 global $wgGroupPermissions;
2396 foreach( $groups as $group ) {
2397 if( isset( $wgGroupPermissions[$group] ) ) {
2398 $rights = array_merge( $rights,
2399 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2406 * @param string $group key name
2407 * @return string localized descriptive name for group, if provided
2410 static function getGroupName( $group ) {
2411 $key = "group-$group";
2412 $name = wfMsg( $key );
2413 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2421 * @param string $group key name
2422 * @return string localized descriptive name for member of a group, if provided
2425 static function getGroupMember( $group ) {
2426 $key = "group-$group-member";
2427 $name = wfMsg( $key );
2428 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2436 * Return the set of defined explicit groups.
2437 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2438 * groups are not included, as they are defined
2439 * automatically, not in the database.
2443 static function getAllGroups() {
2444 global $wgGroupPermissions;
2446 array_keys( $wgGroupPermissions ),
2447 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2451 * Get the title of a page describing a particular group
2453 * @param $group Name of the group
2456 static function getGroupPage( $group ) {
2457 $page = wfMsgForContent( 'grouppage-' . $group );
2458 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2459 $title = Title
::newFromText( $page );
2460 if( is_object( $title ) )
2467 * Create a link to the group in HTML, if available
2469 * @param $group Name of the group
2470 * @param $text The text of the link
2473 static function makeGroupLinkHTML( $group, $text = '' ) {
2475 $text = self
::getGroupName( $group );
2477 $title = self
::getGroupPage( $group );
2480 $sk = $wgUser->getSkin();
2481 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2488 * Create a link to the group in Wikitext, if available
2490 * @param $group Name of the group
2491 * @param $text The text of the link (by default, the name of the group)
2494 static function makeGroupLinkWiki( $group, $text = '' ) {
2496 $text = self
::getGroupName( $group );
2498 $title = self
::getGroupPage( $group );
2500 $page = $title->getPrefixedText();
2501 return "[[$page|$text]]";
2508 * Increment the user's edit-count field.
2509 * Will have no effect for anonymous users.
2511 function incEditCount() {
2512 if( !$this->isAnon() ) {
2513 $dbw = wfGetDB( DB_MASTER
);
2514 $dbw->update( 'user',
2515 array( 'user_editcount=user_editcount+1' ),
2516 array( 'user_id' => $this->getId() ),
2519 // Lazy initialization check...
2520 if( $dbw->affectedRows() == 0 ) {
2521 // Pull from a slave to be less cruel to servers
2522 // Accuracy isn't the point anyway here
2523 $dbr = wfGetDB( DB_SLAVE
);
2524 $count = $dbr->selectField( 'revision',
2526 array( 'rev_user' => $this->getId() ),
2529 // Now here's a goddamn hack...
2530 if( $dbr !== $dbw ) {
2531 // If we actually have a slave server, the count is
2532 // at least one behind because the current transaction
2533 // has not been committed and replicated.
2536 // But if DB_SLAVE is selecting the master, then the
2537 // count we just read includes the revision that was
2538 // just added in the working transaction.
2541 $dbw->update( 'user',
2542 array( 'user_editcount' => $count ),
2543 array( 'user_id' => $this->getId() ),