8 # Number of characters in user_token field
9 define( 'USER_TOKEN_LENGTH', 32 );
11 # Serialized record version
12 define( 'MW_USER_VERSION', 4 );
14 # Some punctuation to prevent editing from broken text-mangling proxies.
15 # FIXME: this is embedded unescaped into HTML attributes in various
16 # places, so we can't safely include ' or " even though we really should.
17 define( 'EDIT_TOKEN_SUFFIX', '\\' );
20 * Thrown by User::setPassword() on error
22 class PasswordError
extends MWException
{
33 * A list of default user toggles, i.e. boolean user preferences that are
34 * displayed by Special:Preferences as checkboxes. This list can be
35 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
37 static public $mToggles = array(
47 'editsectiononrightclick',
57 'enotifwatchlistpages',
58 'enotifusertalkpages',
61 'shownumberswatching',
75 * List of member variables which are saved to the shared cache (memcached).
76 * Any operation which changes the corresponding database fields must
77 * call a cache-clearing function.
79 static $mCacheVars = array(
91 'mEmailAuthenticated',
101 * The cache variable declarations
103 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
104 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
105 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
108 * Whether the cache variables have been loaded
113 * Initialisation data source if mDataLoaded==false. May be one of:
114 * defaults anonymous user initialised from class defaults
115 * name initialise from mName
116 * id initialise from mId
117 * session log in from cookies or session if possible
119 * Use the User::newFrom*() family of functions to set this.
124 * Lazy-initialised variables, invalidated with clearInstanceCache
126 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
127 $mBlockreason, $mBlock, $mEffectiveGroups;
130 * Lightweight constructor for anonymous user
131 * Use the User::newFrom* factory functions for other kinds of users
134 $this->clearInstanceCache( 'defaults' );
138 * Load the user table data for this object from the source given by mFrom
141 if ( $this->mDataLoaded
) {
144 wfProfileIn( __METHOD__
);
146 # Set it now to avoid infinite recursion in accessors
147 $this->mDataLoaded
= true;
149 switch ( $this->mFrom
) {
151 $this->loadDefaults();
154 $this->mId
= self
::idFromName( $this->mName
);
156 # Nonexistent user placeholder object
157 $this->loadDefaults( $this->mName
);
166 $this->loadFromSession();
169 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
171 wfProfileOut( __METHOD__
);
175 * Load user table data given mId
176 * @return false if the ID does not exist, true otherwise
179 function loadFromId() {
181 if ( $this->mId
== 0 ) {
182 $this->loadDefaults();
187 $key = wfMemcKey( 'user', 'id', $this->mId
);
188 $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 * @param int $uid The user ID to check
546 static function edits( $uid ) {
547 $dbr =& wfGetDB( DB_SLAVE
);
548 return $dbr->selectField(
549 'revision', 'count(*)',
550 array( 'rev_user' => $uid ),
556 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
557 * @todo: hash random numbers to improve security, like generateToken()
562 static function randomPassword() {
563 global $wgMinimalPasswordLength;
564 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
565 $l = strlen( $pwchars ) - 1;
567 $pwlength = max( 7, $wgMinimalPasswordLength );
568 $digit = mt_rand(0, $pwlength - 1);
570 for ( $i = 0; $i < $pwlength; $i++
) {
571 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
577 * Set cached properties to default. Note: this no longer clears
578 * uncached lazy-initialised properties. The constructor does that instead.
582 function loadDefaults( $name = false ) {
583 wfProfileIn( __METHOD__
);
585 global $wgCookiePrefix;
588 $this->mName
= $name;
589 $this->mRealName
= '';
590 $this->mPassword
= $this->mNewpassword
= '';
591 $this->mNewpassTime
= null;
593 $this->mOptions
= null; # Defer init
595 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
596 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
598 $this->mTouched
= '0'; # Allow any pages to be cached
601 $this->setToken(); # Random
602 $this->mEmailAuthenticated
= null;
603 $this->mEmailToken
= '';
604 $this->mEmailTokenExpires
= null;
605 $this->mRegistration
= wfTimestamp( TS_MW
);
606 $this->mGroups
= array();
608 wfProfileOut( __METHOD__
);
612 * Initialise php session
613 * @deprecated use wfSetupSession()
615 function SetupSession() {
620 * Load user data from the session or login cookie. If there are no valid
621 * credentials, initialises the user as an anon.
622 * @return true if the user is logged in, false otherwise
626 function loadFromSession() {
627 global $wgMemc, $wgCookiePrefix;
629 if ( isset( $_SESSION['wsUserID'] ) ) {
630 if ( 0 != $_SESSION['wsUserID'] ) {
631 $sId = $_SESSION['wsUserID'];
633 $this->loadDefaults();
636 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
637 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
638 $_SESSION['wsUserID'] = $sId;
640 $this->loadDefaults();
643 if ( isset( $_SESSION['wsUserName'] ) ) {
644 $sName = $_SESSION['wsUserName'];
645 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
646 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
647 $_SESSION['wsUserName'] = $sName;
649 $this->loadDefaults();
653 $passwordCorrect = FALSE;
655 if ( !$this->loadFromId() ) {
656 # Not a valid ID, loadFromId has switched the object to anon for us
660 if ( isset( $_SESSION['wsToken'] ) ) {
661 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
663 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
664 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
667 # No session or persistent login cookie
668 $this->loadDefaults();
672 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
673 wfDebug( "Logged in from $from\n" );
676 # Invalid credentials
677 wfDebug( "Can't log in from $from, invalid credentials\n" );
678 $this->loadDefaults();
684 * Load user and user_group data from the database
685 * $this->mId must be set, this is how the user is identified.
687 * @return true if the user exists, false if the user is anonymous
690 function loadFromDatabase() {
692 $this->mId
= intval( $this->mId
);
694 /** Anonymous user */
696 $this->loadDefaults();
700 $dbr =& wfGetDB( DB_SLAVE
);
701 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
703 if ( $s !== false ) {
704 # Initialise user table data
705 $this->mName
= $s->user_name
;
706 $this->mRealName
= $s->user_real_name
;
707 $this->mPassword
= $s->user_password
;
708 $this->mNewpassword
= $s->user_newpassword
;
709 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $s->user_newpass_time
);
710 $this->mEmail
= $s->user_email
;
711 $this->decodeOptions( $s->user_options
);
712 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
713 $this->mToken
= $s->user_token
;
714 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
715 $this->mEmailToken
= $s->user_email_token
;
716 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $s->user_email_token_expires
);
717 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $s->user_registration
);
720 $res = $dbr->select( 'user_groups',
722 array( 'ug_user' => $this->mId
),
724 $this->mGroups
= array();
725 while( $row = $dbr->fetchObject( $res ) ) {
726 $this->mGroups
[] = $row->ug_group
;
732 $this->loadDefaults();
738 * Clear various cached data stored in this object.
739 * @param string $reloadFrom Reload user and user_groups table data from a
740 * given source. May be "name", "id", "defaults", "session" or false for
743 function clearInstanceCache( $reloadFrom = false ) {
744 $this->mNewtalk
= -1;
745 $this->mDatePreference
= null;
746 $this->mBlockedby
= -1; # Unset
747 $this->mHash
= false;
749 $this->mRights
= null;
750 $this->mEffectiveGroups
= null;
753 $this->mDataLoaded
= false;
754 $this->mFrom
= $reloadFrom;
759 * Combine the language default options with any site-specific options
760 * and add the default language variants.
766 function getDefaultOptions() {
767 global $wgNamespacesToBeSearchedDefault;
769 * Site defaults will override the global/language defaults
771 global $wgDefaultUserOptions, $wgContLang;
772 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
775 * default language setting
777 $variant = $wgContLang->getPreferredVariant( false );
778 $defOpt['variant'] = $variant;
779 $defOpt['language'] = $variant;
781 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
782 $defOpt['searchNs'.$nsnum] = $val;
788 * Get a given default option value.
795 function getDefaultOption( $opt ) {
796 $defOpts = User
::getDefaultOptions();
797 if( isset( $defOpts[$opt] ) ) {
798 return $defOpts[$opt];
805 * Get a list of user toggle names
808 static function getToggles() {
810 $extraToggles = array();
811 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
812 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
817 * Get blocking information
819 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
820 * non-critical checks are done against slaves. Check when actually saving should be done against
823 function getBlockedStatus( $bFromSlave = true ) {
824 global $wgEnableSorbs, $wgProxyWhitelist;
826 if ( -1 != $this->mBlockedby
) {
827 wfDebug( "User::getBlockedStatus: already loaded.\n" );
831 wfProfileIn( __METHOD__
);
832 wfDebug( __METHOD__
.": checking...\n" );
834 $this->mBlockedby
= 0;
838 $this->mBlock
= new Block();
839 $this->mBlock
->fromMaster( !$bFromSlave );
840 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
841 wfDebug( __METHOD__
.": Found block.\n" );
842 $this->mBlockedby
= $this->mBlock
->mBy
;
843 $this->mBlockreason
= $this->mBlock
->mReason
;
844 if ( $this->isLoggedIn() ) {
845 $this->spreadBlock();
848 $this->mBlock
= null;
849 wfDebug( __METHOD__
.": No block.\n" );
853 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
856 if ( wfIsLocallyBlockedProxy( $ip ) ) {
857 $this->mBlockedby
= wfMsg( 'proxyblocker' );
858 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
862 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
863 if ( $this->inSorbsBlacklist( $ip ) ) {
864 $this->mBlockedby
= wfMsg( 'sorbs' );
865 $this->mBlockreason
= wfMsg( 'sorbsreason' );
871 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
873 wfProfileOut( __METHOD__
);
876 function inSorbsBlacklist( $ip ) {
877 global $wgEnableSorbs, $wgSorbsUrl;
879 return $wgEnableSorbs &&
880 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
883 function inDnsBlacklist( $ip, $base ) {
884 wfProfileIn( __METHOD__
);
890 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
892 for ( $i=4; $i>=1; $i-- ) {
893 $host .= $m[$i] . '.';
898 $ipList = gethostbynamel( $host );
901 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
904 wfDebug( "Requested $host, not found in $base.\n" );
908 wfProfileOut( __METHOD__
);
913 * Primitive rate limits: enforce maximum actions per time period
914 * to put a brake on flooding.
916 * Note: when using a shared cache like memcached, IP-address
917 * last-hit counters will be shared across wikis.
919 * @return bool true if a rate limiter was tripped
922 function pingLimiter( $action='edit' ) {
923 global $wgRateLimits, $wgRateLimitsExcludedGroups;
924 if( !isset( $wgRateLimits[$action] ) ) {
928 # Some groups shouldn't trigger the ping limiter, ever
929 foreach( $this->getGroups() as $group ) {
930 if( array_search( $group, $wgRateLimitsExcludedGroups ) !== false )
934 global $wgMemc, $wgRateLimitLog;
935 wfProfileIn( __METHOD__
);
937 $limits = $wgRateLimits[$action];
939 $id = $this->getId();
942 if( isset( $limits['anon'] ) && $id == 0 ) {
943 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
946 if( isset( $limits['user'] ) && $id != 0 ) {
947 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
949 if( $this->isNewbie() ) {
950 if( isset( $limits['newbie'] ) && $id != 0 ) {
951 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
953 if( isset( $limits['ip'] ) ) {
954 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
957 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
958 $subnet = $matches[1];
959 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
964 foreach( $keys as $key => $limit ) {
965 list( $max, $period ) = $limit;
966 $summary = "(limit $max in {$period}s)";
967 $count = $wgMemc->get( $key );
969 if( $count > $max ) {
970 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
971 if( $wgRateLimitLog ) {
972 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
976 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
979 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
980 $wgMemc->add( $key, 1, intval( $period ) );
982 $wgMemc->incr( $key );
985 wfProfileOut( __METHOD__
);
990 * Check if user is blocked
991 * @return bool True if blocked, false otherwise
993 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
994 wfDebug( "User::isBlocked: enter\n" );
995 $this->getBlockedStatus( $bFromSlave );
996 return $this->mBlockedby
!== 0;
1000 * Check if user is blocked from editing a particular article
1002 function isBlockedFrom( $title, $bFromSlave = false ) {
1003 global $wgBlockAllowsUTEdit;
1004 wfProfileIn( __METHOD__
);
1005 wfDebug( __METHOD__
.": enter\n" );
1007 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1008 $title->getNamespace() == NS_USER_TALK
)
1011 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1013 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1014 $blocked = $this->isBlocked( $bFromSlave );
1016 wfProfileOut( __METHOD__
);
1021 * Get name of blocker
1022 * @return string name of blocker
1024 function blockedBy() {
1025 $this->getBlockedStatus();
1026 return $this->mBlockedby
;
1030 * Get blocking reason
1031 * @return string Blocking reason
1033 function blockedFor() {
1034 $this->getBlockedStatus();
1035 return $this->mBlockreason
;
1039 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1047 * Set the user and reload all fields according to that ID
1048 * @deprecated use User::newFromId()
1050 function setID( $v ) {
1052 $this->clearInstanceCache( 'id' );
1056 * Get the user name, or the IP for anons
1058 function getName() {
1059 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1060 # Special case optimisation
1061 return $this->mName
;
1064 if ( $this->mName
=== false ) {
1065 $this->mName
= wfGetIP();
1067 return $this->mName
;
1072 * Set the user name.
1074 * This does not reload fields from the database according to the given
1075 * name. Rather, it is used to create a temporary "nonexistent user" for
1076 * later addition to the database. It can also be used to set the IP
1077 * address for an anonymous user to something other than the current
1080 * User::newFromName() has rougly the same function, when the named user
1083 function setName( $str ) {
1085 $this->mName
= $str;
1089 * Return the title dbkey form of the name, for eg user pages.
1093 function getTitleKey() {
1094 return str_replace( ' ', '_', $this->getName() );
1097 function getNewtalk() {
1100 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1101 if( $this->mNewtalk
=== -1 ) {
1102 $this->mNewtalk
= false; # reset talk page status
1104 # Check memcached separately for anons, who have no
1105 # entire User object stored in there.
1108 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1109 $newtalk = $wgMemc->get( $key );
1110 if( is_integer( $newtalk ) ) {
1111 $this->mNewtalk
= (bool)$newtalk;
1113 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
1114 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
1117 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1121 return (bool)$this->mNewtalk
;
1125 * Return the talk page(s) this user has new messages on.
1127 function getNewMessageLinks() {
1129 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1132 if (!$this->getNewtalk())
1134 $up = $this->getUserPage();
1135 $utp = $up->getTalkPage();
1136 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1141 * Perform a user_newtalk check on current slaves; if the memcached data
1142 * is funky we don't want newtalk state to get stuck on save, as that's
1145 * @param string $field
1150 function checkNewtalk( $field, $id ) {
1151 $dbr =& wfGetDB( DB_SLAVE
);
1152 $ok = $dbr->selectField( 'user_newtalk', $field,
1153 array( $field => $id ), __METHOD__
);
1154 return $ok !== false;
1159 * @param string $field
1163 function updateNewtalk( $field, $id ) {
1164 if( $this->checkNewtalk( $field, $id ) ) {
1165 wfDebug( __METHOD__
." already set ($field, $id), ignoring\n" );
1168 $dbw =& wfGetDB( DB_MASTER
);
1169 $dbw->insert( 'user_newtalk',
1170 array( $field => $id ),
1173 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1178 * Clear the new messages flag for the given user
1179 * @param string $field
1183 function deleteNewtalk( $field, $id ) {
1184 if( !$this->checkNewtalk( $field, $id ) ) {
1185 wfDebug( __METHOD__
.": already gone ($field, $id), ignoring\n" );
1188 $dbw =& wfGetDB( DB_MASTER
);
1189 $dbw->delete( 'user_newtalk',
1190 array( $field => $id ),
1192 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1197 * Update the 'You have new messages!' status.
1200 function setNewtalk( $val ) {
1201 if( wfReadOnly() ) {
1206 $this->mNewtalk
= $val;
1208 if( $this->isAnon() ) {
1210 $id = $this->getName();
1213 $id = $this->getId();
1217 $changed = $this->updateNewtalk( $field, $id );
1219 $changed = $this->deleteNewtalk( $field, $id );
1223 if( $this->isAnon() ) {
1224 // Anons have a separate memcached space, since
1225 // user records aren't kept for them.
1227 $key = wfMemcKey( 'newtalk', 'ip', $val );
1228 $wgMemc->set( $key, $val ?
1 : 0 );
1231 // Make sure the user page is watched, so a notification
1232 // will be sent out if enabled.
1233 $this->addWatch( $this->getTalkPage() );
1236 $this->invalidateCache();
1241 * Generate a current or new-future timestamp to be stored in the
1242 * user_touched field when we update things.
1244 private static function newTouchedTimestamp() {
1245 global $wgClockSkewFudge;
1246 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1250 * Clear user data from memcached.
1251 * Use after applying fun updates to the database; caller's
1252 * responsibility to update user_touched if appropriate.
1254 * Called implicitly from invalidateCache() and saveSettings().
1256 private function clearSharedCache() {
1259 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1264 * Immediately touch the user data cache for this account.
1265 * Updates user_touched field, and removes account data from memcached
1266 * for reload on the next hit.
1268 function invalidateCache() {
1271 $this->mTouched
= self
::newTouchedTimestamp();
1273 $dbw =& wfGetDB( DB_MASTER
);
1274 $dbw->update( 'user',
1275 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1276 array( 'user_id' => $this->mId
),
1279 $this->clearSharedCache();
1283 function validateCache( $timestamp ) {
1285 return ($timestamp >= $this->mTouched
);
1289 * Encrypt a password.
1290 * It can eventuall salt a password @see User::addSalt()
1291 * @param string $p clear Password.
1292 * @return string Encrypted password.
1294 function encryptPassword( $p ) {
1296 return wfEncryptPassword( $this->mId
, $p );
1300 * Set the password and reset the random token
1301 * Calls through to authentication plugin if necessary;
1302 * will have no effect if the auth plugin refuses to
1303 * pass the change through or if the legal password
1306 * @param string $str
1307 * @throws PasswordError on failure
1309 function setPassword( $str ) {
1310 global $wgAuth, $wgMinimalPasswordLength;
1312 if( !$wgAuth->allowPasswordChange() ) {
1313 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1316 if( $wgMinimalPasswordLength &&
1317 strlen( $str ) < $wgMinimalPasswordLength ) {
1318 throw new PasswordError( wfMsg( 'passwordtooshort',
1319 $wgMinimalPasswordLength ) );
1322 if( !$wgAuth->setPassword( $this, $str ) ) {
1323 throw new PasswordError( wfMsg( 'externaldberror' ) );
1328 $this->mPassword
= $this->encryptPassword( $str );
1329 $this->mNewpassword
= '';
1330 $this->mNewpassTime
= NULL;
1336 * Set the random token (used for persistent authentication)
1337 * Called from loadDefaults() among other places.
1340 function setToken( $token = false ) {
1341 global $wgSecretKey, $wgProxyKey;
1344 if ( $wgSecretKey ) {
1345 $key = $wgSecretKey;
1346 } elseif ( $wgProxyKey ) {
1351 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1353 $this->mToken
= $token;
1357 function setCookiePassword( $str ) {
1359 $this->mCookiePassword
= md5( $str );
1363 * Set the password for a password reminder or new account email
1364 * Sets the user_newpass_time field if $throttle is true
1366 function setNewpassword( $str, $throttle = true ) {
1368 $this->mNewpassword
= $this->encryptPassword( $str );
1370 $this->mNewpassTime
= wfTimestampNow();
1375 * Returns true if a password reminder email has already been sent within
1376 * the last $wgPasswordReminderResendTime hours
1378 function isPasswordReminderThrottled() {
1379 global $wgPasswordReminderResendTime;
1381 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1384 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1385 return time() < $expiry;
1388 function getEmail() {
1390 return $this->mEmail
;
1393 function getEmailAuthenticationTimestamp() {
1395 return $this->mEmailAuthenticated
;
1398 function setEmail( $str ) {
1400 $this->mEmail
= $str;
1403 function getRealName() {
1405 return $this->mRealName
;
1408 function setRealName( $str ) {
1410 $this->mRealName
= $str;
1414 * @param string $oname The option to check
1417 function getOption( $oname ) {
1419 if ( is_null( $this->mOptions
) ) {
1420 $this->mOptions
= User
::getDefaultOptions();
1422 if ( array_key_exists( $oname, $this->mOptions
) ) {
1423 return trim( $this->mOptions
[$oname] );
1430 * Get the user's date preference, including some important migration for
1433 function getDatePreference() {
1434 if ( is_null( $this->mDatePreference
) ) {
1436 $value = $this->getOption( 'date' );
1437 $map = $wgLang->getDatePreferenceMigrationMap();
1438 if ( isset( $map[$value] ) ) {
1439 $value = $map[$value];
1441 $this->mDatePreference
= $value;
1443 return $this->mDatePreference
;
1447 * @param string $oname The option to check
1448 * @return bool False if the option is not selected, true if it is
1450 function getBoolOption( $oname ) {
1451 return (bool)$this->getOption( $oname );
1455 * Get an option as an integer value from the source string.
1456 * @param string $oname The option to check
1457 * @param int $default Optional value to return if option is unset/blank.
1460 function getIntOption( $oname, $default=0 ) {
1461 $val = $this->getOption( $oname );
1465 return intval( $val );
1468 function setOption( $oname, $val ) {
1470 if ( is_null( $this->mOptions
) ) {
1471 $this->mOptions
= User
::getDefaultOptions();
1473 if ( $oname == 'skin' ) {
1474 # Clear cached skin, so the new one displays immediately in Special:Preferences
1475 unset( $this->mSkin
);
1477 // Filter out any newlines that may have passed through input validation.
1478 // Newlines are used to separate items in the options blob.
1479 $val = str_replace( "\r\n", "\n", $val );
1480 $val = str_replace( "\r", "\n", $val );
1481 $val = str_replace( "\n", " ", $val );
1482 $this->mOptions
[$oname] = $val;
1485 function getRights() {
1486 if ( is_null( $this->mRights
) ) {
1487 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1489 return $this->mRights
;
1493 * Get the list of explicit group memberships this user has.
1494 * The implicit * and user groups are not included.
1495 * @return array of strings
1497 function getGroups() {
1499 return $this->mGroups
;
1503 * Get the list of implicit group memberships this user has.
1504 * This includes all explicit groups, plus 'user' if logged in
1505 * and '*' for all accounts.
1506 * @param boolean $recache Don't use the cache
1507 * @return array of strings
1509 function getEffectiveGroups( $recache = false ) {
1510 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1512 $this->mEffectiveGroups
= $this->mGroups
;
1513 $this->mEffectiveGroups
[] = '*';
1515 $this->mEffectiveGroups
[] = 'user';
1517 global $wgAutoConfirmAge;
1518 $accountAge = time() - wfTimestampOrNull( TS_UNIX
, $this->mRegistration
);
1519 if( $accountAge >= $wgAutoConfirmAge ) {
1520 $this->mEffectiveGroups
[] = 'autoconfirmed';
1523 # Implicit group for users whose email addresses are confirmed
1524 global $wgEmailAuthentication;
1525 if( self
::isValidEmailAddr( $this->mEmail
) ) {
1526 if( $wgEmailAuthentication ) {
1527 if( $this->mEmailAuthenticated
)
1528 $this->mEffectiveGroups
[] = 'emailconfirmed';
1530 $this->mEffectiveGroups
[] = 'emailconfirmed';
1535 return $this->mEffectiveGroups
;
1539 * Add the user to the given group.
1540 * This takes immediate effect.
1543 function addGroup( $group ) {
1545 $dbw =& wfGetDB( DB_MASTER
);
1546 $dbw->insert( 'user_groups',
1548 'ug_user' => $this->getID(),
1549 'ug_group' => $group,
1552 array( 'IGNORE' ) );
1554 $this->mGroups
[] = $group;
1555 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1557 $this->invalidateCache();
1561 * Remove the user from the given group.
1562 * This takes immediate effect.
1565 function removeGroup( $group ) {
1567 $dbw =& wfGetDB( DB_MASTER
);
1568 $dbw->delete( 'user_groups',
1570 'ug_user' => $this->getID(),
1571 'ug_group' => $group,
1573 'User::removeGroup' );
1575 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1576 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1578 $this->invalidateCache();
1583 * A more legible check for non-anonymousness.
1584 * Returns true if the user is not an anonymous visitor.
1588 function isLoggedIn() {
1589 return( $this->getID() != 0 );
1593 * A more legible check for anonymousness.
1594 * Returns true if the user is an anonymous visitor.
1599 return !$this->isLoggedIn();
1603 * Whether the user is a bot
1607 return $this->isAllowed( 'bot' );
1611 * Check if user is allowed to access a feature / make an action
1612 * @param string $action Action to be checked
1613 * @return boolean True: action is allowed, False: action should not be allowed
1615 function isAllowed($action='') {
1616 if ( $action === '' )
1617 // In the spirit of DWIM
1620 return in_array( $action, $this->getRights() );
1624 * Load a skin if it doesn't exist or return it
1625 * @todo FIXME : need to check the old failback system [AV]
1627 function &getSkin() {
1629 if ( ! isset( $this->mSkin
) ) {
1630 wfProfileIn( __METHOD__
);
1633 $userSkin = $this->getOption( 'skin' );
1634 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1636 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1637 wfProfileOut( __METHOD__
);
1639 return $this->mSkin
;
1643 * @param string $title Article title to look at
1647 * Check watched status of an article
1648 * @return bool True if article is watched
1650 function isWatched( $title ) {
1651 $wl = WatchedItem
::fromUserTitle( $this, $title );
1652 return $wl->isWatched();
1658 function addWatch( $title ) {
1659 $wl = WatchedItem
::fromUserTitle( $this, $title );
1661 $this->invalidateCache();
1665 * Stop watching an article
1667 function removeWatch( $title ) {
1668 $wl = WatchedItem
::fromUserTitle( $this, $title );
1670 $this->invalidateCache();
1674 * Clear the user's notification timestamp for the given title.
1675 * If e-notif e-mails are on, they will receive notification mails on
1676 * the next change of the page if it's watched etc.
1678 function clearNotification( &$title ) {
1679 global $wgUser, $wgUseEnotif;
1681 if ($title->getNamespace() == NS_USER_TALK
&&
1682 $title->getText() == $this->getName() ) {
1683 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1685 $this->setNewtalk( false );
1688 if( !$wgUseEnotif ) {
1692 if( $this->isAnon() ) {
1693 // Nothing else to do...
1697 // Only update the timestamp if the page is being watched.
1698 // The query to find out if it is watched is cached both in memcached and per-invocation,
1699 // and when it does have to be executed, it can be on a slave
1700 // If this is the user's newtalk page, we always update the timestamp
1701 if ($title->getNamespace() == NS_USER_TALK
&&
1702 $title->getText() == $wgUser->getName())
1705 } elseif ( $this->getID() == $wgUser->getID() ) {
1706 $watched = $title->userIsWatching();
1711 // If the page is watched by the user (or may be watched), update the timestamp on any
1712 // any matching rows
1714 $dbw =& wfGetDB( DB_MASTER
);
1715 $dbw->update( 'watchlist',
1717 'wl_notificationtimestamp' => NULL
1718 ), array( /* WHERE */
1719 'wl_title' => $title->getDBkey(),
1720 'wl_namespace' => $title->getNamespace(),
1721 'wl_user' => $this->getID()
1722 ), 'User::clearLastVisited'
1730 * Resets all of the given user's page-change notification timestamps.
1731 * If e-notif e-mails are on, they will receive notification mails on
1732 * the next change of any watched page.
1734 * @param int $currentUser user ID number
1737 function clearAllNotifications( $currentUser ) {
1738 global $wgUseEnotif;
1739 if ( !$wgUseEnotif ) {
1740 $this->setNewtalk( false );
1743 if( $currentUser != 0 ) {
1745 $dbw =& wfGetDB( DB_MASTER
);
1746 $dbw->update( 'watchlist',
1748 'wl_notificationtimestamp' => NULL
1749 ), array( /* WHERE */
1750 'wl_user' => $currentUser
1751 ), 'UserMailer::clearAll'
1754 # we also need to clear here the "you have new message" notification for the own user_talk page
1755 # This is cleared one page view later in Article::viewUpdates();
1761 * @return string Encoding options
1763 function encodeOptions() {
1765 if ( is_null( $this->mOptions
) ) {
1766 $this->mOptions
= User
::getDefaultOptions();
1769 foreach ( $this->mOptions
as $oname => $oval ) {
1770 array_push( $a, $oname.'='.$oval );
1772 $s = implode( "\n", $a );
1779 function decodeOptions( $str ) {
1780 $this->mOptions
= array();
1781 $a = explode( "\n", $str );
1782 foreach ( $a as $s ) {
1784 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1785 $this->mOptions
[$m[1]] = $m[2];
1790 function setCookies() {
1791 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1793 if ( 0 == $this->mId
) return;
1794 $exp = time() +
$wgCookieExpiration;
1796 $_SESSION['wsUserID'] = $this->mId
;
1797 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1799 $_SESSION['wsUserName'] = $this->getName();
1800 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1802 $_SESSION['wsToken'] = $this->mToken
;
1803 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1804 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1806 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1812 * Clears the cookies and session, resets the instance cache
1815 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1816 $this->clearInstanceCache( 'defaults' );
1818 $_SESSION['wsUserID'] = 0;
1820 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1821 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1823 # Remember when user logged out, to prevent seeing cached pages
1824 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1828 * Save object settings into database
1829 * @fixme Only rarely do all these fields need to be set!
1831 function saveSettings() {
1833 if ( wfReadOnly() ) { return; }
1834 if ( 0 == $this->mId
) { return; }
1836 $this->mTouched
= self
::newTouchedTimestamp();
1838 $dbw =& wfGetDB( DB_MASTER
);
1839 $dbw->update( 'user',
1841 'user_name' => $this->mName
,
1842 'user_password' => $this->mPassword
,
1843 'user_newpassword' => $this->mNewpassword
,
1844 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
1845 'user_real_name' => $this->mRealName
,
1846 'user_email' => $this->mEmail
,
1847 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1848 'user_options' => $this->encodeOptions(),
1849 'user_touched' => $dbw->timestamp($this->mTouched
),
1850 'user_token' => $this->mToken
1851 ), array( /* WHERE */
1852 'user_id' => $this->mId
1855 $this->clearSharedCache();
1860 * Checks if a user with the given name exists, returns the ID
1862 function idForName() {
1863 $s = trim( $this->getName() );
1864 if ( 0 == strcmp( '', $s ) ) return 0;
1866 $dbr =& wfGetDB( DB_SLAVE
);
1867 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
1868 if ( $id === false ) {
1875 * Add a user to the database, return the user object
1877 * @param string $name The user's name
1878 * @param array $params Associative array of non-default parameters to save to the database:
1879 * password The user's password. Password logins will be disabled if this is omitted.
1880 * newpassword A temporary password mailed to the user
1881 * email The user's email address
1882 * email_authenticated The email authentication timestamp
1883 * real_name The user's real name
1884 * options An associative array of non-default options
1885 * token Random authentication token. Do not set.
1886 * registration Registration timestamp. Do not set.
1888 * @return User object, or null if the username already exists
1890 static function createNew( $name, $params = array() ) {
1893 if ( isset( $params['options'] ) ) {
1894 $user->mOptions
= $params['options'] +
$user->mOptions
;
1895 unset( $params['options'] );
1897 $dbw =& wfGetDB( DB_MASTER
);
1898 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1900 'user_id' => $seqVal,
1901 'user_name' => $name,
1902 'user_password' => $user->mPassword
,
1903 'user_newpassword' => $user->mNewpassword
,
1904 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
1905 'user_email' => $user->mEmail
,
1906 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
1907 'user_real_name' => $user->mRealName
,
1908 'user_options' => $user->encodeOptions(),
1909 'user_token' => $user->mToken
,
1910 'user_registration' => $dbw->timestamp( $user->mRegistration
),
1912 foreach ( $params as $name => $value ) {
1913 $fields["user_$name"] = $value;
1915 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
1916 if ( $dbw->affectedRows() ) {
1917 $newUser = User
::newFromId( $dbw->insertId() );
1925 * Add an existing user object to the database
1927 function addToDatabase() {
1929 $dbw =& wfGetDB( DB_MASTER
);
1930 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1931 $dbw->insert( 'user',
1933 'user_id' => $seqVal,
1934 'user_name' => $this->mName
,
1935 'user_password' => $this->mPassword
,
1936 'user_newpassword' => $this->mNewpassword
,
1937 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
1938 'user_email' => $this->mEmail
,
1939 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1940 'user_real_name' => $this->mRealName
,
1941 'user_options' => $this->encodeOptions(),
1942 'user_token' => $this->mToken
,
1943 'user_registration' => $dbw->timestamp( $this->mRegistration
),
1946 $this->mId
= $dbw->insertId();
1948 # Clear instance cache other than user table data, which is already accurate
1949 $this->clearInstanceCache();
1953 * If the (non-anonymous) user is blocked, this function will block any IP address
1954 * that they successfully log on from.
1956 function spreadBlock() {
1957 wfDebug( __METHOD__
."()\n" );
1959 if ( $this->mId
== 0 ) {
1963 $userblock = Block
::newFromDB( '', $this->mId
);
1964 if ( !$userblock ) {
1968 $userblock->doAutoblock( wfGetIp() );
1973 * Generate a string which will be different for any combination of
1974 * user options which would produce different parser output.
1975 * This will be used as part of the hash key for the parser cache,
1976 * so users will the same options can share the same cached data
1979 * Extensions which require it should install 'PageRenderingHash' hook,
1980 * which will give them a chance to modify this key based on their own
1985 function getPageRenderingHash() {
1986 global $wgContLang, $wgUseDynamicDates;
1988 return $this->mHash
;
1991 // stubthreshold is only included below for completeness,
1992 // it will always be 0 when this function is called by parsercache.
1994 $confstr = $this->getOption( 'math' );
1995 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1996 if ( $wgUseDynamicDates ) {
1997 $confstr .= '!' . $this->getDatePreference();
1999 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2000 $confstr .= '!' . $this->getOption( 'language' );
2001 $confstr .= '!' . $this->getOption( 'thumbsize' );
2002 // add in language specific options, if any
2003 $extra = $wgContLang->getExtraHashOptions();
2006 // Give a chance for extensions to modify the hash, if they have
2007 // extra options or other effects on the parser cache.
2008 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2010 $this->mHash
= $confstr;
2014 function isBlockedFromCreateAccount() {
2015 $this->getBlockedStatus();
2016 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2019 function isAllowedToCreateAccount() {
2020 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2026 function setLoaded( $loaded ) {}
2029 * Get this user's personal page title.
2034 function getUserPage() {
2035 return Title
::makeTitle( NS_USER
, $this->getName() );
2039 * Get this user's talk page title.
2044 function getTalkPage() {
2045 $title = $this->getUserPage();
2046 return $title->getTalkPage();
2052 function getMaxID() {
2053 static $res; // cache
2055 if ( isset( $res ) )
2058 $dbr =& wfGetDB( DB_SLAVE
);
2059 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2064 * Determine whether the user is a newbie. Newbies are either
2065 * anonymous IPs, or the most recently created accounts.
2066 * @return bool True if it is a newbie.
2068 function isNewbie() {
2069 return !$this->isAllowed( 'autoconfirmed' );
2073 * Check to see if the given clear-text password is one of the accepted passwords
2074 * @param string $password User password.
2075 * @return bool True if the given password is correct otherwise False.
2077 function checkPassword( $password ) {
2078 global $wgAuth, $wgMinimalPasswordLength;
2081 // Even though we stop people from creating passwords that
2082 // are shorter than this, doesn't mean people wont be able
2083 // to. Certain authentication plugins do NOT want to save
2084 // domain passwords in a mysql database, so we should
2085 // check this (incase $wgAuth->strict() is false).
2086 if( strlen( $password ) < $wgMinimalPasswordLength ) {
2090 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2092 } elseif( $wgAuth->strict() ) {
2093 /* Auth plugin doesn't allow local authentication */
2096 $ep = $this->encryptPassword( $password );
2097 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2099 } elseif ( function_exists( 'iconv' ) ) {
2100 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2101 # Check for this with iconv
2102 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2103 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2111 * Check if the given clear-text password matches the temporary password
2112 * sent by e-mail for password reset operations.
2115 function checkTemporaryPassword( $plaintext ) {
2116 $hash = $this->encryptPassword( $plaintext );
2117 return $hash === $this->mNewpassword
;
2121 * Initialize (if necessary) and return a session token value
2122 * which can be used in edit forms to show that the user's
2123 * login credentials aren't being hijacked with a foreign form
2126 * @param mixed $salt - Optional function-specific data for hash.
2127 * Use a string or an array of strings.
2131 function editToken( $salt = '' ) {
2132 if( !isset( $_SESSION['wsEditToken'] ) ) {
2133 $token = $this->generateToken();
2134 $_SESSION['wsEditToken'] = $token;
2136 $token = $_SESSION['wsEditToken'];
2138 if( is_array( $salt ) ) {
2139 $salt = implode( '|', $salt );
2141 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2145 * Generate a hex-y looking random token for various uses.
2146 * Could be made more cryptographically sure if someone cares.
2149 function generateToken( $salt = '' ) {
2150 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2151 return md5( $token . $salt );
2155 * Check given value against the token value stored in the session.
2156 * A match should confirm that the form was submitted from the
2157 * user's own login session, not a form submission from a third-party
2160 * @param string $val - the input value to compare
2161 * @param string $salt - Optional function-specific data for hash
2165 function matchEditToken( $val, $salt = '' ) {
2167 $sessionToken = $this->editToken( $salt );
2168 if ( $val != $sessionToken ) {
2169 wfDebug( "User::matchEditToken: broken session data\n" );
2171 return $val == $sessionToken;
2175 * Generate a new e-mail confirmation token and send a confirmation
2176 * mail to the user's given address.
2178 * @return mixed True on success, a WikiError object on failure.
2180 function sendConfirmationMail() {
2182 $expiration = null; // gets passed-by-ref and defined in next line.
2183 $url = $this->confirmationTokenUrl( $expiration );
2184 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2185 wfMsg( 'confirmemail_body',
2189 $wgContLang->timeanddate( $expiration, false ) ) );
2193 * Send an e-mail to this user's account. Does not check for
2194 * confirmed status or validity.
2196 * @param string $subject
2197 * @param string $body
2198 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2199 * @return mixed True on success, a WikiError object on failure.
2201 function sendMail( $subject, $body, $from = null ) {
2202 if( is_null( $from ) ) {
2203 global $wgPasswordSender;
2204 $from = $wgPasswordSender;
2207 require_once( 'UserMailer.php' );
2208 $to = new MailAddress( $this );
2209 $sender = new MailAddress( $from );
2210 $error = userMailer( $to, $sender, $subject, $body );
2212 if( $error == '' ) {
2215 return new WikiError( $error );
2220 * Generate, store, and return a new e-mail confirmation code.
2221 * A hash (unsalted since it's used as a key) is stored.
2222 * @param &$expiration mixed output: accepts the expiration time
2226 function confirmationToken( &$expiration ) {
2228 $expires = $now +
7 * 24 * 60 * 60;
2229 $expiration = wfTimestamp( TS_MW
, $expires );
2231 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2232 $hash = md5( $token );
2234 $dbw =& wfGetDB( DB_MASTER
);
2235 $dbw->update( 'user',
2236 array( 'user_email_token' => $hash,
2237 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2238 array( 'user_id' => $this->mId
),
2245 * Generate and store a new e-mail confirmation token, and return
2246 * the URL the user can use to confirm.
2247 * @param &$expiration mixed output: accepts the expiration time
2251 function confirmationTokenUrl( &$expiration ) {
2252 $token = $this->confirmationToken( $expiration );
2253 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2254 return $title->getFullUrl();
2258 * Mark the e-mail address confirmed and save.
2260 function confirmEmail() {
2262 $this->mEmailAuthenticated
= wfTimestampNow();
2263 $this->saveSettings();
2268 * Is this user allowed to send e-mails within limits of current
2269 * site configuration?
2272 function canSendEmail() {
2273 return $this->isEmailConfirmed();
2277 * Is this user allowed to receive e-mails within limits of current
2278 * site configuration?
2281 function canReceiveEmail() {
2282 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2286 * Is this user's e-mail address valid-looking and confirmed within
2287 * limits of the current site configuration?
2289 * If $wgEmailAuthentication is on, this may require the user to have
2290 * confirmed their address by returning a code or using a password
2291 * sent to the address from the wiki.
2295 function isEmailConfirmed() {
2296 global $wgEmailAuthentication;
2299 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2300 if( $this->isAnon() )
2302 if( !self
::isValidEmailAddr( $this->mEmail
) )
2304 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2313 * @param array $groups list of groups
2314 * @return array list of permission key names for given groups combined
2317 static function getGroupPermissions( $groups ) {
2318 global $wgGroupPermissions;
2320 foreach( $groups as $group ) {
2321 if( isset( $wgGroupPermissions[$group] ) ) {
2322 $rights = array_merge( $rights,
2323 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2330 * @param string $group key name
2331 * @return string localized descriptive name for group, if provided
2334 static function getGroupName( $group ) {
2335 $key = "group-$group";
2336 $name = wfMsg( $key );
2337 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2345 * @param string $group key name
2346 * @return string localized descriptive name for member of a group, if provided
2349 static function getGroupMember( $group ) {
2350 $key = "group-$group-member";
2351 $name = wfMsg( $key );
2352 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2360 * Return the set of defined explicit groups.
2361 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2362 * groups are not included, as they are defined
2363 * automatically, not in the database.
2367 static function getAllGroups() {
2368 global $wgGroupPermissions;
2370 array_keys( $wgGroupPermissions ),
2371 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2375 * Get the title of a page describing a particular group
2377 * @param $group Name of the group
2380 static function getGroupPage( $group ) {
2381 $page = wfMsgForContent( 'grouppage-' . $group );
2382 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2383 $title = Title
::newFromText( $page );
2384 if( is_object( $title ) )
2391 * Create a link to the group in HTML, if available
2393 * @param $group Name of the group
2394 * @param $text The text of the link
2397 static function makeGroupLinkHTML( $group, $text = '' ) {
2399 $text = self
::getGroupName( $group );
2401 $title = self
::getGroupPage( $group );
2404 $sk = $wgUser->getSkin();
2405 return $sk->makeLinkObj( $title, $text );
2412 * Create a link to the group in Wikitext, if available
2414 * @param $group Name of the group
2415 * @param $text The text of the link (by default, the name of the group)
2418 static function makeGroupLinkWiki( $group, $text = '' ) {
2420 $text = self
::getGroupName( $group );
2422 $title = self
::getGroupPage( $group );
2424 $page = $title->getPrefixedText();
2425 return "[[$page|$text]]";