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',
83 * List of member variables which are saved to the shared cache (memcached).
84 * Any operation which changes the corresponding database fields must
85 * call a cache-clearing function.
87 static $mCacheVars = array(
99 'mEmailAuthenticated',
101 'mEmailTokenExpires',
109 * The cache variable declarations
111 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
112 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
113 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
116 * Whether the cache variables have been loaded
121 * Initialisation data source if mDataLoaded==false. May be one of:
122 * defaults anonymous user initialised from class defaults
123 * name initialise from mName
124 * id initialise from mId
125 * session log in from cookies or session if possible
127 * Use the User::newFrom*() family of functions to set this.
132 * Lazy-initialised variables, invalidated with clearInstanceCache
134 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
135 $mBlockreason, $mBlock, $mEffectiveGroups;
138 * Lightweight constructor for anonymous user
139 * Use the User::newFrom* factory functions for other kinds of users
142 $this->clearInstanceCache( 'defaults' );
146 * Load the user table data for this object from the source given by mFrom
149 if ( $this->mDataLoaded
) {
152 wfProfileIn( __METHOD__
);
154 # Set it now to avoid infinite recursion in accessors
155 $this->mDataLoaded
= true;
157 switch ( $this->mFrom
) {
159 $this->loadDefaults();
162 $this->mId
= self
::idFromName( $this->mName
);
164 # Nonexistent user placeholder object
165 $this->loadDefaults( $this->mName
);
174 $this->loadFromSession();
177 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
179 wfProfileOut( __METHOD__
);
183 * Load user table data given mId
184 * @return false if the ID does not exist, true otherwise
187 function loadFromId() {
189 if ( $this->mId
== 0 ) {
190 $this->loadDefaults();
195 $key = wfMemcKey( 'user', 'id', $this->mId
);
196 $data = $wgMemc->get( $key );
197 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
198 # Object is expired, load from DB
203 wfDebug( "Cache miss for user {$this->mId}\n" );
205 if ( !$this->loadFromDatabase() ) {
206 # Can't load from ID, user is anonymous
210 $this->saveToCache();
212 wfDebug( "Got user {$this->mId} from cache\n" );
214 foreach ( self
::$mCacheVars as $name ) {
215 $this->$name = $data[$name];
222 * Save user data to the shared cache
224 function saveToCache() {
226 if ( $this->isAnon() ) {
227 // Anonymous users are uncached
231 foreach ( self
::$mCacheVars as $name ) {
232 $data[$name] = $this->$name;
234 $data['mVersion'] = MW_USER_VERSION
;
235 $key = wfMemcKey( 'user', 'id', $this->mId
);
237 $wgMemc->set( $key, $data );
241 * Static factory method for creation from username.
243 * This is slightly less efficient than newFromId(), so use newFromId() if
244 * you have both an ID and a name handy.
246 * @param string $name Username, validated by Title:newFromText()
247 * @param mixed $validate Validate username. Takes the same parameters as
248 * User::getCanonicalName(), except that true is accepted as an alias
249 * for 'valid', for BC.
251 * @return User object, or null if the username is invalid. If the username
252 * is not present in the database, the result will be a user object with
253 * a name, zero user ID and default settings.
256 static function newFromName( $name, $validate = 'valid' ) {
257 if ( $validate === true ) {
260 $name = self
::getCanonicalName( $name, $validate );
261 if ( $name === false ) {
264 # Create unloaded user object
272 static function newFromId( $id ) {
280 * Factory method to fetch whichever user has a given email confirmation code.
281 * This code is generated when an account is created or its e-mail address
284 * If the code is invalid or has expired, returns NULL.
286 * @param string $code
290 static function newFromConfirmationCode( $code ) {
291 $dbr = wfGetDB( DB_SLAVE
);
292 $id = $dbr->selectField( 'user', 'user_id', array(
293 'user_email_token' => md5( $code ),
294 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
296 if( $id !== false ) {
297 return User
::newFromId( $id );
304 * Create a new user object using data from session or cookies. If the
305 * login credentials are invalid, the result is an anonymous user.
310 static function newFromSession() {
312 $user->mFrom
= 'session';
317 * Get username given an id.
318 * @param integer $id Database user id
319 * @return string Nickname of a user
322 static function whoIs( $id ) {
323 $dbr = wfGetDB( DB_SLAVE
);
324 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
328 * Get the real name of a user given their identifier
330 * @param int $id Database user id
331 * @return string Real name of a user
333 static function whoIsReal( $id ) {
334 $dbr = wfGetDB( DB_SLAVE
);
335 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
339 * Get database id given a user name
340 * @param string $name Nickname of a user
341 * @return integer|null Database user id (null: if non existent
344 static function idFromName( $name ) {
345 $nt = Title
::newFromText( $name );
346 if( is_null( $nt ) ) {
350 $dbr = wfGetDB( DB_SLAVE
);
351 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
353 if ( $s === false ) {
361 * Does the string match an anonymous IPv4 address?
363 * This function exists for username validation, in order to reject
364 * usernames which are similar in form to IP addresses. Strings such
365 * as 300.300.300.300 will return true because it looks like an IP
366 * address, despite not being strictly valid.
368 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
369 * address because the usemod software would "cloak" anonymous IP
370 * addresses like this, if we allowed accounts like this to be created
371 * new users could get the old edits of these anonymous users.
374 * @param string $name Nickname of a user
377 static function isIP( $name ) {
378 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User
::isIPv6($name);
379 /*return preg_match("/^
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]))\.
383 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
388 * Check if $name is an IPv6 IP.
390 static function isIPv6($name) {
392 * if it has any non-valid characters, it can't be a valid IPv6
395 if (preg_match("/[^:a-fA-F0-9]/", $name))
398 $parts = explode(":", $name);
399 if (count($parts) < 3)
401 foreach ($parts as $part) {
402 if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part))
409 * Is the input a valid username?
411 * Checks if the input is a valid username, we don't want an empty string,
412 * an IP address, anything that containins slashes (would mess up subpages),
413 * is longer than the maximum allowed username size or doesn't begin with
416 * @param string $name
420 static function isValidUserName( $name ) {
421 global $wgContLang, $wgMaxNameChars;
424 || User
::isIP( $name )
425 ||
strpos( $name, '/' ) !== false
426 ||
strlen( $name ) > $wgMaxNameChars
427 ||
$name != $wgContLang->ucfirst( $name ) ) {
428 wfDebugLog( 'username', __METHOD__
.
429 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
433 // Ensure that the name can't be misresolved as a different title,
434 // such as with extra namespace keys at the start.
435 $parsed = Title
::newFromText( $name );
436 if( is_null( $parsed )
437 ||
$parsed->getNamespace()
438 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
439 wfDebugLog( 'username', __METHOD__
.
440 ": '$name' invalid due to ambiguous prefixes" );
444 // Check an additional blacklist of troublemaker characters.
445 // Should these be merged into the title char list?
446 $unicodeBlacklist = '/[' .
447 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
448 '\x{00a0}' . # non-breaking space
449 '\x{2000}-\x{200f}' . # various whitespace
450 '\x{2028}-\x{202f}' . # breaks and control chars
451 '\x{3000}' . # ideographic space
452 '\x{e000}-\x{f8ff}' . # private use
454 if( preg_match( $unicodeBlacklist, $name ) ) {
455 wfDebugLog( 'username', __METHOD__
.
456 ": '$name' invalid due to blacklisted characters" );
464 * Usernames which fail to pass this function will be blocked
465 * from user login and new account registrations, but may be used
466 * internally by batch processes.
468 * If an account already exists in this form, login will be blocked
469 * by a failure to pass this function.
471 * @param string $name
474 static function isUsableName( $name ) {
475 global $wgReservedUsernames;
477 // Must be a valid username, obviously ;)
478 self
::isValidUserName( $name ) &&
480 // Certain names may be reserved for batch processes.
481 !in_array( $name, $wgReservedUsernames );
485 * Usernames which fail to pass this function will be blocked
486 * from new account registrations, but may be used internally
487 * either by batch processes or by user accounts which have
488 * already been created.
490 * Additional character blacklisting may be added here
491 * rather than in isValidUserName() to avoid disrupting
494 * @param string $name
497 static function isCreatableName( $name ) {
499 self
::isUsableName( $name ) &&
501 // Registration-time character blacklisting...
502 strpos( $name, '@' ) === false;
506 * Is the input a valid password for this user?
508 * @param string $password Desired password
511 function isValidPassword( $password ) {
512 global $wgMinimalPasswordLength, $wgContLang;
515 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
517 if( $result === false )
520 // Password needs to be long enough, and can't be the same as the username
521 return strlen( $password ) >= $wgMinimalPasswordLength
522 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
526 * Does a string look like an email address?
528 * There used to be a regular expression here, it got removed because it
529 * rejected valid addresses. Actually just check if there is '@' somewhere
530 * in the given address.
532 * @todo Check for RFC 2822 compilance (bug 959)
534 * @param string $addr email address
537 public static function isValidEmailAddr( $addr ) {
539 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
543 return strpos( $addr, '@' ) !== false;
547 * Given unvalidated user input, return a canonical username, or false if
548 * the username is invalid.
549 * @param string $name
550 * @param mixed $validate Type of validation to use:
551 * false No validation
552 * 'valid' Valid for batch processes
553 * 'usable' Valid for batch processes and login
554 * 'creatable' Valid for batch processes, login and account creation
556 static function getCanonicalName( $name, $validate = 'valid' ) {
557 # Force usernames to capital
559 $name = $wgContLang->ucfirst( $name );
561 # Reject names containing '#'; these will be cleaned up
562 # with title normalisation, but then it's too late to
564 if( strpos( $name, '#' ) !== false )
567 # Clean up name according to title rules
568 $t = Title
::newFromText( $name );
569 if( is_null( $t ) ) {
573 # Reject various classes of invalid names
574 $name = $t->getText();
576 $name = $wgAuth->getCanonicalName( $t->getText() );
578 switch ( $validate ) {
582 if ( !User
::isValidUserName( $name ) ) {
587 if ( !User
::isUsableName( $name ) ) {
592 if ( !User
::isCreatableName( $name ) ) {
597 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
603 * Count the number of edits of a user
605 * It should not be static and some day should be merged as proper member function / deprecated -- domas
607 * @param int $uid The user ID to check
611 static function edits( $uid ) {
612 wfProfileIn( __METHOD__
);
613 $dbr = wfGetDB( DB_SLAVE
);
614 // check if the user_editcount field has been initialized
615 $field = $dbr->selectField(
616 'user', 'user_editcount',
617 array( 'user_id' => $uid ),
621 if( $field === null ) { // it has not been initialized. do so.
622 $dbw = wfGetDB( DB_MASTER
);
623 $count = $dbr->selectField(
624 'revision', 'count(*)',
625 array( 'rev_user' => $uid ),
630 array( 'user_editcount' => $count ),
631 array( 'user_id' => $uid ),
637 wfProfileOut( __METHOD__
);
642 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
643 * @todo hash random numbers to improve security, like generateToken()
648 static function randomPassword() {
649 global $wgMinimalPasswordLength;
650 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
651 $l = strlen( $pwchars ) - 1;
653 $pwlength = max( 7, $wgMinimalPasswordLength );
654 $digit = mt_rand(0, $pwlength - 1);
656 for ( $i = 0; $i < $pwlength; $i++
) {
657 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
663 * Set cached properties to default. Note: this no longer clears
664 * uncached lazy-initialised properties. The constructor does that instead.
668 function loadDefaults( $name = false ) {
669 wfProfileIn( __METHOD__
);
671 global $wgCookiePrefix;
674 $this->mName
= $name;
675 $this->mRealName
= '';
676 $this->mPassword
= $this->mNewpassword
= '';
677 $this->mNewpassTime
= null;
679 $this->mOptions
= null; # Defer init
681 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
682 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
684 $this->mTouched
= '0'; # Allow any pages to be cached
687 $this->setToken(); # Random
688 $this->mEmailAuthenticated
= null;
689 $this->mEmailToken
= '';
690 $this->mEmailTokenExpires
= null;
691 $this->mRegistration
= wfTimestamp( TS_MW
);
692 $this->mGroups
= array();
694 wfProfileOut( __METHOD__
);
698 * Initialise php session
699 * @deprecated use wfSetupSession()
701 function SetupSession() {
706 * Load user data from the session or login cookie. If there are no valid
707 * credentials, initialises the user as an anon.
708 * @return true if the user is logged in, false otherwise
710 private function loadFromSession() {
711 global $wgMemc, $wgCookiePrefix;
713 if ( isset( $_SESSION['wsUserID'] ) ) {
714 if ( 0 != $_SESSION['wsUserID'] ) {
715 $sId = $_SESSION['wsUserID'];
717 $this->loadDefaults();
720 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
721 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
722 $_SESSION['wsUserID'] = $sId;
724 $this->loadDefaults();
727 if ( isset( $_SESSION['wsUserName'] ) ) {
728 $sName = $_SESSION['wsUserName'];
729 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
730 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
731 $_SESSION['wsUserName'] = $sName;
733 $this->loadDefaults();
737 $passwordCorrect = FALSE;
739 if ( !$this->loadFromId() ) {
740 # Not a valid ID, loadFromId has switched the object to anon for us
744 if ( isset( $_SESSION['wsToken'] ) ) {
745 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
747 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
748 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
751 # No session or persistent login cookie
752 $this->loadDefaults();
756 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
757 $_SESSION['wsToken'] = $this->mToken
;
758 wfDebug( "Logged in from $from\n" );
761 # Invalid credentials
762 wfDebug( "Can't log in from $from, invalid credentials\n" );
763 $this->loadDefaults();
769 * Load user and user_group data from the database
770 * $this->mId must be set, this is how the user is identified.
772 * @return true if the user exists, false if the user is anonymous
775 function loadFromDatabase() {
777 $this->mId
= intval( $this->mId
);
779 /** Anonymous user */
781 $this->loadDefaults();
785 $dbr = wfGetDB( DB_MASTER
);
786 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
788 if ( $s !== false ) {
789 # Initialise user table data
790 $this->mName
= $s->user_name
;
791 $this->mRealName
= $s->user_real_name
;
792 $this->mPassword
= $s->user_password
;
793 $this->mNewpassword
= $s->user_newpassword
;
794 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $s->user_newpass_time
);
795 $this->mEmail
= $s->user_email
;
796 $this->decodeOptions( $s->user_options
);
797 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
798 $this->mToken
= $s->user_token
;
799 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
800 $this->mEmailToken
= $s->user_email_token
;
801 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $s->user_email_token_expires
);
802 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $s->user_registration
);
803 $this->mEditCount
= $s->user_editcount
;
804 $this->getEditCount(); // revalidation for nulls
807 $res = $dbr->select( 'user_groups',
809 array( 'ug_user' => $this->mId
),
811 $this->mGroups
= array();
812 while( $row = $dbr->fetchObject( $res ) ) {
813 $this->mGroups
[] = $row->ug_group
;
819 $this->loadDefaults();
825 * Clear various cached data stored in this object.
826 * @param string $reloadFrom Reload user and user_groups table data from a
827 * given source. May be "name", "id", "defaults", "session" or false for
830 function clearInstanceCache( $reloadFrom = false ) {
831 $this->mNewtalk
= -1;
832 $this->mDatePreference
= null;
833 $this->mBlockedby
= -1; # Unset
834 $this->mHash
= false;
836 $this->mRights
= null;
837 $this->mEffectiveGroups
= null;
840 $this->mDataLoaded
= false;
841 $this->mFrom
= $reloadFrom;
846 * Combine the language default options with any site-specific options
847 * and add the default language variants.
848 * Not really private cause it's called by Language class
853 static function getDefaultOptions() {
854 global $wgNamespacesToBeSearchedDefault;
856 * Site defaults will override the global/language defaults
858 global $wgDefaultUserOptions, $wgContLang;
859 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
862 * default language setting
864 $variant = $wgContLang->getPreferredVariant( false );
865 $defOpt['variant'] = $variant;
866 $defOpt['language'] = $variant;
868 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
869 $defOpt['searchNs'.$nsnum] = $val;
875 * Get a given default option value.
882 function getDefaultOption( $opt ) {
883 $defOpts = User
::getDefaultOptions();
884 if( isset( $defOpts[$opt] ) ) {
885 return $defOpts[$opt];
892 * Get a list of user toggle names
895 static function getToggles() {
897 $extraToggles = array();
898 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
899 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
904 * Get blocking information
906 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
907 * non-critical checks are done against slaves. Check when actually saving should be done against
910 function getBlockedStatus( $bFromSlave = true ) {
911 global $wgEnableSorbs, $wgProxyWhitelist;
913 if ( -1 != $this->mBlockedby
) {
914 wfDebug( "User::getBlockedStatus: already loaded.\n" );
918 wfProfileIn( __METHOD__
);
919 wfDebug( __METHOD__
.": checking...\n" );
921 $this->mBlockedby
= 0;
922 $this->mHideName
= 0;
925 if ($this->isAllowed( 'ipblock-exempt' ) ) {
926 # Exempt from all types of IP-block
931 $this->mBlock
= new Block();
932 $this->mBlock
->fromMaster( !$bFromSlave );
933 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
934 wfDebug( __METHOD__
.": Found block.\n" );
935 $this->mBlockedby
= $this->mBlock
->mBy
;
936 $this->mBlockreason
= $this->mBlock
->mReason
;
937 $this->mHideName
= $this->mBlock
->mHideName
;
938 if ( $this->isLoggedIn() ) {
939 $this->spreadBlock();
942 $this->mBlock
= null;
943 wfDebug( __METHOD__
.": No block.\n" );
947 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
950 if ( wfIsLocallyBlockedProxy( $ip ) ) {
951 $this->mBlockedby
= wfMsg( 'proxyblocker' );
952 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
956 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
957 if ( $this->inSorbsBlacklist( $ip ) ) {
958 $this->mBlockedby
= wfMsg( 'sorbs' );
959 $this->mBlockreason
= wfMsg( 'sorbsreason' );
965 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
967 wfProfileOut( __METHOD__
);
970 function inSorbsBlacklist( $ip ) {
971 global $wgEnableSorbs, $wgSorbsUrl;
973 return $wgEnableSorbs &&
974 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
977 function inDnsBlacklist( $ip, $base ) {
978 wfProfileIn( __METHOD__
);
984 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
986 for ( $i=4; $i>=1; $i-- ) {
987 $host .= $m[$i] . '.';
992 $ipList = gethostbynamel( $host );
995 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
998 wfDebug( "Requested $host, not found in $base.\n" );
1002 wfProfileOut( __METHOD__
);
1007 * Is this user subject to rate limiting?
1011 public function isPingLimitable() {
1012 global $wgRateLimitsExcludedGroups;
1013 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
1017 * Primitive rate limits: enforce maximum actions per time period
1018 * to put a brake on flooding.
1020 * Note: when using a shared cache like memcached, IP-address
1021 * last-hit counters will be shared across wikis.
1023 * @return bool true if a rate limiter was tripped
1026 function pingLimiter( $action='edit' ) {
1028 # Call the 'PingLimiter' hook
1030 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1034 global $wgRateLimits;
1035 if( !isset( $wgRateLimits[$action] ) ) {
1039 # Some groups shouldn't trigger the ping limiter, ever
1040 if( !$this->isPingLimitable() )
1043 global $wgMemc, $wgRateLimitLog;
1044 wfProfileIn( __METHOD__
);
1046 $limits = $wgRateLimits[$action];
1048 $id = $this->getId();
1051 if( isset( $limits['anon'] ) && $id == 0 ) {
1052 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1055 if( isset( $limits['user'] ) && $id != 0 ) {
1056 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
1058 if( $this->isNewbie() ) {
1059 if( isset( $limits['newbie'] ) && $id != 0 ) {
1060 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1062 if( isset( $limits['ip'] ) ) {
1063 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1066 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1067 $subnet = $matches[1];
1068 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1073 foreach( $keys as $key => $limit ) {
1074 list( $max, $period ) = $limit;
1075 $summary = "(limit $max in {$period}s)";
1076 $count = $wgMemc->get( $key );
1078 if( $count > $max ) {
1079 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1080 if( $wgRateLimitLog ) {
1081 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1085 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1088 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1089 $wgMemc->add( $key, 1, intval( $period ) );
1091 $wgMemc->incr( $key );
1094 wfProfileOut( __METHOD__
);
1099 * Check if user is blocked
1100 * @return bool True if blocked, false otherwise
1102 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1103 wfDebug( "User::isBlocked: enter\n" );
1104 $this->getBlockedStatus( $bFromSlave );
1105 return $this->mBlockedby
!== 0;
1109 * Check if user is blocked from editing a particular article
1111 function isBlockedFrom( $title, $bFromSlave = false ) {
1112 global $wgBlockAllowsUTEdit;
1113 wfProfileIn( __METHOD__
);
1114 wfDebug( __METHOD__
.": enter\n" );
1116 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1117 $blocked = $this->isBlocked( $bFromSlave );
1118 # If a user's name is suppressed, they cannot make edits anywhere
1119 if ( !$this->mHideName
&& $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1120 $title->getNamespace() == NS_USER_TALK
) {
1122 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1124 wfProfileOut( __METHOD__
);
1129 * Get name of blocker
1130 * @return string name of blocker
1132 function blockedBy() {
1133 $this->getBlockedStatus();
1134 return $this->mBlockedby
;
1138 * Get blocking reason
1139 * @return string Blocking reason
1141 function blockedFor() {
1142 $this->getBlockedStatus();
1143 return $this->mBlockreason
;
1147 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1150 if( $this->mId
=== null and $this->mName
!== null
1151 and User
::isIP( $this->mName
) ) {
1152 // Special case, we know the user is anonymous
1154 } elseif( $this->mId
=== null ) {
1155 // Don't load if this was initialized from an ID
1162 * Set the user and reload all fields according to that ID
1163 * @deprecated use User::newFromId()
1165 function setID( $v ) {
1167 $this->clearInstanceCache( 'id' );
1171 * Get the user name, or the IP for anons
1173 function getName() {
1174 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1175 # Special case optimisation
1176 return $this->mName
;
1179 if ( $this->mName
=== false ) {
1181 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1183 return $this->mName
;
1188 * Set the user name.
1190 * This does not reload fields from the database according to the given
1191 * name. Rather, it is used to create a temporary "nonexistent user" for
1192 * later addition to the database. It can also be used to set the IP
1193 * address for an anonymous user to something other than the current
1196 * User::newFromName() has rougly the same function, when the named user
1199 function setName( $str ) {
1201 $this->mName
= $str;
1205 * Return the title dbkey form of the name, for eg user pages.
1209 function getTitleKey() {
1210 return str_replace( ' ', '_', $this->getName() );
1213 function getNewtalk() {
1216 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1217 if( $this->mNewtalk
=== -1 ) {
1218 $this->mNewtalk
= false; # reset talk page status
1220 # Check memcached separately for anons, who have no
1221 # entire User object stored in there.
1224 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1225 $newtalk = $wgMemc->get( $key );
1226 if( strval( $newtalk ) !== '' ) {
1227 $this->mNewtalk
= (bool)$newtalk;
1229 // Since we are caching this, make sure it is up to date by getting it
1231 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1232 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1235 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1239 return (bool)$this->mNewtalk
;
1243 * Return the talk page(s) this user has new messages on.
1245 function getNewMessageLinks() {
1247 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1250 if (!$this->getNewtalk())
1252 $up = $this->getUserPage();
1253 $utp = $up->getTalkPage();
1254 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1259 * Perform a user_newtalk check, uncached.
1260 * Use getNewtalk for a cached check.
1262 * @param string $field
1264 * @param bool $fromMaster True to fetch from the master, false for a slave
1268 function checkNewtalk( $field, $id, $fromMaster = false ) {
1269 if ( $fromMaster ) {
1270 $db = wfGetDB( DB_MASTER
);
1272 $db = wfGetDB( DB_SLAVE
);
1274 $ok = $db->selectField( 'user_newtalk', $field,
1275 array( $field => $id ), __METHOD__
);
1276 return $ok !== false;
1281 * @param string $field
1285 function updateNewtalk( $field, $id ) {
1286 $dbw = wfGetDB( DB_MASTER
);
1287 $dbw->insert( 'user_newtalk',
1288 array( $field => $id ),
1291 if ( $dbw->affectedRows() ) {
1292 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1295 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1301 * Clear the new messages flag for the given user
1302 * @param string $field
1306 function deleteNewtalk( $field, $id ) {
1307 $dbw = wfGetDB( DB_MASTER
);
1308 $dbw->delete( 'user_newtalk',
1309 array( $field => $id ),
1311 if ( $dbw->affectedRows() ) {
1312 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1315 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1321 * Update the 'You have new messages!' status.
1324 function setNewtalk( $val ) {
1325 if( wfReadOnly() ) {
1330 $this->mNewtalk
= $val;
1332 if( $this->isAnon() ) {
1334 $id = $this->getName();
1337 $id = $this->getId();
1342 $changed = $this->updateNewtalk( $field, $id );
1344 $changed = $this->deleteNewtalk( $field, $id );
1347 if( $this->isAnon() ) {
1348 // Anons have a separate memcached space, since
1349 // user records aren't kept for them.
1350 $key = wfMemcKey( 'newtalk', 'ip', $id );
1351 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1354 $this->invalidateCache();
1359 * Generate a current or new-future timestamp to be stored in the
1360 * user_touched field when we update things.
1362 private static function newTouchedTimestamp() {
1363 global $wgClockSkewFudge;
1364 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1368 * Clear user data from memcached.
1369 * Use after applying fun updates to the database; caller's
1370 * responsibility to update user_touched if appropriate.
1372 * Called implicitly from invalidateCache() and saveSettings().
1374 private function clearSharedCache() {
1377 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1382 * Immediately touch the user data cache for this account.
1383 * Updates user_touched field, and removes account data from memcached
1384 * for reload on the next hit.
1386 function invalidateCache() {
1389 $this->mTouched
= self
::newTouchedTimestamp();
1391 $dbw = wfGetDB( DB_MASTER
);
1392 $dbw->update( 'user',
1393 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1394 array( 'user_id' => $this->mId
),
1397 $this->clearSharedCache();
1401 function validateCache( $timestamp ) {
1403 return ($timestamp >= $this->mTouched
);
1407 * Encrypt a password.
1408 * It can eventually salt a password.
1409 * @see User::addSalt()
1410 * @param string $p clear Password.
1411 * @return string Encrypted password.
1413 function encryptPassword( $p ) {
1415 return wfEncryptPassword( $this->mId
, $p );
1419 * Set the password and reset the random token
1420 * Calls through to authentication plugin if necessary;
1421 * will have no effect if the auth plugin refuses to
1422 * pass the change through or if the legal password
1425 * As a special case, setting the password to null
1426 * wipes it, so the account cannot be logged in until
1427 * a new password is set, for instance via e-mail.
1429 * @param string $str
1430 * @throws PasswordError on failure
1432 function setPassword( $str ) {
1435 if( $str !== null ) {
1436 if( !$wgAuth->allowPasswordChange() ) {
1437 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1440 if( !$this->isValidPassword( $str ) ) {
1441 global $wgMinimalPasswordLength;
1442 throw new PasswordError( wfMsg( 'passwordtooshort',
1443 $wgMinimalPasswordLength ) );
1447 if( !$wgAuth->setPassword( $this, $str ) ) {
1448 throw new PasswordError( wfMsg( 'externaldberror' ) );
1451 $this->setInternalPassword( $str );
1457 * Set the password and reset the random token no matter
1460 * @param string $str
1462 function setInternalPassword( $str ) {
1466 if( $str === null ) {
1467 // Save an invalid hash...
1468 $this->mPassword
= '';
1470 $this->mPassword
= $this->encryptPassword( $str );
1472 $this->mNewpassword
= '';
1473 $this->mNewpassTime
= null;
1476 * Set the random token (used for persistent authentication)
1477 * Called from loadDefaults() among other places.
1480 function setToken( $token = false ) {
1481 global $wgSecretKey, $wgProxyKey;
1484 if ( $wgSecretKey ) {
1485 $key = $wgSecretKey;
1486 } elseif ( $wgProxyKey ) {
1491 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1493 $this->mToken
= $token;
1497 function setCookiePassword( $str ) {
1499 $this->mCookiePassword
= md5( $str );
1503 * Set the password for a password reminder or new account email
1504 * Sets the user_newpass_time field if $throttle is true
1506 function setNewpassword( $str, $throttle = true ) {
1508 $this->mNewpassword
= $this->encryptPassword( $str );
1510 $this->mNewpassTime
= wfTimestampNow();
1515 * Returns true if a password reminder email has already been sent within
1516 * the last $wgPasswordReminderResendTime hours
1518 function isPasswordReminderThrottled() {
1519 global $wgPasswordReminderResendTime;
1521 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1524 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1525 return time() < $expiry;
1528 function getEmail() {
1530 return $this->mEmail
;
1533 function getEmailAuthenticationTimestamp() {
1535 return $this->mEmailAuthenticated
;
1538 function setEmail( $str ) {
1540 $this->mEmail
= $str;
1543 function getRealName() {
1545 return $this->mRealName
;
1548 function setRealName( $str ) {
1550 $this->mRealName
= $str;
1554 * @param string $oname The option to check
1555 * @param string $defaultOverride A default value returned if the option does not exist
1558 function getOption( $oname, $defaultOverride = '' ) {
1561 if ( is_null( $this->mOptions
) ) {
1562 if($defaultOverride != '') {
1563 return $defaultOverride;
1565 $this->mOptions
= User
::getDefaultOptions();
1568 if ( array_key_exists( $oname, $this->mOptions
) ) {
1569 return trim( $this->mOptions
[$oname] );
1571 return $defaultOverride;
1576 * Get the user's date preference, including some important migration for
1579 function getDatePreference() {
1580 if ( is_null( $this->mDatePreference
) ) {
1582 $value = $this->getOption( 'date' );
1583 $map = $wgLang->getDatePreferenceMigrationMap();
1584 if ( isset( $map[$value] ) ) {
1585 $value = $map[$value];
1587 $this->mDatePreference
= $value;
1589 return $this->mDatePreference
;
1593 * @param string $oname The option to check
1594 * @return bool False if the option is not selected, true if it is
1596 function getBoolOption( $oname ) {
1597 return (bool)$this->getOption( $oname );
1601 * Get an option as an integer value from the source string.
1602 * @param string $oname The option to check
1603 * @param int $default Optional value to return if option is unset/blank.
1606 function getIntOption( $oname, $default=0 ) {
1607 $val = $this->getOption( $oname );
1611 return intval( $val );
1614 function setOption( $oname, $val ) {
1616 if ( is_null( $this->mOptions
) ) {
1617 $this->mOptions
= User
::getDefaultOptions();
1619 if ( $oname == 'skin' ) {
1620 # Clear cached skin, so the new one displays immediately in Special:Preferences
1621 unset( $this->mSkin
);
1623 // Filter out any newlines that may have passed through input validation.
1624 // Newlines are used to separate items in the options blob.
1625 $val = str_replace( "\r\n", "\n", $val );
1626 $val = str_replace( "\r", "\n", $val );
1627 $val = str_replace( "\n", " ", $val );
1628 $this->mOptions
[$oname] = $val;
1631 function getRights() {
1632 if ( is_null( $this->mRights
) ) {
1633 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1634 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1636 return $this->mRights
;
1640 * Get the list of explicit group memberships this user has.
1641 * The implicit * and user groups are not included.
1642 * @return array of strings
1644 function getGroups() {
1646 return $this->mGroups
;
1650 * Get the list of implicit group memberships this user has.
1651 * This includes all explicit groups, plus 'user' if logged in,
1652 * '*' for all accounts and autopromoted groups
1653 * @param boolean $recache Don't use the cache
1654 * @return array of strings
1656 function getEffectiveGroups( $recache = false ) {
1657 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1659 $this->mEffectiveGroups
= $this->mGroups
;
1660 $this->mEffectiveGroups
[] = '*';
1662 $this->mEffectiveGroups
[] = 'user';
1664 $this->mEffectiveGroups
= array_unique( array_merge(
1665 $this->mEffectiveGroups
,
1666 Autopromote
::getAutopromoteGroups( $this )
1669 # Hook for additional groups
1670 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1673 return $this->mEffectiveGroups
;
1676 /* Return the edit count for the user. This is where User::edits should have been */
1677 function getEditCount() {
1679 if ( !isset( $this->mEditCount
) ) {
1680 /* Populate the count, if it has not been populated yet */
1681 $this->mEditCount
= User
::edits($this->mId
);
1683 return $this->mEditCount
;
1691 * Add the user to the given group.
1692 * This takes immediate effect.
1693 * @param string $group
1695 function addGroup( $group ) {
1697 $dbw = wfGetDB( DB_MASTER
);
1698 if( $this->getId() ) {
1699 $dbw->insert( 'user_groups',
1701 'ug_user' => $this->getID(),
1702 'ug_group' => $group,
1705 array( 'IGNORE' ) );
1708 $this->mGroups
[] = $group;
1709 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1711 $this->invalidateCache();
1715 * Remove the user from the given group.
1716 * This takes immediate effect.
1717 * @param string $group
1719 function removeGroup( $group ) {
1721 $dbw = wfGetDB( DB_MASTER
);
1722 $dbw->delete( 'user_groups',
1724 'ug_user' => $this->getID(),
1725 'ug_group' => $group,
1727 'User::removeGroup' );
1729 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1730 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1732 $this->invalidateCache();
1737 * A more legible check for non-anonymousness.
1738 * Returns true if the user is not an anonymous visitor.
1742 function isLoggedIn() {
1743 return $this->getID() != 0;
1747 * A more legible check for anonymousness.
1748 * Returns true if the user is an anonymous visitor.
1753 return !$this->isLoggedIn();
1757 * Whether the user is a bot
1761 return $this->isAllowed( 'bot' );
1765 * Check if user is allowed to access a feature / make an action
1766 * @param string $action Action to be checked
1767 * @return boolean True: action is allowed, False: action should not be allowed
1769 function isAllowed($action='') {
1770 if ( $action === '' )
1771 // In the spirit of DWIM
1774 return in_array( $action, $this->getRights() );
1778 * Load a skin if it doesn't exist or return it
1779 * @todo FIXME : need to check the old failback system [AV]
1781 function &getSkin() {
1783 if ( ! isset( $this->mSkin
) ) {
1784 wfProfileIn( __METHOD__
);
1787 $userSkin = $this->getOption( 'skin' );
1788 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1790 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1791 wfProfileOut( __METHOD__
);
1793 return $this->mSkin
;
1797 * @param string $title Article title to look at
1801 * Check watched status of an article
1802 * @return bool True if article is watched
1804 function isWatched( $title ) {
1805 $wl = WatchedItem
::fromUserTitle( $this, $title );
1806 return $wl->isWatched();
1812 function addWatch( $title ) {
1813 $wl = WatchedItem
::fromUserTitle( $this, $title );
1815 $this->invalidateCache();
1819 * Stop watching an article
1821 function removeWatch( $title ) {
1822 $wl = WatchedItem
::fromUserTitle( $this, $title );
1824 $this->invalidateCache();
1828 * Clear the user's notification timestamp for the given title.
1829 * If e-notif e-mails are on, they will receive notification mails on
1830 * the next change of the page if it's watched etc.
1832 function clearNotification( &$title ) {
1833 global $wgUser, $wgUseEnotif;
1835 # Do nothing if the database is locked to writes
1836 if( wfReadOnly() ) {
1840 if ($title->getNamespace() == NS_USER_TALK
&&
1841 $title->getText() == $this->getName() ) {
1842 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1844 $this->setNewtalk( false );
1847 if( !$wgUseEnotif ) {
1851 if( $this->isAnon() ) {
1852 // Nothing else to do...
1856 // Only update the timestamp if the page is being watched.
1857 // The query to find out if it is watched is cached both in memcached and per-invocation,
1858 // and when it does have to be executed, it can be on a slave
1859 // If this is the user's newtalk page, we always update the timestamp
1860 if ($title->getNamespace() == NS_USER_TALK
&&
1861 $title->getText() == $wgUser->getName())
1864 } elseif ( $this->getID() == $wgUser->getID() ) {
1865 $watched = $title->userIsWatching();
1870 // If the page is watched by the user (or may be watched), update the timestamp on any
1871 // any matching rows
1873 $dbw = wfGetDB( DB_MASTER
);
1874 $dbw->update( 'watchlist',
1876 'wl_notificationtimestamp' => NULL
1877 ), array( /* WHERE */
1878 'wl_title' => $title->getDBkey(),
1879 'wl_namespace' => $title->getNamespace(),
1880 'wl_user' => $this->getID()
1881 ), 'User::clearLastVisited'
1889 * Resets all of the given user's page-change notification timestamps.
1890 * If e-notif e-mails are on, they will receive notification mails on
1891 * the next change of any watched page.
1893 * @param int $currentUser user ID number
1896 function clearAllNotifications( $currentUser ) {
1897 global $wgUseEnotif;
1898 if ( !$wgUseEnotif ) {
1899 $this->setNewtalk( false );
1902 if( $currentUser != 0 ) {
1904 $dbw = wfGetDB( DB_MASTER
);
1905 $dbw->update( 'watchlist',
1907 'wl_notificationtimestamp' => NULL
1908 ), array( /* WHERE */
1909 'wl_user' => $currentUser
1913 # we also need to clear here the "you have new message" notification for the own user_talk page
1914 # This is cleared one page view later in Article::viewUpdates();
1920 * @return string Encoding options
1922 function encodeOptions() {
1924 if ( is_null( $this->mOptions
) ) {
1925 $this->mOptions
= User
::getDefaultOptions();
1928 foreach ( $this->mOptions
as $oname => $oval ) {
1929 array_push( $a, $oname.'='.$oval );
1931 $s = implode( "\n", $a );
1938 function decodeOptions( $str ) {
1939 $this->mOptions
= array();
1940 $a = explode( "\n", $str );
1941 foreach ( $a as $s ) {
1943 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1944 $this->mOptions
[$m[1]] = $m[2];
1949 function setCookies() {
1950 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1952 if ( 0 == $this->mId
) return;
1953 $exp = time() +
$wgCookieExpiration;
1955 $_SESSION['wsUserID'] = $this->mId
;
1956 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1958 $_SESSION['wsUserName'] = $this->getName();
1959 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1961 $_SESSION['wsToken'] = $this->mToken
;
1962 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1963 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1965 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1974 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
1976 wfRunHooks( 'UserLogoutComplete', array(&$wgUser) );
1981 * Really logout user
1982 * Clears the cookies and session, resets the instance cache
1984 function doLogout() {
1985 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1986 $this->clearInstanceCache( 'defaults' );
1988 $_SESSION['wsUserID'] = 0;
1990 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1991 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1993 # Remember when user logged out, to prevent seeing cached pages
1994 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1998 * Save object settings into database
1999 * @todo Only rarely do all these fields need to be set!
2001 function saveSettings() {
2003 if ( wfReadOnly() ) { return; }
2004 if ( 0 == $this->mId
) { return; }
2006 $this->mTouched
= self
::newTouchedTimestamp();
2008 $dbw = wfGetDB( DB_MASTER
);
2009 $dbw->update( 'user',
2011 'user_name' => $this->mName
,
2012 'user_password' => $this->mPassword
,
2013 'user_newpassword' => $this->mNewpassword
,
2014 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2015 'user_real_name' => $this->mRealName
,
2016 'user_email' => $this->mEmail
,
2017 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2018 'user_options' => $this->encodeOptions(),
2019 'user_touched' => $dbw->timestamp($this->mTouched
),
2020 'user_token' => $this->mToken
2021 ), array( /* WHERE */
2022 'user_id' => $this->mId
2025 $this->clearSharedCache();
2030 * Checks if a user with the given name exists, returns the ID.
2032 function idForName() {
2033 $s = trim( $this->getName() );
2034 if ( $s === '' ) return 0;
2036 $dbr = wfGetDB( DB_SLAVE
);
2037 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2038 if ( $id === false ) {
2045 * Add a user to the database, return the user object
2047 * @param string $name The user's name
2048 * @param array $params Associative array of non-default parameters to save to the database:
2049 * password The user's password. Password logins will be disabled if this is omitted.
2050 * newpassword A temporary password mailed to the user
2051 * email The user's email address
2052 * email_authenticated The email authentication timestamp
2053 * real_name The user's real name
2054 * options An associative array of non-default options
2055 * token Random authentication token. Do not set.
2056 * registration Registration timestamp. Do not set.
2058 * @return User object, or null if the username already exists
2060 static function createNew( $name, $params = array() ) {
2063 if ( isset( $params['options'] ) ) {
2064 $user->mOptions
= $params['options'] +
$user->mOptions
;
2065 unset( $params['options'] );
2067 $dbw = wfGetDB( DB_MASTER
);
2068 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2070 'user_id' => $seqVal,
2071 'user_name' => $name,
2072 'user_password' => $user->mPassword
,
2073 'user_newpassword' => $user->mNewpassword
,
2074 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2075 'user_email' => $user->mEmail
,
2076 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2077 'user_real_name' => $user->mRealName
,
2078 'user_options' => $user->encodeOptions(),
2079 'user_token' => $user->mToken
,
2080 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2081 'user_editcount' => 0,
2083 foreach ( $params as $name => $value ) {
2084 $fields["user_$name"] = $value;
2086 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2087 if ( $dbw->affectedRows() ) {
2088 $newUser = User
::newFromId( $dbw->insertId() );
2096 * Add an existing user object to the database
2098 function addToDatabase() {
2100 $dbw = wfGetDB( DB_MASTER
);
2101 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2102 $dbw->insert( 'user',
2104 'user_id' => $seqVal,
2105 'user_name' => $this->mName
,
2106 'user_password' => $this->mPassword
,
2107 'user_newpassword' => $this->mNewpassword
,
2108 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2109 'user_email' => $this->mEmail
,
2110 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2111 'user_real_name' => $this->mRealName
,
2112 'user_options' => $this->encodeOptions(),
2113 'user_token' => $this->mToken
,
2114 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2115 'user_editcount' => 0,
2118 $this->mId
= $dbw->insertId();
2120 # Clear instance cache other than user table data, which is already accurate
2121 $this->clearInstanceCache();
2125 * If the (non-anonymous) user is blocked, this function will block any IP address
2126 * that they successfully log on from.
2128 function spreadBlock() {
2129 wfDebug( __METHOD__
."()\n" );
2131 if ( $this->mId
== 0 ) {
2135 $userblock = Block
::newFromDB( '', $this->mId
);
2136 if ( !$userblock ) {
2140 $userblock->doAutoblock( wfGetIp() );
2145 * Generate a string which will be different for any combination of
2146 * user options which would produce different parser output.
2147 * This will be used as part of the hash key for the parser cache,
2148 * so users will the same options can share the same cached data
2151 * Extensions which require it should install 'PageRenderingHash' hook,
2152 * which will give them a chance to modify this key based on their own
2157 function getPageRenderingHash() {
2158 global $wgContLang, $wgUseDynamicDates, $wgLang;
2160 return $this->mHash
;
2163 // stubthreshold is only included below for completeness,
2164 // it will always be 0 when this function is called by parsercache.
2166 $confstr = $this->getOption( 'math' );
2167 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2168 if ( $wgUseDynamicDates ) {
2169 $confstr .= '!' . $this->getDatePreference();
2171 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2172 $confstr .= '!' . $wgLang->getCode();
2173 $confstr .= '!' . $this->getOption( 'thumbsize' );
2174 // add in language specific options, if any
2175 $extra = $wgContLang->getExtraHashOptions();
2178 // Give a chance for extensions to modify the hash, if they have
2179 // extra options or other effects on the parser cache.
2180 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2182 // Make it a valid memcached key fragment
2183 $confstr = str_replace( ' ', '_', $confstr );
2184 $this->mHash
= $confstr;
2188 function isBlockedFromCreateAccount() {
2189 $this->getBlockedStatus();
2190 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2194 * Determine if the user is blocked from using Special:Emailuser.
2199 function isBlockedFromEmailuser() {
2200 $this->getBlockedStatus();
2201 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2204 function isAllowedToCreateAccount() {
2205 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2211 function setLoaded( $loaded ) {}
2214 * Get this user's personal page title.
2219 function getUserPage() {
2220 return Title
::makeTitle( NS_USER
, $this->getName() );
2224 * Get this user's talk page title.
2229 function getTalkPage() {
2230 $title = $this->getUserPage();
2231 return $title->getTalkPage();
2237 function getMaxID() {
2238 static $res; // cache
2240 if ( isset( $res ) )
2243 $dbr = wfGetDB( DB_SLAVE
);
2244 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2249 * Determine whether the user is a newbie. Newbies are either
2250 * anonymous IPs, or the most recently created accounts.
2251 * @return bool True if it is a newbie.
2253 function isNewbie() {
2254 return !$this->isAllowed( 'autoconfirmed' );
2258 * Check to see if the given clear-text password is one of the accepted passwords
2259 * @param string $password User password.
2260 * @return bool True if the given password is correct otherwise False.
2262 function checkPassword( $password ) {
2266 // Even though we stop people from creating passwords that
2267 // are shorter than this, doesn't mean people wont be able
2268 // to. Certain authentication plugins do NOT want to save
2269 // domain passwords in a mysql database, so we should
2270 // check this (incase $wgAuth->strict() is false).
2271 if( !$this->isValidPassword( $password ) ) {
2275 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2277 } elseif( $wgAuth->strict() ) {
2278 /* Auth plugin doesn't allow local authentication */
2280 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2281 /* Auth plugin doesn't allow local authentication for this user name */
2284 $ep = $this->encryptPassword( $password );
2285 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2287 } elseif ( function_exists( 'iconv' ) ) {
2288 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2289 # Check for this with iconv
2290 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2291 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2299 * Check if the given clear-text password matches the temporary password
2300 * sent by e-mail for password reset operations.
2303 function checkTemporaryPassword( $plaintext ) {
2304 $hash = $this->encryptPassword( $plaintext );
2305 return $hash === $this->mNewpassword
;
2309 * Initialize (if necessary) and return a session token value
2310 * which can be used in edit forms to show that the user's
2311 * login credentials aren't being hijacked with a foreign form
2314 * @param mixed $salt - Optional function-specific data for hash.
2315 * Use a string or an array of strings.
2319 function editToken( $salt = '' ) {
2320 if ( $this->isAnon() ) {
2321 return EDIT_TOKEN_SUFFIX
;
2323 if( !isset( $_SESSION['wsEditToken'] ) ) {
2324 $token = $this->generateToken();
2325 $_SESSION['wsEditToken'] = $token;
2327 $token = $_SESSION['wsEditToken'];
2329 if( is_array( $salt ) ) {
2330 $salt = implode( '|', $salt );
2332 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2337 * Generate a hex-y looking random token for various uses.
2338 * Could be made more cryptographically sure if someone cares.
2341 function generateToken( $salt = '' ) {
2342 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2343 return md5( $token . $salt );
2347 * Check given value against the token value stored in the session.
2348 * A match should confirm that the form was submitted from the
2349 * user's own login session, not a form submission from a third-party
2352 * @param string $val - the input value to compare
2353 * @param string $salt - Optional function-specific data for hash
2357 function matchEditToken( $val, $salt = '' ) {
2358 $sessionToken = $this->editToken( $salt );
2359 if ( $val != $sessionToken ) {
2360 wfDebug( "User::matchEditToken: broken session data\n" );
2362 return $val == $sessionToken;
2366 * Check whether the edit token is fine except for the suffix
2368 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2369 $sessionToken = $this->editToken( $salt );
2370 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2374 * Generate a new e-mail confirmation token and send a confirmation
2375 * mail to the user's given address.
2377 * @return mixed True on success, a WikiError object on failure.
2379 function sendConfirmationMail() {
2381 $expiration = null; // gets passed-by-ref and defined in next line.
2382 $url = $this->confirmationTokenUrl( $expiration );
2383 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2384 wfMsg( 'confirmemail_body',
2388 $wgContLang->timeanddate( $expiration, false ) ) );
2392 * Send an e-mail to this user's account. Does not check for
2393 * confirmed status or validity.
2395 * @param string $subject
2396 * @param string $body
2397 * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
2398 * @return mixed True on success, a WikiError object on failure.
2400 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2401 if( is_null( $from ) ) {
2402 global $wgPasswordSender;
2403 $from = $wgPasswordSender;
2406 $to = new MailAddress( $this );
2407 $sender = new MailAddress( $from );
2408 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2412 * Generate, store, and return a new e-mail confirmation code.
2413 * A hash (unsalted since it's used as a key) is stored.
2414 * @param &$expiration mixed output: accepts the expiration time
2418 function confirmationToken( &$expiration ) {
2420 $expires = $now +
7 * 24 * 60 * 60;
2421 $expiration = wfTimestamp( TS_MW
, $expires );
2423 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2424 $hash = md5( $token );
2426 $dbw = wfGetDB( DB_MASTER
);
2427 $dbw->update( 'user',
2428 array( 'user_email_token' => $hash,
2429 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2430 array( 'user_id' => $this->mId
),
2437 * Generate and store a new e-mail confirmation token, and return
2438 * the URL the user can use to confirm.
2439 * @param &$expiration mixed output: accepts the expiration time
2443 function confirmationTokenUrl( &$expiration ) {
2444 $token = $this->confirmationToken( $expiration );
2445 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2446 return $title->getFullUrl();
2450 * Mark the e-mail address confirmed and save.
2452 function confirmEmail() {
2454 $this->mEmailAuthenticated
= wfTimestampNow();
2455 $this->saveSettings();
2460 * Is this user allowed to send e-mails within limits of current
2461 * site configuration?
2464 function canSendEmail() {
2465 $canSend = $this->isEmailConfirmed();
2466 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2471 * Is this user allowed to receive e-mails within limits of current
2472 * site configuration?
2475 function canReceiveEmail() {
2476 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2480 * Is this user's e-mail address valid-looking and confirmed within
2481 * limits of the current site configuration?
2483 * If $wgEmailAuthentication is on, this may require the user to have
2484 * confirmed their address by returning a code or using a password
2485 * sent to the address from the wiki.
2489 function isEmailConfirmed() {
2490 global $wgEmailAuthentication;
2493 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2494 if( $this->isAnon() )
2496 if( !self
::isValidEmailAddr( $this->mEmail
) )
2498 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2507 * Return true if there is an outstanding request for e-mail confirmation.
2510 function isEmailConfirmationPending() {
2511 global $wgEmailAuthentication;
2512 return $wgEmailAuthentication &&
2513 !$this->isEmailConfirmed() &&
2514 $this->mEmailToken
&&
2515 $this->mEmailTokenExpires
> wfTimestamp();
2519 * Get the timestamp of account creation, or false for
2520 * non-existent/anonymous user accounts
2524 public function getRegistration() {
2525 return $this->mId
> 0
2526 ?
$this->mRegistration
2531 * @param array $groups list of groups
2532 * @return array list of permission key names for given groups combined
2535 static function getGroupPermissions( $groups ) {
2536 global $wgGroupPermissions;
2538 foreach( $groups as $group ) {
2539 if( isset( $wgGroupPermissions[$group] ) ) {
2540 $rights = array_merge( $rights,
2541 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2548 * @param string $group key name
2549 * @return string localized descriptive name for group, if provided
2552 static function getGroupName( $group ) {
2553 global $wgMessageCache;
2554 $wgMessageCache->loadAllMessages();
2555 $key = "group-$group";
2556 $name = wfMsg( $key );
2557 return $name == '' ||
wfEmptyMsg( $key, $name )
2563 * @param string $group key name
2564 * @return string localized descriptive name for member of a group, if provided
2567 static function getGroupMember( $group ) {
2568 global $wgMessageCache;
2569 $wgMessageCache->loadAllMessages();
2570 $key = "group-$group-member";
2571 $name = wfMsg( $key );
2572 return $name == '' ||
wfEmptyMsg( $key, $name )
2578 * Return the set of defined explicit groups.
2579 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2580 * groups are not included, as they are defined
2581 * automatically, not in the database.
2585 static function getAllGroups() {
2586 global $wgGroupPermissions;
2588 array_keys( $wgGroupPermissions ),
2589 self
::getImplicitGroups()
2594 * Get a list of implicit groups
2598 public static function getImplicitGroups() {
2599 global $wgImplicitGroups;
2600 $groups = $wgImplicitGroups;
2601 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
2606 * Get the title of a page describing a particular group
2608 * @param $group Name of the group
2611 static function getGroupPage( $group ) {
2612 global $wgMessageCache;
2613 $wgMessageCache->loadAllMessages();
2614 $page = wfMsgForContent( 'grouppage-' . $group );
2615 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2616 $title = Title
::newFromText( $page );
2617 if( is_object( $title ) )
2624 * Create a link to the group in HTML, if available
2626 * @param $group Name of the group
2627 * @param $text The text of the link
2630 static function makeGroupLinkHTML( $group, $text = '' ) {
2632 $text = self
::getGroupName( $group );
2634 $title = self
::getGroupPage( $group );
2637 $sk = $wgUser->getSkin();
2638 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2645 * Create a link to the group in Wikitext, if available
2647 * @param $group Name of the group
2648 * @param $text The text of the link (by default, the name of the group)
2651 static function makeGroupLinkWiki( $group, $text = '' ) {
2653 $text = self
::getGroupName( $group );
2655 $title = self
::getGroupPage( $group );
2657 $page = $title->getPrefixedText();
2658 return "[[$page|$text]]";
2665 * Increment the user's edit-count field.
2666 * Will have no effect for anonymous users.
2668 function incEditCount() {
2669 if( !$this->isAnon() ) {
2670 $dbw = wfGetDB( DB_MASTER
);
2671 $dbw->update( 'user',
2672 array( 'user_editcount=user_editcount+1' ),
2673 array( 'user_id' => $this->getId() ),
2676 // Lazy initialization check...
2677 if( $dbw->affectedRows() == 0 ) {
2678 // Pull from a slave to be less cruel to servers
2679 // Accuracy isn't the point anyway here
2680 $dbr = wfGetDB( DB_SLAVE
);
2681 $count = $dbr->selectField( 'revision',
2683 array( 'rev_user' => $this->getId() ),
2686 // Now here's a goddamn hack...
2687 if( $dbr !== $dbw ) {
2688 // If we actually have a slave server, the count is
2689 // at least one behind because the current transaction
2690 // has not been committed and replicated.
2693 // But if DB_SLAVE is selecting the master, then the
2694 // count we just read includes the revision that was
2695 // just added in the working transaction.
2698 $dbw->update( 'user',
2699 array( 'user_editcount' => $count ),
2700 array( 'user_id' => $this->getId() ),
2704 // edit count in user cache too
2705 $this->invalidateCache();