3 * Implements the User class for the %MediaWiki software.
8 * \int Number of characters in user_token field.
11 define( 'USER_TOKEN_LENGTH', 32 );
14 * \int Serialized record version.
17 define( 'MW_USER_VERSION', 8 );
20 * \string Some punctuation to prevent editing from broken text-mangling proxies.
23 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
26 * Thrown by User::setPassword() on error.
29 class PasswordError
extends MWException
{
34 * The User object encapsulates all of the user-specific settings (user_id,
35 * name, rights, password, email address, options, last login time). Client
36 * classes use the getXXX() functions to access these fields. These functions
37 * do all the work of determining whether the user is logged in,
38 * whether the requested option can be satisfied from cookies or
39 * whether a database query is needed. Most of the settings needed
40 * for rendering normal pages are set in the cookie to minimize use
46 * \type{\arrayof{\string}} A list of default user toggles, i.e., boolean user
47 * preferences that are displayed by Special:Preferences as checkboxes.
48 * This list can be extended via the UserToggles hook or by
49 * $wgContLang::getExtraUserToggles().
52 public static $mToggles = array(
62 'editsectiononrightclick',
74 'enotifwatchlistpages',
75 'enotifusertalkpages',
78 'shownumberswatching',
98 * \type{\arrayof{\string}} List of member variables which are saved to the
99 * shared cache (memcached). Any operation which changes the
100 * corresponding database fields must call a cache-clearing function.
103 static $mCacheVars = array(
114 'mEmailAuthenticated',
116 'mEmailTokenExpires',
121 // user_properties table
126 * \type{\arrayof{\string}} Core rights.
127 * Each of these should have a corresponding message of the form
131 static $mCoreRights = array(
158 'move-rootuserpages',
162 'override-export-depth',
182 'userrights-interwiki',
186 * \string Cached results of getAllRights()
188 static $mAllRights = false;
190 /** @name Cache variables */
192 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
193 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
194 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
198 * \bool Whether the cache variables have been loaded.
200 var $mDataLoaded, $mAuthLoaded, $mOptionsLoaded;
203 * \string Initialization data source if mDataLoaded==false. May be one of:
204 * - 'defaults' anonymous user initialised from class defaults
205 * - 'name' initialise from mName
206 * - 'id' initialise from mId
207 * - 'session' log in from cookies or session if possible
209 * Use the User::newFrom*() family of functions to set this.
213 /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
215 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
216 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
217 $mLocked, $mHideName, $mOptions;
220 static $idCacheByName = array();
223 * Lightweight constructor for an anonymous user.
224 * Use the User::newFrom* factory functions for other kinds of users.
228 * @see newFromConfirmationCode()
229 * @see newFromSession()
233 $this->clearInstanceCache( 'defaults' );
237 * Load the user table data for this object from the source given by mFrom.
240 if ( $this->mDataLoaded
) {
243 wfProfileIn( __METHOD__
);
245 # Set it now to avoid infinite recursion in accessors
246 $this->mDataLoaded
= true;
248 switch ( $this->mFrom
) {
250 $this->loadDefaults();
253 $this->mId
= self
::idFromName( $this->mName
);
255 # Nonexistent user placeholder object
256 $this->loadDefaults( $this->mName
);
265 $this->loadFromSession();
266 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
269 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
271 wfProfileOut( __METHOD__
);
275 * Load user table data, given mId has already been set.
276 * @return \bool false if the ID does not exist, true otherwise
279 function loadFromId() {
281 if ( $this->mId
== 0 ) {
282 $this->loadDefaults();
287 $key = wfMemcKey( 'user', 'id', $this->mId
);
288 $data = $wgMemc->get( $key );
289 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
290 # Object is expired, load from DB
295 wfDebug( "Cache miss for user {$this->mId}\n" );
297 if ( !$this->loadFromDatabase() ) {
298 # Can't load from ID, user is anonymous
301 $this->saveToCache();
303 wfDebug( "Got user {$this->mId} from cache\n" );
305 foreach ( self
::$mCacheVars as $name ) {
306 $this->$name = $data[$name];
313 * Save user data to the shared cache
315 function saveToCache() {
318 $this->loadOptions();
319 if ( $this->isAnon() ) {
320 // Anonymous users are uncached
324 foreach ( self
::$mCacheVars as $name ) {
325 $data[$name] = $this->$name;
327 $data['mVersion'] = MW_USER_VERSION
;
328 $key = wfMemcKey( 'user', 'id', $this->mId
);
330 $wgMemc->set( $key, $data );
334 /** @name newFrom*() static factory methods */
338 * Static factory method for creation from username.
340 * This is slightly less efficient than newFromId(), so use newFromId() if
341 * you have both an ID and a name handy.
343 * @param $name \string Username, validated by Title::newFromText()
344 * @param $validate \mixed Validate username. Takes the same parameters as
345 * User::getCanonicalName(), except that true is accepted as an alias
346 * for 'valid', for BC.
348 * @return \type{User} The User object, or null if the username is invalid. If the
349 * username is not present in the database, the result will be a user object
350 * with a name, zero user ID and default settings.
352 static function newFromName( $name, $validate = 'valid' ) {
353 if ( $validate === true ) {
356 $name = self
::getCanonicalName( $name, $validate );
357 if ( WikiError
::isError( $name ) ) {
359 } elseif ( $name === false ) {
362 # Create unloaded user object
371 * Static factory method for creation from a given user ID.
373 * @param $id \int Valid user ID
374 * @return \type{User} The corresponding User object
376 static function newFromId( $id ) {
384 * Factory method to fetch whichever user has a given email confirmation code.
385 * This code is generated when an account is created or its e-mail address
388 * If the code is invalid or has expired, returns NULL.
390 * @param $code \string Confirmation code
391 * @return \type{User}
393 static function newFromConfirmationCode( $code ) {
394 $dbr = wfGetDB( DB_SLAVE
);
395 $id = $dbr->selectField( 'user', 'user_id', array(
396 'user_email_token' => md5( $code ),
397 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
399 if( $id !== false ) {
400 return User
::newFromId( $id );
407 * Create a new user object using data from session or cookies. If the
408 * login credentials are invalid, the result is an anonymous user.
410 * @return \type{User}
412 static function newFromSession() {
414 $user->mFrom
= 'session';
419 * Create a new user object from a user row.
420 * The row should have all fields from the user table in it.
421 * @param $row array A row from the user table
422 * @return \type{User}
424 static function newFromRow( $row ) {
426 $user->loadFromRow( $row );
434 * Get the username corresponding to a given user ID
435 * @param $id \int User ID
436 * @return \string The corresponding username
438 static function whoIs( $id ) {
439 $dbr = wfGetDB( DB_SLAVE
);
440 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
444 * Get the real name of a user given their user ID
446 * @param $id \int User ID
447 * @return \string The corresponding user's real name
449 static function whoIsReal( $id ) {
450 $dbr = wfGetDB( DB_SLAVE
);
451 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
455 * Get database id given a user name
456 * @param $name \string Username
457 * @return \types{\int,\null} The corresponding user's ID, or null if user is nonexistent
459 static function idFromName( $name ) {
460 $nt = Title
::makeTitleSafe( NS_USER
, $name );
461 if( is_null( $nt ) ) {
466 if ( isset( self
::$idCacheByName[$name] ) ) {
467 return self
::$idCacheByName[$name];
470 $dbr = wfGetDB( DB_SLAVE
);
471 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
473 if ( $s === false ) {
476 $result = $s->user_id
;
479 self
::$idCacheByName[$name] = $result;
481 if ( count( self
::$idCacheByName ) > 1000 ) {
482 self
::$idCacheByName = array();
489 * Does the string match an anonymous IPv4 address?
491 * This function exists for username validation, in order to reject
492 * usernames which are similar in form to IP addresses. Strings such
493 * as 300.300.300.300 will return true because it looks like an IP
494 * address, despite not being strictly valid.
496 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
497 * address because the usemod software would "cloak" anonymous IP
498 * addresses like this, if we allowed accounts like this to be created
499 * new users could get the old edits of these anonymous users.
501 * @param $name \string String to match
502 * @return \bool True or false
504 static function isIP( $name ) {
505 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
509 * Is the input a valid username?
511 * Checks if the input is a valid username, we don't want an empty string,
512 * an IP address, anything that containins slashes (would mess up subpages),
513 * is longer than the maximum allowed username size or doesn't begin with
516 * @param $name \string String to match
517 * @return \bool True or false
519 static function isValidUserName( $name ) {
520 global $wgContLang, $wgMaxNameChars;
523 || User
::isIP( $name )
524 ||
strpos( $name, '/' ) !== false
525 ||
strlen( $name ) > $wgMaxNameChars
526 ||
$name != $wgContLang->ucfirst( $name ) ) {
527 wfDebugLog( 'username', __METHOD__
.
528 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
532 // Ensure that the name can't be misresolved as a different title,
533 // such as with extra namespace keys at the start.
534 $parsed = Title
::newFromText( $name );
535 if( is_null( $parsed )
536 ||
$parsed->getNamespace()
537 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
538 wfDebugLog( 'username', __METHOD__
.
539 ": '$name' invalid due to ambiguous prefixes" );
543 // Check an additional blacklist of troublemaker characters.
544 // Should these be merged into the title char list?
545 $unicodeBlacklist = '/[' .
546 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
547 '\x{00a0}' . # non-breaking space
548 '\x{2000}-\x{200f}' . # various whitespace
549 '\x{2028}-\x{202f}' . # breaks and control chars
550 '\x{3000}' . # ideographic space
551 '\x{e000}-\x{f8ff}' . # private use
553 if( preg_match( $unicodeBlacklist, $name ) ) {
554 wfDebugLog( 'username', __METHOD__
.
555 ": '$name' invalid due to blacklisted characters" );
563 * Usernames which fail to pass this function will be blocked
564 * from user login and new account registrations, but may be used
565 * internally by batch processes.
567 * If an account already exists in this form, login will be blocked
568 * by a failure to pass this function.
570 * @param $name \string String to match
571 * @return \bool True or false
573 static function isUsableName( $name ) {
574 global $wgReservedUsernames;
575 // Must be a valid username, obviously ;)
576 if ( !self
::isValidUserName( $name ) ) {
580 static $reservedUsernames = false;
581 if ( !$reservedUsernames ) {
582 $reservedUsernames = $wgReservedUsernames;
583 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
586 // Certain names may be reserved for batch processes.
587 foreach ( $reservedUsernames as $reserved ) {
588 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
589 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
591 if ( $reserved == $name ) {
599 * Usernames which fail to pass this function will be blocked
600 * from new account registrations, but may be used internally
601 * either by batch processes or by user accounts which have
602 * already been created.
604 * Additional character blacklisting may be added here
605 * rather than in isValidUserName() to avoid disrupting
608 * @param $name \string String to match
609 * @return \bool True or false
611 static function isCreatableName( $name ) {
612 global $wgInvalidUsernameCharacters;
614 self
::isUsableName( $name ) &&
616 // Registration-time character blacklisting...
617 !preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name );
621 * Is the input a valid password for this user?
623 * @param $password String Desired password
624 * @return bool True or false
626 function isValidPassword( $password ) {
627 //simple boolean wrapper for getPasswordValidity
628 return $this->getPasswordValidity( $password ) === true;
632 * Given unvalidated password input, return error message on failure.
634 * @param $password String Desired password
635 * @return mixed: true on success, string of error message on failure
637 function getPasswordValidity( $password ) {
638 global $wgMinimalPasswordLength, $wgContLang;
640 $result = false; //init $result to false for the internal checks
642 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
645 if ( $result === false ) {
646 if( strlen( $password ) < $wgMinimalPasswordLength ) {
647 return 'passwordtooshort';
648 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
649 return 'password-name-match';
651 //it seems weird returning true here, but this is because of the
652 //initialization of $result to false above. If the hook is never run or it
653 //doesn't modify $result, then we will likely get down into this if with
657 } elseif( $result === true ) {
660 return $result; //the isValidPassword hook set a string $result and returned true
665 * Does a string look like an e-mail address?
667 * There used to be a regular expression here, it got removed because it
668 * rejected valid addresses. Actually just check if there is '@' somewhere
669 * in the given address.
671 * @todo Check for RFC 2822 compilance (bug 959)
673 * @param $addr \string E-mail address
674 * @return \bool True or false
676 public static function isValidEmailAddr( $addr ) {
678 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
682 return strpos( $addr, '@' ) !== false;
686 * Given unvalidated user input, return a canonical username, or false if
687 * the username is invalid.
688 * @param $name \string User input
689 * @param $validate \types{\string,\bool} Type of validation to use:
690 * - false No validation
691 * - 'valid' Valid for batch processes
692 * - 'usable' Valid for batch processes and login
693 * - 'creatable' Valid for batch processes, login and account creation
695 static function getCanonicalName( $name, $validate = 'valid' ) {
696 # Force usernames to capital
698 $name = $wgContLang->ucfirst( $name );
700 # Reject names containing '#'; these will be cleaned up
701 # with title normalisation, but then it's too late to
703 if( strpos( $name, '#' ) !== false )
704 return new WikiError( 'usernamehasherror' );
706 # Clean up name according to title rules
707 $t = ( $validate === 'valid' ) ?
708 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
709 # Check for invalid titles
710 if( is_null( $t ) ) {
714 # Reject various classes of invalid names
715 $name = $t->getText();
717 $name = $wgAuth->getCanonicalName( $t->getText() );
719 switch ( $validate ) {
723 if ( !User
::isValidUserName( $name ) ) {
728 if ( !User
::isUsableName( $name ) ) {
733 if ( !User
::isCreatableName( $name ) ) {
738 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
744 * Count the number of edits of a user
745 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
747 * @param $uid \int User ID to check
748 * @return \int The user's edit count
750 static function edits( $uid ) {
751 wfProfileIn( __METHOD__
);
752 $dbr = wfGetDB( DB_SLAVE
);
753 // check if the user_editcount field has been initialized
754 $field = $dbr->selectField(
755 'user', 'user_editcount',
756 array( 'user_id' => $uid ),
760 if( $field === null ) { // it has not been initialized. do so.
761 $dbw = wfGetDB( DB_MASTER
);
762 $count = $dbr->selectField(
763 'revision', 'count(*)',
764 array( 'rev_user' => $uid ),
769 array( 'user_editcount' => $count ),
770 array( 'user_id' => $uid ),
776 wfProfileOut( __METHOD__
);
781 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
782 * @todo hash random numbers to improve security, like generateToken()
784 * @return \string New random password
786 static function randomPassword() {
787 global $wgMinimalPasswordLength;
788 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
789 $l = strlen( $pwchars ) - 1;
791 $pwlength = max( 7, $wgMinimalPasswordLength );
792 $digit = mt_rand( 0, $pwlength - 1 );
794 for ( $i = 0; $i < $pwlength; $i++
) {
795 $np .= $i == $digit ?
chr( mt_rand( 48, 57 ) ) : $pwchars{ mt_rand( 0, $l ) };
801 * Set cached properties to default.
803 * @note This no longer clears uncached lazy-initialised properties;
804 * the constructor does that instead.
807 function loadDefaults( $name = false ) {
808 wfProfileIn( __METHOD__
);
810 global $wgCookiePrefix;
813 $this->mName
= $name;
814 $this->mRealName
= '';
815 $this->mPassword
= $this->mNewpassword
= '';
816 $this->mNewpassTime
= null;
818 $this->mOptionOverrides
= null;
819 $this->mOptionsLoaded
= false;
821 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
822 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
824 $this->mTouched
= '0'; # Allow any pages to be cached
827 $this->setToken(); # Random
828 $this->mEmailAuthenticated
= null;
829 $this->mEmailToken
= '';
830 $this->mEmailTokenExpires
= null;
831 $this->mRegistration
= wfTimestamp( TS_MW
);
832 $this->mGroups
= array();
834 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
836 wfProfileOut( __METHOD__
);
840 * @deprecated Use wfSetupSession().
842 function SetupSession() {
843 wfDeprecated( __METHOD__
);
848 * Load user data from the session or login cookie. If there are no valid
849 * credentials, initialises the user as an anonymous user.
850 * @return \bool True if the user is logged in, false otherwise.
852 private function loadFromSession() {
853 global $wgMemc, $wgCookiePrefix, $wgExternalAuthType, $wgAutocreatePolicy;
856 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
857 if ( $result !== null ) {
861 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
862 $extUser = ExternalUser
::newFromCookie();
864 # TODO: Automatically create the user here (or probably a bit
865 # lower down, in fact)
869 if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
870 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
871 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
872 $this->loadDefaults(); // Possible collision!
873 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
874 cookie user ID ($sId) don't match!" );
877 $_SESSION['wsUserID'] = $sId;
878 } else if ( isset( $_SESSION['wsUserID'] ) ) {
879 if ( $_SESSION['wsUserID'] != 0 ) {
880 $sId = $_SESSION['wsUserID'];
882 $this->loadDefaults();
886 $this->loadDefaults();
890 if ( isset( $_SESSION['wsUserName'] ) ) {
891 $sName = $_SESSION['wsUserName'];
892 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
893 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
894 $_SESSION['wsUserName'] = $sName;
896 $this->loadDefaults();
900 $passwordCorrect = FALSE;
902 if ( !$this->loadFromId() ) {
903 # Not a valid ID, loadFromId has switched the object to anon for us
907 if ( isset( $_SESSION['wsToken'] ) ) {
908 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
910 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
911 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
914 # No session or persistent login cookie
915 $this->loadDefaults();
919 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
920 $_SESSION['wsToken'] = $this->mToken
;
921 wfDebug( "Logged in from $from\n" );
924 # Invalid credentials
925 wfDebug( "Can't log in from $from, invalid credentials\n" );
926 $this->loadDefaults();
932 * Load user and user_group data from the database.
933 * $this::mId must be set, this is how the user is identified.
935 * @return \bool True if the user exists, false if the user is anonymous
938 function loadFromDatabase() {
940 $this->mId
= intval( $this->mId
);
942 /** Anonymous user */
944 $this->loadDefaults();
948 $dbr = wfGetDB( DB_MASTER
);
949 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
951 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
953 if ( $s !== false ) {
954 # Initialise user table data
955 $this->loadFromRow( $s );
956 $this->mGroups
= null; // deferred
957 $this->getEditCount(); // revalidation for nulls
962 $this->loadDefaults();
968 * Initialize this object from a row from the user table.
970 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
972 function loadFromRow( $row ) {
973 $this->mDataLoaded
= true;
975 if ( isset( $row->user_id
) ) {
976 $this->mId
= intval( $row->user_id
);
978 $this->mName
= $row->user_name
;
979 $this->mRealName
= $row->user_real_name
;
980 $this->mPassword
= $row->user_password
;
981 $this->mNewpassword
= $row->user_newpassword
;
982 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
983 $this->mEmail
= $row->user_email
;
984 $this->decodeOptions( $row->user_options
);
985 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
986 $this->mToken
= $row->user_token
;
987 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
988 $this->mEmailToken
= $row->user_email_token
;
989 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
990 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
991 $this->mEditCount
= $row->user_editcount
;
995 * Load the groups from the database if they aren't already loaded.
998 function loadGroups() {
999 if ( is_null( $this->mGroups
) ) {
1000 $dbr = wfGetDB( DB_MASTER
);
1001 $res = $dbr->select( 'user_groups',
1002 array( 'ug_group' ),
1003 array( 'ug_user' => $this->mId
),
1005 $this->mGroups
= array();
1006 while( $row = $dbr->fetchObject( $res ) ) {
1007 $this->mGroups
[] = $row->ug_group
;
1013 * Clear various cached data stored in this object.
1014 * @param $reloadFrom \string Reload user and user_groups table data from a
1015 * given source. May be "name", "id", "defaults", "session", or false for
1018 function clearInstanceCache( $reloadFrom = false ) {
1019 $this->mNewtalk
= -1;
1020 $this->mDatePreference
= null;
1021 $this->mBlockedby
= -1; # Unset
1022 $this->mHash
= false;
1023 $this->mSkin
= null;
1024 $this->mRights
= null;
1025 $this->mEffectiveGroups
= null;
1026 $this->mOptions
= null;
1028 if ( $reloadFrom ) {
1029 $this->mDataLoaded
= false;
1030 $this->mFrom
= $reloadFrom;
1035 * Combine the language default options with any site-specific options
1036 * and add the default language variants.
1038 * @return \type{\arrayof{\string}} Array of options
1040 static function getDefaultOptions() {
1041 global $wgNamespacesToBeSearchedDefault;
1043 * Site defaults will override the global/language defaults
1045 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1046 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
1049 * default language setting
1051 $variant = $wgContLang->getPreferredVariant( false );
1052 $defOpt['variant'] = $variant;
1053 $defOpt['language'] = $variant;
1054 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1055 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1057 $defOpt['skin'] = $wgDefaultSkin;
1063 * Get a given default option value.
1065 * @param $opt \string Name of option to retrieve
1066 * @return \string Default option value
1068 public static function getDefaultOption( $opt ) {
1069 $defOpts = self
::getDefaultOptions();
1070 if( isset( $defOpts[$opt] ) ) {
1071 return $defOpts[$opt];
1078 * Get a list of user toggle names
1079 * @return \type{\arrayof{\string}} Array of user toggle names
1081 static function getToggles() {
1082 global $wgContLang, $wgUseRCPatrol;
1083 $extraToggles = array();
1084 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1085 if( $wgUseRCPatrol ) {
1086 $extraToggles[] = 'hidepatrolled';
1087 $extraToggles[] = 'newpageshidepatrolled';
1088 $extraToggles[] = 'watchlisthidepatrolled';
1090 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1095 * Get blocking information
1097 * @param $bFromSlave \bool Whether to check the slave database first. To
1098 * improve performance, non-critical checks are done
1099 * against slaves. Check when actually saving should be
1100 * done against master.
1102 function getBlockedStatus( $bFromSlave = true ) {
1103 global $wgProxyWhitelist, $wgUser;
1105 if ( -1 != $this->mBlockedby
) {
1106 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1110 wfProfileIn( __METHOD__
);
1111 wfDebug( __METHOD__
.": checking...\n" );
1113 // Initialize data...
1114 // Otherwise something ends up stomping on $this->mBlockedby when
1115 // things get lazy-loaded later, causing false positive block hits
1116 // due to -1 !== 0. Probably session-related... Nothing should be
1117 // overwriting mBlockedby, surely?
1120 $this->mBlockedby
= 0;
1121 $this->mHideName
= 0;
1122 $this->mAllowUsertalk
= 0;
1124 # Check if we are looking at an IP or a logged-in user
1125 if ( $this->isIP( $this->getName() ) ) {
1126 $ip = $this->getName();
1128 # Check if we are looking at the current user
1129 # If we don't, and the user is logged in, we don't know about
1130 # his IP / autoblock status, so ignore autoblock of current user's IP
1131 if ( $this->getID() != $wgUser->getID() ) {
1134 # Get IP of current user
1139 if ( $this->isAllowed( 'ipblock-exempt' ) ) {
1140 # Exempt from all types of IP-block
1145 $this->mBlock
= new Block();
1146 $this->mBlock
->fromMaster( !$bFromSlave );
1147 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1148 wfDebug( __METHOD__
. ": Found block.\n" );
1149 $this->mBlockedby
= $this->mBlock
->mBy
;
1150 $this->mBlockreason
= $this->mBlock
->mReason
;
1151 $this->mHideName
= $this->mBlock
->mHideName
;
1152 $this->mAllowUsertalk
= $this->mBlock
->mAllowUsertalk
;
1153 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1154 $this->spreadBlock();
1157 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1158 // apply to users. Note that the existence of $this->mBlock is not used to
1159 // check for edit blocks, $this->mBlockedby is instead.
1163 if ( !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1165 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1166 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1167 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1171 if ( !$this->mBlockedby
&& !$this->getID() ) {
1172 if ( $this->isDnsBlacklisted( $ip ) ) {
1173 $this->mBlockedby
= wfMsg( 'sorbs' );
1174 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1180 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1182 wfProfileOut( __METHOD__
);
1186 * Whether the given IP is in a DNS blacklist.
1188 * @param $ip \string IP to check
1189 * @param $checkWhitelist Boolean: whether to check the whitelist first
1190 * @return \bool True if blacklisted.
1192 function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1193 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1194 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1196 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1199 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1202 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1203 return $this->inDnsBlacklist( $ip, $urls );
1207 * Whether the given IP is in a given DNS blacklist.
1209 * @param $ip \string IP to check
1210 * @param $bases \string or Array of Strings: URL of the DNS blacklist
1211 * @return \bool True if blacklisted.
1213 function inDnsBlacklist( $ip, $bases ) {
1214 wfProfileIn( __METHOD__
);
1218 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1219 if( IP
::isIPv4( $ip ) ) {
1220 # Reverse IP, bug 21255
1221 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1223 foreach( (array)$bases as $base ) {
1225 $host = "$ipReversed.$base";
1228 $ipList = gethostbynamel( $host );
1231 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1235 wfDebug( "Requested $host, not found in $base.\n" );
1240 wfProfileOut( __METHOD__
);
1245 * Is this user subject to rate limiting?
1247 * @return \bool True if rate limited
1249 public function isPingLimitable() {
1250 global $wgRateLimitsExcludedGroups;
1251 global $wgRateLimitsExcludedIPs;
1252 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1253 // Deprecated, but kept for backwards-compatibility config
1256 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1257 // No other good way currently to disable rate limits
1258 // for specific IPs. :P
1259 // But this is a crappy hack and should die.
1262 return !$this->isAllowed('noratelimit');
1266 * Primitive rate limits: enforce maximum actions per time period
1267 * to put a brake on flooding.
1269 * @note When using a shared cache like memcached, IP-address
1270 * last-hit counters will be shared across wikis.
1272 * @param $action \string Action to enforce; 'edit' if unspecified
1273 * @return \bool True if a rate limiter was tripped
1275 function pingLimiter( $action = 'edit' ) {
1276 # Call the 'PingLimiter' hook
1278 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1282 global $wgRateLimits;
1283 if( !isset( $wgRateLimits[$action] ) ) {
1287 # Some groups shouldn't trigger the ping limiter, ever
1288 if( !$this->isPingLimitable() )
1291 global $wgMemc, $wgRateLimitLog;
1292 wfProfileIn( __METHOD__
);
1294 $limits = $wgRateLimits[$action];
1296 $id = $this->getId();
1300 if( isset( $limits['anon'] ) && $id == 0 ) {
1301 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1304 if( isset( $limits['user'] ) && $id != 0 ) {
1305 $userLimit = $limits['user'];
1307 if( $this->isNewbie() ) {
1308 if( isset( $limits['newbie'] ) && $id != 0 ) {
1309 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1311 if( isset( $limits['ip'] ) ) {
1312 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1315 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1316 $subnet = $matches[1];
1317 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1320 // Check for group-specific permissions
1321 // If more than one group applies, use the group with the highest limit
1322 foreach ( $this->getGroups() as $group ) {
1323 if ( isset( $limits[$group] ) ) {
1324 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1325 $userLimit = $limits[$group];
1329 // Set the user limit key
1330 if ( $userLimit !== false ) {
1331 wfDebug( __METHOD__
. ": effective user limit: $userLimit\n" );
1332 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1336 foreach( $keys as $key => $limit ) {
1337 list( $max, $period ) = $limit;
1338 $summary = "(limit $max in {$period}s)";
1339 $count = $wgMemc->get( $key );
1342 if( $count > $max ) {
1343 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1344 if( $wgRateLimitLog ) {
1345 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1349 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1352 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1353 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1355 $wgMemc->incr( $key );
1358 wfProfileOut( __METHOD__
);
1363 * Check if user is blocked
1365 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1366 * @return \bool True if blocked, false otherwise
1368 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1369 wfDebug( "User::isBlocked: enter\n" );
1370 $this->getBlockedStatus( $bFromSlave );
1371 return $this->mBlockedby
!== 0;
1375 * Check if user is blocked from editing a particular article
1377 * @param $title \string Title to check
1378 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1379 * @return \bool True if blocked, false otherwise
1381 function isBlockedFrom( $title, $bFromSlave = false ) {
1382 global $wgBlockAllowsUTEdit;
1383 wfProfileIn( __METHOD__
);
1384 wfDebug( __METHOD__
. ": enter\n" );
1386 wfDebug( __METHOD__
. ": asking isBlocked()\n" );
1387 $blocked = $this->isBlocked( $bFromSlave );
1388 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1389 # If a user's name is suppressed, they cannot make edits anywhere
1390 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1391 $title->getNamespace() == NS_USER_TALK
) {
1393 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1396 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1398 wfProfileOut( __METHOD__
);
1403 * If user is blocked, return the name of the user who placed the block
1404 * @return \string name of blocker
1406 function blockedBy() {
1407 $this->getBlockedStatus();
1408 return $this->mBlockedby
;
1412 * If user is blocked, return the specified reason for the block
1413 * @return \string Blocking reason
1415 function blockedFor() {
1416 $this->getBlockedStatus();
1417 return $this->mBlockreason
;
1421 * If user is blocked, return the ID for the block
1422 * @return \int Block ID
1424 function getBlockId() {
1425 $this->getBlockedStatus();
1426 return ( $this->mBlock ?
$this->mBlock
->mId
: false );
1430 * Check if user is blocked on all wikis.
1431 * Do not use for actual edit permission checks!
1432 * This is intented for quick UI checks.
1434 * @param $ip \type{\string} IP address, uses current client if none given
1435 * @return \type{\bool} True if blocked, false otherwise
1437 function isBlockedGlobally( $ip = '' ) {
1438 if( $this->mBlockedGlobally
!== null ) {
1439 return $this->mBlockedGlobally
;
1441 // User is already an IP?
1442 if( IP
::isIPAddress( $this->getName() ) ) {
1443 $ip = $this->getName();
1448 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1449 $this->mBlockedGlobally
= (bool)$blocked;
1450 return $this->mBlockedGlobally
;
1454 * Check if user account is locked
1456 * @return \type{\bool} True if locked, false otherwise
1458 function isLocked() {
1459 if( $this->mLocked
!== null ) {
1460 return $this->mLocked
;
1463 $authUser = $wgAuth->getUserInstance( $this );
1464 $this->mLocked
= (bool)$authUser->isLocked();
1465 return $this->mLocked
;
1469 * Check if user account is hidden
1471 * @return \type{\bool} True if hidden, false otherwise
1473 function isHidden() {
1474 if( $this->mHideName
!== null ) {
1475 return $this->mHideName
;
1477 $this->getBlockedStatus();
1478 if( !$this->mHideName
) {
1480 $authUser = $wgAuth->getUserInstance( $this );
1481 $this->mHideName
= (bool)$authUser->isHidden();
1483 return $this->mHideName
;
1487 * Get the user's ID.
1488 * @return \int The user's ID; 0 if the user is anonymous or nonexistent
1491 if( $this->mId
=== null and $this->mName
!== null
1492 and User
::isIP( $this->mName
) ) {
1493 // Special case, we know the user is anonymous
1495 } elseif( $this->mId
=== null ) {
1496 // Don't load if this was initialized from an ID
1503 * Set the user and reload all fields according to a given ID
1504 * @param $v \int User ID to reload
1506 function setId( $v ) {
1508 $this->clearInstanceCache( 'id' );
1512 * Get the user name, or the IP of an anonymous user
1513 * @return \string User's name or IP address
1515 function getName() {
1516 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1517 # Special case optimisation
1518 return $this->mName
;
1521 if ( $this->mName
=== false ) {
1523 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1525 return $this->mName
;
1530 * Set the user name.
1532 * This does not reload fields from the database according to the given
1533 * name. Rather, it is used to create a temporary "nonexistent user" for
1534 * later addition to the database. It can also be used to set the IP
1535 * address for an anonymous user to something other than the current
1538 * @note User::newFromName() has rougly the same function, when the named user
1540 * @param $str \string New user name to set
1542 function setName( $str ) {
1544 $this->mName
= $str;
1548 * Get the user's name escaped by underscores.
1549 * @return \string Username escaped by underscores.
1551 function getTitleKey() {
1552 return str_replace( ' ', '_', $this->getName() );
1556 * Check if the user has new messages.
1557 * @return \bool True if the user has new messages
1559 function getNewtalk() {
1562 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1563 if( $this->mNewtalk
=== -1 ) {
1564 $this->mNewtalk
= false; # reset talk page status
1566 # Check memcached separately for anons, who have no
1567 # entire User object stored in there.
1570 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1571 $newtalk = $wgMemc->get( $key );
1572 if( strval( $newtalk ) !== '' ) {
1573 $this->mNewtalk
= (bool)$newtalk;
1575 // Since we are caching this, make sure it is up to date by getting it
1577 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1578 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1581 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1585 return (bool)$this->mNewtalk
;
1589 * Return the talk page(s) this user has new messages on.
1590 * @return \type{\arrayof{\string}} Array of page URLs
1592 function getNewMessageLinks() {
1594 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1597 if( !$this->getNewtalk() )
1599 $up = $this->getUserPage();
1600 $utp = $up->getTalkPage();
1601 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1605 * Internal uncached check for new messages
1608 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1609 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1610 * @param $fromMaster \bool true to fetch from the master, false for a slave
1611 * @return \bool True if the user has new messages
1614 function checkNewtalk( $field, $id, $fromMaster = false ) {
1615 if ( $fromMaster ) {
1616 $db = wfGetDB( DB_MASTER
);
1618 $db = wfGetDB( DB_SLAVE
);
1620 $ok = $db->selectField( 'user_newtalk', $field,
1621 array( $field => $id ), __METHOD__
);
1622 return $ok !== false;
1626 * Add or update the new messages flag
1627 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1628 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1629 * @return \bool True if successful, false otherwise
1632 function updateNewtalk( $field, $id ) {
1633 $dbw = wfGetDB( DB_MASTER
);
1634 $dbw->insert( 'user_newtalk',
1635 array( $field => $id ),
1638 if ( $dbw->affectedRows() ) {
1639 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1642 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1648 * Clear the new messages flag for the given user
1649 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1650 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1651 * @return \bool True if successful, false otherwise
1654 function deleteNewtalk( $field, $id ) {
1655 $dbw = wfGetDB( DB_MASTER
);
1656 $dbw->delete( 'user_newtalk',
1657 array( $field => $id ),
1659 if ( $dbw->affectedRows() ) {
1660 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1663 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1669 * Update the 'You have new messages!' status.
1670 * @param $val \bool Whether the user has new messages
1672 function setNewtalk( $val ) {
1673 if( wfReadOnly() ) {
1678 $this->mNewtalk
= $val;
1680 if( $this->isAnon() ) {
1682 $id = $this->getName();
1685 $id = $this->getId();
1690 $changed = $this->updateNewtalk( $field, $id );
1692 $changed = $this->deleteNewtalk( $field, $id );
1695 if( $this->isAnon() ) {
1696 // Anons have a separate memcached space, since
1697 // user records aren't kept for them.
1698 $key = wfMemcKey( 'newtalk', 'ip', $id );
1699 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1702 $this->invalidateCache();
1707 * Generate a current or new-future timestamp to be stored in the
1708 * user_touched field when we update things.
1709 * @return \string Timestamp in TS_MW format
1711 private static function newTouchedTimestamp() {
1712 global $wgClockSkewFudge;
1713 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1717 * Clear user data from memcached.
1718 * Use after applying fun updates to the database; caller's
1719 * responsibility to update user_touched if appropriate.
1721 * Called implicitly from invalidateCache() and saveSettings().
1723 private function clearSharedCache() {
1727 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1732 * Immediately touch the user data cache for this account.
1733 * Updates user_touched field, and removes account data from memcached
1734 * for reload on the next hit.
1736 function invalidateCache() {
1737 if( wfReadOnly() ) {
1742 $this->mTouched
= self
::newTouchedTimestamp();
1744 $dbw = wfGetDB( DB_MASTER
);
1745 $dbw->update( 'user',
1746 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1747 array( 'user_id' => $this->mId
),
1750 $this->clearSharedCache();
1755 * Validate the cache for this account.
1756 * @param $timestamp \string A timestamp in TS_MW format
1758 function validateCache( $timestamp ) {
1760 return ( $timestamp >= $this->mTouched
);
1764 * Get the user touched timestamp
1766 function getTouched() {
1768 return $this->mTouched
;
1772 * Set the password and reset the random token.
1773 * Calls through to authentication plugin if necessary;
1774 * will have no effect if the auth plugin refuses to
1775 * pass the change through or if the legal password
1778 * As a special case, setting the password to null
1779 * wipes it, so the account cannot be logged in until
1780 * a new password is set, for instance via e-mail.
1782 * @param $str \string New password to set
1783 * @throws PasswordError on failure
1785 function setPassword( $str ) {
1788 if( $str !== null ) {
1789 if( !$wgAuth->allowPasswordChange() ) {
1790 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1793 if( !$this->isValidPassword( $str ) ) {
1794 global $wgMinimalPasswordLength;
1795 $valid = $this->getPasswordValidity( $str );
1796 throw new PasswordError( wfMsgExt( $valid, array( 'parsemag' ),
1797 $wgMinimalPasswordLength ) );
1801 if( !$wgAuth->setPassword( $this, $str ) ) {
1802 throw new PasswordError( wfMsg( 'externaldberror' ) );
1805 $this->setInternalPassword( $str );
1811 * Set the password and reset the random token unconditionally.
1813 * @param $str \string New password to set
1815 function setInternalPassword( $str ) {
1819 if( $str === null ) {
1820 // Save an invalid hash...
1821 $this->mPassword
= '';
1823 $this->mPassword
= self
::crypt( $str );
1825 $this->mNewpassword
= '';
1826 $this->mNewpassTime
= null;
1830 * Get the user's current token.
1831 * @return \string Token
1833 function getToken() {
1835 return $this->mToken
;
1839 * Set the random token (used for persistent authentication)
1840 * Called from loadDefaults() among other places.
1842 * @param $token \string If specified, set the token to this value
1845 function setToken( $token = false ) {
1846 global $wgSecretKey, $wgProxyKey;
1849 if ( $wgSecretKey ) {
1850 $key = $wgSecretKey;
1851 } elseif ( $wgProxyKey ) {
1856 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1858 $this->mToken
= $token;
1863 * Set the cookie password
1865 * @param $str \string New cookie password
1868 function setCookiePassword( $str ) {
1870 $this->mCookiePassword
= md5( $str );
1874 * Set the password for a password reminder or new account email
1876 * @param $str \string New password to set
1877 * @param $throttle \bool If true, reset the throttle timestamp to the present
1879 function setNewpassword( $str, $throttle = true ) {
1881 $this->mNewpassword
= self
::crypt( $str );
1883 $this->mNewpassTime
= wfTimestampNow();
1888 * Has password reminder email been sent within the last
1889 * $wgPasswordReminderResendTime hours?
1890 * @return \bool True or false
1892 function isPasswordReminderThrottled() {
1893 global $wgPasswordReminderResendTime;
1895 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1898 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1899 return time() < $expiry;
1903 * Get the user's e-mail address
1904 * @return \string User's email address
1906 function getEmail() {
1908 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1909 return $this->mEmail
;
1913 * Get the timestamp of the user's e-mail authentication
1914 * @return \string TS_MW timestamp
1916 function getEmailAuthenticationTimestamp() {
1918 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1919 return $this->mEmailAuthenticated
;
1923 * Set the user's e-mail address
1924 * @param $str \string New e-mail address
1926 function setEmail( $str ) {
1928 $this->mEmail
= $str;
1929 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1933 * Get the user's real name
1934 * @return \string User's real name
1936 function getRealName() {
1938 return $this->mRealName
;
1942 * Set the user's real name
1943 * @param $str \string New real name
1945 function setRealName( $str ) {
1947 $this->mRealName
= $str;
1951 * Get the user's current setting for a given option.
1953 * @param $oname \string The option to check
1954 * @param $defaultOverride \string A default value returned if the option does not exist
1955 * @return \string User's current value for the option
1956 * @see getBoolOption()
1957 * @see getIntOption()
1959 function getOption( $oname, $defaultOverride = null ) {
1960 $this->loadOptions();
1962 if ( is_null( $this->mOptions
) ) {
1963 if($defaultOverride != '') {
1964 return $defaultOverride;
1966 $this->mOptions
= User
::getDefaultOptions();
1969 if ( array_key_exists( $oname, $this->mOptions
) ) {
1970 return $this->mOptions
[$oname];
1972 return $defaultOverride;
1977 * Get all user's options
1981 public function getOptions() {
1982 $this->loadOptions();
1983 return $this->mOptions
;
1987 * Get the user's current setting for a given option, as a boolean value.
1989 * @param $oname \string The option to check
1990 * @return \bool User's current value for the option
1993 function getBoolOption( $oname ) {
1994 return (bool)$this->getOption( $oname );
1999 * Get the user's current setting for a given option, as a boolean value.
2001 * @param $oname \string The option to check
2002 * @param $defaultOverride \int A default value returned if the option does not exist
2003 * @return \int User's current value for the option
2006 function getIntOption( $oname, $defaultOverride=0 ) {
2007 $val = $this->getOption( $oname );
2009 $val = $defaultOverride;
2011 return intval( $val );
2015 * Set the given option for a user.
2017 * @param $oname \string The option to set
2018 * @param $val \mixed New value to set
2020 function setOption( $oname, $val ) {
2022 $this->loadOptions();
2024 if ( $oname == 'skin' ) {
2025 # Clear cached skin, so the new one displays immediately in Special:Preferences
2026 unset( $this->mSkin
);
2029 // Explicitly NULL values should refer to defaults
2030 global $wgDefaultUserOptions;
2031 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2032 $val = $wgDefaultUserOptions[$oname];
2035 $this->mOptions
[$oname] = $val;
2039 * Reset all options to the site defaults
2041 function resetOptions() {
2042 $this->mOptions
= User
::getDefaultOptions();
2046 * Get the user's preferred date format.
2047 * @return \string User's preferred date format
2049 function getDatePreference() {
2050 // Important migration for old data rows
2051 if ( is_null( $this->mDatePreference
) ) {
2053 $value = $this->getOption( 'date' );
2054 $map = $wgLang->getDatePreferenceMigrationMap();
2055 if ( isset( $map[$value] ) ) {
2056 $value = $map[$value];
2058 $this->mDatePreference
= $value;
2060 return $this->mDatePreference
;
2064 * Get the permissions this user has.
2065 * @return \type{\arrayof{\string}} Array of permission names
2067 function getRights() {
2068 if ( is_null( $this->mRights
) ) {
2069 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2070 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2071 // Force reindexation of rights when a hook has unset one of them
2072 $this->mRights
= array_values( $this->mRights
);
2074 return $this->mRights
;
2078 * Get the list of explicit group memberships this user has.
2079 * The implicit * and user groups are not included.
2080 * @return \type{\arrayof{\string}} Array of internal group names
2082 function getGroups() {
2084 return $this->mGroups
;
2088 * Get the list of implicit group memberships this user has.
2089 * This includes all explicit groups, plus 'user' if logged in,
2090 * '*' for all accounts and autopromoted groups
2091 * @param $recache \bool Whether to avoid the cache
2092 * @return \type{\arrayof{\string}} Array of internal group names
2094 function getEffectiveGroups( $recache = false ) {
2095 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2096 wfProfileIn( __METHOD__
);
2097 $this->mEffectiveGroups
= $this->getGroups();
2098 $this->mEffectiveGroups
[] = '*';
2099 if( $this->getId() ) {
2100 $this->mEffectiveGroups
[] = 'user';
2102 $this->mEffectiveGroups
= array_unique( array_merge(
2103 $this->mEffectiveGroups
,
2104 Autopromote
::getAutopromoteGroups( $this )
2107 # Hook for additional groups
2108 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2110 wfProfileOut( __METHOD__
);
2112 return $this->mEffectiveGroups
;
2116 * Get the user's edit count.
2117 * @return \int User'e edit count
2119 function getEditCount() {
2120 if( $this->getId() ) {
2121 if ( !isset( $this->mEditCount
) ) {
2122 /* Populate the count, if it has not been populated yet */
2123 $this->mEditCount
= User
::edits( $this->mId
);
2125 return $this->mEditCount
;
2133 * Add the user to the given group.
2134 * This takes immediate effect.
2135 * @param $group \string Name of the group to add
2137 function addGroup( $group ) {
2138 $dbw = wfGetDB( DB_MASTER
);
2139 if( $this->getId() ) {
2140 $dbw->insert( 'user_groups',
2142 'ug_user' => $this->getID(),
2143 'ug_group' => $group,
2146 array( 'IGNORE' ) );
2149 $this->loadGroups();
2150 $this->mGroups
[] = $group;
2151 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2153 $this->invalidateCache();
2157 * Remove the user from the given group.
2158 * This takes immediate effect.
2159 * @param $group \string Name of the group to remove
2161 function removeGroup( $group ) {
2163 $dbw = wfGetDB( DB_MASTER
);
2164 $dbw->delete( 'user_groups',
2166 'ug_user' => $this->getID(),
2167 'ug_group' => $group,
2169 'User::removeGroup' );
2171 $this->loadGroups();
2172 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2173 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2175 $this->invalidateCache();
2179 * Get whether the user is logged in
2180 * @return \bool True or false
2182 function isLoggedIn() {
2183 return $this->getID() != 0;
2187 * Get whether the user is anonymous
2188 * @return \bool True or false
2191 return !$this->isLoggedIn();
2195 * Get whether the user is a bot
2196 * @return \bool True or false
2200 wfDeprecated( __METHOD__
);
2201 return $this->isAllowed( 'bot' );
2205 * Check if user is allowed to access a feature / make an action
2206 * @param $action \string action to be checked
2207 * @return \bool True if action is allowed, else false
2209 function isAllowed( $action = '' ) {
2210 if ( $action === '' )
2211 return true; // In the spirit of DWIM
2212 # Patrolling may not be enabled
2213 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2214 global $wgUseRCPatrol, $wgUseNPPatrol;
2215 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2218 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2219 # by misconfiguration: 0 == 'foo'
2220 return in_array( $action, $this->getRights(), true );
2224 * Check whether to enable recent changes patrol features for this user
2225 * @return \bool True or false
2227 public function useRCPatrol() {
2228 global $wgUseRCPatrol;
2229 return( $wgUseRCPatrol && ( $this->isAllowed( 'patrol' ) ||
$this->isAllowed( 'patrolmarks' ) ) );
2233 * Check whether to enable new pages patrol features for this user
2234 * @return \bool True or false
2236 public function useNPPatrol() {
2237 global $wgUseRCPatrol, $wgUseNPPatrol;
2238 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowed( 'patrol' ) ||
$this->isAllowed( 'patrolmarks' ) ) );
2242 * Get the current skin, loading it if required, and setting a title
2243 * @param $t Title: the title to use in the skin
2244 * @return Skin The current skin
2245 * @todo FIXME : need to check the old failback system [AV]
2247 function &getSkin( $t = null ) {
2248 if ( !isset( $this->mSkin
) ) {
2249 wfProfileIn( __METHOD__
);
2251 global $wgHiddenPrefs;
2252 if( !in_array( 'skin', $wgHiddenPrefs ) ) {
2255 $userSkin = $this->getOption( 'skin' );
2256 $userSkin = $wgRequest->getVal( 'useskin', $userSkin );
2258 # if we're not allowing users to override, then use the default
2259 global $wgDefaultSkin;
2260 $userSkin = $wgDefaultSkin;
2263 $this->mSkin
=& Skin
::newFromKey( $userSkin );
2264 wfProfileOut( __METHOD__
);
2266 if( $t ||
!$this->mSkin
->getTitle() ) {
2269 $t = $wgOut->getTitle();
2271 $this->mSkin
->setTitle( $t );
2273 return $this->mSkin
;
2277 * Check the watched status of an article.
2278 * @param $title \type{Title} Title of the article to look at
2279 * @return \bool True if article is watched
2281 function isWatched( $title ) {
2282 $wl = WatchedItem
::fromUserTitle( $this, $title );
2283 return $wl->isWatched();
2288 * @param $title \type{Title} Title of the article to look at
2290 function addWatch( $title ) {
2291 $wl = WatchedItem
::fromUserTitle( $this, $title );
2293 $this->invalidateCache();
2297 * Stop watching an article.
2298 * @param $title \type{Title} Title of the article to look at
2300 function removeWatch( $title ) {
2301 $wl = WatchedItem
::fromUserTitle( $this, $title );
2303 $this->invalidateCache();
2307 * Clear the user's notification timestamp for the given title.
2308 * If e-notif e-mails are on, they will receive notification mails on
2309 * the next change of the page if it's watched etc.
2310 * @param $title \type{Title} Title of the article to look at
2312 function clearNotification( &$title ) {
2313 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2315 # Do nothing if the database is locked to writes
2316 if( wfReadOnly() ) {
2320 if( $title->getNamespace() == NS_USER_TALK
&&
2321 $title->getText() == $this->getName() ) {
2322 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2324 $this->setNewtalk( false );
2327 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2331 if( $this->isAnon() ) {
2332 // Nothing else to do...
2336 // Only update the timestamp if the page is being watched.
2337 // The query to find out if it is watched is cached both in memcached and per-invocation,
2338 // and when it does have to be executed, it can be on a slave
2339 // If this is the user's newtalk page, we always update the timestamp
2340 if( $title->getNamespace() == NS_USER_TALK
&&
2341 $title->getText() == $wgUser->getName() )
2344 } elseif ( $this->getId() == $wgUser->getId() ) {
2345 $watched = $title->userIsWatching();
2350 // If the page is watched by the user (or may be watched), update the timestamp on any
2351 // any matching rows
2353 $dbw = wfGetDB( DB_MASTER
);
2354 $dbw->update( 'watchlist',
2356 'wl_notificationtimestamp' => null
2357 ), array( /* WHERE */
2358 'wl_title' => $title->getDBkey(),
2359 'wl_namespace' => $title->getNamespace(),
2360 'wl_user' => $this->getID()
2367 * Resets all of the given user's page-change notification timestamps.
2368 * If e-notif e-mails are on, they will receive notification mails on
2369 * the next change of any watched page.
2371 * @param $currentUser \int User ID
2373 function clearAllNotifications( $currentUser ) {
2374 global $wgUseEnotif, $wgShowUpdatedMarker;
2375 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2376 $this->setNewtalk( false );
2379 if( $currentUser != 0 ) {
2380 $dbw = wfGetDB( DB_MASTER
);
2381 $dbw->update( 'watchlist',
2383 'wl_notificationtimestamp' => null
2384 ), array( /* WHERE */
2385 'wl_user' => $currentUser
2388 # We also need to clear here the "you have new message" notification for the own user_talk page
2389 # This is cleared one page view later in Article::viewUpdates();
2394 * Set this user's options from an encoded string
2395 * @param $str \string Encoded options to import
2398 function decodeOptions( $str ) {
2402 $this->mOptionsLoaded
= true;
2403 $this->mOptionOverrides
= array();
2405 $this->mOptions
= array();
2406 $a = explode( "\n", $str );
2407 foreach ( $a as $s ) {
2409 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2410 $this->mOptions
[$m[1]] = $m[2];
2411 $this->mOptionOverrides
[$m[1]] = $m[2];
2417 * Set a cookie on the user's client. Wrapper for
2418 * WebResponse::setCookie
2419 * @param $name \string Name of the cookie to set
2420 * @param $value \string Value to set
2421 * @param $exp \int Expiration time, as a UNIX time value;
2422 * if 0 or not specified, use the default $wgCookieExpiration
2424 protected function setCookie( $name, $value, $exp = 0 ) {
2426 $wgRequest->response()->setcookie( $name, $value, $exp );
2430 * Clear a cookie on the user's client
2431 * @param $name \string Name of the cookie to clear
2433 protected function clearCookie( $name ) {
2434 $this->setCookie( $name, '', time() - 86400 );
2438 * Set the default cookies for this session on the user's client.
2440 function setCookies() {
2442 if ( 0 == $this->mId
) return;
2444 'wsUserID' => $this->mId
,
2445 'wsToken' => $this->mToken
,
2446 'wsUserName' => $this->getName()
2449 'UserID' => $this->mId
,
2450 'UserName' => $this->getName(),
2452 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2453 $cookies['Token'] = $this->mToken
;
2455 $cookies['Token'] = false;
2458 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2459 #check for null, since the hook could cause a null value
2460 if ( !is_null( $session ) && isset( $_SESSION ) ){
2461 $_SESSION = $session +
$_SESSION;
2463 foreach ( $cookies as $name => $value ) {
2464 if ( $value === false ) {
2465 $this->clearCookie( $name );
2467 $this->setCookie( $name, $value );
2473 * Log this user out.
2476 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2482 * Clear the user's cookies and session, and reset the instance cache.
2486 function doLogout() {
2487 $this->clearInstanceCache( 'defaults' );
2489 $_SESSION['wsUserID'] = 0;
2491 $this->clearCookie( 'UserID' );
2492 $this->clearCookie( 'Token' );
2494 # Remember when user logged out, to prevent seeing cached pages
2495 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2499 * Save this user's settings into the database.
2500 * @todo Only rarely do all these fields need to be set!
2502 function saveSettings() {
2504 if ( wfReadOnly() ) { return; }
2505 if ( 0 == $this->mId
) { return; }
2507 $this->mTouched
= self
::newTouchedTimestamp();
2509 $dbw = wfGetDB( DB_MASTER
);
2510 $dbw->update( 'user',
2512 'user_name' => $this->mName
,
2513 'user_password' => $this->mPassword
,
2514 'user_newpassword' => $this->mNewpassword
,
2515 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2516 'user_real_name' => $this->mRealName
,
2517 'user_email' => $this->mEmail
,
2518 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2519 'user_options' => '',
2520 'user_touched' => $dbw->timestamp( $this->mTouched
),
2521 'user_token' => $this->mToken
,
2522 'user_email_token' => $this->mEmailToken
,
2523 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2524 ), array( /* WHERE */
2525 'user_id' => $this->mId
2529 $this->saveOptions();
2531 wfRunHooks( 'UserSaveSettings', array( $this ) );
2532 $this->clearSharedCache();
2533 $this->getUserPage()->invalidateCache();
2537 * If only this user's username is known, and it exists, return the user ID.
2539 function idForName() {
2540 $s = trim( $this->getName() );
2541 if ( $s === '' ) return 0;
2543 $dbr = wfGetDB( DB_SLAVE
);
2544 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2545 if ( $id === false ) {
2552 * Add a user to the database, return the user object
2554 * @param $name \string Username to add
2555 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2556 * - password The user's password. Password logins will be disabled if this is omitted.
2557 * - newpassword A temporary password mailed to the user
2558 * - email The user's email address
2559 * - email_authenticated The email authentication timestamp
2560 * - real_name The user's real name
2561 * - options An associative array of non-default options
2562 * - token Random authentication token. Do not set.
2563 * - registration Registration timestamp. Do not set.
2565 * @return \type{User} A new User object, or null if the username already exists
2567 static function createNew( $name, $params = array() ) {
2570 if ( isset( $params['options'] ) ) {
2571 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
2572 unset( $params['options'] );
2574 $dbw = wfGetDB( DB_MASTER
);
2575 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2577 'user_id' => $seqVal,
2578 'user_name' => $name,
2579 'user_password' => $user->mPassword
,
2580 'user_newpassword' => $user->mNewpassword
,
2581 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2582 'user_email' => $user->mEmail
,
2583 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2584 'user_real_name' => $user->mRealName
,
2585 'user_options' => '',
2586 'user_token' => $user->mToken
,
2587 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2588 'user_editcount' => 0,
2590 foreach ( $params as $name => $value ) {
2591 $fields["user_$name"] = $value;
2593 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2594 if ( $dbw->affectedRows() ) {
2595 $newUser = User
::newFromId( $dbw->insertId() );
2603 * Add this existing user object to the database
2605 function addToDatabase() {
2607 $dbw = wfGetDB( DB_MASTER
);
2608 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2609 $dbw->insert( 'user',
2611 'user_id' => $seqVal,
2612 'user_name' => $this->mName
,
2613 'user_password' => $this->mPassword
,
2614 'user_newpassword' => $this->mNewpassword
,
2615 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2616 'user_email' => $this->mEmail
,
2617 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2618 'user_real_name' => $this->mRealName
,
2619 'user_options' => '',
2620 'user_token' => $this->mToken
,
2621 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2622 'user_editcount' => 0,
2625 $this->mId
= $dbw->insertId();
2627 // Clear instance cache other than user table data, which is already accurate
2628 $this->clearInstanceCache();
2630 $this->saveOptions();
2634 * If this (non-anonymous) user is blocked, block any IP address
2635 * they've successfully logged in from.
2637 function spreadBlock() {
2638 wfDebug( __METHOD__
. "()\n" );
2640 if ( $this->mId
== 0 ) {
2644 $userblock = Block
::newFromDB( '', $this->mId
);
2645 if ( !$userblock ) {
2649 $userblock->doAutoblock( wfGetIP() );
2653 * Generate a string which will be different for any combination of
2654 * user options which would produce different parser output.
2655 * This will be used as part of the hash key for the parser cache,
2656 * so users with the same options can share the same cached data
2659 * Extensions which require it should install 'PageRenderingHash' hook,
2660 * which will give them a chance to modify this key based on their own
2663 * @return \string Page rendering hash
2665 function getPageRenderingHash() {
2666 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2668 return $this->mHash
;
2671 // stubthreshold is only included below for completeness,
2672 // it will always be 0 when this function is called by parsercache.
2674 $confstr = $this->getOption( 'math' );
2675 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2676 if ( $wgUseDynamicDates ) {
2677 $confstr .= '!' . $this->getDatePreference();
2679 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
2680 $confstr .= '!' . $wgLang->getCode();
2681 $confstr .= '!' . $this->getOption( 'thumbsize' );
2682 // add in language specific options, if any
2683 $extra = $wgContLang->getExtraHashOptions();
2686 $confstr .= $wgRenderHashAppend;
2688 // Give a chance for extensions to modify the hash, if they have
2689 // extra options or other effects on the parser cache.
2690 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2692 // Make it a valid memcached key fragment
2693 $confstr = str_replace( ' ', '_', $confstr );
2694 $this->mHash
= $confstr;
2699 * Get whether the user is explicitly blocked from account creation.
2700 * @return \bool True if blocked
2702 function isBlockedFromCreateAccount() {
2703 $this->getBlockedStatus();
2704 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2708 * Get whether the user is blocked from using Special:Emailuser.
2709 * @return \bool True if blocked
2711 function isBlockedFromEmailuser() {
2712 $this->getBlockedStatus();
2713 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2717 * Get whether the user is allowed to create an account.
2718 * @return \bool True if allowed
2720 function isAllowedToCreateAccount() {
2721 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2727 function setLoaded( $loaded ) {
2728 wfDeprecated( __METHOD__
);
2732 * Get this user's personal page title.
2734 * @return \type{Title} User's personal page title
2736 function getUserPage() {
2737 return Title
::makeTitle( NS_USER
, $this->getName() );
2741 * Get this user's talk page title.
2743 * @return \type{Title} User's talk page title
2745 function getTalkPage() {
2746 $title = $this->getUserPage();
2747 return $title->getTalkPage();
2751 * Get the maximum valid user ID.
2752 * @return \int User ID
2755 function getMaxID() {
2756 static $res; // cache
2758 if ( isset( $res ) )
2761 $dbr = wfGetDB( DB_SLAVE
);
2762 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2767 * Determine whether the user is a newbie. Newbies are either
2768 * anonymous IPs, or the most recently created accounts.
2769 * @return \bool True if the user is a newbie
2771 function isNewbie() {
2772 return !$this->isAllowed( 'autoconfirmed' );
2776 * Check to see if the given clear-text password is one of the accepted passwords
2777 * @param $password \string user password.
2778 * @return \bool True if the given password is correct, otherwise False.
2780 function checkPassword( $password ) {
2784 // Even though we stop people from creating passwords that
2785 // are shorter than this, doesn't mean people wont be able
2786 // to. Certain authentication plugins do NOT want to save
2787 // domain passwords in a mysql database, so we should
2788 // check this (incase $wgAuth->strict() is false).
2789 if( !$this->isValidPassword( $password ) ) {
2793 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2795 } elseif( $wgAuth->strict() ) {
2796 /* Auth plugin doesn't allow local authentication */
2798 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2799 /* Auth plugin doesn't allow local authentication for this user name */
2802 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2804 } elseif ( function_exists( 'iconv' ) ) {
2805 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2806 # Check for this with iconv
2807 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2808 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2816 * Check if the given clear-text password matches the temporary password
2817 * sent by e-mail for password reset operations.
2818 * @return \bool True if matches, false otherwise
2820 function checkTemporaryPassword( $plaintext ) {
2821 global $wgNewPasswordExpiry;
2822 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
2824 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
2825 return ( time() < $expiry );
2832 * Initialize (if necessary) and return a session token value
2833 * which can be used in edit forms to show that the user's
2834 * login credentials aren't being hijacked with a foreign form
2837 * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2838 * @return \string The new edit token
2840 function editToken( $salt = '' ) {
2841 if ( $this->isAnon() ) {
2842 return EDIT_TOKEN_SUFFIX
;
2844 if( !isset( $_SESSION['wsEditToken'] ) ) {
2845 $token = $this->generateToken();
2846 $_SESSION['wsEditToken'] = $token;
2848 $token = $_SESSION['wsEditToken'];
2850 if( is_array( $salt ) ) {
2851 $salt = implode( '|', $salt );
2853 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2858 * Generate a looking random token for various uses.
2860 * @param $salt \string Optional salt value
2861 * @return \string The new random token
2863 function generateToken( $salt = '' ) {
2864 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2865 return md5( $token . $salt );
2869 * Check given value against the token value stored in the session.
2870 * A match should confirm that the form was submitted from the
2871 * user's own login session, not a form submission from a third-party
2874 * @param $val \string Input value to compare
2875 * @param $salt \string Optional function-specific data for hashing
2876 * @return \bool Whether the token matches
2878 function matchEditToken( $val, $salt = '' ) {
2879 $sessionToken = $this->editToken( $salt );
2880 if ( $val != $sessionToken ) {
2881 wfDebug( "User::matchEditToken: broken session data\n" );
2883 return $val == $sessionToken;
2887 * Check given value against the token value stored in the session,
2888 * ignoring the suffix.
2890 * @param $val \string Input value to compare
2891 * @param $salt \string Optional function-specific data for hashing
2892 * @return \bool Whether the token matches
2894 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2895 $sessionToken = $this->editToken( $salt );
2896 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2900 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2901 * mail to the user's given address.
2903 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure.
2905 function sendConfirmationMail() {
2907 $expiration = null; // gets passed-by-ref and defined in next line.
2908 $token = $this->confirmationToken( $expiration );
2909 $url = $this->confirmationTokenUrl( $token );
2910 $invalidateURL = $this->invalidationTokenUrl( $token );
2911 $this->saveSettings();
2913 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2914 wfMsg( 'confirmemail_body',
2918 $wgLang->timeanddate( $expiration, false ),
2920 $wgLang->date( $expiration, false ),
2921 $wgLang->time( $expiration, false ) ) );
2925 * Send an e-mail to this user's account. Does not check for
2926 * confirmed status or validity.
2928 * @param $subject \string Message subject
2929 * @param $body \string Message body
2930 * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2931 * @param $replyto \string Reply-To address
2932 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure
2934 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2935 if( is_null( $from ) ) {
2936 global $wgPasswordSender;
2937 $from = $wgPasswordSender;
2940 $to = new MailAddress( $this );
2941 $sender = new MailAddress( $from );
2942 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2946 * Generate, store, and return a new e-mail confirmation code.
2947 * A hash (unsalted, since it's used as a key) is stored.
2949 * @note Call saveSettings() after calling this function to commit
2950 * this change to the database.
2952 * @param[out] &$expiration \mixed Accepts the expiration time
2953 * @return \string New token
2956 function confirmationToken( &$expiration ) {
2958 $expires = $now +
7 * 24 * 60 * 60;
2959 $expiration = wfTimestamp( TS_MW
, $expires );
2960 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2961 $hash = md5( $token );
2963 $this->mEmailToken
= $hash;
2964 $this->mEmailTokenExpires
= $expiration;
2969 * Return a URL the user can use to confirm their email address.
2970 * @param $token \string Accepts the email confirmation token
2971 * @return \string New token URL
2974 function confirmationTokenUrl( $token ) {
2975 return $this->getTokenUrl( 'ConfirmEmail', $token );
2979 * Return a URL the user can use to invalidate their email address.
2980 * @param $token \string Accepts the email confirmation token
2981 * @return \string New token URL
2984 function invalidationTokenUrl( $token ) {
2985 return $this->getTokenUrl( 'Invalidateemail', $token );
2989 * Internal function to format the e-mail validation/invalidation URLs.
2990 * This uses $wgArticlePath directly as a quickie hack to use the
2991 * hardcoded English names of the Special: pages, for ASCII safety.
2993 * @note Since these URLs get dropped directly into emails, using the
2994 * short English names avoids insanely long URL-encoded links, which
2995 * also sometimes can get corrupted in some browsers/mailers
2996 * (bug 6957 with Gmail and Internet Explorer).
2998 * @param $page \string Special page
2999 * @param $token \string Token
3000 * @return \string Formatted URL
3002 protected function getTokenUrl( $page, $token ) {
3003 global $wgArticlePath;
3007 "Special:$page/$token",
3012 * Mark the e-mail address confirmed.
3014 * @note Call saveSettings() after calling this function to commit the change.
3016 function confirmEmail() {
3017 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3018 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3023 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3024 * address if it was already confirmed.
3026 * @note Call saveSettings() after calling this function to commit the change.
3028 function invalidateEmail() {
3030 $this->mEmailToken
= null;
3031 $this->mEmailTokenExpires
= null;
3032 $this->setEmailAuthenticationTimestamp( null );
3033 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3038 * Set the e-mail authentication timestamp.
3039 * @param $timestamp \string TS_MW timestamp
3041 function setEmailAuthenticationTimestamp( $timestamp ) {
3043 $this->mEmailAuthenticated
= $timestamp;
3044 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3048 * Is this user allowed to send e-mails within limits of current
3049 * site configuration?
3050 * @return \bool True if allowed
3052 function canSendEmail() {
3053 global $wgEnableEmail, $wgEnableUserEmail, $wgUser;
3054 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$wgUser->isAllowed( 'sendemail' ) ) {
3057 $canSend = $this->isEmailConfirmed();
3058 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3063 * Is this user allowed to receive e-mails within limits of current
3064 * site configuration?
3065 * @return \bool True if allowed
3067 function canReceiveEmail() {
3068 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3072 * Is this user's e-mail address valid-looking and confirmed within
3073 * limits of the current site configuration?
3075 * @note If $wgEmailAuthentication is on, this may require the user to have
3076 * confirmed their address by returning a code or using a password
3077 * sent to the address from the wiki.
3079 * @return \bool True if confirmed
3081 function isEmailConfirmed() {
3082 global $wgEmailAuthentication;
3085 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3086 if( $this->isAnon() )
3088 if( !self
::isValidEmailAddr( $this->mEmail
) )
3090 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3099 * Check whether there is an outstanding request for e-mail confirmation.
3100 * @return \bool True if pending
3102 function isEmailConfirmationPending() {
3103 global $wgEmailAuthentication;
3104 return $wgEmailAuthentication &&
3105 !$this->isEmailConfirmed() &&
3106 $this->mEmailToken
&&
3107 $this->mEmailTokenExpires
> wfTimestamp();
3111 * Get the timestamp of account creation.
3113 * @return \types{\string,\bool} string Timestamp of account creation, or false for
3114 * non-existent/anonymous user accounts.
3116 public function getRegistration() {
3117 return $this->getId() > 0
3118 ?
$this->mRegistration
3123 * Get the timestamp of the first edit
3125 * @return \types{\string,\bool} string Timestamp of first edit, or false for
3126 * non-existent/anonymous user accounts.
3128 public function getFirstEditTimestamp() {
3129 if( $this->getId() == 0 ) return false; // anons
3130 $dbr = wfGetDB( DB_SLAVE
);
3131 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3132 array( 'rev_user' => $this->getId() ),
3134 array( 'ORDER BY' => 'rev_timestamp ASC' )
3136 if( !$time ) return false; // no edits
3137 return wfTimestamp( TS_MW
, $time );
3141 * Get the permissions associated with a given list of groups
3143 * @param $groups \type{\arrayof{\string}} List of internal group names
3144 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3146 static function getGroupPermissions( $groups ) {
3147 global $wgGroupPermissions, $wgRevokePermissions;
3149 // grant every granted permission first
3150 foreach( $groups as $group ) {
3151 if( isset( $wgGroupPermissions[$group] ) ) {
3152 $rights = array_merge( $rights,
3153 // array_filter removes empty items
3154 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3157 // now revoke the revoked permissions
3158 foreach( $groups as $group ) {
3159 if( isset( $wgRevokePermissions[$group] ) ) {
3160 $rights = array_diff( $rights,
3161 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3164 return array_unique( $rights );
3168 * Get all the groups who have a given permission
3170 * @param $role \string Role to check
3171 * @return \type{\arrayof{\string}} List of internal group names with the given permission
3173 static function getGroupsWithPermission( $role ) {
3174 global $wgGroupPermissions;
3175 $allowedGroups = array();
3176 foreach ( $wgGroupPermissions as $group => $rights ) {
3177 if ( isset( $rights[$role] ) && $rights[$role] ) {
3178 $allowedGroups[] = $group;
3181 return $allowedGroups;
3185 * Get the localized descriptive name for a group, if it exists
3187 * @param $group \string Internal group name
3188 * @return \string Localized descriptive group name
3190 static function getGroupName( $group ) {
3191 global $wgMessageCache;
3192 $wgMessageCache->loadAllMessages();
3193 $key = "group-$group";
3194 $name = wfMsg( $key );
3195 return $name == '' ||
wfEmptyMsg( $key, $name )
3201 * Get the localized descriptive name for a member of a group, if it exists
3203 * @param $group \string Internal group name
3204 * @return \string Localized name for group member
3206 static function getGroupMember( $group ) {
3207 global $wgMessageCache;
3208 $wgMessageCache->loadAllMessages();
3209 $key = "group-$group-member";
3210 $name = wfMsg( $key );
3211 return $name == '' ||
wfEmptyMsg( $key, $name )
3217 * Return the set of defined explicit groups.
3218 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3219 * are not included, as they are defined automatically, not in the database.
3220 * @return \type{\arrayof{\string}} Array of internal group names
3222 static function getAllGroups() {
3223 global $wgGroupPermissions, $wgRevokePermissions;
3225 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3226 self
::getImplicitGroups()
3231 * Get a list of all available permissions.
3232 * @return \type{\arrayof{\string}} Array of permission names
3234 static function getAllRights() {
3235 if ( self
::$mAllRights === false ) {
3236 global $wgAvailableRights;
3237 if ( count( $wgAvailableRights ) ) {
3238 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3240 self
::$mAllRights = self
::$mCoreRights;
3242 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3244 return self
::$mAllRights;
3248 * Get a list of implicit groups
3249 * @return \type{\arrayof{\string}} Array of internal group names
3251 public static function getImplicitGroups() {
3252 global $wgImplicitGroups;
3253 $groups = $wgImplicitGroups;
3254 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3259 * Get the title of a page describing a particular group
3261 * @param $group \string Internal group name
3262 * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3264 static function getGroupPage( $group ) {
3265 global $wgMessageCache;
3266 $wgMessageCache->loadAllMessages();
3267 $page = wfMsgForContent( 'grouppage-' . $group );
3268 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3269 $title = Title
::newFromText( $page );
3270 if( is_object( $title ) )
3277 * Create a link to the group in HTML, if available;
3278 * else return the group name.
3280 * @param $group \string Internal name of the group
3281 * @param $text \string The text of the link
3282 * @return \string HTML link to the group
3284 static function makeGroupLinkHTML( $group, $text = '' ) {
3286 $text = self
::getGroupName( $group );
3288 $title = self
::getGroupPage( $group );
3291 $sk = $wgUser->getSkin();
3292 return $sk->link( $title, htmlspecialchars( $text ) );
3299 * Create a link to the group in Wikitext, if available;
3300 * else return the group name.
3302 * @param $group \string Internal name of the group
3303 * @param $text \string The text of the link
3304 * @return \string Wikilink to the group
3306 static function makeGroupLinkWiki( $group, $text = '' ) {
3308 $text = self
::getGroupName( $group );
3310 $title = self
::getGroupPage( $group );
3312 $page = $title->getPrefixedText();
3313 return "[[$page|$text]]";
3320 * Returns an array of the groups that a particular group can add/remove.
3322 * @param $group String: the group to check for whether it can add/remove
3323 * @return Array array( 'add' => array( addablegroups ),
3324 * 'remove' => array( removablegroups ),
3325 * 'add-self' => array( addablegroups to self),
3326 * 'remove-self' => array( removable groups from self) )
3328 static function changeableByGroup( $group ) {
3329 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3331 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3332 if( empty( $wgAddGroups[$group] ) ) {
3333 // Don't add anything to $groups
3334 } elseif( $wgAddGroups[$group] === true ) {
3335 // You get everything
3336 $groups['add'] = self
::getAllGroups();
3337 } elseif( is_array( $wgAddGroups[$group] ) ) {
3338 $groups['add'] = $wgAddGroups[$group];
3341 // Same thing for remove
3342 if( empty( $wgRemoveGroups[$group] ) ) {
3343 } elseif( $wgRemoveGroups[$group] === true ) {
3344 $groups['remove'] = self
::getAllGroups();
3345 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3346 $groups['remove'] = $wgRemoveGroups[$group];
3349 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3350 if( empty( $wgGroupsAddToSelf['user']) ||
$wgGroupsAddToSelf['user'] !== true ) {
3351 foreach( $wgGroupsAddToSelf as $key => $value ) {
3352 if( is_int( $key ) ) {
3353 $wgGroupsAddToSelf['user'][] = $value;
3358 if( empty( $wgGroupsRemoveFromSelf['user']) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
3359 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3360 if( is_int( $key ) ) {
3361 $wgGroupsRemoveFromSelf['user'][] = $value;
3366 // Now figure out what groups the user can add to him/herself
3367 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3368 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3369 // No idea WHY this would be used, but it's there
3370 $groups['add-self'] = User
::getAllGroups();
3371 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3372 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3375 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3376 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3377 $groups['remove-self'] = User
::getAllGroups();
3378 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3379 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3386 * Returns an array of groups that this user can add and remove
3387 * @return Array array( 'add' => array( addablegroups ),
3388 * 'remove' => array( removablegroups ),
3389 * 'add-self' => array( addablegroups to self),
3390 * 'remove-self' => array( removable groups from self) )
3392 function changeableGroups() {
3393 if( $this->isAllowed( 'userrights' ) ) {
3394 // This group gives the right to modify everything (reverse-
3395 // compatibility with old "userrights lets you change
3397 // Using array_merge to make the groups reindexed
3398 $all = array_merge( User
::getAllGroups() );
3402 'add-self' => array(),
3403 'remove-self' => array()
3407 // Okay, it's not so simple, we will have to go through the arrays
3410 'remove' => array(),
3411 'add-self' => array(),
3412 'remove-self' => array()
3414 $addergroups = $this->getEffectiveGroups();
3416 foreach( $addergroups as $addergroup ) {
3417 $groups = array_merge_recursive(
3418 $groups, $this->changeableByGroup( $addergroup )
3420 $groups['add'] = array_unique( $groups['add'] );
3421 $groups['remove'] = array_unique( $groups['remove'] );
3422 $groups['add-self'] = array_unique( $groups['add-self'] );
3423 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3429 * Increment the user's edit-count field.
3430 * Will have no effect for anonymous users.
3432 function incEditCount() {
3433 if( !$this->isAnon() ) {
3434 $dbw = wfGetDB( DB_MASTER
);
3435 $dbw->update( 'user',
3436 array( 'user_editcount=user_editcount+1' ),
3437 array( 'user_id' => $this->getId() ),
3440 // Lazy initialization check...
3441 if( $dbw->affectedRows() == 0 ) {
3442 // Pull from a slave to be less cruel to servers
3443 // Accuracy isn't the point anyway here
3444 $dbr = wfGetDB( DB_SLAVE
);
3445 $count = $dbr->selectField( 'revision',
3447 array( 'rev_user' => $this->getId() ),
3450 // Now here's a goddamn hack...
3451 if( $dbr !== $dbw ) {
3452 // If we actually have a slave server, the count is
3453 // at least one behind because the current transaction
3454 // has not been committed and replicated.
3457 // But if DB_SLAVE is selecting the master, then the
3458 // count we just read includes the revision that was
3459 // just added in the working transaction.
3462 $dbw->update( 'user',
3463 array( 'user_editcount' => $count ),
3464 array( 'user_id' => $this->getId() ),
3468 // edit count in user cache too
3469 $this->invalidateCache();
3473 * Get the description of a given right
3475 * @param $right \string Right to query
3476 * @return \string Localized description of the right
3478 static function getRightDescription( $right ) {
3479 global $wgMessageCache;
3480 $wgMessageCache->loadAllMessages();
3481 $key = "right-$right";
3482 $name = wfMsg( $key );
3483 return $name == '' ||
wfEmptyMsg( $key, $name )
3489 * Make an old-style password hash
3491 * @param $password \string Plain-text password
3492 * @param $userId \string User ID
3493 * @return \string Password hash
3495 static function oldCrypt( $password, $userId ) {
3496 global $wgPasswordSalt;
3497 if ( $wgPasswordSalt ) {
3498 return md5( $userId . '-' . md5( $password ) );
3500 return md5( $password );
3505 * Make a new-style password hash
3507 * @param $password \string Plain-text password
3508 * @param $salt \string Optional salt, may be random or the user ID.
3509 * If unspecified or false, will generate one automatically
3510 * @return \string Password hash
3512 static function crypt( $password, $salt = false ) {
3513 global $wgPasswordSalt;
3516 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3520 if( $wgPasswordSalt ) {
3521 if ( $salt === false ) {
3522 $salt = substr( wfGenerateToken(), 0, 8 );
3524 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3526 return ':A:' . md5( $password );
3531 * Compare a password hash with a plain-text password. Requires the user
3532 * ID if there's a chance that the hash is an old-style hash.
3534 * @param $hash \string Password hash
3535 * @param $password \string Plain-text password to compare
3536 * @param $userId \string User ID for old-style password salt
3539 static function comparePasswords( $hash, $password, $userId = false ) {
3541 $type = substr( $hash, 0, 3 );
3544 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3548 if ( $type == ':A:' ) {
3550 return md5( $password ) === substr( $hash, 3 );
3551 } elseif ( $type == ':B:' ) {
3553 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3554 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3557 return self
::oldCrypt( $password, $userId ) === $hash;
3562 * Add a newuser log entry for this user
3563 * @param $byEmail Boolean: account made by email?
3565 public function addNewUserLogEntry( $byEmail = false ) {
3566 global $wgUser, $wgNewUserLog;
3567 if( empty( $wgNewUserLog ) ) {
3568 return true; // disabled
3571 if( $this->getName() == $wgUser->getName() ) {
3575 $action = 'create2';
3577 ?
wfMsgForContent( 'newuserlog-byemail' )
3580 $log = new LogPage( 'newusers' );
3583 $this->getUserPage(),
3585 array( $this->getId() )
3591 * Add an autocreate newuser log entry for this user
3592 * Used by things like CentralAuth and perhaps other authplugins.
3594 public function addNewUserLogEntryAutoCreate() {
3595 global $wgNewUserLog;
3596 if( empty( $wgNewUserLog ) ) {
3597 return true; // disabled
3599 $log = new LogPage( 'newusers', false );
3600 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3604 protected function loadOptions() {
3606 if ( $this->mOptionsLoaded ||
!$this->getId() )
3609 $this->mOptions
= self
::getDefaultOptions();
3611 // Maybe load from the object
3612 if ( !is_null( $this->mOptionOverrides
) ) {
3613 wfDebug( "Loading options for user " . $this->getId() . " from override cache.\n" );
3614 foreach( $this->mOptionOverrides
as $key => $value ) {
3615 $this->mOptions
[$key] = $value;
3618 wfDebug( "Loading options for user " . $this->getId() . " from database.\n" );
3619 // Load from database
3620 $dbr = wfGetDB( DB_SLAVE
);
3622 $res = $dbr->select(
3625 array( 'up_user' => $this->getId() ),
3629 while( $row = $dbr->fetchObject( $res ) ) {
3630 $this->mOptionOverrides
[$row->up_property
] = $row->up_value
;
3631 $this->mOptions
[$row->up_property
] = $row->up_value
;
3635 $this->mOptionsLoaded
= true;
3637 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
3640 protected function saveOptions() {
3641 global $wgAllowPrefChange;
3643 $extuser = ExternalUser
::newFromUser( $this );
3645 $this->loadOptions();
3646 $dbw = wfGetDB( DB_MASTER
);
3648 $insert_rows = array();
3650 $saveOptions = $this->mOptions
;
3652 // Allow hooks to abort, for instance to save to a global profile.
3653 // Reset options to default state before saving.
3654 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3657 foreach( $saveOptions as $key => $value ) {
3658 # Don't bother storing default values
3659 if ( ( is_null( self
::getDefaultOption( $key ) ) &&
3660 !( $value === false ||
is_null($value) ) ) ||
3661 $value != self
::getDefaultOption( $key ) ) {
3662 $insert_rows[] = array(
3663 'up_user' => $this->getId(),
3664 'up_property' => $key,
3665 'up_value' => $value,
3668 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3669 switch ( $wgAllowPrefChange[$key] ) {
3675 $extuser->setPref( $key, $value );
3681 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__
);
3682 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
);
3687 * Provide an array of HTML5 attributes to put on an input element
3688 * intended for the user to enter a new password. This may include
3689 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3691 * Do *not* use this when asking the user to enter his current password!
3692 * Regardless of configuration, users may have invalid passwords for whatever
3693 * reason (e.g., they were set before requirements were tightened up).
3694 * Only use it when asking for a new password, like on account creation or
3697 * Obviously, you still need to do server-side checking.
3699 * @return array Array of HTML attributes suitable for feeding to
3700 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3701 * That will potentially output invalid XHTML 1.0 Transitional, and will
3702 * get confused by the boolean attribute syntax used.)
3704 public static function passwordChangeInputAttribs() {
3705 global $wgMinimalPasswordLength;
3707 if ( $wgMinimalPasswordLength == 0 ) {
3711 # Note that the pattern requirement will always be satisfied if the
3712 # input is empty, so we need required in all cases.
3713 $ret = array( 'required' );
3715 # We can't actually do this right now, because Opera 9.6 will print out
3716 # the entered password visibly in its error message! When other
3717 # browsers add support for this attribute, or Opera fixes its support,
3718 # we can add support with a version check to avoid doing this on Opera
3719 # versions where it will be a problem. Reported to Opera as
3720 # DSK-262266, but they don't have a public bug tracker for us to follow.
3722 if ( $wgMinimalPasswordLength > 1 ) {
3723 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3724 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3725 $wgMinimalPasswordLength );