7 # Number of characters in user_token field
8 define( 'USER_TOKEN_LENGTH', 32 );
10 # Serialized record version
11 define( 'MW_USER_VERSION', 6 );
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',
110 * Each of these should have a corresponding message of the form "right-$right"
112 static $mCoreRights = array(
152 static $mAllRights = false;
155 * The cache variable declarations
157 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
158 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
159 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
162 * Whether the cache variables have been loaded
167 * Initialisation data source if mDataLoaded==false. May be one of:
168 * defaults anonymous user initialised from class defaults
169 * name initialise from mName
170 * id initialise from mId
171 * session log in from cookies or session if possible
173 * Use the User::newFrom*() family of functions to set this.
178 * Lazy-initialised variables, invalidated with clearInstanceCache
180 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
181 $mBlockreason, $mBlock, $mEffectiveGroups;
184 * Lightweight constructor for anonymous user
185 * Use the User::newFrom* factory functions for other kinds of users
188 $this->clearInstanceCache( 'defaults' );
192 * Load the user table data for this object from the source given by mFrom
195 if ( $this->mDataLoaded
) {
198 wfProfileIn( __METHOD__
);
200 # Set it now to avoid infinite recursion in accessors
201 $this->mDataLoaded
= true;
203 switch ( $this->mFrom
) {
205 $this->loadDefaults();
208 $this->mId
= self
::idFromName( $this->mName
);
210 # Nonexistent user placeholder object
211 $this->loadDefaults( $this->mName
);
220 $this->loadFromSession();
223 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
225 wfProfileOut( __METHOD__
);
229 * Load user table data given mId
230 * @return false if the ID does not exist, true otherwise
233 function loadFromId() {
235 if ( $this->mId
== 0 ) {
236 $this->loadDefaults();
241 $key = wfMemcKey( 'user', 'id', $this->mId
);
242 $data = $wgMemc->get( $key );
243 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
244 # Object is expired, load from DB
249 wfDebug( "Cache miss for user {$this->mId}\n" );
251 if ( !$this->loadFromDatabase() ) {
252 # Can't load from ID, user is anonymous
255 $this->saveToCache();
257 wfDebug( "Got user {$this->mId} from cache\n" );
259 foreach ( self
::$mCacheVars as $name ) {
260 $this->$name = $data[$name];
267 * Save user data to the shared cache
269 function saveToCache() {
272 if ( $this->isAnon() ) {
273 // Anonymous users are uncached
277 foreach ( self
::$mCacheVars as $name ) {
278 $data[$name] = $this->$name;
280 $data['mVersion'] = MW_USER_VERSION
;
281 $key = wfMemcKey( 'user', 'id', $this->mId
);
283 $wgMemc->set( $key, $data );
287 * Static factory method for creation from username.
289 * This is slightly less efficient than newFromId(), so use newFromId() if
290 * you have both an ID and a name handy.
292 * @param string $name Username, validated by Title:newFromText()
293 * @param mixed $validate Validate username. Takes the same parameters as
294 * User::getCanonicalName(), except that true is accepted as an alias
295 * for 'valid', for BC.
297 * @return User object, or null if the username is invalid. If the username
298 * is not present in the database, the result will be a user object with
299 * a name, zero user ID and default settings.
302 static function newFromName( $name, $validate = 'valid' ) {
303 if ( $validate === true ) {
306 $name = self
::getCanonicalName( $name, $validate );
307 if ( $name === false ) {
310 # Create unloaded user object
318 static function newFromId( $id ) {
326 * Factory method to fetch whichever user has a given email confirmation code.
327 * This code is generated when an account is created or its e-mail address
330 * If the code is invalid or has expired, returns NULL.
332 * @param string $code
336 static function newFromConfirmationCode( $code ) {
337 $dbr = wfGetDB( DB_SLAVE
);
338 $id = $dbr->selectField( 'user', 'user_id', array(
339 'user_email_token' => md5( $code ),
340 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
342 if( $id !== false ) {
343 return User
::newFromId( $id );
350 * Create a new user object using data from session or cookies. If the
351 * login credentials are invalid, the result is an anonymous user.
356 static function newFromSession() {
358 $user->mFrom
= 'session';
363 * Create a new user object from a user row.
364 * The row should have all fields from the user table in it.
366 static function newFromRow( $row ) {
368 $user->loadFromRow( $row );
373 * Get username given an id.
374 * @param integer $id Database user id
375 * @return string Nickname of a user
378 static function whoIs( $id ) {
379 $dbr = wfGetDB( DB_SLAVE
);
380 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
384 * Get the real name of a user given their identifier
386 * @param int $id Database user id
387 * @return string Real name of a user
389 static function whoIsReal( $id ) {
390 $dbr = wfGetDB( DB_SLAVE
);
391 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
395 * Get database id given a user name
396 * @param string $name Nickname of a user
397 * @return integer|null Database user id (null: if non existent
400 static function idFromName( $name ) {
401 $nt = Title
::newFromText( $name );
402 if( is_null( $nt ) ) {
406 $dbr = wfGetDB( DB_SLAVE
);
407 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
409 if ( $s === false ) {
417 * Does the string match an anonymous IPv4 address?
419 * This function exists for username validation, in order to reject
420 * usernames which are similar in form to IP addresses. Strings such
421 * as 300.300.300.300 will return true because it looks like an IP
422 * address, despite not being strictly valid.
424 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
425 * address because the usemod software would "cloak" anonymous IP
426 * addresses like this, if we allowed accounts like this to be created
427 * new users could get the old edits of these anonymous users.
430 * @param string $name Nickname of a user
433 static function isIP( $name ) {
434 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User
::isIPv6($name);
435 /*return preg_match("/^
436 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
437 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
438 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
439 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
444 * Check if $name is an IPv6 IP.
446 static function isIPv6($name) {
448 * if it has any non-valid characters, it can't be a valid IPv6
451 if (preg_match("/[^:a-fA-F0-9]/", $name))
454 $parts = explode(":", $name);
455 if (count($parts) < 3)
457 foreach ($parts as $part) {
458 if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part))
465 * Is the input a valid username?
467 * Checks if the input is a valid username, we don't want an empty string,
468 * an IP address, anything that containins slashes (would mess up subpages),
469 * is longer than the maximum allowed username size or doesn't begin with
472 * @param string $name
476 static function isValidUserName( $name ) {
477 global $wgContLang, $wgMaxNameChars;
480 || User
::isIP( $name )
481 ||
strpos( $name, '/' ) !== false
482 ||
strlen( $name ) > $wgMaxNameChars
483 ||
$name != $wgContLang->ucfirst( $name ) ) {
484 wfDebugLog( 'username', __METHOD__
.
485 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
489 // Ensure that the name can't be misresolved as a different title,
490 // such as with extra namespace keys at the start.
491 $parsed = Title
::newFromText( $name );
492 if( is_null( $parsed )
493 ||
$parsed->getNamespace()
494 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
495 wfDebugLog( 'username', __METHOD__
.
496 ": '$name' invalid due to ambiguous prefixes" );
500 // Check an additional blacklist of troublemaker characters.
501 // Should these be merged into the title char list?
502 $unicodeBlacklist = '/[' .
503 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
504 '\x{00a0}' . # non-breaking space
505 '\x{2000}-\x{200f}' . # various whitespace
506 '\x{2028}-\x{202f}' . # breaks and control chars
507 '\x{3000}' . # ideographic space
508 '\x{e000}-\x{f8ff}' . # private use
510 if( preg_match( $unicodeBlacklist, $name ) ) {
511 wfDebugLog( 'username', __METHOD__
.
512 ": '$name' invalid due to blacklisted characters" );
520 * Usernames which fail to pass this function will be blocked
521 * from user login and new account registrations, but may be used
522 * internally by batch processes.
524 * If an account already exists in this form, login will be blocked
525 * by a failure to pass this function.
527 * @param string $name
530 static function isUsableName( $name ) {
531 global $wgReservedUsernames;
533 // Must be a valid username, obviously ;)
534 self
::isValidUserName( $name ) &&
536 // Certain names may be reserved for batch processes.
537 !in_array( $name, $wgReservedUsernames );
541 * Usernames which fail to pass this function will be blocked
542 * from new account registrations, but may be used internally
543 * either by batch processes or by user accounts which have
544 * already been created.
546 * Additional character blacklisting may be added here
547 * rather than in isValidUserName() to avoid disrupting
550 * @param string $name
553 static function isCreatableName( $name ) {
555 self
::isUsableName( $name ) &&
557 // Registration-time character blacklisting...
558 strpos( $name, '@' ) === false;
562 * Is the input a valid password for this user?
564 * @param string $password Desired password
567 function isValidPassword( $password ) {
568 global $wgMinimalPasswordLength, $wgContLang;
571 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
573 if( $result === false )
576 // Password needs to be long enough, and can't be the same as the username
577 return strlen( $password ) >= $wgMinimalPasswordLength
578 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
582 * Does a string look like an email address?
584 * There used to be a regular expression here, it got removed because it
585 * rejected valid addresses. Actually just check if there is '@' somewhere
586 * in the given address.
588 * @todo Check for RFC 2822 compilance (bug 959)
590 * @param string $addr email address
593 public static function isValidEmailAddr( $addr ) {
595 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
599 return strpos( $addr, '@' ) !== false;
603 * Given unvalidated user input, return a canonical username, or false if
604 * the username is invalid.
605 * @param string $name
606 * @param mixed $validate Type of validation to use:
607 * false No validation
608 * 'valid' Valid for batch processes
609 * 'usable' Valid for batch processes and login
610 * 'creatable' Valid for batch processes, login and account creation
612 static function getCanonicalName( $name, $validate = 'valid' ) {
613 # Force usernames to capital
615 $name = $wgContLang->ucfirst( $name );
617 # Reject names containing '#'; these will be cleaned up
618 # with title normalisation, but then it's too late to
620 if( strpos( $name, '#' ) !== false )
623 # Clean up name according to title rules
624 $t = Title
::newFromText( $name );
625 if( is_null( $t ) ) {
629 # Reject various classes of invalid names
630 $name = $t->getText();
632 $name = $wgAuth->getCanonicalName( $t->getText() );
634 switch ( $validate ) {
638 if ( !User
::isValidUserName( $name ) ) {
643 if ( !User
::isUsableName( $name ) ) {
648 if ( !User
::isCreatableName( $name ) ) {
653 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
659 * Count the number of edits of a user
661 * It should not be static and some day should be merged as proper member function / deprecated -- domas
663 * @param int $uid The user ID to check
667 static function edits( $uid ) {
668 wfProfileIn( __METHOD__
);
669 $dbr = wfGetDB( DB_SLAVE
);
670 // check if the user_editcount field has been initialized
671 $field = $dbr->selectField(
672 'user', 'user_editcount',
673 array( 'user_id' => $uid ),
677 if( $field === null ) { // it has not been initialized. do so.
678 $dbw = wfGetDB( DB_MASTER
);
679 $count = $dbr->selectField(
680 'revision', 'count(*)',
681 array( 'rev_user' => $uid ),
686 array( 'user_editcount' => $count ),
687 array( 'user_id' => $uid ),
693 wfProfileOut( __METHOD__
);
698 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
699 * @todo hash random numbers to improve security, like generateToken()
704 static function randomPassword() {
705 global $wgMinimalPasswordLength;
706 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
707 $l = strlen( $pwchars ) - 1;
709 $pwlength = max( 7, $wgMinimalPasswordLength );
710 $digit = mt_rand(0, $pwlength - 1);
712 for ( $i = 0; $i < $pwlength; $i++
) {
713 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
719 * Set cached properties to default. Note: this no longer clears
720 * uncached lazy-initialised properties. The constructor does that instead.
724 function loadDefaults( $name = false ) {
725 wfProfileIn( __METHOD__
);
727 global $wgCookiePrefix;
730 $this->mName
= $name;
731 $this->mRealName
= '';
732 $this->mPassword
= $this->mNewpassword
= '';
733 $this->mNewpassTime
= null;
735 $this->mOptions
= null; # Defer init
737 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
738 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
740 $this->mTouched
= '0'; # Allow any pages to be cached
743 $this->setToken(); # Random
744 $this->mEmailAuthenticated
= null;
745 $this->mEmailToken
= '';
746 $this->mEmailTokenExpires
= null;
747 $this->mRegistration
= wfTimestamp( TS_MW
);
748 $this->mGroups
= array();
750 wfProfileOut( __METHOD__
);
754 * Initialise php session
755 * @deprecated use wfSetupSession()
757 function SetupSession() {
758 wfDeprecated( __METHOD__
);
763 * Load user data from the session or login cookie. If there are no valid
764 * credentials, initialises the user as an anon.
765 * @return true if the user is logged in, false otherwise
767 private function loadFromSession() {
768 global $wgMemc, $wgCookiePrefix;
770 if ( isset( $_SESSION['wsUserID'] ) ) {
771 if ( 0 != $_SESSION['wsUserID'] ) {
772 $sId = $_SESSION['wsUserID'];
774 $this->loadDefaults();
777 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
778 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
779 $_SESSION['wsUserID'] = $sId;
781 $this->loadDefaults();
784 if ( isset( $_SESSION['wsUserName'] ) ) {
785 $sName = $_SESSION['wsUserName'];
786 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
787 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
788 $_SESSION['wsUserName'] = $sName;
790 $this->loadDefaults();
794 $passwordCorrect = FALSE;
796 if ( !$this->loadFromId() ) {
797 # Not a valid ID, loadFromId has switched the object to anon for us
801 if ( isset( $_SESSION['wsToken'] ) ) {
802 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
804 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
805 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
808 # No session or persistent login cookie
809 $this->loadDefaults();
813 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
814 $_SESSION['wsToken'] = $this->mToken
;
815 wfDebug( "Logged in from $from\n" );
818 # Invalid credentials
819 wfDebug( "Can't log in from $from, invalid credentials\n" );
820 $this->loadDefaults();
826 * Load user and user_group data from the database
827 * $this->mId must be set, this is how the user is identified.
829 * @return true if the user exists, false if the user is anonymous
832 function loadFromDatabase() {
834 $this->mId
= intval( $this->mId
);
836 /** Anonymous user */
838 $this->loadDefaults();
842 $dbr = wfGetDB( DB_MASTER
);
843 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
845 if ( $s !== false ) {
846 # Initialise user table data
847 $this->loadFromRow( $s );
848 $this->mGroups
= null; // deferred
849 $this->getEditCount(); // revalidation for nulls
854 $this->loadDefaults();
860 * Initialise the user object from a row from the user table
862 function loadFromRow( $row ) {
863 $this->mDataLoaded
= true;
865 if ( isset( $row->user_id
) ) {
866 $this->mId
= $row->user_id
;
868 $this->mName
= $row->user_name
;
869 $this->mRealName
= $row->user_real_name
;
870 $this->mPassword
= $row->user_password
;
871 $this->mNewpassword
= $row->user_newpassword
;
872 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
873 $this->mEmail
= $row->user_email
;
874 $this->decodeOptions( $row->user_options
);
875 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
876 $this->mToken
= $row->user_token
;
877 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
878 $this->mEmailToken
= $row->user_email_token
;
879 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
880 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
881 $this->mEditCount
= $row->user_editcount
;
885 * Load the groups from the database if they aren't already loaded
888 function loadGroups() {
889 if ( is_null( $this->mGroups
) ) {
890 $dbr = wfGetDB( DB_MASTER
);
891 $res = $dbr->select( 'user_groups',
893 array( 'ug_user' => $this->mId
),
895 $this->mGroups
= array();
896 while( $row = $dbr->fetchObject( $res ) ) {
897 $this->mGroups
[] = $row->ug_group
;
903 * Clear various cached data stored in this object.
904 * @param string $reloadFrom Reload user and user_groups table data from a
905 * given source. May be "name", "id", "defaults", "session" or false for
908 function clearInstanceCache( $reloadFrom = false ) {
909 $this->mNewtalk
= -1;
910 $this->mDatePreference
= null;
911 $this->mBlockedby
= -1; # Unset
912 $this->mHash
= false;
914 $this->mRights
= null;
915 $this->mEffectiveGroups
= null;
918 $this->mDataLoaded
= false;
919 $this->mFrom
= $reloadFrom;
924 * Combine the language default options with any site-specific options
925 * and add the default language variants.
926 * Not really private cause it's called by Language class
931 static function getDefaultOptions() {
932 global $wgNamespacesToBeSearchedDefault;
934 * Site defaults will override the global/language defaults
936 global $wgDefaultUserOptions, $wgContLang;
937 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
940 * default language setting
942 $variant = $wgContLang->getPreferredVariant( false );
943 $defOpt['variant'] = $variant;
944 $defOpt['language'] = $variant;
946 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
947 $defOpt['searchNs'.$nsnum] = $val;
953 * Get a given default option value.
960 function getDefaultOption( $opt ) {
961 $defOpts = User
::getDefaultOptions();
962 if( isset( $defOpts[$opt] ) ) {
963 return $defOpts[$opt];
970 * Get a list of user toggle names
973 static function getToggles() {
975 $extraToggles = array();
976 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
977 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
982 * Get blocking information
984 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
985 * non-critical checks are done against slaves. Check when actually saving should be done against
988 function getBlockedStatus( $bFromSlave = true ) {
989 global $wgEnableSorbs, $wgProxyWhitelist;
991 if ( -1 != $this->mBlockedby
) {
992 wfDebug( "User::getBlockedStatus: already loaded.\n" );
996 wfProfileIn( __METHOD__
);
997 wfDebug( __METHOD__
.": checking...\n" );
999 $this->mBlockedby
= 0;
1000 $this->mHideName
= 0;
1003 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1004 # Exempt from all types of IP-block
1009 $this->mBlock
= new Block();
1010 $this->mBlock
->fromMaster( !$bFromSlave );
1011 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1012 wfDebug( __METHOD__
.": Found block.\n" );
1013 $this->mBlockedby
= $this->mBlock
->mBy
;
1014 $this->mBlockreason
= $this->mBlock
->mReason
;
1015 $this->mHideName
= $this->mBlock
->mHideName
;
1016 if ( $this->isLoggedIn() ) {
1017 $this->spreadBlock();
1020 $this->mBlock
= null;
1021 wfDebug( __METHOD__
.": No block.\n" );
1025 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1028 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1029 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1030 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1034 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1035 if ( $this->inSorbsBlacklist( $ip ) ) {
1036 $this->mBlockedby
= wfMsg( 'sorbs' );
1037 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1043 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1045 wfProfileOut( __METHOD__
);
1048 function inSorbsBlacklist( $ip ) {
1049 global $wgEnableSorbs, $wgSorbsUrl;
1051 return $wgEnableSorbs &&
1052 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1055 function inDnsBlacklist( $ip, $base ) {
1056 wfProfileIn( __METHOD__
);
1062 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
1064 for ( $i=4; $i>=1; $i-- ) {
1065 $host .= $m[$i] . '.';
1070 $ipList = gethostbynamel( $host );
1073 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1076 wfDebug( "Requested $host, not found in $base.\n" );
1080 wfProfileOut( __METHOD__
);
1085 * Is this user subject to rate limiting?
1089 public function isPingLimitable() {
1090 global $wgRateLimitsExcludedGroups;
1091 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
1095 * Primitive rate limits: enforce maximum actions per time period
1096 * to put a brake on flooding.
1098 * Note: when using a shared cache like memcached, IP-address
1099 * last-hit counters will be shared across wikis.
1101 * @return bool true if a rate limiter was tripped
1104 function pingLimiter( $action='edit' ) {
1106 # Call the 'PingLimiter' hook
1108 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1112 global $wgRateLimits;
1113 if( !isset( $wgRateLimits[$action] ) ) {
1117 # Some groups shouldn't trigger the ping limiter, ever
1118 if( !$this->isPingLimitable() )
1121 global $wgMemc, $wgRateLimitLog;
1122 wfProfileIn( __METHOD__
);
1124 $limits = $wgRateLimits[$action];
1126 $id = $this->getId();
1129 if( isset( $limits['anon'] ) && $id == 0 ) {
1130 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1133 if( isset( $limits['user'] ) && $id != 0 ) {
1134 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
1136 if( $this->isNewbie() ) {
1137 if( isset( $limits['newbie'] ) && $id != 0 ) {
1138 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1140 if( isset( $limits['ip'] ) ) {
1141 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1144 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1145 $subnet = $matches[1];
1146 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1151 foreach( $keys as $key => $limit ) {
1152 list( $max, $period ) = $limit;
1153 $summary = "(limit $max in {$period}s)";
1154 $count = $wgMemc->get( $key );
1156 if( $count > $max ) {
1157 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1158 if( $wgRateLimitLog ) {
1159 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1163 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1166 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1167 $wgMemc->add( $key, 1, intval( $period ) );
1169 $wgMemc->incr( $key );
1172 wfProfileOut( __METHOD__
);
1177 * Check if user is blocked
1178 * @return bool True if blocked, false otherwise
1180 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1181 wfDebug( "User::isBlocked: enter\n" );
1182 $this->getBlockedStatus( $bFromSlave );
1183 return $this->mBlockedby
!== 0;
1187 * Check if user is blocked from editing a particular article
1189 function isBlockedFrom( $title, $bFromSlave = false ) {
1190 global $wgBlockAllowsUTEdit;
1191 wfProfileIn( __METHOD__
);
1192 wfDebug( __METHOD__
.": enter\n" );
1194 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1195 $blocked = $this->isBlocked( $bFromSlave );
1196 # If a user's name is suppressed, they cannot make edits anywhere
1197 if ( !$this->mHideName
&& $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1198 $title->getNamespace() == NS_USER_TALK
) {
1200 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1202 wfProfileOut( __METHOD__
);
1207 * Get name of blocker
1208 * @return string name of blocker
1210 function blockedBy() {
1211 $this->getBlockedStatus();
1212 return $this->mBlockedby
;
1216 * Get blocking reason
1217 * @return string Blocking reason
1219 function blockedFor() {
1220 $this->getBlockedStatus();
1221 return $this->mBlockreason
;
1225 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1228 if( $this->mId
=== null and $this->mName
!== null
1229 and User
::isIP( $this->mName
) ) {
1230 // Special case, we know the user is anonymous
1232 } elseif( $this->mId
=== null ) {
1233 // Don't load if this was initialized from an ID
1240 * Set the user and reload all fields according to that ID
1241 * @deprecated use User::newFromId()
1243 function setID( $v ) {
1244 wfDeprecated( __METHOD__
);
1246 $this->clearInstanceCache( 'id' );
1250 * Get the user name, or the IP for anons
1252 function getName() {
1253 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1254 # Special case optimisation
1255 return $this->mName
;
1258 if ( $this->mName
=== false ) {
1260 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1262 return $this->mName
;
1267 * Set the user name.
1269 * This does not reload fields from the database according to the given
1270 * name. Rather, it is used to create a temporary "nonexistent user" for
1271 * later addition to the database. It can also be used to set the IP
1272 * address for an anonymous user to something other than the current
1275 * User::newFromName() has rougly the same function, when the named user
1278 function setName( $str ) {
1280 $this->mName
= $str;
1284 * Return the title dbkey form of the name, for eg user pages.
1288 function getTitleKey() {
1289 return str_replace( ' ', '_', $this->getName() );
1292 function getNewtalk() {
1295 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1296 if( $this->mNewtalk
=== -1 ) {
1297 $this->mNewtalk
= false; # reset talk page status
1299 # Check memcached separately for anons, who have no
1300 # entire User object stored in there.
1303 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1304 $newtalk = $wgMemc->get( $key );
1305 if( strval( $newtalk ) !== '' ) {
1306 $this->mNewtalk
= (bool)$newtalk;
1308 // Since we are caching this, make sure it is up to date by getting it
1310 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1311 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1314 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1318 return (bool)$this->mNewtalk
;
1322 * Return the talk page(s) this user has new messages on.
1324 function getNewMessageLinks() {
1326 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1329 if (!$this->getNewtalk())
1331 $up = $this->getUserPage();
1332 $utp = $up->getTalkPage();
1333 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1338 * Perform a user_newtalk check, uncached.
1339 * Use getNewtalk for a cached check.
1341 * @param string $field
1343 * @param bool $fromMaster True to fetch from the master, false for a slave
1347 function checkNewtalk( $field, $id, $fromMaster = false ) {
1348 if ( $fromMaster ) {
1349 $db = wfGetDB( DB_MASTER
);
1351 $db = wfGetDB( DB_SLAVE
);
1353 $ok = $db->selectField( 'user_newtalk', $field,
1354 array( $field => $id ), __METHOD__
);
1355 return $ok !== false;
1360 * @param string $field
1364 function updateNewtalk( $field, $id ) {
1365 $dbw = wfGetDB( DB_MASTER
);
1366 $dbw->insert( 'user_newtalk',
1367 array( $field => $id ),
1370 if ( $dbw->affectedRows() ) {
1371 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1374 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1380 * Clear the new messages flag for the given user
1381 * @param string $field
1385 function deleteNewtalk( $field, $id ) {
1386 $dbw = wfGetDB( DB_MASTER
);
1387 $dbw->delete( 'user_newtalk',
1388 array( $field => $id ),
1390 if ( $dbw->affectedRows() ) {
1391 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1394 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1400 * Update the 'You have new messages!' status.
1403 function setNewtalk( $val ) {
1404 if( wfReadOnly() ) {
1409 $this->mNewtalk
= $val;
1411 if( $this->isAnon() ) {
1413 $id = $this->getName();
1416 $id = $this->getId();
1421 $changed = $this->updateNewtalk( $field, $id );
1423 $changed = $this->deleteNewtalk( $field, $id );
1426 if( $this->isAnon() ) {
1427 // Anons have a separate memcached space, since
1428 // user records aren't kept for them.
1429 $key = wfMemcKey( 'newtalk', 'ip', $id );
1430 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1433 $this->invalidateCache();
1438 * Generate a current or new-future timestamp to be stored in the
1439 * user_touched field when we update things.
1441 private static function newTouchedTimestamp() {
1442 global $wgClockSkewFudge;
1443 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1447 * Clear user data from memcached.
1448 * Use after applying fun updates to the database; caller's
1449 * responsibility to update user_touched if appropriate.
1451 * Called implicitly from invalidateCache() and saveSettings().
1453 private function clearSharedCache() {
1456 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1461 * Immediately touch the user data cache for this account.
1462 * Updates user_touched field, and removes account data from memcached
1463 * for reload on the next hit.
1465 function invalidateCache() {
1468 $this->mTouched
= self
::newTouchedTimestamp();
1470 $dbw = wfGetDB( DB_MASTER
);
1471 $dbw->update( 'user',
1472 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1473 array( 'user_id' => $this->mId
),
1476 $this->clearSharedCache();
1480 function validateCache( $timestamp ) {
1482 return ($timestamp >= $this->mTouched
);
1486 * Encrypt a password.
1487 * It can eventually salt a password.
1488 * @see User::addSalt()
1489 * @param string $p clear Password.
1490 * @return string Encrypted password.
1492 function encryptPassword( $p ) {
1494 return wfEncryptPassword( $this->mId
, $p );
1498 * Set the password and reset the random token
1499 * Calls through to authentication plugin if necessary;
1500 * will have no effect if the auth plugin refuses to
1501 * pass the change through or if the legal password
1504 * As a special case, setting the password to null
1505 * wipes it, so the account cannot be logged in until
1506 * a new password is set, for instance via e-mail.
1508 * @param string $str
1509 * @throws PasswordError on failure
1511 function setPassword( $str ) {
1514 if( $str !== null ) {
1515 if( !$wgAuth->allowPasswordChange() ) {
1516 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1519 if( !$this->isValidPassword( $str ) ) {
1520 global $wgMinimalPasswordLength;
1521 throw new PasswordError( wfMsg( 'passwordtooshort',
1522 $wgMinimalPasswordLength ) );
1526 if( !$wgAuth->setPassword( $this, $str ) ) {
1527 throw new PasswordError( wfMsg( 'externaldberror' ) );
1530 $this->setInternalPassword( $str );
1536 * Set the password and reset the random token no matter
1539 * @param string $str
1541 function setInternalPassword( $str ) {
1545 if( $str === null ) {
1546 // Save an invalid hash...
1547 $this->mPassword
= '';
1549 $this->mPassword
= $this->encryptPassword( $str );
1551 $this->mNewpassword
= '';
1552 $this->mNewpassTime
= null;
1555 * Set the random token (used for persistent authentication)
1556 * Called from loadDefaults() among other places.
1559 function setToken( $token = false ) {
1560 global $wgSecretKey, $wgProxyKey;
1563 if ( $wgSecretKey ) {
1564 $key = $wgSecretKey;
1565 } elseif ( $wgProxyKey ) {
1570 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1572 $this->mToken
= $token;
1576 function setCookiePassword( $str ) {
1578 $this->mCookiePassword
= md5( $str );
1582 * Set the password for a password reminder or new account email
1583 * Sets the user_newpass_time field if $throttle is true
1585 function setNewpassword( $str, $throttle = true ) {
1587 $this->mNewpassword
= $this->encryptPassword( $str );
1589 $this->mNewpassTime
= wfTimestampNow();
1594 * Returns true if a password reminder email has already been sent within
1595 * the last $wgPasswordReminderResendTime hours
1597 function isPasswordReminderThrottled() {
1598 global $wgPasswordReminderResendTime;
1600 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1603 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1604 return time() < $expiry;
1607 function getEmail() {
1609 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1610 return $this->mEmail
;
1613 function getEmailAuthenticationTimestamp() {
1615 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1616 return $this->mEmailAuthenticated
;
1619 function setEmail( $str ) {
1621 $this->mEmail
= $str;
1622 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1625 function getRealName() {
1627 return $this->mRealName
;
1630 function setRealName( $str ) {
1632 $this->mRealName
= $str;
1636 * @param string $oname The option to check
1637 * @param string $defaultOverride A default value returned if the option does not exist
1640 function getOption( $oname, $defaultOverride = '' ) {
1643 if ( is_null( $this->mOptions
) ) {
1644 if($defaultOverride != '') {
1645 return $defaultOverride;
1647 $this->mOptions
= User
::getDefaultOptions();
1650 if ( array_key_exists( $oname, $this->mOptions
) ) {
1651 return trim( $this->mOptions
[$oname] );
1653 return $defaultOverride;
1658 * Get the user's date preference, including some important migration for
1661 function getDatePreference() {
1662 if ( is_null( $this->mDatePreference
) ) {
1664 $value = $this->getOption( 'date' );
1665 $map = $wgLang->getDatePreferenceMigrationMap();
1666 if ( isset( $map[$value] ) ) {
1667 $value = $map[$value];
1669 $this->mDatePreference
= $value;
1671 return $this->mDatePreference
;
1675 * @param string $oname The option to check
1676 * @return bool False if the option is not selected, true if it is
1678 function getBoolOption( $oname ) {
1679 return (bool)$this->getOption( $oname );
1683 * Get an option as an integer value from the source string.
1684 * @param string $oname The option to check
1685 * @param int $default Optional value to return if option is unset/blank.
1688 function getIntOption( $oname, $default=0 ) {
1689 $val = $this->getOption( $oname );
1693 return intval( $val );
1696 function setOption( $oname, $val ) {
1698 if ( is_null( $this->mOptions
) ) {
1699 $this->mOptions
= User
::getDefaultOptions();
1701 if ( $oname == 'skin' ) {
1702 # Clear cached skin, so the new one displays immediately in Special:Preferences
1703 unset( $this->mSkin
);
1705 // Filter out any newlines that may have passed through input validation.
1706 // Newlines are used to separate items in the options blob.
1707 $val = str_replace( "\r\n", "\n", $val );
1708 $val = str_replace( "\r", "\n", $val );
1709 $val = str_replace( "\n", " ", $val );
1710 $this->mOptions
[$oname] = $val;
1713 function getRights() {
1714 if ( is_null( $this->mRights
) ) {
1715 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1716 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1718 return $this->mRights
;
1722 * Get the list of explicit group memberships this user has.
1723 * The implicit * and user groups are not included.
1724 * @return array of strings
1726 function getGroups() {
1728 return $this->mGroups
;
1732 * Get the list of implicit group memberships this user has.
1733 * This includes all explicit groups, plus 'user' if logged in,
1734 * '*' for all accounts and autopromoted groups
1735 * @param boolean $recache Don't use the cache
1736 * @return array of strings
1738 function getEffectiveGroups( $recache = false ) {
1739 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1740 $this->mEffectiveGroups
= $this->getGroups();
1741 $this->mEffectiveGroups
[] = '*';
1742 if( $this->getId() ) {
1743 $this->mEffectiveGroups
[] = 'user';
1745 $this->mEffectiveGroups
= array_unique( array_merge(
1746 $this->mEffectiveGroups
,
1747 Autopromote
::getAutopromoteGroups( $this )
1750 # Hook for additional groups
1751 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1754 return $this->mEffectiveGroups
;
1757 /* Return the edit count for the user. This is where User::edits should have been */
1758 function getEditCount() {
1760 if ( !isset( $this->mEditCount
) ) {
1761 /* Populate the count, if it has not been populated yet */
1762 $this->mEditCount
= User
::edits($this->mId
);
1764 return $this->mEditCount
;
1772 * Add the user to the given group.
1773 * This takes immediate effect.
1774 * @param string $group
1776 function addGroup( $group ) {
1777 $dbw = wfGetDB( DB_MASTER
);
1778 if( $this->getId() ) {
1779 $dbw->insert( 'user_groups',
1781 'ug_user' => $this->getID(),
1782 'ug_group' => $group,
1785 array( 'IGNORE' ) );
1788 $this->loadGroups();
1789 $this->mGroups
[] = $group;
1790 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1792 $this->invalidateCache();
1796 * Remove the user from the given group.
1797 * This takes immediate effect.
1798 * @param string $group
1800 function removeGroup( $group ) {
1802 $dbw = wfGetDB( DB_MASTER
);
1803 $dbw->delete( 'user_groups',
1805 'ug_user' => $this->getID(),
1806 'ug_group' => $group,
1808 'User::removeGroup' );
1810 $this->loadGroups();
1811 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1812 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1814 $this->invalidateCache();
1819 * A more legible check for non-anonymousness.
1820 * Returns true if the user is not an anonymous visitor.
1824 function isLoggedIn() {
1825 return $this->getID() != 0;
1829 * A more legible check for anonymousness.
1830 * Returns true if the user is an anonymous visitor.
1835 return !$this->isLoggedIn();
1839 * Whether the user is a bot
1843 wfDeprecated( __METHOD__
);
1844 return $this->isAllowed( 'bot' );
1848 * Check if user is allowed to access a feature / make an action
1849 * @param string $action Action to be checked
1850 * @return boolean True: action is allowed, False: action should not be allowed
1852 function isAllowed($action='') {
1853 if ( $action === '' )
1854 // In the spirit of DWIM
1857 return in_array( $action, $this->getRights() );
1861 * Check whether to enable recent changes patrol features for this user
1864 public function useRCPatrol() {
1865 global $wgUseRCPatrol;
1866 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
1870 * Check whether to enable recent changes patrol features for this user
1873 public function useNPPatrol() {
1874 global $wgUseRCPatrol, $wgUseNPPatrol;
1875 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
1879 * Load a skin if it doesn't exist or return it
1880 * @todo FIXME : need to check the old failback system [AV]
1882 function &getSkin() {
1884 if ( ! isset( $this->mSkin
) ) {
1885 wfProfileIn( __METHOD__
);
1888 $userSkin = $this->getOption( 'skin' );
1889 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1891 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1892 wfProfileOut( __METHOD__
);
1894 return $this->mSkin
;
1898 * @param string $title Article title to look at
1902 * Check watched status of an article
1903 * @return bool True if article is watched
1905 function isWatched( $title ) {
1906 $wl = WatchedItem
::fromUserTitle( $this, $title );
1907 return $wl->isWatched();
1913 function addWatch( $title ) {
1914 $wl = WatchedItem
::fromUserTitle( $this, $title );
1916 $this->invalidateCache();
1920 * Stop watching an article
1922 function removeWatch( $title ) {
1923 $wl = WatchedItem
::fromUserTitle( $this, $title );
1925 $this->invalidateCache();
1929 * Clear the user's notification timestamp for the given title.
1930 * If e-notif e-mails are on, they will receive notification mails on
1931 * the next change of the page if it's watched etc.
1933 function clearNotification( &$title ) {
1934 global $wgUser, $wgUseEnotif;
1936 # Do nothing if the database is locked to writes
1937 if( wfReadOnly() ) {
1941 if ($title->getNamespace() == NS_USER_TALK
&&
1942 $title->getText() == $this->getName() ) {
1943 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1945 $this->setNewtalk( false );
1948 if( !$wgUseEnotif ) {
1952 if( $this->isAnon() ) {
1953 // Nothing else to do...
1957 // Only update the timestamp if the page is being watched.
1958 // The query to find out if it is watched is cached both in memcached and per-invocation,
1959 // and when it does have to be executed, it can be on a slave
1960 // If this is the user's newtalk page, we always update the timestamp
1961 if ($title->getNamespace() == NS_USER_TALK
&&
1962 $title->getText() == $wgUser->getName())
1965 } elseif ( $this->getID() == $wgUser->getID() ) {
1966 $watched = $title->userIsWatching();
1971 // If the page is watched by the user (or may be watched), update the timestamp on any
1972 // any matching rows
1974 $dbw = wfGetDB( DB_MASTER
);
1975 $dbw->update( 'watchlist',
1977 'wl_notificationtimestamp' => NULL
1978 ), array( /* WHERE */
1979 'wl_title' => $title->getDBkey(),
1980 'wl_namespace' => $title->getNamespace(),
1981 'wl_user' => $this->getID()
1982 ), 'User::clearLastVisited'
1990 * Resets all of the given user's page-change notification timestamps.
1991 * If e-notif e-mails are on, they will receive notification mails on
1992 * the next change of any watched page.
1994 * @param int $currentUser user ID number
1997 function clearAllNotifications( $currentUser ) {
1998 global $wgUseEnotif;
1999 if ( !$wgUseEnotif ) {
2000 $this->setNewtalk( false );
2003 if( $currentUser != 0 ) {
2005 $dbw = wfGetDB( DB_MASTER
);
2006 $dbw->update( 'watchlist',
2008 'wl_notificationtimestamp' => NULL
2009 ), array( /* WHERE */
2010 'wl_user' => $currentUser
2014 # we also need to clear here the "you have new message" notification for the own user_talk page
2015 # This is cleared one page view later in Article::viewUpdates();
2021 * @return string Encoding options
2023 function encodeOptions() {
2025 if ( is_null( $this->mOptions
) ) {
2026 $this->mOptions
= User
::getDefaultOptions();
2029 foreach ( $this->mOptions
as $oname => $oval ) {
2030 array_push( $a, $oname.'='.$oval );
2032 $s = implode( "\n", $a );
2039 function decodeOptions( $str ) {
2040 $this->mOptions
= array();
2041 $a = explode( "\n", $str );
2042 foreach ( $a as $s ) {
2044 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2045 $this->mOptions
[$m[1]] = $m[2];
2050 protected function setCookie( $name, $value, $exp=0 ) {
2051 global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly;
2053 $exp = time() +
$wgCookieExpiration;
2055 $httpOnlySafe = wfHttpOnlySafe();
2056 wfDebugLog( 'cookie',
2057 'setcookie: "' . implode( '", "',
2059 $wgCookiePrefix . $name,
2065 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2066 if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) {
2067 setcookie( $wgCookiePrefix . $name,
2073 $wgCookieHttpOnly );
2075 // setcookie() fails on PHP 5.1 if you give it future-compat paramters.
2077 setcookie( $wgCookiePrefix . $name,
2086 protected function clearCookie( $name ) {
2087 $this->setCookie( $name, '', time() - 86400 );
2090 function setCookies() {
2092 if ( 0 == $this->mId
) return;
2094 $_SESSION['wsUserID'] = $this->mId
;
2096 $this->setCookie( 'UserID', $this->mId
);
2097 $this->setCookie( 'UserName', $this->getName() );
2099 $_SESSION['wsUserName'] = $this->getName();
2101 $_SESSION['wsToken'] = $this->mToken
;
2102 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2103 $this->setCookie( 'Token', $this->mToken
);
2105 $this->clearCookie( 'Token' );
2114 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2120 * Really logout user
2121 * Clears the cookies and session, resets the instance cache
2123 function doLogout() {
2124 $this->clearInstanceCache( 'defaults' );
2126 $_SESSION['wsUserID'] = 0;
2128 $this->clearCookie( 'UserID' );
2129 $this->clearCookie( 'Token' );
2131 # Remember when user logged out, to prevent seeing cached pages
2132 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2136 * Save object settings into database
2137 * @todo Only rarely do all these fields need to be set!
2139 function saveSettings() {
2141 if ( wfReadOnly() ) { return; }
2142 if ( 0 == $this->mId
) { return; }
2144 $this->mTouched
= self
::newTouchedTimestamp();
2146 $dbw = wfGetDB( DB_MASTER
);
2147 $dbw->update( 'user',
2149 'user_name' => $this->mName
,
2150 'user_password' => $this->mPassword
,
2151 'user_newpassword' => $this->mNewpassword
,
2152 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2153 'user_real_name' => $this->mRealName
,
2154 'user_email' => $this->mEmail
,
2155 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2156 'user_options' => $this->encodeOptions(),
2157 'user_touched' => $dbw->timestamp($this->mTouched
),
2158 'user_token' => $this->mToken
,
2159 'user_email_token' => $this->mEmailToken
,
2160 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2161 ), array( /* WHERE */
2162 'user_id' => $this->mId
2165 wfRunHooks( 'UserSaveSettings', array( $this ) );
2166 $this->clearSharedCache();
2170 * Checks if a user with the given name exists, returns the ID.
2172 function idForName() {
2173 $s = trim( $this->getName() );
2174 if ( $s === '' ) return 0;
2176 $dbr = wfGetDB( DB_SLAVE
);
2177 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2178 if ( $id === false ) {
2185 * Add a user to the database, return the user object
2187 * @param string $name The user's name
2188 * @param array $params Associative array of non-default parameters to save to the database:
2189 * password The user's password. Password logins will be disabled if this is omitted.
2190 * newpassword A temporary password mailed to the user
2191 * email The user's email address
2192 * email_authenticated The email authentication timestamp
2193 * real_name The user's real name
2194 * options An associative array of non-default options
2195 * token Random authentication token. Do not set.
2196 * registration Registration timestamp. Do not set.
2198 * @return User object, or null if the username already exists
2200 static function createNew( $name, $params = array() ) {
2203 if ( isset( $params['options'] ) ) {
2204 $user->mOptions
= $params['options'] +
$user->mOptions
;
2205 unset( $params['options'] );
2207 $dbw = wfGetDB( DB_MASTER
);
2208 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2210 'user_id' => $seqVal,
2211 'user_name' => $name,
2212 'user_password' => $user->mPassword
,
2213 'user_newpassword' => $user->mNewpassword
,
2214 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2215 'user_email' => $user->mEmail
,
2216 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2217 'user_real_name' => $user->mRealName
,
2218 'user_options' => $user->encodeOptions(),
2219 'user_token' => $user->mToken
,
2220 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2221 'user_editcount' => 0,
2223 foreach ( $params as $name => $value ) {
2224 $fields["user_$name"] = $value;
2226 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2227 if ( $dbw->affectedRows() ) {
2228 $newUser = User
::newFromId( $dbw->insertId() );
2236 * Add an existing user object to the database
2238 function addToDatabase() {
2240 $dbw = wfGetDB( DB_MASTER
);
2241 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2242 $dbw->insert( 'user',
2244 'user_id' => $seqVal,
2245 'user_name' => $this->mName
,
2246 'user_password' => $this->mPassword
,
2247 'user_newpassword' => $this->mNewpassword
,
2248 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2249 'user_email' => $this->mEmail
,
2250 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2251 'user_real_name' => $this->mRealName
,
2252 'user_options' => $this->encodeOptions(),
2253 'user_token' => $this->mToken
,
2254 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2255 'user_editcount' => 0,
2258 $this->mId
= $dbw->insertId();
2260 # Clear instance cache other than user table data, which is already accurate
2261 $this->clearInstanceCache();
2265 * If the (non-anonymous) user is blocked, this function will block any IP address
2266 * that they successfully log on from.
2268 function spreadBlock() {
2269 wfDebug( __METHOD__
."()\n" );
2271 if ( $this->mId
== 0 ) {
2275 $userblock = Block
::newFromDB( '', $this->mId
);
2276 if ( !$userblock ) {
2280 $userblock->doAutoblock( wfGetIp() );
2285 * Generate a string which will be different for any combination of
2286 * user options which would produce different parser output.
2287 * This will be used as part of the hash key for the parser cache,
2288 * so users will the same options can share the same cached data
2291 * Extensions which require it should install 'PageRenderingHash' hook,
2292 * which will give them a chance to modify this key based on their own
2297 function getPageRenderingHash() {
2298 global $wgContLang, $wgUseDynamicDates, $wgLang;
2300 return $this->mHash
;
2303 // stubthreshold is only included below for completeness,
2304 // it will always be 0 when this function is called by parsercache.
2306 $confstr = $this->getOption( 'math' );
2307 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2308 if ( $wgUseDynamicDates ) {
2309 $confstr .= '!' . $this->getDatePreference();
2311 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2312 $confstr .= '!' . $wgLang->getCode();
2313 $confstr .= '!' . $this->getOption( 'thumbsize' );
2314 // add in language specific options, if any
2315 $extra = $wgContLang->getExtraHashOptions();
2318 // Give a chance for extensions to modify the hash, if they have
2319 // extra options or other effects on the parser cache.
2320 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2322 // Make it a valid memcached key fragment
2323 $confstr = str_replace( ' ', '_', $confstr );
2324 $this->mHash
= $confstr;
2328 function isBlockedFromCreateAccount() {
2329 $this->getBlockedStatus();
2330 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2334 * Determine if the user is blocked from using Special:Emailuser.
2339 function isBlockedFromEmailuser() {
2340 $this->getBlockedStatus();
2341 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2344 function isAllowedToCreateAccount() {
2345 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2351 function setLoaded( $loaded ) {
2352 wfDeprecated( __METHOD__
);
2356 * Get this user's personal page title.
2361 function getUserPage() {
2362 return Title
::makeTitle( NS_USER
, $this->getName() );
2366 * Get this user's talk page title.
2371 function getTalkPage() {
2372 $title = $this->getUserPage();
2373 return $title->getTalkPage();
2379 function getMaxID() {
2380 static $res; // cache
2382 if ( isset( $res ) )
2385 $dbr = wfGetDB( DB_SLAVE
);
2386 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2391 * Determine whether the user is a newbie. Newbies are either
2392 * anonymous IPs, or the most recently created accounts.
2393 * @return bool True if it is a newbie.
2395 function isNewbie() {
2396 return !$this->isAllowed( 'autoconfirmed' );
2400 * Check to see if the given clear-text password is one of the accepted passwords
2401 * @param string $password User password.
2402 * @return bool True if the given password is correct otherwise False.
2404 function checkPassword( $password ) {
2408 // Even though we stop people from creating passwords that
2409 // are shorter than this, doesn't mean people wont be able
2410 // to. Certain authentication plugins do NOT want to save
2411 // domain passwords in a mysql database, so we should
2412 // check this (incase $wgAuth->strict() is false).
2413 if( !$this->isValidPassword( $password ) ) {
2417 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2419 } elseif( $wgAuth->strict() ) {
2420 /* Auth plugin doesn't allow local authentication */
2422 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2423 /* Auth plugin doesn't allow local authentication for this user name */
2426 $ep = $this->encryptPassword( $password );
2427 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2429 } elseif ( function_exists( 'iconv' ) ) {
2430 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2431 # Check for this with iconv
2432 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2433 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2441 * Check if the given clear-text password matches the temporary password
2442 * sent by e-mail for password reset operations.
2445 function checkTemporaryPassword( $plaintext ) {
2446 $hash = $this->encryptPassword( $plaintext );
2447 return $hash === $this->mNewpassword
;
2451 * Initialize (if necessary) and return a session token value
2452 * which can be used in edit forms to show that the user's
2453 * login credentials aren't being hijacked with a foreign form
2456 * @param mixed $salt - Optional function-specific data for hash.
2457 * Use a string or an array of strings.
2461 function editToken( $salt = '' ) {
2462 if ( $this->isAnon() ) {
2463 return EDIT_TOKEN_SUFFIX
;
2465 if( !isset( $_SESSION['wsEditToken'] ) ) {
2466 $token = $this->generateToken();
2467 $_SESSION['wsEditToken'] = $token;
2469 $token = $_SESSION['wsEditToken'];
2471 if( is_array( $salt ) ) {
2472 $salt = implode( '|', $salt );
2474 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2479 * Generate a hex-y looking random token for various uses.
2480 * Could be made more cryptographically sure if someone cares.
2483 function generateToken( $salt = '' ) {
2484 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2485 return md5( $token . $salt );
2489 * Check given value against the token value stored in the session.
2490 * A match should confirm that the form was submitted from the
2491 * user's own login session, not a form submission from a third-party
2494 * @param string $val - the input value to compare
2495 * @param string $salt - Optional function-specific data for hash
2499 function matchEditToken( $val, $salt = '' ) {
2500 $sessionToken = $this->editToken( $salt );
2501 if ( $val != $sessionToken ) {
2502 wfDebug( "User::matchEditToken: broken session data\n" );
2504 return $val == $sessionToken;
2508 * Check whether the edit token is fine except for the suffix
2510 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2511 $sessionToken = $this->editToken( $salt );
2512 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2516 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2517 * mail to the user's given address.
2519 * Calls saveSettings() internally; as it has side effects, not committing changes
2520 * would be pretty silly.
2522 * @return mixed True on success, a WikiError object on failure.
2524 function sendConfirmationMail() {
2526 $expiration = null; // gets passed-by-ref and defined in next line.
2527 $token = $this->confirmationToken( $expiration );
2528 $url = $this->confirmationTokenUrl( $token );
2529 $invalidateURL = $this->invalidationTokenUrl( $token );
2530 $this->saveSettings();
2532 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2533 wfMsg( 'confirmemail_body',
2537 $wgLang->timeanddate( $expiration, false ),
2542 * Send an e-mail to this user's account. Does not check for
2543 * confirmed status or validity.
2545 * @param string $subject
2546 * @param string $body
2547 * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
2548 * @return mixed True on success, a WikiError object on failure.
2550 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2551 if( is_null( $from ) ) {
2552 global $wgPasswordSender;
2553 $from = $wgPasswordSender;
2556 $to = new MailAddress( $this );
2557 $sender = new MailAddress( $from );
2558 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2562 * Generate, store, and return a new e-mail confirmation code.
2563 * A hash (unsalted since it's used as a key) is stored.
2565 * Call saveSettings() after calling this function to commit
2566 * this change to the database.
2568 * @param &$expiration mixed output: accepts the expiration time
2572 function confirmationToken( &$expiration ) {
2574 $expires = $now +
7 * 24 * 60 * 60;
2575 $expiration = wfTimestamp( TS_MW
, $expires );
2576 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2577 $hash = md5( $token );
2579 $this->mEmailToken
= $hash;
2580 $this->mEmailTokenExpires
= $expiration;
2585 * Return a URL the user can use to confirm their email address.
2586 * @param $token: accepts the email confirmation token
2590 function confirmationTokenUrl( $token ) {
2591 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2592 return $title->getFullUrl();
2595 * Return a URL the user can use to invalidate their email address.
2596 * @param $token: accepts the email confirmation token
2600 function invalidationTokenUrl( $token ) {
2601 $title = SpecialPage
::getTitleFor( 'Invalidateemail', $token );
2602 return $title->getFullUrl();
2606 * Mark the e-mail address confirmed.
2608 * Call saveSettings() after calling this function to commit the change.
2610 function confirmEmail() {
2611 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2616 * Invalidate the user's email confirmation, unauthenticate the email
2617 * if it was already confirmed.
2619 * Call saveSettings() after calling this function to commit the change.
2621 function invalidateEmail() {
2623 $this->mEmailToken
= null;
2624 $this->mEmailTokenExpires
= null;
2625 $this->setEmailAuthenticationTimestamp( null );
2629 function setEmailAuthenticationTimestamp( $timestamp ) {
2631 $this->mEmailAuthenticated
= $timestamp;
2632 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2636 * Is this user allowed to send e-mails within limits of current
2637 * site configuration?
2640 function canSendEmail() {
2641 $canSend = $this->isEmailConfirmed();
2642 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2647 * Is this user allowed to receive e-mails within limits of current
2648 * site configuration?
2651 function canReceiveEmail() {
2652 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2656 * Is this user's e-mail address valid-looking and confirmed within
2657 * limits of the current site configuration?
2659 * If $wgEmailAuthentication is on, this may require the user to have
2660 * confirmed their address by returning a code or using a password
2661 * sent to the address from the wiki.
2665 function isEmailConfirmed() {
2666 global $wgEmailAuthentication;
2669 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2670 if( $this->isAnon() )
2672 if( !self
::isValidEmailAddr( $this->mEmail
) )
2674 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2683 * Return true if there is an outstanding request for e-mail confirmation.
2686 function isEmailConfirmationPending() {
2687 global $wgEmailAuthentication;
2688 return $wgEmailAuthentication &&
2689 !$this->isEmailConfirmed() &&
2690 $this->mEmailToken
&&
2691 $this->mEmailTokenExpires
> wfTimestamp();
2695 * Get the timestamp of account creation, or false for
2696 * non-existent/anonymous user accounts
2700 public function getRegistration() {
2701 return $this->mId
> 0
2702 ?
$this->mRegistration
2707 * @param array $groups list of groups
2708 * @return array list of permission key names for given groups combined
2710 static function getGroupPermissions( $groups ) {
2711 global $wgGroupPermissions;
2713 foreach( $groups as $group ) {
2714 if( isset( $wgGroupPermissions[$group] ) ) {
2715 $rights = array_merge( $rights,
2716 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2723 * @param string $group key name
2724 * @return string localized descriptive name for group, if provided
2726 static function getGroupName( $group ) {
2727 global $wgMessageCache;
2728 $wgMessageCache->loadAllMessages();
2729 $key = "group-$group";
2730 $name = wfMsg( $key );
2731 return $name == '' ||
wfEmptyMsg( $key, $name )
2737 * @param string $group key name
2738 * @return string localized descriptive name for member of a group, if provided
2740 static function getGroupMember( $group ) {
2741 global $wgMessageCache;
2742 $wgMessageCache->loadAllMessages();
2743 $key = "group-$group-member";
2744 $name = wfMsg( $key );
2745 return $name == '' ||
wfEmptyMsg( $key, $name )
2751 * Return the set of defined explicit groups.
2752 * The implicit groups (by default *, 'user' and 'autoconfirmed')
2753 * are not included, as they are defined automatically,
2754 * not in the database.
2757 static function getAllGroups() {
2758 global $wgGroupPermissions;
2760 array_keys( $wgGroupPermissions ),
2761 self
::getImplicitGroups()
2766 * Get a list of all available permissions
2768 static function getAllRights() {
2769 if ( self
::$mAllRights === false ) {
2770 global $wgAvailableRights;
2771 if ( count( $wgAvailableRights ) ) {
2772 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
2774 self
::$mAllRights = self
::$mCoreRights;
2776 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
2778 return self
::$mAllRights;
2782 * Get a list of implicit groups
2786 public static function getImplicitGroups() {
2787 global $wgImplicitGroups;
2788 $groups = $wgImplicitGroups;
2789 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
2794 * Get the title of a page describing a particular group
2796 * @param $group Name of the group
2799 static function getGroupPage( $group ) {
2800 global $wgMessageCache;
2801 $wgMessageCache->loadAllMessages();
2802 $page = wfMsgForContent( 'grouppage-' . $group );
2803 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2804 $title = Title
::newFromText( $page );
2805 if( is_object( $title ) )
2812 * Create a link to the group in HTML, if available
2814 * @param $group Name of the group
2815 * @param $text The text of the link
2818 static function makeGroupLinkHTML( $group, $text = '' ) {
2820 $text = self
::getGroupName( $group );
2822 $title = self
::getGroupPage( $group );
2825 $sk = $wgUser->getSkin();
2826 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2833 * Create a link to the group in Wikitext, if available
2835 * @param $group Name of the group
2836 * @param $text The text of the link (by default, the name of the group)
2839 static function makeGroupLinkWiki( $group, $text = '' ) {
2841 $text = self
::getGroupName( $group );
2843 $title = self
::getGroupPage( $group );
2845 $page = $title->getPrefixedText();
2846 return "[[$page|$text]]";
2853 * Increment the user's edit-count field.
2854 * Will have no effect for anonymous users.
2856 function incEditCount() {
2857 if( !$this->isAnon() ) {
2858 $dbw = wfGetDB( DB_MASTER
);
2859 $dbw->update( 'user',
2860 array( 'user_editcount=user_editcount+1' ),
2861 array( 'user_id' => $this->getId() ),
2864 // Lazy initialization check...
2865 if( $dbw->affectedRows() == 0 ) {
2866 // Pull from a slave to be less cruel to servers
2867 // Accuracy isn't the point anyway here
2868 $dbr = wfGetDB( DB_SLAVE
);
2869 $count = $dbr->selectField( 'revision',
2871 array( 'rev_user' => $this->getId() ),
2874 // Now here's a goddamn hack...
2875 if( $dbr !== $dbw ) {
2876 // If we actually have a slave server, the count is
2877 // at least one behind because the current transaction
2878 // has not been committed and replicated.
2881 // But if DB_SLAVE is selecting the master, then the
2882 // count we just read includes the revision that was
2883 // just added in the working transaction.
2886 $dbw->update( 'user',
2887 array( 'user_editcount' => $count ),
2888 array( 'user_id' => $this->getId() ),
2892 // edit count in user cache too
2893 $this->invalidateCache();
2896 static function getRightDescription( $right ) {
2897 global $wgMessageCache;
2898 $wgMessageCache->loadAllMessages();
2899 $key = "right-$right";
2900 $name = wfMsg( $key );
2901 return $name == '' ||
wfEmptyMsg( $key, $name )