92381e767e5b295b0b4e2b081b0affc4a63b6de8
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', '\\' );
26 * A list of default user toggles, i.e. boolean user preferences that are
27 * displayed by Special:Preferences as checkboxes. This list can be
28 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
30 static public $mToggles = array(
40 'editsectiononrightclick',
50 'enotifwatchlistpages',
51 'enotifusertalkpages',
54 'shownumberswatching',
68 * List of member variables which are saved to the shared cache (memcached).
69 * Any operation which changes the corresponding database fields must
70 * call a cache-clearing function.
72 static $mCacheVars = array(
84 'mEmailAuthenticated',
94 * The cache variable declarations
96 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
97 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
98 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
101 * Whether the cache variables have been loaded
106 * Initialisation data source if mDataLoaded==false. May be one of:
107 * defaults anonymous user initialised from class defaults
108 * name initialise from mName
109 * id initialise from mId
110 * session log in from cookies or session if possible
112 * Use the User::newFrom*() family of functions to set this.
117 * Lazy-initialised variables, invalidated with clearInstanceCache
119 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
120 $mBlockreason, $mBlock, $mEffectiveGroups;
123 * Lightweight constructor for anonymous user
124 * Use the User::newFrom* factory functions for other kinds of users
127 $this->clearInstanceCache( 'defaults' );
131 * Load the user table data for this object from the source given by mFrom
134 if ( $this->mDataLoaded
) {
137 wfProfileIn( __METHOD__
);
139 # Set it now to avoid infinite recursion in accessors
140 $this->mDataLoaded
= true;
142 switch ( $this->mFrom
) {
144 $this->loadDefaults();
147 $this->mId
= self
::idFromName( $this->mName
);
149 # Nonexistent user placeholder object
150 $this->loadDefaults( $this->mName
);
159 $this->loadFromSession();
162 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
164 wfProfileOut( __METHOD__
);
168 * Load user table data given mId
169 * @return false if the ID does not exist, true otherwise
172 function loadFromId() {
174 if ( $this->mId
== 0 ) {
175 $this->loadDefaults();
180 $key = wfMemcKey( 'user', 'id', $this->mId
);
181 $data = $wgMemc->get( $key );
183 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
184 # Object is expired, load from DB
189 wfDebug( "Cache miss for user {$this->mId}\n" );
191 if ( !$this->loadFromDatabase() ) {
192 # Can't load from ID, user is anonymous
198 foreach ( self
::$mCacheVars as $name ) {
199 $data[$name] = $this->$name;
201 $data['mVersion'] = MW_USER_VERSION
;
202 $wgMemc->set( $key, $data );
204 wfDebug( "Got user {$this->mId} from cache\n" );
206 foreach ( self
::$mCacheVars as $name ) {
207 $this->$name = $data[$name];
214 * Static factory method for creation from username.
216 * This is slightly less efficient than newFromId(), so use newFromId() if
217 * you have both an ID and a name handy.
219 * @param string $name Username, validated by Title:newFromText()
220 * @param mixed $validate Validate username. Takes the same parameters as
221 * User::getCanonicalName(), except that true is accepted as an alias
222 * for 'valid', for BC.
224 * @return User object, or null if the username is invalid. If the username
225 * is not present in the database, the result will be a user object with
226 * a name, zero user ID and default settings.
229 static function newFromName( $name, $validate = 'valid' ) {
230 if ( $validate === true ) {
233 $name = self
::getCanonicalName( $name, $validate );
234 if ( $name === false ) {
237 # Create unloaded user object
245 static function newFromId( $id ) {
253 * Factory method to fetch whichever user has a given email confirmation code.
254 * This code is generated when an account is created or its e-mail address
257 * If the code is invalid or has expired, returns NULL.
259 * @param string $code
263 static function newFromConfirmationCode( $code ) {
264 $dbr =& wfGetDB( DB_SLAVE
);
265 $id = $dbr->selectField( 'user', 'user_id', array(
266 'user_email_token' => md5( $code ),
267 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
269 if( $id !== false ) {
270 return User
::newFromId( $id );
277 * Create a new user object using data from session or cookies. If the
278 * login credentials are invalid, the result is an anonymous user.
283 static function newFromSession() {
285 $user->mFrom
= 'session';
290 * Get username given an id.
291 * @param integer $id Database user id
292 * @return string Nickname of a user
295 static function whoIs( $id ) {
296 $dbr =& wfGetDB( DB_SLAVE
);
297 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
301 * Get real username given an id.
302 * @param integer $id Database user id
303 * @return string Realname of a user
306 static function whoIsReal( $id ) {
307 $dbr =& wfGetDB( DB_SLAVE
);
308 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), 'User::whoIsReal' );
312 * Get database id given a user name
313 * @param string $name Nickname of a user
314 * @return integer|null Database user id (null: if non existent
317 static function idFromName( $name ) {
318 $nt = Title
::newFromText( $name );
319 if( is_null( $nt ) ) {
323 $dbr =& wfGetDB( DB_SLAVE
);
324 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
326 if ( $s === false ) {
334 * Does the string match an anonymous IPv4 address?
336 * This function exists for username validation, in order to reject
337 * usernames which are similar in form to IP addresses. Strings such
338 * as 300.300.300.300 will return true because it looks like an IP
339 * address, despite not being strictly valid.
341 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
342 * address because the usemod software would "cloak" anonymous IP
343 * addresses like this, if we allowed accounts like this to be created
344 * new users could get the old edits of these anonymous users.
349 * @param string $name Nickname of a user
352 static function isIP( $name ) {
353 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name);
354 /*return preg_match("/^
355 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
356 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
357 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
358 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
363 * Is the input a valid username?
365 * Checks if the input is a valid username, we don't want an empty string,
366 * an IP address, anything that containins slashes (would mess up subpages),
367 * is longer than the maximum allowed username size or doesn't begin with
370 * @param string $name
374 static function isValidUserName( $name ) {
375 global $wgContLang, $wgMaxNameChars;
378 || User
::isIP( $name )
379 ||
strpos( $name, '/' ) !== false
380 ||
strlen( $name ) > $wgMaxNameChars
381 ||
$name != $wgContLang->ucfirst( $name ) )
384 // Ensure that the name can't be misresolved as a different title,
385 // such as with extra namespace keys at the start.
386 $parsed = Title
::newFromText( $name );
387 if( is_null( $parsed )
388 ||
$parsed->getNamespace()
389 ||
strcmp( $name, $parsed->getPrefixedText() ) )
392 // Check an additional blacklist of troublemaker characters.
393 // Should these be merged into the title char list?
394 $unicodeBlacklist = '/[' .
395 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
396 '\x{00a0}' . # non-breaking space
397 '\x{2000}-\x{200f}' . # various whitespace
398 '\x{2028}-\x{202f}' . # breaks and control chars
399 '\x{3000}' . # ideographic space
400 '\x{e000}-\x{f8ff}' . # private use
402 if( preg_match( $unicodeBlacklist, $name ) ) {
410 * Usernames which fail to pass this function will be blocked
411 * from user login and new account registrations, but may be used
412 * internally by batch processes.
414 * If an account already exists in this form, login will be blocked
415 * by a failure to pass this function.
417 * @param string $name
420 static function isUsableName( $name ) {
421 global $wgReservedUsernames;
423 // Must be a usable username, obviously ;)
424 self
::isValidUserName( $name ) &&
426 // Certain names may be reserved for batch processes.
427 !in_array( $name, $wgReservedUsernames );
431 * Usernames which fail to pass this function will be blocked
432 * from new account registrations, but may be used internally
433 * either by batch processes or by user accounts which have
434 * already been created.
436 * Additional character blacklisting may be added here
437 * rather than in isValidUserName() to avoid disrupting
440 * @param string $name
443 static function isCreatableName( $name ) {
445 self
::isUsableName( $name ) &&
447 // Registration-time character blacklisting...
448 strpos( $name, '@' ) === false;
452 * Is the input a valid password?
454 * @param string $password
458 static function isValidPassword( $password ) {
459 global $wgMinimalPasswordLength;
460 return strlen( $password ) >= $wgMinimalPasswordLength;
464 * Does the string match roughly an email address ?
466 * There used to be a regular expression here, it got removed because it
467 * rejected valid addresses. Actually just check if there is '@' somewhere
468 * in the given address.
470 * @todo Check for RFC 2822 compilance
473 * @param string $addr email address
477 static function isValidEmailAddr ( $addr ) {
478 return ( trim( $addr ) != '' ) &&
479 (false !== strpos( $addr, '@' ) );
483 * Given unvalidated user input, return a canonical username, or false if
484 * the username is invalid.
485 * @param string $name
486 * @param mixed $validate Type of validation to use:
487 * false No validation
488 * 'valid' Valid for batch processes
489 * 'usable' Valid for batch processes and login
490 * 'creatable' Valid for batch processes, login and account creation
492 static function getCanonicalName( $name, $validate = 'valid' ) {
493 # Force usernames to capital
495 $name = $wgContLang->ucfirst( $name );
497 # Clean up name according to title rules
498 $t = Title
::newFromText( $name );
499 if( is_null( $t ) ) {
503 # Reject various classes of invalid names
504 $name = $t->getText();
506 $name = $wgAuth->getCanonicalName( $t->getText() );
508 switch ( $validate ) {
512 if ( !User
::isValidUserName( $name ) ) {
517 if ( !User
::isUsableName( $name ) ) {
522 if ( !User
::isCreatableName( $name ) ) {
527 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
533 * Count the number of edits of a user
535 * @param int $uid The user ID to check
539 static function edits( $uid ) {
540 $dbr =& wfGetDB( DB_SLAVE
);
541 return $dbr->selectField(
542 'revision', 'count(*)',
543 array( 'rev_user' => $uid ),
549 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
550 * @todo: hash random numbers to improve security, like generateToken()
555 static function randomPassword() {
556 global $wgMinimalPasswordLength;
557 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
558 $l = strlen( $pwchars ) - 1;
560 $pwlength = max( 7, $wgMinimalPasswordLength );
561 $digit = mt_rand(0, $pwlength - 1);
563 for ( $i = 0; $i < $pwlength; $i++
) {
564 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
570 * Set cached properties to default. Note: this no longer clears
571 * uncached lazy-initialised properties. The constructor does that instead.
575 function loadDefaults( $name = false ) {
576 wfProfileIn( __METHOD__
);
578 global $wgCookiePrefix;
581 $this->mName
= $name;
582 $this->mRealName
= '';
583 $this->mPassword
= $this->mNewpassword
= '';
584 $this->mNewpassTime
= null;
586 $this->mOptions
= null; # Defer init
588 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
589 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
591 $this->mTouched
= '0'; # Allow any pages to be cached
594 $this->setToken(); # Random
595 $this->mEmailAuthenticated
= null;
596 $this->mEmailToken
= '';
597 $this->mEmailTokenExpires
= null;
598 $this->mRegistration
= wfTimestamp( TS_MW
);
599 $this->mGroups
= array();
601 wfProfileOut( __METHOD__
);
605 * Initialise php session
606 * @deprecated use wfSetupSession()
608 function SetupSession() {
613 * Load user data from the session or login cookie. If there are no valid
614 * credentials, initialises the user as an anon.
615 * @return true if the user is logged in, false otherwise
619 function loadFromSession() {
620 global $wgMemc, $wgCookiePrefix;
622 if ( isset( $_SESSION['wsUserID'] ) ) {
623 if ( 0 != $_SESSION['wsUserID'] ) {
624 $sId = $_SESSION['wsUserID'];
626 $this->loadDefaults();
629 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
630 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
631 $_SESSION['wsUserID'] = $sId;
633 $this->loadDefaults();
636 if ( isset( $_SESSION['wsUserName'] ) ) {
637 $sName = $_SESSION['wsUserName'];
638 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
639 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
640 $_SESSION['wsUserName'] = $sName;
642 $this->loadDefaults();
646 $passwordCorrect = FALSE;
648 if ( !$this->loadFromId() ) {
649 # Not a valid ID, loadFromId has switched the object to anon for us
653 if ( isset( $_SESSION['wsToken'] ) ) {
654 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
656 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
657 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
660 # No session or persistent login cookie
661 $this->loadDefaults();
665 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
666 wfDebug( "Logged in from $from\n" );
669 # Invalid credentials
670 wfDebug( "Can't log in from $from, invalid credentials\n" );
671 $this->loadDefaults();
677 * Load user and user_group data from the database
678 * $this->mId must be set, this is how the user is identified.
680 * @return true if the user exists, false if the user is anonymous
683 function loadFromDatabase() {
685 $this->mId
= intval( $this->mId
);
687 /** Anonymous user */
689 $this->loadDefaults();
693 $dbr =& wfGetDB( DB_SLAVE
);
694 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
696 if ( $s !== false ) {
697 # Initialise user table data
698 $this->mName
= $s->user_name
;
699 $this->mRealName
= $s->user_real_name
;
700 $this->mPassword
= $s->user_password
;
701 $this->mNewpassword
= $s->user_newpassword
;
702 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $s->user_newpass_time
);
703 $this->mEmail
= $s->user_email
;
704 $this->decodeOptions( $s->user_options
);
705 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
706 $this->mToken
= $s->user_token
;
707 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
708 $this->mEmailToken
= $s->user_email_token
;
709 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $s->user_email_token_expires
);
710 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $s->user_registration
);
713 $res = $dbr->select( 'user_groups',
715 array( 'ug_user' => $this->mId
),
717 $this->mGroups
= array();
718 while( $row = $dbr->fetchObject( $res ) ) {
719 $this->mGroups
[] = $row->ug_group
;
725 $this->loadDefaults();
731 * Clear various cached data stored in this object.
732 * @param string $reloadFrom Reload user and user_groups table data from a
733 * given source. May be "name", "id", "defaults", "session" or false for
736 function clearInstanceCache( $reloadFrom = false ) {
737 $this->mNewtalk
= -1;
738 $this->mDatePreference
= null;
739 $this->mBlockedby
= -1; # Unset
740 $this->mHash
= false;
742 $this->mRights
= null;
743 $this->mEffectiveGroups
= null;
746 $this->mDataLoaded
= false;
747 $this->mFrom
= $reloadFrom;
752 * Combine the language default options with any site-specific options
753 * and add the default language variants.
759 function getDefaultOptions() {
760 global $wgNamespacesToBeSearchedDefault;
762 * Site defaults will override the global/language defaults
764 global $wgDefaultUserOptions, $wgContLang;
765 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
768 * default language setting
770 $variant = $wgContLang->getPreferredVariant( false );
771 $defOpt['variant'] = $variant;
772 $defOpt['language'] = $variant;
774 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
775 $defOpt['searchNs'.$nsnum] = $val;
781 * Get a given default option value.
788 function getDefaultOption( $opt ) {
789 $defOpts = User
::getDefaultOptions();
790 if( isset( $defOpts[$opt] ) ) {
791 return $defOpts[$opt];
798 * Get a list of user toggle names
801 static function getToggles() {
803 $extraToggles = array();
804 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
805 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
810 * Get blocking information
812 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
813 * non-critical checks are done against slaves. Check when actually saving should be done against
816 function getBlockedStatus( $bFromSlave = true ) {
817 global $wgEnableSorbs, $wgProxyWhitelist;
819 if ( -1 != $this->mBlockedby
) {
820 wfDebug( "User::getBlockedStatus: already loaded.\n" );
824 wfProfileIn( __METHOD__
);
825 wfDebug( __METHOD__
.": checking...\n" );
827 $this->mBlockedby
= 0;
831 $this->mBlock
= new Block();
832 $this->mBlock
->fromMaster( !$bFromSlave );
833 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
834 wfDebug( __METHOD__
.": Found block.\n" );
835 $this->mBlockedby
= $this->mBlock
->mBy
;
836 $this->mBlockreason
= $this->mBlock
->mReason
;
837 if ( $this->isLoggedIn() ) {
838 $this->spreadBlock();
841 $this->mBlock
= null;
842 wfDebug( __METHOD__
.": No block.\n" );
846 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
849 if ( wfIsLocallyBlockedProxy( $ip ) ) {
850 $this->mBlockedby
= wfMsg( 'proxyblocker' );
851 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
855 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
856 if ( $this->inSorbsBlacklist( $ip ) ) {
857 $this->mBlockedby
= wfMsg( 'sorbs' );
858 $this->mBlockreason
= wfMsg( 'sorbsreason' );
864 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
866 wfProfileOut( __METHOD__
);
869 function inSorbsBlacklist( $ip ) {
870 global $wgEnableSorbs, $wgSorbsUrl;
872 return $wgEnableSorbs &&
873 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
876 function inDnsBlacklist( $ip, $base ) {
877 wfProfileIn( __METHOD__
);
883 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
885 for ( $i=4; $i>=1; $i-- ) {
886 $host .= $m[$i] . '.';
891 $ipList = gethostbynamel( $host );
894 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
897 wfDebug( "Requested $host, not found in $base.\n" );
901 wfProfileOut( __METHOD__
);
906 * Primitive rate limits: enforce maximum actions per time period
907 * to put a brake on flooding.
909 * Note: when using a shared cache like memcached, IP-address
910 * last-hit counters will be shared across wikis.
912 * @return bool true if a rate limiter was tripped
915 function pingLimiter( $action='edit' ) {
916 global $wgRateLimits, $wgRateLimitsExcludedGroups;
917 if( !isset( $wgRateLimits[$action] ) ) {
921 # Some groups shouldn't trigger the ping limiter, ever
922 foreach( $this->getGroups() as $group ) {
923 if( array_search( $group, $wgRateLimitsExcludedGroups ) !== false )
927 global $wgMemc, $wgRateLimitLog;
928 wfProfileIn( __METHOD__
);
930 $limits = $wgRateLimits[$action];
932 $id = $this->getId();
935 if( isset( $limits['anon'] ) && $id == 0 ) {
936 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
939 if( isset( $limits['user'] ) && $id != 0 ) {
940 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
942 if( $this->isNewbie() ) {
943 if( isset( $limits['newbie'] ) && $id != 0 ) {
944 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
946 if( isset( $limits['ip'] ) ) {
947 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
950 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
951 $subnet = $matches[1];
952 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
957 foreach( $keys as $key => $limit ) {
958 list( $max, $period ) = $limit;
959 $summary = "(limit $max in {$period}s)";
960 $count = $wgMemc->get( $key );
962 if( $count > $max ) {
963 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
964 if( $wgRateLimitLog ) {
965 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
969 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
972 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
973 $wgMemc->add( $key, 1, intval( $period ) );
975 $wgMemc->incr( $key );
978 wfProfileOut( __METHOD__
);
983 * Check if user is blocked
984 * @return bool True if blocked, false otherwise
986 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
987 wfDebug( "User::isBlocked: enter\n" );
988 $this->getBlockedStatus( $bFromSlave );
989 return $this->mBlockedby
!== 0;
993 * Check if user is blocked from editing a particular article
995 function isBlockedFrom( $title, $bFromSlave = false ) {
996 global $wgBlockAllowsUTEdit;
997 wfProfileIn( __METHOD__
);
998 wfDebug( __METHOD__
.": enter\n" );
1000 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1001 $title->getNamespace() == NS_USER_TALK
)
1004 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1006 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1007 $blocked = $this->isBlocked( $bFromSlave );
1009 wfProfileOut( __METHOD__
);
1014 * Get name of blocker
1015 * @return string name of blocker
1017 function blockedBy() {
1018 $this->getBlockedStatus();
1019 return $this->mBlockedby
;
1023 * Get blocking reason
1024 * @return string Blocking reason
1026 function blockedFor() {
1027 $this->getBlockedStatus();
1028 return $this->mBlockreason
;
1032 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1040 * Set the user and reload all fields according to that ID
1041 * @deprecated use User::newFromId()
1043 function setID( $v ) {
1045 $this->clearInstanceCache( 'id' );
1049 * Get the user name, or the IP for anons
1051 function getName() {
1052 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1053 # Special case optimisation
1054 return $this->mName
;
1057 if ( $this->mName
=== false ) {
1058 $this->mName
= wfGetIP();
1060 return $this->mName
;
1065 * Set the user name.
1067 * This does not reload fields from the database according to the given
1068 * name. Rather, it is used to create a temporary "nonexistent user" for
1069 * later addition to the database. It can also be used to set the IP
1070 * address for an anonymous user to something other than the current
1073 * User::newFromName() has rougly the same function, when the named user
1076 function setName( $str ) {
1078 $this->mName
= $str;
1082 * Return the title dbkey form of the name, for eg user pages.
1086 function getTitleKey() {
1087 return str_replace( ' ', '_', $this->getName() );
1090 function getNewtalk() {
1093 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1094 if( $this->mNewtalk
=== -1 ) {
1095 $this->mNewtalk
= false; # reset talk page status
1097 # Check memcached separately for anons, who have no
1098 # entire User object stored in there.
1101 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1102 $newtalk = $wgMemc->get( $key );
1103 if( is_integer( $newtalk ) ) {
1104 $this->mNewtalk
= (bool)$newtalk;
1106 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
1107 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
1110 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1114 return (bool)$this->mNewtalk
;
1118 * Return the talk page(s) this user has new messages on.
1120 function getNewMessageLinks() {
1122 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1125 if (!$this->getNewtalk())
1127 $up = $this->getUserPage();
1128 $utp = $up->getTalkPage();
1129 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1134 * Perform a user_newtalk check on current slaves; if the memcached data
1135 * is funky we don't want newtalk state to get stuck on save, as that's
1138 * @param string $field
1143 function checkNewtalk( $field, $id ) {
1144 $dbr =& wfGetDB( DB_SLAVE
);
1145 $ok = $dbr->selectField( 'user_newtalk', $field,
1146 array( $field => $id ), __METHOD__
);
1147 return $ok !== false;
1152 * @param string $field
1156 function updateNewtalk( $field, $id ) {
1157 if( $this->checkNewtalk( $field, $id ) ) {
1158 wfDebug( __METHOD__
." already set ($field, $id), ignoring\n" );
1161 $dbw =& wfGetDB( DB_MASTER
);
1162 $dbw->insert( 'user_newtalk',
1163 array( $field => $id ),
1166 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1171 * Clear the new messages flag for the given user
1172 * @param string $field
1176 function deleteNewtalk( $field, $id ) {
1177 if( !$this->checkNewtalk( $field, $id ) ) {
1178 wfDebug( __METHOD__
.": already gone ($field, $id), ignoring\n" );
1181 $dbw =& wfGetDB( DB_MASTER
);
1182 $dbw->delete( 'user_newtalk',
1183 array( $field => $id ),
1185 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1190 * Update the 'You have new messages!' status.
1193 function setNewtalk( $val ) {
1194 if( wfReadOnly() ) {
1199 $this->mNewtalk
= $val;
1201 if( $this->isAnon() ) {
1203 $id = $this->getName();
1206 $id = $this->getId();
1210 $changed = $this->updateNewtalk( $field, $id );
1212 $changed = $this->deleteNewtalk( $field, $id );
1216 if( $this->isAnon() ) {
1217 // Anons have a separate memcached space, since
1218 // user records aren't kept for them.
1220 $key = wfMemcKey( 'newtalk', 'ip', $val );
1221 $wgMemc->set( $key, $val ?
1 : 0 );
1224 // Make sure the user page is watched, so a notification
1225 // will be sent out if enabled.
1226 $this->addWatch( $this->getTalkPage() );
1229 $this->invalidateCache();
1234 * Generate a current or new-future timestamp to be stored in the
1235 * user_touched field when we update things.
1237 private static function newTouchedTimestamp() {
1238 global $wgClockSkewFudge;
1239 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1243 * Clear user data from memcached.
1244 * Use after applying fun updates to the database; caller's
1245 * responsibility to update user_touched if appropriate.
1247 * Called implicitly from invalidateCache() and saveSettings().
1249 private function clearSharedCache() {
1252 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1257 * Immediately touch the user data cache for this account.
1258 * Updates user_touched field, and removes account data from memcached
1259 * for reload on the next hit.
1261 function invalidateCache() {
1264 $this->mTouched
= self
::newTouchedTimestamp();
1266 $dbw =& wfGetDB( DB_MASTER
);
1267 $dbw->update( 'user',
1268 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1269 array( 'user_id' => $this->mId
),
1272 $this->clearSharedCache();
1276 function validateCache( $timestamp ) {
1278 return ($timestamp >= $this->mTouched
);
1282 * Encrypt a password.
1283 * It can eventuall salt a password @see User::addSalt()
1284 * @param string $p clear Password.
1285 * @return string Encrypted password.
1287 function encryptPassword( $p ) {
1289 return wfEncryptPassword( $this->mId
, $p );
1293 * Set the password and reset the random token
1295 function setPassword( $str ) {
1298 $this->mPassword
= $this->encryptPassword( $str );
1299 $this->mNewpassword
= '';
1300 $this->mNewpassTime
= NULL;
1304 * Set the random token (used for persistent authentication)
1305 * Called from loadDefaults() among other places.
1308 function setToken( $token = false ) {
1309 global $wgSecretKey, $wgProxyKey;
1312 if ( $wgSecretKey ) {
1313 $key = $wgSecretKey;
1314 } elseif ( $wgProxyKey ) {
1319 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1321 $this->mToken
= $token;
1325 function setCookiePassword( $str ) {
1327 $this->mCookiePassword
= md5( $str );
1331 * Set the password for a password reminder or new account email
1332 * Sets the user_newpass_time field if $throttle is true
1334 function setNewpassword( $str, $throttle = true ) {
1336 $this->mNewpassword
= $this->encryptPassword( $str );
1338 $this->mNewpassTime
= wfTimestampNow();
1343 * Returns true if a password reminder email has already been sent within
1344 * the last $wgPasswordReminderResendTime hours
1346 function isPasswordReminderThrottled() {
1347 global $wgPasswordReminderResendTime;
1349 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1352 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1353 return time() < $expiry;
1356 function getEmail() {
1358 return $this->mEmail
;
1361 function getEmailAuthenticationTimestamp() {
1363 return $this->mEmailAuthenticated
;
1366 function setEmail( $str ) {
1368 $this->mEmail
= $str;
1371 function getRealName() {
1373 return $this->mRealName
;
1376 function setRealName( $str ) {
1378 $this->mRealName
= $str;
1382 * @param string $oname The option to check
1385 function getOption( $oname ) {
1387 if ( is_null( $this->mOptions
) ) {
1388 $this->mOptions
= User
::getDefaultOptions();
1390 if ( array_key_exists( $oname, $this->mOptions
) ) {
1391 return trim( $this->mOptions
[$oname] );
1398 * Get the user's date preference, including some important migration for
1401 function getDatePreference() {
1402 if ( is_null( $this->mDatePreference
) ) {
1404 $value = $this->getOption( 'date' );
1405 $map = $wgLang->getDatePreferenceMigrationMap();
1406 if ( isset( $map[$value] ) ) {
1407 $value = $map[$value];
1409 $this->mDatePreference
= $value;
1411 return $this->mDatePreference
;
1415 * @param string $oname The option to check
1416 * @return bool False if the option is not selected, true if it is
1418 function getBoolOption( $oname ) {
1419 return (bool)$this->getOption( $oname );
1423 * Get an option as an integer value from the source string.
1424 * @param string $oname The option to check
1425 * @param int $default Optional value to return if option is unset/blank.
1428 function getIntOption( $oname, $default=0 ) {
1429 $val = $this->getOption( $oname );
1433 return intval( $val );
1436 function setOption( $oname, $val ) {
1438 if ( is_null( $this->mOptions
) ) {
1439 $this->mOptions
= User
::getDefaultOptions();
1441 if ( $oname == 'skin' ) {
1442 # Clear cached skin, so the new one displays immediately in Special:Preferences
1443 unset( $this->mSkin
);
1445 // Filter out any newlines that may have passed through input validation.
1446 // Newlines are used to separate items in the options blob.
1447 $val = str_replace( "\r\n", "\n", $val );
1448 $val = str_replace( "\r", "\n", $val );
1449 $val = str_replace( "\n", " ", $val );
1450 $this->mOptions
[$oname] = $val;
1453 function getRights() {
1454 if ( is_null( $this->mRights
) ) {
1455 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1457 return $this->mRights
;
1461 * Get the list of explicit group memberships this user has.
1462 * The implicit * and user groups are not included.
1463 * @return array of strings
1465 function getGroups() {
1467 return $this->mGroups
;
1471 * Get the list of implicit group memberships this user has.
1472 * This includes all explicit groups, plus 'user' if logged in
1473 * and '*' for all accounts.
1474 * @param boolean $recache Don't use the cache
1475 * @return array of strings
1477 function getEffectiveGroups( $recache = false ) {
1478 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1480 $this->mEffectiveGroups
= $this->mGroups
;
1481 $this->mEffectiveGroups
[] = '*';
1483 $this->mEffectiveGroups
[] = 'user';
1485 global $wgAutoConfirmAge;
1486 $accountAge = time() - wfTimestampOrNull( TS_UNIX
, $this->mRegistration
);
1487 if( $accountAge >= $wgAutoConfirmAge ) {
1488 $this->mEffectiveGroups
[] = 'autoconfirmed';
1491 # Implicit group for users whose email addresses are confirmed
1492 global $wgEmailAuthentication;
1493 if( self
::isValidEmailAddr( $this->mEmail
) ) {
1494 if( $wgEmailAuthentication ) {
1495 if( $this->mEmailAuthenticated
)
1496 $this->mEffectiveGroups
[] = 'emailconfirmed';
1498 $this->mEffectiveGroups
[] = 'emailconfirmed';
1503 return $this->mEffectiveGroups
;
1507 * Add the user to the given group.
1508 * This takes immediate effect.
1511 function addGroup( $group ) {
1513 $dbw =& wfGetDB( DB_MASTER
);
1514 $dbw->insert( 'user_groups',
1516 'ug_user' => $this->getID(),
1517 'ug_group' => $group,
1520 array( 'IGNORE' ) );
1522 $this->mGroups
[] = $group;
1523 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1525 $this->invalidateCache();
1529 * Remove the user from the given group.
1530 * This takes immediate effect.
1533 function removeGroup( $group ) {
1535 $dbw =& wfGetDB( DB_MASTER
);
1536 $dbw->delete( 'user_groups',
1538 'ug_user' => $this->getID(),
1539 'ug_group' => $group,
1541 'User::removeGroup' );
1543 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1544 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1546 $this->invalidateCache();
1551 * A more legible check for non-anonymousness.
1552 * Returns true if the user is not an anonymous visitor.
1556 function isLoggedIn() {
1557 return( $this->getID() != 0 );
1561 * A more legible check for anonymousness.
1562 * Returns true if the user is an anonymous visitor.
1567 return !$this->isLoggedIn();
1571 * Whether the user is a bot
1575 return $this->isAllowed( 'bot' );
1579 * Check if user is allowed to access a feature / make an action
1580 * @param string $action Action to be checked
1581 * @return boolean True: action is allowed, False: action should not be allowed
1583 function isAllowed($action='') {
1584 if ( $action === '' )
1585 // In the spirit of DWIM
1588 return in_array( $action, $this->getRights() );
1592 * Load a skin if it doesn't exist or return it
1593 * @todo FIXME : need to check the old failback system [AV]
1595 function &getSkin() {
1597 if ( ! isset( $this->mSkin
) ) {
1598 wfProfileIn( __METHOD__
);
1601 $userSkin = $this->getOption( 'skin' );
1602 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1604 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1605 wfProfileOut( __METHOD__
);
1607 return $this->mSkin
;
1611 * @param string $title Article title to look at
1615 * Check watched status of an article
1616 * @return bool True if article is watched
1618 function isWatched( $title ) {
1619 $wl = WatchedItem
::fromUserTitle( $this, $title );
1620 return $wl->isWatched();
1626 function addWatch( $title ) {
1627 $wl = WatchedItem
::fromUserTitle( $this, $title );
1629 $this->invalidateCache();
1633 * Stop watching an article
1635 function removeWatch( $title ) {
1636 $wl = WatchedItem
::fromUserTitle( $this, $title );
1638 $this->invalidateCache();
1642 * Clear the user's notification timestamp for the given title.
1643 * If e-notif e-mails are on, they will receive notification mails on
1644 * the next change of the page if it's watched etc.
1646 function clearNotification( &$title ) {
1647 global $wgUser, $wgUseEnotif;
1649 if ($title->getNamespace() == NS_USER_TALK
&&
1650 $title->getText() == $this->getName() ) {
1651 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1653 $this->setNewtalk( false );
1656 if( !$wgUseEnotif ) {
1660 if( $this->isAnon() ) {
1661 // Nothing else to do...
1665 // Only update the timestamp if the page is being watched.
1666 // The query to find out if it is watched is cached both in memcached and per-invocation,
1667 // and when it does have to be executed, it can be on a slave
1668 // If this is the user's newtalk page, we always update the timestamp
1669 if ($title->getNamespace() == NS_USER_TALK
&&
1670 $title->getText() == $wgUser->getName())
1673 } elseif ( $this->getID() == $wgUser->getID() ) {
1674 $watched = $title->userIsWatching();
1679 // If the page is watched by the user (or may be watched), update the timestamp on any
1680 // any matching rows
1682 $dbw =& wfGetDB( DB_MASTER
);
1683 $dbw->update( 'watchlist',
1685 'wl_notificationtimestamp' => NULL
1686 ), array( /* WHERE */
1687 'wl_title' => $title->getDBkey(),
1688 'wl_namespace' => $title->getNamespace(),
1689 'wl_user' => $this->getID()
1690 ), 'User::clearLastVisited'
1698 * Resets all of the given user's page-change notification timestamps.
1699 * If e-notif e-mails are on, they will receive notification mails on
1700 * the next change of any watched page.
1702 * @param int $currentUser user ID number
1705 function clearAllNotifications( $currentUser ) {
1706 global $wgUseEnotif;
1707 if ( !$wgUseEnotif ) {
1708 $this->setNewtalk( false );
1711 if( $currentUser != 0 ) {
1713 $dbw =& wfGetDB( DB_MASTER
);
1714 $dbw->update( 'watchlist',
1716 'wl_notificationtimestamp' => NULL
1717 ), array( /* WHERE */
1718 'wl_user' => $currentUser
1719 ), 'UserMailer::clearAll'
1722 # we also need to clear here the "you have new message" notification for the own user_talk page
1723 # This is cleared one page view later in Article::viewUpdates();
1729 * @return string Encoding options
1731 function encodeOptions() {
1733 if ( is_null( $this->mOptions
) ) {
1734 $this->mOptions
= User
::getDefaultOptions();
1737 foreach ( $this->mOptions
as $oname => $oval ) {
1738 array_push( $a, $oname.'='.$oval );
1740 $s = implode( "\n", $a );
1747 function decodeOptions( $str ) {
1748 $this->mOptions
= array();
1749 $a = explode( "\n", $str );
1750 foreach ( $a as $s ) {
1752 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1753 $this->mOptions
[$m[1]] = $m[2];
1758 function setCookies() {
1759 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1761 if ( 0 == $this->mId
) return;
1762 $exp = time() +
$wgCookieExpiration;
1764 $_SESSION['wsUserID'] = $this->mId
;
1765 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1767 $_SESSION['wsUserName'] = $this->getName();
1768 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1770 $_SESSION['wsToken'] = $this->mToken
;
1771 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1772 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1774 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1780 * Clears the cookies and session, resets the instance cache
1783 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1784 $this->clearInstanceCache( 'defaults' );
1786 $_SESSION['wsUserID'] = 0;
1788 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1789 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1791 # Remember when user logged out, to prevent seeing cached pages
1792 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1796 * Save object settings into database
1797 * @fixme Only rarely do all these fields need to be set!
1799 function saveSettings() {
1801 if ( wfReadOnly() ) { return; }
1802 if ( 0 == $this->mId
) { return; }
1804 $this->mTouched
= self
::newTouchedTimestamp();
1806 $dbw =& wfGetDB( DB_MASTER
);
1807 $dbw->update( 'user',
1809 'user_name' => $this->mName
,
1810 'user_password' => $this->mPassword
,
1811 'user_newpassword' => $this->mNewpassword
,
1812 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
1813 'user_real_name' => $this->mRealName
,
1814 'user_email' => $this->mEmail
,
1815 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1816 'user_options' => $this->encodeOptions(),
1817 'user_touched' => $dbw->timestamp($this->mTouched
),
1818 'user_token' => $this->mToken
1819 ), array( /* WHERE */
1820 'user_id' => $this->mId
1823 $this->clearSharedCache();
1828 * Checks if a user with the given name exists, returns the ID
1830 function idForName() {
1831 $s = trim( $this->getName() );
1832 if ( 0 == strcmp( '', $s ) ) return 0;
1834 $dbr =& wfGetDB( DB_SLAVE
);
1835 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
1836 if ( $id === false ) {
1843 * Add a user to the database, return the user object
1845 * @param string $name The user's name
1846 * @param array $params Associative array of non-default parameters to save to the database:
1847 * password The user's password. Password logins will be disabled if this is omitted.
1848 * newpassword A temporary password mailed to the user
1849 * email The user's email address
1850 * email_authenticated The email authentication timestamp
1851 * real_name The user's real name
1852 * options An associative array of non-default options
1853 * token Random authentication token. Do not set.
1854 * registration Registration timestamp. Do not set.
1856 * @return User object, or null if the username already exists
1858 static function createNew( $name, $params = array() ) {
1861 if ( isset( $params['options'] ) ) {
1862 $user->mOptions
= $params['options'] +
$user->mOptions
;
1863 unset( $params['options'] );
1865 $dbw =& wfGetDB( DB_MASTER
);
1866 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1868 'user_id' => $seqVal,
1869 'user_name' => $name,
1870 'user_password' => $user->mPassword
,
1871 'user_newpassword' => $user->mNewpassword
,
1872 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
1873 'user_email' => $user->mEmail
,
1874 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
1875 'user_real_name' => $user->mRealName
,
1876 'user_options' => $user->encodeOptions(),
1877 'user_token' => $user->mToken
,
1878 'user_registration' => $dbw->timestamp( $user->mRegistration
),
1880 foreach ( $params as $name => $value ) {
1881 $fields["user_$name"] = $value;
1883 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
1884 if ( $dbw->affectedRows() ) {
1885 $newUser = User
::newFromId( $dbw->insertId() );
1893 * Add an existing user object to the database
1895 function addToDatabase() {
1897 $dbw =& wfGetDB( DB_MASTER
);
1898 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1899 $dbw->insert( 'user',
1901 'user_id' => $seqVal,
1902 'user_name' => $this->mName
,
1903 'user_password' => $this->mPassword
,
1904 'user_newpassword' => $this->mNewpassword
,
1905 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
1906 'user_email' => $this->mEmail
,
1907 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1908 'user_real_name' => $this->mRealName
,
1909 'user_options' => $this->encodeOptions(),
1910 'user_token' => $this->mToken
,
1911 'user_registration' => $dbw->timestamp( $this->mRegistration
),
1914 $this->mId
= $dbw->insertId();
1916 # Clear instance cache other than user table data, which is already accurate
1917 $this->clearInstanceCache();
1921 * If the (non-anonymous) user is blocked, this function will block any IP address
1922 * that they successfully log on from.
1924 function spreadBlock() {
1925 wfDebug( __METHOD__
."()\n" );
1927 if ( $this->mId
== 0 ) {
1931 $userblock = Block
::newFromDB( '', $this->mId
);
1932 if ( !$userblock ) {
1936 $userblock->doAutoblock( wfGetIp() );
1941 * Generate a string which will be different for any combination of
1942 * user options which would produce different parser output.
1943 * This will be used as part of the hash key for the parser cache,
1944 * so users will the same options can share the same cached data
1947 * Extensions which require it should install 'PageRenderingHash' hook,
1948 * which will give them a chance to modify this key based on their own
1953 function getPageRenderingHash() {
1954 global $wgContLang, $wgUseDynamicDates;
1956 return $this->mHash
;
1959 // stubthreshold is only included below for completeness,
1960 // it will always be 0 when this function is called by parsercache.
1962 $confstr = $this->getOption( 'math' );
1963 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1964 if ( $wgUseDynamicDates ) {
1965 $confstr .= '!' . $this->getDatePreference();
1967 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
1968 $confstr .= '!' . $this->getOption( 'language' );
1969 $confstr .= '!' . $this->getOption( 'thumbsize' );
1970 // add in language specific options, if any
1971 $extra = $wgContLang->getExtraHashOptions();
1974 // Give a chance for extensions to modify the hash, if they have
1975 // extra options or other effects on the parser cache.
1976 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
1978 $this->mHash
= $confstr;
1982 function isBlockedFromCreateAccount() {
1983 $this->getBlockedStatus();
1984 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
1987 function isAllowedToCreateAccount() {
1988 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
1994 function setLoaded( $loaded ) {}
1997 * Get this user's personal page title.
2002 function getUserPage() {
2003 return Title
::makeTitle( NS_USER
, $this->getName() );
2007 * Get this user's talk page title.
2012 function getTalkPage() {
2013 $title = $this->getUserPage();
2014 return $title->getTalkPage();
2020 function getMaxID() {
2021 static $res; // cache
2023 if ( isset( $res ) )
2026 $dbr =& wfGetDB( DB_SLAVE
);
2027 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2032 * Determine whether the user is a newbie. Newbies are either
2033 * anonymous IPs, or the most recently created accounts.
2034 * @return bool True if it is a newbie.
2036 function isNewbie() {
2037 return !$this->isAllowed( 'autoconfirmed' );
2041 * Check to see if the given clear-text password is one of the accepted passwords
2042 * @param string $password User password.
2043 * @return bool True if the given password is correct otherwise False.
2045 function checkPassword( $password ) {
2046 global $wgAuth, $wgMinimalPasswordLength;
2049 // Even though we stop people from creating passwords that
2050 // are shorter than this, doesn't mean people wont be able
2051 // to. Certain authentication plugins do NOT want to save
2052 // domain passwords in a mysql database, so we should
2053 // check this (incase $wgAuth->strict() is false).
2054 if( strlen( $password ) < $wgMinimalPasswordLength ) {
2058 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2060 } elseif( $wgAuth->strict() ) {
2061 /* Auth plugin doesn't allow local authentication */
2064 $ep = $this->encryptPassword( $password );
2065 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2067 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
2069 } elseif ( function_exists( 'iconv' ) ) {
2070 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2071 # Check for this with iconv
2072 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2073 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2081 * Initialize (if necessary) and return a session token value
2082 * which can be used in edit forms to show that the user's
2083 * login credentials aren't being hijacked with a foreign form
2086 * @param mixed $salt - Optional function-specific data for hash.
2087 * Use a string or an array of strings.
2091 function editToken( $salt = '' ) {
2092 if( !isset( $_SESSION['wsEditToken'] ) ) {
2093 $token = $this->generateToken();
2094 $_SESSION['wsEditToken'] = $token;
2096 $token = $_SESSION['wsEditToken'];
2098 if( is_array( $salt ) ) {
2099 $salt = implode( '|', $salt );
2101 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2105 * Generate a hex-y looking random token for various uses.
2106 * Could be made more cryptographically sure if someone cares.
2109 function generateToken( $salt = '' ) {
2110 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2111 return md5( $token . $salt );
2115 * Check given value against the token value stored in the session.
2116 * A match should confirm that the form was submitted from the
2117 * user's own login session, not a form submission from a third-party
2120 * @param string $val - the input value to compare
2121 * @param string $salt - Optional function-specific data for hash
2125 function matchEditToken( $val, $salt = '' ) {
2127 $sessionToken = $this->editToken( $salt );
2128 if ( $val != $sessionToken ) {
2129 wfDebug( "User::matchEditToken: broken session data\n" );
2131 return $val == $sessionToken;
2135 * Generate a new e-mail confirmation token and send a confirmation
2136 * mail to the user's given address.
2138 * @return mixed True on success, a WikiError object on failure.
2140 function sendConfirmationMail() {
2142 $expiration = null; // gets passed-by-ref and defined in next line.
2143 $url = $this->confirmationTokenUrl( $expiration );
2144 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2145 wfMsg( 'confirmemail_body',
2149 $wgContLang->timeanddate( $expiration, false ) ) );
2153 * Send an e-mail to this user's account. Does not check for
2154 * confirmed status or validity.
2156 * @param string $subject
2157 * @param string $body
2158 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2159 * @return mixed True on success, a WikiError object on failure.
2161 function sendMail( $subject, $body, $from = null ) {
2162 if( is_null( $from ) ) {
2163 global $wgPasswordSender;
2164 $from = $wgPasswordSender;
2167 require_once( 'UserMailer.php' );
2168 $to = new MailAddress( $this );
2169 $sender = new MailAddress( $from );
2170 $error = userMailer( $to, $sender, $subject, $body );
2172 if( $error == '' ) {
2175 return new WikiError( $error );
2180 * Generate, store, and return a new e-mail confirmation code.
2181 * A hash (unsalted since it's used as a key) is stored.
2182 * @param &$expiration mixed output: accepts the expiration time
2186 function confirmationToken( &$expiration ) {
2188 $expires = $now +
7 * 24 * 60 * 60;
2189 $expiration = wfTimestamp( TS_MW
, $expires );
2191 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2192 $hash = md5( $token );
2194 $dbw =& wfGetDB( DB_MASTER
);
2195 $dbw->update( 'user',
2196 array( 'user_email_token' => $hash,
2197 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2198 array( 'user_id' => $this->mId
),
2205 * Generate and store a new e-mail confirmation token, and return
2206 * the URL the user can use to confirm.
2207 * @param &$expiration mixed output: accepts the expiration time
2211 function confirmationTokenUrl( &$expiration ) {
2212 $token = $this->confirmationToken( $expiration );
2213 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2214 return $title->getFullUrl();
2218 * Mark the e-mail address confirmed and save.
2220 function confirmEmail() {
2222 $this->mEmailAuthenticated
= wfTimestampNow();
2223 $this->saveSettings();
2228 * Is this user allowed to send e-mails within limits of current
2229 * site configuration?
2232 function canSendEmail() {
2233 return $this->isEmailConfirmed();
2237 * Is this user allowed to receive e-mails within limits of current
2238 * site configuration?
2241 function canReceiveEmail() {
2242 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2246 * Is this user's e-mail address valid-looking and confirmed within
2247 * limits of the current site configuration?
2249 * If $wgEmailAuthentication is on, this may require the user to have
2250 * confirmed their address by returning a code or using a password
2251 * sent to the address from the wiki.
2255 function isEmailConfirmed() {
2256 global $wgEmailAuthentication;
2259 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2260 if( $this->isAnon() )
2262 if( !self
::isValidEmailAddr( $this->mEmail
) )
2264 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2273 * @param array $groups list of groups
2274 * @return array list of permission key names for given groups combined
2277 static function getGroupPermissions( $groups ) {
2278 global $wgGroupPermissions;
2280 foreach( $groups as $group ) {
2281 if( isset( $wgGroupPermissions[$group] ) ) {
2282 $rights = array_merge( $rights,
2283 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2290 * @param string $group key name
2291 * @return string localized descriptive name for group, if provided
2294 static function getGroupName( $group ) {
2295 $key = "group-$group";
2296 $name = wfMsg( $key );
2297 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2305 * @param string $group key name
2306 * @return string localized descriptive name for member of a group, if provided
2309 static function getGroupMember( $group ) {
2310 $key = "group-$group-member";
2311 $name = wfMsg( $key );
2312 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2320 * Return the set of defined explicit groups.
2321 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2322 * groups are not included, as they are defined
2323 * automatically, not in the database.
2327 static function getAllGroups() {
2328 global $wgGroupPermissions;
2330 array_keys( $wgGroupPermissions ),
2331 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2335 * Get the title of a page describing a particular group
2337 * @param $group Name of the group
2340 static function getGroupPage( $group ) {
2341 $page = wfMsgForContent( 'grouppage-' . $group );
2342 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2343 $title = Title
::newFromText( $page );
2344 if( is_object( $title ) )
2351 * Create a link to the group in HTML, if available
2353 * @param $group Name of the group
2354 * @param $text The text of the link
2357 static function makeGroupLinkHTML( $group, $text = '' ) {
2359 $text = self
::getGroupName( $group );
2361 $title = self
::getGroupPage( $group );
2364 $sk = $wgUser->getSkin();
2365 return $sk->makeLinkObj( $title, $text );
2372 * Create a link to the group in Wikitext, if available
2374 * @param $group Name of the group
2375 * @param $text The text of the link (by default, the name of the group)
2378 static function makeGroupLinkWiki( $group, $text = '' ) {
2380 $text = self
::getGroupName( $group );
2382 $title = self
::getGroupPage( $group );
2384 $page = $title->getPrefixedText();
2385 return "[[$page|$text]]";