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',
58 'enotifwatchlistpages',
59 'enotifusertalkpages',
62 '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_MASTER
);
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' ) {
924 # Call the 'PingLimiter' hook
926 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
930 global $wgRateLimits, $wgRateLimitsExcludedGroups;
931 if( !isset( $wgRateLimits[$action] ) ) {
935 # Some groups shouldn't trigger the ping limiter, ever
936 foreach( $this->getGroups() as $group ) {
937 if( array_search( $group, $wgRateLimitsExcludedGroups ) !== false )
941 global $wgMemc, $wgRateLimitLog;
942 wfProfileIn( __METHOD__
);
944 $limits = $wgRateLimits[$action];
946 $id = $this->getId();
949 if( isset( $limits['anon'] ) && $id == 0 ) {
950 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
953 if( isset( $limits['user'] ) && $id != 0 ) {
954 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
956 if( $this->isNewbie() ) {
957 if( isset( $limits['newbie'] ) && $id != 0 ) {
958 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
960 if( isset( $limits['ip'] ) ) {
961 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
964 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
965 $subnet = $matches[1];
966 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
971 foreach( $keys as $key => $limit ) {
972 list( $max, $period ) = $limit;
973 $summary = "(limit $max in {$period}s)";
974 $count = $wgMemc->get( $key );
976 if( $count > $max ) {
977 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
978 if( $wgRateLimitLog ) {
979 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
983 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
986 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
987 $wgMemc->add( $key, 1, intval( $period ) );
989 $wgMemc->incr( $key );
992 wfProfileOut( __METHOD__
);
997 * Check if user is blocked
998 * @return bool True if blocked, false otherwise
1000 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1001 wfDebug( "User::isBlocked: enter\n" );
1002 $this->getBlockedStatus( $bFromSlave );
1003 return $this->mBlockedby
!== 0;
1007 * Check if user is blocked from editing a particular article
1009 function isBlockedFrom( $title, $bFromSlave = false ) {
1010 global $wgBlockAllowsUTEdit;
1011 wfProfileIn( __METHOD__
);
1012 wfDebug( __METHOD__
.": enter\n" );
1014 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1015 $title->getNamespace() == NS_USER_TALK
)
1018 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1020 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1021 $blocked = $this->isBlocked( $bFromSlave );
1023 wfProfileOut( __METHOD__
);
1028 * Get name of blocker
1029 * @return string name of blocker
1031 function blockedBy() {
1032 $this->getBlockedStatus();
1033 return $this->mBlockedby
;
1037 * Get blocking reason
1038 * @return string Blocking reason
1040 function blockedFor() {
1041 $this->getBlockedStatus();
1042 return $this->mBlockreason
;
1046 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1054 * Set the user and reload all fields according to that ID
1055 * @deprecated use User::newFromId()
1057 function setID( $v ) {
1059 $this->clearInstanceCache( 'id' );
1063 * Get the user name, or the IP for anons
1065 function getName() {
1066 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1067 # Special case optimisation
1068 return $this->mName
;
1071 if ( $this->mName
=== false ) {
1072 $this->mName
= wfGetIP();
1074 return $this->mName
;
1079 * Set the user name.
1081 * This does not reload fields from the database according to the given
1082 * name. Rather, it is used to create a temporary "nonexistent user" for
1083 * later addition to the database. It can also be used to set the IP
1084 * address for an anonymous user to something other than the current
1087 * User::newFromName() has rougly the same function, when the named user
1090 function setName( $str ) {
1092 $this->mName
= $str;
1096 * Return the title dbkey form of the name, for eg user pages.
1100 function getTitleKey() {
1101 return str_replace( ' ', '_', $this->getName() );
1104 function getNewtalk() {
1107 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1108 if( $this->mNewtalk
=== -1 ) {
1109 $this->mNewtalk
= false; # reset talk page status
1111 # Check memcached separately for anons, who have no
1112 # entire User object stored in there.
1115 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1116 $newtalk = $wgMemc->get( $key );
1117 if( is_integer( $newtalk ) ) {
1118 $this->mNewtalk
= (bool)$newtalk;
1120 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
1121 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
1124 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1128 return (bool)$this->mNewtalk
;
1132 * Return the talk page(s) this user has new messages on.
1134 function getNewMessageLinks() {
1136 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1139 if (!$this->getNewtalk())
1141 $up = $this->getUserPage();
1142 $utp = $up->getTalkPage();
1143 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1148 * Perform a user_newtalk check on current slaves; if the memcached data
1149 * is funky we don't want newtalk state to get stuck on save, as that's
1152 * @param string $field
1157 function checkNewtalk( $field, $id ) {
1158 $dbr =& wfGetDB( DB_SLAVE
);
1159 $ok = $dbr->selectField( 'user_newtalk', $field,
1160 array( $field => $id ), __METHOD__
);
1161 return $ok !== false;
1166 * @param string $field
1170 function updateNewtalk( $field, $id ) {
1171 if( $this->checkNewtalk( $field, $id ) ) {
1172 wfDebug( __METHOD__
." already set ($field, $id), ignoring\n" );
1175 $dbw =& wfGetDB( DB_MASTER
);
1176 $dbw->insert( 'user_newtalk',
1177 array( $field => $id ),
1180 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1185 * Clear the new messages flag for the given user
1186 * @param string $field
1190 function deleteNewtalk( $field, $id ) {
1191 if( !$this->checkNewtalk( $field, $id ) ) {
1192 wfDebug( __METHOD__
.": already gone ($field, $id), ignoring\n" );
1195 $dbw =& wfGetDB( DB_MASTER
);
1196 $dbw->delete( 'user_newtalk',
1197 array( $field => $id ),
1199 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1204 * Update the 'You have new messages!' status.
1207 function setNewtalk( $val ) {
1208 if( wfReadOnly() ) {
1213 $this->mNewtalk
= $val;
1215 if( $this->isAnon() ) {
1217 $id = $this->getName();
1220 $id = $this->getId();
1224 $changed = $this->updateNewtalk( $field, $id );
1226 $changed = $this->deleteNewtalk( $field, $id );
1230 if( $this->isAnon() ) {
1231 // Anons have a separate memcached space, since
1232 // user records aren't kept for them.
1234 $key = wfMemcKey( 'newtalk', 'ip', $val );
1235 $wgMemc->set( $key, $val ?
1 : 0 );
1238 // Make sure the user page is watched, so a notification
1239 // will be sent out if enabled.
1240 $this->addWatch( $this->getTalkPage() );
1243 $this->invalidateCache();
1248 * Generate a current or new-future timestamp to be stored in the
1249 * user_touched field when we update things.
1251 private static function newTouchedTimestamp() {
1252 global $wgClockSkewFudge;
1253 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1257 * Clear user data from memcached.
1258 * Use after applying fun updates to the database; caller's
1259 * responsibility to update user_touched if appropriate.
1261 * Called implicitly from invalidateCache() and saveSettings().
1263 private function clearSharedCache() {
1266 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1271 * Immediately touch the user data cache for this account.
1272 * Updates user_touched field, and removes account data from memcached
1273 * for reload on the next hit.
1275 function invalidateCache() {
1278 $this->mTouched
= self
::newTouchedTimestamp();
1280 $dbw =& wfGetDB( DB_MASTER
);
1281 $dbw->update( 'user',
1282 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1283 array( 'user_id' => $this->mId
),
1286 $this->clearSharedCache();
1290 function validateCache( $timestamp ) {
1292 return ($timestamp >= $this->mTouched
);
1296 * Encrypt a password.
1297 * It can eventuall salt a password @see User::addSalt()
1298 * @param string $p clear Password.
1299 * @return string Encrypted password.
1301 function encryptPassword( $p ) {
1303 return wfEncryptPassword( $this->mId
, $p );
1307 * Set the password and reset the random token
1308 * Calls through to authentication plugin if necessary;
1309 * will have no effect if the auth plugin refuses to
1310 * pass the change through or if the legal password
1313 * As a special case, setting the password to null
1314 * wipes it, so the account cannot be logged in until
1315 * a new password is set, for instance via e-mail.
1317 * @param string $str
1318 * @throws PasswordError on failure
1320 function setPassword( $str ) {
1323 if( $str !== null ) {
1324 if( !$wgAuth->allowPasswordChange() ) {
1325 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1328 if( !$this->isValidPassword( $str ) ) {
1329 global $wgMinimalPasswordLength;
1330 throw new PasswordError( wfMsg( 'passwordtooshort',
1331 $wgMinimalPasswordLength ) );
1335 if( !$wgAuth->setPassword( $this, $str ) ) {
1336 throw new PasswordError( wfMsg( 'externaldberror' ) );
1342 if( $str === null ) {
1343 // Save an invalid hash...
1344 $this->mPassword
= '';
1346 $this->mPassword
= $this->encryptPassword( $str );
1348 $this->mNewpassword
= '';
1349 $this->mNewpassTime
= null;
1355 * Set the random token (used for persistent authentication)
1356 * Called from loadDefaults() among other places.
1359 function setToken( $token = false ) {
1360 global $wgSecretKey, $wgProxyKey;
1363 if ( $wgSecretKey ) {
1364 $key = $wgSecretKey;
1365 } elseif ( $wgProxyKey ) {
1370 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1372 $this->mToken
= $token;
1376 function setCookiePassword( $str ) {
1378 $this->mCookiePassword
= md5( $str );
1382 * Set the password for a password reminder or new account email
1383 * Sets the user_newpass_time field if $throttle is true
1385 function setNewpassword( $str, $throttle = true ) {
1387 $this->mNewpassword
= $this->encryptPassword( $str );
1389 $this->mNewpassTime
= wfTimestampNow();
1394 * Returns true if a password reminder email has already been sent within
1395 * the last $wgPasswordReminderResendTime hours
1397 function isPasswordReminderThrottled() {
1398 global $wgPasswordReminderResendTime;
1400 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1403 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1404 return time() < $expiry;
1407 function getEmail() {
1409 return $this->mEmail
;
1412 function getEmailAuthenticationTimestamp() {
1414 return $this->mEmailAuthenticated
;
1417 function setEmail( $str ) {
1419 $this->mEmail
= $str;
1422 function getRealName() {
1424 return $this->mRealName
;
1427 function setRealName( $str ) {
1429 $this->mRealName
= $str;
1433 * @param string $oname The option to check
1434 * @param string $defaultOverride A default value returned if the option does not exist
1437 function getOption( $oname, $defaultOverride = '' ) {
1440 if ( is_null( $this->mOptions
) ) {
1441 if($defaultOverride != '') {
1442 return $defaultOverride;
1444 $this->mOptions
= User
::getDefaultOptions();
1447 if ( array_key_exists( $oname, $this->mOptions
) ) {
1448 return trim( $this->mOptions
[$oname] );
1450 return $defaultOverride;
1455 * Get the user's date preference, including some important migration for
1458 function getDatePreference() {
1459 if ( is_null( $this->mDatePreference
) ) {
1461 $value = $this->getOption( 'date' );
1462 $map = $wgLang->getDatePreferenceMigrationMap();
1463 if ( isset( $map[$value] ) ) {
1464 $value = $map[$value];
1466 $this->mDatePreference
= $value;
1468 return $this->mDatePreference
;
1472 * @param string $oname The option to check
1473 * @return bool False if the option is not selected, true if it is
1475 function getBoolOption( $oname ) {
1476 return (bool)$this->getOption( $oname );
1480 * Get an option as an integer value from the source string.
1481 * @param string $oname The option to check
1482 * @param int $default Optional value to return if option is unset/blank.
1485 function getIntOption( $oname, $default=0 ) {
1486 $val = $this->getOption( $oname );
1490 return intval( $val );
1493 function setOption( $oname, $val ) {
1495 if ( is_null( $this->mOptions
) ) {
1496 $this->mOptions
= User
::getDefaultOptions();
1498 if ( $oname == 'skin' ) {
1499 # Clear cached skin, so the new one displays immediately in Special:Preferences
1500 unset( $this->mSkin
);
1502 // Filter out any newlines that may have passed through input validation.
1503 // Newlines are used to separate items in the options blob.
1504 $val = str_replace( "\r\n", "\n", $val );
1505 $val = str_replace( "\r", "\n", $val );
1506 $val = str_replace( "\n", " ", $val );
1507 $this->mOptions
[$oname] = $val;
1510 function getRights() {
1511 if ( is_null( $this->mRights
) ) {
1512 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1514 return $this->mRights
;
1518 * Get the list of explicit group memberships this user has.
1519 * The implicit * and user groups are not included.
1520 * @return array of strings
1522 function getGroups() {
1524 return $this->mGroups
;
1528 * Get the list of implicit group memberships this user has.
1529 * This includes all explicit groups, plus 'user' if logged in
1530 * and '*' for all accounts.
1531 * @param boolean $recache Don't use the cache
1532 * @return array of strings
1534 function getEffectiveGroups( $recache = false ) {
1535 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1537 $this->mEffectiveGroups
= $this->mGroups
;
1538 $this->mEffectiveGroups
[] = '*';
1540 $this->mEffectiveGroups
[] = 'user';
1542 global $wgAutoConfirmAge;
1543 $accountAge = time() - wfTimestampOrNull( TS_UNIX
, $this->mRegistration
);
1544 if( $accountAge >= $wgAutoConfirmAge ) {
1545 $this->mEffectiveGroups
[] = 'autoconfirmed';
1548 # Implicit group for users whose email addresses are confirmed
1549 global $wgEmailAuthentication;
1550 if( self
::isValidEmailAddr( $this->mEmail
) ) {
1551 if( $wgEmailAuthentication ) {
1552 if( $this->mEmailAuthenticated
)
1553 $this->mEffectiveGroups
[] = 'emailconfirmed';
1555 $this->mEffectiveGroups
[] = 'emailconfirmed';
1560 return $this->mEffectiveGroups
;
1564 * Add the user to the given group.
1565 * This takes immediate effect.
1568 function addGroup( $group ) {
1570 $dbw =& wfGetDB( DB_MASTER
);
1571 $dbw->insert( 'user_groups',
1573 'ug_user' => $this->getID(),
1574 'ug_group' => $group,
1577 array( 'IGNORE' ) );
1579 $this->mGroups
[] = $group;
1580 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1582 $this->invalidateCache();
1586 * Remove the user from the given group.
1587 * This takes immediate effect.
1590 function removeGroup( $group ) {
1592 $dbw =& wfGetDB( DB_MASTER
);
1593 $dbw->delete( 'user_groups',
1595 'ug_user' => $this->getID(),
1596 'ug_group' => $group,
1598 'User::removeGroup' );
1600 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1601 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1603 $this->invalidateCache();
1608 * A more legible check for non-anonymousness.
1609 * Returns true if the user is not an anonymous visitor.
1613 function isLoggedIn() {
1614 return( $this->getID() != 0 );
1618 * A more legible check for anonymousness.
1619 * Returns true if the user is an anonymous visitor.
1624 return !$this->isLoggedIn();
1628 * Whether the user is a bot
1632 return $this->isAllowed( 'bot' );
1636 * Check if user is allowed to access a feature / make an action
1637 * @param string $action Action to be checked
1638 * @return boolean True: action is allowed, False: action should not be allowed
1640 function isAllowed($action='') {
1641 if ( $action === '' )
1642 // In the spirit of DWIM
1645 return in_array( $action, $this->getRights() );
1649 * Load a skin if it doesn't exist or return it
1650 * @todo FIXME : need to check the old failback system [AV]
1652 function &getSkin() {
1654 if ( ! isset( $this->mSkin
) ) {
1655 wfProfileIn( __METHOD__
);
1658 $userSkin = $this->getOption( 'skin' );
1659 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1661 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1662 wfProfileOut( __METHOD__
);
1664 return $this->mSkin
;
1668 * @param string $title Article title to look at
1672 * Check watched status of an article
1673 * @return bool True if article is watched
1675 function isWatched( $title ) {
1676 $wl = WatchedItem
::fromUserTitle( $this, $title );
1677 return $wl->isWatched();
1683 function addWatch( $title ) {
1684 $wl = WatchedItem
::fromUserTitle( $this, $title );
1686 $this->invalidateCache();
1690 * Stop watching an article
1692 function removeWatch( $title ) {
1693 $wl = WatchedItem
::fromUserTitle( $this, $title );
1695 $this->invalidateCache();
1699 * Clear the user's notification timestamp for the given title.
1700 * If e-notif e-mails are on, they will receive notification mails on
1701 * the next change of the page if it's watched etc.
1703 function clearNotification( &$title ) {
1704 global $wgUser, $wgUseEnotif;
1706 if ($title->getNamespace() == NS_USER_TALK
&&
1707 $title->getText() == $this->getName() ) {
1708 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1710 $this->setNewtalk( false );
1713 if( !$wgUseEnotif ) {
1717 if( $this->isAnon() ) {
1718 // Nothing else to do...
1722 // Only update the timestamp if the page is being watched.
1723 // The query to find out if it is watched is cached both in memcached and per-invocation,
1724 // and when it does have to be executed, it can be on a slave
1725 // If this is the user's newtalk page, we always update the timestamp
1726 if ($title->getNamespace() == NS_USER_TALK
&&
1727 $title->getText() == $wgUser->getName())
1730 } elseif ( $this->getID() == $wgUser->getID() ) {
1731 $watched = $title->userIsWatching();
1736 // If the page is watched by the user (or may be watched), update the timestamp on any
1737 // any matching rows
1739 $dbw =& wfGetDB( DB_MASTER
);
1740 $dbw->update( 'watchlist',
1742 'wl_notificationtimestamp' => NULL
1743 ), array( /* WHERE */
1744 'wl_title' => $title->getDBkey(),
1745 'wl_namespace' => $title->getNamespace(),
1746 'wl_user' => $this->getID()
1747 ), 'User::clearLastVisited'
1755 * Resets all of the given user's page-change notification timestamps.
1756 * If e-notif e-mails are on, they will receive notification mails on
1757 * the next change of any watched page.
1759 * @param int $currentUser user ID number
1762 function clearAllNotifications( $currentUser ) {
1763 global $wgUseEnotif;
1764 if ( !$wgUseEnotif ) {
1765 $this->setNewtalk( false );
1768 if( $currentUser != 0 ) {
1770 $dbw =& wfGetDB( DB_MASTER
);
1771 $dbw->update( 'watchlist',
1773 'wl_notificationtimestamp' => NULL
1774 ), array( /* WHERE */
1775 'wl_user' => $currentUser
1776 ), 'UserMailer::clearAll'
1779 # we also need to clear here the "you have new message" notification for the own user_talk page
1780 # This is cleared one page view later in Article::viewUpdates();
1786 * @return string Encoding options
1788 function encodeOptions() {
1790 if ( is_null( $this->mOptions
) ) {
1791 $this->mOptions
= User
::getDefaultOptions();
1794 foreach ( $this->mOptions
as $oname => $oval ) {
1795 array_push( $a, $oname.'='.$oval );
1797 $s = implode( "\n", $a );
1804 function decodeOptions( $str ) {
1805 $this->mOptions
= array();
1806 $a = explode( "\n", $str );
1807 foreach ( $a as $s ) {
1809 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1810 $this->mOptions
[$m[1]] = $m[2];
1815 function setCookies() {
1816 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1818 if ( 0 == $this->mId
) return;
1819 $exp = time() +
$wgCookieExpiration;
1821 $_SESSION['wsUserID'] = $this->mId
;
1822 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1824 $_SESSION['wsUserName'] = $this->getName();
1825 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1827 $_SESSION['wsToken'] = $this->mToken
;
1828 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1829 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1831 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1837 * Clears the cookies and session, resets the instance cache
1840 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1841 $this->clearInstanceCache( 'defaults' );
1843 $_SESSION['wsUserID'] = 0;
1845 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1846 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1848 # Remember when user logged out, to prevent seeing cached pages
1849 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1853 * Save object settings into database
1854 * @fixme Only rarely do all these fields need to be set!
1856 function saveSettings() {
1858 if ( wfReadOnly() ) { return; }
1859 if ( 0 == $this->mId
) { return; }
1861 $this->mTouched
= self
::newTouchedTimestamp();
1863 $dbw =& wfGetDB( DB_MASTER
);
1864 $dbw->update( 'user',
1866 'user_name' => $this->mName
,
1867 'user_password' => $this->mPassword
,
1868 'user_newpassword' => $this->mNewpassword
,
1869 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
1870 'user_real_name' => $this->mRealName
,
1871 'user_email' => $this->mEmail
,
1872 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1873 'user_options' => $this->encodeOptions(),
1874 'user_touched' => $dbw->timestamp($this->mTouched
),
1875 'user_token' => $this->mToken
1876 ), array( /* WHERE */
1877 'user_id' => $this->mId
1880 $this->clearSharedCache();
1885 * Checks if a user with the given name exists, returns the ID
1887 function idForName() {
1888 $s = trim( $this->getName() );
1889 if ( 0 == strcmp( '', $s ) ) return 0;
1891 $dbr =& wfGetDB( DB_SLAVE
);
1892 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
1893 if ( $id === false ) {
1900 * Add a user to the database, return the user object
1902 * @param string $name The user's name
1903 * @param array $params Associative array of non-default parameters to save to the database:
1904 * password The user's password. Password logins will be disabled if this is omitted.
1905 * newpassword A temporary password mailed to the user
1906 * email The user's email address
1907 * email_authenticated The email authentication timestamp
1908 * real_name The user's real name
1909 * options An associative array of non-default options
1910 * token Random authentication token. Do not set.
1911 * registration Registration timestamp. Do not set.
1913 * @return User object, or null if the username already exists
1915 static function createNew( $name, $params = array() ) {
1918 if ( isset( $params['options'] ) ) {
1919 $user->mOptions
= $params['options'] +
$user->mOptions
;
1920 unset( $params['options'] );
1922 $dbw =& wfGetDB( DB_MASTER
);
1923 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1925 'user_id' => $seqVal,
1926 'user_name' => $name,
1927 'user_password' => $user->mPassword
,
1928 'user_newpassword' => $user->mNewpassword
,
1929 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
1930 'user_email' => $user->mEmail
,
1931 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
1932 'user_real_name' => $user->mRealName
,
1933 'user_options' => $user->encodeOptions(),
1934 'user_token' => $user->mToken
,
1935 'user_registration' => $dbw->timestamp( $user->mRegistration
),
1936 'user_editcount' => 0,
1938 foreach ( $params as $name => $value ) {
1939 $fields["user_$name"] = $value;
1941 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
1942 if ( $dbw->affectedRows() ) {
1943 $newUser = User
::newFromId( $dbw->insertId() );
1951 * Add an existing user object to the database
1953 function addToDatabase() {
1955 $dbw =& wfGetDB( DB_MASTER
);
1956 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1957 $dbw->insert( 'user',
1959 'user_id' => $seqVal,
1960 'user_name' => $this->mName
,
1961 'user_password' => $this->mPassword
,
1962 'user_newpassword' => $this->mNewpassword
,
1963 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
1964 'user_email' => $this->mEmail
,
1965 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1966 'user_real_name' => $this->mRealName
,
1967 'user_options' => $this->encodeOptions(),
1968 'user_token' => $this->mToken
,
1969 'user_registration' => $dbw->timestamp( $this->mRegistration
),
1970 'user_editcount' => 0,
1973 $this->mId
= $dbw->insertId();
1975 # Clear instance cache other than user table data, which is already accurate
1976 $this->clearInstanceCache();
1980 * If the (non-anonymous) user is blocked, this function will block any IP address
1981 * that they successfully log on from.
1983 function spreadBlock() {
1984 wfDebug( __METHOD__
."()\n" );
1986 if ( $this->mId
== 0 ) {
1990 $userblock = Block
::newFromDB( '', $this->mId
);
1991 if ( !$userblock ) {
1995 $userblock->doAutoblock( wfGetIp() );
2000 * Generate a string which will be different for any combination of
2001 * user options which would produce different parser output.
2002 * This will be used as part of the hash key for the parser cache,
2003 * so users will the same options can share the same cached data
2006 * Extensions which require it should install 'PageRenderingHash' hook,
2007 * which will give them a chance to modify this key based on their own
2012 function getPageRenderingHash() {
2013 global $wgContLang, $wgUseDynamicDates;
2015 return $this->mHash
;
2018 // stubthreshold is only included below for completeness,
2019 // it will always be 0 when this function is called by parsercache.
2021 $confstr = $this->getOption( 'math' );
2022 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2023 if ( $wgUseDynamicDates ) {
2024 $confstr .= '!' . $this->getDatePreference();
2026 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2027 $confstr .= '!' . $this->getOption( 'language' );
2028 $confstr .= '!' . $this->getOption( 'thumbsize' );
2029 // add in language specific options, if any
2030 $extra = $wgContLang->getExtraHashOptions();
2033 // Give a chance for extensions to modify the hash, if they have
2034 // extra options or other effects on the parser cache.
2035 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2037 $this->mHash
= $confstr;
2041 function isBlockedFromCreateAccount() {
2042 $this->getBlockedStatus();
2043 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2046 function isAllowedToCreateAccount() {
2047 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2053 function setLoaded( $loaded ) {}
2056 * Get this user's personal page title.
2061 function getUserPage() {
2062 return Title
::makeTitle( NS_USER
, $this->getName() );
2066 * Get this user's talk page title.
2071 function getTalkPage() {
2072 $title = $this->getUserPage();
2073 return $title->getTalkPage();
2079 function getMaxID() {
2080 static $res; // cache
2082 if ( isset( $res ) )
2085 $dbr =& wfGetDB( DB_SLAVE
);
2086 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2091 * Determine whether the user is a newbie. Newbies are either
2092 * anonymous IPs, or the most recently created accounts.
2093 * @return bool True if it is a newbie.
2095 function isNewbie() {
2096 return !$this->isAllowed( 'autoconfirmed' );
2100 * Check to see if the given clear-text password is one of the accepted passwords
2101 * @param string $password User password.
2102 * @return bool True if the given password is correct otherwise False.
2104 function checkPassword( $password ) {
2108 // Even though we stop people from creating passwords that
2109 // are shorter than this, doesn't mean people wont be able
2110 // to. Certain authentication plugins do NOT want to save
2111 // domain passwords in a mysql database, so we should
2112 // check this (incase $wgAuth->strict() is false).
2113 if( !$this->isValidPassword( $password ) ) {
2117 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2119 } elseif( $wgAuth->strict() ) {
2120 /* Auth plugin doesn't allow local authentication */
2123 $ep = $this->encryptPassword( $password );
2124 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2126 } elseif ( function_exists( 'iconv' ) ) {
2127 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2128 # Check for this with iconv
2129 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2130 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2138 * Check if the given clear-text password matches the temporary password
2139 * sent by e-mail for password reset operations.
2142 function checkTemporaryPassword( $plaintext ) {
2143 $hash = $this->encryptPassword( $plaintext );
2144 return $hash === $this->mNewpassword
;
2148 * Initialize (if necessary) and return a session token value
2149 * which can be used in edit forms to show that the user's
2150 * login credentials aren't being hijacked with a foreign form
2153 * @param mixed $salt - Optional function-specific data for hash.
2154 * Use a string or an array of strings.
2158 function editToken( $salt = '' ) {
2159 if( !isset( $_SESSION['wsEditToken'] ) ) {
2160 $token = $this->generateToken();
2161 $_SESSION['wsEditToken'] = $token;
2163 $token = $_SESSION['wsEditToken'];
2165 if( is_array( $salt ) ) {
2166 $salt = implode( '|', $salt );
2168 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2172 * Generate a hex-y looking random token for various uses.
2173 * Could be made more cryptographically sure if someone cares.
2176 function generateToken( $salt = '' ) {
2177 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2178 return md5( $token . $salt );
2182 * Check given value against the token value stored in the session.
2183 * A match should confirm that the form was submitted from the
2184 * user's own login session, not a form submission from a third-party
2187 * @param string $val - the input value to compare
2188 * @param string $salt - Optional function-specific data for hash
2192 function matchEditToken( $val, $salt = '' ) {
2194 $sessionToken = $this->editToken( $salt );
2195 if ( $val != $sessionToken ) {
2196 wfDebug( "User::matchEditToken: broken session data\n" );
2198 return $val == $sessionToken;
2202 * Generate a new e-mail confirmation token and send a confirmation
2203 * mail to the user's given address.
2205 * @return mixed True on success, a WikiError object on failure.
2207 function sendConfirmationMail() {
2209 $expiration = null; // gets passed-by-ref and defined in next line.
2210 $url = $this->confirmationTokenUrl( $expiration );
2211 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2212 wfMsg( 'confirmemail_body',
2216 $wgContLang->timeanddate( $expiration, false ) ) );
2220 * Send an e-mail to this user's account. Does not check for
2221 * confirmed status or validity.
2223 * @param string $subject
2224 * @param string $body
2225 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2226 * @return mixed True on success, a WikiError object on failure.
2228 function sendMail( $subject, $body, $from = null ) {
2229 if( is_null( $from ) ) {
2230 global $wgPasswordSender;
2231 $from = $wgPasswordSender;
2234 require_once( 'UserMailer.php' );
2235 $to = new MailAddress( $this );
2236 $sender = new MailAddress( $from );
2237 $error = userMailer( $to, $sender, $subject, $body );
2239 if( $error == '' ) {
2242 return new WikiError( $error );
2247 * Generate, store, and return a new e-mail confirmation code.
2248 * A hash (unsalted since it's used as a key) is stored.
2249 * @param &$expiration mixed output: accepts the expiration time
2253 function confirmationToken( &$expiration ) {
2255 $expires = $now +
7 * 24 * 60 * 60;
2256 $expiration = wfTimestamp( TS_MW
, $expires );
2258 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2259 $hash = md5( $token );
2261 $dbw =& wfGetDB( DB_MASTER
);
2262 $dbw->update( 'user',
2263 array( 'user_email_token' => $hash,
2264 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2265 array( 'user_id' => $this->mId
),
2272 * Generate and store a new e-mail confirmation token, and return
2273 * the URL the user can use to confirm.
2274 * @param &$expiration mixed output: accepts the expiration time
2278 function confirmationTokenUrl( &$expiration ) {
2279 $token = $this->confirmationToken( $expiration );
2280 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2281 return $title->getFullUrl();
2285 * Mark the e-mail address confirmed and save.
2287 function confirmEmail() {
2289 $this->mEmailAuthenticated
= wfTimestampNow();
2290 $this->saveSettings();
2295 * Is this user allowed to send e-mails within limits of current
2296 * site configuration?
2299 function canSendEmail() {
2300 return $this->isEmailConfirmed();
2304 * Is this user allowed to receive e-mails within limits of current
2305 * site configuration?
2308 function canReceiveEmail() {
2309 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2313 * Is this user's e-mail address valid-looking and confirmed within
2314 * limits of the current site configuration?
2316 * If $wgEmailAuthentication is on, this may require the user to have
2317 * confirmed their address by returning a code or using a password
2318 * sent to the address from the wiki.
2322 function isEmailConfirmed() {
2323 global $wgEmailAuthentication;
2326 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2327 if( $this->isAnon() )
2329 if( !self
::isValidEmailAddr( $this->mEmail
) )
2331 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2340 * Return true if there is an outstanding request for e-mail confirmation.
2343 function isEmailConfirmationPending() {
2344 global $wgEmailAuthentication;
2345 return $wgEmailAuthentication &&
2346 !$this->isEmailConfirmed() &&
2347 $this->mEmailToken
&&
2348 $this->mEmailTokenExpires
> wfTimestamp();
2352 * @param array $groups list of groups
2353 * @return array list of permission key names for given groups combined
2356 static function getGroupPermissions( $groups ) {
2357 global $wgGroupPermissions;
2359 foreach( $groups as $group ) {
2360 if( isset( $wgGroupPermissions[$group] ) ) {
2361 $rights = array_merge( $rights,
2362 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2369 * @param string $group key name
2370 * @return string localized descriptive name for group, if provided
2373 static function getGroupName( $group ) {
2374 $key = "group-$group";
2375 $name = wfMsg( $key );
2376 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2384 * @param string $group key name
2385 * @return string localized descriptive name for member of a group, if provided
2388 static function getGroupMember( $group ) {
2389 $key = "group-$group-member";
2390 $name = wfMsg( $key );
2391 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2399 * Return the set of defined explicit groups.
2400 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2401 * groups are not included, as they are defined
2402 * automatically, not in the database.
2406 static function getAllGroups() {
2407 global $wgGroupPermissions;
2409 array_keys( $wgGroupPermissions ),
2410 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2414 * Get the title of a page describing a particular group
2416 * @param $group Name of the group
2419 static function getGroupPage( $group ) {
2420 $page = wfMsgForContent( 'grouppage-' . $group );
2421 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2422 $title = Title
::newFromText( $page );
2423 if( is_object( $title ) )
2430 * Create a link to the group in HTML, if available
2432 * @param $group Name of the group
2433 * @param $text The text of the link
2436 static function makeGroupLinkHTML( $group, $text = '' ) {
2438 $text = self
::getGroupName( $group );
2440 $title = self
::getGroupPage( $group );
2443 $sk = $wgUser->getSkin();
2444 return $sk->makeLinkObj( $title, $text );
2451 * Create a link to the group in Wikitext, if available
2453 * @param $group Name of the group
2454 * @param $text The text of the link (by default, the name of the group)
2457 static function makeGroupLinkWiki( $group, $text = '' ) {
2459 $text = self
::getGroupName( $group );
2461 $title = self
::getGroupPage( $group );
2463 $page = $title->getPrefixedText();
2464 return "[[$page|$text]]";
2471 * Increment the user's edit-count field.
2472 * Will have no effect for anonymous users.
2474 function incEditCount() {
2475 if( !$this->isAnon() ) {
2476 $dbw = wfGetDB( DB_MASTER
);
2477 $dbw->update( 'user',
2478 array( 'user_editcount=user_editcount+1' ),
2479 array( 'user_id' => $this->getId() ),
2482 // Lazy initialization check...
2483 if( $dbw->affectedRows() == 0 ) {
2484 // Pull from a slave to be less cruel to servers
2485 // Accuracy isn't the point anyway here
2486 $dbr = wfGetDB( DB_SLAVE
);
2487 $count = $dbr->selectField( 'revision',
2489 array( 'rev_user' => $this->getId() ),
2492 // Now here's a goddamn hack...
2493 if( $dbr !== $dbw ) {
2494 // If we actually have a slave server, the count is
2495 // at least one behind because the current transaction
2496 // has not been committed and replicated.
2499 // But if DB_SLAVE is selecting the master, then the
2500 // count we just read includes the revision that was
2501 // just added in the working transaction.
2504 $dbw->update( 'user',
2505 array( 'user_editcount' => $count ),
2506 array( 'user_id' => $this->getId() ),