8 # Number of characters in user_token field
9 define( 'USER_TOKEN_LENGTH', 32 );
11 # Serialized record version
12 define( 'MW_USER_VERSION', 4 );
21 * A list of default user toggles, i.e. boolean user preferences that are
22 * displayed by Special:Preferences as checkboxes. This list can be
23 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
25 static public $mToggles = array(
35 'editsectiononrightclick',
45 'enotifwatchlistpages',
46 'enotifusertalkpages',
49 'shownumberswatching',
62 * List of member variables which are saved to the shared cache (memcached).
63 * Any operation which changes the corresponding database fields must
64 * call a cache-clearing function.
66 static $mCacheVars = array(
78 'mEmailAuthenticated',
88 * The cache variable declarations
90 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
91 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
92 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
95 * Whether the cache variables have been loaded
100 * Initialisation data source if mDataLoaded==false. May be one of:
101 * defaults anonymous user initialised from class defaults
102 * name initialise from mName
103 * id initialise from mId
104 * session log in from cookies or session if possible
106 * Use the User::newFrom*() family of functions to set this.
111 * Lazy-initialised variables, invalidated with clearInstanceCache
113 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
114 $mBlockreason, $mBlock, $mEffectiveGroups;
117 * Lightweight constructor for anonymous user
118 * Use the User::newFrom* factory functions for other kinds of users
121 $this->clearInstanceCache( 'defaults' );
125 * Load the user table data for this object from the source given by mFrom
128 if ( $this->mDataLoaded
) {
131 wfProfileIn( __METHOD__
);
133 # Set it now to avoid infinite recursion in accessors
134 $this->mDataLoaded
= true;
136 switch ( $this->mFrom
) {
138 $this->loadDefaults();
141 $this->mId
= self
::idFromName( $this->mName
);
143 # Nonexistent user placeholder object
144 $this->loadDefaults( $this->mName
);
153 $this->loadFromSession();
156 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
158 wfProfileOut( __METHOD__
);
162 * Load user table data given mId
163 * @return false if the ID does not exist, true otherwise
166 function loadFromId() {
168 if ( $this->mId
== 0 ) {
169 $this->loadDefaults();
174 $key = wfMemcKey( 'user', 'id', $this->mId
);
175 $data = $wgMemc->get( $key );
177 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
178 # Object is expired, load from DB
183 wfDebug( "Cache miss for user {$this->mId}\n" );
185 if ( !$this->loadFromDatabase() ) {
186 # Can't load from ID, user is anonymous
192 foreach ( self
::$mCacheVars as $name ) {
193 $data[$name] = $this->$name;
195 $data['mVersion'] = MW_USER_VERSION
;
196 $wgMemc->set( $key, $data );
198 wfDebug( "Got user {$this->mId} from cache\n" );
200 foreach ( self
::$mCacheVars as $name ) {
201 $this->$name = $data[$name];
208 * Static factory method for creation from username.
210 * This is slightly less efficient than newFromId(), so use newFromId() if
211 * you have both an ID and a name handy.
213 * @param string $name Username, validated by Title:newFromText()
214 * @param mixed $validate Validate username. Takes the same parameters as
215 * User::getCanonicalName(), except that true is accepted as an alias
216 * for 'valid', for BC.
218 * @return User object, or null if the username is invalid. If the username
219 * is not present in the database, the result will be a user object with
220 * a name, zero user ID and default settings.
223 static function newFromName( $name, $validate = 'valid' ) {
224 if ( $validate === true ) {
227 $name = self
::getCanonicalName( $name, $validate );
228 if ( $name === false ) {
231 # Create unloaded user object
239 static function newFromId( $id ) {
247 * Factory method to fetch whichever user has a given email confirmation code.
248 * This code is generated when an account is created or its e-mail address
251 * If the code is invalid or has expired, returns NULL.
253 * @param string $code
257 static function newFromConfirmationCode( $code ) {
258 $dbr =& wfGetDB( DB_SLAVE
);
259 $id = $dbr->selectField( 'user', 'user_id', array(
260 'user_email_token' => md5( $code ),
261 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
263 if( $id !== false ) {
264 return User
::newFromId( $id );
271 * Create a new user object using data from session or cookies. If the
272 * login credentials are invalid, the result is an anonymous user.
277 static function newFromSession() {
279 $user->mFrom
= 'session';
284 * Get username given an id.
285 * @param integer $id Database user id
286 * @return string Nickname of a user
289 static function whoIs( $id ) {
290 $dbr =& wfGetDB( DB_SLAVE
);
291 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
295 * Get real username given an id.
296 * @param integer $id Database user id
297 * @return string Realname of a user
300 static function whoIsReal( $id ) {
301 $dbr =& wfGetDB( DB_SLAVE
);
302 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), 'User::whoIsReal' );
306 * Get database id given a user name
307 * @param string $name Nickname of a user
308 * @return integer|null Database user id (null: if non existent
311 static function idFromName( $name ) {
312 $nt = Title
::newFromText( $name );
313 if( is_null( $nt ) ) {
317 $dbr =& wfGetDB( DB_SLAVE
);
318 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
320 if ( $s === false ) {
328 * Does the string match an anonymous IPv4 address?
330 * This function exists for username validation, in order to reject
331 * usernames which are similar in form to IP addresses. Strings such
332 * as 300.300.300.300 will return true because it looks like an IP
333 * address, despite not being strictly valid.
335 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
336 * address because the usemod software would "cloak" anonymous IP
337 * addresses like this, if we allowed accounts like this to be created
338 * new users could get the old edits of these anonymous users.
343 * @param string $name Nickname of a user
346 static function isIP( $name ) {
347 return preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/",$name);
348 /*return preg_match("/^
349 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
350 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
351 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
352 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
357 * Is the input a valid username?
359 * Checks if the input is a valid username, we don't want an empty string,
360 * an IP address, anything that containins slashes (would mess up subpages),
361 * is longer than the maximum allowed username size or doesn't begin with
364 * @param string $name
368 static function isValidUserName( $name ) {
369 global $wgContLang, $wgMaxNameChars;
372 || User
::isIP( $name )
373 ||
strpos( $name, '/' ) !== false
374 ||
strlen( $name ) > $wgMaxNameChars
375 ||
$name != $wgContLang->ucfirst( $name ) )
378 // Ensure that the name can't be misresolved as a different title,
379 // such as with extra namespace keys at the start.
380 $parsed = Title
::newFromText( $name );
381 if( is_null( $parsed )
382 ||
$parsed->getNamespace()
383 ||
strcmp( $name, $parsed->getPrefixedText() ) )
386 // Check an additional blacklist of troublemaker characters.
387 // Should these be merged into the title char list?
388 $unicodeBlacklist = '/[' .
389 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
390 '\x{00a0}' . # non-breaking space
391 '\x{2000}-\x{200f}' . # various whitespace
392 '\x{2028}-\x{202f}' . # breaks and control chars
393 '\x{3000}' . # ideographic space
394 '\x{e000}-\x{f8ff}' . # private use
396 if( preg_match( $unicodeBlacklist, $name ) ) {
404 * Usernames which fail to pass this function will be blocked
405 * from user login and new account registrations, but may be used
406 * internally by batch processes.
408 * If an account already exists in this form, login will be blocked
409 * by a failure to pass this function.
411 * @param string $name
414 static function isUsableName( $name ) {
415 global $wgReservedUsernames;
417 // Must be a usable username, obviously ;)
418 self
::isValidUserName( $name ) &&
420 // Certain names may be reserved for batch processes.
421 !in_array( $name, $wgReservedUsernames );
425 * Usernames which fail to pass this function will be blocked
426 * from new account registrations, but may be used internally
427 * either by batch processes or by user accounts which have
428 * already been created.
430 * Additional character blacklisting may be added here
431 * rather than in isValidUserName() to avoid disrupting
434 * @param string $name
437 static function isCreatableName( $name ) {
439 self
::isUsableName( $name ) &&
441 // Registration-time character blacklisting...
442 strpos( $name, '@' ) === false;
446 * Is the input a valid password?
448 * @param string $password
452 static function isValidPassword( $password ) {
453 global $wgMinimalPasswordLength;
454 return strlen( $password ) >= $wgMinimalPasswordLength;
458 * Does the string match roughly an email address ?
460 * There used to be a regular expression here, it got removed because it
461 * rejected valid addresses. Actually just check if there is '@' somewhere
462 * in the given address.
464 * @todo Check for RFC 2822 compilance
467 * @param string $addr email address
471 static function isValidEmailAddr ( $addr ) {
472 return ( trim( $addr ) != '' ) &&
473 (false !== strpos( $addr, '@' ) );
477 * Given unvalidated user input, return a canonical username, or false if
478 * the username is invalid.
479 * @param string $name
480 * @param mixed $validate Type of validation to use:
481 * false No validation
482 * 'valid' Valid for batch processes
483 * 'usable' Valid for batch processes and login
484 * 'creatable' Valid for batch processes, login and account creation
486 static function getCanonicalName( $name, $validate = 'valid' ) {
487 # Force usernames to capital
489 $name = $wgContLang->ucfirst( $name );
491 # Clean up name according to title rules
492 $t = Title
::newFromText( $name );
493 if( is_null( $t ) ) {
497 # Reject various classes of invalid names
498 $name = $t->getText();
500 $name = $wgAuth->getCanonicalName( $t->getText() );
502 switch ( $validate ) {
506 if ( !User
::isValidUserName( $name ) ) {
511 if ( !User
::isUsableName( $name ) ) {
516 if ( !User
::isCreatableName( $name ) ) {
521 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
527 * Count the number of edits of a user
529 * @param int $uid The user ID to check
533 static function edits( $uid ) {
534 $dbr =& wfGetDB( DB_SLAVE
);
535 return $dbr->selectField(
536 'revision', 'count(*)',
537 array( 'rev_user' => $uid ),
543 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
544 * @todo: hash random numbers to improve security, like generateToken()
549 static function randomPassword() {
550 global $wgMinimalPasswordLength;
551 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
552 $l = strlen( $pwchars ) - 1;
554 $pwlength = max( 7, $wgMinimalPasswordLength );
555 $digit = mt_rand(0, $pwlength - 1);
557 for ( $i = 0; $i < $pwlength; $i++
) {
558 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
564 * Set cached properties to default. Note: this no longer clears
565 * uncached lazy-initialised properties. The constructor does that instead.
569 function loadDefaults( $name = false ) {
570 wfProfileIn( __METHOD__
);
572 global $wgCookiePrefix;
575 $this->mName
= $name;
576 $this->mRealName
= '';
577 $this->mPassword
= $this->mNewpassword
= '';
578 $this->mNewpassTime
= null;
580 $this->mOptions
= null; # Defer init
582 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
583 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
585 $this->mTouched
= '0'; # Allow any pages to be cached
588 $this->setToken(); # Random
589 $this->mEmailAuthenticated
= null;
590 $this->mEmailToken
= '';
591 $this->mEmailTokenExpires
= null;
592 $this->mRegistration
= wfTimestamp( TS_MW
);
593 $this->mGroups
= array();
595 wfProfileOut( __METHOD__
);
599 * Initialise php session
600 * @deprecated use wfSetupSession()
602 function SetupSession() {
607 * Load user data from the session or login cookie. If there are no valid
608 * credentials, initialises the user as an anon.
609 * @return true if the user is logged in, false otherwise
613 function loadFromSession() {
614 global $wgMemc, $wgCookiePrefix;
616 if ( isset( $_SESSION['wsUserID'] ) ) {
617 if ( 0 != $_SESSION['wsUserID'] ) {
618 $sId = $_SESSION['wsUserID'];
620 $this->loadDefaults();
623 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
624 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
625 $_SESSION['wsUserID'] = $sId;
627 $this->loadDefaults();
630 if ( isset( $_SESSION['wsUserName'] ) ) {
631 $sName = $_SESSION['wsUserName'];
632 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
633 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
634 $_SESSION['wsUserName'] = $sName;
636 $this->loadDefaults();
640 $passwordCorrect = FALSE;
642 if ( !$this->loadFromId() ) {
643 # Not a valid ID, loadFromId has switched the object to anon for us
647 if ( isset( $_SESSION['wsToken'] ) ) {
648 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
650 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
651 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
654 # No session or persistent login cookie
655 $this->loadDefaults();
659 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
660 wfDebug( "Logged in from $from\n" );
663 # Invalid credentials
664 wfDebug( "Can't log in from $from, invalid credentials\n" );
665 $this->loadDefaults();
671 * Load user and user_group data from the database
672 * $this->mId must be set, this is how the user is identified.
674 * @return true if the user exists, false if the user is anonymous
677 function loadFromDatabase() {
679 $this->mId
= intval( $this->mId
);
681 /** Anonymous user */
683 $this->loadDefaults();
687 $dbr =& wfGetDB( DB_SLAVE
);
688 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
690 if ( $s !== false ) {
691 # Initialise user table data
692 $this->mName
= $s->user_name
;
693 $this->mRealName
= $s->user_real_name
;
694 $this->mPassword
= $s->user_password
;
695 $this->mNewpassword
= $s->user_newpassword
;
696 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $s->user_newpass_time
);
697 $this->mEmail
= $s->user_email
;
698 $this->decodeOptions( $s->user_options
);
699 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
700 $this->mToken
= $s->user_token
;
701 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
702 $this->mEmailToken
= $s->user_email_token
;
703 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $s->user_email_token_expires
);
704 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $s->user_registration
);
707 $res = $dbr->select( 'user_groups',
709 array( 'ug_user' => $this->mId
),
711 $this->mGroups
= array();
712 while( $row = $dbr->fetchObject( $res ) ) {
713 $this->mGroups
[] = $row->ug_group
;
719 $this->loadDefaults();
725 * Clear various cached data stored in this object.
726 * @param string $reloadFrom Reload user and user_groups table data from a
727 * given source. May be "name", "id", "defaults", "session" or false for
730 function clearInstanceCache( $reloadFrom = false ) {
731 $this->mNewtalk
= -1;
732 $this->mDatePreference
= null;
733 $this->mBlockedby
= -1; # Unset
734 $this->mHash
= false;
736 $this->mRights
= null;
737 $this->mEffectiveGroups
= null;
740 $this->mDataLoaded
= false;
741 $this->mFrom
= $reloadFrom;
746 * Combine the language default options with any site-specific options
747 * and add the default language variants.
753 function getDefaultOptions() {
754 global $wgNamespacesToBeSearchedDefault;
756 * Site defaults will override the global/language defaults
758 global $wgDefaultUserOptions, $wgContLang;
759 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
762 * default language setting
764 $variant = $wgContLang->getPreferredVariant( false );
765 $defOpt['variant'] = $variant;
766 $defOpt['language'] = $variant;
768 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
769 $defOpt['searchNs'.$nsnum] = $val;
775 * Get a given default option value.
782 function getDefaultOption( $opt ) {
783 $defOpts = User
::getDefaultOptions();
784 if( isset( $defOpts[$opt] ) ) {
785 return $defOpts[$opt];
792 * Get a list of user toggle names
795 static function getToggles() {
797 $extraToggles = array();
798 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
799 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
804 * Get blocking information
806 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
807 * non-critical checks are done against slaves. Check when actually saving should be done against
810 function getBlockedStatus( $bFromSlave = true ) {
811 global $wgEnableSorbs, $wgProxyWhitelist;
813 if ( -1 != $this->mBlockedby
) {
814 wfDebug( "User::getBlockedStatus: already loaded.\n" );
818 wfProfileIn( __METHOD__
);
819 wfDebug( __METHOD__
.": checking...\n" );
821 $this->mBlockedby
= 0;
825 $this->mBlock
= new Block();
826 $this->mBlock
->fromMaster( !$bFromSlave );
827 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
828 wfDebug( __METHOD__
.": Found block.\n" );
829 $this->mBlockedby
= $this->mBlock
->mBy
;
830 $this->mBlockreason
= $this->mBlock
->mReason
;
831 if ( $this->isLoggedIn() ) {
832 $this->spreadBlock();
835 $this->mBlock
= null;
836 wfDebug( __METHOD__
.": No block.\n" );
840 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
843 if ( wfIsLocallyBlockedProxy( $ip ) ) {
844 $this->mBlockedby
= wfMsg( 'proxyblocker' );
845 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
849 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
850 if ( $this->inSorbsBlacklist( $ip ) ) {
851 $this->mBlockedby
= wfMsg( 'sorbs' );
852 $this->mBlockreason
= wfMsg( 'sorbsreason' );
858 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
860 wfProfileOut( __METHOD__
);
863 function inSorbsBlacklist( $ip ) {
864 global $wgEnableSorbs;
865 return $wgEnableSorbs &&
866 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
869 function inDnsBlacklist( $ip, $base ) {
870 wfProfileIn( __METHOD__
);
875 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
877 for ( $i=4; $i>=1; $i-- ) {
878 $host .= $m[$i] . '.';
883 $ipList = gethostbynamel( $host );
886 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
889 wfDebug( "Requested $host, not found in $base.\n" );
893 wfProfileOut( __METHOD__
);
898 * Primitive rate limits: enforce maximum actions per time period
899 * to put a brake on flooding.
901 * Note: when using a shared cache like memcached, IP-address
902 * last-hit counters will be shared across wikis.
904 * @return bool true if a rate limiter was tripped
907 function pingLimiter( $action='edit' ) {
908 global $wgRateLimits, $wgRateLimitsExcludedGroups;
909 if( !isset( $wgRateLimits[$action] ) ) {
913 # Some groups shouldn't trigger the ping limiter, ever
914 foreach( $this->getGroups() as $group ) {
915 if( array_search( $group, $wgRateLimitsExcludedGroups ) !== false )
919 global $wgMemc, $wgRateLimitLog;
920 wfProfileIn( __METHOD__
);
922 $limits = $wgRateLimits[$action];
924 $id = $this->getId();
927 if( isset( $limits['anon'] ) && $id == 0 ) {
928 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
931 if( isset( $limits['user'] ) && $id != 0 ) {
932 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
934 if( $this->isNewbie() ) {
935 if( isset( $limits['newbie'] ) && $id != 0 ) {
936 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
938 if( isset( $limits['ip'] ) ) {
939 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
941 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
942 $subnet = $matches[1];
943 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
948 foreach( $keys as $key => $limit ) {
949 list( $max, $period ) = $limit;
950 $summary = "(limit $max in {$period}s)";
951 $count = $wgMemc->get( $key );
953 if( $count > $max ) {
954 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
955 if( $wgRateLimitLog ) {
956 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
960 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
963 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
964 $wgMemc->add( $key, 1, intval( $period ) );
966 $wgMemc->incr( $key );
969 wfProfileOut( __METHOD__
);
974 * Check if user is blocked
975 * @return bool True if blocked, false otherwise
977 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
978 wfDebug( "User::isBlocked: enter\n" );
979 $this->getBlockedStatus( $bFromSlave );
980 return $this->mBlockedby
!== 0;
984 * Check if user is blocked from editing a particular article
986 function isBlockedFrom( $title, $bFromSlave = false ) {
987 global $wgBlockAllowsUTEdit;
988 wfProfileIn( __METHOD__
);
989 wfDebug( __METHOD__
.": enter\n" );
991 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
992 $title->getNamespace() == NS_USER_TALK
)
995 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
997 wfDebug( __METHOD__
.": asking isBlocked()\n" );
998 $blocked = $this->isBlocked( $bFromSlave );
1000 wfProfileOut( __METHOD__
);
1005 * Get name of blocker
1006 * @return string name of blocker
1008 function blockedBy() {
1009 $this->getBlockedStatus();
1010 return $this->mBlockedby
;
1014 * Get blocking reason
1015 * @return string Blocking reason
1017 function blockedFor() {
1018 $this->getBlockedStatus();
1019 return $this->mBlockreason
;
1023 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1031 * Set the user and reload all fields according to that ID
1032 * @deprecated use User::newFromId()
1034 function setID( $v ) {
1036 $this->clearInstanceCache( 'id' );
1040 * Get the user name, or the IP for anons
1042 function getName() {
1043 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1044 # Special case optimisation
1045 return $this->mName
;
1048 if ( $this->mName
=== false ) {
1049 $this->mName
= wfGetIP();
1051 return $this->mName
;
1056 * Set the user name.
1058 * This does not reload fields from the database according to the given
1059 * name. Rather, it is used to create a temporary "nonexistent user" for
1060 * later addition to the database. It can also be used to set the IP
1061 * address for an anonymous user to something other than the current
1064 * User::newFromName() has rougly the same function, when the named user
1067 function setName( $str ) {
1069 $this->mName
= $str;
1073 * Return the title dbkey form of the name, for eg user pages.
1077 function getTitleKey() {
1078 return str_replace( ' ', '_', $this->getName() );
1081 function getNewtalk() {
1084 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1085 if( $this->mNewtalk
=== -1 ) {
1086 $this->mNewtalk
= false; # reset talk page status
1088 # Check memcached separately for anons, who have no
1089 # entire User object stored in there.
1092 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1093 $newtalk = $wgMemc->get( $key );
1094 if( is_integer( $newtalk ) ) {
1095 $this->mNewtalk
= (bool)$newtalk;
1097 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
1098 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
1101 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1105 return (bool)$this->mNewtalk
;
1109 * Return the talk page(s) this user has new messages on.
1111 function getNewMessageLinks() {
1113 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1116 if (!$this->getNewtalk())
1118 $up = $this->getUserPage();
1119 $utp = $up->getTalkPage();
1120 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1125 * Perform a user_newtalk check on current slaves; if the memcached data
1126 * is funky we don't want newtalk state to get stuck on save, as that's
1129 * @param string $field
1134 function checkNewtalk( $field, $id ) {
1135 $dbr =& wfGetDB( DB_SLAVE
);
1136 $ok = $dbr->selectField( 'user_newtalk', $field,
1137 array( $field => $id ), __METHOD__
);
1138 return $ok !== false;
1143 * @param string $field
1147 function updateNewtalk( $field, $id ) {
1148 if( $this->checkNewtalk( $field, $id ) ) {
1149 wfDebug( __METHOD__
." already set ($field, $id), ignoring\n" );
1152 $dbw =& wfGetDB( DB_MASTER
);
1153 $dbw->insert( 'user_newtalk',
1154 array( $field => $id ),
1157 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1162 * Clear the new messages flag for the given user
1163 * @param string $field
1167 function deleteNewtalk( $field, $id ) {
1168 if( !$this->checkNewtalk( $field, $id ) ) {
1169 wfDebug( __METHOD__
.": already gone ($field, $id), ignoring\n" );
1172 $dbw =& wfGetDB( DB_MASTER
);
1173 $dbw->delete( 'user_newtalk',
1174 array( $field => $id ),
1176 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1181 * Update the 'You have new messages!' status.
1184 function setNewtalk( $val ) {
1185 if( wfReadOnly() ) {
1190 $this->mNewtalk
= $val;
1192 if( $this->isAnon() ) {
1194 $id = $this->getName();
1197 $id = $this->getId();
1201 $changed = $this->updateNewtalk( $field, $id );
1203 $changed = $this->deleteNewtalk( $field, $id );
1207 if( $this->isAnon() ) {
1208 // Anons have a separate memcached space, since
1209 // user records aren't kept for them.
1211 $key = wfMemcKey( 'newtalk', 'ip', $val );
1212 $wgMemc->set( $key, $val ?
1 : 0 );
1215 // Make sure the user page is watched, so a notification
1216 // will be sent out if enabled.
1217 $this->addWatch( $this->getTalkPage() );
1220 $this->invalidateCache();
1225 * Generate a current or new-future timestamp to be stored in the
1226 * user_touched field when we update things.
1228 private static function newTouchedTimestamp() {
1229 global $wgClockSkewFudge;
1230 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1234 * Clear user data from memcached.
1235 * Use after applying fun updates to the database; caller's
1236 * responsibility to update user_touched if appropriate.
1238 * Called implicitly from invalidateCache() and saveSettings().
1240 private function clearSharedCache() {
1243 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1248 * Immediately touch the user data cache for this account.
1249 * Updates user_touched field, and removes account data from memcached
1250 * for reload on the next hit.
1252 function invalidateCache() {
1255 $this->mTouched
= self
::newTouchedTimestamp();
1257 $dbw =& wfGetDB( DB_MASTER
);
1258 $dbw->update( 'user',
1259 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1260 array( 'user_id' => $this->mId
),
1263 $this->clearSharedCache();
1267 function validateCache( $timestamp ) {
1269 return ($timestamp >= $this->mTouched
);
1273 * Encrypt a password.
1274 * It can eventuall salt a password @see User::addSalt()
1275 * @param string $p clear Password.
1276 * @return string Encrypted password.
1278 function encryptPassword( $p ) {
1280 return wfEncryptPassword( $this->mId
, $p );
1284 * Set the password and reset the random token
1286 function setPassword( $str ) {
1289 $this->mPassword
= $this->encryptPassword( $str );
1290 $this->mNewpassword
= '';
1291 $this->mNewpassTime
= NULL;
1295 * Set the random token (used for persistent authentication)
1296 * Called from loadDefaults() among other places.
1299 function setToken( $token = false ) {
1300 global $wgSecretKey, $wgProxyKey;
1303 if ( $wgSecretKey ) {
1304 $key = $wgSecretKey;
1305 } elseif ( $wgProxyKey ) {
1310 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1312 $this->mToken
= $token;
1316 function setCookiePassword( $str ) {
1318 $this->mCookiePassword
= md5( $str );
1322 * Set the password for a password reminder or new account email
1323 * Sets the user_newpass_time field if $throttle is true
1325 function setNewpassword( $str, $throttle = true ) {
1327 $this->mNewpassword
= $this->encryptPassword( $str );
1329 $this->mNewpassTime
= wfTimestampNow();
1334 * Returns true if a password reminder email has already been sent within
1335 * the last $wgPasswordReminderResendTime hours
1337 function isPasswordReminderThrottled() {
1338 global $wgPasswordReminderResendTime;
1340 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1343 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1344 return time() < $expiry;
1347 function getEmail() {
1349 return $this->mEmail
;
1352 function getEmailAuthenticationTimestamp() {
1354 return $this->mEmailAuthenticated
;
1357 function setEmail( $str ) {
1359 $this->mEmail
= $str;
1362 function getRealName() {
1364 return $this->mRealName
;
1367 function setRealName( $str ) {
1369 $this->mRealName
= $str;
1373 * @param string $oname The option to check
1376 function getOption( $oname ) {
1378 if ( is_null( $this->mOptions
) ) {
1379 $this->mOptions
= User
::getDefaultOptions();
1381 if ( array_key_exists( $oname, $this->mOptions
) ) {
1382 return trim( $this->mOptions
[$oname] );
1389 * Get the user's date preference, including some important migration for
1392 function getDatePreference() {
1393 if ( is_null( $this->mDatePreference
) ) {
1395 $value = $this->getOption( 'date' );
1396 $map = $wgLang->getDatePreferenceMigrationMap();
1397 if ( isset( $map[$value] ) ) {
1398 $value = $map[$value];
1400 $this->mDatePreference
= $value;
1402 return $this->mDatePreference
;
1406 * @param string $oname The option to check
1407 * @return bool False if the option is not selected, true if it is
1409 function getBoolOption( $oname ) {
1410 return (bool)$this->getOption( $oname );
1414 * Get an option as an integer value from the source string.
1415 * @param string $oname The option to check
1416 * @param int $default Optional value to return if option is unset/blank.
1419 function getIntOption( $oname, $default=0 ) {
1420 $val = $this->getOption( $oname );
1424 return intval( $val );
1427 function setOption( $oname, $val ) {
1429 if ( is_null( $this->mOptions
) ) {
1430 $this->mOptions
= User
::getDefaultOptions();
1432 if ( $oname == 'skin' ) {
1433 # Clear cached skin, so the new one displays immediately in Special:Preferences
1434 unset( $this->mSkin
);
1436 // Filter out any newlines that may have passed through input validation.
1437 // Newlines are used to separate items in the options blob.
1438 $val = str_replace( "\r\n", "\n", $val );
1439 $val = str_replace( "\r", "\n", $val );
1440 $val = str_replace( "\n", " ", $val );
1441 $this->mOptions
[$oname] = $val;
1444 function getRights() {
1445 if ( is_null( $this->mRights
) ) {
1446 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1448 return $this->mRights
;
1452 * Get the list of explicit group memberships this user has.
1453 * The implicit * and user groups are not included.
1454 * @return array of strings
1456 function getGroups() {
1458 return $this->mGroups
;
1462 * Get the list of implicit group memberships this user has.
1463 * This includes all explicit groups, plus 'user' if logged in
1464 * and '*' for all accounts.
1465 * @param boolean $recache Don't use the cache
1466 * @return array of strings
1468 function getEffectiveGroups( $recache = false ) {
1469 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1471 $this->mEffectiveGroups
= $this->mGroups
;
1472 $this->mEffectiveGroups
[] = '*';
1474 $this->mEffectiveGroups
[] = 'user';
1476 global $wgAutoConfirmAge;
1477 $accountAge = time() - wfTimestampOrNull( TS_UNIX
, $this->mRegistration
);
1478 if( $accountAge >= $wgAutoConfirmAge ) {
1479 $this->mEffectiveGroups
[] = 'autoconfirmed';
1482 # Implicit group for users whose email addresses are confirmed
1483 global $wgEmailAuthentication;
1484 if( self
::isValidEmailAddr( $this->mEmail
) ) {
1485 if( $wgEmailAuthentication ) {
1486 if( $this->mEmailAuthenticated
)
1487 $this->mEffectiveGroups
[] = 'emailconfirmed';
1489 $this->mEffectiveGroups
[] = 'emailconfirmed';
1494 return $this->mEffectiveGroups
;
1498 * Add the user to the given group.
1499 * This takes immediate effect.
1502 function addGroup( $group ) {
1504 $dbw =& wfGetDB( DB_MASTER
);
1505 $dbw->insert( 'user_groups',
1507 'ug_user' => $this->getID(),
1508 'ug_group' => $group,
1511 array( 'IGNORE' ) );
1513 $this->mGroups
[] = $group;
1514 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1516 $this->invalidateCache();
1520 * Remove the user from the given group.
1521 * This takes immediate effect.
1524 function removeGroup( $group ) {
1526 $dbw =& wfGetDB( DB_MASTER
);
1527 $dbw->delete( 'user_groups',
1529 'ug_user' => $this->getID(),
1530 'ug_group' => $group,
1532 'User::removeGroup' );
1534 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1535 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1537 $this->invalidateCache();
1542 * A more legible check for non-anonymousness.
1543 * Returns true if the user is not an anonymous visitor.
1547 function isLoggedIn() {
1548 return( $this->getID() != 0 );
1552 * A more legible check for anonymousness.
1553 * Returns true if the user is an anonymous visitor.
1558 return !$this->isLoggedIn();
1562 * Whether the user is a bot
1566 return $this->isAllowed( 'bot' );
1570 * Check if user is allowed to access a feature / make an action
1571 * @param string $action Action to be checked
1572 * @return boolean True: action is allowed, False: action should not be allowed
1574 function isAllowed($action='') {
1575 if ( $action === '' )
1576 // In the spirit of DWIM
1579 return in_array( $action, $this->getRights() );
1583 * Load a skin if it doesn't exist or return it
1584 * @todo FIXME : need to check the old failback system [AV]
1586 function &getSkin() {
1587 global $IP, $wgRequest;
1588 if ( ! isset( $this->mSkin
) ) {
1589 wfProfileIn( __METHOD__
);
1592 $userSkin = $this->getOption( 'skin' );
1593 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1595 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1596 wfProfileOut( __METHOD__
);
1598 return $this->mSkin
;
1602 * @param string $title Article title to look at
1606 * Check watched status of an article
1607 * @return bool True if article is watched
1609 function isWatched( $title ) {
1610 $wl = WatchedItem
::fromUserTitle( $this, $title );
1611 return $wl->isWatched();
1617 function addWatch( $title ) {
1618 $wl = WatchedItem
::fromUserTitle( $this, $title );
1620 $this->invalidateCache();
1624 * Stop watching an article
1626 function removeWatch( $title ) {
1627 $wl = WatchedItem
::fromUserTitle( $this, $title );
1629 $this->invalidateCache();
1633 * Clear the user's notification timestamp for the given title.
1634 * If e-notif e-mails are on, they will receive notification mails on
1635 * the next change of the page if it's watched etc.
1637 function clearNotification( &$title ) {
1638 global $wgUser, $wgUseEnotif;
1640 if ($title->getNamespace() == NS_USER_TALK
&&
1641 $title->getText() == $this->getName() ) {
1642 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1644 $this->setNewtalk( false );
1647 if( !$wgUseEnotif ) {
1651 if( $this->isAnon() ) {
1652 // Nothing else to do...
1656 // Only update the timestamp if the page is being watched.
1657 // The query to find out if it is watched is cached both in memcached and per-invocation,
1658 // and when it does have to be executed, it can be on a slave
1659 // If this is the user's newtalk page, we always update the timestamp
1660 if ($title->getNamespace() == NS_USER_TALK
&&
1661 $title->getText() == $wgUser->getName())
1664 } elseif ( $this->getID() == $wgUser->getID() ) {
1665 $watched = $title->userIsWatching();
1670 // If the page is watched by the user (or may be watched), update the timestamp on any
1671 // any matching rows
1673 $dbw =& wfGetDB( DB_MASTER
);
1674 $success = $dbw->update( 'watchlist',
1676 'wl_notificationtimestamp' => NULL
1677 ), array( /* WHERE */
1678 'wl_title' => $title->getDBkey(),
1679 'wl_namespace' => $title->getNamespace(),
1680 'wl_user' => $this->getID()
1681 ), 'User::clearLastVisited'
1689 * Resets all of the given user's page-change notification timestamps.
1690 * If e-notif e-mails are on, they will receive notification mails on
1691 * the next change of any watched page.
1693 * @param int $currentUser user ID number
1696 function clearAllNotifications( $currentUser ) {
1697 global $wgUseEnotif;
1698 if ( !$wgUseEnotif ) {
1699 $this->setNewtalk( false );
1702 if( $currentUser != 0 ) {
1704 $dbw =& wfGetDB( DB_MASTER
);
1705 $success = $dbw->update( 'watchlist',
1707 'wl_notificationtimestamp' => NULL
1708 ), array( /* WHERE */
1709 'wl_user' => $currentUser
1710 ), 'UserMailer::clearAll'
1713 # we also need to clear here the "you have new message" notification for the own user_talk page
1714 # This is cleared one page view later in Article::viewUpdates();
1720 * @return string Encoding options
1722 function encodeOptions() {
1724 if ( is_null( $this->mOptions
) ) {
1725 $this->mOptions
= User
::getDefaultOptions();
1728 foreach ( $this->mOptions
as $oname => $oval ) {
1729 array_push( $a, $oname.'='.$oval );
1731 $s = implode( "\n", $a );
1738 function decodeOptions( $str ) {
1739 $this->mOptions
= array();
1740 $a = explode( "\n", $str );
1741 foreach ( $a as $s ) {
1742 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1743 $this->mOptions
[$m[1]] = $m[2];
1748 function setCookies() {
1749 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1751 if ( 0 == $this->mId
) return;
1752 $exp = time() +
$wgCookieExpiration;
1754 $_SESSION['wsUserID'] = $this->mId
;
1755 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1757 $_SESSION['wsUserName'] = $this->getName();
1758 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1760 $_SESSION['wsToken'] = $this->mToken
;
1761 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1762 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1764 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1770 * Clears the cookies and session, resets the instance cache
1773 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1774 $this->clearInstanceCache( 'defaults' );
1776 $_SESSION['wsUserID'] = 0;
1778 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1779 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1781 # Remember when user logged out, to prevent seeing cached pages
1782 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1786 * Save object settings into database
1787 * @fixme Only rarely do all these fields need to be set!
1789 function saveSettings() {
1791 if ( wfReadOnly() ) { return; }
1792 if ( 0 == $this->mId
) { return; }
1794 $this->mTouched
= self
::newTouchedTimestamp();
1796 $dbw =& wfGetDB( DB_MASTER
);
1797 $dbw->update( 'user',
1799 'user_name' => $this->mName
,
1800 'user_password' => $this->mPassword
,
1801 'user_newpassword' => $this->mNewpassword
,
1802 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
1803 'user_real_name' => $this->mRealName
,
1804 'user_email' => $this->mEmail
,
1805 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1806 'user_options' => $this->encodeOptions(),
1807 'user_touched' => $dbw->timestamp($this->mTouched
),
1808 'user_token' => $this->mToken
1809 ), array( /* WHERE */
1810 'user_id' => $this->mId
1813 $this->clearSharedCache();
1818 * Checks if a user with the given name exists, returns the ID
1820 function idForName() {
1822 $s = trim( $this->getName() );
1823 if ( 0 == strcmp( '', $s ) ) return 0;
1825 $dbr =& wfGetDB( DB_SLAVE
);
1826 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
1827 if ( $id === false ) {
1834 * Add a user to the database, return the user object
1836 * @param string $name The user's name
1837 * @param array $params Associative array of non-default parameters to save to the database:
1838 * password The user's password. Password logins will be disabled if this is omitted.
1839 * newpassword A temporary password mailed to the user
1840 * email The user's email address
1841 * email_authenticated The email authentication timestamp
1842 * real_name The user's real name
1843 * options An associative array of non-default options
1844 * token Random authentication token. Do not set.
1845 * registration Registration timestamp. Do not set.
1847 * @return User object, or null if the username already exists
1849 static function createNew( $name, $params = array() ) {
1852 if ( isset( $params['options'] ) ) {
1853 $user->mOptions
= $params['options'] +
$user->mOptions
;
1854 unset( $params['options'] );
1856 $dbw =& wfGetDB( DB_MASTER
);
1857 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1859 'user_id' => $seqVal,
1860 'user_name' => $name,
1861 'user_password' => $user->mPassword
,
1862 'user_newpassword' => $user->mNewpassword
,
1863 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
1864 'user_email' => $user->mEmail
,
1865 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
1866 'user_real_name' => $user->mRealName
,
1867 'user_options' => $user->encodeOptions(),
1868 'user_token' => $user->mToken
,
1869 'user_registration' => $dbw->timestamp( $user->mRegistration
),
1871 foreach ( $params as $name => $value ) {
1872 $fields["user_$name"] = $value;
1874 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
1875 if ( $dbw->affectedRows() ) {
1876 $newUser = User
::newFromId( $dbw->insertId() );
1884 * Add an existing user object to the database
1886 function addToDatabase() {
1888 $dbw =& wfGetDB( DB_MASTER
);
1889 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1890 $dbw->insert( 'user',
1892 'user_id' => $seqVal,
1893 'user_name' => $this->mName
,
1894 'user_password' => $this->mPassword
,
1895 'user_newpassword' => $this->mNewpassword
,
1896 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
1897 'user_email' => $this->mEmail
,
1898 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1899 'user_real_name' => $this->mRealName
,
1900 'user_options' => $this->encodeOptions(),
1901 'user_token' => $this->mToken
,
1902 'user_registration' => $dbw->timestamp( $this->mRegistration
),
1905 $this->mId
= $dbw->insertId();
1907 # Clear instance cache other than user table data, which is already accurate
1908 $this->clearInstanceCache();
1912 * If the (non-anonymous) user is blocked, this function will block any IP address
1913 * that they successfully log on from.
1915 function spreadBlock() {
1916 wfDebug( __METHOD__
."()\n" );
1918 if ( $this->mId
== 0 ) {
1922 $userblock = Block
::newFromDB( '', $this->mId
);
1923 if ( !$userblock ) {
1927 # Check if this IP address is already blocked
1928 $ipblock = Block
::newFromDB( wfGetIP() );
1930 # If the user is already blocked. Then check if the autoblock would
1931 # excede the user block. If it would excede, then do nothing, else
1932 # prolong block time
1933 if ($userblock->mExpiry
&&
1934 ($userblock->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
1937 # Just update the timestamp
1938 $ipblock->updateTimestamp();
1941 $ipblock = new Block
;
1944 # Make a new block object with the desired properties
1945 wfDebug( "Autoblocking {$this->mName}@" . wfGetIP() . "\n" );
1946 $ipblock->mAddress
= wfGetIP();
1947 $ipblock->mUser
= 0;
1948 $ipblock->mBy
= $userblock->mBy
;
1949 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1950 $ipblock->mTimestamp
= wfTimestampNow();
1951 $ipblock->mAuto
= 1;
1952 # If the user is already blocked with an expiry date, we don't
1953 # want to pile on top of that!
1954 if($userblock->mExpiry
) {
1955 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1957 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1966 * Generate a string which will be different for any combination of
1967 * user options which would produce different parser output.
1968 * This will be used as part of the hash key for the parser cache,
1969 * so users will the same options can share the same cached data
1972 * Extensions which require it should install 'PageRenderingHash' hook,
1973 * which will give them a chance to modify this key based on their own
1978 function getPageRenderingHash() {
1979 global $wgContLang, $wgUseDynamicDates;
1981 return $this->mHash
;
1984 // stubthreshold is only included below for completeness,
1985 // it will always be 0 when this function is called by parsercache.
1987 $confstr = $this->getOption( 'math' );
1988 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1989 if ( $wgUseDynamicDates ) {
1990 $confstr .= '!' . $this->getDatePreference();
1992 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
1993 $confstr .= '!' . $this->getOption( 'language' );
1994 $confstr .= '!' . $this->getOption( 'thumbsize' );
1995 // add in language specific options, if any
1996 $extra = $wgContLang->getExtraHashOptions();
1999 // Give a chance for extensions to modify the hash, if they have
2000 // extra options or other effects on the parser cache.
2001 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2003 $this->mHash
= $confstr;
2007 function isBlockedFromCreateAccount() {
2008 $this->getBlockedStatus();
2009 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2012 function isAllowedToCreateAccount() {
2013 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2019 function setLoaded( $loaded ) {}
2022 * Get this user's personal page title.
2027 function getUserPage() {
2028 return Title
::makeTitle( NS_USER
, $this->getName() );
2032 * Get this user's talk page title.
2037 function getTalkPage() {
2038 $title = $this->getUserPage();
2039 return $title->getTalkPage();
2045 function getMaxID() {
2046 static $res; // cache
2048 if ( isset( $res ) )
2051 $dbr =& wfGetDB( DB_SLAVE
);
2052 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2057 * Determine whether the user is a newbie. Newbies are either
2058 * anonymous IPs, or the most recently created accounts.
2059 * @return bool True if it is a newbie.
2061 function isNewbie() {
2062 return !$this->isAllowed( 'autoconfirmed' );
2066 * Check to see if the given clear-text password is one of the accepted passwords
2067 * @param string $password User password.
2068 * @return bool True if the given password is correct otherwise False.
2070 function checkPassword( $password ) {
2071 global $wgAuth, $wgMinimalPasswordLength;
2074 // Even though we stop people from creating passwords that
2075 // are shorter than this, doesn't mean people wont be able
2076 // to. Certain authentication plugins do NOT want to save
2077 // domain passwords in a mysql database, so we should
2078 // check this (incase $wgAuth->strict() is false).
2079 if( strlen( $password ) < $wgMinimalPasswordLength ) {
2083 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2085 } elseif( $wgAuth->strict() ) {
2086 /* Auth plugin doesn't allow local authentication */
2089 $ep = $this->encryptPassword( $password );
2090 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2092 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
2094 } elseif ( function_exists( 'iconv' ) ) {
2095 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2096 # Check for this with iconv
2097 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2098 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2106 * Initialize (if necessary) and return a session token value
2107 * which can be used in edit forms to show that the user's
2108 * login credentials aren't being hijacked with a foreign form
2111 * @param mixed $salt - Optional function-specific data for hash.
2112 * Use a string or an array of strings.
2116 function editToken( $salt = '' ) {
2117 if( !isset( $_SESSION['wsEditToken'] ) ) {
2118 $token = $this->generateToken();
2119 $_SESSION['wsEditToken'] = $token;
2121 $token = $_SESSION['wsEditToken'];
2123 if( is_array( $salt ) ) {
2124 $salt = implode( '|', $salt );
2126 return md5( $token . $salt );
2130 * Generate a hex-y looking random token for various uses.
2131 * Could be made more cryptographically sure if someone cares.
2134 function generateToken( $salt = '' ) {
2135 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2136 return md5( $token . $salt );
2140 * Check given value against the token value stored in the session.
2141 * A match should confirm that the form was submitted from the
2142 * user's own login session, not a form submission from a third-party
2145 * @param string $val - the input value to compare
2146 * @param string $salt - Optional function-specific data for hash
2150 function matchEditToken( $val, $salt = '' ) {
2152 $sessionToken = $this->editToken( $salt );
2153 if ( $val != $sessionToken ) {
2154 wfDebug( "User::matchEditToken: broken session data\n" );
2156 return $val == $sessionToken;
2160 * Generate a new e-mail confirmation token and send a confirmation
2161 * mail to the user's given address.
2163 * @return mixed True on success, a WikiError object on failure.
2165 function sendConfirmationMail() {
2167 $url = $this->confirmationTokenUrl( $expiration );
2168 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2169 wfMsg( 'confirmemail_body',
2173 $wgContLang->timeanddate( $expiration, false ) ) );
2177 * Send an e-mail to this user's account. Does not check for
2178 * confirmed status or validity.
2180 * @param string $subject
2181 * @param string $body
2182 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2183 * @return mixed True on success, a WikiError object on failure.
2185 function sendMail( $subject, $body, $from = null ) {
2186 if( is_null( $from ) ) {
2187 global $wgPasswordSender;
2188 $from = $wgPasswordSender;
2191 require_once( 'UserMailer.php' );
2192 $to = new MailAddress( $this );
2193 $sender = new MailAddress( $from );
2194 $error = userMailer( $to, $sender, $subject, $body );
2196 if( $error == '' ) {
2199 return new WikiError( $error );
2204 * Generate, store, and return a new e-mail confirmation code.
2205 * A hash (unsalted since it's used as a key) is stored.
2206 * @param &$expiration mixed output: accepts the expiration time
2210 function confirmationToken( &$expiration ) {
2212 $expires = $now +
7 * 24 * 60 * 60;
2213 $expiration = wfTimestamp( TS_MW
, $expires );
2215 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2216 $hash = md5( $token );
2218 $dbw =& wfGetDB( DB_MASTER
);
2219 $dbw->update( 'user',
2220 array( 'user_email_token' => $hash,
2221 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2222 array( 'user_id' => $this->mId
),
2229 * Generate and store a new e-mail confirmation token, and return
2230 * the URL the user can use to confirm.
2231 * @param &$expiration mixed output: accepts the expiration time
2235 function confirmationTokenUrl( &$expiration ) {
2236 $token = $this->confirmationToken( $expiration );
2237 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2238 return $title->getFullUrl();
2242 * Mark the e-mail address confirmed and save.
2244 function confirmEmail() {
2246 $this->mEmailAuthenticated
= wfTimestampNow();
2247 $this->saveSettings();
2252 * Is this user allowed to send e-mails within limits of current
2253 * site configuration?
2256 function canSendEmail() {
2257 return $this->isEmailConfirmed();
2261 * Is this user allowed to receive e-mails within limits of current
2262 * site configuration?
2265 function canReceiveEmail() {
2266 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2270 * Is this user's e-mail address valid-looking and confirmed within
2271 * limits of the current site configuration?
2273 * If $wgEmailAuthentication is on, this may require the user to have
2274 * confirmed their address by returning a code or using a password
2275 * sent to the address from the wiki.
2279 function isEmailConfirmed() {
2280 global $wgEmailAuthentication;
2283 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2284 if( $this->isAnon() )
2286 if( !self
::isValidEmailAddr( $this->mEmail
) )
2288 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2297 * @param array $groups list of groups
2298 * @return array list of permission key names for given groups combined
2301 static function getGroupPermissions( $groups ) {
2302 global $wgGroupPermissions;
2304 foreach( $groups as $group ) {
2305 if( isset( $wgGroupPermissions[$group] ) ) {
2306 $rights = array_merge( $rights,
2307 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2314 * @param string $group key name
2315 * @return string localized descriptive name for group, if provided
2318 static function getGroupName( $group ) {
2319 $key = "group-$group";
2320 $name = wfMsg( $key );
2321 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2329 * @param string $group key name
2330 * @return string localized descriptive name for member of a group, if provided
2333 static function getGroupMember( $group ) {
2334 $key = "group-$group-member";
2335 $name = wfMsg( $key );
2336 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2344 * Return the set of defined explicit groups.
2345 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2346 * groups are not included, as they are defined
2347 * automatically, not in the database.
2351 static function getAllGroups() {
2352 global $wgGroupPermissions;
2354 array_keys( $wgGroupPermissions ),
2355 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2359 * Get the title of a page describing a particular group
2361 * @param $group Name of the group
2364 static function getGroupPage( $group ) {
2365 $page = wfMsgForContent( 'grouppage-' . $group );
2366 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2367 $title = Title
::newFromText( $page );
2368 if( is_object( $title ) )
2375 * Create a link to the group in HTML, if available
2377 * @param $group Name of the group
2378 * @param $text The text of the link
2381 static function makeGroupLinkHTML( $group, $text = '' ) {
2383 $text = self
::getGroupName( $group );
2385 $title = self
::getGroupPage( $group );
2388 $sk = $wgUser->getSkin();
2389 return $sk->makeLinkObj( $title, $text );
2396 * Create a link to the group in Wikitext, if available
2398 * @param $group Name of the group
2399 * @param $text The text of the link (by default, the name of the group)
2402 static function makeGroupLinkWiki( $group, $text = '' ) {
2404 $text = self
::getGroupName( $group );
2406 $title = self
::getGroupPage( $group );
2408 $page = $title->getPrefixedText();
2409 return "[[$page|$text]]";