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, $wgSorbsUrl;
866 return $wgEnableSorbs &&
867 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
870 function inDnsBlacklist( $ip, $base ) {
871 wfProfileIn( __METHOD__
);
877 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
879 for ( $i=4; $i>=1; $i-- ) {
880 $host .= $m[$i] . '.';
885 $ipList = gethostbynamel( $host );
888 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
891 wfDebug( "Requested $host, not found in $base.\n" );
895 wfProfileOut( __METHOD__
);
900 * Primitive rate limits: enforce maximum actions per time period
901 * to put a brake on flooding.
903 * Note: when using a shared cache like memcached, IP-address
904 * last-hit counters will be shared across wikis.
906 * @return bool true if a rate limiter was tripped
909 function pingLimiter( $action='edit' ) {
910 global $wgRateLimits, $wgRateLimitsExcludedGroups;
911 if( !isset( $wgRateLimits[$action] ) ) {
915 # Some groups shouldn't trigger the ping limiter, ever
916 foreach( $this->getGroups() as $group ) {
917 if( array_search( $group, $wgRateLimitsExcludedGroups ) !== false )
921 global $wgMemc, $wgRateLimitLog;
922 wfProfileIn( __METHOD__
);
924 $limits = $wgRateLimits[$action];
926 $id = $this->getId();
929 if( isset( $limits['anon'] ) && $id == 0 ) {
930 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
933 if( isset( $limits['user'] ) && $id != 0 ) {
934 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
936 if( $this->isNewbie() ) {
937 if( isset( $limits['newbie'] ) && $id != 0 ) {
938 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
940 if( isset( $limits['ip'] ) ) {
941 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
944 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
945 $subnet = $matches[1];
946 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
951 foreach( $keys as $key => $limit ) {
952 list( $max, $period ) = $limit;
953 $summary = "(limit $max in {$period}s)";
954 $count = $wgMemc->get( $key );
956 if( $count > $max ) {
957 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
958 if( $wgRateLimitLog ) {
959 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
963 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
966 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
967 $wgMemc->add( $key, 1, intval( $period ) );
969 $wgMemc->incr( $key );
972 wfProfileOut( __METHOD__
);
977 * Check if user is blocked
978 * @return bool True if blocked, false otherwise
980 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
981 wfDebug( "User::isBlocked: enter\n" );
982 $this->getBlockedStatus( $bFromSlave );
983 return $this->mBlockedby
!== 0;
987 * Check if user is blocked from editing a particular article
989 function isBlockedFrom( $title, $bFromSlave = false ) {
990 global $wgBlockAllowsUTEdit;
991 wfProfileIn( __METHOD__
);
992 wfDebug( __METHOD__
.": enter\n" );
994 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
995 $title->getNamespace() == NS_USER_TALK
)
998 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1000 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1001 $blocked = $this->isBlocked( $bFromSlave );
1003 wfProfileOut( __METHOD__
);
1008 * Get name of blocker
1009 * @return string name of blocker
1011 function blockedBy() {
1012 $this->getBlockedStatus();
1013 return $this->mBlockedby
;
1017 * Get blocking reason
1018 * @return string Blocking reason
1020 function blockedFor() {
1021 $this->getBlockedStatus();
1022 return $this->mBlockreason
;
1026 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1034 * Set the user and reload all fields according to that ID
1035 * @deprecated use User::newFromId()
1037 function setID( $v ) {
1039 $this->clearInstanceCache( 'id' );
1043 * Get the user name, or the IP for anons
1045 function getName() {
1046 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1047 # Special case optimisation
1048 return $this->mName
;
1051 if ( $this->mName
=== false ) {
1052 $this->mName
= wfGetIP();
1054 return $this->mName
;
1059 * Set the user name.
1061 * This does not reload fields from the database according to the given
1062 * name. Rather, it is used to create a temporary "nonexistent user" for
1063 * later addition to the database. It can also be used to set the IP
1064 * address for an anonymous user to something other than the current
1067 * User::newFromName() has rougly the same function, when the named user
1070 function setName( $str ) {
1072 $this->mName
= $str;
1076 * Return the title dbkey form of the name, for eg user pages.
1080 function getTitleKey() {
1081 return str_replace( ' ', '_', $this->getName() );
1084 function getNewtalk() {
1087 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1088 if( $this->mNewtalk
=== -1 ) {
1089 $this->mNewtalk
= false; # reset talk page status
1091 # Check memcached separately for anons, who have no
1092 # entire User object stored in there.
1095 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1096 $newtalk = $wgMemc->get( $key );
1097 if( is_integer( $newtalk ) ) {
1098 $this->mNewtalk
= (bool)$newtalk;
1100 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
1101 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
1104 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1108 return (bool)$this->mNewtalk
;
1112 * Return the talk page(s) this user has new messages on.
1114 function getNewMessageLinks() {
1116 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1119 if (!$this->getNewtalk())
1121 $up = $this->getUserPage();
1122 $utp = $up->getTalkPage();
1123 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1128 * Perform a user_newtalk check on current slaves; if the memcached data
1129 * is funky we don't want newtalk state to get stuck on save, as that's
1132 * @param string $field
1137 function checkNewtalk( $field, $id ) {
1138 $dbr =& wfGetDB( DB_SLAVE
);
1139 $ok = $dbr->selectField( 'user_newtalk', $field,
1140 array( $field => $id ), __METHOD__
);
1141 return $ok !== false;
1146 * @param string $field
1150 function updateNewtalk( $field, $id ) {
1151 if( $this->checkNewtalk( $field, $id ) ) {
1152 wfDebug( __METHOD__
." already set ($field, $id), ignoring\n" );
1155 $dbw =& wfGetDB( DB_MASTER
);
1156 $dbw->insert( 'user_newtalk',
1157 array( $field => $id ),
1160 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1165 * Clear the new messages flag for the given user
1166 * @param string $field
1170 function deleteNewtalk( $field, $id ) {
1171 if( !$this->checkNewtalk( $field, $id ) ) {
1172 wfDebug( __METHOD__
.": already gone ($field, $id), ignoring\n" );
1175 $dbw =& wfGetDB( DB_MASTER
);
1176 $dbw->delete( 'user_newtalk',
1177 array( $field => $id ),
1179 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1184 * Update the 'You have new messages!' status.
1187 function setNewtalk( $val ) {
1188 if( wfReadOnly() ) {
1193 $this->mNewtalk
= $val;
1195 if( $this->isAnon() ) {
1197 $id = $this->getName();
1200 $id = $this->getId();
1204 $changed = $this->updateNewtalk( $field, $id );
1206 $changed = $this->deleteNewtalk( $field, $id );
1210 if( $this->isAnon() ) {
1211 // Anons have a separate memcached space, since
1212 // user records aren't kept for them.
1214 $key = wfMemcKey( 'newtalk', 'ip', $val );
1215 $wgMemc->set( $key, $val ?
1 : 0 );
1218 // Make sure the user page is watched, so a notification
1219 // will be sent out if enabled.
1220 $this->addWatch( $this->getTalkPage() );
1223 $this->invalidateCache();
1228 * Generate a current or new-future timestamp to be stored in the
1229 * user_touched field when we update things.
1231 private static function newTouchedTimestamp() {
1232 global $wgClockSkewFudge;
1233 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1237 * Clear user data from memcached.
1238 * Use after applying fun updates to the database; caller's
1239 * responsibility to update user_touched if appropriate.
1241 * Called implicitly from invalidateCache() and saveSettings().
1243 private function clearSharedCache() {
1246 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1251 * Immediately touch the user data cache for this account.
1252 * Updates user_touched field, and removes account data from memcached
1253 * for reload on the next hit.
1255 function invalidateCache() {
1258 $this->mTouched
= self
::newTouchedTimestamp();
1260 $dbw =& wfGetDB( DB_MASTER
);
1261 $dbw->update( 'user',
1262 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1263 array( 'user_id' => $this->mId
),
1266 $this->clearSharedCache();
1270 function validateCache( $timestamp ) {
1272 return ($timestamp >= $this->mTouched
);
1276 * Encrypt a password.
1277 * It can eventuall salt a password @see User::addSalt()
1278 * @param string $p clear Password.
1279 * @return string Encrypted password.
1281 function encryptPassword( $p ) {
1283 return wfEncryptPassword( $this->mId
, $p );
1287 * Set the password and reset the random token
1289 function setPassword( $str ) {
1292 $this->mPassword
= $this->encryptPassword( $str );
1293 $this->mNewpassword
= '';
1294 $this->mNewpassTime
= NULL;
1298 * Set the random token (used for persistent authentication)
1299 * Called from loadDefaults() among other places.
1302 function setToken( $token = false ) {
1303 global $wgSecretKey, $wgProxyKey;
1306 if ( $wgSecretKey ) {
1307 $key = $wgSecretKey;
1308 } elseif ( $wgProxyKey ) {
1313 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1315 $this->mToken
= $token;
1319 function setCookiePassword( $str ) {
1321 $this->mCookiePassword
= md5( $str );
1325 * Set the password for a password reminder or new account email
1326 * Sets the user_newpass_time field if $throttle is true
1328 function setNewpassword( $str, $throttle = true ) {
1330 $this->mNewpassword
= $this->encryptPassword( $str );
1332 $this->mNewpassTime
= wfTimestampNow();
1337 * Returns true if a password reminder email has already been sent within
1338 * the last $wgPasswordReminderResendTime hours
1340 function isPasswordReminderThrottled() {
1341 global $wgPasswordReminderResendTime;
1343 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1346 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1347 return time() < $expiry;
1350 function getEmail() {
1352 return $this->mEmail
;
1355 function getEmailAuthenticationTimestamp() {
1357 return $this->mEmailAuthenticated
;
1360 function setEmail( $str ) {
1362 $this->mEmail
= $str;
1365 function getRealName() {
1367 return $this->mRealName
;
1370 function setRealName( $str ) {
1372 $this->mRealName
= $str;
1376 * @param string $oname The option to check
1379 function getOption( $oname ) {
1381 if ( is_null( $this->mOptions
) ) {
1382 $this->mOptions
= User
::getDefaultOptions();
1384 if ( array_key_exists( $oname, $this->mOptions
) ) {
1385 return trim( $this->mOptions
[$oname] );
1392 * Get the user's date preference, including some important migration for
1395 function getDatePreference() {
1396 if ( is_null( $this->mDatePreference
) ) {
1398 $value = $this->getOption( 'date' );
1399 $map = $wgLang->getDatePreferenceMigrationMap();
1400 if ( isset( $map[$value] ) ) {
1401 $value = $map[$value];
1403 $this->mDatePreference
= $value;
1405 return $this->mDatePreference
;
1409 * @param string $oname The option to check
1410 * @return bool False if the option is not selected, true if it is
1412 function getBoolOption( $oname ) {
1413 return (bool)$this->getOption( $oname );
1417 * Get an option as an integer value from the source string.
1418 * @param string $oname The option to check
1419 * @param int $default Optional value to return if option is unset/blank.
1422 function getIntOption( $oname, $default=0 ) {
1423 $val = $this->getOption( $oname );
1427 return intval( $val );
1430 function setOption( $oname, $val ) {
1432 if ( is_null( $this->mOptions
) ) {
1433 $this->mOptions
= User
::getDefaultOptions();
1435 if ( $oname == 'skin' ) {
1436 # Clear cached skin, so the new one displays immediately in Special:Preferences
1437 unset( $this->mSkin
);
1439 // Filter out any newlines that may have passed through input validation.
1440 // Newlines are used to separate items in the options blob.
1441 $val = str_replace( "\r\n", "\n", $val );
1442 $val = str_replace( "\r", "\n", $val );
1443 $val = str_replace( "\n", " ", $val );
1444 $this->mOptions
[$oname] = $val;
1447 function getRights() {
1448 if ( is_null( $this->mRights
) ) {
1449 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1451 return $this->mRights
;
1455 * Get the list of explicit group memberships this user has.
1456 * The implicit * and user groups are not included.
1457 * @return array of strings
1459 function getGroups() {
1461 return $this->mGroups
;
1465 * Get the list of implicit group memberships this user has.
1466 * This includes all explicit groups, plus 'user' if logged in
1467 * and '*' for all accounts.
1468 * @param boolean $recache Don't use the cache
1469 * @return array of strings
1471 function getEffectiveGroups( $recache = false ) {
1472 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1474 $this->mEffectiveGroups
= $this->mGroups
;
1475 $this->mEffectiveGroups
[] = '*';
1477 $this->mEffectiveGroups
[] = 'user';
1479 global $wgAutoConfirmAge;
1480 $accountAge = time() - wfTimestampOrNull( TS_UNIX
, $this->mRegistration
);
1481 if( $accountAge >= $wgAutoConfirmAge ) {
1482 $this->mEffectiveGroups
[] = 'autoconfirmed';
1485 # Implicit group for users whose email addresses are confirmed
1486 global $wgEmailAuthentication;
1487 if( self
::isValidEmailAddr( $this->mEmail
) ) {
1488 if( $wgEmailAuthentication ) {
1489 if( $this->mEmailAuthenticated
)
1490 $this->mEffectiveGroups
[] = 'emailconfirmed';
1492 $this->mEffectiveGroups
[] = 'emailconfirmed';
1497 return $this->mEffectiveGroups
;
1501 * Add the user to the given group.
1502 * This takes immediate effect.
1505 function addGroup( $group ) {
1507 $dbw =& wfGetDB( DB_MASTER
);
1508 $dbw->insert( 'user_groups',
1510 'ug_user' => $this->getID(),
1511 'ug_group' => $group,
1514 array( 'IGNORE' ) );
1516 $this->mGroups
[] = $group;
1517 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1519 $this->invalidateCache();
1523 * Remove the user from the given group.
1524 * This takes immediate effect.
1527 function removeGroup( $group ) {
1529 $dbw =& wfGetDB( DB_MASTER
);
1530 $dbw->delete( 'user_groups',
1532 'ug_user' => $this->getID(),
1533 'ug_group' => $group,
1535 'User::removeGroup' );
1537 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1538 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1540 $this->invalidateCache();
1545 * A more legible check for non-anonymousness.
1546 * Returns true if the user is not an anonymous visitor.
1550 function isLoggedIn() {
1551 return( $this->getID() != 0 );
1555 * A more legible check for anonymousness.
1556 * Returns true if the user is an anonymous visitor.
1561 return !$this->isLoggedIn();
1565 * Whether the user is a bot
1569 return $this->isAllowed( 'bot' );
1573 * Check if user is allowed to access a feature / make an action
1574 * @param string $action Action to be checked
1575 * @return boolean True: action is allowed, False: action should not be allowed
1577 function isAllowed($action='') {
1578 if ( $action === '' )
1579 // In the spirit of DWIM
1582 return in_array( $action, $this->getRights() );
1586 * Load a skin if it doesn't exist or return it
1587 * @todo FIXME : need to check the old failback system [AV]
1589 function &getSkin() {
1591 if ( ! isset( $this->mSkin
) ) {
1592 wfProfileIn( __METHOD__
);
1595 $userSkin = $this->getOption( 'skin' );
1596 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1598 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1599 wfProfileOut( __METHOD__
);
1601 return $this->mSkin
;
1605 * @param string $title Article title to look at
1609 * Check watched status of an article
1610 * @return bool True if article is watched
1612 function isWatched( $title ) {
1613 $wl = WatchedItem
::fromUserTitle( $this, $title );
1614 return $wl->isWatched();
1620 function addWatch( $title ) {
1621 $wl = WatchedItem
::fromUserTitle( $this, $title );
1623 $this->invalidateCache();
1627 * Stop watching an article
1629 function removeWatch( $title ) {
1630 $wl = WatchedItem
::fromUserTitle( $this, $title );
1632 $this->invalidateCache();
1636 * Clear the user's notification timestamp for the given title.
1637 * If e-notif e-mails are on, they will receive notification mails on
1638 * the next change of the page if it's watched etc.
1640 function clearNotification( &$title ) {
1641 global $wgUser, $wgUseEnotif;
1643 if ($title->getNamespace() == NS_USER_TALK
&&
1644 $title->getText() == $this->getName() ) {
1645 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1647 $this->setNewtalk( false );
1650 if( !$wgUseEnotif ) {
1654 if( $this->isAnon() ) {
1655 // Nothing else to do...
1659 // Only update the timestamp if the page is being watched.
1660 // The query to find out if it is watched is cached both in memcached and per-invocation,
1661 // and when it does have to be executed, it can be on a slave
1662 // If this is the user's newtalk page, we always update the timestamp
1663 if ($title->getNamespace() == NS_USER_TALK
&&
1664 $title->getText() == $wgUser->getName())
1667 } elseif ( $this->getID() == $wgUser->getID() ) {
1668 $watched = $title->userIsWatching();
1673 // If the page is watched by the user (or may be watched), update the timestamp on any
1674 // any matching rows
1676 $dbw =& wfGetDB( DB_MASTER
);
1677 $dbw->update( 'watchlist',
1679 'wl_notificationtimestamp' => NULL
1680 ), array( /* WHERE */
1681 'wl_title' => $title->getDBkey(),
1682 'wl_namespace' => $title->getNamespace(),
1683 'wl_user' => $this->getID()
1684 ), 'User::clearLastVisited'
1692 * Resets all of the given user's page-change notification timestamps.
1693 * If e-notif e-mails are on, they will receive notification mails on
1694 * the next change of any watched page.
1696 * @param int $currentUser user ID number
1699 function clearAllNotifications( $currentUser ) {
1700 global $wgUseEnotif;
1701 if ( !$wgUseEnotif ) {
1702 $this->setNewtalk( false );
1705 if( $currentUser != 0 ) {
1707 $dbw =& wfGetDB( DB_MASTER
);
1708 $dbw->update( 'watchlist',
1710 'wl_notificationtimestamp' => NULL
1711 ), array( /* WHERE */
1712 'wl_user' => $currentUser
1713 ), 'UserMailer::clearAll'
1716 # we also need to clear here the "you have new message" notification for the own user_talk page
1717 # This is cleared one page view later in Article::viewUpdates();
1723 * @return string Encoding options
1725 function encodeOptions() {
1727 if ( is_null( $this->mOptions
) ) {
1728 $this->mOptions
= User
::getDefaultOptions();
1731 foreach ( $this->mOptions
as $oname => $oval ) {
1732 array_push( $a, $oname.'='.$oval );
1734 $s = implode( "\n", $a );
1741 function decodeOptions( $str ) {
1742 $this->mOptions
= array();
1743 $a = explode( "\n", $str );
1744 foreach ( $a as $s ) {
1746 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1747 $this->mOptions
[$m[1]] = $m[2];
1752 function setCookies() {
1753 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1755 if ( 0 == $this->mId
) return;
1756 $exp = time() +
$wgCookieExpiration;
1758 $_SESSION['wsUserID'] = $this->mId
;
1759 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1761 $_SESSION['wsUserName'] = $this->getName();
1762 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1764 $_SESSION['wsToken'] = $this->mToken
;
1765 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1766 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1768 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1774 * Clears the cookies and session, resets the instance cache
1777 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1778 $this->clearInstanceCache( 'defaults' );
1780 $_SESSION['wsUserID'] = 0;
1782 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1783 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1785 # Remember when user logged out, to prevent seeing cached pages
1786 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1790 * Save object settings into database
1791 * @fixme Only rarely do all these fields need to be set!
1793 function saveSettings() {
1795 if ( wfReadOnly() ) { return; }
1796 if ( 0 == $this->mId
) { return; }
1798 $this->mTouched
= self
::newTouchedTimestamp();
1800 $dbw =& wfGetDB( DB_MASTER
);
1801 $dbw->update( 'user',
1803 'user_name' => $this->mName
,
1804 'user_password' => $this->mPassword
,
1805 'user_newpassword' => $this->mNewpassword
,
1806 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
1807 'user_real_name' => $this->mRealName
,
1808 'user_email' => $this->mEmail
,
1809 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1810 'user_options' => $this->encodeOptions(),
1811 'user_touched' => $dbw->timestamp($this->mTouched
),
1812 'user_token' => $this->mToken
1813 ), array( /* WHERE */
1814 'user_id' => $this->mId
1817 $this->clearSharedCache();
1822 * Checks if a user with the given name exists, returns the ID
1824 function idForName() {
1825 $s = trim( $this->getName() );
1826 if ( 0 == strcmp( '', $s ) ) return 0;
1828 $dbr =& wfGetDB( DB_SLAVE
);
1829 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
1830 if ( $id === false ) {
1837 * Add a user to the database, return the user object
1839 * @param string $name The user's name
1840 * @param array $params Associative array of non-default parameters to save to the database:
1841 * password The user's password. Password logins will be disabled if this is omitted.
1842 * newpassword A temporary password mailed to the user
1843 * email The user's email address
1844 * email_authenticated The email authentication timestamp
1845 * real_name The user's real name
1846 * options An associative array of non-default options
1847 * token Random authentication token. Do not set.
1848 * registration Registration timestamp. Do not set.
1850 * @return User object, or null if the username already exists
1852 static function createNew( $name, $params = array() ) {
1855 if ( isset( $params['options'] ) ) {
1856 $user->mOptions
= $params['options'] +
$user->mOptions
;
1857 unset( $params['options'] );
1859 $dbw =& wfGetDB( DB_MASTER
);
1860 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1862 'user_id' => $seqVal,
1863 'user_name' => $name,
1864 'user_password' => $user->mPassword
,
1865 'user_newpassword' => $user->mNewpassword
,
1866 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
1867 'user_email' => $user->mEmail
,
1868 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
1869 'user_real_name' => $user->mRealName
,
1870 'user_options' => $user->encodeOptions(),
1871 'user_token' => $user->mToken
,
1872 'user_registration' => $dbw->timestamp( $user->mRegistration
),
1874 foreach ( $params as $name => $value ) {
1875 $fields["user_$name"] = $value;
1877 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
1878 if ( $dbw->affectedRows() ) {
1879 $newUser = User
::newFromId( $dbw->insertId() );
1887 * Add an existing user object to the database
1889 function addToDatabase() {
1891 $dbw =& wfGetDB( DB_MASTER
);
1892 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1893 $dbw->insert( 'user',
1895 'user_id' => $seqVal,
1896 'user_name' => $this->mName
,
1897 'user_password' => $this->mPassword
,
1898 'user_newpassword' => $this->mNewpassword
,
1899 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
1900 'user_email' => $this->mEmail
,
1901 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1902 'user_real_name' => $this->mRealName
,
1903 'user_options' => $this->encodeOptions(),
1904 'user_token' => $this->mToken
,
1905 'user_registration' => $dbw->timestamp( $this->mRegistration
),
1908 $this->mId
= $dbw->insertId();
1910 # Clear instance cache other than user table data, which is already accurate
1911 $this->clearInstanceCache();
1915 * If the (non-anonymous) user is blocked, this function will block any IP address
1916 * that they successfully log on from.
1918 function spreadBlock() {
1919 wfDebug( __METHOD__
."()\n" );
1921 if ( $this->mId
== 0 ) {
1925 $userblock = Block
::newFromDB( '', $this->mId
);
1926 if ( !$userblock ) {
1930 $userblock->doAutoblock( wfGetIp() );
1935 * Generate a string which will be different for any combination of
1936 * user options which would produce different parser output.
1937 * This will be used as part of the hash key for the parser cache,
1938 * so users will the same options can share the same cached data
1941 * Extensions which require it should install 'PageRenderingHash' hook,
1942 * which will give them a chance to modify this key based on their own
1947 function getPageRenderingHash() {
1948 global $wgContLang, $wgUseDynamicDates;
1950 return $this->mHash
;
1953 // stubthreshold is only included below for completeness,
1954 // it will always be 0 when this function is called by parsercache.
1956 $confstr = $this->getOption( 'math' );
1957 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1958 if ( $wgUseDynamicDates ) {
1959 $confstr .= '!' . $this->getDatePreference();
1961 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
1962 $confstr .= '!' . $this->getOption( 'language' );
1963 $confstr .= '!' . $this->getOption( 'thumbsize' );
1964 // add in language specific options, if any
1965 $extra = $wgContLang->getExtraHashOptions();
1968 // Give a chance for extensions to modify the hash, if they have
1969 // extra options or other effects on the parser cache.
1970 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
1972 $this->mHash
= $confstr;
1976 function isBlockedFromCreateAccount() {
1977 $this->getBlockedStatus();
1978 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
1981 function isAllowedToCreateAccount() {
1982 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
1988 function setLoaded( $loaded ) {}
1991 * Get this user's personal page title.
1996 function getUserPage() {
1997 return Title
::makeTitle( NS_USER
, $this->getName() );
2001 * Get this user's talk page title.
2006 function getTalkPage() {
2007 $title = $this->getUserPage();
2008 return $title->getTalkPage();
2014 function getMaxID() {
2015 static $res; // cache
2017 if ( isset( $res ) )
2020 $dbr =& wfGetDB( DB_SLAVE
);
2021 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2026 * Determine whether the user is a newbie. Newbies are either
2027 * anonymous IPs, or the most recently created accounts.
2028 * @return bool True if it is a newbie.
2030 function isNewbie() {
2031 return !$this->isAllowed( 'autoconfirmed' );
2035 * Check to see if the given clear-text password is one of the accepted passwords
2036 * @param string $password User password.
2037 * @return bool True if the given password is correct otherwise False.
2039 function checkPassword( $password ) {
2040 global $wgAuth, $wgMinimalPasswordLength;
2043 // Even though we stop people from creating passwords that
2044 // are shorter than this, doesn't mean people wont be able
2045 // to. Certain authentication plugins do NOT want to save
2046 // domain passwords in a mysql database, so we should
2047 // check this (incase $wgAuth->strict() is false).
2048 if( strlen( $password ) < $wgMinimalPasswordLength ) {
2052 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2054 } elseif( $wgAuth->strict() ) {
2055 /* Auth plugin doesn't allow local authentication */
2058 $ep = $this->encryptPassword( $password );
2059 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2061 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
2063 } elseif ( function_exists( 'iconv' ) ) {
2064 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2065 # Check for this with iconv
2066 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2067 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2075 * Initialize (if necessary) and return a session token value
2076 * which can be used in edit forms to show that the user's
2077 * login credentials aren't being hijacked with a foreign form
2080 * @param mixed $salt - Optional function-specific data for hash.
2081 * Use a string or an array of strings.
2085 function editToken( $salt = '' ) {
2086 if( !isset( $_SESSION['wsEditToken'] ) ) {
2087 $token = $this->generateToken();
2088 $_SESSION['wsEditToken'] = $token;
2090 $token = $_SESSION['wsEditToken'];
2092 if( is_array( $salt ) ) {
2093 $salt = implode( '|', $salt );
2095 return md5( $token . $salt );
2099 * Generate a hex-y looking random token for various uses.
2100 * Could be made more cryptographically sure if someone cares.
2103 function generateToken( $salt = '' ) {
2104 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2105 return md5( $token . $salt );
2109 * Check given value against the token value stored in the session.
2110 * A match should confirm that the form was submitted from the
2111 * user's own login session, not a form submission from a third-party
2114 * @param string $val - the input value to compare
2115 * @param string $salt - Optional function-specific data for hash
2119 function matchEditToken( $val, $salt = '' ) {
2121 $sessionToken = $this->editToken( $salt );
2122 if ( $val != $sessionToken ) {
2123 wfDebug( "User::matchEditToken: broken session data\n" );
2125 return $val == $sessionToken;
2129 * Generate a new e-mail confirmation token and send a confirmation
2130 * mail to the user's given address.
2132 * @return mixed True on success, a WikiError object on failure.
2134 function sendConfirmationMail() {
2136 $url = $this->confirmationTokenUrl( $expiration );
2137 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2138 wfMsg( 'confirmemail_body',
2142 $wgContLang->timeanddate( $expiration, false ) ) );
2146 * Send an e-mail to this user's account. Does not check for
2147 * confirmed status or validity.
2149 * @param string $subject
2150 * @param string $body
2151 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2152 * @return mixed True on success, a WikiError object on failure.
2154 function sendMail( $subject, $body, $from = null ) {
2155 if( is_null( $from ) ) {
2156 global $wgPasswordSender;
2157 $from = $wgPasswordSender;
2160 require_once( 'UserMailer.php' );
2161 $to = new MailAddress( $this );
2162 $sender = new MailAddress( $from );
2163 $error = userMailer( $to, $sender, $subject, $body );
2165 if( $error == '' ) {
2168 return new WikiError( $error );
2173 * Generate, store, and return a new e-mail confirmation code.
2174 * A hash (unsalted since it's used as a key) is stored.
2175 * @param &$expiration mixed output: accepts the expiration time
2179 function confirmationToken( &$expiration ) {
2181 $expires = $now +
7 * 24 * 60 * 60;
2182 $expiration = wfTimestamp( TS_MW
, $expires );
2184 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2185 $hash = md5( $token );
2187 $dbw =& wfGetDB( DB_MASTER
);
2188 $dbw->update( 'user',
2189 array( 'user_email_token' => $hash,
2190 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2191 array( 'user_id' => $this->mId
),
2198 * Generate and store a new e-mail confirmation token, and return
2199 * the URL the user can use to confirm.
2200 * @param &$expiration mixed output: accepts the expiration time
2204 function confirmationTokenUrl( &$expiration ) {
2205 $token = $this->confirmationToken( $expiration );
2206 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2207 return $title->getFullUrl();
2211 * Mark the e-mail address confirmed and save.
2213 function confirmEmail() {
2215 $this->mEmailAuthenticated
= wfTimestampNow();
2216 $this->saveSettings();
2221 * Is this user allowed to send e-mails within limits of current
2222 * site configuration?
2225 function canSendEmail() {
2226 return $this->isEmailConfirmed();
2230 * Is this user allowed to receive e-mails within limits of current
2231 * site configuration?
2234 function canReceiveEmail() {
2235 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2239 * Is this user's e-mail address valid-looking and confirmed within
2240 * limits of the current site configuration?
2242 * If $wgEmailAuthentication is on, this may require the user to have
2243 * confirmed their address by returning a code or using a password
2244 * sent to the address from the wiki.
2248 function isEmailConfirmed() {
2249 global $wgEmailAuthentication;
2252 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2253 if( $this->isAnon() )
2255 if( !self
::isValidEmailAddr( $this->mEmail
) )
2257 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2266 * @param array $groups list of groups
2267 * @return array list of permission key names for given groups combined
2270 static function getGroupPermissions( $groups ) {
2271 global $wgGroupPermissions;
2273 foreach( $groups as $group ) {
2274 if( isset( $wgGroupPermissions[$group] ) ) {
2275 $rights = array_merge( $rights,
2276 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2283 * @param string $group key name
2284 * @return string localized descriptive name for group, if provided
2287 static function getGroupName( $group ) {
2288 $key = "group-$group";
2289 $name = wfMsg( $key );
2290 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2298 * @param string $group key name
2299 * @return string localized descriptive name for member of a group, if provided
2302 static function getGroupMember( $group ) {
2303 $key = "group-$group-member";
2304 $name = wfMsg( $key );
2305 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2313 * Return the set of defined explicit groups.
2314 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2315 * groups are not included, as they are defined
2316 * automatically, not in the database.
2320 static function getAllGroups() {
2321 global $wgGroupPermissions;
2323 array_keys( $wgGroupPermissions ),
2324 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2328 * Get the title of a page describing a particular group
2330 * @param $group Name of the group
2333 static function getGroupPage( $group ) {
2334 $page = wfMsgForContent( 'grouppage-' . $group );
2335 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2336 $title = Title
::newFromText( $page );
2337 if( is_object( $title ) )
2344 * Create a link to the group in HTML, if available
2346 * @param $group Name of the group
2347 * @param $text The text of the link
2350 static function makeGroupLinkHTML( $group, $text = '' ) {
2352 $text = self
::getGroupName( $group );
2354 $title = self
::getGroupPage( $group );
2357 $sk = $wgUser->getSkin();
2358 return $sk->makeLinkObj( $title, $text );
2365 * Create a link to the group in Wikitext, if available
2367 * @param $group Name of the group
2368 * @param $text The text of the link (by default, the name of the group)
2371 static function makeGroupLinkWiki( $group, $text = '' ) {
2373 $text = self
::getGroupName( $group );
2375 $title = self
::getGroupPage( $group );
2377 $page = $title->getPrefixedText();
2378 return "[[$page|$text]]";