7 # Number of characters in user_token field
8 define( 'USER_TOKEN_LENGTH', 32 );
10 # Serialized record version
11 define( 'MW_USER_VERSION', 5 );
13 # Some punctuation to prevent editing from broken text-mangling proxies.
14 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
17 * Thrown by User::setPassword() on error
18 * @addtogroup Exception
20 class PasswordError
extends MWException
{
25 * The User object encapsulates all of the user-specific settings (user_id,
26 * name, rights, password, email address, options, last login time). Client
27 * classes use the getXXX() functions to access these fields. These functions
28 * do all the work of determining whether the user is logged in,
29 * whether the requested option can be satisfied from cookies or
30 * whether a database query is needed. Most of the settings needed
31 * for rendering normal pages are set in the cookie to minimize use
37 * A list of default user toggles, i.e. boolean user preferences that are
38 * displayed by Special:Preferences as checkboxes. This list can be
39 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
41 static public $mToggles = array(
51 'editsectiononrightclick',
63 'enotifwatchlistpages',
64 'enotifusertalkpages',
67 'shownumberswatching',
82 * List of member variables which are saved to the shared cache (memcached).
83 * Any operation which changes the corresponding database fields must
84 * call a cache-clearing function.
86 static $mCacheVars = array(
98 'mEmailAuthenticated',
100 'mEmailTokenExpires',
108 * The cache variable declarations
110 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
111 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
112 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
115 * Whether the cache variables have been loaded
120 * Initialisation data source if mDataLoaded==false. May be one of:
121 * defaults anonymous user initialised from class defaults
122 * name initialise from mName
123 * id initialise from mId
124 * session log in from cookies or session if possible
126 * Use the User::newFrom*() family of functions to set this.
131 * Lazy-initialised variables, invalidated with clearInstanceCache
133 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
134 $mBlockreason, $mBlock, $mEffectiveGroups;
137 * Lightweight constructor for anonymous user
138 * Use the User::newFrom* factory functions for other kinds of users
141 $this->clearInstanceCache( 'defaults' );
145 * Load the user table data for this object from the source given by mFrom
148 if ( $this->mDataLoaded
) {
151 wfProfileIn( __METHOD__
);
153 # Set it now to avoid infinite recursion in accessors
154 $this->mDataLoaded
= true;
156 switch ( $this->mFrom
) {
158 $this->loadDefaults();
161 $this->mId
= self
::idFromName( $this->mName
);
163 # Nonexistent user placeholder object
164 $this->loadDefaults( $this->mName
);
173 $this->loadFromSession();
176 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
178 wfProfileOut( __METHOD__
);
182 * Load user table data given mId
183 * @return false if the ID does not exist, true otherwise
186 function loadFromId() {
188 if ( $this->mId
== 0 ) {
189 $this->loadDefaults();
194 $key = wfMemcKey( 'user', 'id', $this->mId
);
195 $data = $wgMemc->get( $key );
196 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
197 # Object is expired, load from DB
202 wfDebug( "Cache miss for user {$this->mId}\n" );
204 if ( !$this->loadFromDatabase() ) {
205 # Can't load from ID, user is anonymous
209 $this->saveToCache();
211 wfDebug( "Got user {$this->mId} from cache\n" );
213 foreach ( self
::$mCacheVars as $name ) {
214 $this->$name = $data[$name];
221 * Save user data to the shared cache
223 function saveToCache() {
225 if ( $this->isAnon() ) {
226 // Anonymous users are uncached
230 foreach ( self
::$mCacheVars as $name ) {
231 $data[$name] = $this->$name;
233 $data['mVersion'] = MW_USER_VERSION
;
234 $key = wfMemcKey( 'user', 'id', $this->mId
);
236 $wgMemc->set( $key, $data );
240 * Static factory method for creation from username.
242 * This is slightly less efficient than newFromId(), so use newFromId() if
243 * you have both an ID and a name handy.
245 * @param string $name Username, validated by Title:newFromText()
246 * @param mixed $validate Validate username. Takes the same parameters as
247 * User::getCanonicalName(), except that true is accepted as an alias
248 * for 'valid', for BC.
250 * @return User object, or null if the username is invalid. If the username
251 * is not present in the database, the result will be a user object with
252 * a name, zero user ID and default settings.
255 static function newFromName( $name, $validate = 'valid' ) {
256 if ( $validate === true ) {
259 $name = self
::getCanonicalName( $name, $validate );
260 if ( $name === false ) {
263 # Create unloaded user object
271 static function newFromId( $id ) {
279 * Factory method to fetch whichever user has a given email confirmation code.
280 * This code is generated when an account is created or its e-mail address
283 * If the code is invalid or has expired, returns NULL.
285 * @param string $code
289 static function newFromConfirmationCode( $code ) {
290 $dbr = wfGetDB( DB_SLAVE
);
291 $id = $dbr->selectField( 'user', 'user_id', array(
292 'user_email_token' => md5( $code ),
293 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
295 if( $id !== false ) {
296 return User
::newFromId( $id );
303 * Create a new user object using data from session or cookies. If the
304 * login credentials are invalid, the result is an anonymous user.
309 static function newFromSession() {
311 $user->mFrom
= 'session';
316 * Get username given an id.
317 * @param integer $id Database user id
318 * @return string Nickname of a user
321 static function whoIs( $id ) {
322 $dbr = wfGetDB( DB_SLAVE
);
323 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
327 * Get the real name of a user given their identifier
329 * @param int $id Database user id
330 * @return string Real name of a user
332 static function whoIsReal( $id ) {
333 $dbr = wfGetDB( DB_SLAVE
);
334 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
338 * Get database id given a user name
339 * @param string $name Nickname of a user
340 * @return integer|null Database user id (null: if non existent
343 static function idFromName( $name ) {
344 $nt = Title
::newFromText( $name );
345 if( is_null( $nt ) ) {
349 $dbr = wfGetDB( DB_SLAVE
);
350 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
352 if ( $s === false ) {
360 * Does the string match an anonymous IPv4 address?
362 * This function exists for username validation, in order to reject
363 * usernames which are similar in form to IP addresses. Strings such
364 * as 300.300.300.300 will return true because it looks like an IP
365 * address, despite not being strictly valid.
367 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
368 * address because the usemod software would "cloak" anonymous IP
369 * addresses like this, if we allowed accounts like this to be created
370 * new users could get the old edits of these anonymous users.
373 * @param string $name Nickname of a user
376 static function isIP( $name ) {
377 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User
::isIPv6($name);
378 /*return preg_match("/^
379 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
380 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
381 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
382 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
387 * Check if $name is an IPv6 IP.
389 static function isIPv6($name) {
391 * if it has any non-valid characters, it can't be a valid IPv6
394 if (preg_match("/[^:a-fA-F0-9]/", $name))
397 $parts = explode(":", $name);
398 if (count($parts) < 3)
400 foreach ($parts as $part) {
401 if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part))
408 * Is the input a valid username?
410 * Checks if the input is a valid username, we don't want an empty string,
411 * an IP address, anything that containins slashes (would mess up subpages),
412 * is longer than the maximum allowed username size or doesn't begin with
415 * @param string $name
419 static function isValidUserName( $name ) {
420 global $wgContLang, $wgMaxNameChars;
423 || User
::isIP( $name )
424 ||
strpos( $name, '/' ) !== false
425 ||
strlen( $name ) > $wgMaxNameChars
426 ||
$name != $wgContLang->ucfirst( $name ) )
429 // Ensure that the name can't be misresolved as a different title,
430 // such as with extra namespace keys at the start.
431 $parsed = Title
::newFromText( $name );
432 if( is_null( $parsed )
433 ||
$parsed->getNamespace()
434 ||
strcmp( $name, $parsed->getPrefixedText() ) )
437 // Check an additional blacklist of troublemaker characters.
438 // Should these be merged into the title char list?
439 $unicodeBlacklist = '/[' .
440 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
441 '\x{00a0}' . # non-breaking space
442 '\x{2000}-\x{200f}' . # various whitespace
443 '\x{2028}-\x{202f}' . # breaks and control chars
444 '\x{3000}' . # ideographic space
445 '\x{e000}-\x{f8ff}' . # private use
447 if( preg_match( $unicodeBlacklist, $name ) ) {
455 * Usernames which fail to pass this function will be blocked
456 * from user login and new account registrations, but may be used
457 * internally by batch processes.
459 * If an account already exists in this form, login will be blocked
460 * by a failure to pass this function.
462 * @param string $name
465 static function isUsableName( $name ) {
466 global $wgReservedUsernames;
468 // Must be a valid username, obviously ;)
469 self
::isValidUserName( $name ) &&
471 // Certain names may be reserved for batch processes.
472 !in_array( $name, $wgReservedUsernames );
476 * Usernames which fail to pass this function will be blocked
477 * from new account registrations, but may be used internally
478 * either by batch processes or by user accounts which have
479 * already been created.
481 * Additional character blacklisting may be added here
482 * rather than in isValidUserName() to avoid disrupting
485 * @param string $name
488 static function isCreatableName( $name ) {
490 self
::isUsableName( $name ) &&
492 // Registration-time character blacklisting...
493 strpos( $name, '@' ) === false;
497 * Is the input a valid password for this user?
499 * @param string $password Desired password
502 function isValidPassword( $password ) {
503 global $wgMinimalPasswordLength, $wgContLang;
506 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
508 if( $result === false )
511 // Password needs to be long enough, and can't be the same as the username
512 return strlen( $password ) >= $wgMinimalPasswordLength
513 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
517 * Does a string look like an email address?
519 * There used to be a regular expression here, it got removed because it
520 * rejected valid addresses. Actually just check if there is '@' somewhere
521 * in the given address.
523 * @todo Check for RFC 2822 compilance (bug 959)
525 * @param string $addr email address
528 public static function isValidEmailAddr( $addr ) {
530 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
534 return strpos( $addr, '@' ) !== false;
538 * Given unvalidated user input, return a canonical username, or false if
539 * the username is invalid.
540 * @param string $name
541 * @param mixed $validate Type of validation to use:
542 * false No validation
543 * 'valid' Valid for batch processes
544 * 'usable' Valid for batch processes and login
545 * 'creatable' Valid for batch processes, login and account creation
547 static function getCanonicalName( $name, $validate = 'valid' ) {
548 # Force usernames to capital
550 $name = $wgContLang->ucfirst( $name );
552 # Reject names containing '#'; these will be cleaned up
553 # with title normalisation, but then it's too late to
555 if( strpos( $name, '#' ) !== false )
558 # Clean up name according to title rules
559 $t = Title
::newFromText( $name );
560 if( is_null( $t ) ) {
564 # Reject various classes of invalid names
565 $name = $t->getText();
567 $name = $wgAuth->getCanonicalName( $t->getText() );
569 switch ( $validate ) {
573 if ( !User
::isValidUserName( $name ) ) {
578 if ( !User
::isUsableName( $name ) ) {
583 if ( !User
::isCreatableName( $name ) ) {
588 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
594 * Count the number of edits of a user
596 * It should not be static and some day should be merged as proper member function / deprecated -- domas
598 * @param int $uid The user ID to check
602 static function edits( $uid ) {
603 wfProfileIn( __METHOD__
);
604 $dbr = wfGetDB( DB_SLAVE
);
605 // check if the user_editcount field has been initialized
606 $field = $dbr->selectField(
607 'user', 'user_editcount',
608 array( 'user_id' => $uid ),
612 if( $field === null ) { // it has not been initialized. do so.
613 $dbw = wfGetDB( DB_MASTER
);
614 $count = $dbr->selectField(
615 'revision', 'count(*)',
616 array( 'rev_user' => $uid ),
621 array( 'user_editcount' => $count ),
622 array( 'user_id' => $uid ),
628 wfProfileOut( __METHOD__
);
633 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
634 * @todo hash random numbers to improve security, like generateToken()
639 static function randomPassword() {
640 global $wgMinimalPasswordLength;
641 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
642 $l = strlen( $pwchars ) - 1;
644 $pwlength = max( 7, $wgMinimalPasswordLength );
645 $digit = mt_rand(0, $pwlength - 1);
647 for ( $i = 0; $i < $pwlength; $i++
) {
648 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
654 * Set cached properties to default. Note: this no longer clears
655 * uncached lazy-initialised properties. The constructor does that instead.
659 function loadDefaults( $name = false ) {
660 wfProfileIn( __METHOD__
);
662 global $wgCookiePrefix;
665 $this->mName
= $name;
666 $this->mRealName
= '';
667 $this->mPassword
= $this->mNewpassword
= '';
668 $this->mNewpassTime
= null;
670 $this->mOptions
= null; # Defer init
672 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
673 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
675 $this->mTouched
= '0'; # Allow any pages to be cached
678 $this->setToken(); # Random
679 $this->mEmailAuthenticated
= null;
680 $this->mEmailToken
= '';
681 $this->mEmailTokenExpires
= null;
682 $this->mRegistration
= wfTimestamp( TS_MW
);
683 $this->mGroups
= array();
685 wfProfileOut( __METHOD__
);
689 * Initialise php session
690 * @deprecated use wfSetupSession()
692 function SetupSession() {
697 * Load user data from the session or login cookie. If there are no valid
698 * credentials, initialises the user as an anon.
699 * @return true if the user is logged in, false otherwise
701 private function loadFromSession() {
702 global $wgMemc, $wgCookiePrefix;
704 if ( isset( $_SESSION['wsUserID'] ) ) {
705 if ( 0 != $_SESSION['wsUserID'] ) {
706 $sId = $_SESSION['wsUserID'];
708 $this->loadDefaults();
711 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
712 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
713 $_SESSION['wsUserID'] = $sId;
715 $this->loadDefaults();
718 if ( isset( $_SESSION['wsUserName'] ) ) {
719 $sName = $_SESSION['wsUserName'];
720 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
721 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
722 $_SESSION['wsUserName'] = $sName;
724 $this->loadDefaults();
728 $passwordCorrect = FALSE;
730 if ( !$this->loadFromId() ) {
731 # Not a valid ID, loadFromId has switched the object to anon for us
735 if ( isset( $_SESSION['wsToken'] ) ) {
736 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
738 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
739 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
742 # No session or persistent login cookie
743 $this->loadDefaults();
747 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
748 $_SESSION['wsToken'] = $this->mToken
;
749 wfDebug( "Logged in from $from\n" );
752 # Invalid credentials
753 wfDebug( "Can't log in from $from, invalid credentials\n" );
754 $this->loadDefaults();
760 * Load user and user_group data from the database
761 * $this->mId must be set, this is how the user is identified.
763 * @return true if the user exists, false if the user is anonymous
766 function loadFromDatabase() {
768 $this->mId
= intval( $this->mId
);
770 /** Anonymous user */
772 $this->loadDefaults();
776 $dbr = wfGetDB( DB_MASTER
);
777 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
779 if ( $s !== false ) {
780 # Initialise user table data
781 $this->mName
= $s->user_name
;
782 $this->mRealName
= $s->user_real_name
;
783 $this->mPassword
= $s->user_password
;
784 $this->mNewpassword
= $s->user_newpassword
;
785 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $s->user_newpass_time
);
786 $this->mEmail
= $s->user_email
;
787 $this->decodeOptions( $s->user_options
);
788 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
789 $this->mToken
= $s->user_token
;
790 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
791 $this->mEmailToken
= $s->user_email_token
;
792 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $s->user_email_token_expires
);
793 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $s->user_registration
);
794 $this->mEditCount
= $s->user_editcount
;
795 $this->getEditCount(); // revalidation for nulls
798 $res = $dbr->select( 'user_groups',
800 array( 'ug_user' => $this->mId
),
802 $this->mGroups
= array();
803 while( $row = $dbr->fetchObject( $res ) ) {
804 $this->mGroups
[] = $row->ug_group
;
810 $this->loadDefaults();
816 * Clear various cached data stored in this object.
817 * @param string $reloadFrom Reload user and user_groups table data from a
818 * given source. May be "name", "id", "defaults", "session" or false for
821 function clearInstanceCache( $reloadFrom = false ) {
822 $this->mNewtalk
= -1;
823 $this->mDatePreference
= null;
824 $this->mBlockedby
= -1; # Unset
825 $this->mHash
= false;
827 $this->mRights
= null;
828 $this->mEffectiveGroups
= null;
831 $this->mDataLoaded
= false;
832 $this->mFrom
= $reloadFrom;
837 * Combine the language default options with any site-specific options
838 * and add the default language variants.
839 * Not really private cause it's called by Language class
844 static function getDefaultOptions() {
845 global $wgNamespacesToBeSearchedDefault;
847 * Site defaults will override the global/language defaults
849 global $wgDefaultUserOptions, $wgContLang;
850 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
853 * default language setting
855 $variant = $wgContLang->getPreferredVariant( false );
856 $defOpt['variant'] = $variant;
857 $defOpt['language'] = $variant;
859 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
860 $defOpt['searchNs'.$nsnum] = $val;
866 * Get a given default option value.
873 function getDefaultOption( $opt ) {
874 $defOpts = User
::getDefaultOptions();
875 if( isset( $defOpts[$opt] ) ) {
876 return $defOpts[$opt];
883 * Get a list of user toggle names
886 static function getToggles() {
888 $extraToggles = array();
889 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
890 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
895 * Get blocking information
897 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
898 * non-critical checks are done against slaves. Check when actually saving should be done against
901 function getBlockedStatus( $bFromSlave = true ) {
902 global $wgEnableSorbs, $wgProxyWhitelist;
904 if ( -1 != $this->mBlockedby
) {
905 wfDebug( "User::getBlockedStatus: already loaded.\n" );
909 wfProfileIn( __METHOD__
);
910 wfDebug( __METHOD__
.": checking...\n" );
912 $this->mBlockedby
= 0;
913 $this->mHideName
= 0;
916 if ($this->isAllowed( 'ipblock-exempt' ) ) {
917 # Exempt from all types of IP-block
922 $this->mBlock
= new Block();
923 $this->mBlock
->fromMaster( !$bFromSlave );
924 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
925 wfDebug( __METHOD__
.": Found block.\n" );
926 $this->mBlockedby
= $this->mBlock
->mBy
;
927 $this->mBlockreason
= $this->mBlock
->mReason
;
928 $this->mHideName
= $this->mBlock
->mHideName
;
929 if ( $this->isLoggedIn() ) {
930 $this->spreadBlock();
933 $this->mBlock
= null;
934 wfDebug( __METHOD__
.": No block.\n" );
938 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
941 if ( wfIsLocallyBlockedProxy( $ip ) ) {
942 $this->mBlockedby
= wfMsg( 'proxyblocker' );
943 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
947 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
948 if ( $this->inSorbsBlacklist( $ip ) ) {
949 $this->mBlockedby
= wfMsg( 'sorbs' );
950 $this->mBlockreason
= wfMsg( 'sorbsreason' );
956 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
958 wfProfileOut( __METHOD__
);
961 function inSorbsBlacklist( $ip ) {
962 global $wgEnableSorbs, $wgSorbsUrl;
964 return $wgEnableSorbs &&
965 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
968 function inDnsBlacklist( $ip, $base ) {
969 wfProfileIn( __METHOD__
);
975 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
977 for ( $i=4; $i>=1; $i-- ) {
978 $host .= $m[$i] . '.';
983 $ipList = gethostbynamel( $host );
986 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
989 wfDebug( "Requested $host, not found in $base.\n" );
993 wfProfileOut( __METHOD__
);
998 * Is this user subject to rate limiting?
1002 public function isPingLimitable() {
1003 global $wgRateLimitsExcludedGroups;
1004 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
1008 * Primitive rate limits: enforce maximum actions per time period
1009 * to put a brake on flooding.
1011 * Note: when using a shared cache like memcached, IP-address
1012 * last-hit counters will be shared across wikis.
1014 * @return bool true if a rate limiter was tripped
1017 function pingLimiter( $action='edit' ) {
1019 # Call the 'PingLimiter' hook
1021 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1025 global $wgRateLimits, $wgRateLimitsExcludedGroups;
1026 if( !isset( $wgRateLimits[$action] ) ) {
1030 # Some groups shouldn't trigger the ping limiter, ever
1031 if( !$this->isPingLimitable() )
1034 global $wgMemc, $wgRateLimitLog;
1035 wfProfileIn( __METHOD__
);
1037 $limits = $wgRateLimits[$action];
1039 $id = $this->getId();
1042 if( isset( $limits['anon'] ) && $id == 0 ) {
1043 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1046 if( isset( $limits['user'] ) && $id != 0 ) {
1047 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
1049 if( $this->isNewbie() ) {
1050 if( isset( $limits['newbie'] ) && $id != 0 ) {
1051 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1053 if( isset( $limits['ip'] ) ) {
1054 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1057 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1058 $subnet = $matches[1];
1059 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1064 foreach( $keys as $key => $limit ) {
1065 list( $max, $period ) = $limit;
1066 $summary = "(limit $max in {$period}s)";
1067 $count = $wgMemc->get( $key );
1069 if( $count > $max ) {
1070 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1071 if( $wgRateLimitLog ) {
1072 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1076 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1079 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1080 $wgMemc->add( $key, 1, intval( $period ) );
1082 $wgMemc->incr( $key );
1085 wfProfileOut( __METHOD__
);
1090 * Check if user is blocked
1091 * @return bool True if blocked, false otherwise
1093 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1094 wfDebug( "User::isBlocked: enter\n" );
1095 $this->getBlockedStatus( $bFromSlave );
1096 return $this->mBlockedby
!== 0;
1100 * Check if user is blocked from editing a particular article
1102 function isBlockedFrom( $title, $bFromSlave = false ) {
1103 global $wgBlockAllowsUTEdit;
1104 wfProfileIn( __METHOD__
);
1105 wfDebug( __METHOD__
.": enter\n" );
1107 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1108 $blocked = $this->isBlocked( $bFromSlave );
1109 # If a user's name is suppressed, they cannot make edits anywhere
1110 if ( !$this->mHideName
&& $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1111 $title->getNamespace() == NS_USER_TALK
) {
1113 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1115 wfProfileOut( __METHOD__
);
1120 * Get name of blocker
1121 * @return string name of blocker
1123 function blockedBy() {
1124 $this->getBlockedStatus();
1125 return $this->mBlockedby
;
1129 * Get blocking reason
1130 * @return string Blocking reason
1132 function blockedFor() {
1133 $this->getBlockedStatus();
1134 return $this->mBlockreason
;
1138 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1141 if( $this->mId
=== null and $this->mName
!== null
1142 and User
::isIP( $this->mName
) ) {
1143 // Special case, we know the user is anonymous
1145 } elseif( $this->mId
=== null ) {
1146 // Don't load if this was initialized from an ID
1153 * Set the user and reload all fields according to that ID
1154 * @deprecated use User::newFromId()
1156 function setID( $v ) {
1158 $this->clearInstanceCache( 'id' );
1162 * Get the user name, or the IP for anons
1164 function getName() {
1165 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1166 # Special case optimisation
1167 return $this->mName
;
1170 if ( $this->mName
=== false ) {
1172 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1174 return $this->mName
;
1179 * Set the user name.
1181 * This does not reload fields from the database according to the given
1182 * name. Rather, it is used to create a temporary "nonexistent user" for
1183 * later addition to the database. It can also be used to set the IP
1184 * address for an anonymous user to something other than the current
1187 * User::newFromName() has rougly the same function, when the named user
1190 function setName( $str ) {
1192 $this->mName
= $str;
1196 * Return the title dbkey form of the name, for eg user pages.
1200 function getTitleKey() {
1201 return str_replace( ' ', '_', $this->getName() );
1204 function getNewtalk() {
1207 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1208 if( $this->mNewtalk
=== -1 ) {
1209 $this->mNewtalk
= false; # reset talk page status
1211 # Check memcached separately for anons, who have no
1212 # entire User object stored in there.
1215 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1216 $newtalk = $wgMemc->get( $key );
1217 if( strval( $newtalk ) !== '' ) {
1218 $this->mNewtalk
= (bool)$newtalk;
1220 // Since we are caching this, make sure it is up to date by getting it
1222 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1223 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1226 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1230 return (bool)$this->mNewtalk
;
1234 * Return the talk page(s) this user has new messages on.
1236 function getNewMessageLinks() {
1238 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1241 if (!$this->getNewtalk())
1243 $up = $this->getUserPage();
1244 $utp = $up->getTalkPage();
1245 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1250 * Perform a user_newtalk check, uncached.
1251 * Use getNewtalk for a cached check.
1253 * @param string $field
1255 * @param bool $fromMaster True to fetch from the master, false for a slave
1259 function checkNewtalk( $field, $id, $fromMaster = false ) {
1260 if ( $fromMaster ) {
1261 $db = wfGetDB( DB_MASTER
);
1263 $db = wfGetDB( DB_SLAVE
);
1265 $ok = $db->selectField( 'user_newtalk', $field,
1266 array( $field => $id ), __METHOD__
);
1267 return $ok !== false;
1272 * @param string $field
1276 function updateNewtalk( $field, $id ) {
1277 $dbw = wfGetDB( DB_MASTER
);
1278 $dbw->insert( 'user_newtalk',
1279 array( $field => $id ),
1282 if ( $dbw->affectedRows() ) {
1283 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1286 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1292 * Clear the new messages flag for the given user
1293 * @param string $field
1297 function deleteNewtalk( $field, $id ) {
1298 $dbw = wfGetDB( DB_MASTER
);
1299 $dbw->delete( 'user_newtalk',
1300 array( $field => $id ),
1302 if ( $dbw->affectedRows() ) {
1303 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1306 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1312 * Update the 'You have new messages!' status.
1315 function setNewtalk( $val ) {
1316 if( wfReadOnly() ) {
1321 $this->mNewtalk
= $val;
1323 if( $this->isAnon() ) {
1325 $id = $this->getName();
1328 $id = $this->getId();
1333 $changed = $this->updateNewtalk( $field, $id );
1335 $changed = $this->deleteNewtalk( $field, $id );
1338 if( $this->isAnon() ) {
1339 // Anons have a separate memcached space, since
1340 // user records aren't kept for them.
1341 $key = wfMemcKey( 'newtalk', 'ip', $id );
1342 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1345 $this->invalidateCache();
1350 * Generate a current or new-future timestamp to be stored in the
1351 * user_touched field when we update things.
1353 private static function newTouchedTimestamp() {
1354 global $wgClockSkewFudge;
1355 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1359 * Clear user data from memcached.
1360 * Use after applying fun updates to the database; caller's
1361 * responsibility to update user_touched if appropriate.
1363 * Called implicitly from invalidateCache() and saveSettings().
1365 private function clearSharedCache() {
1368 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1373 * Immediately touch the user data cache for this account.
1374 * Updates user_touched field, and removes account data from memcached
1375 * for reload on the next hit.
1377 function invalidateCache() {
1380 $this->mTouched
= self
::newTouchedTimestamp();
1382 $dbw = wfGetDB( DB_MASTER
);
1383 $dbw->update( 'user',
1384 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1385 array( 'user_id' => $this->mId
),
1388 $this->clearSharedCache();
1392 function validateCache( $timestamp ) {
1394 return ($timestamp >= $this->mTouched
);
1398 * Encrypt a password.
1399 * It can eventually salt a password.
1400 * @see User::addSalt()
1401 * @param string $p clear Password.
1402 * @return string Encrypted password.
1404 function encryptPassword( $p ) {
1406 return wfEncryptPassword( $this->mId
, $p );
1410 * Set the password and reset the random token
1411 * Calls through to authentication plugin if necessary;
1412 * will have no effect if the auth plugin refuses to
1413 * pass the change through or if the legal password
1416 * As a special case, setting the password to null
1417 * wipes it, so the account cannot be logged in until
1418 * a new password is set, for instance via e-mail.
1420 * @param string $str
1421 * @throws PasswordError on failure
1423 function setPassword( $str ) {
1426 if( $str !== null ) {
1427 if( !$wgAuth->allowPasswordChange() ) {
1428 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1431 if( !$this->isValidPassword( $str ) ) {
1432 global $wgMinimalPasswordLength;
1433 throw new PasswordError( wfMsg( 'passwordtooshort',
1434 $wgMinimalPasswordLength ) );
1438 if( !$wgAuth->setPassword( $this, $str ) ) {
1439 throw new PasswordError( wfMsg( 'externaldberror' ) );
1442 $this->setInternalPassword( $str );
1448 * Set the password and reset the random token no matter
1451 * @param string $str
1453 function setInternalPassword( $str ) {
1457 if( $str === null ) {
1458 // Save an invalid hash...
1459 $this->mPassword
= '';
1461 $this->mPassword
= $this->encryptPassword( $str );
1463 $this->mNewpassword
= '';
1464 $this->mNewpassTime
= null;
1467 * Set the random token (used for persistent authentication)
1468 * Called from loadDefaults() among other places.
1471 function setToken( $token = false ) {
1472 global $wgSecretKey, $wgProxyKey;
1475 if ( $wgSecretKey ) {
1476 $key = $wgSecretKey;
1477 } elseif ( $wgProxyKey ) {
1482 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1484 $this->mToken
= $token;
1488 function setCookiePassword( $str ) {
1490 $this->mCookiePassword
= md5( $str );
1494 * Set the password for a password reminder or new account email
1495 * Sets the user_newpass_time field if $throttle is true
1497 function setNewpassword( $str, $throttle = true ) {
1499 $this->mNewpassword
= $this->encryptPassword( $str );
1501 $this->mNewpassTime
= wfTimestampNow();
1506 * Returns true if a password reminder email has already been sent within
1507 * the last $wgPasswordReminderResendTime hours
1509 function isPasswordReminderThrottled() {
1510 global $wgPasswordReminderResendTime;
1512 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1515 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1516 return time() < $expiry;
1519 function getEmail() {
1521 return $this->mEmail
;
1524 function getEmailAuthenticationTimestamp() {
1526 return $this->mEmailAuthenticated
;
1529 function setEmail( $str ) {
1531 $this->mEmail
= $str;
1534 function getRealName() {
1536 return $this->mRealName
;
1539 function setRealName( $str ) {
1541 $this->mRealName
= $str;
1545 * @param string $oname The option to check
1546 * @param string $defaultOverride A default value returned if the option does not exist
1549 function getOption( $oname, $defaultOverride = '' ) {
1552 if ( is_null( $this->mOptions
) ) {
1553 if($defaultOverride != '') {
1554 return $defaultOverride;
1556 $this->mOptions
= User
::getDefaultOptions();
1559 if ( array_key_exists( $oname, $this->mOptions
) ) {
1560 return trim( $this->mOptions
[$oname] );
1562 return $defaultOverride;
1567 * Get the user's date preference, including some important migration for
1570 function getDatePreference() {
1571 if ( is_null( $this->mDatePreference
) ) {
1573 $value = $this->getOption( 'date' );
1574 $map = $wgLang->getDatePreferenceMigrationMap();
1575 if ( isset( $map[$value] ) ) {
1576 $value = $map[$value];
1578 $this->mDatePreference
= $value;
1580 return $this->mDatePreference
;
1584 * @param string $oname The option to check
1585 * @return bool False if the option is not selected, true if it is
1587 function getBoolOption( $oname ) {
1588 return (bool)$this->getOption( $oname );
1592 * Get an option as an integer value from the source string.
1593 * @param string $oname The option to check
1594 * @param int $default Optional value to return if option is unset/blank.
1597 function getIntOption( $oname, $default=0 ) {
1598 $val = $this->getOption( $oname );
1602 return intval( $val );
1605 function setOption( $oname, $val ) {
1607 if ( is_null( $this->mOptions
) ) {
1608 $this->mOptions
= User
::getDefaultOptions();
1610 if ( $oname == 'skin' ) {
1611 # Clear cached skin, so the new one displays immediately in Special:Preferences
1612 unset( $this->mSkin
);
1614 // Filter out any newlines that may have passed through input validation.
1615 // Newlines are used to separate items in the options blob.
1616 $val = str_replace( "\r\n", "\n", $val );
1617 $val = str_replace( "\r", "\n", $val );
1618 $val = str_replace( "\n", " ", $val );
1619 $this->mOptions
[$oname] = $val;
1622 function getRights() {
1623 if ( is_null( $this->mRights
) ) {
1624 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1625 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1627 return $this->mRights
;
1631 * Get the list of explicit group memberships this user has.
1632 * The implicit * and user groups are not included.
1633 * @return array of strings
1635 function getGroups() {
1637 return $this->mGroups
;
1641 * Get the list of implicit group memberships this user has.
1642 * This includes all explicit groups, plus 'user' if logged in
1643 * and '*' for all accounts.
1644 * @param boolean $recache Don't use the cache
1645 * @return array of strings
1647 function getEffectiveGroups( $recache = false ) {
1648 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1650 $this->mEffectiveGroups
= $this->mGroups
;
1651 $this->mEffectiveGroups
[] = '*';
1653 $this->mEffectiveGroups
[] = 'user';
1655 global $wgAutoConfirmAge, $wgAutoConfirmCount;
1657 $accountAge = time() - wfTimestampOrNull( TS_UNIX
, $this->mRegistration
);
1658 if( $accountAge >= $wgAutoConfirmAge && $this->getEditCount() >= $wgAutoConfirmCount ) {
1659 $this->mEffectiveGroups
[] = 'autoconfirmed';
1661 # Implicit group for users whose email addresses are confirmed
1662 global $wgEmailAuthentication;
1663 if( self
::isValidEmailAddr( $this->mEmail
) ) {
1664 if( $wgEmailAuthentication ) {
1665 if( $this->mEmailAuthenticated
)
1666 $this->mEffectiveGroups
[] = 'emailconfirmed';
1668 $this->mEffectiveGroups
[] = 'emailconfirmed';
1671 # Hook for additional groups
1672 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1675 return $this->mEffectiveGroups
;
1678 /* Return the edit count for the user. This is where User::edits should have been */
1679 function getEditCount() {
1681 if ( !isset( $this->mEditCount
) ) {
1682 /* Populate the count, if it has not been populated yet */
1683 $this->mEditCount
= User
::edits($this->mId
);
1685 return $this->mEditCount
;
1693 * Add the user to the given group.
1694 * This takes immediate effect.
1695 * @param string $group
1697 function addGroup( $group ) {
1699 $dbw = wfGetDB( DB_MASTER
);
1700 if( $this->getId() ) {
1701 $dbw->insert( 'user_groups',
1703 'ug_user' => $this->getID(),
1704 'ug_group' => $group,
1707 array( 'IGNORE' ) );
1710 $this->mGroups
[] = $group;
1711 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1713 $this->invalidateCache();
1717 * Remove the user from the given group.
1718 * This takes immediate effect.
1719 * @param string $group
1721 function removeGroup( $group ) {
1723 $dbw = wfGetDB( DB_MASTER
);
1724 $dbw->delete( 'user_groups',
1726 'ug_user' => $this->getID(),
1727 'ug_group' => $group,
1729 'User::removeGroup' );
1731 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1732 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1734 $this->invalidateCache();
1739 * A more legible check for non-anonymousness.
1740 * Returns true if the user is not an anonymous visitor.
1744 function isLoggedIn() {
1745 if( $this->mId
=== null and $this->mName
!== null ) {
1746 // Special-case optimization
1747 return !self
::isIP( $this->mName
);
1749 return $this->getID() != 0;
1753 * A more legible check for anonymousness.
1754 * Returns true if the user is an anonymous visitor.
1759 return !$this->isLoggedIn();
1763 * Whether the user is a bot
1767 return $this->isAllowed( 'bot' );
1771 * Check if user is allowed to access a feature / make an action
1772 * @param string $action Action to be checked
1773 * @return boolean True: action is allowed, False: action should not be allowed
1775 function isAllowed($action='') {
1776 if ( $action === '' )
1777 // In the spirit of DWIM
1780 return in_array( $action, $this->getRights() );
1784 * Load a skin if it doesn't exist or return it
1785 * @todo FIXME : need to check the old failback system [AV]
1787 function &getSkin() {
1789 if ( ! isset( $this->mSkin
) ) {
1790 wfProfileIn( __METHOD__
);
1793 $userSkin = $this->getOption( 'skin' );
1794 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1796 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1797 wfProfileOut( __METHOD__
);
1799 return $this->mSkin
;
1803 * @param string $title Article title to look at
1807 * Check watched status of an article
1808 * @return bool True if article is watched
1810 function isWatched( $title ) {
1811 $wl = WatchedItem
::fromUserTitle( $this, $title );
1812 return $wl->isWatched();
1818 function addWatch( $title ) {
1819 $wl = WatchedItem
::fromUserTitle( $this, $title );
1821 $this->invalidateCache();
1825 * Stop watching an article
1827 function removeWatch( $title ) {
1828 $wl = WatchedItem
::fromUserTitle( $this, $title );
1830 $this->invalidateCache();
1834 * Clear the user's notification timestamp for the given title.
1835 * If e-notif e-mails are on, they will receive notification mails on
1836 * the next change of the page if it's watched etc.
1838 function clearNotification( &$title ) {
1839 global $wgUser, $wgUseEnotif;
1841 # Do nothing if the database is locked to writes
1842 if( wfReadOnly() ) {
1846 if ($title->getNamespace() == NS_USER_TALK
&&
1847 $title->getText() == $this->getName() ) {
1848 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1850 $this->setNewtalk( false );
1853 if( !$wgUseEnotif ) {
1857 if( $this->isAnon() ) {
1858 // Nothing else to do...
1862 // Only update the timestamp if the page is being watched.
1863 // The query to find out if it is watched is cached both in memcached and per-invocation,
1864 // and when it does have to be executed, it can be on a slave
1865 // If this is the user's newtalk page, we always update the timestamp
1866 if ($title->getNamespace() == NS_USER_TALK
&&
1867 $title->getText() == $wgUser->getName())
1870 } elseif ( $this->getID() == $wgUser->getID() ) {
1871 $watched = $title->userIsWatching();
1876 // If the page is watched by the user (or may be watched), update the timestamp on any
1877 // any matching rows
1879 $dbw = wfGetDB( DB_MASTER
);
1880 $dbw->update( 'watchlist',
1882 'wl_notificationtimestamp' => NULL
1883 ), array( /* WHERE */
1884 'wl_title' => $title->getDBkey(),
1885 'wl_namespace' => $title->getNamespace(),
1886 'wl_user' => $this->getID()
1887 ), 'User::clearLastVisited'
1895 * Resets all of the given user's page-change notification timestamps.
1896 * If e-notif e-mails are on, they will receive notification mails on
1897 * the next change of any watched page.
1899 * @param int $currentUser user ID number
1902 function clearAllNotifications( $currentUser ) {
1903 global $wgUseEnotif;
1904 if ( !$wgUseEnotif ) {
1905 $this->setNewtalk( false );
1908 if( $currentUser != 0 ) {
1910 $dbw = wfGetDB( DB_MASTER
);
1911 $dbw->update( 'watchlist',
1913 'wl_notificationtimestamp' => NULL
1914 ), array( /* WHERE */
1915 'wl_user' => $currentUser
1919 # we also need to clear here the "you have new message" notification for the own user_talk page
1920 # This is cleared one page view later in Article::viewUpdates();
1926 * @return string Encoding options
1928 function encodeOptions() {
1930 if ( is_null( $this->mOptions
) ) {
1931 $this->mOptions
= User
::getDefaultOptions();
1934 foreach ( $this->mOptions
as $oname => $oval ) {
1935 array_push( $a, $oname.'='.$oval );
1937 $s = implode( "\n", $a );
1944 function decodeOptions( $str ) {
1945 $this->mOptions
= array();
1946 $a = explode( "\n", $str );
1947 foreach ( $a as $s ) {
1949 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1950 $this->mOptions
[$m[1]] = $m[2];
1955 function setCookies() {
1956 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1958 if ( 0 == $this->mId
) return;
1959 $exp = time() +
$wgCookieExpiration;
1961 $_SESSION['wsUserID'] = $this->mId
;
1962 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1964 $_SESSION['wsUserName'] = $this->getName();
1965 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1967 $_SESSION['wsToken'] = $this->mToken
;
1968 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1969 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1971 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1977 * Clears the cookies and session, resets the instance cache
1980 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1981 $this->clearInstanceCache( 'defaults' );
1983 $_SESSION['wsUserID'] = 0;
1985 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1986 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1988 # Remember when user logged out, to prevent seeing cached pages
1989 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1993 * Save object settings into database
1994 * @todo Only rarely do all these fields need to be set!
1996 function saveSettings() {
1998 if ( wfReadOnly() ) { return; }
1999 if ( 0 == $this->mId
) { return; }
2001 $this->mTouched
= self
::newTouchedTimestamp();
2003 $dbw = wfGetDB( DB_MASTER
);
2004 $dbw->update( 'user',
2006 'user_name' => $this->mName
,
2007 'user_password' => $this->mPassword
,
2008 'user_newpassword' => $this->mNewpassword
,
2009 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2010 'user_real_name' => $this->mRealName
,
2011 'user_email' => $this->mEmail
,
2012 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2013 'user_options' => $this->encodeOptions(),
2014 'user_touched' => $dbw->timestamp($this->mTouched
),
2015 'user_token' => $this->mToken
2016 ), array( /* WHERE */
2017 'user_id' => $this->mId
2020 $this->clearSharedCache();
2025 * Checks if a user with the given name exists, returns the ID
2027 function idForName() {
2028 $s = trim( $this->getName() );
2029 if ( 0 == strcmp( '', $s ) ) return 0;
2031 $dbr = wfGetDB( DB_SLAVE
);
2032 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2033 if ( $id === false ) {
2040 * Add a user to the database, return the user object
2042 * @param string $name The user's name
2043 * @param array $params Associative array of non-default parameters to save to the database:
2044 * password The user's password. Password logins will be disabled if this is omitted.
2045 * newpassword A temporary password mailed to the user
2046 * email The user's email address
2047 * email_authenticated The email authentication timestamp
2048 * real_name The user's real name
2049 * options An associative array of non-default options
2050 * token Random authentication token. Do not set.
2051 * registration Registration timestamp. Do not set.
2053 * @return User object, or null if the username already exists
2055 static function createNew( $name, $params = array() ) {
2058 if ( isset( $params['options'] ) ) {
2059 $user->mOptions
= $params['options'] +
$user->mOptions
;
2060 unset( $params['options'] );
2062 $dbw = wfGetDB( DB_MASTER
);
2063 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2065 'user_id' => $seqVal,
2066 'user_name' => $name,
2067 'user_password' => $user->mPassword
,
2068 'user_newpassword' => $user->mNewpassword
,
2069 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2070 'user_email' => $user->mEmail
,
2071 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2072 'user_real_name' => $user->mRealName
,
2073 'user_options' => $user->encodeOptions(),
2074 'user_token' => $user->mToken
,
2075 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2076 'user_editcount' => 0,
2078 foreach ( $params as $name => $value ) {
2079 $fields["user_$name"] = $value;
2081 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2082 if ( $dbw->affectedRows() ) {
2083 $newUser = User
::newFromId( $dbw->insertId() );
2091 * Add an existing user object to the database
2093 function addToDatabase() {
2095 $dbw = wfGetDB( DB_MASTER
);
2096 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2097 $dbw->insert( 'user',
2099 'user_id' => $seqVal,
2100 'user_name' => $this->mName
,
2101 'user_password' => $this->mPassword
,
2102 'user_newpassword' => $this->mNewpassword
,
2103 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2104 'user_email' => $this->mEmail
,
2105 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2106 'user_real_name' => $this->mRealName
,
2107 'user_options' => $this->encodeOptions(),
2108 'user_token' => $this->mToken
,
2109 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2110 'user_editcount' => 0,
2113 $this->mId
= $dbw->insertId();
2115 # Clear instance cache other than user table data, which is already accurate
2116 $this->clearInstanceCache();
2120 * If the (non-anonymous) user is blocked, this function will block any IP address
2121 * that they successfully log on from.
2123 function spreadBlock() {
2124 wfDebug( __METHOD__
."()\n" );
2126 if ( $this->mId
== 0 ) {
2130 $userblock = Block
::newFromDB( '', $this->mId
);
2131 if ( !$userblock ) {
2135 $userblock->doAutoblock( wfGetIp() );
2140 * Generate a string which will be different for any combination of
2141 * user options which would produce different parser output.
2142 * This will be used as part of the hash key for the parser cache,
2143 * so users will the same options can share the same cached data
2146 * Extensions which require it should install 'PageRenderingHash' hook,
2147 * which will give them a chance to modify this key based on their own
2152 function getPageRenderingHash() {
2153 global $wgContLang, $wgUseDynamicDates, $wgLang;
2155 return $this->mHash
;
2158 // stubthreshold is only included below for completeness,
2159 // it will always be 0 when this function is called by parsercache.
2161 $confstr = $this->getOption( 'math' );
2162 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2163 if ( $wgUseDynamicDates ) {
2164 $confstr .= '!' . $this->getDatePreference();
2166 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2167 $confstr .= '!' . $wgLang->getCode();
2168 $confstr .= '!' . $this->getOption( 'thumbsize' );
2169 // add in language specific options, if any
2170 $extra = $wgContLang->getExtraHashOptions();
2173 // Give a chance for extensions to modify the hash, if they have
2174 // extra options or other effects on the parser cache.
2175 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2177 // Make it a valid memcached key fragment
2178 $confstr = str_replace( ' ', '_', $confstr );
2179 $this->mHash
= $confstr;
2183 function isBlockedFromCreateAccount() {
2184 $this->getBlockedStatus();
2185 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2189 * Determine if the user is blocked from using Special:Emailuser.
2194 function isBlockedFromEmailuser() {
2195 $this->getBlockedStatus();
2196 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2199 function isAllowedToCreateAccount() {
2200 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2206 function setLoaded( $loaded ) {}
2209 * Get this user's personal page title.
2214 function getUserPage() {
2215 return Title
::makeTitle( NS_USER
, $this->getName() );
2219 * Get this user's talk page title.
2224 function getTalkPage() {
2225 $title = $this->getUserPage();
2226 return $title->getTalkPage();
2232 function getMaxID() {
2233 static $res; // cache
2235 if ( isset( $res ) )
2238 $dbr = wfGetDB( DB_SLAVE
);
2239 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2244 * Determine whether the user is a newbie. Newbies are either
2245 * anonymous IPs, or the most recently created accounts.
2246 * @return bool True if it is a newbie.
2248 function isNewbie() {
2249 return !$this->isAllowed( 'autoconfirmed' );
2253 * Check to see if the given clear-text password is one of the accepted passwords
2254 * @param string $password User password.
2255 * @return bool True if the given password is correct otherwise False.
2257 function checkPassword( $password ) {
2261 // Even though we stop people from creating passwords that
2262 // are shorter than this, doesn't mean people wont be able
2263 // to. Certain authentication plugins do NOT want to save
2264 // domain passwords in a mysql database, so we should
2265 // check this (incase $wgAuth->strict() is false).
2266 if( !$this->isValidPassword( $password ) ) {
2270 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2272 } elseif( $wgAuth->strict() ) {
2273 /* Auth plugin doesn't allow local authentication */
2275 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2276 /* Auth plugin doesn't allow local authentication for this user name */
2279 $ep = $this->encryptPassword( $password );
2280 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2282 } elseif ( function_exists( 'iconv' ) ) {
2283 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2284 # Check for this with iconv
2285 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2286 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2294 * Check if the given clear-text password matches the temporary password
2295 * sent by e-mail for password reset operations.
2298 function checkTemporaryPassword( $plaintext ) {
2299 $hash = $this->encryptPassword( $plaintext );
2300 return $hash === $this->mNewpassword
;
2304 * Initialize (if necessary) and return a session token value
2305 * which can be used in edit forms to show that the user's
2306 * login credentials aren't being hijacked with a foreign form
2309 * @param mixed $salt - Optional function-specific data for hash.
2310 * Use a string or an array of strings.
2314 function editToken( $salt = '' ) {
2315 if ( $this->isAnon() ) {
2316 return EDIT_TOKEN_SUFFIX
;
2318 if( !isset( $_SESSION['wsEditToken'] ) ) {
2319 $token = $this->generateToken();
2320 $_SESSION['wsEditToken'] = $token;
2322 $token = $_SESSION['wsEditToken'];
2324 if( is_array( $salt ) ) {
2325 $salt = implode( '|', $salt );
2327 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2332 * Generate a hex-y looking random token for various uses.
2333 * Could be made more cryptographically sure if someone cares.
2336 function generateToken( $salt = '' ) {
2337 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2338 return md5( $token . $salt );
2342 * Check given value against the token value stored in the session.
2343 * A match should confirm that the form was submitted from the
2344 * user's own login session, not a form submission from a third-party
2347 * @param string $val - the input value to compare
2348 * @param string $salt - Optional function-specific data for hash
2352 function matchEditToken( $val, $salt = '' ) {
2353 $sessionToken = $this->editToken( $salt );
2354 if ( $val != $sessionToken ) {
2355 wfDebug( "User::matchEditToken: broken session data\n" );
2357 return $val == $sessionToken;
2361 * Check whether the edit token is fine except for the suffix
2363 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2364 $sessionToken = $this->editToken( $salt );
2365 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2369 * Generate a new e-mail confirmation token and send a confirmation
2370 * mail to the user's given address.
2372 * @return mixed True on success, a WikiError object on failure.
2374 function sendConfirmationMail() {
2376 $expiration = null; // gets passed-by-ref and defined in next line.
2377 $url = $this->confirmationTokenUrl( $expiration );
2378 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2379 wfMsg( 'confirmemail_body',
2383 $wgContLang->timeanddate( $expiration, false ) ) );
2387 * Send an e-mail to this user's account. Does not check for
2388 * confirmed status or validity.
2390 * @param string $subject
2391 * @param string $body
2392 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2393 * @return mixed True on success, a WikiError object on failure.
2395 function sendMail( $subject, $body, $from = null ) {
2396 if( is_null( $from ) ) {
2397 global $wgPasswordSender;
2398 $from = $wgPasswordSender;
2401 $to = new MailAddress( $this );
2402 $sender = new MailAddress( $from );
2403 $error = UserMailer
::send( $to, $sender, $subject, $body );
2405 if( $error == '' ) {
2408 return new WikiError( $error );
2413 * Generate, store, and return a new e-mail confirmation code.
2414 * A hash (unsalted since it's used as a key) is stored.
2415 * @param &$expiration mixed output: accepts the expiration time
2419 function confirmationToken( &$expiration ) {
2421 $expires = $now +
7 * 24 * 60 * 60;
2422 $expiration = wfTimestamp( TS_MW
, $expires );
2424 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2425 $hash = md5( $token );
2427 $dbw = wfGetDB( DB_MASTER
);
2428 $dbw->update( 'user',
2429 array( 'user_email_token' => $hash,
2430 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2431 array( 'user_id' => $this->mId
),
2438 * Generate and store a new e-mail confirmation token, and return
2439 * the URL the user can use to confirm.
2440 * @param &$expiration mixed output: accepts the expiration time
2444 function confirmationTokenUrl( &$expiration ) {
2445 $token = $this->confirmationToken( $expiration );
2446 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2447 return $title->getFullUrl();
2451 * Mark the e-mail address confirmed and save.
2453 function confirmEmail() {
2455 $this->mEmailAuthenticated
= wfTimestampNow();
2456 $this->saveSettings();
2461 * Is this user allowed to send e-mails within limits of current
2462 * site configuration?
2465 function canSendEmail() {
2466 return $this->isEmailConfirmed();
2470 * Is this user allowed to receive e-mails within limits of current
2471 * site configuration?
2474 function canReceiveEmail() {
2475 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2479 * Is this user's e-mail address valid-looking and confirmed within
2480 * limits of the current site configuration?
2482 * If $wgEmailAuthentication is on, this may require the user to have
2483 * confirmed their address by returning a code or using a password
2484 * sent to the address from the wiki.
2488 function isEmailConfirmed() {
2489 global $wgEmailAuthentication;
2492 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2493 if( $this->isAnon() )
2495 if( !self
::isValidEmailAddr( $this->mEmail
) )
2497 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2506 * Return true if there is an outstanding request for e-mail confirmation.
2509 function isEmailConfirmationPending() {
2510 global $wgEmailAuthentication;
2511 return $wgEmailAuthentication &&
2512 !$this->isEmailConfirmed() &&
2513 $this->mEmailToken
&&
2514 $this->mEmailTokenExpires
> wfTimestamp();
2518 * Get the timestamp of account creation, or false for
2519 * non-existent/anonymous user accounts
2523 public function getRegistration() {
2524 return $this->mId
> 0
2525 ?
$this->mRegistration
2530 * @param array $groups list of groups
2531 * @return array list of permission key names for given groups combined
2534 static function getGroupPermissions( $groups ) {
2535 global $wgGroupPermissions;
2537 foreach( $groups as $group ) {
2538 if( isset( $wgGroupPermissions[$group] ) ) {
2539 $rights = array_merge( $rights,
2540 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2547 * @param string $group key name
2548 * @return string localized descriptive name for group, if provided
2551 static function getGroupName( $group ) {
2552 global $wgMessageCache;
2553 $wgMessageCache->loadAllMessages();
2554 $key = "group-$group";
2555 $name = wfMsg( $key );
2556 return $name == '' ||
wfEmptyMsg( $key, $name )
2562 * @param string $group key name
2563 * @return string localized descriptive name for member of a group, if provided
2566 static function getGroupMember( $group ) {
2567 global $wgMessageCache;
2568 $wgMessageCache->loadAllMessages();
2569 $key = "group-$group-member";
2570 $name = wfMsg( $key );
2571 return $name == '' ||
wfEmptyMsg( $key, $name )
2577 * Return the set of defined explicit groups.
2578 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2579 * groups are not included, as they are defined
2580 * automatically, not in the database.
2584 static function getAllGroups() {
2585 global $wgGroupPermissions;
2587 array_keys( $wgGroupPermissions ),
2588 self
::getImplicitGroups()
2593 * Get a list of implicit groups
2597 public static function getImplicitGroups() {
2598 static $groups = null;
2599 if( !is_array( $groups ) ) {
2600 $groups = array( '*', 'user', 'autoconfirmed', 'emailconfirmed' );
2601 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
2607 * Get the title of a page describing a particular group
2609 * @param $group Name of the group
2612 static function getGroupPage( $group ) {
2613 global $wgMessageCache;
2614 $wgMessageCache->loadAllMessages();
2615 $page = wfMsgForContent( 'grouppage-' . $group );
2616 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2617 $title = Title
::newFromText( $page );
2618 if( is_object( $title ) )
2625 * Create a link to the group in HTML, if available
2627 * @param $group Name of the group
2628 * @param $text The text of the link
2631 static function makeGroupLinkHTML( $group, $text = '' ) {
2633 $text = self
::getGroupName( $group );
2635 $title = self
::getGroupPage( $group );
2638 $sk = $wgUser->getSkin();
2639 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2646 * Create a link to the group in Wikitext, if available
2648 * @param $group Name of the group
2649 * @param $text The text of the link (by default, the name of the group)
2652 static function makeGroupLinkWiki( $group, $text = '' ) {
2654 $text = self
::getGroupName( $group );
2656 $title = self
::getGroupPage( $group );
2658 $page = $title->getPrefixedText();
2659 return "[[$page|$text]]";
2666 * Increment the user's edit-count field.
2667 * Will have no effect for anonymous users.
2669 function incEditCount() {
2670 if( !$this->isAnon() ) {
2671 $dbw = wfGetDB( DB_MASTER
);
2672 $dbw->update( 'user',
2673 array( 'user_editcount=user_editcount+1' ),
2674 array( 'user_id' => $this->getId() ),
2677 // Lazy initialization check...
2678 if( $dbw->affectedRows() == 0 ) {
2679 // Pull from a slave to be less cruel to servers
2680 // Accuracy isn't the point anyway here
2681 $dbr = wfGetDB( DB_SLAVE
);
2682 $count = $dbr->selectField( 'revision',
2684 array( 'rev_user' => $this->getId() ),
2687 // Now here's a goddamn hack...
2688 if( $dbr !== $dbw ) {
2689 // If we actually have a slave server, the count is
2690 // at least one behind because the current transaction
2691 // has not been committed and replicated.
2694 // But if DB_SLAVE is selecting the master, then the
2695 // count we just read includes the revision that was
2696 // just added in the working transaction.
2699 $dbw->update( 'user',
2700 array( 'user_editcount' => $count ),
2701 array( 'user_id' => $this->getId() ),
2705 // edit count in user cache too
2706 $this->invalidateCache();