7 # Number of characters in user_token field
8 define( 'USER_TOKEN_LENGTH', 32 );
10 # Serialized record version
11 define( 'MW_USER_VERSION', 5 );
13 # Some punctuation to prevent editing from broken text-mangling proxies.
14 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
17 * Thrown by User::setPassword() on error
18 * @addtogroup Exception
20 class PasswordError
extends MWException
{
25 * The User object encapsulates all of the user-specific settings (user_id,
26 * name, rights, password, email address, options, last login time). Client
27 * classes use the getXXX() functions to access these fields. These functions
28 * do all the work of determining whether the user is logged in,
29 * whether the requested option can be satisfied from cookies or
30 * whether a database query is needed. Most of the settings needed
31 * for rendering normal pages are set in the cookie to minimize use
37 * A list of default user toggles, i.e. boolean user preferences that are
38 * displayed by Special:Preferences as checkboxes. This list can be
39 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
41 static public $mToggles = array(
51 'editsectiononrightclick',
63 'enotifwatchlistpages',
64 'enotifusertalkpages',
67 'shownumberswatching',
83 * List of member variables which are saved to the shared cache (memcached).
84 * Any operation which changes the corresponding database fields must
85 * call a cache-clearing function.
87 static $mCacheVars = array(
99 'mEmailAuthenticated',
101 'mEmailTokenExpires',
109 * The cache variable declarations
111 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
112 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
113 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
116 * Whether the cache variables have been loaded
121 * Initialisation data source if mDataLoaded==false. May be one of:
122 * defaults anonymous user initialised from class defaults
123 * name initialise from mName
124 * id initialise from mId
125 * session log in from cookies or session if possible
127 * Use the User::newFrom*() family of functions to set this.
132 * Lazy-initialised variables, invalidated with clearInstanceCache
134 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
135 $mBlockreason, $mBlock, $mEffectiveGroups;
138 * Lightweight constructor for anonymous user
139 * Use the User::newFrom* factory functions for other kinds of users
142 $this->clearInstanceCache( 'defaults' );
146 * Load the user table data for this object from the source given by mFrom
149 if ( $this->mDataLoaded
) {
152 wfProfileIn( __METHOD__
);
154 # Set it now to avoid infinite recursion in accessors
155 $this->mDataLoaded
= true;
157 switch ( $this->mFrom
) {
159 $this->loadDefaults();
162 $this->mId
= self
::idFromName( $this->mName
);
164 # Nonexistent user placeholder object
165 $this->loadDefaults( $this->mName
);
174 $this->loadFromSession();
177 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
179 wfProfileOut( __METHOD__
);
183 * Load user table data given mId
184 * @return false if the ID does not exist, true otherwise
187 function loadFromId() {
189 if ( $this->mId
== 0 ) {
190 $this->loadDefaults();
195 $key = wfMemcKey( 'user', 'id', $this->mId
);
196 $data = $wgMemc->get( $key );
197 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
198 # Object is expired, load from DB
203 wfDebug( "Cache miss for user {$this->mId}\n" );
205 if ( !$this->loadFromDatabase() ) {
206 # Can't load from ID, user is anonymous
209 $this->saveToCache();
211 wfDebug( "Got user {$this->mId} from cache\n" );
213 foreach ( self
::$mCacheVars as $name ) {
214 $this->$name = $data[$name];
221 * Save user data to the shared cache
223 function saveToCache() {
226 if ( $this->isAnon() ) {
227 // Anonymous users are uncached
231 foreach ( self
::$mCacheVars as $name ) {
232 $data[$name] = $this->$name;
234 $data['mVersion'] = MW_USER_VERSION
;
235 $key = wfMemcKey( 'user', 'id', $this->mId
);
237 $wgMemc->set( $key, $data );
241 * Static factory method for creation from username.
243 * This is slightly less efficient than newFromId(), so use newFromId() if
244 * you have both an ID and a name handy.
246 * @param string $name Username, validated by Title:newFromText()
247 * @param mixed $validate Validate username. Takes the same parameters as
248 * User::getCanonicalName(), except that true is accepted as an alias
249 * for 'valid', for BC.
251 * @return User object, or null if the username is invalid. If the username
252 * is not present in the database, the result will be a user object with
253 * a name, zero user ID and default settings.
256 static function newFromName( $name, $validate = 'valid' ) {
257 if ( $validate === true ) {
260 $name = self
::getCanonicalName( $name, $validate );
261 if ( $name === false ) {
264 # Create unloaded user object
272 static function newFromId( $id ) {
280 * Factory method to fetch whichever user has a given email confirmation code.
281 * This code is generated when an account is created or its e-mail address
284 * If the code is invalid or has expired, returns NULL.
286 * @param string $code
290 static function newFromConfirmationCode( $code ) {
291 $dbr = wfGetDB( DB_SLAVE
);
292 $id = $dbr->selectField( 'user', 'user_id', array(
293 'user_email_token' => md5( $code ),
294 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
296 if( $id !== false ) {
297 return User
::newFromId( $id );
304 * Create a new user object using data from session or cookies. If the
305 * login credentials are invalid, the result is an anonymous user.
310 static function newFromSession() {
312 $user->mFrom
= 'session';
317 * Create a new user object from a user row.
318 * The row should have all fields from the user table in it.
320 static function newFromRow( $row ) {
322 $user->loadFromRow( $row );
327 * Get username given an id.
328 * @param integer $id Database user id
329 * @return string Nickname of a user
332 static function whoIs( $id ) {
333 $dbr = wfGetDB( DB_SLAVE
);
334 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
338 * Get the real name of a user given their identifier
340 * @param int $id Database user id
341 * @return string Real name of a user
343 static function whoIsReal( $id ) {
344 $dbr = wfGetDB( DB_SLAVE
);
345 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
349 * Get database id given a user name
350 * @param string $name Nickname of a user
351 * @return integer|null Database user id (null: if non existent
354 static function idFromName( $name ) {
355 $nt = Title
::newFromText( $name );
356 if( is_null( $nt ) ) {
360 $dbr = wfGetDB( DB_SLAVE
);
361 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
363 if ( $s === false ) {
371 * Does the string match an anonymous IPv4 address?
373 * This function exists for username validation, in order to reject
374 * usernames which are similar in form to IP addresses. Strings such
375 * as 300.300.300.300 will return true because it looks like an IP
376 * address, despite not being strictly valid.
378 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
379 * address because the usemod software would "cloak" anonymous IP
380 * addresses like this, if we allowed accounts like this to be created
381 * new users could get the old edits of these anonymous users.
384 * @param string $name Nickname of a user
387 static function isIP( $name ) {
388 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User
::isIPv6($name);
389 /*return preg_match("/^
390 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
391 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
392 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
393 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
398 * Check if $name is an IPv6 IP.
400 static function isIPv6($name) {
402 * if it has any non-valid characters, it can't be a valid IPv6
405 if (preg_match("/[^:a-fA-F0-9]/", $name))
408 $parts = explode(":", $name);
409 if (count($parts) < 3)
411 foreach ($parts as $part) {
412 if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part))
419 * Is the input a valid username?
421 * Checks if the input is a valid username, we don't want an empty string,
422 * an IP address, anything that containins slashes (would mess up subpages),
423 * is longer than the maximum allowed username size or doesn't begin with
426 * @param string $name
430 static function isValidUserName( $name ) {
431 global $wgContLang, $wgMaxNameChars;
434 || User
::isIP( $name )
435 ||
strpos( $name, '/' ) !== false
436 ||
strlen( $name ) > $wgMaxNameChars
437 ||
$name != $wgContLang->ucfirst( $name ) ) {
438 wfDebugLog( 'username', __METHOD__
.
439 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
443 // Ensure that the name can't be misresolved as a different title,
444 // such as with extra namespace keys at the start.
445 $parsed = Title
::newFromText( $name );
446 if( is_null( $parsed )
447 ||
$parsed->getNamespace()
448 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
449 wfDebugLog( 'username', __METHOD__
.
450 ": '$name' invalid due to ambiguous prefixes" );
454 // Check an additional blacklist of troublemaker characters.
455 // Should these be merged into the title char list?
456 $unicodeBlacklist = '/[' .
457 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
458 '\x{00a0}' . # non-breaking space
459 '\x{2000}-\x{200f}' . # various whitespace
460 '\x{2028}-\x{202f}' . # breaks and control chars
461 '\x{3000}' . # ideographic space
462 '\x{e000}-\x{f8ff}' . # private use
464 if( preg_match( $unicodeBlacklist, $name ) ) {
465 wfDebugLog( 'username', __METHOD__
.
466 ": '$name' invalid due to blacklisted characters" );
474 * Usernames which fail to pass this function will be blocked
475 * from user login and new account registrations, but may be used
476 * internally by batch processes.
478 * If an account already exists in this form, login will be blocked
479 * by a failure to pass this function.
481 * @param string $name
484 static function isUsableName( $name ) {
485 global $wgReservedUsernames;
487 // Must be a valid username, obviously ;)
488 self
::isValidUserName( $name ) &&
490 // Certain names may be reserved for batch processes.
491 !in_array( $name, $wgReservedUsernames );
495 * Usernames which fail to pass this function will be blocked
496 * from new account registrations, but may be used internally
497 * either by batch processes or by user accounts which have
498 * already been created.
500 * Additional character blacklisting may be added here
501 * rather than in isValidUserName() to avoid disrupting
504 * @param string $name
507 static function isCreatableName( $name ) {
509 self
::isUsableName( $name ) &&
511 // Registration-time character blacklisting...
512 strpos( $name, '@' ) === false;
516 * Is the input a valid password for this user?
518 * @param string $password Desired password
521 function isValidPassword( $password ) {
522 global $wgMinimalPasswordLength, $wgContLang;
525 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
527 if( $result === false )
530 // Password needs to be long enough, and can't be the same as the username
531 return strlen( $password ) >= $wgMinimalPasswordLength
532 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
536 * Does a string look like an email address?
538 * There used to be a regular expression here, it got removed because it
539 * rejected valid addresses. Actually just check if there is '@' somewhere
540 * in the given address.
542 * @todo Check for RFC 2822 compilance (bug 959)
544 * @param string $addr email address
547 public static function isValidEmailAddr( $addr ) {
549 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
553 return strpos( $addr, '@' ) !== false;
557 * Given unvalidated user input, return a canonical username, or false if
558 * the username is invalid.
559 * @param string $name
560 * @param mixed $validate Type of validation to use:
561 * false No validation
562 * 'valid' Valid for batch processes
563 * 'usable' Valid for batch processes and login
564 * 'creatable' Valid for batch processes, login and account creation
566 static function getCanonicalName( $name, $validate = 'valid' ) {
567 # Force usernames to capital
569 $name = $wgContLang->ucfirst( $name );
571 # Reject names containing '#'; these will be cleaned up
572 # with title normalisation, but then it's too late to
574 if( strpos( $name, '#' ) !== false )
577 # Clean up name according to title rules
578 $t = Title
::newFromText( $name );
579 if( is_null( $t ) ) {
583 # Reject various classes of invalid names
584 $name = $t->getText();
586 $name = $wgAuth->getCanonicalName( $t->getText() );
588 switch ( $validate ) {
592 if ( !User
::isValidUserName( $name ) ) {
597 if ( !User
::isUsableName( $name ) ) {
602 if ( !User
::isCreatableName( $name ) ) {
607 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
613 * Count the number of edits of a user
615 * It should not be static and some day should be merged as proper member function / deprecated -- domas
617 * @param int $uid The user ID to check
621 static function edits( $uid ) {
622 wfProfileIn( __METHOD__
);
623 $dbr = wfGetDB( DB_SLAVE
);
624 // check if the user_editcount field has been initialized
625 $field = $dbr->selectField(
626 'user', 'user_editcount',
627 array( 'user_id' => $uid ),
631 if( $field === null ) { // it has not been initialized. do so.
632 $dbw = wfGetDB( DB_MASTER
);
633 $count = $dbr->selectField(
634 'revision', 'count(*)',
635 array( 'rev_user' => $uid ),
640 array( 'user_editcount' => $count ),
641 array( 'user_id' => $uid ),
647 wfProfileOut( __METHOD__
);
652 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
653 * @todo hash random numbers to improve security, like generateToken()
658 static function randomPassword() {
659 global $wgMinimalPasswordLength;
660 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
661 $l = strlen( $pwchars ) - 1;
663 $pwlength = max( 7, $wgMinimalPasswordLength );
664 $digit = mt_rand(0, $pwlength - 1);
666 for ( $i = 0; $i < $pwlength; $i++
) {
667 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
673 * Set cached properties to default. Note: this no longer clears
674 * uncached lazy-initialised properties. The constructor does that instead.
678 function loadDefaults( $name = false ) {
679 wfProfileIn( __METHOD__
);
681 global $wgCookiePrefix;
684 $this->mName
= $name;
685 $this->mRealName
= '';
686 $this->mPassword
= $this->mNewpassword
= '';
687 $this->mNewpassTime
= null;
689 $this->mOptions
= null; # Defer init
691 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
692 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
694 $this->mTouched
= '0'; # Allow any pages to be cached
697 $this->setToken(); # Random
698 $this->mEmailAuthenticated
= null;
699 $this->mEmailToken
= '';
700 $this->mEmailTokenExpires
= null;
701 $this->mRegistration
= wfTimestamp( TS_MW
);
702 $this->mGroups
= array();
704 wfProfileOut( __METHOD__
);
708 * Initialise php session
709 * @deprecated use wfSetupSession()
711 function SetupSession() {
712 wfDeprecated( __METHOD__
);
717 * Load user data from the session or login cookie. If there are no valid
718 * credentials, initialises the user as an anon.
719 * @return true if the user is logged in, false otherwise
721 private function loadFromSession() {
722 global $wgMemc, $wgCookiePrefix;
724 if ( isset( $_SESSION['wsUserID'] ) ) {
725 if ( 0 != $_SESSION['wsUserID'] ) {
726 $sId = $_SESSION['wsUserID'];
728 $this->loadDefaults();
731 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
732 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
733 $_SESSION['wsUserID'] = $sId;
735 $this->loadDefaults();
738 if ( isset( $_SESSION['wsUserName'] ) ) {
739 $sName = $_SESSION['wsUserName'];
740 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
741 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
742 $_SESSION['wsUserName'] = $sName;
744 $this->loadDefaults();
748 $passwordCorrect = FALSE;
750 if ( !$this->loadFromId() ) {
751 # Not a valid ID, loadFromId has switched the object to anon for us
755 if ( isset( $_SESSION['wsToken'] ) ) {
756 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
758 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
759 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
762 # No session or persistent login cookie
763 $this->loadDefaults();
767 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
768 $_SESSION['wsToken'] = $this->mToken
;
769 wfDebug( "Logged in from $from\n" );
772 # Invalid credentials
773 wfDebug( "Can't log in from $from, invalid credentials\n" );
774 $this->loadDefaults();
780 * Load user and user_group data from the database
781 * $this->mId must be set, this is how the user is identified.
783 * @return true if the user exists, false if the user is anonymous
786 function loadFromDatabase() {
788 $this->mId
= intval( $this->mId
);
790 /** Anonymous user */
792 $this->loadDefaults();
796 $dbr = wfGetDB( DB_MASTER
);
797 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
799 if ( $s !== false ) {
800 # Initialise user table data
801 $this->loadFromRow( $s );
802 $this->mGroups
= null; // deferred
803 $this->getEditCount(); // revalidation for nulls
808 $this->loadDefaults();
814 * Initialise the user object from a row from the user table
816 function loadFromRow( $row ) {
817 $this->mDataLoaded
= true;
819 if ( isset( $row->user_id
) ) {
820 $this->mId
= $row->user_id
;
822 $this->mName
= $row->user_name
;
823 $this->mRealName
= $row->user_real_name
;
824 $this->mPassword
= $row->user_password
;
825 $this->mNewpassword
= $row->user_newpassword
;
826 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
827 $this->mEmail
= $row->user_email
;
828 $this->decodeOptions( $row->user_options
);
829 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
830 $this->mToken
= $row->user_token
;
831 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
832 $this->mEmailToken
= $row->user_email_token
;
833 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
834 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
835 $this->mEditCount
= $row->user_editcount
;
839 * Load the groups from the database if they aren't already loaded
842 function loadGroups() {
843 if ( is_null( $this->mGroups
) ) {
844 $dbr = wfGetDB( DB_MASTER
);
845 $res = $dbr->select( 'user_groups',
847 array( 'ug_user' => $this->mId
),
849 $this->mGroups
= array();
850 while( $row = $dbr->fetchObject( $res ) ) {
851 $this->mGroups
[] = $row->ug_group
;
857 * Clear various cached data stored in this object.
858 * @param string $reloadFrom Reload user and user_groups table data from a
859 * given source. May be "name", "id", "defaults", "session" or false for
862 function clearInstanceCache( $reloadFrom = false ) {
863 $this->mNewtalk
= -1;
864 $this->mDatePreference
= null;
865 $this->mBlockedby
= -1; # Unset
866 $this->mHash
= false;
868 $this->mRights
= null;
869 $this->mEffectiveGroups
= null;
872 $this->mDataLoaded
= false;
873 $this->mFrom
= $reloadFrom;
878 * Combine the language default options with any site-specific options
879 * and add the default language variants.
880 * Not really private cause it's called by Language class
885 static function getDefaultOptions() {
886 global $wgNamespacesToBeSearchedDefault;
888 * Site defaults will override the global/language defaults
890 global $wgDefaultUserOptions, $wgContLang;
891 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
894 * default language setting
896 $variant = $wgContLang->getPreferredVariant( false );
897 $defOpt['variant'] = $variant;
898 $defOpt['language'] = $variant;
900 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
901 $defOpt['searchNs'.$nsnum] = $val;
907 * Get a given default option value.
914 function getDefaultOption( $opt ) {
915 $defOpts = User
::getDefaultOptions();
916 if( isset( $defOpts[$opt] ) ) {
917 return $defOpts[$opt];
924 * Get a list of user toggle names
927 static function getToggles() {
929 $extraToggles = array();
930 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
931 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
936 * Get blocking information
938 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
939 * non-critical checks are done against slaves. Check when actually saving should be done against
942 function getBlockedStatus( $bFromSlave = true ) {
943 global $wgEnableSorbs, $wgProxyWhitelist;
945 if ( -1 != $this->mBlockedby
) {
946 wfDebug( "User::getBlockedStatus: already loaded.\n" );
950 wfProfileIn( __METHOD__
);
951 wfDebug( __METHOD__
.": checking...\n" );
953 $this->mBlockedby
= 0;
954 $this->mHideName
= 0;
957 if ($this->isAllowed( 'ipblock-exempt' ) ) {
958 # Exempt from all types of IP-block
963 $this->mBlock
= new Block();
964 $this->mBlock
->fromMaster( !$bFromSlave );
965 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
966 wfDebug( __METHOD__
.": Found block.\n" );
967 $this->mBlockedby
= $this->mBlock
->mBy
;
968 $this->mBlockreason
= $this->mBlock
->mReason
;
969 $this->mHideName
= $this->mBlock
->mHideName
;
970 if ( $this->isLoggedIn() ) {
971 $this->spreadBlock();
974 $this->mBlock
= null;
975 wfDebug( __METHOD__
.": No block.\n" );
979 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
982 if ( wfIsLocallyBlockedProxy( $ip ) ) {
983 $this->mBlockedby
= wfMsg( 'proxyblocker' );
984 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
988 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
989 if ( $this->inSorbsBlacklist( $ip ) ) {
990 $this->mBlockedby
= wfMsg( 'sorbs' );
991 $this->mBlockreason
= wfMsg( 'sorbsreason' );
997 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
999 wfProfileOut( __METHOD__
);
1002 function inSorbsBlacklist( $ip ) {
1003 global $wgEnableSorbs, $wgSorbsUrl;
1005 return $wgEnableSorbs &&
1006 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1009 function inDnsBlacklist( $ip, $base ) {
1010 wfProfileIn( __METHOD__
);
1016 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
1018 for ( $i=4; $i>=1; $i-- ) {
1019 $host .= $m[$i] . '.';
1024 $ipList = gethostbynamel( $host );
1027 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1030 wfDebug( "Requested $host, not found in $base.\n" );
1034 wfProfileOut( __METHOD__
);
1039 * Is this user subject to rate limiting?
1043 public function isPingLimitable() {
1044 global $wgRateLimitsExcludedGroups;
1045 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
1049 * Primitive rate limits: enforce maximum actions per time period
1050 * to put a brake on flooding.
1052 * Note: when using a shared cache like memcached, IP-address
1053 * last-hit counters will be shared across wikis.
1055 * @return bool true if a rate limiter was tripped
1058 function pingLimiter( $action='edit' ) {
1060 # Call the 'PingLimiter' hook
1062 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1066 global $wgRateLimits;
1067 if( !isset( $wgRateLimits[$action] ) ) {
1071 # Some groups shouldn't trigger the ping limiter, ever
1072 if( !$this->isPingLimitable() )
1075 global $wgMemc, $wgRateLimitLog;
1076 wfProfileIn( __METHOD__
);
1078 $limits = $wgRateLimits[$action];
1080 $id = $this->getId();
1083 if( isset( $limits['anon'] ) && $id == 0 ) {
1084 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1087 if( isset( $limits['user'] ) && $id != 0 ) {
1088 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
1090 if( $this->isNewbie() ) {
1091 if( isset( $limits['newbie'] ) && $id != 0 ) {
1092 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1094 if( isset( $limits['ip'] ) ) {
1095 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1098 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1099 $subnet = $matches[1];
1100 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1105 foreach( $keys as $key => $limit ) {
1106 list( $max, $period ) = $limit;
1107 $summary = "(limit $max in {$period}s)";
1108 $count = $wgMemc->get( $key );
1110 if( $count > $max ) {
1111 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1112 if( $wgRateLimitLog ) {
1113 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1117 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1120 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1121 $wgMemc->add( $key, 1, intval( $period ) );
1123 $wgMemc->incr( $key );
1126 wfProfileOut( __METHOD__
);
1131 * Check if user is blocked
1132 * @return bool True if blocked, false otherwise
1134 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1135 wfDebug( "User::isBlocked: enter\n" );
1136 $this->getBlockedStatus( $bFromSlave );
1137 return $this->mBlockedby
!== 0;
1141 * Check if user is blocked from editing a particular article
1143 function isBlockedFrom( $title, $bFromSlave = false ) {
1144 global $wgBlockAllowsUTEdit;
1145 wfProfileIn( __METHOD__
);
1146 wfDebug( __METHOD__
.": enter\n" );
1148 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1149 $blocked = $this->isBlocked( $bFromSlave );
1150 # If a user's name is suppressed, they cannot make edits anywhere
1151 if ( !$this->mHideName
&& $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1152 $title->getNamespace() == NS_USER_TALK
) {
1154 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1156 wfProfileOut( __METHOD__
);
1161 * Get name of blocker
1162 * @return string name of blocker
1164 function blockedBy() {
1165 $this->getBlockedStatus();
1166 return $this->mBlockedby
;
1170 * Get blocking reason
1171 * @return string Blocking reason
1173 function blockedFor() {
1174 $this->getBlockedStatus();
1175 return $this->mBlockreason
;
1179 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1182 if( $this->mId
=== null and $this->mName
!== null
1183 and User
::isIP( $this->mName
) ) {
1184 // Special case, we know the user is anonymous
1186 } elseif( $this->mId
=== null ) {
1187 // Don't load if this was initialized from an ID
1194 * Set the user and reload all fields according to that ID
1195 * @deprecated use User::newFromId()
1197 function setID( $v ) {
1198 wfDeprecated( __METHOD__
);
1200 $this->clearInstanceCache( 'id' );
1204 * Get the user name, or the IP for anons
1206 function getName() {
1207 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1208 # Special case optimisation
1209 return $this->mName
;
1212 if ( $this->mName
=== false ) {
1214 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1216 return $this->mName
;
1221 * Set the user name.
1223 * This does not reload fields from the database according to the given
1224 * name. Rather, it is used to create a temporary "nonexistent user" for
1225 * later addition to the database. It can also be used to set the IP
1226 * address for an anonymous user to something other than the current
1229 * User::newFromName() has rougly the same function, when the named user
1232 function setName( $str ) {
1234 $this->mName
= $str;
1238 * Return the title dbkey form of the name, for eg user pages.
1242 function getTitleKey() {
1243 return str_replace( ' ', '_', $this->getName() );
1246 function getNewtalk() {
1249 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1250 if( $this->mNewtalk
=== -1 ) {
1251 $this->mNewtalk
= false; # reset talk page status
1253 # Check memcached separately for anons, who have no
1254 # entire User object stored in there.
1257 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1258 $newtalk = $wgMemc->get( $key );
1259 if( strval( $newtalk ) !== '' ) {
1260 $this->mNewtalk
= (bool)$newtalk;
1262 // Since we are caching this, make sure it is up to date by getting it
1264 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1265 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1268 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1272 return (bool)$this->mNewtalk
;
1276 * Return the talk page(s) this user has new messages on.
1278 function getNewMessageLinks() {
1280 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1283 if (!$this->getNewtalk())
1285 $up = $this->getUserPage();
1286 $utp = $up->getTalkPage();
1287 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1292 * Perform a user_newtalk check, uncached.
1293 * Use getNewtalk for a cached check.
1295 * @param string $field
1297 * @param bool $fromMaster True to fetch from the master, false for a slave
1301 function checkNewtalk( $field, $id, $fromMaster = false ) {
1302 if ( $fromMaster ) {
1303 $db = wfGetDB( DB_MASTER
);
1305 $db = wfGetDB( DB_SLAVE
);
1307 $ok = $db->selectField( 'user_newtalk', $field,
1308 array( $field => $id ), __METHOD__
);
1309 return $ok !== false;
1314 * @param string $field
1318 function updateNewtalk( $field, $id ) {
1319 $dbw = wfGetDB( DB_MASTER
);
1320 $dbw->insert( 'user_newtalk',
1321 array( $field => $id ),
1324 if ( $dbw->affectedRows() ) {
1325 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1328 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1334 * Clear the new messages flag for the given user
1335 * @param string $field
1339 function deleteNewtalk( $field, $id ) {
1340 $dbw = wfGetDB( DB_MASTER
);
1341 $dbw->delete( 'user_newtalk',
1342 array( $field => $id ),
1344 if ( $dbw->affectedRows() ) {
1345 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1348 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1354 * Update the 'You have new messages!' status.
1357 function setNewtalk( $val ) {
1358 if( wfReadOnly() ) {
1363 $this->mNewtalk
= $val;
1365 if( $this->isAnon() ) {
1367 $id = $this->getName();
1370 $id = $this->getId();
1375 $changed = $this->updateNewtalk( $field, $id );
1377 $changed = $this->deleteNewtalk( $field, $id );
1380 if( $this->isAnon() ) {
1381 // Anons have a separate memcached space, since
1382 // user records aren't kept for them.
1383 $key = wfMemcKey( 'newtalk', 'ip', $id );
1384 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1387 $this->invalidateCache();
1392 * Generate a current or new-future timestamp to be stored in the
1393 * user_touched field when we update things.
1395 private static function newTouchedTimestamp() {
1396 global $wgClockSkewFudge;
1397 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1401 * Clear user data from memcached.
1402 * Use after applying fun updates to the database; caller's
1403 * responsibility to update user_touched if appropriate.
1405 * Called implicitly from invalidateCache() and saveSettings().
1407 private function clearSharedCache() {
1410 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1415 * Immediately touch the user data cache for this account.
1416 * Updates user_touched field, and removes account data from memcached
1417 * for reload on the next hit.
1419 function invalidateCache() {
1422 $this->mTouched
= self
::newTouchedTimestamp();
1424 $dbw = wfGetDB( DB_MASTER
);
1425 $dbw->update( 'user',
1426 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1427 array( 'user_id' => $this->mId
),
1430 $this->clearSharedCache();
1434 function validateCache( $timestamp ) {
1436 return ($timestamp >= $this->mTouched
);
1440 * Encrypt a password.
1441 * It can eventually salt a password.
1442 * @see User::addSalt()
1443 * @param string $p clear Password.
1444 * @return string Encrypted password.
1446 function encryptPassword( $p ) {
1448 return wfEncryptPassword( $this->mId
, $p );
1452 * Set the password and reset the random token
1453 * Calls through to authentication plugin if necessary;
1454 * will have no effect if the auth plugin refuses to
1455 * pass the change through or if the legal password
1458 * As a special case, setting the password to null
1459 * wipes it, so the account cannot be logged in until
1460 * a new password is set, for instance via e-mail.
1462 * @param string $str
1463 * @throws PasswordError on failure
1465 function setPassword( $str ) {
1468 if( $str !== null ) {
1469 if( !$wgAuth->allowPasswordChange() ) {
1470 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1473 if( !$this->isValidPassword( $str ) ) {
1474 global $wgMinimalPasswordLength;
1475 throw new PasswordError( wfMsg( 'passwordtooshort',
1476 $wgMinimalPasswordLength ) );
1480 if( !$wgAuth->setPassword( $this, $str ) ) {
1481 throw new PasswordError( wfMsg( 'externaldberror' ) );
1484 $this->setInternalPassword( $str );
1490 * Set the password and reset the random token no matter
1493 * @param string $str
1495 function setInternalPassword( $str ) {
1499 if( $str === null ) {
1500 // Save an invalid hash...
1501 $this->mPassword
= '';
1503 $this->mPassword
= $this->encryptPassword( $str );
1505 $this->mNewpassword
= '';
1506 $this->mNewpassTime
= null;
1509 * Set the random token (used for persistent authentication)
1510 * Called from loadDefaults() among other places.
1513 function setToken( $token = false ) {
1514 global $wgSecretKey, $wgProxyKey;
1517 if ( $wgSecretKey ) {
1518 $key = $wgSecretKey;
1519 } elseif ( $wgProxyKey ) {
1524 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1526 $this->mToken
= $token;
1530 function setCookiePassword( $str ) {
1532 $this->mCookiePassword
= md5( $str );
1536 * Set the password for a password reminder or new account email
1537 * Sets the user_newpass_time field if $throttle is true
1539 function setNewpassword( $str, $throttle = true ) {
1541 $this->mNewpassword
= $this->encryptPassword( $str );
1543 $this->mNewpassTime
= wfTimestampNow();
1548 * Returns true if a password reminder email has already been sent within
1549 * the last $wgPasswordReminderResendTime hours
1551 function isPasswordReminderThrottled() {
1552 global $wgPasswordReminderResendTime;
1554 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1557 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1558 return time() < $expiry;
1561 function getEmail() {
1563 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1564 return $this->mEmail
;
1567 function getEmailAuthenticationTimestamp() {
1569 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1570 return $this->mEmailAuthenticated
;
1573 function setEmail( $str ) {
1575 $this->mEmail
= $str;
1576 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1579 function getRealName() {
1581 return $this->mRealName
;
1584 function setRealName( $str ) {
1586 $this->mRealName
= $str;
1590 * @param string $oname The option to check
1591 * @param string $defaultOverride A default value returned if the option does not exist
1594 function getOption( $oname, $defaultOverride = '' ) {
1597 if ( is_null( $this->mOptions
) ) {
1598 if($defaultOverride != '') {
1599 return $defaultOverride;
1601 $this->mOptions
= User
::getDefaultOptions();
1604 if ( array_key_exists( $oname, $this->mOptions
) ) {
1605 return trim( $this->mOptions
[$oname] );
1607 return $defaultOverride;
1612 * Get the user's date preference, including some important migration for
1615 function getDatePreference() {
1616 if ( is_null( $this->mDatePreference
) ) {
1618 $value = $this->getOption( 'date' );
1619 $map = $wgLang->getDatePreferenceMigrationMap();
1620 if ( isset( $map[$value] ) ) {
1621 $value = $map[$value];
1623 $this->mDatePreference
= $value;
1625 return $this->mDatePreference
;
1629 * @param string $oname The option to check
1630 * @return bool False if the option is not selected, true if it is
1632 function getBoolOption( $oname ) {
1633 return (bool)$this->getOption( $oname );
1637 * Get an option as an integer value from the source string.
1638 * @param string $oname The option to check
1639 * @param int $default Optional value to return if option is unset/blank.
1642 function getIntOption( $oname, $default=0 ) {
1643 $val = $this->getOption( $oname );
1647 return intval( $val );
1650 function setOption( $oname, $val ) {
1652 if ( is_null( $this->mOptions
) ) {
1653 $this->mOptions
= User
::getDefaultOptions();
1655 if ( $oname == 'skin' ) {
1656 # Clear cached skin, so the new one displays immediately in Special:Preferences
1657 unset( $this->mSkin
);
1659 // Filter out any newlines that may have passed through input validation.
1660 // Newlines are used to separate items in the options blob.
1661 $val = str_replace( "\r\n", "\n", $val );
1662 $val = str_replace( "\r", "\n", $val );
1663 $val = str_replace( "\n", " ", $val );
1664 $this->mOptions
[$oname] = $val;
1667 function getRights() {
1668 if ( is_null( $this->mRights
) ) {
1669 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1670 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1672 return $this->mRights
;
1676 * Get the list of explicit group memberships this user has.
1677 * The implicit * and user groups are not included.
1678 * @return array of strings
1680 function getGroups() {
1682 return $this->mGroups
;
1686 * Get the list of implicit group memberships this user has.
1687 * This includes all explicit groups, plus 'user' if logged in,
1688 * '*' for all accounts and autopromoted groups
1689 * @param boolean $recache Don't use the cache
1690 * @return array of strings
1692 function getEffectiveGroups( $recache = false ) {
1693 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1694 $this->mEffectiveGroups
= $this->getGroups();
1695 $this->mEffectiveGroups
[] = '*';
1696 if( $this->getId() ) {
1697 $this->mEffectiveGroups
[] = 'user';
1699 $this->mEffectiveGroups
= array_unique( array_merge(
1700 $this->mEffectiveGroups
,
1701 Autopromote
::getAutopromoteGroups( $this )
1704 # Hook for additional groups
1705 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1708 return $this->mEffectiveGroups
;
1711 /* Return the edit count for the user. This is where User::edits should have been */
1712 function getEditCount() {
1714 if ( !isset( $this->mEditCount
) ) {
1715 /* Populate the count, if it has not been populated yet */
1716 $this->mEditCount
= User
::edits($this->mId
);
1718 return $this->mEditCount
;
1726 * Add the user to the given group.
1727 * This takes immediate effect.
1728 * @param string $group
1730 function addGroup( $group ) {
1731 $dbw = wfGetDB( DB_MASTER
);
1732 if( $this->getId() ) {
1733 $dbw->insert( 'user_groups',
1735 'ug_user' => $this->getID(),
1736 'ug_group' => $group,
1739 array( 'IGNORE' ) );
1742 $this->loadGroups();
1743 $this->mGroups
[] = $group;
1744 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1746 $this->invalidateCache();
1750 * Remove the user from the given group.
1751 * This takes immediate effect.
1752 * @param string $group
1754 function removeGroup( $group ) {
1756 $dbw = wfGetDB( DB_MASTER
);
1757 $dbw->delete( 'user_groups',
1759 'ug_user' => $this->getID(),
1760 'ug_group' => $group,
1762 'User::removeGroup' );
1764 $this->loadGroups();
1765 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1766 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1768 $this->invalidateCache();
1773 * A more legible check for non-anonymousness.
1774 * Returns true if the user is not an anonymous visitor.
1778 function isLoggedIn() {
1779 return $this->getID() != 0;
1783 * A more legible check for anonymousness.
1784 * Returns true if the user is an anonymous visitor.
1789 return !$this->isLoggedIn();
1793 * Whether the user is a bot
1797 wfDeprecated( __METHOD__
);
1798 return $this->isAllowed( 'bot' );
1802 * Check if user is allowed to access a feature / make an action
1803 * @param string $action Action to be checked
1804 * @return boolean True: action is allowed, False: action should not be allowed
1806 function isAllowed($action='') {
1807 if ( $action === '' )
1808 // In the spirit of DWIM
1811 return in_array( $action, $this->getRights() );
1815 * Check whether to enable recent changes patrol features for this user
1818 public function useRCPatrol() {
1819 global $wgUseRCPatrol;
1820 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
1824 * Check whether to enable recent changes patrol features for this user
1827 public function useNPPatrol() {
1828 global $wgUseRCPatrol, $wgUseNPPatrol;
1829 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
1833 * Load a skin if it doesn't exist or return it
1834 * @todo FIXME : need to check the old failback system [AV]
1836 function &getSkin() {
1838 if ( ! isset( $this->mSkin
) ) {
1839 wfProfileIn( __METHOD__
);
1842 $userSkin = $this->getOption( 'skin' );
1843 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1845 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1846 wfProfileOut( __METHOD__
);
1848 return $this->mSkin
;
1852 * @param string $title Article title to look at
1856 * Check watched status of an article
1857 * @return bool True if article is watched
1859 function isWatched( $title ) {
1860 $wl = WatchedItem
::fromUserTitle( $this, $title );
1861 return $wl->isWatched();
1867 function addWatch( $title ) {
1868 $wl = WatchedItem
::fromUserTitle( $this, $title );
1870 $this->invalidateCache();
1874 * Stop watching an article
1876 function removeWatch( $title ) {
1877 $wl = WatchedItem
::fromUserTitle( $this, $title );
1879 $this->invalidateCache();
1883 * Clear the user's notification timestamp for the given title.
1884 * If e-notif e-mails are on, they will receive notification mails on
1885 * the next change of the page if it's watched etc.
1887 function clearNotification( &$title ) {
1888 global $wgUser, $wgUseEnotif;
1890 # Do nothing if the database is locked to writes
1891 if( wfReadOnly() ) {
1895 if ($title->getNamespace() == NS_USER_TALK
&&
1896 $title->getText() == $this->getName() ) {
1897 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1899 $this->setNewtalk( false );
1902 if( !$wgUseEnotif ) {
1906 if( $this->isAnon() ) {
1907 // Nothing else to do...
1911 // Only update the timestamp if the page is being watched.
1912 // The query to find out if it is watched is cached both in memcached and per-invocation,
1913 // and when it does have to be executed, it can be on a slave
1914 // If this is the user's newtalk page, we always update the timestamp
1915 if ($title->getNamespace() == NS_USER_TALK
&&
1916 $title->getText() == $wgUser->getName())
1919 } elseif ( $this->getID() == $wgUser->getID() ) {
1920 $watched = $title->userIsWatching();
1925 // If the page is watched by the user (or may be watched), update the timestamp on any
1926 // any matching rows
1928 $dbw = wfGetDB( DB_MASTER
);
1929 $dbw->update( 'watchlist',
1931 'wl_notificationtimestamp' => NULL
1932 ), array( /* WHERE */
1933 'wl_title' => $title->getDBkey(),
1934 'wl_namespace' => $title->getNamespace(),
1935 'wl_user' => $this->getID()
1936 ), 'User::clearLastVisited'
1944 * Resets all of the given user's page-change notification timestamps.
1945 * If e-notif e-mails are on, they will receive notification mails on
1946 * the next change of any watched page.
1948 * @param int $currentUser user ID number
1951 function clearAllNotifications( $currentUser ) {
1952 global $wgUseEnotif;
1953 if ( !$wgUseEnotif ) {
1954 $this->setNewtalk( false );
1957 if( $currentUser != 0 ) {
1959 $dbw = wfGetDB( DB_MASTER
);
1960 $dbw->update( 'watchlist',
1962 'wl_notificationtimestamp' => NULL
1963 ), array( /* WHERE */
1964 'wl_user' => $currentUser
1968 # we also need to clear here the "you have new message" notification for the own user_talk page
1969 # This is cleared one page view later in Article::viewUpdates();
1975 * @return string Encoding options
1977 function encodeOptions() {
1979 if ( is_null( $this->mOptions
) ) {
1980 $this->mOptions
= User
::getDefaultOptions();
1983 foreach ( $this->mOptions
as $oname => $oval ) {
1984 array_push( $a, $oname.'='.$oval );
1986 $s = implode( "\n", $a );
1993 function decodeOptions( $str ) {
1994 $this->mOptions
= array();
1995 $a = explode( "\n", $str );
1996 foreach ( $a as $s ) {
1998 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1999 $this->mOptions
[$m[1]] = $m[2];
2004 protected function setCookie( $name, $value, $exp=0 ) {
2005 global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly;
2007 $exp = time() +
$wgCookieExpiration;
2009 $httpOnlySafe = version_compare("5.2", PHP_VERSION
, "<");
2011 if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) {
2012 setcookie( $wgCookiePrefix . $name,
2018 $wgCookieHttpOnly );
2020 // setcookie() fails on PHP 5.1 if you give it future-compat paramters.
2022 setcookie( $wgCookiePrefix . $name,
2031 protected function clearCookie( $name ) {
2032 $this->setCookie( $name, '', time() - 86400 );
2035 function setCookies() {
2037 if ( 0 == $this->mId
) return;
2039 $_SESSION['wsUserID'] = $this->mId
;
2041 $this->setCookie( 'UserID', $this->mId
);
2042 $this->setCookie( 'UserName', $this->getName() );
2044 $_SESSION['wsUserName'] = $this->getName();
2046 $_SESSION['wsToken'] = $this->mToken
;
2047 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2048 $this->setCookie( 'Token', $this->mToken
);
2050 $this->clearCookie( 'Token' );
2059 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2065 * Really logout user
2066 * Clears the cookies and session, resets the instance cache
2068 function doLogout() {
2069 $this->clearInstanceCache( 'defaults' );
2071 $_SESSION['wsUserID'] = 0;
2073 $this->clearCookie( 'UserID' );
2074 $this->clearCookie( 'Token' );
2076 # Remember when user logged out, to prevent seeing cached pages
2077 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2081 * Save object settings into database
2082 * @todo Only rarely do all these fields need to be set!
2084 function saveSettings() {
2086 if ( wfReadOnly() ) { return; }
2087 if ( 0 == $this->mId
) { return; }
2089 $this->mTouched
= self
::newTouchedTimestamp();
2091 $dbw = wfGetDB( DB_MASTER
);
2092 $dbw->update( 'user',
2094 'user_name' => $this->mName
,
2095 'user_password' => $this->mPassword
,
2096 'user_newpassword' => $this->mNewpassword
,
2097 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2098 'user_real_name' => $this->mRealName
,
2099 'user_email' => $this->mEmail
,
2100 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2101 'user_options' => $this->encodeOptions(),
2102 'user_touched' => $dbw->timestamp($this->mTouched
),
2103 'user_token' => $this->mToken
,
2104 'user_email_token' => $this->mEmailToken
,
2105 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2106 ), array( /* WHERE */
2107 'user_id' => $this->mId
2110 wfRunHooks( 'UserSaveSettings', array( $this ) );
2111 $this->clearSharedCache();
2115 * Checks if a user with the given name exists, returns the ID.
2117 function idForName() {
2118 $s = trim( $this->getName() );
2119 if ( $s === '' ) return 0;
2121 $dbr = wfGetDB( DB_SLAVE
);
2122 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2123 if ( $id === false ) {
2130 * Add a user to the database, return the user object
2132 * @param string $name The user's name
2133 * @param array $params Associative array of non-default parameters to save to the database:
2134 * password The user's password. Password logins will be disabled if this is omitted.
2135 * newpassword A temporary password mailed to the user
2136 * email The user's email address
2137 * email_authenticated The email authentication timestamp
2138 * real_name The user's real name
2139 * options An associative array of non-default options
2140 * token Random authentication token. Do not set.
2141 * registration Registration timestamp. Do not set.
2143 * @return User object, or null if the username already exists
2145 static function createNew( $name, $params = array() ) {
2148 if ( isset( $params['options'] ) ) {
2149 $user->mOptions
= $params['options'] +
$user->mOptions
;
2150 unset( $params['options'] );
2152 $dbw = wfGetDB( DB_MASTER
);
2153 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2155 'user_id' => $seqVal,
2156 'user_name' => $name,
2157 'user_password' => $user->mPassword
,
2158 'user_newpassword' => $user->mNewpassword
,
2159 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2160 'user_email' => $user->mEmail
,
2161 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2162 'user_real_name' => $user->mRealName
,
2163 'user_options' => $user->encodeOptions(),
2164 'user_token' => $user->mToken
,
2165 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2166 'user_editcount' => 0,
2168 foreach ( $params as $name => $value ) {
2169 $fields["user_$name"] = $value;
2171 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2172 if ( $dbw->affectedRows() ) {
2173 $newUser = User
::newFromId( $dbw->insertId() );
2181 * Add an existing user object to the database
2183 function addToDatabase() {
2185 $dbw = wfGetDB( DB_MASTER
);
2186 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2187 $dbw->insert( 'user',
2189 'user_id' => $seqVal,
2190 'user_name' => $this->mName
,
2191 'user_password' => $this->mPassword
,
2192 'user_newpassword' => $this->mNewpassword
,
2193 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2194 'user_email' => $this->mEmail
,
2195 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2196 'user_real_name' => $this->mRealName
,
2197 'user_options' => $this->encodeOptions(),
2198 'user_token' => $this->mToken
,
2199 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2200 'user_editcount' => 0,
2203 $this->mId
= $dbw->insertId();
2205 # Clear instance cache other than user table data, which is already accurate
2206 $this->clearInstanceCache();
2210 * If the (non-anonymous) user is blocked, this function will block any IP address
2211 * that they successfully log on from.
2213 function spreadBlock() {
2214 wfDebug( __METHOD__
."()\n" );
2216 if ( $this->mId
== 0 ) {
2220 $userblock = Block
::newFromDB( '', $this->mId
);
2221 if ( !$userblock ) {
2225 $userblock->doAutoblock( wfGetIp() );
2230 * Generate a string which will be different for any combination of
2231 * user options which would produce different parser output.
2232 * This will be used as part of the hash key for the parser cache,
2233 * so users will the same options can share the same cached data
2236 * Extensions which require it should install 'PageRenderingHash' hook,
2237 * which will give them a chance to modify this key based on their own
2242 function getPageRenderingHash() {
2243 global $wgContLang, $wgUseDynamicDates, $wgLang;
2245 return $this->mHash
;
2248 // stubthreshold is only included below for completeness,
2249 // it will always be 0 when this function is called by parsercache.
2251 $confstr = $this->getOption( 'math' );
2252 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2253 if ( $wgUseDynamicDates ) {
2254 $confstr .= '!' . $this->getDatePreference();
2256 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2257 $confstr .= '!' . $wgLang->getCode();
2258 $confstr .= '!' . $this->getOption( 'thumbsize' );
2259 // add in language specific options, if any
2260 $extra = $wgContLang->getExtraHashOptions();
2263 // Give a chance for extensions to modify the hash, if they have
2264 // extra options or other effects on the parser cache.
2265 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2267 // Make it a valid memcached key fragment
2268 $confstr = str_replace( ' ', '_', $confstr );
2269 $this->mHash
= $confstr;
2273 function isBlockedFromCreateAccount() {
2274 $this->getBlockedStatus();
2275 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2279 * Determine if the user is blocked from using Special:Emailuser.
2284 function isBlockedFromEmailuser() {
2285 $this->getBlockedStatus();
2286 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2289 function isAllowedToCreateAccount() {
2290 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2296 function setLoaded( $loaded ) {
2297 wfDeprecated( __METHOD__
);
2301 * Get this user's personal page title.
2306 function getUserPage() {
2307 return Title
::makeTitle( NS_USER
, $this->getName() );
2311 * Get this user's talk page title.
2316 function getTalkPage() {
2317 $title = $this->getUserPage();
2318 return $title->getTalkPage();
2324 function getMaxID() {
2325 static $res; // cache
2327 if ( isset( $res ) )
2330 $dbr = wfGetDB( DB_SLAVE
);
2331 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2336 * Determine whether the user is a newbie. Newbies are either
2337 * anonymous IPs, or the most recently created accounts.
2338 * @return bool True if it is a newbie.
2340 function isNewbie() {
2341 return !$this->isAllowed( 'autoconfirmed' );
2345 * Check to see if the given clear-text password is one of the accepted passwords
2346 * @param string $password User password.
2347 * @return bool True if the given password is correct otherwise False.
2349 function checkPassword( $password ) {
2353 // Even though we stop people from creating passwords that
2354 // are shorter than this, doesn't mean people wont be able
2355 // to. Certain authentication plugins do NOT want to save
2356 // domain passwords in a mysql database, so we should
2357 // check this (incase $wgAuth->strict() is false).
2358 if( !$this->isValidPassword( $password ) ) {
2362 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2364 } elseif( $wgAuth->strict() ) {
2365 /* Auth plugin doesn't allow local authentication */
2367 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2368 /* Auth plugin doesn't allow local authentication for this user name */
2371 $ep = $this->encryptPassword( $password );
2372 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2374 } elseif ( function_exists( 'iconv' ) ) {
2375 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2376 # Check for this with iconv
2377 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2378 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2386 * Check if the given clear-text password matches the temporary password
2387 * sent by e-mail for password reset operations.
2390 function checkTemporaryPassword( $plaintext ) {
2391 $hash = $this->encryptPassword( $plaintext );
2392 return $hash === $this->mNewpassword
;
2396 * Initialize (if necessary) and return a session token value
2397 * which can be used in edit forms to show that the user's
2398 * login credentials aren't being hijacked with a foreign form
2401 * @param mixed $salt - Optional function-specific data for hash.
2402 * Use a string or an array of strings.
2406 function editToken( $salt = '' ) {
2407 if ( $this->isAnon() ) {
2408 return EDIT_TOKEN_SUFFIX
;
2410 if( !isset( $_SESSION['wsEditToken'] ) ) {
2411 $token = $this->generateToken();
2412 $_SESSION['wsEditToken'] = $token;
2414 $token = $_SESSION['wsEditToken'];
2416 if( is_array( $salt ) ) {
2417 $salt = implode( '|', $salt );
2419 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2424 * Generate a hex-y looking random token for various uses.
2425 * Could be made more cryptographically sure if someone cares.
2428 function generateToken( $salt = '' ) {
2429 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2430 return md5( $token . $salt );
2434 * Check given value against the token value stored in the session.
2435 * A match should confirm that the form was submitted from the
2436 * user's own login session, not a form submission from a third-party
2439 * @param string $val - the input value to compare
2440 * @param string $salt - Optional function-specific data for hash
2444 function matchEditToken( $val, $salt = '' ) {
2445 $sessionToken = $this->editToken( $salt );
2446 if ( $val != $sessionToken ) {
2447 wfDebug( "User::matchEditToken: broken session data\n" );
2449 return $val == $sessionToken;
2453 * Check whether the edit token is fine except for the suffix
2455 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2456 $sessionToken = $this->editToken( $salt );
2457 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2461 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2462 * mail to the user's given address.
2464 * Call saveSettings() after calling this function to commit the confirmation
2465 * token to the database.
2467 * @return mixed True on success, a WikiError object on failure.
2469 function sendConfirmationMail() {
2471 $expiration = null; // gets passed-by-ref and defined in next line.
2472 $token = $this->confirmationToken( $expiration );
2473 $url = $this->confirmationTokenUrl( $token );
2474 $invalidateURL = $this->invalidationTokenUrl( $token );
2475 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2476 wfMsg( 'confirmemail_body',
2480 $wgLang->timeanddate( $expiration, false ),
2485 * Send an e-mail to this user's account. Does not check for
2486 * confirmed status or validity.
2488 * @param string $subject
2489 * @param string $body
2490 * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
2491 * @return mixed True on success, a WikiError object on failure.
2493 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2494 if( is_null( $from ) ) {
2495 global $wgPasswordSender;
2496 $from = $wgPasswordSender;
2499 $to = new MailAddress( $this );
2500 $sender = new MailAddress( $from );
2501 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2505 * Generate, store, and return a new e-mail confirmation code.
2506 * A hash (unsalted since it's used as a key) is stored.
2508 * Call saveSettings() after calling this function to commit
2509 * this change to the database.
2511 * @param &$expiration mixed output: accepts the expiration time
2515 function confirmationToken( &$expiration ) {
2517 $expires = $now +
7 * 24 * 60 * 60;
2518 $expiration = wfTimestamp( TS_MW
, $expires );
2519 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2520 $hash = md5( $token );
2522 $this->mEmailToken
= $hash;
2523 $this->mEmailTokenExpires
= $expiration;
2528 * Return a URL the user can use to confirm their email address.
2529 * @param $token: accepts the email confirmation token
2533 function confirmationTokenUrl( $token ) {
2534 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2535 return $title->getFullUrl();
2538 * Return a URL the user can use to invalidate their email address.
2539 * @param $token: accepts the email confirmation token
2543 function invalidationTokenUrl( $token ) {
2544 $title = SpecialPage
::getTitleFor( 'Invalidateemail', $token );
2545 return $title->getFullUrl();
2549 * Mark the e-mail address confirmed.
2551 * Call saveSettings() after calling this function to commit the change.
2553 function confirmEmail() {
2554 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2559 * Invalidate the user's email confirmation, unauthenticate the email
2560 * if it was already confirmed.
2562 * Call saveSettings() after calling this function to commit the change.
2564 function invalidateEmail() {
2566 $this->mEmailToken
= null;
2567 $this->mEmailTokenExpires
= null;
2568 $this->setEmailAuthenticationTimestamp( null );
2572 function setEmailAuthenticationTimestamp( $timestamp ) {
2574 $this->mEmailAuthenticated
= $timestamp;
2575 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2579 * Is this user allowed to send e-mails within limits of current
2580 * site configuration?
2583 function canSendEmail() {
2584 $canSend = $this->isEmailConfirmed();
2585 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2590 * Is this user allowed to receive e-mails within limits of current
2591 * site configuration?
2594 function canReceiveEmail() {
2595 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2599 * Is this user's e-mail address valid-looking and confirmed within
2600 * limits of the current site configuration?
2602 * If $wgEmailAuthentication is on, this may require the user to have
2603 * confirmed their address by returning a code or using a password
2604 * sent to the address from the wiki.
2608 function isEmailConfirmed() {
2609 global $wgEmailAuthentication;
2612 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2613 if( $this->isAnon() )
2615 if( !self
::isValidEmailAddr( $this->mEmail
) )
2617 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2626 * Return true if there is an outstanding request for e-mail confirmation.
2629 function isEmailConfirmationPending() {
2630 global $wgEmailAuthentication;
2631 return $wgEmailAuthentication &&
2632 !$this->isEmailConfirmed() &&
2633 $this->mEmailToken
&&
2634 $this->mEmailTokenExpires
> wfTimestamp();
2638 * Get the timestamp of account creation, or false for
2639 * non-existent/anonymous user accounts
2643 public function getRegistration() {
2644 return $this->mId
> 0
2645 ?
$this->mRegistration
2650 * @param array $groups list of groups
2651 * @return array list of permission key names for given groups combined
2654 static function getGroupPermissions( $groups ) {
2655 global $wgGroupPermissions;
2657 foreach( $groups as $group ) {
2658 if( isset( $wgGroupPermissions[$group] ) ) {
2659 $rights = array_merge( $rights,
2660 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2667 * @param string $group key name
2668 * @return string localized descriptive name for group, if provided
2671 static function getGroupName( $group ) {
2672 global $wgMessageCache;
2673 $wgMessageCache->loadAllMessages();
2674 $key = "group-$group";
2675 $name = wfMsg( $key );
2676 return $name == '' ||
wfEmptyMsg( $key, $name )
2682 * @param string $group key name
2683 * @return string localized descriptive name for member of a group, if provided
2686 static function getGroupMember( $group ) {
2687 global $wgMessageCache;
2688 $wgMessageCache->loadAllMessages();
2689 $key = "group-$group-member";
2690 $name = wfMsg( $key );
2691 return $name == '' ||
wfEmptyMsg( $key, $name )
2697 * Return the set of defined explicit groups.
2698 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2699 * groups are not included, as they are defined
2700 * automatically, not in the database.
2704 static function getAllGroups() {
2705 global $wgGroupPermissions;
2707 array_keys( $wgGroupPermissions ),
2708 self
::getImplicitGroups()
2713 * Get a list of implicit groups
2717 public static function getImplicitGroups() {
2718 global $wgImplicitGroups;
2719 $groups = $wgImplicitGroups;
2720 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
2725 * Get the title of a page describing a particular group
2727 * @param $group Name of the group
2730 static function getGroupPage( $group ) {
2731 global $wgMessageCache;
2732 $wgMessageCache->loadAllMessages();
2733 $page = wfMsgForContent( 'grouppage-' . $group );
2734 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2735 $title = Title
::newFromText( $page );
2736 if( is_object( $title ) )
2743 * Create a link to the group in HTML, if available
2745 * @param $group Name of the group
2746 * @param $text The text of the link
2749 static function makeGroupLinkHTML( $group, $text = '' ) {
2751 $text = self
::getGroupName( $group );
2753 $title = self
::getGroupPage( $group );
2756 $sk = $wgUser->getSkin();
2757 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2764 * Create a link to the group in Wikitext, if available
2766 * @param $group Name of the group
2767 * @param $text The text of the link (by default, the name of the group)
2770 static function makeGroupLinkWiki( $group, $text = '' ) {
2772 $text = self
::getGroupName( $group );
2774 $title = self
::getGroupPage( $group );
2776 $page = $title->getPrefixedText();
2777 return "[[$page|$text]]";
2784 * Increment the user's edit-count field.
2785 * Will have no effect for anonymous users.
2787 function incEditCount() {
2788 if( !$this->isAnon() ) {
2789 $dbw = wfGetDB( DB_MASTER
);
2790 $dbw->update( 'user',
2791 array( 'user_editcount=user_editcount+1' ),
2792 array( 'user_id' => $this->getId() ),
2795 // Lazy initialization check...
2796 if( $dbw->affectedRows() == 0 ) {
2797 // Pull from a slave to be less cruel to servers
2798 // Accuracy isn't the point anyway here
2799 $dbr = wfGetDB( DB_SLAVE
);
2800 $count = $dbr->selectField( 'revision',
2802 array( 'rev_user' => $this->getId() ),
2805 // Now here's a goddamn hack...
2806 if( $dbr !== $dbw ) {
2807 // If we actually have a slave server, the count is
2808 // at least one behind because the current transaction
2809 // has not been committed and replicated.
2812 // But if DB_SLAVE is selecting the master, then the
2813 // count we just read includes the revision that was
2814 // just added in the working transaction.
2817 $dbw->update( 'user',
2818 array( 'user_editcount' => $count ),
2819 array( 'user_id' => $this->getId() ),
2823 // edit count in user cache too
2824 $this->invalidateCache();