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 ( $name === false ) {
360 # Create unloaded user object
369 * Static factory method for creation from a given user ID.
371 * @param $id \int Valid user ID
372 * @return \type{User} The corresponding User object
374 static function newFromId( $id ) {
382 * Factory method to fetch whichever user has a given email confirmation code.
383 * This code is generated when an account is created or its e-mail address
386 * If the code is invalid or has expired, returns NULL.
388 * @param $code \string Confirmation code
389 * @return \type{User}
391 static function newFromConfirmationCode( $code ) {
392 $dbr = wfGetDB( DB_SLAVE
);
393 $id = $dbr->selectField( 'user', 'user_id', array(
394 'user_email_token' => md5( $code ),
395 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
397 if( $id !== false ) {
398 return User
::newFromId( $id );
405 * Create a new user object using data from session or cookies. If the
406 * login credentials are invalid, the result is an anonymous user.
408 * @return \type{User}
410 static function newFromSession() {
412 $user->mFrom
= 'session';
417 * Create a new user object from a user row.
418 * The row should have all fields from the user table in it.
419 * @param $row array A row from the user table
420 * @return \type{User}
422 static function newFromRow( $row ) {
424 $user->loadFromRow( $row );
432 * Get the username corresponding to a given user ID
433 * @param $id \int User ID
434 * @return \string The corresponding username
436 static function whoIs( $id ) {
437 $dbr = wfGetDB( DB_SLAVE
);
438 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
442 * Get the real name of a user given their user ID
444 * @param $id \int User ID
445 * @return \string The corresponding user's real name
447 static function whoIsReal( $id ) {
448 $dbr = wfGetDB( DB_SLAVE
);
449 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
453 * Get database id given a user name
454 * @param $name \string Username
455 * @return \types{\int,\null} The corresponding user's ID, or null if user is nonexistent
457 static function idFromName( $name ) {
458 $nt = Title
::makeTitleSafe( NS_USER
, $name );
459 if( is_null( $nt ) ) {
464 if ( isset( self
::$idCacheByName[$name] ) ) {
465 return self
::$idCacheByName[$name];
468 $dbr = wfGetDB( DB_SLAVE
);
469 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
471 if ( $s === false ) {
474 $result = $s->user_id
;
477 self
::$idCacheByName[$name] = $result;
479 if ( count( self
::$idCacheByName ) > 1000 ) {
480 self
::$idCacheByName = array();
487 * Does the string match an anonymous IPv4 address?
489 * This function exists for username validation, in order to reject
490 * usernames which are similar in form to IP addresses. Strings such
491 * as 300.300.300.300 will return true because it looks like an IP
492 * address, despite not being strictly valid.
494 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
495 * address because the usemod software would "cloak" anonymous IP
496 * addresses like this, if we allowed accounts like this to be created
497 * new users could get the old edits of these anonymous users.
499 * @param $name \string String to match
500 * @return \bool True or false
502 static function isIP( $name ) {
503 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
507 * Is the input a valid username?
509 * Checks if the input is a valid username, we don't want an empty string,
510 * an IP address, anything that containins slashes (would mess up subpages),
511 * is longer than the maximum allowed username size or doesn't begin with
514 * @param $name \string String to match
515 * @return \bool True or false
517 static function isValidUserName( $name ) {
518 global $wgContLang, $wgMaxNameChars;
521 || User
::isIP( $name )
522 ||
strpos( $name, '/' ) !== false
523 ||
strlen( $name ) > $wgMaxNameChars
524 ||
$name != $wgContLang->ucfirst( $name ) ) {
525 wfDebugLog( 'username', __METHOD__
.
526 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
530 // Ensure that the name can't be misresolved as a different title,
531 // such as with extra namespace keys at the start.
532 $parsed = Title
::newFromText( $name );
533 if( is_null( $parsed )
534 ||
$parsed->getNamespace()
535 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
536 wfDebugLog( 'username', __METHOD__
.
537 ": '$name' invalid due to ambiguous prefixes" );
541 // Check an additional blacklist of troublemaker characters.
542 // Should these be merged into the title char list?
543 $unicodeBlacklist = '/[' .
544 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
545 '\x{00a0}' . # non-breaking space
546 '\x{2000}-\x{200f}' . # various whitespace
547 '\x{2028}-\x{202f}' . # breaks and control chars
548 '\x{3000}' . # ideographic space
549 '\x{e000}-\x{f8ff}' . # private use
551 if( preg_match( $unicodeBlacklist, $name ) ) {
552 wfDebugLog( 'username', __METHOD__
.
553 ": '$name' invalid due to blacklisted characters" );
561 * Usernames which fail to pass this function will be blocked
562 * from user login and new account registrations, but may be used
563 * internally by batch processes.
565 * If an account already exists in this form, login will be blocked
566 * by a failure to pass this function.
568 * @param $name \string String to match
569 * @return \bool True or false
571 static function isUsableName( $name ) {
572 global $wgReservedUsernames;
573 // Must be a valid username, obviously ;)
574 if ( !self
::isValidUserName( $name ) ) {
578 static $reservedUsernames = false;
579 if ( !$reservedUsernames ) {
580 $reservedUsernames = $wgReservedUsernames;
581 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
584 // Certain names may be reserved for batch processes.
585 foreach ( $reservedUsernames as $reserved ) {
586 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
587 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
589 if ( $reserved == $name ) {
597 * Usernames which fail to pass this function will be blocked
598 * from new account registrations, but may be used internally
599 * either by batch processes or by user accounts which have
600 * already been created.
602 * Additional character blacklisting may be added here
603 * rather than in isValidUserName() to avoid disrupting
606 * @param $name \string String to match
607 * @return \bool True or false
609 static function isCreatableName( $name ) {
610 global $wgInvalidUsernameCharacters;
612 self
::isUsableName( $name ) &&
614 // Registration-time character blacklisting...
615 !preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name );
619 * Is the input a valid password for this user?
621 * @param $password String Desired password
622 * @return bool True or false
624 function isValidPassword( $password ) {
625 global $wgMinimalPasswordLength, $wgContLang;
627 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
629 if( $result === false )
632 // Password needs to be long enough, and can't be the same as the username
633 return strlen( $password ) >= $wgMinimalPasswordLength
634 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
638 * Given unvalidated password input, return error message on failure.
640 * @param $password String Desired password
641 * @return mixed: true on success, string of error message on failure
643 function getPasswordValidity( $password ) {
644 global $wgMinimalPasswordLength, $wgContLang;
646 if ( !$this->isValidPassword( $password ) ) {
647 if( strlen( $password ) < $wgMinimalPasswordLength ) {
648 return 'passwordtooshort';
649 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
650 return 'password-name-match';
658 * Does a string look like an e-mail address?
660 * There used to be a regular expression here, it got removed because it
661 * rejected valid addresses. Actually just check if there is '@' somewhere
662 * in the given address.
664 * @todo Check for RFC 2822 compilance (bug 959)
666 * @param $addr \string E-mail address
667 * @return \bool True or false
669 public static function isValidEmailAddr( $addr ) {
671 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
675 return strpos( $addr, '@' ) !== false;
679 * Given unvalidated user input, return a canonical username, or false if
680 * the username is invalid.
681 * @param $name \string User input
682 * @param $validate \types{\string,\bool} Type of validation to use:
683 * - false No validation
684 * - 'valid' Valid for batch processes
685 * - 'usable' Valid for batch processes and login
686 * - 'creatable' Valid for batch processes, login and account creation
688 static function getCanonicalName( $name, $validate = 'valid' ) {
689 # Maybe force usernames to capital
690 $name = Title
::capitalize( $name, NS_USER
);
692 # Reject names containing '#'; these will be cleaned up
693 # with title normalisation, but then it's too late to
695 if( strpos( $name, '#' ) !== false )
698 # Clean up name according to title rules
699 $t = ( $validate === 'valid' ) ?
700 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
701 # Check for invalid titles
702 if( is_null( $t ) ) {
706 # Reject various classes of invalid names
707 $name = $t->getText();
709 $name = $wgAuth->getCanonicalName( $t->getText() );
711 switch ( $validate ) {
715 if ( !User
::isValidUserName( $name ) ) {
720 if ( !User
::isUsableName( $name ) ) {
725 if ( !User
::isCreatableName( $name ) ) {
730 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
736 * Count the number of edits of a user
737 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
739 * @param $uid \int User ID to check
740 * @return \int The user's edit count
742 static function edits( $uid ) {
743 wfProfileIn( __METHOD__
);
744 $dbr = wfGetDB( DB_SLAVE
);
745 // check if the user_editcount field has been initialized
746 $field = $dbr->selectField(
747 'user', 'user_editcount',
748 array( 'user_id' => $uid ),
752 if( $field === null ) { // it has not been initialized. do so.
753 $dbw = wfGetDB( DB_MASTER
);
754 $count = $dbr->selectField(
755 'revision', 'count(*)',
756 array( 'rev_user' => $uid ),
761 array( 'user_editcount' => $count ),
762 array( 'user_id' => $uid ),
768 wfProfileOut( __METHOD__
);
773 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
774 * @todo hash random numbers to improve security, like generateToken()
776 * @return \string New random password
778 static function randomPassword() {
779 global $wgMinimalPasswordLength;
780 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
781 $l = strlen( $pwchars ) - 1;
783 $pwlength = max( 7, $wgMinimalPasswordLength );
784 $digit = mt_rand( 0, $pwlength - 1 );
786 for ( $i = 0; $i < $pwlength; $i++
) {
787 $np .= $i == $digit ?
chr( mt_rand( 48, 57 ) ) : $pwchars{ mt_rand( 0, $l ) };
793 * Set cached properties to default.
795 * @note This no longer clears uncached lazy-initialised properties;
796 * the constructor does that instead.
799 function loadDefaults( $name = false ) {
800 wfProfileIn( __METHOD__
);
802 global $wgCookiePrefix;
805 $this->mName
= $name;
806 $this->mRealName
= '';
807 $this->mPassword
= $this->mNewpassword
= '';
808 $this->mNewpassTime
= null;
810 $this->mOptionOverrides
= null;
811 $this->mOptionsLoaded
= false;
813 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
814 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
816 $this->mTouched
= '0'; # Allow any pages to be cached
819 $this->setToken(); # Random
820 $this->mEmailAuthenticated
= null;
821 $this->mEmailToken
= '';
822 $this->mEmailTokenExpires
= null;
823 $this->mRegistration
= wfTimestamp( TS_MW
);
824 $this->mGroups
= array();
826 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
828 wfProfileOut( __METHOD__
);
832 * @deprecated Use wfSetupSession().
834 function SetupSession() {
835 wfDeprecated( __METHOD__
);
840 * Load user data from the session or login cookie. If there are no valid
841 * credentials, initialises the user as an anonymous user.
842 * @return \bool True if the user is logged in, false otherwise.
844 private function loadFromSession() {
845 global $wgMemc, $wgCookiePrefix;
848 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
849 if ( $result !== null ) {
853 if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
854 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
855 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
856 $this->loadDefaults(); // Possible collision!
857 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
858 cookie user ID ($sId) don't match!" );
861 $_SESSION['wsUserID'] = $sId;
862 } else if ( isset( $_SESSION['wsUserID'] ) ) {
863 if ( $_SESSION['wsUserID'] != 0 ) {
864 $sId = $_SESSION['wsUserID'];
866 $this->loadDefaults();
870 $this->loadDefaults();
874 if ( isset( $_SESSION['wsUserName'] ) ) {
875 $sName = $_SESSION['wsUserName'];
876 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
877 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
878 $_SESSION['wsUserName'] = $sName;
880 $this->loadDefaults();
884 $passwordCorrect = FALSE;
886 if ( !$this->loadFromId() ) {
887 # Not a valid ID, loadFromId has switched the object to anon for us
891 if ( isset( $_SESSION['wsToken'] ) ) {
892 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
894 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
895 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
898 # No session or persistent login cookie
899 $this->loadDefaults();
903 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
904 $_SESSION['wsToken'] = $this->mToken
;
905 wfDebug( "Logged in from $from\n" );
908 # Invalid credentials
909 wfDebug( "Can't log in from $from, invalid credentials\n" );
910 $this->loadDefaults();
916 * Load user and user_group data from the database.
917 * $this::mId must be set, this is how the user is identified.
919 * @return \bool True if the user exists, false if the user is anonymous
922 function loadFromDatabase() {
924 $this->mId
= intval( $this->mId
);
926 /** Anonymous user */
928 $this->loadDefaults();
932 $dbr = wfGetDB( DB_MASTER
);
933 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
935 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
937 if ( $s !== false ) {
938 # Initialise user table data
939 $this->loadFromRow( $s );
940 $this->mGroups
= null; // deferred
941 $this->getEditCount(); // revalidation for nulls
946 $this->loadDefaults();
952 * Initialize this object from a row from the user table.
954 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
956 function loadFromRow( $row ) {
957 $this->mDataLoaded
= true;
959 if ( isset( $row->user_id
) ) {
960 $this->mId
= intval( $row->user_id
);
962 $this->mName
= $row->user_name
;
963 $this->mRealName
= $row->user_real_name
;
964 $this->mPassword
= $row->user_password
;
965 $this->mNewpassword
= $row->user_newpassword
;
966 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
967 $this->mEmail
= $row->user_email
;
968 $this->decodeOptions( $row->user_options
);
969 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
970 $this->mToken
= $row->user_token
;
971 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
972 $this->mEmailToken
= $row->user_email_token
;
973 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
974 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
975 $this->mEditCount
= $row->user_editcount
;
979 * Load the groups from the database if they aren't already loaded.
982 function loadGroups() {
983 if ( is_null( $this->mGroups
) ) {
984 $dbr = wfGetDB( DB_MASTER
);
985 $res = $dbr->select( 'user_groups',
987 array( 'ug_user' => $this->mId
),
989 $this->mGroups
= array();
990 while( $row = $dbr->fetchObject( $res ) ) {
991 $this->mGroups
[] = $row->ug_group
;
997 * Clear various cached data stored in this object.
998 * @param $reloadFrom \string Reload user and user_groups table data from a
999 * given source. May be "name", "id", "defaults", "session", or false for
1002 function clearInstanceCache( $reloadFrom = false ) {
1003 $this->mNewtalk
= -1;
1004 $this->mDatePreference
= null;
1005 $this->mBlockedby
= -1; # Unset
1006 $this->mHash
= false;
1007 $this->mSkin
= null;
1008 $this->mRights
= null;
1009 $this->mEffectiveGroups
= null;
1010 $this->mOptions
= null;
1012 if ( $reloadFrom ) {
1013 $this->mDataLoaded
= false;
1014 $this->mFrom
= $reloadFrom;
1019 * Combine the language default options with any site-specific options
1020 * and add the default language variants.
1022 * @return \type{\arrayof{\string}} Array of options
1024 static function getDefaultOptions() {
1025 global $wgNamespacesToBeSearchedDefault;
1027 * Site defaults will override the global/language defaults
1029 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1030 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
1033 * default language setting
1035 $variant = $wgContLang->getPreferredVariant( false );
1036 $defOpt['variant'] = $variant;
1037 $defOpt['language'] = $variant;
1038 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1039 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1041 $defOpt['skin'] = $wgDefaultSkin;
1047 * Get a given default option value.
1049 * @param $opt \string Name of option to retrieve
1050 * @return \string Default option value
1052 public static function getDefaultOption( $opt ) {
1053 $defOpts = self
::getDefaultOptions();
1054 if( isset( $defOpts[$opt] ) ) {
1055 return $defOpts[$opt];
1062 * Get a list of user toggle names
1063 * @return \type{\arrayof{\string}} Array of user toggle names
1065 static function getToggles() {
1066 global $wgContLang, $wgUseRCPatrol;
1067 $extraToggles = array();
1068 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1069 if( $wgUseRCPatrol ) {
1070 $extraToggles[] = 'hidepatrolled';
1071 $extraToggles[] = 'newpageshidepatrolled';
1072 $extraToggles[] = 'watchlisthidepatrolled';
1074 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1079 * Get blocking information
1081 * @param $bFromSlave \bool Whether to check the slave database first. To
1082 * improve performance, non-critical checks are done
1083 * against slaves. Check when actually saving should be
1084 * done against master.
1086 function getBlockedStatus( $bFromSlave = true ) {
1087 global $wgEnableSorbs, $wgProxyWhitelist, $wgUser;
1089 if ( -1 != $this->mBlockedby
) {
1090 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1094 wfProfileIn( __METHOD__
);
1095 wfDebug( __METHOD__
.": checking...\n" );
1097 // Initialize data...
1098 // Otherwise something ends up stomping on $this->mBlockedby when
1099 // things get lazy-loaded later, causing false positive block hits
1100 // due to -1 !== 0. Probably session-related... Nothing should be
1101 // overwriting mBlockedby, surely?
1104 $this->mBlockedby
= 0;
1105 $this->mHideName
= 0;
1106 $this->mAllowUsertalk
= 0;
1108 # Check if we are looking at an IP or a logged-in user
1109 if ( $this->isIP( $this->getName() ) ) {
1110 $ip = $this->getName();
1112 # Check if we are looking at the current user
1113 # If we don't, and the user is logged in, we don't know about
1114 # his IP / autoblock status, so ignore autoblock of current user's IP
1115 if ( $this->getID() != $wgUser->getID() ) {
1118 # Get IP of current user
1123 if ( $this->isAllowed( 'ipblock-exempt' ) ) {
1124 # Exempt from all types of IP-block
1129 $this->mBlock
= new Block();
1130 $this->mBlock
->fromMaster( !$bFromSlave );
1131 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1132 wfDebug( __METHOD__
. ": Found block.\n" );
1133 $this->mBlockedby
= $this->mBlock
->mBy
;
1134 $this->mBlockreason
= $this->mBlock
->mReason
;
1135 $this->mHideName
= $this->mBlock
->mHideName
;
1136 $this->mAllowUsertalk
= $this->mBlock
->mAllowUsertalk
;
1137 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1138 $this->spreadBlock();
1141 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1142 // apply to users. Note that the existence of $this->mBlock is not used to
1143 // check for edit blocks, $this->mBlockedby is instead.
1147 if ( !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1149 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1150 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1151 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1155 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1156 if ( $this->inSorbsBlacklist( $ip ) ) {
1157 $this->mBlockedby
= wfMsg( 'sorbs' );
1158 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1164 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1166 wfProfileOut( __METHOD__
);
1170 * Whether the given IP is in the SORBS blacklist.
1172 * @param $ip \string IP to check
1173 * @return \bool True if blacklisted.
1175 function inSorbsBlacklist( $ip ) {
1176 global $wgEnableSorbs, $wgSorbsUrl;
1178 return $wgEnableSorbs &&
1179 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1183 * Whether the given IP is in a given DNS blacklist.
1185 * @param $ip \string IP to check
1186 * @param $base \string URL of the DNS blacklist
1187 * @return \bool True if blacklisted.
1189 function inDnsBlacklist( $ip, $base ) {
1190 wfProfileIn( __METHOD__
);
1194 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1195 if( IP
::isIPv4( $ip ) ) {
1197 $host = "$ip.$base";
1200 $ipList = gethostbynamel( $host );
1203 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1206 wfDebug( "Requested $host, not found in $base.\n" );
1210 wfProfileOut( __METHOD__
);
1215 * Is this user subject to rate limiting?
1217 * @return \bool True if rate limited
1219 public function isPingLimitable() {
1220 global $wgRateLimitsExcludedGroups;
1221 global $wgRateLimitsExcludedIPs;
1222 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1223 // Deprecated, but kept for backwards-compatibility config
1226 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1227 // No other good way currently to disable rate limits
1228 // for specific IPs. :P
1229 // But this is a crappy hack and should die.
1232 return !$this->isAllowed('noratelimit');
1236 * Primitive rate limits: enforce maximum actions per time period
1237 * to put a brake on flooding.
1239 * @note When using a shared cache like memcached, IP-address
1240 * last-hit counters will be shared across wikis.
1242 * @param $action \string Action to enforce; 'edit' if unspecified
1243 * @return \bool True if a rate limiter was tripped
1245 function pingLimiter( $action = 'edit' ) {
1246 # Call the 'PingLimiter' hook
1248 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1252 global $wgRateLimits;
1253 if( !isset( $wgRateLimits[$action] ) ) {
1257 # Some groups shouldn't trigger the ping limiter, ever
1258 if( !$this->isPingLimitable() )
1261 global $wgMemc, $wgRateLimitLog;
1262 wfProfileIn( __METHOD__
);
1264 $limits = $wgRateLimits[$action];
1266 $id = $this->getId();
1270 if( isset( $limits['anon'] ) && $id == 0 ) {
1271 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1274 if( isset( $limits['user'] ) && $id != 0 ) {
1275 $userLimit = $limits['user'];
1277 if( $this->isNewbie() ) {
1278 if( isset( $limits['newbie'] ) && $id != 0 ) {
1279 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1281 if( isset( $limits['ip'] ) ) {
1282 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1285 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1286 $subnet = $matches[1];
1287 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1290 // Check for group-specific permissions
1291 // If more than one group applies, use the group with the highest limit
1292 foreach ( $this->getGroups() as $group ) {
1293 if ( isset( $limits[$group] ) ) {
1294 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1295 $userLimit = $limits[$group];
1299 // Set the user limit key
1300 if ( $userLimit !== false ) {
1301 wfDebug( __METHOD__
. ": effective user limit: $userLimit\n" );
1302 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1306 foreach( $keys as $key => $limit ) {
1307 list( $max, $period ) = $limit;
1308 $summary = "(limit $max in {$period}s)";
1309 $count = $wgMemc->get( $key );
1312 if( $count > $max ) {
1313 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1314 if( $wgRateLimitLog ) {
1315 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1319 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1321 $wgMemc->incr( $key );
1323 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1324 $wgMemc->set( $key, 1, intval( $period ) ); // first ping
1328 wfProfileOut( __METHOD__
);
1333 * Check if user is blocked
1335 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1336 * @return \bool True if blocked, false otherwise
1338 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1339 wfDebug( "User::isBlocked: enter\n" );
1340 $this->getBlockedStatus( $bFromSlave );
1341 return $this->mBlockedby
!== 0;
1345 * Check if user is blocked from editing a particular article
1347 * @param $title \string Title to check
1348 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1349 * @return \bool True if blocked, false otherwise
1351 function isBlockedFrom( $title, $bFromSlave = false ) {
1352 global $wgBlockAllowsUTEdit;
1353 wfProfileIn( __METHOD__
);
1354 wfDebug( __METHOD__
. ": enter\n" );
1356 wfDebug( __METHOD__
. ": asking isBlocked()\n" );
1357 $blocked = $this->isBlocked( $bFromSlave );
1358 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1359 # If a user's name is suppressed, they cannot make edits anywhere
1360 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1361 $title->getNamespace() == NS_USER_TALK
) {
1363 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1366 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1368 wfProfileOut( __METHOD__
);
1373 * If user is blocked, return the name of the user who placed the block
1374 * @return \string name of blocker
1376 function blockedBy() {
1377 $this->getBlockedStatus();
1378 return $this->mBlockedby
;
1382 * If user is blocked, return the specified reason for the block
1383 * @return \string Blocking reason
1385 function blockedFor() {
1386 $this->getBlockedStatus();
1387 return $this->mBlockreason
;
1391 * If user is blocked, return the ID for the block
1392 * @return \int Block ID
1394 function getBlockId() {
1395 $this->getBlockedStatus();
1396 return ( $this->mBlock ?
$this->mBlock
->mId
: false );
1400 * Check if user is blocked on all wikis.
1401 * Do not use for actual edit permission checks!
1402 * This is intented for quick UI checks.
1404 * @param $ip \type{\string} IP address, uses current client if none given
1405 * @return \type{\bool} True if blocked, false otherwise
1407 function isBlockedGlobally( $ip = '' ) {
1408 if( $this->mBlockedGlobally
!== null ) {
1409 return $this->mBlockedGlobally
;
1411 // User is already an IP?
1412 if( IP
::isIPAddress( $this->getName() ) ) {
1413 $ip = $this->getName();
1418 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1419 $this->mBlockedGlobally
= (bool)$blocked;
1420 return $this->mBlockedGlobally
;
1424 * Check if user account is locked
1426 * @return \type{\bool} True if locked, false otherwise
1428 function isLocked() {
1429 if( $this->mLocked
!== null ) {
1430 return $this->mLocked
;
1433 $authUser = $wgAuth->getUserInstance( $this );
1434 $this->mLocked
= (bool)$authUser->isLocked();
1435 return $this->mLocked
;
1439 * Check if user account is hidden
1441 * @return \type{\bool} True if hidden, false otherwise
1443 function isHidden() {
1444 if( $this->mHideName
!== null ) {
1445 return $this->mHideName
;
1447 $this->getBlockedStatus();
1448 if( !$this->mHideName
) {
1450 $authUser = $wgAuth->getUserInstance( $this );
1451 $this->mHideName
= (bool)$authUser->isHidden();
1453 return $this->mHideName
;
1457 * Get the user's ID.
1458 * @return \int The user's ID; 0 if the user is anonymous or nonexistent
1461 if( $this->mId
=== null and $this->mName
!== null
1462 and User
::isIP( $this->mName
) ) {
1463 // Special case, we know the user is anonymous
1465 } elseif( $this->mId
=== null ) {
1466 // Don't load if this was initialized from an ID
1473 * Set the user and reload all fields according to a given ID
1474 * @param $v \int User ID to reload
1476 function setId( $v ) {
1478 $this->clearInstanceCache( 'id' );
1482 * Get the user name, or the IP of an anonymous user
1483 * @return \string User's name or IP address
1485 function getName() {
1486 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1487 # Special case optimisation
1488 return $this->mName
;
1491 if ( $this->mName
=== false ) {
1493 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1495 return $this->mName
;
1500 * Set the user name.
1502 * This does not reload fields from the database according to the given
1503 * name. Rather, it is used to create a temporary "nonexistent user" for
1504 * later addition to the database. It can also be used to set the IP
1505 * address for an anonymous user to something other than the current
1508 * @note User::newFromName() has rougly the same function, when the named user
1510 * @param $str \string New user name to set
1512 function setName( $str ) {
1514 $this->mName
= $str;
1518 * Get the user's name escaped by underscores.
1519 * @return \string Username escaped by underscores.
1521 function getTitleKey() {
1522 return str_replace( ' ', '_', $this->getName() );
1526 * Check if the user has new messages.
1527 * @return \bool True if the user has new messages
1529 function getNewtalk() {
1532 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1533 if( $this->mNewtalk
=== -1 ) {
1534 $this->mNewtalk
= false; # reset talk page status
1536 # Check memcached separately for anons, who have no
1537 # entire User object stored in there.
1540 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1541 $newtalk = $wgMemc->get( $key );
1542 if( strval( $newtalk ) !== '' ) {
1543 $this->mNewtalk
= (bool)$newtalk;
1545 // Since we are caching this, make sure it is up to date by getting it
1547 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1548 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1551 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1555 return (bool)$this->mNewtalk
;
1559 * Return the talk page(s) this user has new messages on.
1560 * @return \type{\arrayof{\string}} Array of page URLs
1562 function getNewMessageLinks() {
1564 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1567 if( !$this->getNewtalk() )
1569 $up = $this->getUserPage();
1570 $utp = $up->getTalkPage();
1571 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1575 * Internal uncached check for new messages
1578 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1579 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1580 * @param $fromMaster \bool true to fetch from the master, false for a slave
1581 * @return \bool True if the user has new messages
1584 function checkNewtalk( $field, $id, $fromMaster = false ) {
1585 if ( $fromMaster ) {
1586 $db = wfGetDB( DB_MASTER
);
1588 $db = wfGetDB( DB_SLAVE
);
1590 $ok = $db->selectField( 'user_newtalk', $field,
1591 array( $field => $id ), __METHOD__
);
1592 return $ok !== false;
1596 * Add or update the new messages flag
1597 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1598 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1599 * @return \bool True if successful, false otherwise
1602 function updateNewtalk( $field, $id ) {
1603 $dbw = wfGetDB( DB_MASTER
);
1604 $dbw->insert( 'user_newtalk',
1605 array( $field => $id ),
1608 if ( $dbw->affectedRows() ) {
1609 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1612 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1618 * Clear the new messages flag for the given user
1619 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1620 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1621 * @return \bool True if successful, false otherwise
1624 function deleteNewtalk( $field, $id ) {
1625 $dbw = wfGetDB( DB_MASTER
);
1626 $dbw->delete( 'user_newtalk',
1627 array( $field => $id ),
1629 if ( $dbw->affectedRows() ) {
1630 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1633 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1639 * Update the 'You have new messages!' status.
1640 * @param $val \bool Whether the user has new messages
1642 function setNewtalk( $val ) {
1643 if( wfReadOnly() ) {
1648 $this->mNewtalk
= $val;
1650 if( $this->isAnon() ) {
1652 $id = $this->getName();
1655 $id = $this->getId();
1660 $changed = $this->updateNewtalk( $field, $id );
1662 $changed = $this->deleteNewtalk( $field, $id );
1665 if( $this->isAnon() ) {
1666 // Anons have a separate memcached space, since
1667 // user records aren't kept for them.
1668 $key = wfMemcKey( 'newtalk', 'ip', $id );
1669 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1672 $this->invalidateCache();
1677 * Generate a current or new-future timestamp to be stored in the
1678 * user_touched field when we update things.
1679 * @return \string Timestamp in TS_MW format
1681 private static function newTouchedTimestamp() {
1682 global $wgClockSkewFudge;
1683 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1687 * Clear user data from memcached.
1688 * Use after applying fun updates to the database; caller's
1689 * responsibility to update user_touched if appropriate.
1691 * Called implicitly from invalidateCache() and saveSettings().
1693 private function clearSharedCache() {
1697 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1702 * Immediately touch the user data cache for this account.
1703 * Updates user_touched field, and removes account data from memcached
1704 * for reload on the next hit.
1706 function invalidateCache() {
1707 if( wfReadOnly() ) {
1712 $this->mTouched
= self
::newTouchedTimestamp();
1714 $dbw = wfGetDB( DB_MASTER
);
1715 $dbw->update( 'user',
1716 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1717 array( 'user_id' => $this->mId
),
1720 $this->clearSharedCache();
1725 * Validate the cache for this account.
1726 * @param $timestamp \string A timestamp in TS_MW format
1728 function validateCache( $timestamp ) {
1730 return ( $timestamp >= $this->mTouched
);
1734 * Get the user touched timestamp
1736 function getTouched() {
1738 return $this->mTouched
;
1742 * Set the password and reset the random token.
1743 * Calls through to authentication plugin if necessary;
1744 * will have no effect if the auth plugin refuses to
1745 * pass the change through or if the legal password
1748 * As a special case, setting the password to null
1749 * wipes it, so the account cannot be logged in until
1750 * a new password is set, for instance via e-mail.
1752 * @param $str \string New password to set
1753 * @throws PasswordError on failure
1755 function setPassword( $str ) {
1758 if( $str !== null ) {
1759 if( !$wgAuth->allowPasswordChange() ) {
1760 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1763 if( !$this->isValidPassword( $str ) ) {
1764 global $wgMinimalPasswordLength;
1765 $valid = $this->getPasswordValidity( $str );
1766 throw new PasswordError( wfMsgExt( $valid, array( 'parsemag' ),
1767 $wgMinimalPasswordLength ) );
1771 if( !$wgAuth->setPassword( $this, $str ) ) {
1772 throw new PasswordError( wfMsg( 'externaldberror' ) );
1775 $this->setInternalPassword( $str );
1781 * Set the password and reset the random token unconditionally.
1783 * @param $str \string New password to set
1785 function setInternalPassword( $str ) {
1789 if( $str === null ) {
1790 // Save an invalid hash...
1791 $this->mPassword
= '';
1793 $this->mPassword
= self
::crypt( $str );
1795 $this->mNewpassword
= '';
1796 $this->mNewpassTime
= null;
1800 * Get the user's current token.
1801 * @return \string Token
1803 function getToken() {
1805 return $this->mToken
;
1809 * Set the random token (used for persistent authentication)
1810 * Called from loadDefaults() among other places.
1812 * @param $token \string If specified, set the token to this value
1815 function setToken( $token = false ) {
1816 global $wgSecretKey, $wgProxyKey;
1819 if ( $wgSecretKey ) {
1820 $key = $wgSecretKey;
1821 } elseif ( $wgProxyKey ) {
1826 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1828 $this->mToken
= $token;
1833 * Set the cookie password
1835 * @param $str \string New cookie password
1838 function setCookiePassword( $str ) {
1840 $this->mCookiePassword
= md5( $str );
1844 * Set the password for a password reminder or new account email
1846 * @param $str \string New password to set
1847 * @param $throttle \bool If true, reset the throttle timestamp to the present
1849 function setNewpassword( $str, $throttle = true ) {
1851 $this->mNewpassword
= self
::crypt( $str );
1853 $this->mNewpassTime
= wfTimestampNow();
1858 * Has password reminder email been sent within the last
1859 * $wgPasswordReminderResendTime hours?
1860 * @return \bool True or false
1862 function isPasswordReminderThrottled() {
1863 global $wgPasswordReminderResendTime;
1865 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1868 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1869 return time() < $expiry;
1873 * Get the user's e-mail address
1874 * @return \string User's email address
1876 function getEmail() {
1878 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1879 return $this->mEmail
;
1883 * Get the timestamp of the user's e-mail authentication
1884 * @return \string TS_MW timestamp
1886 function getEmailAuthenticationTimestamp() {
1888 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1889 return $this->mEmailAuthenticated
;
1893 * Set the user's e-mail address
1894 * @param $str \string New e-mail address
1896 function setEmail( $str ) {
1898 $this->mEmail
= $str;
1899 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1903 * Get the user's real name
1904 * @return \string User's real name
1906 function getRealName() {
1908 return $this->mRealName
;
1912 * Set the user's real name
1913 * @param $str \string New real name
1915 function setRealName( $str ) {
1917 $this->mRealName
= $str;
1921 * Get the user's current setting for a given option.
1923 * @param $oname \string The option to check
1924 * @param $defaultOverride \string A default value returned if the option does not exist
1925 * @return \string User's current value for the option
1926 * @see getBoolOption()
1927 * @see getIntOption()
1929 function getOption( $oname, $defaultOverride = null ) {
1930 $this->loadOptions();
1932 if ( is_null( $this->mOptions
) ) {
1933 if($defaultOverride != '') {
1934 return $defaultOverride;
1936 $this->mOptions
= User
::getDefaultOptions();
1939 if ( array_key_exists( $oname, $this->mOptions
) ) {
1940 return $this->mOptions
[$oname];
1942 return $defaultOverride;
1947 * Get the user's current setting for a given option, as a boolean value.
1949 * @param $oname \string The option to check
1950 * @return \bool User's current value for the option
1953 function getBoolOption( $oname ) {
1954 return (bool)$this->getOption( $oname );
1959 * Get the user's current setting for a given option, as a boolean value.
1961 * @param $oname \string The option to check
1962 * @param $defaultOverride \int A default value returned if the option does not exist
1963 * @return \int User's current value for the option
1966 function getIntOption( $oname, $defaultOverride=0 ) {
1967 $val = $this->getOption( $oname );
1969 $val = $defaultOverride;
1971 return intval( $val );
1975 * Set the given option for a user.
1977 * @param $oname \string The option to set
1978 * @param $val \mixed New value to set
1980 function setOption( $oname, $val ) {
1982 $this->loadOptions();
1984 if ( $oname == 'skin' ) {
1985 # Clear cached skin, so the new one displays immediately in Special:Preferences
1986 unset( $this->mSkin
);
1989 // Explicitly NULL values should refer to defaults
1990 global $wgDefaultUserOptions;
1991 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
1992 $val = $wgDefaultUserOptions[$oname];
1995 $this->mOptions
[$oname] = $val;
1999 * Reset all options to the site defaults
2001 function resetOptions() {
2002 $this->mOptions
= User
::getDefaultOptions();
2006 * Get the user's preferred date format.
2007 * @return \string User's preferred date format
2009 function getDatePreference() {
2010 // Important migration for old data rows
2011 if ( is_null( $this->mDatePreference
) ) {
2013 $value = $this->getOption( 'date' );
2014 $map = $wgLang->getDatePreferenceMigrationMap();
2015 if ( isset( $map[$value] ) ) {
2016 $value = $map[$value];
2018 $this->mDatePreference
= $value;
2020 return $this->mDatePreference
;
2024 * Get the permissions this user has.
2025 * @return \type{\arrayof{\string}} Array of permission names
2027 function getRights() {
2028 if ( is_null( $this->mRights
) ) {
2029 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2030 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2031 // Force reindexation of rights when a hook has unset one of them
2032 $this->mRights
= array_values( $this->mRights
);
2034 return $this->mRights
;
2038 * Get the list of explicit group memberships this user has.
2039 * The implicit * and user groups are not included.
2040 * @return \type{\arrayof{\string}} Array of internal group names
2042 function getGroups() {
2044 return $this->mGroups
;
2048 * Get the list of implicit group memberships this user has.
2049 * This includes all explicit groups, plus 'user' if logged in,
2050 * '*' for all accounts and autopromoted groups
2051 * @param $recache \bool Whether to avoid the cache
2052 * @return \type{\arrayof{\string}} Array of internal group names
2054 function getEffectiveGroups( $recache = false ) {
2055 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2056 wfProfileIn( __METHOD__
);
2057 $this->mEffectiveGroups
= $this->getGroups();
2058 $this->mEffectiveGroups
[] = '*';
2059 if( $this->getId() ) {
2060 $this->mEffectiveGroups
[] = 'user';
2062 $this->mEffectiveGroups
= array_unique( array_merge(
2063 $this->mEffectiveGroups
,
2064 Autopromote
::getAutopromoteGroups( $this )
2067 # Hook for additional groups
2068 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2070 wfProfileOut( __METHOD__
);
2072 return $this->mEffectiveGroups
;
2076 * Get the user's edit count.
2077 * @return \int User'e edit count
2079 function getEditCount() {
2080 if( $this->getId() ) {
2081 if ( !isset( $this->mEditCount
) ) {
2082 /* Populate the count, if it has not been populated yet */
2083 $this->mEditCount
= User
::edits( $this->mId
);
2085 return $this->mEditCount
;
2093 * Add the user to the given group.
2094 * This takes immediate effect.
2095 * @param $group \string Name of the group to add
2097 function addGroup( $group ) {
2098 $dbw = wfGetDB( DB_MASTER
);
2099 if( $this->getId() ) {
2100 $dbw->insert( 'user_groups',
2102 'ug_user' => $this->getID(),
2103 'ug_group' => $group,
2106 array( 'IGNORE' ) );
2109 $this->loadGroups();
2110 $this->mGroups
[] = $group;
2111 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2113 $this->invalidateCache();
2117 * Remove the user from the given group.
2118 * This takes immediate effect.
2119 * @param $group \string Name of the group to remove
2121 function removeGroup( $group ) {
2123 $dbw = wfGetDB( DB_MASTER
);
2124 $dbw->delete( 'user_groups',
2126 'ug_user' => $this->getID(),
2127 'ug_group' => $group,
2129 'User::removeGroup' );
2131 $this->loadGroups();
2132 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2133 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2135 $this->invalidateCache();
2139 * Get whether the user is logged in
2140 * @return \bool True or false
2142 function isLoggedIn() {
2143 return $this->getID() != 0;
2147 * Get whether the user is anonymous
2148 * @return \bool True or false
2151 return !$this->isLoggedIn();
2155 * Get whether the user is a bot
2156 * @return \bool True or false
2160 wfDeprecated( __METHOD__
);
2161 return $this->isAllowed( 'bot' );
2165 * Check if user is allowed to access a feature / make an action
2166 * @param $action \string action to be checked
2167 * @return \bool True if action is allowed, else false
2169 function isAllowed( $action = '' ) {
2170 if ( $action === '' )
2171 return true; // In the spirit of DWIM
2172 # Patrolling may not be enabled
2173 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2174 global $wgUseRCPatrol, $wgUseNPPatrol;
2175 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2178 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2179 # by misconfiguration: 0 == 'foo'
2180 return in_array( $action, $this->getRights(), true );
2184 * Check whether to enable recent changes patrol features for this user
2185 * @return \bool True or false
2187 public function useRCPatrol() {
2188 global $wgUseRCPatrol;
2189 return( $wgUseRCPatrol && ( $this->isAllowed( 'patrol' ) ||
$this->isAllowed( 'patrolmarks' ) ) );
2193 * Check whether to enable new pages patrol features for this user
2194 * @return \bool True or false
2196 public function useNPPatrol() {
2197 global $wgUseRCPatrol, $wgUseNPPatrol;
2198 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowed( 'patrol' ) ||
$this->isAllowed( 'patrolmarks' ) ) );
2202 * Get the current skin, loading it if required, and setting a title
2203 * @param $t Title: the title to use in the skin
2204 * @return Skin The current skin
2205 * @todo FIXME : need to check the old failback system [AV]
2207 function &getSkin( $t = null ) {
2208 if ( !isset( $this->mSkin
) ) {
2209 wfProfileIn( __METHOD__
);
2211 global $wgHiddenPrefs;
2212 if( !in_array( 'skin', $wgHiddenPrefs ) ) {
2215 $userSkin = $this->getOption( 'skin' );
2216 $userSkin = $wgRequest->getVal( 'useskin', $userSkin );
2218 # if we're not allowing users to override, then use the default
2219 global $wgDefaultSkin;
2220 $userSkin = $wgDefaultSkin;
2223 $this->mSkin
=& Skin
::newFromKey( $userSkin );
2224 wfProfileOut( __METHOD__
);
2226 if( $t ||
!$this->mSkin
->getTitle() ) {
2229 $t = $wgOut->getTitle();
2231 $this->mSkin
->setTitle( $t );
2233 return $this->mSkin
;
2237 * Check the watched status of an article.
2238 * @param $title \type{Title} Title of the article to look at
2239 * @return \bool True if article is watched
2241 function isWatched( $title ) {
2242 $wl = WatchedItem
::fromUserTitle( $this, $title );
2243 return $wl->isWatched();
2248 * @param $title \type{Title} Title of the article to look at
2250 function addWatch( $title ) {
2251 $wl = WatchedItem
::fromUserTitle( $this, $title );
2253 $this->invalidateCache();
2257 * Stop watching an article.
2258 * @param $title \type{Title} Title of the article to look at
2260 function removeWatch( $title ) {
2261 $wl = WatchedItem
::fromUserTitle( $this, $title );
2263 $this->invalidateCache();
2267 * Clear the user's notification timestamp for the given title.
2268 * If e-notif e-mails are on, they will receive notification mails on
2269 * the next change of the page if it's watched etc.
2270 * @param $title \type{Title} Title of the article to look at
2272 function clearNotification( &$title ) {
2273 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2275 # Do nothing if the database is locked to writes
2276 if( wfReadOnly() ) {
2280 if( $title->getNamespace() == NS_USER_TALK
&&
2281 $title->getText() == $this->getName() ) {
2282 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2284 $this->setNewtalk( false );
2287 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2291 if( $this->isAnon() ) {
2292 // Nothing else to do...
2296 // Only update the timestamp if the page is being watched.
2297 // The query to find out if it is watched is cached both in memcached and per-invocation,
2298 // and when it does have to be executed, it can be on a slave
2299 // If this is the user's newtalk page, we always update the timestamp
2300 if( $title->getNamespace() == NS_USER_TALK
&&
2301 $title->getText() == $wgUser->getName() )
2304 } elseif ( $this->getId() == $wgUser->getId() ) {
2305 $watched = $title->userIsWatching();
2310 // If the page is watched by the user (or may be watched), update the timestamp on any
2311 // any matching rows
2313 $dbw = wfGetDB( DB_MASTER
);
2314 $dbw->update( 'watchlist',
2316 'wl_notificationtimestamp' => NULL
2317 ), array( /* WHERE */
2318 'wl_title' => $title->getDBkey(),
2319 'wl_namespace' => $title->getNamespace(),
2320 'wl_user' => $this->getID()
2327 * Resets all of the given user's page-change notification timestamps.
2328 * If e-notif e-mails are on, they will receive notification mails on
2329 * the next change of any watched page.
2331 * @param $currentUser \int User ID
2333 function clearAllNotifications( $currentUser ) {
2334 global $wgUseEnotif, $wgShowUpdatedMarker;
2335 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2336 $this->setNewtalk( false );
2339 if( $currentUser != 0 ) {
2340 $dbw = wfGetDB( DB_MASTER
);
2341 $dbw->update( 'watchlist',
2343 'wl_notificationtimestamp' => NULL
2344 ), array( /* WHERE */
2345 'wl_user' => $currentUser
2348 # We also need to clear here the "you have new message" notification for the own user_talk page
2349 # This is cleared one page view later in Article::viewUpdates();
2354 * Set this user's options from an encoded string
2355 * @param $str \string Encoded options to import
2358 function decodeOptions( $str ) {
2362 $this->mOptionsLoaded
= true;
2363 $this->mOptionOverrides
= array();
2365 $this->mOptions
= array();
2366 $a = explode( "\n", $str );
2367 foreach ( $a as $s ) {
2369 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2370 $this->mOptions
[$m[1]] = $m[2];
2371 $this->mOptionOverrides
[$m[1]] = $m[2];
2377 * Set a cookie on the user's client. Wrapper for
2378 * WebResponse::setCookie
2379 * @param $name \string Name of the cookie to set
2380 * @param $value \string Value to set
2381 * @param $exp \int Expiration time, as a UNIX time value;
2382 * if 0 or not specified, use the default $wgCookieExpiration
2384 protected function setCookie( $name, $value, $exp = 0 ) {
2386 $wgRequest->response()->setcookie( $name, $value, $exp );
2390 * Clear a cookie on the user's client
2391 * @param $name \string Name of the cookie to clear
2393 protected function clearCookie( $name ) {
2394 $this->setCookie( $name, '', time() - 86400 );
2398 * Set the default cookies for this session on the user's client.
2400 function setCookies() {
2402 if ( 0 == $this->mId
) return;
2404 'wsUserID' => $this->mId
,
2405 'wsToken' => $this->mToken
,
2406 'wsUserName' => $this->getName()
2409 'UserID' => $this->mId
,
2410 'UserName' => $this->getName(),
2412 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2413 $cookies['Token'] = $this->mToken
;
2415 $cookies['Token'] = false;
2418 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2419 #check for null, since the hook could cause a null value
2420 if ( !is_null( $session ) && isset( $_SESSION ) ){
2421 $_SESSION = $session +
$_SESSION;
2423 foreach ( $cookies as $name => $value ) {
2424 if ( $value === false ) {
2425 $this->clearCookie( $name );
2427 $this->setCookie( $name, $value );
2433 * Log this user out.
2436 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2442 * Clear the user's cookies and session, and reset the instance cache.
2446 function doLogout() {
2447 $this->clearInstanceCache( 'defaults' );
2449 $_SESSION['wsUserID'] = 0;
2451 $this->clearCookie( 'UserID' );
2452 $this->clearCookie( 'Token' );
2454 # Remember when user logged out, to prevent seeing cached pages
2455 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2459 * Save this user's settings into the database.
2460 * @todo Only rarely do all these fields need to be set!
2462 function saveSettings() {
2464 if ( wfReadOnly() ) { return; }
2465 if ( 0 == $this->mId
) { return; }
2467 $this->mTouched
= self
::newTouchedTimestamp();
2469 $dbw = wfGetDB( DB_MASTER
);
2470 $dbw->update( 'user',
2472 'user_name' => $this->mName
,
2473 'user_password' => $this->mPassword
,
2474 'user_newpassword' => $this->mNewpassword
,
2475 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2476 'user_real_name' => $this->mRealName
,
2477 'user_email' => $this->mEmail
,
2478 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2479 'user_options' => '',
2480 'user_touched' => $dbw->timestamp( $this->mTouched
),
2481 'user_token' => $this->mToken
,
2482 'user_email_token' => $this->mEmailToken
,
2483 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2484 ), array( /* WHERE */
2485 'user_id' => $this->mId
2489 $this->saveOptions();
2491 wfRunHooks( 'UserSaveSettings', array( $this ) );
2492 $this->clearSharedCache();
2493 $this->getUserPage()->invalidateCache();
2497 * If only this user's username is known, and it exists, return the user ID.
2499 function idForName() {
2500 $s = trim( $this->getName() );
2501 if ( $s === '' ) return 0;
2503 $dbr = wfGetDB( DB_SLAVE
);
2504 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2505 if ( $id === false ) {
2512 * Add a user to the database, return the user object
2514 * @param $name \string Username to add
2515 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2516 * - password The user's password. Password logins will be disabled if this is omitted.
2517 * - newpassword A temporary password mailed to the user
2518 * - email The user's email address
2519 * - email_authenticated The email authentication timestamp
2520 * - real_name The user's real name
2521 * - options An associative array of non-default options
2522 * - token Random authentication token. Do not set.
2523 * - registration Registration timestamp. Do not set.
2525 * @return \type{User} A new User object, or null if the username already exists
2527 static function createNew( $name, $params = array() ) {
2530 if ( isset( $params['options'] ) ) {
2531 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
2532 unset( $params['options'] );
2534 $dbw = wfGetDB( DB_MASTER
);
2535 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2537 'user_id' => $seqVal,
2538 'user_name' => $name,
2539 'user_password' => $user->mPassword
,
2540 'user_newpassword' => $user->mNewpassword
,
2541 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2542 'user_email' => $user->mEmail
,
2543 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2544 'user_real_name' => $user->mRealName
,
2545 'user_options' => '',
2546 'user_token' => $user->mToken
,
2547 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2548 'user_editcount' => 0,
2550 foreach ( $params as $name => $value ) {
2551 $fields["user_$name"] = $value;
2553 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2554 if ( $dbw->affectedRows() ) {
2555 $newUser = User
::newFromId( $dbw->insertId() );
2563 * Add this existing user object to the database
2565 function addToDatabase() {
2567 $dbw = wfGetDB( DB_MASTER
);
2568 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2569 $dbw->insert( 'user',
2571 'user_id' => $seqVal,
2572 'user_name' => $this->mName
,
2573 'user_password' => $this->mPassword
,
2574 'user_newpassword' => $this->mNewpassword
,
2575 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2576 'user_email' => $this->mEmail
,
2577 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2578 'user_real_name' => $this->mRealName
,
2579 'user_options' => '',
2580 'user_token' => $this->mToken
,
2581 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2582 'user_editcount' => 0,
2585 $this->mId
= $dbw->insertId();
2587 // Clear instance cache other than user table data, which is already accurate
2588 $this->clearInstanceCache();
2590 $this->saveOptions();
2594 * If this (non-anonymous) user is blocked, block any IP address
2595 * they've successfully logged in from.
2597 function spreadBlock() {
2598 wfDebug( __METHOD__
. "()\n" );
2600 if ( $this->mId
== 0 ) {
2604 $userblock = Block
::newFromDB( '', $this->mId
);
2605 if ( !$userblock ) {
2609 $userblock->doAutoblock( wfGetIP() );
2613 * Generate a string which will be different for any combination of
2614 * user options which would produce different parser output.
2615 * This will be used as part of the hash key for the parser cache,
2616 * so users will the same options can share the same cached data
2619 * Extensions which require it should install 'PageRenderingHash' hook,
2620 * which will give them a chance to modify this key based on their own
2623 * @return \string Page rendering hash
2625 function getPageRenderingHash() {
2626 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2628 return $this->mHash
;
2631 // stubthreshold is only included below for completeness,
2632 // it will always be 0 when this function is called by parsercache.
2634 $confstr = $this->getOption( 'math' );
2635 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2636 if ( $wgUseDynamicDates ) {
2637 $confstr .= '!' . $this->getDatePreference();
2639 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
2640 $confstr .= '!' . $wgLang->getCode();
2641 $confstr .= '!' . $this->getOption( 'thumbsize' );
2642 // add in language specific options, if any
2643 $extra = $wgContLang->getExtraHashOptions();
2646 $confstr .= $wgRenderHashAppend;
2648 // Give a chance for extensions to modify the hash, if they have
2649 // extra options or other effects on the parser cache.
2650 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2652 // Make it a valid memcached key fragment
2653 $confstr = str_replace( ' ', '_', $confstr );
2654 $this->mHash
= $confstr;
2659 * Get whether the user is explicitly blocked from account creation.
2660 * @return \bool True if blocked
2662 function isBlockedFromCreateAccount() {
2663 $this->getBlockedStatus();
2664 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2668 * Get whether the user is blocked from using Special:Emailuser.
2669 * @return \bool True if blocked
2671 function isBlockedFromEmailuser() {
2672 $this->getBlockedStatus();
2673 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2677 * Get whether the user is allowed to create an account.
2678 * @return \bool True if allowed
2680 function isAllowedToCreateAccount() {
2681 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2687 function setLoaded( $loaded ) {
2688 wfDeprecated( __METHOD__
);
2692 * Get this user's personal page title.
2694 * @return \type{Title} User's personal page title
2696 function getUserPage() {
2697 return Title
::makeTitle( NS_USER
, $this->getName() );
2701 * Get this user's talk page title.
2703 * @return \type{Title} User's talk page title
2705 function getTalkPage() {
2706 $title = $this->getUserPage();
2707 return $title->getTalkPage();
2711 * Get the maximum valid user ID.
2712 * @return \int User ID
2715 function getMaxID() {
2716 static $res; // cache
2718 if ( isset( $res ) )
2721 $dbr = wfGetDB( DB_SLAVE
);
2722 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2727 * Determine whether the user is a newbie. Newbies are either
2728 * anonymous IPs, or the most recently created accounts.
2729 * @return \bool True if the user is a newbie
2731 function isNewbie() {
2732 return !$this->isAllowed( 'autoconfirmed' );
2736 * Check to see if the given clear-text password is one of the accepted passwords
2737 * @param $password \string user password.
2738 * @return \bool True if the given password is correct, otherwise False.
2740 function checkPassword( $password ) {
2744 // Even though we stop people from creating passwords that
2745 // are shorter than this, doesn't mean people wont be able
2746 // to. Certain authentication plugins do NOT want to save
2747 // domain passwords in a mysql database, so we should
2748 // check this (incase $wgAuth->strict() is false).
2749 if( !$this->isValidPassword( $password ) ) {
2753 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2755 } elseif( $wgAuth->strict() ) {
2756 /* Auth plugin doesn't allow local authentication */
2758 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2759 /* Auth plugin doesn't allow local authentication for this user name */
2762 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2764 } elseif ( function_exists( 'iconv' ) ) {
2765 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2766 # Check for this with iconv
2767 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2768 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2776 * Check if the given clear-text password matches the temporary password
2777 * sent by e-mail for password reset operations.
2778 * @return \bool True if matches, false otherwise
2780 function checkTemporaryPassword( $plaintext ) {
2781 global $wgNewPasswordExpiry;
2782 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
2784 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
2785 return ( time() < $expiry );
2792 * Initialize (if necessary) and return a session token value
2793 * which can be used in edit forms to show that the user's
2794 * login credentials aren't being hijacked with a foreign form
2797 * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2798 * @return \string The new edit token
2800 function editToken( $salt = '' ) {
2801 if ( $this->isAnon() ) {
2802 return EDIT_TOKEN_SUFFIX
;
2804 if( !isset( $_SESSION['wsEditToken'] ) ) {
2805 $token = $this->generateToken();
2806 $_SESSION['wsEditToken'] = $token;
2808 $token = $_SESSION['wsEditToken'];
2810 if( is_array( $salt ) ) {
2811 $salt = implode( '|', $salt );
2813 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2818 * Generate a looking random token for various uses.
2820 * @param $salt \string Optional salt value
2821 * @return \string The new random token
2823 function generateToken( $salt = '' ) {
2824 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2825 return md5( $token . $salt );
2829 * Check given value against the token value stored in the session.
2830 * A match should confirm that the form was submitted from the
2831 * user's own login session, not a form submission from a third-party
2834 * @param $val \string Input value to compare
2835 * @param $salt \string Optional function-specific data for hashing
2836 * @return \bool Whether the token matches
2838 function matchEditToken( $val, $salt = '' ) {
2839 $sessionToken = $this->editToken( $salt );
2840 if ( $val != $sessionToken ) {
2841 wfDebug( "User::matchEditToken: broken session data\n" );
2843 return $val == $sessionToken;
2847 * Check given value against the token value stored in the session,
2848 * ignoring the suffix.
2850 * @param $val \string Input value to compare
2851 * @param $salt \string Optional function-specific data for hashing
2852 * @return \bool Whether the token matches
2854 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2855 $sessionToken = $this->editToken( $salt );
2856 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2860 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2861 * mail to the user's given address.
2863 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure.
2865 function sendConfirmationMail() {
2867 $expiration = null; // gets passed-by-ref and defined in next line.
2868 $token = $this->confirmationToken( $expiration );
2869 $url = $this->confirmationTokenUrl( $token );
2870 $invalidateURL = $this->invalidationTokenUrl( $token );
2871 $this->saveSettings();
2873 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2874 wfMsg( 'confirmemail_body',
2878 $wgLang->timeanddate( $expiration, false ),
2880 $wgLang->date( $expiration, false ),
2881 $wgLang->time( $expiration, false ) ) );
2885 * Send an e-mail to this user's account. Does not check for
2886 * confirmed status or validity.
2888 * @param $subject \string Message subject
2889 * @param $body \string Message body
2890 * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2891 * @param $replyto \string Reply-To address
2892 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure
2894 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2895 if( is_null( $from ) ) {
2896 global $wgPasswordSender;
2897 $from = $wgPasswordSender;
2900 $to = new MailAddress( $this );
2901 $sender = new MailAddress( $from );
2902 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2906 * Generate, store, and return a new e-mail confirmation code.
2907 * A hash (unsalted, since it's used as a key) is stored.
2909 * @note Call saveSettings() after calling this function to commit
2910 * this change to the database.
2912 * @param[out] &$expiration \mixed Accepts the expiration time
2913 * @return \string New token
2916 function confirmationToken( &$expiration ) {
2918 $expires = $now +
7 * 24 * 60 * 60;
2919 $expiration = wfTimestamp( TS_MW
, $expires );
2920 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2921 $hash = md5( $token );
2923 $this->mEmailToken
= $hash;
2924 $this->mEmailTokenExpires
= $expiration;
2929 * Return a URL the user can use to confirm their email address.
2930 * @param $token \string Accepts the email confirmation token
2931 * @return \string New token URL
2934 function confirmationTokenUrl( $token ) {
2935 return $this->getTokenUrl( 'ConfirmEmail', $token );
2939 * Return a URL the user can use to invalidate their email address.
2940 * @param $token \string Accepts the email confirmation token
2941 * @return \string New token URL
2944 function invalidationTokenUrl( $token ) {
2945 return $this->getTokenUrl( 'Invalidateemail', $token );
2949 * Internal function to format the e-mail validation/invalidation URLs.
2950 * This uses $wgArticlePath directly as a quickie hack to use the
2951 * hardcoded English names of the Special: pages, for ASCII safety.
2953 * @note Since these URLs get dropped directly into emails, using the
2954 * short English names avoids insanely long URL-encoded links, which
2955 * also sometimes can get corrupted in some browsers/mailers
2956 * (bug 6957 with Gmail and Internet Explorer).
2958 * @param $page \string Special page
2959 * @param $token \string Token
2960 * @return \string Formatted URL
2962 protected function getTokenUrl( $page, $token ) {
2963 global $wgArticlePath;
2967 "Special:$page/$token",
2972 * Mark the e-mail address confirmed.
2974 * @note Call saveSettings() after calling this function to commit the change.
2976 function confirmEmail() {
2977 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2978 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
2983 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2984 * address if it was already confirmed.
2986 * @note Call saveSettings() after calling this function to commit the change.
2988 function invalidateEmail() {
2990 $this->mEmailToken
= null;
2991 $this->mEmailTokenExpires
= null;
2992 $this->setEmailAuthenticationTimestamp( null );
2993 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
2998 * Set the e-mail authentication timestamp.
2999 * @param $timestamp \string TS_MW timestamp
3001 function setEmailAuthenticationTimestamp( $timestamp ) {
3003 $this->mEmailAuthenticated
= $timestamp;
3004 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3008 * Is this user allowed to send e-mails within limits of current
3009 * site configuration?
3010 * @return \bool True if allowed
3012 function canSendEmail() {
3013 global $wgEnableEmail, $wgEnableUserEmail, $wgUser;
3014 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$wgUser->isAllowed( 'sendemail' ) ) {
3017 $canSend = $this->isEmailConfirmed();
3018 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3023 * Is this user allowed to receive e-mails within limits of current
3024 * site configuration?
3025 * @return \bool True if allowed
3027 function canReceiveEmail() {
3028 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3032 * Is this user's e-mail address valid-looking and confirmed within
3033 * limits of the current site configuration?
3035 * @note If $wgEmailAuthentication is on, this may require the user to have
3036 * confirmed their address by returning a code or using a password
3037 * sent to the address from the wiki.
3039 * @return \bool True if confirmed
3041 function isEmailConfirmed() {
3042 global $wgEmailAuthentication;
3045 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3046 if( $this->isAnon() )
3048 if( !self
::isValidEmailAddr( $this->mEmail
) )
3050 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3059 * Check whether there is an outstanding request for e-mail confirmation.
3060 * @return \bool True if pending
3062 function isEmailConfirmationPending() {
3063 global $wgEmailAuthentication;
3064 return $wgEmailAuthentication &&
3065 !$this->isEmailConfirmed() &&
3066 $this->mEmailToken
&&
3067 $this->mEmailTokenExpires
> wfTimestamp();
3071 * Get the timestamp of account creation.
3073 * @return \types{\string,\bool} string Timestamp of account creation, or false for
3074 * non-existent/anonymous user accounts.
3076 public function getRegistration() {
3077 return $this->getId() > 0
3078 ?
$this->mRegistration
3083 * Get the timestamp of the first edit
3085 * @return \types{\string,\bool} string Timestamp of first edit, or false for
3086 * non-existent/anonymous user accounts.
3088 public function getFirstEditTimestamp() {
3089 if( $this->getId() == 0 ) return false; // anons
3090 $dbr = wfGetDB( DB_SLAVE
);
3091 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3092 array( 'rev_user' => $this->getId() ),
3094 array( 'ORDER BY' => 'rev_timestamp ASC' )
3096 if( !$time ) return false; // no edits
3097 return wfTimestamp( TS_MW
, $time );
3101 * Get the permissions associated with a given list of groups
3103 * @param $groups \type{\arrayof{\string}} List of internal group names
3104 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3106 static function getGroupPermissions( $groups ) {
3107 global $wgGroupPermissions, $wgRevokePermissions;
3109 // grant every granted permission first
3110 foreach( $groups as $group ) {
3111 if( isset( $wgGroupPermissions[$group] ) ) {
3112 $rights = array_merge( $rights,
3113 // array_filter removes empty items
3114 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3117 // now revoke the revoked permissions
3118 foreach( $groups as $group ) {
3119 if( isset( $wgRevokePermissions[$group] ) ) {
3120 $rights = array_diff( $rights,
3121 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3124 return array_unique( $rights );
3128 * Get all the groups who have a given permission
3130 * @param $role \string Role to check
3131 * @return \type{\arrayof{\string}} List of internal group names with the given permission
3133 static function getGroupsWithPermission( $role ) {
3134 global $wgGroupPermissions;
3135 $allowedGroups = array();
3136 foreach ( $wgGroupPermissions as $group => $rights ) {
3137 if ( isset( $rights[$role] ) && $rights[$role] ) {
3138 $allowedGroups[] = $group;
3141 return $allowedGroups;
3145 * Get the localized descriptive name for a group, if it exists
3147 * @param $group \string Internal group name
3148 * @return \string Localized descriptive group name
3150 static function getGroupName( $group ) {
3151 global $wgMessageCache;
3152 $wgMessageCache->loadAllMessages();
3153 $key = "group-$group";
3154 $name = wfMsg( $key );
3155 return $name == '' ||
wfEmptyMsg( $key, $name )
3161 * Get the localized descriptive name for a member of a group, if it exists
3163 * @param $group \string Internal group name
3164 * @return \string Localized name for group member
3166 static function getGroupMember( $group ) {
3167 global $wgMessageCache;
3168 $wgMessageCache->loadAllMessages();
3169 $key = "group-$group-member";
3170 $name = wfMsg( $key );
3171 return $name == '' ||
wfEmptyMsg( $key, $name )
3177 * Return the set of defined explicit groups.
3178 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3179 * are not included, as they are defined automatically, not in the database.
3180 * @return \type{\arrayof{\string}} Array of internal group names
3182 static function getAllGroups() {
3183 global $wgGroupPermissions, $wgRevokePermissions;
3185 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3186 self
::getImplicitGroups()
3191 * Get a list of all available permissions.
3192 * @return \type{\arrayof{\string}} Array of permission names
3194 static function getAllRights() {
3195 if ( self
::$mAllRights === false ) {
3196 global $wgAvailableRights;
3197 if ( count( $wgAvailableRights ) ) {
3198 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3200 self
::$mAllRights = self
::$mCoreRights;
3202 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3204 return self
::$mAllRights;
3208 * Get a list of implicit groups
3209 * @return \type{\arrayof{\string}} Array of internal group names
3211 public static function getImplicitGroups() {
3212 global $wgImplicitGroups;
3213 $groups = $wgImplicitGroups;
3214 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3219 * Get the title of a page describing a particular group
3221 * @param $group \string Internal group name
3222 * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3224 static function getGroupPage( $group ) {
3225 global $wgMessageCache;
3226 $wgMessageCache->loadAllMessages();
3227 $page = wfMsgForContent( 'grouppage-' . $group );
3228 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3229 $title = Title
::newFromText( $page );
3230 if( is_object( $title ) )
3237 * Create a link to the group in HTML, if available;
3238 * else return the group name.
3240 * @param $group \string Internal name of the group
3241 * @param $text \string The text of the link
3242 * @return \string HTML link to the group
3244 static function makeGroupLinkHTML( $group, $text = '' ) {
3246 $text = self
::getGroupName( $group );
3248 $title = self
::getGroupPage( $group );
3251 $sk = $wgUser->getSkin();
3252 return $sk->link( $title, htmlspecialchars( $text ) );
3259 * Create a link to the group in Wikitext, if available;
3260 * else return the group name.
3262 * @param $group \string Internal name of the group
3263 * @param $text \string The text of the link
3264 * @return \string Wikilink to the group
3266 static function makeGroupLinkWiki( $group, $text = '' ) {
3268 $text = self
::getGroupName( $group );
3270 $title = self
::getGroupPage( $group );
3272 $page = $title->getPrefixedText();
3273 return "[[$page|$text]]";
3280 * Returns an array of the groups that a particular group can add/remove.
3282 * @param $group String: the group to check for whether it can add/remove
3283 * @return Array array( 'add' => array( addablegroups ),
3284 * 'remove' => array( removablegroups ),
3285 * 'add-self' => array( addablegroups to self),
3286 * 'remove-self' => array( removable groups from self) )
3288 static function changeableByGroup( $group ) {
3289 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3291 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3292 if( empty( $wgAddGroups[$group] ) ) {
3293 // Don't add anything to $groups
3294 } elseif( $wgAddGroups[$group] === true ) {
3295 // You get everything
3296 $groups['add'] = self
::getAllGroups();
3297 } elseif( is_array( $wgAddGroups[$group] ) ) {
3298 $groups['add'] = $wgAddGroups[$group];
3301 // Same thing for remove
3302 if( empty( $wgRemoveGroups[$group] ) ) {
3303 } elseif( $wgRemoveGroups[$group] === true ) {
3304 $groups['remove'] = self
::getAllGroups();
3305 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3306 $groups['remove'] = $wgRemoveGroups[$group];
3309 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3310 if( empty( $wgGroupsAddToSelf['user']) ||
$wgGroupsAddToSelf['user'] !== true ) {
3311 foreach( $wgGroupsAddToSelf as $key => $value ) {
3312 if( is_int( $key ) ) {
3313 $wgGroupsAddToSelf['user'][] = $value;
3318 if( empty( $wgGroupsRemoveFromSelf['user']) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
3319 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3320 if( is_int( $key ) ) {
3321 $wgGroupsRemoveFromSelf['user'][] = $value;
3326 // Now figure out what groups the user can add to him/herself
3327 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3328 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3329 // No idea WHY this would be used, but it's there
3330 $groups['add-self'] = User
::getAllGroups();
3331 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3332 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3335 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3336 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3337 $groups['remove-self'] = User
::getAllGroups();
3338 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3339 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3346 * Returns an array of groups that this user can add and remove
3347 * @return Array array( 'add' => array( addablegroups ),
3348 * 'remove' => array( removablegroups ),
3349 * 'add-self' => array( addablegroups to self),
3350 * 'remove-self' => array( removable groups from self) )
3352 function changeableGroups() {
3353 if( $this->isAllowed( 'userrights' ) ) {
3354 // This group gives the right to modify everything (reverse-
3355 // compatibility with old "userrights lets you change
3357 // Using array_merge to make the groups reindexed
3358 $all = array_merge( User
::getAllGroups() );
3362 'add-self' => array(),
3363 'remove-self' => array()
3367 // Okay, it's not so simple, we will have to go through the arrays
3370 'remove' => array(),
3371 'add-self' => array(),
3372 'remove-self' => array()
3374 $addergroups = $this->getEffectiveGroups();
3376 foreach( $addergroups as $addergroup ) {
3377 $groups = array_merge_recursive(
3378 $groups, $this->changeableByGroup( $addergroup )
3380 $groups['add'] = array_unique( $groups['add'] );
3381 $groups['remove'] = array_unique( $groups['remove'] );
3382 $groups['add-self'] = array_unique( $groups['add-self'] );
3383 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3389 * Increment the user's edit-count field.
3390 * Will have no effect for anonymous users.
3392 function incEditCount() {
3393 if( !$this->isAnon() ) {
3394 $dbw = wfGetDB( DB_MASTER
);
3395 $dbw->update( 'user',
3396 array( 'user_editcount=user_editcount+1' ),
3397 array( 'user_id' => $this->getId() ),
3400 // Lazy initialization check...
3401 if( $dbw->affectedRows() == 0 ) {
3402 // Pull from a slave to be less cruel to servers
3403 // Accuracy isn't the point anyway here
3404 $dbr = wfGetDB( DB_SLAVE
);
3405 $count = $dbr->selectField( 'revision',
3407 array( 'rev_user' => $this->getId() ),
3410 // Now here's a goddamn hack...
3411 if( $dbr !== $dbw ) {
3412 // If we actually have a slave server, the count is
3413 // at least one behind because the current transaction
3414 // has not been committed and replicated.
3417 // But if DB_SLAVE is selecting the master, then the
3418 // count we just read includes the revision that was
3419 // just added in the working transaction.
3422 $dbw->update( 'user',
3423 array( 'user_editcount' => $count ),
3424 array( 'user_id' => $this->getId() ),
3428 // edit count in user cache too
3429 $this->invalidateCache();
3433 * Get the description of a given right
3435 * @param $right \string Right to query
3436 * @return \string Localized description of the right
3438 static function getRightDescription( $right ) {
3439 global $wgMessageCache;
3440 $wgMessageCache->loadAllMessages();
3441 $key = "right-$right";
3442 $name = wfMsg( $key );
3443 return $name == '' ||
wfEmptyMsg( $key, $name )
3449 * Make an old-style password hash
3451 * @param $password \string Plain-text password
3452 * @param $userId \string User ID
3453 * @return \string Password hash
3455 static function oldCrypt( $password, $userId ) {
3456 global $wgPasswordSalt;
3457 if ( $wgPasswordSalt ) {
3458 return md5( $userId . '-' . md5( $password ) );
3460 return md5( $password );
3465 * Make a new-style password hash
3467 * @param $password \string Plain-text password
3468 * @param $salt \string Optional salt, may be random or the user ID.
3469 * If unspecified or false, will generate one automatically
3470 * @return \string Password hash
3472 static function crypt( $password, $salt = false ) {
3473 global $wgPasswordSalt;
3476 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3480 if( $wgPasswordSalt ) {
3481 if ( $salt === false ) {
3482 $salt = substr( wfGenerateToken(), 0, 8 );
3484 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3486 return ':A:' . md5( $password );
3491 * Compare a password hash with a plain-text password. Requires the user
3492 * ID if there's a chance that the hash is an old-style hash.
3494 * @param $hash \string Password hash
3495 * @param $password \string Plain-text password to compare
3496 * @param $userId \string User ID for old-style password salt
3499 static function comparePasswords( $hash, $password, $userId = false ) {
3501 $type = substr( $hash, 0, 3 );
3504 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3508 if ( $type == ':A:' ) {
3510 return md5( $password ) === substr( $hash, 3 );
3511 } elseif ( $type == ':B:' ) {
3513 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3514 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3517 return self
::oldCrypt( $password, $userId ) === $hash;
3522 * Add a newuser log entry for this user
3523 * @param $byEmail Boolean: account made by email?
3525 public function addNewUserLogEntry( $byEmail = false ) {
3526 global $wgUser, $wgContLang, $wgNewUserLog;
3527 if( empty( $wgNewUserLog ) ) {
3528 return true; // disabled
3530 $talk = $wgContLang->getFormattedNsText( NS_TALK
);
3531 if( $this->getName() == $wgUser->getName() ) {
3535 $action = 'create2';
3537 ?
wfMsgForContent( 'newuserlog-byemail' )
3540 $log = new LogPage( 'newusers' );
3543 $this->getUserPage(),
3545 array( $this->getId() )
3551 * Add an autocreate newuser log entry for this user
3552 * Used by things like CentralAuth and perhaps other authplugins.
3554 public function addNewUserLogEntryAutoCreate() {
3555 global $wgNewUserLog;
3556 if( empty( $wgNewUserLog ) ) {
3557 return true; // disabled
3559 $log = new LogPage( 'newusers', false );
3560 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3564 protected function loadOptions() {
3566 if ( $this->mOptionsLoaded ||
!$this->getId() )
3569 $this->mOptions
= self
::getDefaultOptions();
3571 // Maybe load from the object
3572 if ( !is_null( $this->mOptionOverrides
) ) {
3573 wfDebug( "Loading options for user " . $this->getId() . " from override cache.\n" );
3574 foreach( $this->mOptionOverrides
as $key => $value ) {
3575 $this->mOptions
[$key] = $value;
3578 wfDebug( "Loading options for user " . $this->getId() . " from database.\n" );
3579 // Load from database
3580 $dbr = wfGetDB( DB_SLAVE
);
3582 $res = $dbr->select(
3585 array( 'up_user' => $this->getId() ),
3589 while( $row = $dbr->fetchObject( $res ) ) {
3590 $this->mOptionOverrides
[$row->up_property
] = $row->up_value
;
3591 $this->mOptions
[$row->up_property
] = $row->up_value
;
3595 $this->mOptionsLoaded
= true;
3597 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
3600 protected function saveOptions() {
3601 global $wgAllowPrefChange;
3603 $extuser = ExternalUser
::newFromUser( $this );
3605 $this->loadOptions();
3606 $dbw = wfGetDB( DB_MASTER
);
3608 $insert_rows = array();
3610 $saveOptions = $this->mOptions
;
3612 // Allow hooks to abort, for instance to save to a global profile.
3613 // Reset options to default state before saving.
3614 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3617 foreach( $saveOptions as $key => $value ) {
3618 # Don't bother storing default values
3619 if ( ( is_null( self
::getDefaultOption( $key ) ) &&
3620 !( $value === false ||
is_null($value) ) ) ||
3621 $value != self
::getDefaultOption( $key ) ) {
3622 $insert_rows[] = array(
3623 'up_user' => $this->getId(),
3624 'up_property' => $key,
3625 'up_value' => $value,
3628 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3629 switch ( $wgAllowPrefChange[$key] ) {
3635 $extuser->setPref( $key, $value );
3641 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__
);
3642 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
);
3647 * Provide an array of HTML 5 attributes to put on an input element
3648 * intended for the user to enter a new password. This may include
3649 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3651 * Do *not* use this when asking the user to enter his current password!
3652 * Regardless of configuration, users may have invalid passwords for whatever
3653 * reason (e.g., they were set before requirements were tightened up).
3654 * Only use it when asking for a new password, like on account creation or
3657 * Obviously, you still need to do server-side checking.
3659 * @return array Array of HTML attributes suitable for feeding to
3660 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3661 * That will potentially output invalid XHTML 1.0 Transitional, and will
3662 * get confused by the boolean attribute syntax used.)
3664 public static function passwordChangeInputAttribs() {
3665 global $wgMinimalPasswordLength;
3667 if ( $wgMinimalPasswordLength == 0 ) {
3671 # Note that the pattern requirement will always be satisfied if the
3672 # input is empty, so we need required in all cases.
3673 $ret = array( 'required' );
3675 # We can't actually do this right now, because Opera 9.6 will print out
3676 # the entered password visibly in its error message! When other
3677 # browsers add support for this attribute, or Opera fixes its support,
3678 # we can add support with a version check to avoid doing this on Opera
3679 # versions where it will be a problem. Reported to Opera as
3680 # DSK-262266, but they don't have a public bug tracker for us to follow.
3682 if ( $wgMinimalPasswordLength > 1 ) {
3683 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3684 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3685 $wgMinimalPasswordLength );