234752a41462ff20d070702ad33386ddc99b73d3
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;
771 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
772 if ( $result !== null ) {
776 if ( isset( $_SESSION['wsUserID'] ) ) {
777 if ( 0 != $_SESSION['wsUserID'] ) {
778 $sId = $_SESSION['wsUserID'];
780 $this->loadDefaults();
783 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
784 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
785 $_SESSION['wsUserID'] = $sId;
787 $this->loadDefaults();
790 if ( isset( $_SESSION['wsUserName'] ) ) {
791 $sName = $_SESSION['wsUserName'];
792 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
793 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
794 $_SESSION['wsUserName'] = $sName;
796 $this->loadDefaults();
800 $passwordCorrect = FALSE;
802 if ( !$this->loadFromId() ) {
803 # Not a valid ID, loadFromId has switched the object to anon for us
807 if ( isset( $_SESSION['wsToken'] ) ) {
808 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
810 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
811 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
814 # No session or persistent login cookie
815 $this->loadDefaults();
819 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
820 $_SESSION['wsToken'] = $this->mToken
;
821 wfDebug( "Logged in from $from\n" );
824 # Invalid credentials
825 wfDebug( "Can't log in from $from, invalid credentials\n" );
826 $this->loadDefaults();
832 * Load user and user_group data from the database
833 * $this->mId must be set, this is how the user is identified.
835 * @return true if the user exists, false if the user is anonymous
838 function loadFromDatabase() {
840 $this->mId
= intval( $this->mId
);
842 /** Anonymous user */
844 $this->loadDefaults();
848 $dbr = wfGetDB( DB_MASTER
);
849 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
851 if ( $s !== false ) {
852 # Initialise user table data
853 $this->loadFromRow( $s );
854 $this->mGroups
= null; // deferred
855 $this->getEditCount(); // revalidation for nulls
860 $this->loadDefaults();
866 * Initialise the user object from a row from the user table
868 function loadFromRow( $row ) {
869 $this->mDataLoaded
= true;
871 if ( isset( $row->user_id
) ) {
872 $this->mId
= $row->user_id
;
874 $this->mName
= $row->user_name
;
875 $this->mRealName
= $row->user_real_name
;
876 $this->mPassword
= $row->user_password
;
877 $this->mNewpassword
= $row->user_newpassword
;
878 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
879 $this->mEmail
= $row->user_email
;
880 $this->decodeOptions( $row->user_options
);
881 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
882 $this->mToken
= $row->user_token
;
883 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
884 $this->mEmailToken
= $row->user_email_token
;
885 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
886 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
887 $this->mEditCount
= $row->user_editcount
;
891 * Load the groups from the database if they aren't already loaded
894 function loadGroups() {
895 if ( is_null( $this->mGroups
) ) {
896 $dbr = wfGetDB( DB_MASTER
);
897 $res = $dbr->select( 'user_groups',
899 array( 'ug_user' => $this->mId
),
901 $this->mGroups
= array();
902 while( $row = $dbr->fetchObject( $res ) ) {
903 $this->mGroups
[] = $row->ug_group
;
909 * Clear various cached data stored in this object.
910 * @param string $reloadFrom Reload user and user_groups table data from a
911 * given source. May be "name", "id", "defaults", "session" or false for
914 function clearInstanceCache( $reloadFrom = false ) {
915 $this->mNewtalk
= -1;
916 $this->mDatePreference
= null;
917 $this->mBlockedby
= -1; # Unset
918 $this->mHash
= false;
920 $this->mRights
= null;
921 $this->mEffectiveGroups
= null;
924 $this->mDataLoaded
= false;
925 $this->mFrom
= $reloadFrom;
930 * Combine the language default options with any site-specific options
931 * and add the default language variants.
932 * Not really private cause it's called by Language class
937 static function getDefaultOptions() {
938 global $wgNamespacesToBeSearchedDefault;
940 * Site defaults will override the global/language defaults
942 global $wgDefaultUserOptions, $wgContLang;
943 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
946 * default language setting
948 $variant = $wgContLang->getPreferredVariant( false );
949 $defOpt['variant'] = $variant;
950 $defOpt['language'] = $variant;
952 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
953 $defOpt['searchNs'.$nsnum] = $val;
959 * Get a given default option value.
966 function getDefaultOption( $opt ) {
967 $defOpts = User
::getDefaultOptions();
968 if( isset( $defOpts[$opt] ) ) {
969 return $defOpts[$opt];
976 * Get a list of user toggle names
979 static function getToggles() {
981 $extraToggles = array();
982 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
983 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
988 * Get blocking information
990 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
991 * non-critical checks are done against slaves. Check when actually saving should be done against
994 function getBlockedStatus( $bFromSlave = true ) {
995 global $wgEnableSorbs, $wgProxyWhitelist;
997 if ( -1 != $this->mBlockedby
) {
998 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1002 wfProfileIn( __METHOD__
);
1003 wfDebug( __METHOD__
.": checking...\n" );
1005 // Initialize data...
1006 // Otherwise something ends up stomping on $this->mBlockedby when
1007 // things get lazy-loaded later, causing false positive block hits
1008 // due to -1 !== 0. Probably session-related... Nothing should be
1009 // overwriting mBlockedby, surely?
1012 $this->mBlockedby
= 0;
1013 $this->mHideName
= 0;
1016 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1017 # Exempt from all types of IP-block
1022 $this->mBlock
= new Block();
1023 $this->mBlock
->fromMaster( !$bFromSlave );
1024 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1025 wfDebug( __METHOD__
.": Found block.\n" );
1026 $this->mBlockedby
= $this->mBlock
->mBy
;
1027 $this->mBlockreason
= $this->mBlock
->mReason
;
1028 $this->mHideName
= $this->mBlock
->mHideName
;
1029 if ( $this->isLoggedIn() ) {
1030 $this->spreadBlock();
1033 $this->mBlock
= null;
1034 wfDebug( __METHOD__
.": No block.\n" );
1038 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1041 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1042 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1043 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1047 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1048 if ( $this->inSorbsBlacklist( $ip ) ) {
1049 $this->mBlockedby
= wfMsg( 'sorbs' );
1050 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1056 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1058 wfProfileOut( __METHOD__
);
1061 function inSorbsBlacklist( $ip ) {
1062 global $wgEnableSorbs, $wgSorbsUrl;
1064 return $wgEnableSorbs &&
1065 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1068 function inDnsBlacklist( $ip, $base ) {
1069 wfProfileIn( __METHOD__
);
1075 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
1077 for ( $i=4; $i>=1; $i-- ) {
1078 $host .= $m[$i] . '.';
1083 $ipList = gethostbynamel( $host );
1086 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1089 wfDebug( "Requested $host, not found in $base.\n" );
1093 wfProfileOut( __METHOD__
);
1098 * Is this user subject to rate limiting?
1102 public function isPingLimitable() {
1103 global $wgRateLimitsExcludedGroups;
1104 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
1108 * Primitive rate limits: enforce maximum actions per time period
1109 * to put a brake on flooding.
1111 * Note: when using a shared cache like memcached, IP-address
1112 * last-hit counters will be shared across wikis.
1114 * @return bool true if a rate limiter was tripped
1117 function pingLimiter( $action='edit' ) {
1119 # Call the 'PingLimiter' hook
1121 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1125 global $wgRateLimits;
1126 if( !isset( $wgRateLimits[$action] ) ) {
1130 # Some groups shouldn't trigger the ping limiter, ever
1131 if( !$this->isPingLimitable() )
1134 global $wgMemc, $wgRateLimitLog;
1135 wfProfileIn( __METHOD__
);
1137 $limits = $wgRateLimits[$action];
1139 $id = $this->getId();
1142 if( isset( $limits['anon'] ) && $id == 0 ) {
1143 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1146 if( isset( $limits['user'] ) && $id != 0 ) {
1147 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
1149 if( $this->isNewbie() ) {
1150 if( isset( $limits['newbie'] ) && $id != 0 ) {
1151 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1153 if( isset( $limits['ip'] ) ) {
1154 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1157 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1158 $subnet = $matches[1];
1159 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1164 foreach( $keys as $key => $limit ) {
1165 list( $max, $period ) = $limit;
1166 $summary = "(limit $max in {$period}s)";
1167 $count = $wgMemc->get( $key );
1169 if( $count > $max ) {
1170 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1171 if( $wgRateLimitLog ) {
1172 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1176 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1179 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1180 $wgMemc->add( $key, 1, intval( $period ) );
1182 $wgMemc->incr( $key );
1185 wfProfileOut( __METHOD__
);
1190 * Check if user is blocked
1191 * @return bool True if blocked, false otherwise
1193 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1194 wfDebug( "User::isBlocked: enter\n" );
1195 $this->getBlockedStatus( $bFromSlave );
1196 return $this->mBlockedby
!== 0;
1200 * Check if user is blocked from editing a particular article
1202 function isBlockedFrom( $title, $bFromSlave = false ) {
1203 global $wgBlockAllowsUTEdit;
1204 wfProfileIn( __METHOD__
);
1205 wfDebug( __METHOD__
.": enter\n" );
1207 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1208 $blocked = $this->isBlocked( $bFromSlave );
1209 # If a user's name is suppressed, they cannot make edits anywhere
1210 if ( !$this->mHideName
&& $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1211 $title->getNamespace() == NS_USER_TALK
) {
1213 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1215 wfProfileOut( __METHOD__
);
1220 * Get name of blocker
1221 * @return string name of blocker
1223 function blockedBy() {
1224 $this->getBlockedStatus();
1225 return $this->mBlockedby
;
1229 * Get blocking reason
1230 * @return string Blocking reason
1232 function blockedFor() {
1233 $this->getBlockedStatus();
1234 return $this->mBlockreason
;
1238 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1241 if( $this->mId
=== null and $this->mName
!== null
1242 and User
::isIP( $this->mName
) ) {
1243 // Special case, we know the user is anonymous
1245 } elseif( $this->mId
=== null ) {
1246 // Don't load if this was initialized from an ID
1253 * Set the user and reload all fields according to that ID
1255 function setID( $v ) {
1257 $this->clearInstanceCache( 'id' );
1261 * Get the user name, or the IP for anons
1263 function getName() {
1264 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1265 # Special case optimisation
1266 return $this->mName
;
1269 if ( $this->mName
=== false ) {
1271 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1273 return $this->mName
;
1278 * Set the user name.
1280 * This does not reload fields from the database according to the given
1281 * name. Rather, it is used to create a temporary "nonexistent user" for
1282 * later addition to the database. It can also be used to set the IP
1283 * address for an anonymous user to something other than the current
1286 * User::newFromName() has rougly the same function, when the named user
1289 function setName( $str ) {
1291 $this->mName
= $str;
1295 * Return the title dbkey form of the name, for eg user pages.
1299 function getTitleKey() {
1300 return str_replace( ' ', '_', $this->getName() );
1303 function getNewtalk() {
1306 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1307 if( $this->mNewtalk
=== -1 ) {
1308 $this->mNewtalk
= false; # reset talk page status
1310 # Check memcached separately for anons, who have no
1311 # entire User object stored in there.
1314 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1315 $newtalk = $wgMemc->get( $key );
1316 if( strval( $newtalk ) !== '' ) {
1317 $this->mNewtalk
= (bool)$newtalk;
1319 // Since we are caching this, make sure it is up to date by getting it
1321 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1322 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1325 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1329 return (bool)$this->mNewtalk
;
1333 * Return the talk page(s) this user has new messages on.
1335 function getNewMessageLinks() {
1337 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1340 if (!$this->getNewtalk())
1342 $up = $this->getUserPage();
1343 $utp = $up->getTalkPage();
1344 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1349 * Perform a user_newtalk check, uncached.
1350 * Use getNewtalk for a cached check.
1352 * @param string $field
1354 * @param bool $fromMaster True to fetch from the master, false for a slave
1358 function checkNewtalk( $field, $id, $fromMaster = false ) {
1359 if ( $fromMaster ) {
1360 $db = wfGetDB( DB_MASTER
);
1362 $db = wfGetDB( DB_SLAVE
);
1364 $ok = $db->selectField( 'user_newtalk', $field,
1365 array( $field => $id ), __METHOD__
);
1366 return $ok !== false;
1371 * @param string $field
1375 function updateNewtalk( $field, $id ) {
1376 $dbw = wfGetDB( DB_MASTER
);
1377 $dbw->insert( 'user_newtalk',
1378 array( $field => $id ),
1381 if ( $dbw->affectedRows() ) {
1382 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1385 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1391 * Clear the new messages flag for the given user
1392 * @param string $field
1396 function deleteNewtalk( $field, $id ) {
1397 $dbw = wfGetDB( DB_MASTER
);
1398 $dbw->delete( 'user_newtalk',
1399 array( $field => $id ),
1401 if ( $dbw->affectedRows() ) {
1402 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1405 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1411 * Update the 'You have new messages!' status.
1414 function setNewtalk( $val ) {
1415 if( wfReadOnly() ) {
1420 $this->mNewtalk
= $val;
1422 if( $this->isAnon() ) {
1424 $id = $this->getName();
1427 $id = $this->getId();
1432 $changed = $this->updateNewtalk( $field, $id );
1434 $changed = $this->deleteNewtalk( $field, $id );
1437 if( $this->isAnon() ) {
1438 // Anons have a separate memcached space, since
1439 // user records aren't kept for them.
1440 $key = wfMemcKey( 'newtalk', 'ip', $id );
1441 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1444 $this->invalidateCache();
1449 * Generate a current or new-future timestamp to be stored in the
1450 * user_touched field when we update things.
1452 private static function newTouchedTimestamp() {
1453 global $wgClockSkewFudge;
1454 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1458 * Clear user data from memcached.
1459 * Use after applying fun updates to the database; caller's
1460 * responsibility to update user_touched if appropriate.
1462 * Called implicitly from invalidateCache() and saveSettings().
1464 private function clearSharedCache() {
1467 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1472 * Immediately touch the user data cache for this account.
1473 * Updates user_touched field, and removes account data from memcached
1474 * for reload on the next hit.
1476 function invalidateCache() {
1479 $this->mTouched
= self
::newTouchedTimestamp();
1481 $dbw = wfGetDB( DB_MASTER
);
1482 $dbw->update( 'user',
1483 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1484 array( 'user_id' => $this->mId
),
1487 $this->clearSharedCache();
1491 function validateCache( $timestamp ) {
1493 return ($timestamp >= $this->mTouched
);
1497 * Encrypt a password.
1498 * It can eventually salt a password.
1499 * @see User::addSalt()
1500 * @param string $p clear Password.
1501 * @return string Encrypted password.
1503 function encryptPassword( $p ) {
1505 return wfEncryptPassword( $this->mId
, $p );
1509 * Set the password and reset the random token
1510 * Calls through to authentication plugin if necessary;
1511 * will have no effect if the auth plugin refuses to
1512 * pass the change through or if the legal password
1515 * As a special case, setting the password to null
1516 * wipes it, so the account cannot be logged in until
1517 * a new password is set, for instance via e-mail.
1519 * @param string $str
1520 * @throws PasswordError on failure
1522 function setPassword( $str ) {
1525 if( $str !== null ) {
1526 if( !$wgAuth->allowPasswordChange() ) {
1527 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1530 if( !$this->isValidPassword( $str ) ) {
1531 global $wgMinimalPasswordLength;
1532 throw new PasswordError( wfMsg( 'passwordtooshort',
1533 $wgMinimalPasswordLength ) );
1537 if( !$wgAuth->setPassword( $this, $str ) ) {
1538 throw new PasswordError( wfMsg( 'externaldberror' ) );
1541 $this->setInternalPassword( $str );
1547 * Set the password and reset the random token no matter
1550 * @param string $str
1552 function setInternalPassword( $str ) {
1556 if( $str === null ) {
1557 // Save an invalid hash...
1558 $this->mPassword
= '';
1560 $this->mPassword
= $this->encryptPassword( $str );
1562 $this->mNewpassword
= '';
1563 $this->mNewpassTime
= null;
1566 * Set the random token (used for persistent authentication)
1567 * Called from loadDefaults() among other places.
1570 function setToken( $token = false ) {
1571 global $wgSecretKey, $wgProxyKey;
1574 if ( $wgSecretKey ) {
1575 $key = $wgSecretKey;
1576 } elseif ( $wgProxyKey ) {
1581 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1583 $this->mToken
= $token;
1587 function setCookiePassword( $str ) {
1589 $this->mCookiePassword
= md5( $str );
1593 * Set the password for a password reminder or new account email
1594 * Sets the user_newpass_time field if $throttle is true
1596 function setNewpassword( $str, $throttle = true ) {
1598 $this->mNewpassword
= $this->encryptPassword( $str );
1600 $this->mNewpassTime
= wfTimestampNow();
1605 * Returns true if a password reminder email has already been sent within
1606 * the last $wgPasswordReminderResendTime hours
1608 function isPasswordReminderThrottled() {
1609 global $wgPasswordReminderResendTime;
1611 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1614 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1615 return time() < $expiry;
1618 function getEmail() {
1620 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1621 return $this->mEmail
;
1624 function getEmailAuthenticationTimestamp() {
1626 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1627 return $this->mEmailAuthenticated
;
1630 function setEmail( $str ) {
1632 $this->mEmail
= $str;
1633 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1636 function getRealName() {
1638 return $this->mRealName
;
1641 function setRealName( $str ) {
1643 $this->mRealName
= $str;
1647 * @param string $oname The option to check
1648 * @param string $defaultOverride A default value returned if the option does not exist
1651 function getOption( $oname, $defaultOverride = '' ) {
1654 if ( is_null( $this->mOptions
) ) {
1655 if($defaultOverride != '') {
1656 return $defaultOverride;
1658 $this->mOptions
= User
::getDefaultOptions();
1661 if ( array_key_exists( $oname, $this->mOptions
) ) {
1662 return trim( $this->mOptions
[$oname] );
1664 return $defaultOverride;
1669 * Get the user's date preference, including some important migration for
1672 function getDatePreference() {
1673 if ( is_null( $this->mDatePreference
) ) {
1675 $value = $this->getOption( 'date' );
1676 $map = $wgLang->getDatePreferenceMigrationMap();
1677 if ( isset( $map[$value] ) ) {
1678 $value = $map[$value];
1680 $this->mDatePreference
= $value;
1682 return $this->mDatePreference
;
1686 * @param string $oname The option to check
1687 * @return bool False if the option is not selected, true if it is
1689 function getBoolOption( $oname ) {
1690 return (bool)$this->getOption( $oname );
1694 * Get an option as an integer value from the source string.
1695 * @param string $oname The option to check
1696 * @param int $default Optional value to return if option is unset/blank.
1699 function getIntOption( $oname, $default=0 ) {
1700 $val = $this->getOption( $oname );
1704 return intval( $val );
1707 function setOption( $oname, $val ) {
1709 if ( is_null( $this->mOptions
) ) {
1710 $this->mOptions
= User
::getDefaultOptions();
1712 if ( $oname == 'skin' ) {
1713 # Clear cached skin, so the new one displays immediately in Special:Preferences
1714 unset( $this->mSkin
);
1716 // Filter out any newlines that may have passed through input validation.
1717 // Newlines are used to separate items in the options blob.
1718 $val = str_replace( "\r\n", "\n", $val );
1719 $val = str_replace( "\r", "\n", $val );
1720 $val = str_replace( "\n", " ", $val );
1721 $this->mOptions
[$oname] = $val;
1724 function getRights() {
1725 if ( is_null( $this->mRights
) ) {
1726 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1727 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1728 // Force reindexation of rights when a hook has unset one of them
1729 $this->mRights
= array_values( $this->mRights
);
1731 return $this->mRights
;
1735 * Get the list of explicit group memberships this user has.
1736 * The implicit * and user groups are not included.
1737 * @return array of strings
1739 function getGroups() {
1741 return $this->mGroups
;
1745 * Get the list of implicit group memberships this user has.
1746 * This includes all explicit groups, plus 'user' if logged in,
1747 * '*' for all accounts and autopromoted groups
1748 * @param boolean $recache Don't use the cache
1749 * @return array of strings
1751 function getEffectiveGroups( $recache = false ) {
1752 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1753 $this->mEffectiveGroups
= $this->getGroups();
1754 $this->mEffectiveGroups
[] = '*';
1755 if( $this->getId() ) {
1756 $this->mEffectiveGroups
[] = 'user';
1758 $this->mEffectiveGroups
= array_unique( array_merge(
1759 $this->mEffectiveGroups
,
1760 Autopromote
::getAutopromoteGroups( $this )
1763 # Hook for additional groups
1764 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1767 return $this->mEffectiveGroups
;
1770 /* Return the edit count for the user. This is where User::edits should have been */
1771 function getEditCount() {
1773 if ( !isset( $this->mEditCount
) ) {
1774 /* Populate the count, if it has not been populated yet */
1775 $this->mEditCount
= User
::edits($this->mId
);
1777 return $this->mEditCount
;
1785 * Add the user to the given group.
1786 * This takes immediate effect.
1787 * @param string $group
1789 function addGroup( $group ) {
1790 $dbw = wfGetDB( DB_MASTER
);
1791 if( $this->getId() ) {
1792 $dbw->insert( 'user_groups',
1794 'ug_user' => $this->getID(),
1795 'ug_group' => $group,
1798 array( 'IGNORE' ) );
1801 $this->loadGroups();
1802 $this->mGroups
[] = $group;
1803 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1805 $this->invalidateCache();
1809 * Remove the user from the given group.
1810 * This takes immediate effect.
1811 * @param string $group
1813 function removeGroup( $group ) {
1815 $dbw = wfGetDB( DB_MASTER
);
1816 $dbw->delete( 'user_groups',
1818 'ug_user' => $this->getID(),
1819 'ug_group' => $group,
1821 'User::removeGroup' );
1823 $this->loadGroups();
1824 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1825 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1827 $this->invalidateCache();
1832 * A more legible check for non-anonymousness.
1833 * Returns true if the user is not an anonymous visitor.
1837 function isLoggedIn() {
1838 return $this->getID() != 0;
1842 * A more legible check for anonymousness.
1843 * Returns true if the user is an anonymous visitor.
1848 return !$this->isLoggedIn();
1852 * Whether the user is a bot
1856 wfDeprecated( __METHOD__
);
1857 return $this->isAllowed( 'bot' );
1861 * Check if user is allowed to access a feature / make an action
1862 * @param string $action Action to be checked
1863 * @return boolean True: action is allowed, False: action should not be allowed
1865 function isAllowed($action='') {
1866 if ( $action === '' )
1867 // In the spirit of DWIM
1870 return in_array( $action, $this->getRights() );
1874 * Check whether to enable recent changes patrol features for this user
1877 public function useRCPatrol() {
1878 global $wgUseRCPatrol;
1879 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
1883 * Check whether to enable recent changes patrol features for this user
1886 public function useNPPatrol() {
1887 global $wgUseRCPatrol, $wgUseNPPatrol;
1888 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
1892 * Load a skin if it doesn't exist or return it
1893 * @todo FIXME : need to check the old failback system [AV]
1895 function &getSkin() {
1897 if ( ! isset( $this->mSkin
) ) {
1898 wfProfileIn( __METHOD__
);
1901 $userSkin = $this->getOption( 'skin' );
1902 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1904 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1905 wfProfileOut( __METHOD__
);
1907 return $this->mSkin
;
1911 * @param string $title Article title to look at
1915 * Check watched status of an article
1916 * @return bool True if article is watched
1918 function isWatched( $title ) {
1919 $wl = WatchedItem
::fromUserTitle( $this, $title );
1920 return $wl->isWatched();
1926 function addWatch( $title ) {
1927 $wl = WatchedItem
::fromUserTitle( $this, $title );
1929 $this->invalidateCache();
1933 * Stop watching an article
1935 function removeWatch( $title ) {
1936 $wl = WatchedItem
::fromUserTitle( $this, $title );
1938 $this->invalidateCache();
1942 * Clear the user's notification timestamp for the given title.
1943 * If e-notif e-mails are on, they will receive notification mails on
1944 * the next change of the page if it's watched etc.
1946 function clearNotification( &$title ) {
1947 global $wgUser, $wgUseEnotif;
1949 # Do nothing if the database is locked to writes
1950 if( wfReadOnly() ) {
1954 if ($title->getNamespace() == NS_USER_TALK
&&
1955 $title->getText() == $this->getName() ) {
1956 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1958 $this->setNewtalk( false );
1961 if( !$wgUseEnotif ) {
1965 if( $this->isAnon() ) {
1966 // Nothing else to do...
1970 // Only update the timestamp if the page is being watched.
1971 // The query to find out if it is watched is cached both in memcached and per-invocation,
1972 // and when it does have to be executed, it can be on a slave
1973 // If this is the user's newtalk page, we always update the timestamp
1974 if ($title->getNamespace() == NS_USER_TALK
&&
1975 $title->getText() == $wgUser->getName())
1978 } elseif ( $this->getID() == $wgUser->getID() ) {
1979 $watched = $title->userIsWatching();
1984 // If the page is watched by the user (or may be watched), update the timestamp on any
1985 // any matching rows
1987 $dbw = wfGetDB( DB_MASTER
);
1988 $dbw->update( 'watchlist',
1990 'wl_notificationtimestamp' => NULL
1991 ), array( /* WHERE */
1992 'wl_title' => $title->getDBkey(),
1993 'wl_namespace' => $title->getNamespace(),
1994 'wl_user' => $this->getID()
1995 ), 'User::clearLastVisited'
2003 * Resets all of the given user's page-change notification timestamps.
2004 * If e-notif e-mails are on, they will receive notification mails on
2005 * the next change of any watched page.
2007 * @param int $currentUser user ID number
2010 function clearAllNotifications( $currentUser ) {
2011 global $wgUseEnotif, $wgShowUpdatedMarker;
2012 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2013 $this->setNewtalk( false );
2016 if( $currentUser != 0 ) {
2017 $dbw = wfGetDB( DB_MASTER
);
2018 $dbw->update( 'watchlist',
2020 'wl_notificationtimestamp' => NULL
2021 ), array( /* WHERE */
2022 'wl_user' => $currentUser
2025 # We also need to clear here the "you have new message" notification for the own user_talk page
2026 # This is cleared one page view later in Article::viewUpdates();
2032 * @return string Encoding options
2034 function encodeOptions() {
2036 if ( is_null( $this->mOptions
) ) {
2037 $this->mOptions
= User
::getDefaultOptions();
2040 foreach ( $this->mOptions
as $oname => $oval ) {
2041 array_push( $a, $oname.'='.$oval );
2043 $s = implode( "\n", $a );
2050 function decodeOptions( $str ) {
2051 $this->mOptions
= array();
2052 $a = explode( "\n", $str );
2053 foreach ( $a as $s ) {
2055 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2056 $this->mOptions
[$m[1]] = $m[2];
2061 protected function setCookie( $name, $value, $exp=0 ) {
2062 global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly;
2064 $exp = time() +
$wgCookieExpiration;
2066 $httpOnlySafe = wfHttpOnlySafe();
2067 wfDebugLog( 'cookie',
2068 'setcookie: "' . implode( '", "',
2070 $wgCookiePrefix . $name,
2076 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2077 if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) {
2078 setcookie( $wgCookiePrefix . $name,
2084 $wgCookieHttpOnly );
2086 // setcookie() fails on PHP 5.1 if you give it future-compat paramters.
2088 setcookie( $wgCookiePrefix . $name,
2097 protected function clearCookie( $name ) {
2098 $this->setCookie( $name, '', time() - 86400 );
2101 function setCookies() {
2103 if ( 0 == $this->mId
) return;
2105 $_SESSION['wsUserID'] = $this->mId
;
2107 $this->setCookie( 'UserID', $this->mId
);
2108 $this->setCookie( 'UserName', $this->getName() );
2110 $_SESSION['wsUserName'] = $this->getName();
2112 $_SESSION['wsToken'] = $this->mToken
;
2113 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2114 $this->setCookie( 'Token', $this->mToken
);
2116 $this->clearCookie( 'Token' );
2125 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2131 * Really logout user
2132 * Clears the cookies and session, resets the instance cache
2134 function doLogout() {
2135 $this->clearInstanceCache( 'defaults' );
2137 $_SESSION['wsUserID'] = 0;
2139 $this->clearCookie( 'UserID' );
2140 $this->clearCookie( 'Token' );
2142 # Remember when user logged out, to prevent seeing cached pages
2143 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2147 * Save object settings into database
2148 * @todo Only rarely do all these fields need to be set!
2150 function saveSettings() {
2152 if ( wfReadOnly() ) { return; }
2153 if ( 0 == $this->mId
) { return; }
2155 $this->mTouched
= self
::newTouchedTimestamp();
2157 $dbw = wfGetDB( DB_MASTER
);
2158 $dbw->update( 'user',
2160 'user_name' => $this->mName
,
2161 'user_password' => $this->mPassword
,
2162 'user_newpassword' => $this->mNewpassword
,
2163 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2164 'user_real_name' => $this->mRealName
,
2165 'user_email' => $this->mEmail
,
2166 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2167 'user_options' => $this->encodeOptions(),
2168 'user_touched' => $dbw->timestamp($this->mTouched
),
2169 'user_token' => $this->mToken
,
2170 'user_email_token' => $this->mEmailToken
,
2171 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2172 ), array( /* WHERE */
2173 'user_id' => $this->mId
2176 wfRunHooks( 'UserSaveSettings', array( $this ) );
2177 $this->clearSharedCache();
2181 * Checks if a user with the given name exists, returns the ID.
2183 function idForName() {
2184 $s = trim( $this->getName() );
2185 if ( $s === '' ) return 0;
2187 $dbr = wfGetDB( DB_SLAVE
);
2188 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2189 if ( $id === false ) {
2196 * Add a user to the database, return the user object
2198 * @param string $name The user's name
2199 * @param array $params Associative array of non-default parameters to save to the database:
2200 * password The user's password. Password logins will be disabled if this is omitted.
2201 * newpassword A temporary password mailed to the user
2202 * email The user's email address
2203 * email_authenticated The email authentication timestamp
2204 * real_name The user's real name
2205 * options An associative array of non-default options
2206 * token Random authentication token. Do not set.
2207 * registration Registration timestamp. Do not set.
2209 * @return User object, or null if the username already exists
2211 static function createNew( $name, $params = array() ) {
2214 if ( isset( $params['options'] ) ) {
2215 $user->mOptions
= $params['options'] +
$user->mOptions
;
2216 unset( $params['options'] );
2218 $dbw = wfGetDB( DB_MASTER
);
2219 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2221 'user_id' => $seqVal,
2222 'user_name' => $name,
2223 'user_password' => $user->mPassword
,
2224 'user_newpassword' => $user->mNewpassword
,
2225 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2226 'user_email' => $user->mEmail
,
2227 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2228 'user_real_name' => $user->mRealName
,
2229 'user_options' => $user->encodeOptions(),
2230 'user_token' => $user->mToken
,
2231 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2232 'user_editcount' => 0,
2234 foreach ( $params as $name => $value ) {
2235 $fields["user_$name"] = $value;
2237 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2238 if ( $dbw->affectedRows() ) {
2239 $newUser = User
::newFromId( $dbw->insertId() );
2247 * Add an existing user object to the database
2249 function addToDatabase() {
2251 $dbw = wfGetDB( DB_MASTER
);
2252 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2253 $dbw->insert( 'user',
2255 'user_id' => $seqVal,
2256 'user_name' => $this->mName
,
2257 'user_password' => $this->mPassword
,
2258 'user_newpassword' => $this->mNewpassword
,
2259 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2260 'user_email' => $this->mEmail
,
2261 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2262 'user_real_name' => $this->mRealName
,
2263 'user_options' => $this->encodeOptions(),
2264 'user_token' => $this->mToken
,
2265 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2266 'user_editcount' => 0,
2269 $this->mId
= $dbw->insertId();
2271 # Clear instance cache other than user table data, which is already accurate
2272 $this->clearInstanceCache();
2276 * If the (non-anonymous) user is blocked, this function will block any IP address
2277 * that they successfully log on from.
2279 function spreadBlock() {
2280 wfDebug( __METHOD__
."()\n" );
2282 if ( $this->mId
== 0 ) {
2286 $userblock = Block
::newFromDB( '', $this->mId
);
2287 if ( !$userblock ) {
2291 $userblock->doAutoblock( wfGetIp() );
2296 * Generate a string which will be different for any combination of
2297 * user options which would produce different parser output.
2298 * This will be used as part of the hash key for the parser cache,
2299 * so users will the same options can share the same cached data
2302 * Extensions which require it should install 'PageRenderingHash' hook,
2303 * which will give them a chance to modify this key based on their own
2308 function getPageRenderingHash() {
2309 global $wgContLang, $wgUseDynamicDates, $wgLang;
2311 return $this->mHash
;
2314 // stubthreshold is only included below for completeness,
2315 // it will always be 0 when this function is called by parsercache.
2317 $confstr = $this->getOption( 'math' );
2318 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2319 if ( $wgUseDynamicDates ) {
2320 $confstr .= '!' . $this->getDatePreference();
2322 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2323 $confstr .= '!' . $wgLang->getCode();
2324 $confstr .= '!' . $this->getOption( 'thumbsize' );
2325 // add in language specific options, if any
2326 $extra = $wgContLang->getExtraHashOptions();
2329 // Give a chance for extensions to modify the hash, if they have
2330 // extra options or other effects on the parser cache.
2331 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2333 // Make it a valid memcached key fragment
2334 $confstr = str_replace( ' ', '_', $confstr );
2335 $this->mHash
= $confstr;
2339 function isBlockedFromCreateAccount() {
2340 $this->getBlockedStatus();
2341 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2345 * Determine if the user is blocked from using Special:Emailuser.
2350 function isBlockedFromEmailuser() {
2351 $this->getBlockedStatus();
2352 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2355 function isAllowedToCreateAccount() {
2356 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2362 function setLoaded( $loaded ) {
2363 wfDeprecated( __METHOD__
);
2367 * Get this user's personal page title.
2372 function getUserPage() {
2373 return Title
::makeTitle( NS_USER
, $this->getName() );
2377 * Get this user's talk page title.
2382 function getTalkPage() {
2383 $title = $this->getUserPage();
2384 return $title->getTalkPage();
2390 function getMaxID() {
2391 static $res; // cache
2393 if ( isset( $res ) )
2396 $dbr = wfGetDB( DB_SLAVE
);
2397 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2402 * Determine whether the user is a newbie. Newbies are either
2403 * anonymous IPs, or the most recently created accounts.
2404 * @return bool True if it is a newbie.
2406 function isNewbie() {
2407 return !$this->isAllowed( 'autoconfirmed' );
2411 * Check to see if the given clear-text password is one of the accepted passwords
2412 * @param string $password User password.
2413 * @return bool True if the given password is correct otherwise False.
2415 function checkPassword( $password ) {
2419 // Even though we stop people from creating passwords that
2420 // are shorter than this, doesn't mean people wont be able
2421 // to. Certain authentication plugins do NOT want to save
2422 // domain passwords in a mysql database, so we should
2423 // check this (incase $wgAuth->strict() is false).
2424 if( !$this->isValidPassword( $password ) ) {
2428 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2430 } elseif( $wgAuth->strict() ) {
2431 /* Auth plugin doesn't allow local authentication */
2433 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2434 /* Auth plugin doesn't allow local authentication for this user name */
2437 $ep = $this->encryptPassword( $password );
2438 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2440 } elseif ( function_exists( 'iconv' ) ) {
2441 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2442 # Check for this with iconv
2443 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2444 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2452 * Check if the given clear-text password matches the temporary password
2453 * sent by e-mail for password reset operations.
2456 function checkTemporaryPassword( $plaintext ) {
2457 $hash = $this->encryptPassword( $plaintext );
2458 return $hash === $this->mNewpassword
;
2462 * Initialize (if necessary) and return a session token value
2463 * which can be used in edit forms to show that the user's
2464 * login credentials aren't being hijacked with a foreign form
2467 * @param mixed $salt - Optional function-specific data for hash.
2468 * Use a string or an array of strings.
2472 function editToken( $salt = '' ) {
2473 if ( $this->isAnon() ) {
2474 return EDIT_TOKEN_SUFFIX
;
2476 if( !isset( $_SESSION['wsEditToken'] ) ) {
2477 $token = $this->generateToken();
2478 $_SESSION['wsEditToken'] = $token;
2480 $token = $_SESSION['wsEditToken'];
2482 if( is_array( $salt ) ) {
2483 $salt = implode( '|', $salt );
2485 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2490 * Generate a hex-y looking random token for various uses.
2491 * Could be made more cryptographically sure if someone cares.
2494 function generateToken( $salt = '' ) {
2495 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2496 return md5( $token . $salt );
2500 * Check given value against the token value stored in the session.
2501 * A match should confirm that the form was submitted from the
2502 * user's own login session, not a form submission from a third-party
2505 * @param string $val - the input value to compare
2506 * @param string $salt - Optional function-specific data for hash
2510 function matchEditToken( $val, $salt = '' ) {
2511 $sessionToken = $this->editToken( $salt );
2512 if ( $val != $sessionToken ) {
2513 wfDebug( "User::matchEditToken: broken session data\n" );
2515 return $val == $sessionToken;
2519 * Check whether the edit token is fine except for the suffix
2521 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2522 $sessionToken = $this->editToken( $salt );
2523 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2527 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2528 * mail to the user's given address.
2530 * Calls saveSettings() internally; as it has side effects, not committing changes
2531 * would be pretty silly.
2533 * @return mixed True on success, a WikiError object on failure.
2535 function sendConfirmationMail() {
2537 $expiration = null; // gets passed-by-ref and defined in next line.
2538 $token = $this->confirmationToken( $expiration );
2539 $url = $this->confirmationTokenUrl( $token );
2540 $invalidateURL = $this->invalidationTokenUrl( $token );
2541 $this->saveSettings();
2543 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2544 wfMsg( 'confirmemail_body',
2548 $wgLang->timeanddate( $expiration, false ),
2553 * Send an e-mail to this user's account. Does not check for
2554 * confirmed status or validity.
2556 * @param string $subject
2557 * @param string $body
2558 * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
2559 * @return mixed True on success, a WikiError object on failure.
2561 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2562 if( is_null( $from ) ) {
2563 global $wgPasswordSender;
2564 $from = $wgPasswordSender;
2567 $to = new MailAddress( $this );
2568 $sender = new MailAddress( $from );
2569 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2573 * Generate, store, and return a new e-mail confirmation code.
2574 * A hash (unsalted since it's used as a key) is stored.
2576 * Call saveSettings() after calling this function to commit
2577 * this change to the database.
2579 * @param &$expiration mixed output: accepts the expiration time
2583 function confirmationToken( &$expiration ) {
2585 $expires = $now +
7 * 24 * 60 * 60;
2586 $expiration = wfTimestamp( TS_MW
, $expires );
2587 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2588 $hash = md5( $token );
2590 $this->mEmailToken
= $hash;
2591 $this->mEmailTokenExpires
= $expiration;
2596 * Return a URL the user can use to confirm their email address.
2597 * @param $token: accepts the email confirmation token
2601 function confirmationTokenUrl( $token ) {
2602 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2603 return $title->getFullUrl();
2606 * Return a URL the user can use to invalidate their email address.
2607 * @param $token: accepts the email confirmation token
2611 function invalidationTokenUrl( $token ) {
2612 $title = SpecialPage
::getTitleFor( 'Invalidateemail', $token );
2613 return $title->getFullUrl();
2617 * Mark the e-mail address confirmed.
2619 * Call saveSettings() after calling this function to commit the change.
2621 function confirmEmail() {
2622 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2627 * Invalidate the user's email confirmation, unauthenticate the email
2628 * if it was already confirmed.
2630 * Call saveSettings() after calling this function to commit the change.
2632 function invalidateEmail() {
2634 $this->mEmailToken
= null;
2635 $this->mEmailTokenExpires
= null;
2636 $this->setEmailAuthenticationTimestamp( null );
2640 function setEmailAuthenticationTimestamp( $timestamp ) {
2642 $this->mEmailAuthenticated
= $timestamp;
2643 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2647 * Is this user allowed to send e-mails within limits of current
2648 * site configuration?
2651 function canSendEmail() {
2652 $canSend = $this->isEmailConfirmed();
2653 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2658 * Is this user allowed to receive e-mails within limits of current
2659 * site configuration?
2662 function canReceiveEmail() {
2663 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2667 * Is this user's e-mail address valid-looking and confirmed within
2668 * limits of the current site configuration?
2670 * If $wgEmailAuthentication is on, this may require the user to have
2671 * confirmed their address by returning a code or using a password
2672 * sent to the address from the wiki.
2676 function isEmailConfirmed() {
2677 global $wgEmailAuthentication;
2680 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2681 if( $this->isAnon() )
2683 if( !self
::isValidEmailAddr( $this->mEmail
) )
2685 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2694 * Return true if there is an outstanding request for e-mail confirmation.
2697 function isEmailConfirmationPending() {
2698 global $wgEmailAuthentication;
2699 return $wgEmailAuthentication &&
2700 !$this->isEmailConfirmed() &&
2701 $this->mEmailToken
&&
2702 $this->mEmailTokenExpires
> wfTimestamp();
2706 * Get the timestamp of account creation, or false for
2707 * non-existent/anonymous user accounts
2711 public function getRegistration() {
2712 return $this->mId
> 0
2713 ?
$this->mRegistration
2718 * @param array $groups list of groups
2719 * @return array list of permission key names for given groups combined
2721 static function getGroupPermissions( $groups ) {
2722 global $wgGroupPermissions;
2724 foreach( $groups as $group ) {
2725 if( isset( $wgGroupPermissions[$group] ) ) {
2726 $rights = array_merge( $rights,
2727 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2734 * @param string $group key name
2735 * @return string localized descriptive name for group, if provided
2737 static function getGroupName( $group ) {
2738 global $wgMessageCache;
2739 $wgMessageCache->loadAllMessages();
2740 $key = "group-$group";
2741 $name = wfMsg( $key );
2742 return $name == '' ||
wfEmptyMsg( $key, $name )
2748 * @param string $group key name
2749 * @return string localized descriptive name for member of a group, if provided
2751 static function getGroupMember( $group ) {
2752 global $wgMessageCache;
2753 $wgMessageCache->loadAllMessages();
2754 $key = "group-$group-member";
2755 $name = wfMsg( $key );
2756 return $name == '' ||
wfEmptyMsg( $key, $name )
2762 * Return the set of defined explicit groups.
2763 * The implicit groups (by default *, 'user' and 'autoconfirmed')
2764 * are not included, as they are defined automatically,
2765 * not in the database.
2768 static function getAllGroups() {
2769 global $wgGroupPermissions;
2771 array_keys( $wgGroupPermissions ),
2772 self
::getImplicitGroups()
2777 * Get a list of all available permissions
2779 static function getAllRights() {
2780 if ( self
::$mAllRights === false ) {
2781 global $wgAvailableRights;
2782 if ( count( $wgAvailableRights ) ) {
2783 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
2785 self
::$mAllRights = self
::$mCoreRights;
2787 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
2789 return self
::$mAllRights;
2793 * Get a list of implicit groups
2797 public static function getImplicitGroups() {
2798 global $wgImplicitGroups;
2799 $groups = $wgImplicitGroups;
2800 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
2805 * Get the title of a page describing a particular group
2807 * @param $group Name of the group
2810 static function getGroupPage( $group ) {
2811 global $wgMessageCache;
2812 $wgMessageCache->loadAllMessages();
2813 $page = wfMsgForContent( 'grouppage-' . $group );
2814 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2815 $title = Title
::newFromText( $page );
2816 if( is_object( $title ) )
2823 * Create a link to the group in HTML, if available
2825 * @param $group Name of the group
2826 * @param $text The text of the link
2829 static function makeGroupLinkHTML( $group, $text = '' ) {
2831 $text = self
::getGroupName( $group );
2833 $title = self
::getGroupPage( $group );
2836 $sk = $wgUser->getSkin();
2837 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2844 * Create a link to the group in Wikitext, if available
2846 * @param $group Name of the group
2847 * @param $text The text of the link (by default, the name of the group)
2850 static function makeGroupLinkWiki( $group, $text = '' ) {
2852 $text = self
::getGroupName( $group );
2854 $title = self
::getGroupPage( $group );
2856 $page = $title->getPrefixedText();
2857 return "[[$page|$text]]";
2864 * Increment the user's edit-count field.
2865 * Will have no effect for anonymous users.
2867 function incEditCount() {
2868 if( !$this->isAnon() ) {
2869 $dbw = wfGetDB( DB_MASTER
);
2870 $dbw->update( 'user',
2871 array( 'user_editcount=user_editcount+1' ),
2872 array( 'user_id' => $this->getId() ),
2875 // Lazy initialization check...
2876 if( $dbw->affectedRows() == 0 ) {
2877 // Pull from a slave to be less cruel to servers
2878 // Accuracy isn't the point anyway here
2879 $dbr = wfGetDB( DB_SLAVE
);
2880 $count = $dbr->selectField( 'revision',
2882 array( 'rev_user' => $this->getId() ),
2885 // Now here's a goddamn hack...
2886 if( $dbr !== $dbw ) {
2887 // If we actually have a slave server, the count is
2888 // at least one behind because the current transaction
2889 // has not been committed and replicated.
2892 // But if DB_SLAVE is selecting the master, then the
2893 // count we just read includes the revision that was
2894 // just added in the working transaction.
2897 $dbw->update( 'user',
2898 array( 'user_editcount' => $count ),
2899 array( 'user_id' => $this->getId() ),
2903 // edit count in user cache too
2904 $this->invalidateCache();
2907 static function getRightDescription( $right ) {
2908 global $wgMessageCache;
2909 $wgMessageCache->loadAllMessages();
2910 $key = "right-$right";
2911 $name = wfMsg( $key );
2912 return $name == '' ||
wfEmptyMsg( $key, $name )