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',
76 * List of member variables which are saved to the shared cache (memcached).
77 * Any operation which changes the corresponding database fields must
78 * call a cache-clearing function.
80 static $mCacheVars = array(
92 'mEmailAuthenticated',
102 * The cache variable declarations
104 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
105 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
106 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
109 * Whether the cache variables have been loaded
114 * Initialisation data source if mDataLoaded==false. May be one of:
115 * defaults anonymous user initialised from class defaults
116 * name initialise from mName
117 * id initialise from mId
118 * session log in from cookies or session if possible
120 * Use the User::newFrom*() family of functions to set this.
125 * Lazy-initialised variables, invalidated with clearInstanceCache
127 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
128 $mBlockreason, $mBlock, $mEffectiveGroups;
131 * Lightweight constructor for anonymous user
132 * Use the User::newFrom* factory functions for other kinds of users
135 $this->clearInstanceCache( 'defaults' );
139 * Load the user table data for this object from the source given by mFrom
142 if ( $this->mDataLoaded
) {
145 wfProfileIn( __METHOD__
);
147 # Set it now to avoid infinite recursion in accessors
148 $this->mDataLoaded
= true;
150 switch ( $this->mFrom
) {
152 $this->loadDefaults();
155 $this->mId
= self
::idFromName( $this->mName
);
157 # Nonexistent user placeholder object
158 $this->loadDefaults( $this->mName
);
167 $this->loadFromSession();
170 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
172 wfProfileOut( __METHOD__
);
176 * Load user table data given mId
177 * @return false if the ID does not exist, true otherwise
180 function loadFromId() {
182 if ( $this->mId
== 0 ) {
183 $this->loadDefaults();
188 $key = wfMemcKey( 'user', 'id', $this->mId
);
189 $data = $wgMemc->get( $key );
191 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
192 # Object is expired, load from DB
197 wfDebug( "Cache miss for user {$this->mId}\n" );
199 if ( !$this->loadFromDatabase() ) {
200 # Can't load from ID, user is anonymous
206 foreach ( self
::$mCacheVars as $name ) {
207 $data[$name] = $this->$name;
209 $data['mVersion'] = MW_USER_VERSION
;
210 $wgMemc->set( $key, $data );
212 wfDebug( "Got user {$this->mId} from cache\n" );
214 foreach ( self
::$mCacheVars as $name ) {
215 $this->$name = $data[$name];
222 * Static factory method for creation from username.
224 * This is slightly less efficient than newFromId(), so use newFromId() if
225 * you have both an ID and a name handy.
227 * @param string $name Username, validated by Title:newFromText()
228 * @param mixed $validate Validate username. Takes the same parameters as
229 * User::getCanonicalName(), except that true is accepted as an alias
230 * for 'valid', for BC.
232 * @return User object, or null if the username is invalid. If the username
233 * is not present in the database, the result will be a user object with
234 * a name, zero user ID and default settings.
237 static function newFromName( $name, $validate = 'valid' ) {
238 if ( $validate === true ) {
241 $name = self
::getCanonicalName( $name, $validate );
242 if ( $name === false ) {
245 # Create unloaded user object
253 static function newFromId( $id ) {
261 * Factory method to fetch whichever user has a given email confirmation code.
262 * This code is generated when an account is created or its e-mail address
265 * If the code is invalid or has expired, returns NULL.
267 * @param string $code
271 static function newFromConfirmationCode( $code ) {
272 $dbr =& wfGetDB( DB_SLAVE
);
273 $id = $dbr->selectField( 'user', 'user_id', array(
274 'user_email_token' => md5( $code ),
275 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
277 if( $id !== false ) {
278 return User
::newFromId( $id );
285 * Create a new user object using data from session or cookies. If the
286 * login credentials are invalid, the result is an anonymous user.
291 static function newFromSession() {
293 $user->mFrom
= 'session';
298 * Get username given an id.
299 * @param integer $id Database user id
300 * @return string Nickname of a user
303 static function whoIs( $id ) {
304 $dbr =& wfGetDB( DB_SLAVE
);
305 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
309 * Get real username given an id.
310 * @param integer $id Database user id
311 * @return string Realname of a user
314 static function whoIsReal( $id ) {
315 $dbr =& wfGetDB( DB_SLAVE
);
316 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), 'User::whoIsReal' );
320 * Get database id given a user name
321 * @param string $name Nickname of a user
322 * @return integer|null Database user id (null: if non existent
325 static function idFromName( $name ) {
326 $nt = Title
::newFromText( $name );
327 if( is_null( $nt ) ) {
331 $dbr =& wfGetDB( DB_SLAVE
);
332 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
334 if ( $s === false ) {
342 * Does the string match an anonymous IPv4 address?
344 * This function exists for username validation, in order to reject
345 * usernames which are similar in form to IP addresses. Strings such
346 * as 300.300.300.300 will return true because it looks like an IP
347 * address, despite not being strictly valid.
349 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
350 * address because the usemod software would "cloak" anonymous IP
351 * addresses like this, if we allowed accounts like this to be created
352 * new users could get the old edits of these anonymous users.
357 * @param string $name Nickname of a user
360 static function isIP( $name ) {
361 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name);
362 /*return preg_match("/^
363 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
364 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
365 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
366 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
371 * Is the input a valid username?
373 * Checks if the input is a valid username, we don't want an empty string,
374 * an IP address, anything that containins slashes (would mess up subpages),
375 * is longer than the maximum allowed username size or doesn't begin with
378 * @param string $name
382 static function isValidUserName( $name ) {
383 global $wgContLang, $wgMaxNameChars;
386 || User
::isIP( $name )
387 ||
strpos( $name, '/' ) !== false
388 ||
strlen( $name ) > $wgMaxNameChars
389 ||
$name != $wgContLang->ucfirst( $name ) )
392 // Ensure that the name can't be misresolved as a different title,
393 // such as with extra namespace keys at the start.
394 $parsed = Title
::newFromText( $name );
395 if( is_null( $parsed )
396 ||
$parsed->getNamespace()
397 ||
strcmp( $name, $parsed->getPrefixedText() ) )
400 // Check an additional blacklist of troublemaker characters.
401 // Should these be merged into the title char list?
402 $unicodeBlacklist = '/[' .
403 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
404 '\x{00a0}' . # non-breaking space
405 '\x{2000}-\x{200f}' . # various whitespace
406 '\x{2028}-\x{202f}' . # breaks and control chars
407 '\x{3000}' . # ideographic space
408 '\x{e000}-\x{f8ff}' . # private use
410 if( preg_match( $unicodeBlacklist, $name ) ) {
418 * Usernames which fail to pass this function will be blocked
419 * from user login and new account registrations, but may be used
420 * internally by batch processes.
422 * If an account already exists in this form, login will be blocked
423 * by a failure to pass this function.
425 * @param string $name
428 static function isUsableName( $name ) {
429 global $wgReservedUsernames;
431 // Must be a usable username, obviously ;)
432 self
::isValidUserName( $name ) &&
434 // Certain names may be reserved for batch processes.
435 !in_array( $name, $wgReservedUsernames );
439 * Usernames which fail to pass this function will be blocked
440 * from new account registrations, but may be used internally
441 * either by batch processes or by user accounts which have
442 * already been created.
444 * Additional character blacklisting may be added here
445 * rather than in isValidUserName() to avoid disrupting
448 * @param string $name
451 static function isCreatableName( $name ) {
453 self
::isUsableName( $name ) &&
455 // Registration-time character blacklisting...
456 strpos( $name, '@' ) === false;
460 * Is the input a valid password?
462 * @param string $password
466 static function isValidPassword( $password ) {
467 global $wgMinimalPasswordLength;
468 return strlen( $password ) >= $wgMinimalPasswordLength;
472 * Does the string match roughly an email address ?
474 * There used to be a regular expression here, it got removed because it
475 * rejected valid addresses. Actually just check if there is '@' somewhere
476 * in the given address.
478 * @todo Check for RFC 2822 compilance
481 * @param string $addr email address
485 static function isValidEmailAddr ( $addr ) {
486 return ( trim( $addr ) != '' ) &&
487 (false !== strpos( $addr, '@' ) );
491 * Given unvalidated user input, return a canonical username, or false if
492 * the username is invalid.
493 * @param string $name
494 * @param mixed $validate Type of validation to use:
495 * false No validation
496 * 'valid' Valid for batch processes
497 * 'usable' Valid for batch processes and login
498 * 'creatable' Valid for batch processes, login and account creation
500 static function getCanonicalName( $name, $validate = 'valid' ) {
501 # Force usernames to capital
503 $name = $wgContLang->ucfirst( $name );
505 # Clean up name according to title rules
506 $t = Title
::newFromText( $name );
507 if( is_null( $t ) ) {
511 # Reject various classes of invalid names
512 $name = $t->getText();
514 $name = $wgAuth->getCanonicalName( $t->getText() );
516 switch ( $validate ) {
520 if ( !User
::isValidUserName( $name ) ) {
525 if ( !User
::isUsableName( $name ) ) {
530 if ( !User
::isCreatableName( $name ) ) {
535 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
541 * Count the number of edits of a user
543 * @param int $uid The user ID to check
547 static function edits( $uid ) {
548 $dbr =& wfGetDB( DB_SLAVE
);
549 return $dbr->selectField(
550 'revision', 'count(*)',
551 array( 'rev_user' => $uid ),
557 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
558 * @todo: hash random numbers to improve security, like generateToken()
563 static function randomPassword() {
564 global $wgMinimalPasswordLength;
565 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
566 $l = strlen( $pwchars ) - 1;
568 $pwlength = max( 7, $wgMinimalPasswordLength );
569 $digit = mt_rand(0, $pwlength - 1);
571 for ( $i = 0; $i < $pwlength; $i++
) {
572 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
578 * Set cached properties to default. Note: this no longer clears
579 * uncached lazy-initialised properties. The constructor does that instead.
583 function loadDefaults( $name = false ) {
584 wfProfileIn( __METHOD__
);
586 global $wgCookiePrefix;
589 $this->mName
= $name;
590 $this->mRealName
= '';
591 $this->mPassword
= $this->mNewpassword
= '';
592 $this->mNewpassTime
= null;
594 $this->mOptions
= null; # Defer init
596 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
597 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
599 $this->mTouched
= '0'; # Allow any pages to be cached
602 $this->setToken(); # Random
603 $this->mEmailAuthenticated
= null;
604 $this->mEmailToken
= '';
605 $this->mEmailTokenExpires
= null;
606 $this->mRegistration
= wfTimestamp( TS_MW
);
607 $this->mGroups
= array();
609 wfProfileOut( __METHOD__
);
613 * Initialise php session
614 * @deprecated use wfSetupSession()
616 function SetupSession() {
621 * Load user data from the session or login cookie. If there are no valid
622 * credentials, initialises the user as an anon.
623 * @return true if the user is logged in, false otherwise
627 function loadFromSession() {
628 global $wgMemc, $wgCookiePrefix;
630 if ( isset( $_SESSION['wsUserID'] ) ) {
631 if ( 0 != $_SESSION['wsUserID'] ) {
632 $sId = $_SESSION['wsUserID'];
634 $this->loadDefaults();
637 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
638 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
639 $_SESSION['wsUserID'] = $sId;
641 $this->loadDefaults();
644 if ( isset( $_SESSION['wsUserName'] ) ) {
645 $sName = $_SESSION['wsUserName'];
646 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
647 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
648 $_SESSION['wsUserName'] = $sName;
650 $this->loadDefaults();
654 $passwordCorrect = FALSE;
656 if ( !$this->loadFromId() ) {
657 # Not a valid ID, loadFromId has switched the object to anon for us
661 if ( isset( $_SESSION['wsToken'] ) ) {
662 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
664 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
665 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
668 # No session or persistent login cookie
669 $this->loadDefaults();
673 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
674 wfDebug( "Logged in from $from\n" );
677 # Invalid credentials
678 wfDebug( "Can't log in from $from, invalid credentials\n" );
679 $this->loadDefaults();
685 * Load user and user_group data from the database
686 * $this->mId must be set, this is how the user is identified.
688 * @return true if the user exists, false if the user is anonymous
691 function loadFromDatabase() {
693 $this->mId
= intval( $this->mId
);
695 /** Anonymous user */
697 $this->loadDefaults();
701 $dbr =& wfGetDB( DB_MASTER
);
702 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
704 if ( $s !== false ) {
705 # Initialise user table data
706 $this->mName
= $s->user_name
;
707 $this->mRealName
= $s->user_real_name
;
708 $this->mPassword
= $s->user_password
;
709 $this->mNewpassword
= $s->user_newpassword
;
710 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $s->user_newpass_time
);
711 $this->mEmail
= $s->user_email
;
712 $this->decodeOptions( $s->user_options
);
713 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
714 $this->mToken
= $s->user_token
;
715 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
716 $this->mEmailToken
= $s->user_email_token
;
717 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $s->user_email_token_expires
);
718 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $s->user_registration
);
721 $res = $dbr->select( 'user_groups',
723 array( 'ug_user' => $this->mId
),
725 $this->mGroups
= array();
726 while( $row = $dbr->fetchObject( $res ) ) {
727 $this->mGroups
[] = $row->ug_group
;
733 $this->loadDefaults();
739 * Clear various cached data stored in this object.
740 * @param string $reloadFrom Reload user and user_groups table data from a
741 * given source. May be "name", "id", "defaults", "session" or false for
744 function clearInstanceCache( $reloadFrom = false ) {
745 $this->mNewtalk
= -1;
746 $this->mDatePreference
= null;
747 $this->mBlockedby
= -1; # Unset
748 $this->mHash
= false;
750 $this->mRights
= null;
751 $this->mEffectiveGroups
= null;
754 $this->mDataLoaded
= false;
755 $this->mFrom
= $reloadFrom;
760 * Combine the language default options with any site-specific options
761 * and add the default language variants.
767 function getDefaultOptions() {
768 global $wgNamespacesToBeSearchedDefault;
770 * Site defaults will override the global/language defaults
772 global $wgDefaultUserOptions, $wgContLang;
773 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
776 * default language setting
778 $variant = $wgContLang->getPreferredVariant( false );
779 $defOpt['variant'] = $variant;
780 $defOpt['language'] = $variant;
782 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
783 $defOpt['searchNs'.$nsnum] = $val;
789 * Get a given default option value.
796 function getDefaultOption( $opt ) {
797 $defOpts = User
::getDefaultOptions();
798 if( isset( $defOpts[$opt] ) ) {
799 return $defOpts[$opt];
806 * Get a list of user toggle names
809 static function getToggles() {
811 $extraToggles = array();
812 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
813 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
818 * Get blocking information
820 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
821 * non-critical checks are done against slaves. Check when actually saving should be done against
824 function getBlockedStatus( $bFromSlave = true ) {
825 global $wgEnableSorbs, $wgProxyWhitelist;
827 if ( -1 != $this->mBlockedby
) {
828 wfDebug( "User::getBlockedStatus: already loaded.\n" );
832 wfProfileIn( __METHOD__
);
833 wfDebug( __METHOD__
.": checking...\n" );
835 $this->mBlockedby
= 0;
839 $this->mBlock
= new Block();
840 $this->mBlock
->fromMaster( !$bFromSlave );
841 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
842 wfDebug( __METHOD__
.": Found block.\n" );
843 $this->mBlockedby
= $this->mBlock
->mBy
;
844 $this->mBlockreason
= $this->mBlock
->mReason
;
845 if ( $this->isLoggedIn() ) {
846 $this->spreadBlock();
849 $this->mBlock
= null;
850 wfDebug( __METHOD__
.": No block.\n" );
854 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
857 if ( wfIsLocallyBlockedProxy( $ip ) ) {
858 $this->mBlockedby
= wfMsg( 'proxyblocker' );
859 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
863 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
864 if ( $this->inSorbsBlacklist( $ip ) ) {
865 $this->mBlockedby
= wfMsg( 'sorbs' );
866 $this->mBlockreason
= wfMsg( 'sorbsreason' );
872 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
874 wfProfileOut( __METHOD__
);
877 function inSorbsBlacklist( $ip ) {
878 global $wgEnableSorbs, $wgSorbsUrl;
880 return $wgEnableSorbs &&
881 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
884 function inDnsBlacklist( $ip, $base ) {
885 wfProfileIn( __METHOD__
);
891 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
893 for ( $i=4; $i>=1; $i-- ) {
894 $host .= $m[$i] . '.';
899 $ipList = gethostbynamel( $host );
902 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
905 wfDebug( "Requested $host, not found in $base.\n" );
909 wfProfileOut( __METHOD__
);
914 * Primitive rate limits: enforce maximum actions per time period
915 * to put a brake on flooding.
917 * Note: when using a shared cache like memcached, IP-address
918 * last-hit counters will be shared across wikis.
920 * @return bool true if a rate limiter was tripped
923 function pingLimiter( $action='edit' ) {
925 # Call the 'PingLimiter' hook
927 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
931 global $wgRateLimits, $wgRateLimitsExcludedGroups;
932 if( !isset( $wgRateLimits[$action] ) ) {
936 # Some groups shouldn't trigger the ping limiter, ever
937 foreach( $this->getGroups() as $group ) {
938 if( array_search( $group, $wgRateLimitsExcludedGroups ) !== false )
942 global $wgMemc, $wgRateLimitLog;
943 wfProfileIn( __METHOD__
);
945 $limits = $wgRateLimits[$action];
947 $id = $this->getId();
950 if( isset( $limits['anon'] ) && $id == 0 ) {
951 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
954 if( isset( $limits['user'] ) && $id != 0 ) {
955 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
957 if( $this->isNewbie() ) {
958 if( isset( $limits['newbie'] ) && $id != 0 ) {
959 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
961 if( isset( $limits['ip'] ) ) {
962 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
965 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
966 $subnet = $matches[1];
967 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
972 foreach( $keys as $key => $limit ) {
973 list( $max, $period ) = $limit;
974 $summary = "(limit $max in {$period}s)";
975 $count = $wgMemc->get( $key );
977 if( $count > $max ) {
978 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
979 if( $wgRateLimitLog ) {
980 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
984 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
987 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
988 $wgMemc->add( $key, 1, intval( $period ) );
990 $wgMemc->incr( $key );
993 wfProfileOut( __METHOD__
);
998 * Check if user is blocked
999 * @return bool True if blocked, false otherwise
1001 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1002 wfDebug( "User::isBlocked: enter\n" );
1003 $this->getBlockedStatus( $bFromSlave );
1004 return $this->mBlockedby
!== 0;
1008 * Check if user is blocked from editing a particular article
1010 function isBlockedFrom( $title, $bFromSlave = false ) {
1011 global $wgBlockAllowsUTEdit;
1012 wfProfileIn( __METHOD__
);
1013 wfDebug( __METHOD__
.": enter\n" );
1015 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1016 $title->getNamespace() == NS_USER_TALK
)
1019 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1021 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1022 $blocked = $this->isBlocked( $bFromSlave );
1024 wfProfileOut( __METHOD__
);
1029 * Get name of blocker
1030 * @return string name of blocker
1032 function blockedBy() {
1033 $this->getBlockedStatus();
1034 return $this->mBlockedby
;
1038 * Get blocking reason
1039 * @return string Blocking reason
1041 function blockedFor() {
1042 $this->getBlockedStatus();
1043 return $this->mBlockreason
;
1047 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1055 * Set the user and reload all fields according to that ID
1056 * @deprecated use User::newFromId()
1058 function setID( $v ) {
1060 $this->clearInstanceCache( 'id' );
1064 * Get the user name, or the IP for anons
1066 function getName() {
1067 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1068 # Special case optimisation
1069 return $this->mName
;
1072 if ( $this->mName
=== false ) {
1073 $this->mName
= wfGetIP();
1075 return $this->mName
;
1080 * Set the user name.
1082 * This does not reload fields from the database according to the given
1083 * name. Rather, it is used to create a temporary "nonexistent user" for
1084 * later addition to the database. It can also be used to set the IP
1085 * address for an anonymous user to something other than the current
1088 * User::newFromName() has rougly the same function, when the named user
1091 function setName( $str ) {
1093 $this->mName
= $str;
1097 * Return the title dbkey form of the name, for eg user pages.
1101 function getTitleKey() {
1102 return str_replace( ' ', '_', $this->getName() );
1105 function getNewtalk() {
1108 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1109 if( $this->mNewtalk
=== -1 ) {
1110 $this->mNewtalk
= false; # reset talk page status
1112 # Check memcached separately for anons, who have no
1113 # entire User object stored in there.
1116 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1117 $newtalk = $wgMemc->get( $key );
1118 if( is_integer( $newtalk ) ) {
1119 $this->mNewtalk
= (bool)$newtalk;
1121 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
1122 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
1125 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1129 return (bool)$this->mNewtalk
;
1133 * Return the talk page(s) this user has new messages on.
1135 function getNewMessageLinks() {
1137 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1140 if (!$this->getNewtalk())
1142 $up = $this->getUserPage();
1143 $utp = $up->getTalkPage();
1144 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1149 * Perform a user_newtalk check on current slaves; if the memcached data
1150 * is funky we don't want newtalk state to get stuck on save, as that's
1153 * @param string $field
1158 function checkNewtalk( $field, $id ) {
1159 $dbr =& wfGetDB( DB_SLAVE
);
1160 $ok = $dbr->selectField( 'user_newtalk', $field,
1161 array( $field => $id ), __METHOD__
);
1162 return $ok !== false;
1167 * @param string $field
1171 function updateNewtalk( $field, $id ) {
1172 if( $this->checkNewtalk( $field, $id ) ) {
1173 wfDebug( __METHOD__
." already set ($field, $id), ignoring\n" );
1176 $dbw =& wfGetDB( DB_MASTER
);
1177 $dbw->insert( 'user_newtalk',
1178 array( $field => $id ),
1181 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1186 * Clear the new messages flag for the given user
1187 * @param string $field
1191 function deleteNewtalk( $field, $id ) {
1192 if( !$this->checkNewtalk( $field, $id ) ) {
1193 wfDebug( __METHOD__
.": already gone ($field, $id), ignoring\n" );
1196 $dbw =& wfGetDB( DB_MASTER
);
1197 $dbw->delete( 'user_newtalk',
1198 array( $field => $id ),
1200 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1205 * Update the 'You have new messages!' status.
1208 function setNewtalk( $val ) {
1209 if( wfReadOnly() ) {
1214 $this->mNewtalk
= $val;
1216 if( $this->isAnon() ) {
1218 $id = $this->getName();
1221 $id = $this->getId();
1225 $changed = $this->updateNewtalk( $field, $id );
1227 $changed = $this->deleteNewtalk( $field, $id );
1231 if( $this->isAnon() ) {
1232 // Anons have a separate memcached space, since
1233 // user records aren't kept for them.
1235 $key = wfMemcKey( 'newtalk', 'ip', $val );
1236 $wgMemc->set( $key, $val ?
1 : 0 );
1239 // Make sure the user page is watched, so a notification
1240 // will be sent out if enabled.
1241 $this->addWatch( $this->getTalkPage() );
1244 $this->invalidateCache();
1249 * Generate a current or new-future timestamp to be stored in the
1250 * user_touched field when we update things.
1252 private static function newTouchedTimestamp() {
1253 global $wgClockSkewFudge;
1254 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1258 * Clear user data from memcached.
1259 * Use after applying fun updates to the database; caller's
1260 * responsibility to update user_touched if appropriate.
1262 * Called implicitly from invalidateCache() and saveSettings().
1264 private function clearSharedCache() {
1267 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1272 * Immediately touch the user data cache for this account.
1273 * Updates user_touched field, and removes account data from memcached
1274 * for reload on the next hit.
1276 function invalidateCache() {
1279 $this->mTouched
= self
::newTouchedTimestamp();
1281 $dbw =& wfGetDB( DB_MASTER
);
1282 $dbw->update( 'user',
1283 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1284 array( 'user_id' => $this->mId
),
1287 $this->clearSharedCache();
1291 function validateCache( $timestamp ) {
1293 return ($timestamp >= $this->mTouched
);
1297 * Encrypt a password.
1298 * It can eventuall salt a password @see User::addSalt()
1299 * @param string $p clear Password.
1300 * @return string Encrypted password.
1302 function encryptPassword( $p ) {
1304 return wfEncryptPassword( $this->mId
, $p );
1308 * Set the password and reset the random token
1309 * Calls through to authentication plugin if necessary;
1310 * will have no effect if the auth plugin refuses to
1311 * pass the change through or if the legal password
1314 * As a special case, setting the password to null
1315 * wipes it, so the account cannot be logged in until
1316 * a new password is set, for instance via e-mail.
1318 * @param string $str
1319 * @throws PasswordError on failure
1321 function setPassword( $str ) {
1324 if( $str !== null ) {
1325 if( !$wgAuth->allowPasswordChange() ) {
1326 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1329 if( !$this->isValidPassword( $str ) ) {
1330 global $wgMinimalPasswordLength;
1331 throw new PasswordError( wfMsg( 'passwordtooshort',
1332 $wgMinimalPasswordLength ) );
1336 if( !$wgAuth->setPassword( $this, $str ) ) {
1337 throw new PasswordError( wfMsg( 'externaldberror' ) );
1343 if( $str === null ) {
1344 // Save an invalid hash...
1345 $this->mPassword
= '';
1347 $this->mPassword
= $this->encryptPassword( $str );
1349 $this->mNewpassword
= '';
1350 $this->mNewpassTime
= null;
1356 * Set the random token (used for persistent authentication)
1357 * Called from loadDefaults() among other places.
1360 function setToken( $token = false ) {
1361 global $wgSecretKey, $wgProxyKey;
1364 if ( $wgSecretKey ) {
1365 $key = $wgSecretKey;
1366 } elseif ( $wgProxyKey ) {
1371 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1373 $this->mToken
= $token;
1377 function setCookiePassword( $str ) {
1379 $this->mCookiePassword
= md5( $str );
1383 * Set the password for a password reminder or new account email
1384 * Sets the user_newpass_time field if $throttle is true
1386 function setNewpassword( $str, $throttle = true ) {
1388 $this->mNewpassword
= $this->encryptPassword( $str );
1390 $this->mNewpassTime
= wfTimestampNow();
1395 * Returns true if a password reminder email has already been sent within
1396 * the last $wgPasswordReminderResendTime hours
1398 function isPasswordReminderThrottled() {
1399 global $wgPasswordReminderResendTime;
1401 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1404 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1405 return time() < $expiry;
1408 function getEmail() {
1410 return $this->mEmail
;
1413 function getEmailAuthenticationTimestamp() {
1415 return $this->mEmailAuthenticated
;
1418 function setEmail( $str ) {
1420 $this->mEmail
= $str;
1423 function getRealName() {
1425 return $this->mRealName
;
1428 function setRealName( $str ) {
1430 $this->mRealName
= $str;
1434 * @param string $oname The option to check
1435 * @param string $defaultOverride A default value returned if the option does not exist
1438 function getOption( $oname, $defaultOverride = '' ) {
1441 if ( is_null( $this->mOptions
) ) {
1442 if($defaultOverride != '') {
1443 return $defaultOverride;
1445 $this->mOptions
= User
::getDefaultOptions();
1448 if ( array_key_exists( $oname, $this->mOptions
) ) {
1449 return trim( $this->mOptions
[$oname] );
1451 return $defaultOverride;
1456 * Get the user's date preference, including some important migration for
1459 function getDatePreference() {
1460 if ( is_null( $this->mDatePreference
) ) {
1462 $value = $this->getOption( 'date' );
1463 $map = $wgLang->getDatePreferenceMigrationMap();
1464 if ( isset( $map[$value] ) ) {
1465 $value = $map[$value];
1467 $this->mDatePreference
= $value;
1469 return $this->mDatePreference
;
1473 * @param string $oname The option to check
1474 * @return bool False if the option is not selected, true if it is
1476 function getBoolOption( $oname ) {
1477 return (bool)$this->getOption( $oname );
1481 * Get an option as an integer value from the source string.
1482 * @param string $oname The option to check
1483 * @param int $default Optional value to return if option is unset/blank.
1486 function getIntOption( $oname, $default=0 ) {
1487 $val = $this->getOption( $oname );
1491 return intval( $val );
1494 function setOption( $oname, $val ) {
1496 if ( is_null( $this->mOptions
) ) {
1497 $this->mOptions
= User
::getDefaultOptions();
1499 if ( $oname == 'skin' ) {
1500 # Clear cached skin, so the new one displays immediately in Special:Preferences
1501 unset( $this->mSkin
);
1503 // Filter out any newlines that may have passed through input validation.
1504 // Newlines are used to separate items in the options blob.
1505 $val = str_replace( "\r\n", "\n", $val );
1506 $val = str_replace( "\r", "\n", $val );
1507 $val = str_replace( "\n", " ", $val );
1508 $this->mOptions
[$oname] = $val;
1511 function getRights() {
1512 if ( is_null( $this->mRights
) ) {
1513 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1515 return $this->mRights
;
1519 * Get the list of explicit group memberships this user has.
1520 * The implicit * and user groups are not included.
1521 * @return array of strings
1523 function getGroups() {
1525 return $this->mGroups
;
1529 * Get the list of implicit group memberships this user has.
1530 * This includes all explicit groups, plus 'user' if logged in
1531 * and '*' for all accounts.
1532 * @param boolean $recache Don't use the cache
1533 * @return array of strings
1535 function getEffectiveGroups( $recache = false ) {
1536 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1538 $this->mEffectiveGroups
= $this->mGroups
;
1539 $this->mEffectiveGroups
[] = '*';
1541 $this->mEffectiveGroups
[] = 'user';
1543 global $wgAutoConfirmAge;
1544 $accountAge = time() - wfTimestampOrNull( TS_UNIX
, $this->mRegistration
);
1545 if( $accountAge >= $wgAutoConfirmAge ) {
1546 $this->mEffectiveGroups
[] = 'autoconfirmed';
1549 # Implicit group for users whose email addresses are confirmed
1550 global $wgEmailAuthentication;
1551 if( self
::isValidEmailAddr( $this->mEmail
) ) {
1552 if( $wgEmailAuthentication ) {
1553 if( $this->mEmailAuthenticated
)
1554 $this->mEffectiveGroups
[] = 'emailconfirmed';
1556 $this->mEffectiveGroups
[] = 'emailconfirmed';
1561 return $this->mEffectiveGroups
;
1565 * Add the user to the given group.
1566 * This takes immediate effect.
1569 function addGroup( $group ) {
1571 $dbw =& wfGetDB( DB_MASTER
);
1572 $dbw->insert( 'user_groups',
1574 'ug_user' => $this->getID(),
1575 'ug_group' => $group,
1578 array( 'IGNORE' ) );
1580 $this->mGroups
[] = $group;
1581 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1583 $this->invalidateCache();
1587 * Remove the user from the given group.
1588 * This takes immediate effect.
1591 function removeGroup( $group ) {
1593 $dbw =& wfGetDB( DB_MASTER
);
1594 $dbw->delete( 'user_groups',
1596 'ug_user' => $this->getID(),
1597 'ug_group' => $group,
1599 'User::removeGroup' );
1601 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1602 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1604 $this->invalidateCache();
1609 * A more legible check for non-anonymousness.
1610 * Returns true if the user is not an anonymous visitor.
1614 function isLoggedIn() {
1615 return( $this->getID() != 0 );
1619 * A more legible check for anonymousness.
1620 * Returns true if the user is an anonymous visitor.
1625 return !$this->isLoggedIn();
1629 * Whether the user is a bot
1633 return $this->isAllowed( 'bot' );
1637 * Check if user is allowed to access a feature / make an action
1638 * @param string $action Action to be checked
1639 * @return boolean True: action is allowed, False: action should not be allowed
1641 function isAllowed($action='') {
1642 if ( $action === '' )
1643 // In the spirit of DWIM
1646 return in_array( $action, $this->getRights() );
1650 * Load a skin if it doesn't exist or return it
1651 * @todo FIXME : need to check the old failback system [AV]
1653 function &getSkin() {
1655 if ( ! isset( $this->mSkin
) ) {
1656 wfProfileIn( __METHOD__
);
1659 $userSkin = $this->getOption( 'skin' );
1660 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1662 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1663 wfProfileOut( __METHOD__
);
1665 return $this->mSkin
;
1669 * @param string $title Article title to look at
1673 * Check watched status of an article
1674 * @return bool True if article is watched
1676 function isWatched( $title ) {
1677 $wl = WatchedItem
::fromUserTitle( $this, $title );
1678 return $wl->isWatched();
1684 function addWatch( $title ) {
1685 $wl = WatchedItem
::fromUserTitle( $this, $title );
1687 $this->invalidateCache();
1691 * Stop watching an article
1693 function removeWatch( $title ) {
1694 $wl = WatchedItem
::fromUserTitle( $this, $title );
1696 $this->invalidateCache();
1700 * Clear the user's notification timestamp for the given title.
1701 * If e-notif e-mails are on, they will receive notification mails on
1702 * the next change of the page if it's watched etc.
1704 function clearNotification( &$title ) {
1705 global $wgUser, $wgUseEnotif;
1707 # Do nothing if the database is locked to writes
1708 if( wfReadOnly() ) {
1712 if ($title->getNamespace() == NS_USER_TALK
&&
1713 $title->getText() == $this->getName() ) {
1714 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1716 $this->setNewtalk( false );
1719 if( !$wgUseEnotif ) {
1723 if( $this->isAnon() ) {
1724 // Nothing else to do...
1728 // Only update the timestamp if the page is being watched.
1729 // The query to find out if it is watched is cached both in memcached and per-invocation,
1730 // and when it does have to be executed, it can be on a slave
1731 // If this is the user's newtalk page, we always update the timestamp
1732 if ($title->getNamespace() == NS_USER_TALK
&&
1733 $title->getText() == $wgUser->getName())
1736 } elseif ( $this->getID() == $wgUser->getID() ) {
1737 $watched = $title->userIsWatching();
1742 // If the page is watched by the user (or may be watched), update the timestamp on any
1743 // any matching rows
1745 $dbw =& wfGetDB( DB_MASTER
);
1746 $dbw->update( 'watchlist',
1748 'wl_notificationtimestamp' => NULL
1749 ), array( /* WHERE */
1750 'wl_title' => $title->getDBkey(),
1751 'wl_namespace' => $title->getNamespace(),
1752 'wl_user' => $this->getID()
1753 ), 'User::clearLastVisited'
1761 * Resets all of the given user's page-change notification timestamps.
1762 * If e-notif e-mails are on, they will receive notification mails on
1763 * the next change of any watched page.
1765 * @param int $currentUser user ID number
1768 function clearAllNotifications( $currentUser ) {
1769 global $wgUseEnotif;
1770 if ( !$wgUseEnotif ) {
1771 $this->setNewtalk( false );
1774 if( $currentUser != 0 ) {
1776 $dbw =& wfGetDB( DB_MASTER
);
1777 $dbw->update( 'watchlist',
1779 'wl_notificationtimestamp' => NULL
1780 ), array( /* WHERE */
1781 'wl_user' => $currentUser
1782 ), 'UserMailer::clearAll'
1785 # we also need to clear here the "you have new message" notification for the own user_talk page
1786 # This is cleared one page view later in Article::viewUpdates();
1792 * @return string Encoding options
1794 function encodeOptions() {
1796 if ( is_null( $this->mOptions
) ) {
1797 $this->mOptions
= User
::getDefaultOptions();
1800 foreach ( $this->mOptions
as $oname => $oval ) {
1801 array_push( $a, $oname.'='.$oval );
1803 $s = implode( "\n", $a );
1810 function decodeOptions( $str ) {
1811 $this->mOptions
= array();
1812 $a = explode( "\n", $str );
1813 foreach ( $a as $s ) {
1815 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1816 $this->mOptions
[$m[1]] = $m[2];
1821 function setCookies() {
1822 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1824 if ( 0 == $this->mId
) return;
1825 $exp = time() +
$wgCookieExpiration;
1827 $_SESSION['wsUserID'] = $this->mId
;
1828 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1830 $_SESSION['wsUserName'] = $this->getName();
1831 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1833 $_SESSION['wsToken'] = $this->mToken
;
1834 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1835 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1837 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1843 * Clears the cookies and session, resets the instance cache
1846 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1847 $this->clearInstanceCache( 'defaults' );
1849 $_SESSION['wsUserID'] = 0;
1851 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1852 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1854 # Remember when user logged out, to prevent seeing cached pages
1855 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1859 * Save object settings into database
1860 * @fixme Only rarely do all these fields need to be set!
1862 function saveSettings() {
1864 if ( wfReadOnly() ) { return; }
1865 if ( 0 == $this->mId
) { return; }
1867 $this->mTouched
= self
::newTouchedTimestamp();
1869 $dbw =& wfGetDB( DB_MASTER
);
1870 $dbw->update( 'user',
1872 'user_name' => $this->mName
,
1873 'user_password' => $this->mPassword
,
1874 'user_newpassword' => $this->mNewpassword
,
1875 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
1876 'user_real_name' => $this->mRealName
,
1877 'user_email' => $this->mEmail
,
1878 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1879 'user_options' => $this->encodeOptions(),
1880 'user_touched' => $dbw->timestamp($this->mTouched
),
1881 'user_token' => $this->mToken
1882 ), array( /* WHERE */
1883 'user_id' => $this->mId
1886 $this->clearSharedCache();
1891 * Checks if a user with the given name exists, returns the ID
1893 function idForName() {
1894 $s = trim( $this->getName() );
1895 if ( 0 == strcmp( '', $s ) ) return 0;
1897 $dbr =& wfGetDB( DB_SLAVE
);
1898 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
1899 if ( $id === false ) {
1906 * Add a user to the database, return the user object
1908 * @param string $name The user's name
1909 * @param array $params Associative array of non-default parameters to save to the database:
1910 * password The user's password. Password logins will be disabled if this is omitted.
1911 * newpassword A temporary password mailed to the user
1912 * email The user's email address
1913 * email_authenticated The email authentication timestamp
1914 * real_name The user's real name
1915 * options An associative array of non-default options
1916 * token Random authentication token. Do not set.
1917 * registration Registration timestamp. Do not set.
1919 * @return User object, or null if the username already exists
1921 static function createNew( $name, $params = array() ) {
1924 if ( isset( $params['options'] ) ) {
1925 $user->mOptions
= $params['options'] +
$user->mOptions
;
1926 unset( $params['options'] );
1928 $dbw =& wfGetDB( DB_MASTER
);
1929 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1931 'user_id' => $seqVal,
1932 'user_name' => $name,
1933 'user_password' => $user->mPassword
,
1934 'user_newpassword' => $user->mNewpassword
,
1935 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
1936 'user_email' => $user->mEmail
,
1937 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
1938 'user_real_name' => $user->mRealName
,
1939 'user_options' => $user->encodeOptions(),
1940 'user_token' => $user->mToken
,
1941 'user_registration' => $dbw->timestamp( $user->mRegistration
),
1942 'user_editcount' => 0,
1944 foreach ( $params as $name => $value ) {
1945 $fields["user_$name"] = $value;
1947 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
1948 if ( $dbw->affectedRows() ) {
1949 $newUser = User
::newFromId( $dbw->insertId() );
1957 * Add an existing user object to the database
1959 function addToDatabase() {
1961 $dbw =& wfGetDB( DB_MASTER
);
1962 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1963 $dbw->insert( 'user',
1965 'user_id' => $seqVal,
1966 'user_name' => $this->mName
,
1967 'user_password' => $this->mPassword
,
1968 'user_newpassword' => $this->mNewpassword
,
1969 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
1970 'user_email' => $this->mEmail
,
1971 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1972 'user_real_name' => $this->mRealName
,
1973 'user_options' => $this->encodeOptions(),
1974 'user_token' => $this->mToken
,
1975 'user_registration' => $dbw->timestamp( $this->mRegistration
),
1976 'user_editcount' => 0,
1979 $this->mId
= $dbw->insertId();
1981 # Clear instance cache other than user table data, which is already accurate
1982 $this->clearInstanceCache();
1986 * If the (non-anonymous) user is blocked, this function will block any IP address
1987 * that they successfully log on from.
1989 function spreadBlock() {
1990 wfDebug( __METHOD__
."()\n" );
1992 if ( $this->mId
== 0 ) {
1996 $userblock = Block
::newFromDB( '', $this->mId
);
1997 if ( !$userblock ) {
2001 $userblock->doAutoblock( wfGetIp() );
2006 * Generate a string which will be different for any combination of
2007 * user options which would produce different parser output.
2008 * This will be used as part of the hash key for the parser cache,
2009 * so users will the same options can share the same cached data
2012 * Extensions which require it should install 'PageRenderingHash' hook,
2013 * which will give them a chance to modify this key based on their own
2018 function getPageRenderingHash() {
2019 global $wgContLang, $wgUseDynamicDates;
2021 return $this->mHash
;
2024 // stubthreshold is only included below for completeness,
2025 // it will always be 0 when this function is called by parsercache.
2027 $confstr = $this->getOption( 'math' );
2028 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2029 if ( $wgUseDynamicDates ) {
2030 $confstr .= '!' . $this->getDatePreference();
2032 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2033 $confstr .= '!' . $this->getOption( 'language' );
2034 $confstr .= '!' . $this->getOption( 'thumbsize' );
2035 // add in language specific options, if any
2036 $extra = $wgContLang->getExtraHashOptions();
2039 // Give a chance for extensions to modify the hash, if they have
2040 // extra options or other effects on the parser cache.
2041 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2043 $this->mHash
= $confstr;
2047 function isBlockedFromCreateAccount() {
2048 $this->getBlockedStatus();
2049 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2052 function isAllowedToCreateAccount() {
2053 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2059 function setLoaded( $loaded ) {}
2062 * Get this user's personal page title.
2067 function getUserPage() {
2068 return Title
::makeTitle( NS_USER
, $this->getName() );
2072 * Get this user's talk page title.
2077 function getTalkPage() {
2078 $title = $this->getUserPage();
2079 return $title->getTalkPage();
2085 function getMaxID() {
2086 static $res; // cache
2088 if ( isset( $res ) )
2091 $dbr =& wfGetDB( DB_SLAVE
);
2092 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2097 * Determine whether the user is a newbie. Newbies are either
2098 * anonymous IPs, or the most recently created accounts.
2099 * @return bool True if it is a newbie.
2101 function isNewbie() {
2102 return !$this->isAllowed( 'autoconfirmed' );
2106 * Check to see if the given clear-text password is one of the accepted passwords
2107 * @param string $password User password.
2108 * @return bool True if the given password is correct otherwise False.
2110 function checkPassword( $password ) {
2114 // Even though we stop people from creating passwords that
2115 // are shorter than this, doesn't mean people wont be able
2116 // to. Certain authentication plugins do NOT want to save
2117 // domain passwords in a mysql database, so we should
2118 // check this (incase $wgAuth->strict() is false).
2119 if( !$this->isValidPassword( $password ) ) {
2123 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2125 } elseif( $wgAuth->strict() ) {
2126 /* Auth plugin doesn't allow local authentication */
2129 $ep = $this->encryptPassword( $password );
2130 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2132 } elseif ( function_exists( 'iconv' ) ) {
2133 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2134 # Check for this with iconv
2135 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2136 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2144 * Check if the given clear-text password matches the temporary password
2145 * sent by e-mail for password reset operations.
2148 function checkTemporaryPassword( $plaintext ) {
2149 $hash = $this->encryptPassword( $plaintext );
2150 return $hash === $this->mNewpassword
;
2154 * Initialize (if necessary) and return a session token value
2155 * which can be used in edit forms to show that the user's
2156 * login credentials aren't being hijacked with a foreign form
2159 * @param mixed $salt - Optional function-specific data for hash.
2160 * Use a string or an array of strings.
2164 function editToken( $salt = '' ) {
2165 if( !isset( $_SESSION['wsEditToken'] ) ) {
2166 $token = $this->generateToken();
2167 $_SESSION['wsEditToken'] = $token;
2169 $token = $_SESSION['wsEditToken'];
2171 if( is_array( $salt ) ) {
2172 $salt = implode( '|', $salt );
2174 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2178 * Generate a hex-y looking random token for various uses.
2179 * Could be made more cryptographically sure if someone cares.
2182 function generateToken( $salt = '' ) {
2183 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2184 return md5( $token . $salt );
2188 * Check given value against the token value stored in the session.
2189 * A match should confirm that the form was submitted from the
2190 * user's own login session, not a form submission from a third-party
2193 * @param string $val - the input value to compare
2194 * @param string $salt - Optional function-specific data for hash
2198 function matchEditToken( $val, $salt = '' ) {
2200 $sessionToken = $this->editToken( $salt );
2201 if ( $val != $sessionToken ) {
2202 wfDebug( "User::matchEditToken: broken session data\n" );
2204 return $val == $sessionToken;
2208 * Generate a new e-mail confirmation token and send a confirmation
2209 * mail to the user's given address.
2211 * @return mixed True on success, a WikiError object on failure.
2213 function sendConfirmationMail() {
2215 $expiration = null; // gets passed-by-ref and defined in next line.
2216 $url = $this->confirmationTokenUrl( $expiration );
2217 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2218 wfMsg( 'confirmemail_body',
2222 $wgContLang->timeanddate( $expiration, false ) ) );
2226 * Send an e-mail to this user's account. Does not check for
2227 * confirmed status or validity.
2229 * @param string $subject
2230 * @param string $body
2231 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2232 * @return mixed True on success, a WikiError object on failure.
2234 function sendMail( $subject, $body, $from = null ) {
2235 if( is_null( $from ) ) {
2236 global $wgPasswordSender;
2237 $from = $wgPasswordSender;
2240 require_once( 'UserMailer.php' );
2241 $to = new MailAddress( $this );
2242 $sender = new MailAddress( $from );
2243 $error = userMailer( $to, $sender, $subject, $body );
2245 if( $error == '' ) {
2248 return new WikiError( $error );
2253 * Generate, store, and return a new e-mail confirmation code.
2254 * A hash (unsalted since it's used as a key) is stored.
2255 * @param &$expiration mixed output: accepts the expiration time
2259 function confirmationToken( &$expiration ) {
2261 $expires = $now +
7 * 24 * 60 * 60;
2262 $expiration = wfTimestamp( TS_MW
, $expires );
2264 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2265 $hash = md5( $token );
2267 $dbw =& wfGetDB( DB_MASTER
);
2268 $dbw->update( 'user',
2269 array( 'user_email_token' => $hash,
2270 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2271 array( 'user_id' => $this->mId
),
2278 * Generate and store a new e-mail confirmation token, and return
2279 * the URL the user can use to confirm.
2280 * @param &$expiration mixed output: accepts the expiration time
2284 function confirmationTokenUrl( &$expiration ) {
2285 $token = $this->confirmationToken( $expiration );
2286 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2287 return $title->getFullUrl();
2291 * Mark the e-mail address confirmed and save.
2293 function confirmEmail() {
2295 $this->mEmailAuthenticated
= wfTimestampNow();
2296 $this->saveSettings();
2301 * Is this user allowed to send e-mails within limits of current
2302 * site configuration?
2305 function canSendEmail() {
2306 return $this->isEmailConfirmed();
2310 * Is this user allowed to receive e-mails within limits of current
2311 * site configuration?
2314 function canReceiveEmail() {
2315 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2319 * Is this user's e-mail address valid-looking and confirmed within
2320 * limits of the current site configuration?
2322 * If $wgEmailAuthentication is on, this may require the user to have
2323 * confirmed their address by returning a code or using a password
2324 * sent to the address from the wiki.
2328 function isEmailConfirmed() {
2329 global $wgEmailAuthentication;
2332 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2333 if( $this->isAnon() )
2335 if( !self
::isValidEmailAddr( $this->mEmail
) )
2337 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2346 * Return true if there is an outstanding request for e-mail confirmation.
2349 function isEmailConfirmationPending() {
2350 global $wgEmailAuthentication;
2351 return $wgEmailAuthentication &&
2352 !$this->isEmailConfirmed() &&
2353 $this->mEmailToken
&&
2354 $this->mEmailTokenExpires
> wfTimestamp();
2358 * @param array $groups list of groups
2359 * @return array list of permission key names for given groups combined
2362 static function getGroupPermissions( $groups ) {
2363 global $wgGroupPermissions;
2365 foreach( $groups as $group ) {
2366 if( isset( $wgGroupPermissions[$group] ) ) {
2367 $rights = array_merge( $rights,
2368 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2375 * @param string $group key name
2376 * @return string localized descriptive name for group, if provided
2379 static function getGroupName( $group ) {
2380 $key = "group-$group";
2381 $name = wfMsg( $key );
2382 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2390 * @param string $group key name
2391 * @return string localized descriptive name for member of a group, if provided
2394 static function getGroupMember( $group ) {
2395 $key = "group-$group-member";
2396 $name = wfMsg( $key );
2397 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2405 * Return the set of defined explicit groups.
2406 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2407 * groups are not included, as they are defined
2408 * automatically, not in the database.
2412 static function getAllGroups() {
2413 global $wgGroupPermissions;
2415 array_keys( $wgGroupPermissions ),
2416 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2420 * Get the title of a page describing a particular group
2422 * @param $group Name of the group
2425 static function getGroupPage( $group ) {
2426 $page = wfMsgForContent( 'grouppage-' . $group );
2427 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2428 $title = Title
::newFromText( $page );
2429 if( is_object( $title ) )
2436 * Create a link to the group in HTML, if available
2438 * @param $group Name of the group
2439 * @param $text The text of the link
2442 static function makeGroupLinkHTML( $group, $text = '' ) {
2444 $text = self
::getGroupName( $group );
2446 $title = self
::getGroupPage( $group );
2449 $sk = $wgUser->getSkin();
2450 return $sk->makeLinkObj( $title, $text );
2457 * Create a link to the group in Wikitext, if available
2459 * @param $group Name of the group
2460 * @param $text The text of the link (by default, the name of the group)
2463 static function makeGroupLinkWiki( $group, $text = '' ) {
2465 $text = self
::getGroupName( $group );
2467 $title = self
::getGroupPage( $group );
2469 $page = $title->getPrefixedText();
2470 return "[[$page|$text]]";
2477 * Increment the user's edit-count field.
2478 * Will have no effect for anonymous users.
2480 function incEditCount() {
2481 if( !$this->isAnon() ) {
2482 $dbw = wfGetDB( DB_MASTER
);
2483 $dbw->update( 'user',
2484 array( 'user_editcount=user_editcount+1' ),
2485 array( 'user_id' => $this->getId() ),
2488 // Lazy initialization check...
2489 if( $dbw->affectedRows() == 0 ) {
2490 // Pull from a slave to be less cruel to servers
2491 // Accuracy isn't the point anyway here
2492 $dbr = wfGetDB( DB_SLAVE
);
2493 $count = $dbr->selectField( 'revision',
2495 array( 'rev_user' => $this->getId() ),
2498 // Now here's a goddamn hack...
2499 if( $dbr !== $dbw ) {
2500 // If we actually have a slave server, the count is
2501 // at least one behind because the current transaction
2502 // has not been committed and replicated.
2505 // But if DB_SLAVE is selecting the master, then the
2506 // count we just read includes the revision that was
2507 // just added in the working transaction.
2510 $dbw->update( 'user',
2511 array( 'user_editcount' => $count ),
2512 array( 'user_id' => $this->getId() ),