0b53fe6863223938fe4d726f3f0549bb1d87b544
3 * Implements the User class for the %MediaWiki software.
8 * \int Number of characters in user_token field.
11 define( 'USER_TOKEN_LENGTH', 32 );
14 * \int Serialized record version.
17 define( 'MW_USER_VERSION', 8 );
20 * \string Some punctuation to prevent editing from broken text-mangling proxies.
23 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
26 * Thrown by User::setPassword() on error.
29 class PasswordError
extends MWException
{
34 * The User object encapsulates all of the user-specific settings (user_id,
35 * name, rights, password, email address, options, last login time). Client
36 * classes use the getXXX() functions to access these fields. These functions
37 * do all the work of determining whether the user is logged in,
38 * whether the requested option can be satisfied from cookies or
39 * whether a database query is needed. Most of the settings needed
40 * for rendering normal pages are set in the cookie to minimize use
46 * \type{\arrayof{\string}} A list of default user toggles, i.e., boolean user
47 * preferences that are displayed by Special:Preferences as checkboxes.
48 * This list can be extended via the UserToggles hook or by
49 * $wgContLang::getExtraUserToggles().
52 public static $mToggles = array(
62 'editsectiononrightclick',
74 'enotifwatchlistpages',
75 'enotifusertalkpages',
78 'shownumberswatching',
98 * \type{\arrayof{\string}} List of member variables which are saved to the
99 * shared cache (memcached). Any operation which changes the
100 * corresponding database fields must call a cache-clearing function.
103 static $mCacheVars = array(
114 'mEmailAuthenticated',
116 'mEmailTokenExpires',
121 // user_properties table
126 * \type{\arrayof{\string}} Core rights.
127 * Each of these should have a corresponding message of the form
131 static $mCoreRights = array(
158 'move-rootuserpages',
162 'override-export-depth',
182 'userrights-interwiki',
186 * \string Cached results of getAllRights()
188 static $mAllRights = false;
190 /** @name Cache variables */
192 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
193 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
194 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
198 * \bool Whether the cache variables have been loaded.
200 var $mDataLoaded, $mAuthLoaded, $mOptionsLoaded;
203 * \string Initialization data source if mDataLoaded==false. May be one of:
204 * - 'defaults' anonymous user initialised from class defaults
205 * - 'name' initialise from mName
206 * - 'id' initialise from mId
207 * - 'session' log in from cookies or session if possible
209 * Use the User::newFrom*() family of functions to set this.
213 /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
215 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
216 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
217 $mLocked, $mHideName, $mOptions;
220 static $idCacheByName = array();
223 * Lightweight constructor for an anonymous user.
224 * Use the User::newFrom* factory functions for other kinds of users.
228 * @see newFromConfirmationCode()
229 * @see newFromSession()
233 $this->clearInstanceCache( 'defaults' );
237 * Load the user table data for this object from the source given by mFrom.
240 if ( $this->mDataLoaded
) {
243 wfProfileIn( __METHOD__
);
245 # Set it now to avoid infinite recursion in accessors
246 $this->mDataLoaded
= true;
248 switch ( $this->mFrom
) {
250 $this->loadDefaults();
253 $this->mId
= self
::idFromName( $this->mName
);
255 # Nonexistent user placeholder object
256 $this->loadDefaults( $this->mName
);
265 $this->loadFromSession();
266 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
269 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
271 wfProfileOut( __METHOD__
);
275 * Load user table data, given mId has already been set.
276 * @return \bool false if the ID does not exist, true otherwise
279 function loadFromId() {
281 if ( $this->mId
== 0 ) {
282 $this->loadDefaults();
287 $key = wfMemcKey( 'user', 'id', $this->mId
);
288 $data = $wgMemc->get( $key );
289 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
290 # Object is expired, load from DB
295 wfDebug( "Cache miss for user {$this->mId}\n" );
297 if ( !$this->loadFromDatabase() ) {
298 # Can't load from ID, user is anonymous
301 $this->saveToCache();
303 wfDebug( "Got user {$this->mId} from cache\n" );
305 foreach ( self
::$mCacheVars as $name ) {
306 $this->$name = $data[$name];
313 * Save user data to the shared cache
315 function saveToCache() {
318 $this->loadOptions();
319 if ( $this->isAnon() ) {
320 // Anonymous users are uncached
324 foreach ( self
::$mCacheVars as $name ) {
325 $data[$name] = $this->$name;
327 $data['mVersion'] = MW_USER_VERSION
;
328 $key = wfMemcKey( 'user', 'id', $this->mId
);
330 $wgMemc->set( $key, $data );
334 /** @name newFrom*() static factory methods */
338 * Static factory method for creation from username.
340 * This is slightly less efficient than newFromId(), so use newFromId() if
341 * you have both an ID and a name handy.
343 * @param $name \string Username, validated by Title::newFromText()
344 * @param $validate \mixed Validate username. Takes the same parameters as
345 * User::getCanonicalName(), except that true is accepted as an alias
346 * for 'valid', for BC.
348 * @return \type{User} The User object, or null if the username is invalid. If the
349 * username is not present in the database, the result will be a user object
350 * with a name, zero user ID and default settings.
352 static function newFromName( $name, $validate = 'valid' ) {
353 if ( $validate === true ) {
356 $name = self
::getCanonicalName( $name, $validate );
357 if ( WikiError
::isError( $name ) ) {
359 } elseif ( $name === false ) {
362 # Create unloaded user object
371 * Static factory method for creation from a given user ID.
373 * @param $id \int Valid user ID
374 * @return \type{User} The corresponding User object
376 static function newFromId( $id ) {
384 * Factory method to fetch whichever user has a given email confirmation code.
385 * This code is generated when an account is created or its e-mail address
388 * If the code is invalid or has expired, returns NULL.
390 * @param $code \string Confirmation code
391 * @return \type{User}
393 static function newFromConfirmationCode( $code ) {
394 $dbr = wfGetDB( DB_SLAVE
);
395 $id = $dbr->selectField( 'user', 'user_id', array(
396 'user_email_token' => md5( $code ),
397 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
399 if( $id !== false ) {
400 return User
::newFromId( $id );
407 * Create a new user object using data from session or cookies. If the
408 * login credentials are invalid, the result is an anonymous user.
410 * @return \type{User}
412 static function newFromSession() {
414 $user->mFrom
= 'session';
419 * Create a new user object from a user row.
420 * The row should have all fields from the user table in it.
421 * @param $row array A row from the user table
422 * @return \type{User}
424 static function newFromRow( $row ) {
426 $user->loadFromRow( $row );
434 * Get the username corresponding to a given user ID
435 * @param $id \int User ID
436 * @return \string The corresponding username
438 static function whoIs( $id ) {
439 $dbr = wfGetDB( DB_SLAVE
);
440 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
444 * Get the real name of a user given their user ID
446 * @param $id \int User ID
447 * @return \string The corresponding user's real name
449 static function whoIsReal( $id ) {
450 $dbr = wfGetDB( DB_SLAVE
);
451 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
455 * Get database id given a user name
456 * @param $name \string Username
457 * @return \types{\int,\null} The corresponding user's ID, or null if user is nonexistent
459 static function idFromName( $name ) {
460 $nt = Title
::makeTitleSafe( NS_USER
, $name );
461 if( is_null( $nt ) ) {
466 if ( isset( self
::$idCacheByName[$name] ) ) {
467 return self
::$idCacheByName[$name];
470 $dbr = wfGetDB( DB_SLAVE
);
471 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
473 if ( $s === false ) {
476 $result = $s->user_id
;
479 self
::$idCacheByName[$name] = $result;
481 if ( count( self
::$idCacheByName ) > 1000 ) {
482 self
::$idCacheByName = array();
489 * Does the string match an anonymous IPv4 address?
491 * This function exists for username validation, in order to reject
492 * usernames which are similar in form to IP addresses. Strings such
493 * as 300.300.300.300 will return true because it looks like an IP
494 * address, despite not being strictly valid.
496 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
497 * address because the usemod software would "cloak" anonymous IP
498 * addresses like this, if we allowed accounts like this to be created
499 * new users could get the old edits of these anonymous users.
501 * @param $name \string String to match
502 * @return \bool True or false
504 static function isIP( $name ) {
505 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
509 * Is the input a valid username?
511 * Checks if the input is a valid username, we don't want an empty string,
512 * an IP address, anything that containins slashes (would mess up subpages),
513 * is longer than the maximum allowed username size or doesn't begin with
516 * @param $name \string String to match
517 * @return \bool True or false
519 static function isValidUserName( $name ) {
520 global $wgContLang, $wgMaxNameChars;
523 || User
::isIP( $name )
524 ||
strpos( $name, '/' ) !== false
525 ||
strlen( $name ) > $wgMaxNameChars
526 ||
$name != $wgContLang->ucfirst( $name ) ) {
527 wfDebugLog( 'username', __METHOD__
.
528 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
532 // Ensure that the name can't be misresolved as a different title,
533 // such as with extra namespace keys at the start.
534 $parsed = Title
::newFromText( $name );
535 if( is_null( $parsed )
536 ||
$parsed->getNamespace()
537 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
538 wfDebugLog( 'username', __METHOD__
.
539 ": '$name' invalid due to ambiguous prefixes" );
543 // Check an additional blacklist of troublemaker characters.
544 // Should these be merged into the title char list?
545 $unicodeBlacklist = '/[' .
546 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
547 '\x{00a0}' . # non-breaking space
548 '\x{2000}-\x{200f}' . # various whitespace
549 '\x{2028}-\x{202f}' . # breaks and control chars
550 '\x{3000}' . # ideographic space
551 '\x{e000}-\x{f8ff}' . # private use
553 if( preg_match( $unicodeBlacklist, $name ) ) {
554 wfDebugLog( 'username', __METHOD__
.
555 ": '$name' invalid due to blacklisted characters" );
563 * Usernames which fail to pass this function will be blocked
564 * from user login and new account registrations, but may be used
565 * internally by batch processes.
567 * If an account already exists in this form, login will be blocked
568 * by a failure to pass this function.
570 * @param $name \string String to match
571 * @return \bool True or false
573 static function isUsableName( $name ) {
574 global $wgReservedUsernames;
575 // Must be a valid username, obviously ;)
576 if ( !self
::isValidUserName( $name ) ) {
580 static $reservedUsernames = false;
581 if ( !$reservedUsernames ) {
582 $reservedUsernames = $wgReservedUsernames;
583 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
586 // Certain names may be reserved for batch processes.
587 foreach ( $reservedUsernames as $reserved ) {
588 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
589 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
591 if ( $reserved == $name ) {
599 * Usernames which fail to pass this function will be blocked
600 * from new account registrations, but may be used internally
601 * either by batch processes or by user accounts which have
602 * already been created.
604 * Additional character blacklisting may be added here
605 * rather than in isValidUserName() to avoid disrupting
608 * @param $name \string String to match
609 * @return \bool True or false
611 static function isCreatableName( $name ) {
612 global $wgInvalidUsernameCharacters;
614 self
::isUsableName( $name ) &&
616 // Registration-time character blacklisting...
617 !preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name );
621 * Is the input a valid password for this user?
623 * @param $password String Desired password
624 * @return mixed: bool True or false or a message key explaining why the password is invalid
626 function isValidPassword( $password ) {
627 global $wgMinimalPasswordLength, $wgContLang;
629 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
631 if( $result === false )
634 // Password needs to be long enough, and can't be the same as the username
635 return strlen( $password ) >= $wgMinimalPasswordLength
636 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
640 * Given unvalidated password input, return error message on failure.
642 * @param $password String Desired password
643 * @return mixed: true on success, string of error message on failure
645 function getPasswordValidity( $password ) {
646 global $wgMinimalPasswordLength, $wgContLang;
648 if ( ( $result = $this->isValidPassword( $password ) ) === false ) {
649 if( strlen( $password ) < $wgMinimalPasswordLength ) {
650 return 'passwordtooshort';
651 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
652 return 'password-name-match';
654 } elseif( $result === true ) {
657 return $result; //the isValidPassword hook set a string $result and returned false
662 * Does a string look like an e-mail address?
664 * There used to be a regular expression here, it got removed because it
665 * rejected valid addresses. Actually just check if there is '@' somewhere
666 * in the given address.
668 * @todo Check for RFC 2822 compilance (bug 959)
670 * @param $addr \string E-mail address
671 * @return \bool True or false
673 public static function isValidEmailAddr( $addr ) {
675 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
679 return strpos( $addr, '@' ) !== false;
683 * Given unvalidated user input, return a canonical username, or false if
684 * the username is invalid.
685 * @param $name \string User input
686 * @param $validate \types{\string,\bool} Type of validation to use:
687 * - false No validation
688 * - 'valid' Valid for batch processes
689 * - 'usable' Valid for batch processes and login
690 * - 'creatable' Valid for batch processes, login and account creation
692 static function getCanonicalName( $name, $validate = 'valid' ) {
693 # Maybe force usernames to capital
694 $name = Title
::capitalize( $name, NS_USER
);
696 # Reject names containing '#'; these will be cleaned up
697 # with title normalisation, but then it's too late to
699 if( strpos( $name, '#' ) !== false )
700 return new WikiError( 'usernamehasherror' );
702 # Clean up name according to title rules
703 $t = ( $validate === 'valid' ) ?
704 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
705 # Check for invalid titles
706 if( is_null( $t ) ) {
710 # Reject various classes of invalid names
711 $name = $t->getText();
713 $name = $wgAuth->getCanonicalName( $t->getText() );
715 switch ( $validate ) {
719 if ( !User
::isValidUserName( $name ) ) {
724 if ( !User
::isUsableName( $name ) ) {
729 if ( !User
::isCreatableName( $name ) ) {
734 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
740 * Count the number of edits of a user
741 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
743 * @param $uid \int User ID to check
744 * @return \int The user's edit count
746 static function edits( $uid ) {
747 wfProfileIn( __METHOD__
);
748 $dbr = wfGetDB( DB_SLAVE
);
749 // check if the user_editcount field has been initialized
750 $field = $dbr->selectField(
751 'user', 'user_editcount',
752 array( 'user_id' => $uid ),
756 if( $field === null ) { // it has not been initialized. do so.
757 $dbw = wfGetDB( DB_MASTER
);
758 $count = $dbr->selectField(
759 'revision', 'count(*)',
760 array( 'rev_user' => $uid ),
765 array( 'user_editcount' => $count ),
766 array( 'user_id' => $uid ),
772 wfProfileOut( __METHOD__
);
777 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
778 * @todo hash random numbers to improve security, like generateToken()
780 * @return \string New random password
782 static function randomPassword() {
783 global $wgMinimalPasswordLength;
784 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
785 $l = strlen( $pwchars ) - 1;
787 $pwlength = max( 7, $wgMinimalPasswordLength );
788 $digit = mt_rand( 0, $pwlength - 1 );
790 for ( $i = 0; $i < $pwlength; $i++
) {
791 $np .= $i == $digit ?
chr( mt_rand( 48, 57 ) ) : $pwchars{ mt_rand( 0, $l ) };
797 * Set cached properties to default.
799 * @note This no longer clears uncached lazy-initialised properties;
800 * the constructor does that instead.
803 function loadDefaults( $name = false ) {
804 wfProfileIn( __METHOD__
);
806 global $wgCookiePrefix;
809 $this->mName
= $name;
810 $this->mRealName
= '';
811 $this->mPassword
= $this->mNewpassword
= '';
812 $this->mNewpassTime
= null;
814 $this->mOptionOverrides
= null;
815 $this->mOptionsLoaded
= false;
817 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
818 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
820 $this->mTouched
= '0'; # Allow any pages to be cached
823 $this->setToken(); # Random
824 $this->mEmailAuthenticated
= null;
825 $this->mEmailToken
= '';
826 $this->mEmailTokenExpires
= null;
827 $this->mRegistration
= wfTimestamp( TS_MW
);
828 $this->mGroups
= array();
830 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
832 wfProfileOut( __METHOD__
);
836 * @deprecated Use wfSetupSession().
838 function SetupSession() {
839 wfDeprecated( __METHOD__
);
844 * Load user data from the session or login cookie. If there are no valid
845 * credentials, initialises the user as an anonymous user.
846 * @return \bool True if the user is logged in, false otherwise.
848 private function loadFromSession() {
849 global $wgMemc, $wgCookiePrefix;
852 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
853 if ( $result !== null ) {
857 if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
858 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
859 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
860 $this->loadDefaults(); // Possible collision!
861 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
862 cookie user ID ($sId) don't match!" );
865 $_SESSION['wsUserID'] = $sId;
866 } else if ( isset( $_SESSION['wsUserID'] ) ) {
867 if ( $_SESSION['wsUserID'] != 0 ) {
868 $sId = $_SESSION['wsUserID'];
870 $this->loadDefaults();
874 $this->loadDefaults();
878 if ( isset( $_SESSION['wsUserName'] ) ) {
879 $sName = $_SESSION['wsUserName'];
880 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
881 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
882 $_SESSION['wsUserName'] = $sName;
884 $this->loadDefaults();
888 $passwordCorrect = FALSE;
890 if ( !$this->loadFromId() ) {
891 # Not a valid ID, loadFromId has switched the object to anon for us
895 if ( isset( $_SESSION['wsToken'] ) ) {
896 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
898 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
899 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
902 # No session or persistent login cookie
903 $this->loadDefaults();
907 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
908 $_SESSION['wsToken'] = $this->mToken
;
909 wfDebug( "Logged in from $from\n" );
912 # Invalid credentials
913 wfDebug( "Can't log in from $from, invalid credentials\n" );
914 $this->loadDefaults();
920 * Load user and user_group data from the database.
921 * $this::mId must be set, this is how the user is identified.
923 * @return \bool True if the user exists, false if the user is anonymous
926 function loadFromDatabase() {
928 $this->mId
= intval( $this->mId
);
930 /** Anonymous user */
932 $this->loadDefaults();
936 $dbr = wfGetDB( DB_MASTER
);
937 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
939 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
941 if ( $s !== false ) {
942 # Initialise user table data
943 $this->loadFromRow( $s );
944 $this->mGroups
= null; // deferred
945 $this->getEditCount(); // revalidation for nulls
950 $this->loadDefaults();
956 * Initialize this object from a row from the user table.
958 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
960 function loadFromRow( $row ) {
961 $this->mDataLoaded
= true;
963 if ( isset( $row->user_id
) ) {
964 $this->mId
= intval( $row->user_id
);
966 $this->mName
= $row->user_name
;
967 $this->mRealName
= $row->user_real_name
;
968 $this->mPassword
= $row->user_password
;
969 $this->mNewpassword
= $row->user_newpassword
;
970 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
971 $this->mEmail
= $row->user_email
;
972 $this->decodeOptions( $row->user_options
);
973 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
974 $this->mToken
= $row->user_token
;
975 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
976 $this->mEmailToken
= $row->user_email_token
;
977 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
978 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
979 $this->mEditCount
= $row->user_editcount
;
983 * Load the groups from the database if they aren't already loaded.
986 function loadGroups() {
987 if ( is_null( $this->mGroups
) ) {
988 $dbr = wfGetDB( DB_MASTER
);
989 $res = $dbr->select( 'user_groups',
991 array( 'ug_user' => $this->mId
),
993 $this->mGroups
= array();
994 while( $row = $dbr->fetchObject( $res ) ) {
995 $this->mGroups
[] = $row->ug_group
;
1001 * Clear various cached data stored in this object.
1002 * @param $reloadFrom \string Reload user and user_groups table data from a
1003 * given source. May be "name", "id", "defaults", "session", or false for
1006 function clearInstanceCache( $reloadFrom = false ) {
1007 $this->mNewtalk
= -1;
1008 $this->mDatePreference
= null;
1009 $this->mBlockedby
= -1; # Unset
1010 $this->mHash
= false;
1011 $this->mSkin
= null;
1012 $this->mRights
= null;
1013 $this->mEffectiveGroups
= null;
1014 $this->mOptions
= null;
1016 if ( $reloadFrom ) {
1017 $this->mDataLoaded
= false;
1018 $this->mFrom
= $reloadFrom;
1023 * Combine the language default options with any site-specific options
1024 * and add the default language variants.
1026 * @return \type{\arrayof{\string}} Array of options
1028 static function getDefaultOptions() {
1029 global $wgNamespacesToBeSearchedDefault;
1031 * Site defaults will override the global/language defaults
1033 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1034 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
1037 * default language setting
1039 $variant = $wgContLang->getPreferredVariant( false );
1040 $defOpt['variant'] = $variant;
1041 $defOpt['language'] = $variant;
1042 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1043 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1045 $defOpt['skin'] = $wgDefaultSkin;
1051 * Get a given default option value.
1053 * @param $opt \string Name of option to retrieve
1054 * @return \string Default option value
1056 public static function getDefaultOption( $opt ) {
1057 $defOpts = self
::getDefaultOptions();
1058 if( isset( $defOpts[$opt] ) ) {
1059 return $defOpts[$opt];
1066 * Get a list of user toggle names
1067 * @return \type{\arrayof{\string}} Array of user toggle names
1069 static function getToggles() {
1070 global $wgContLang, $wgUseRCPatrol;
1071 $extraToggles = array();
1072 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1073 if( $wgUseRCPatrol ) {
1074 $extraToggles[] = 'hidepatrolled';
1075 $extraToggles[] = 'newpageshidepatrolled';
1076 $extraToggles[] = 'watchlisthidepatrolled';
1078 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1083 * Get blocking information
1085 * @param $bFromSlave \bool Whether to check the slave database first. To
1086 * improve performance, non-critical checks are done
1087 * against slaves. Check when actually saving should be
1088 * done against master.
1090 function getBlockedStatus( $bFromSlave = true ) {
1091 global $wgEnableSorbs, $wgProxyWhitelist, $wgUser;
1093 if ( -1 != $this->mBlockedby
) {
1094 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1098 wfProfileIn( __METHOD__
);
1099 wfDebug( __METHOD__
.": checking...\n" );
1101 // Initialize data...
1102 // Otherwise something ends up stomping on $this->mBlockedby when
1103 // things get lazy-loaded later, causing false positive block hits
1104 // due to -1 !== 0. Probably session-related... Nothing should be
1105 // overwriting mBlockedby, surely?
1108 $this->mBlockedby
= 0;
1109 $this->mHideName
= 0;
1110 $this->mAllowUsertalk
= 0;
1112 # Check if we are looking at an IP or a logged-in user
1113 if ( $this->isIP( $this->getName() ) ) {
1114 $ip = $this->getName();
1116 # Check if we are looking at the current user
1117 # If we don't, and the user is logged in, we don't know about
1118 # his IP / autoblock status, so ignore autoblock of current user's IP
1119 if ( $this->getID() != $wgUser->getID() ) {
1122 # Get IP of current user
1127 if ( $this->isAllowed( 'ipblock-exempt' ) ) {
1128 # Exempt from all types of IP-block
1133 $this->mBlock
= new Block();
1134 $this->mBlock
->fromMaster( !$bFromSlave );
1135 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1136 wfDebug( __METHOD__
. ": Found block.\n" );
1137 $this->mBlockedby
= $this->mBlock
->mBy
;
1138 $this->mBlockreason
= $this->mBlock
->mReason
;
1139 $this->mHideName
= $this->mBlock
->mHideName
;
1140 $this->mAllowUsertalk
= $this->mBlock
->mAllowUsertalk
;
1141 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1142 $this->spreadBlock();
1145 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1146 // apply to users. Note that the existence of $this->mBlock is not used to
1147 // check for edit blocks, $this->mBlockedby is instead.
1151 if ( !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1153 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1154 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1155 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1159 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1160 if ( $this->inSorbsBlacklist( $ip ) ) {
1161 $this->mBlockedby
= wfMsg( 'sorbs' );
1162 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1168 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1170 wfProfileOut( __METHOD__
);
1174 * Whether the given IP is in the SORBS blacklist.
1176 * @param $ip \string IP to check
1177 * @return \bool True if blacklisted.
1179 function inSorbsBlacklist( $ip ) {
1180 global $wgEnableSorbs, $wgSorbsUrl;
1182 return $wgEnableSorbs &&
1183 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1187 * Whether the given IP is in a given DNS blacklist.
1189 * @param $ip \string IP to check
1190 * @param $bases \string or Array of Strings: URL of the DNS blacklist
1191 * @return \bool True if blacklisted.
1193 function inDnsBlacklist( $ip, $bases ) {
1194 wfProfileIn( __METHOD__
);
1198 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1199 if( IP
::isIPv4( $ip ) ) {
1200 # Reverse IP, bug 21255
1201 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1203 foreach( (array)$bases as $base ) {
1205 $host = "$ipReversed.$base";
1208 $ipList = gethostbynamel( $host );
1211 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1215 wfDebug( "Requested $host, not found in $base.\n" );
1220 wfProfileOut( __METHOD__
);
1225 * Is this user subject to rate limiting?
1227 * @return \bool True if rate limited
1229 public function isPingLimitable() {
1230 global $wgRateLimitsExcludedGroups;
1231 global $wgRateLimitsExcludedIPs;
1232 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1233 // Deprecated, but kept for backwards-compatibility config
1236 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1237 // No other good way currently to disable rate limits
1238 // for specific IPs. :P
1239 // But this is a crappy hack and should die.
1242 return !$this->isAllowed('noratelimit');
1246 * Primitive rate limits: enforce maximum actions per time period
1247 * to put a brake on flooding.
1249 * @note When using a shared cache like memcached, IP-address
1250 * last-hit counters will be shared across wikis.
1252 * @param $action \string Action to enforce; 'edit' if unspecified
1253 * @return \bool True if a rate limiter was tripped
1255 function pingLimiter( $action = 'edit' ) {
1256 # Call the 'PingLimiter' hook
1258 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1262 global $wgRateLimits;
1263 if( !isset( $wgRateLimits[$action] ) ) {
1267 # Some groups shouldn't trigger the ping limiter, ever
1268 if( !$this->isPingLimitable() )
1271 global $wgMemc, $wgRateLimitLog;
1272 wfProfileIn( __METHOD__
);
1274 $limits = $wgRateLimits[$action];
1276 $id = $this->getId();
1280 if( isset( $limits['anon'] ) && $id == 0 ) {
1281 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1284 if( isset( $limits['user'] ) && $id != 0 ) {
1285 $userLimit = $limits['user'];
1287 if( $this->isNewbie() ) {
1288 if( isset( $limits['newbie'] ) && $id != 0 ) {
1289 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1291 if( isset( $limits['ip'] ) ) {
1292 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1295 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1296 $subnet = $matches[1];
1297 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1300 // Check for group-specific permissions
1301 // If more than one group applies, use the group with the highest limit
1302 foreach ( $this->getGroups() as $group ) {
1303 if ( isset( $limits[$group] ) ) {
1304 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1305 $userLimit = $limits[$group];
1309 // Set the user limit key
1310 if ( $userLimit !== false ) {
1311 wfDebug( __METHOD__
. ": effective user limit: $userLimit\n" );
1312 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1316 foreach( $keys as $key => $limit ) {
1317 list( $max, $period ) = $limit;
1318 $summary = "(limit $max in {$period}s)";
1319 $count = $wgMemc->get( $key );
1322 if( $count > $max ) {
1323 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1324 if( $wgRateLimitLog ) {
1325 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1329 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1331 $wgMemc->incr( $key );
1333 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1334 $wgMemc->set( $key, 1, intval( $period ) ); // first ping
1338 wfProfileOut( __METHOD__
);
1343 * Check if user is blocked
1345 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1346 * @return \bool True if blocked, false otherwise
1348 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1349 wfDebug( "User::isBlocked: enter\n" );
1350 $this->getBlockedStatus( $bFromSlave );
1351 return $this->mBlockedby
!== 0;
1355 * Check if user is blocked from editing a particular article
1357 * @param $title \string Title to check
1358 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1359 * @return \bool True if blocked, false otherwise
1361 function isBlockedFrom( $title, $bFromSlave = false ) {
1362 global $wgBlockAllowsUTEdit;
1363 wfProfileIn( __METHOD__
);
1364 wfDebug( __METHOD__
. ": enter\n" );
1366 wfDebug( __METHOD__
. ": asking isBlocked()\n" );
1367 $blocked = $this->isBlocked( $bFromSlave );
1368 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1369 # If a user's name is suppressed, they cannot make edits anywhere
1370 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1371 $title->getNamespace() == NS_USER_TALK
) {
1373 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1376 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1378 wfProfileOut( __METHOD__
);
1383 * If user is blocked, return the name of the user who placed the block
1384 * @return \string name of blocker
1386 function blockedBy() {
1387 $this->getBlockedStatus();
1388 return $this->mBlockedby
;
1392 * If user is blocked, return the specified reason for the block
1393 * @return \string Blocking reason
1395 function blockedFor() {
1396 $this->getBlockedStatus();
1397 return $this->mBlockreason
;
1401 * If user is blocked, return the ID for the block
1402 * @return \int Block ID
1404 function getBlockId() {
1405 $this->getBlockedStatus();
1406 return ( $this->mBlock ?
$this->mBlock
->mId
: false );
1410 * Check if user is blocked on all wikis.
1411 * Do not use for actual edit permission checks!
1412 * This is intented for quick UI checks.
1414 * @param $ip \type{\string} IP address, uses current client if none given
1415 * @return \type{\bool} True if blocked, false otherwise
1417 function isBlockedGlobally( $ip = '' ) {
1418 if( $this->mBlockedGlobally
!== null ) {
1419 return $this->mBlockedGlobally
;
1421 // User is already an IP?
1422 if( IP
::isIPAddress( $this->getName() ) ) {
1423 $ip = $this->getName();
1428 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1429 $this->mBlockedGlobally
= (bool)$blocked;
1430 return $this->mBlockedGlobally
;
1434 * Check if user account is locked
1436 * @return \type{\bool} True if locked, false otherwise
1438 function isLocked() {
1439 if( $this->mLocked
!== null ) {
1440 return $this->mLocked
;
1443 $authUser = $wgAuth->getUserInstance( $this );
1444 $this->mLocked
= (bool)$authUser->isLocked();
1445 return $this->mLocked
;
1449 * Check if user account is hidden
1451 * @return \type{\bool} True if hidden, false otherwise
1453 function isHidden() {
1454 if( $this->mHideName
!== null ) {
1455 return $this->mHideName
;
1457 $this->getBlockedStatus();
1458 if( !$this->mHideName
) {
1460 $authUser = $wgAuth->getUserInstance( $this );
1461 $this->mHideName
= (bool)$authUser->isHidden();
1463 return $this->mHideName
;
1467 * Get the user's ID.
1468 * @return \int The user's ID; 0 if the user is anonymous or nonexistent
1471 if( $this->mId
=== null and $this->mName
!== null
1472 and User
::isIP( $this->mName
) ) {
1473 // Special case, we know the user is anonymous
1475 } elseif( $this->mId
=== null ) {
1476 // Don't load if this was initialized from an ID
1483 * Set the user and reload all fields according to a given ID
1484 * @param $v \int User ID to reload
1486 function setId( $v ) {
1488 $this->clearInstanceCache( 'id' );
1492 * Get the user name, or the IP of an anonymous user
1493 * @return \string User's name or IP address
1495 function getName() {
1496 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1497 # Special case optimisation
1498 return $this->mName
;
1501 if ( $this->mName
=== false ) {
1503 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1505 return $this->mName
;
1510 * Set the user name.
1512 * This does not reload fields from the database according to the given
1513 * name. Rather, it is used to create a temporary "nonexistent user" for
1514 * later addition to the database. It can also be used to set the IP
1515 * address for an anonymous user to something other than the current
1518 * @note User::newFromName() has rougly the same function, when the named user
1520 * @param $str \string New user name to set
1522 function setName( $str ) {
1524 $this->mName
= $str;
1528 * Get the user's name escaped by underscores.
1529 * @return \string Username escaped by underscores.
1531 function getTitleKey() {
1532 return str_replace( ' ', '_', $this->getName() );
1536 * Check if the user has new messages.
1537 * @return \bool True if the user has new messages
1539 function getNewtalk() {
1542 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1543 if( $this->mNewtalk
=== -1 ) {
1544 $this->mNewtalk
= false; # reset talk page status
1546 # Check memcached separately for anons, who have no
1547 # entire User object stored in there.
1550 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1551 $newtalk = $wgMemc->get( $key );
1552 if( strval( $newtalk ) !== '' ) {
1553 $this->mNewtalk
= (bool)$newtalk;
1555 // Since we are caching this, make sure it is up to date by getting it
1557 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1558 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1561 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1565 return (bool)$this->mNewtalk
;
1569 * Return the talk page(s) this user has new messages on.
1570 * @return \type{\arrayof{\string}} Array of page URLs
1572 function getNewMessageLinks() {
1574 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1577 if( !$this->getNewtalk() )
1579 $up = $this->getUserPage();
1580 $utp = $up->getTalkPage();
1581 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1585 * Internal uncached check for new messages
1588 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1589 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1590 * @param $fromMaster \bool true to fetch from the master, false for a slave
1591 * @return \bool True if the user has new messages
1594 function checkNewtalk( $field, $id, $fromMaster = false ) {
1595 if ( $fromMaster ) {
1596 $db = wfGetDB( DB_MASTER
);
1598 $db = wfGetDB( DB_SLAVE
);
1600 $ok = $db->selectField( 'user_newtalk', $field,
1601 array( $field => $id ), __METHOD__
);
1602 return $ok !== false;
1606 * Add or update the new messages flag
1607 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1608 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1609 * @return \bool True if successful, false otherwise
1612 function updateNewtalk( $field, $id ) {
1613 $dbw = wfGetDB( DB_MASTER
);
1614 $dbw->insert( 'user_newtalk',
1615 array( $field => $id ),
1618 if ( $dbw->affectedRows() ) {
1619 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1622 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1628 * Clear the new messages flag for the given user
1629 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1630 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1631 * @return \bool True if successful, false otherwise
1634 function deleteNewtalk( $field, $id ) {
1635 $dbw = wfGetDB( DB_MASTER
);
1636 $dbw->delete( 'user_newtalk',
1637 array( $field => $id ),
1639 if ( $dbw->affectedRows() ) {
1640 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1643 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1649 * Update the 'You have new messages!' status.
1650 * @param $val \bool Whether the user has new messages
1652 function setNewtalk( $val ) {
1653 if( wfReadOnly() ) {
1658 $this->mNewtalk
= $val;
1660 if( $this->isAnon() ) {
1662 $id = $this->getName();
1665 $id = $this->getId();
1670 $changed = $this->updateNewtalk( $field, $id );
1672 $changed = $this->deleteNewtalk( $field, $id );
1675 if( $this->isAnon() ) {
1676 // Anons have a separate memcached space, since
1677 // user records aren't kept for them.
1678 $key = wfMemcKey( 'newtalk', 'ip', $id );
1679 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1682 $this->invalidateCache();
1687 * Generate a current or new-future timestamp to be stored in the
1688 * user_touched field when we update things.
1689 * @return \string Timestamp in TS_MW format
1691 private static function newTouchedTimestamp() {
1692 global $wgClockSkewFudge;
1693 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1697 * Clear user data from memcached.
1698 * Use after applying fun updates to the database; caller's
1699 * responsibility to update user_touched if appropriate.
1701 * Called implicitly from invalidateCache() and saveSettings().
1703 private function clearSharedCache() {
1707 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1712 * Immediately touch the user data cache for this account.
1713 * Updates user_touched field, and removes account data from memcached
1714 * for reload on the next hit.
1716 function invalidateCache() {
1717 if( wfReadOnly() ) {
1722 $this->mTouched
= self
::newTouchedTimestamp();
1724 $dbw = wfGetDB( DB_MASTER
);
1725 $dbw->update( 'user',
1726 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1727 array( 'user_id' => $this->mId
),
1730 $this->clearSharedCache();
1735 * Validate the cache for this account.
1736 * @param $timestamp \string A timestamp in TS_MW format
1738 function validateCache( $timestamp ) {
1740 return ( $timestamp >= $this->mTouched
);
1744 * Get the user touched timestamp
1746 function getTouched() {
1748 return $this->mTouched
;
1752 * Set the password and reset the random token.
1753 * Calls through to authentication plugin if necessary;
1754 * will have no effect if the auth plugin refuses to
1755 * pass the change through or if the legal password
1758 * As a special case, setting the password to null
1759 * wipes it, so the account cannot be logged in until
1760 * a new password is set, for instance via e-mail.
1762 * @param $str \string New password to set
1763 * @throws PasswordError on failure
1765 function setPassword( $str ) {
1768 if( $str !== null ) {
1769 if( !$wgAuth->allowPasswordChange() ) {
1770 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1773 if( $this->isValidPassword( $str ) !== true ) {
1774 global $wgMinimalPasswordLength;
1775 $valid = $this->getPasswordValidity( $str );
1776 throw new PasswordError( wfMsgExt( $valid, array( 'parsemag' ),
1777 $wgMinimalPasswordLength ) );
1781 if( !$wgAuth->setPassword( $this, $str ) ) {
1782 throw new PasswordError( wfMsg( 'externaldberror' ) );
1785 $this->setInternalPassword( $str );
1791 * Set the password and reset the random token unconditionally.
1793 * @param $str \string New password to set
1795 function setInternalPassword( $str ) {
1799 if( $str === null ) {
1800 // Save an invalid hash...
1801 $this->mPassword
= '';
1803 $this->mPassword
= self
::crypt( $str );
1805 $this->mNewpassword
= '';
1806 $this->mNewpassTime
= null;
1810 * Get the user's current token.
1811 * @return \string Token
1813 function getToken() {
1815 return $this->mToken
;
1819 * Set the random token (used for persistent authentication)
1820 * Called from loadDefaults() among other places.
1822 * @param $token \string If specified, set the token to this value
1825 function setToken( $token = false ) {
1826 global $wgSecretKey, $wgProxyKey;
1829 if ( $wgSecretKey ) {
1830 $key = $wgSecretKey;
1831 } elseif ( $wgProxyKey ) {
1836 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1838 $this->mToken
= $token;
1843 * Set the cookie password
1845 * @param $str \string New cookie password
1848 function setCookiePassword( $str ) {
1850 $this->mCookiePassword
= md5( $str );
1854 * Set the password for a password reminder or new account email
1856 * @param $str \string New password to set
1857 * @param $throttle \bool If true, reset the throttle timestamp to the present
1859 function setNewpassword( $str, $throttle = true ) {
1861 $this->mNewpassword
= self
::crypt( $str );
1863 $this->mNewpassTime
= wfTimestampNow();
1868 * Has password reminder email been sent within the last
1869 * $wgPasswordReminderResendTime hours?
1870 * @return \bool True or false
1872 function isPasswordReminderThrottled() {
1873 global $wgPasswordReminderResendTime;
1875 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1878 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1879 return time() < $expiry;
1883 * Get the user's e-mail address
1884 * @return \string User's email address
1886 function getEmail() {
1888 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1889 return $this->mEmail
;
1893 * Get the timestamp of the user's e-mail authentication
1894 * @return \string TS_MW timestamp
1896 function getEmailAuthenticationTimestamp() {
1898 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1899 return $this->mEmailAuthenticated
;
1903 * Set the user's e-mail address
1904 * @param $str \string New e-mail address
1906 function setEmail( $str ) {
1908 $this->mEmail
= $str;
1909 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1913 * Get the user's real name
1914 * @return \string User's real name
1916 function getRealName() {
1918 return $this->mRealName
;
1922 * Set the user's real name
1923 * @param $str \string New real name
1925 function setRealName( $str ) {
1927 $this->mRealName
= $str;
1931 * Get the user's current setting for a given option.
1933 * @param $oname \string The option to check
1934 * @param $defaultOverride \string A default value returned if the option does not exist
1935 * @return \string User's current value for the option
1936 * @see getBoolOption()
1937 * @see getIntOption()
1939 function getOption( $oname, $defaultOverride = null ) {
1940 $this->loadOptions();
1942 if ( is_null( $this->mOptions
) ) {
1943 if($defaultOverride != '') {
1944 return $defaultOverride;
1946 $this->mOptions
= User
::getDefaultOptions();
1949 if ( array_key_exists( $oname, $this->mOptions
) ) {
1950 return $this->mOptions
[$oname];
1952 return $defaultOverride;
1957 * Get the user's current setting for a given option, as a boolean value.
1959 * @param $oname \string The option to check
1960 * @return \bool User's current value for the option
1963 function getBoolOption( $oname ) {
1964 return (bool)$this->getOption( $oname );
1969 * Get the user's current setting for a given option, as a boolean value.
1971 * @param $oname \string The option to check
1972 * @param $defaultOverride \int A default value returned if the option does not exist
1973 * @return \int User's current value for the option
1976 function getIntOption( $oname, $defaultOverride=0 ) {
1977 $val = $this->getOption( $oname );
1979 $val = $defaultOverride;
1981 return intval( $val );
1985 * Set the given option for a user.
1987 * @param $oname \string The option to set
1988 * @param $val \mixed New value to set
1990 function setOption( $oname, $val ) {
1992 $this->loadOptions();
1994 if ( $oname == 'skin' ) {
1995 # Clear cached skin, so the new one displays immediately in Special:Preferences
1996 unset( $this->mSkin
);
1999 // Explicitly NULL values should refer to defaults
2000 global $wgDefaultUserOptions;
2001 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2002 $val = $wgDefaultUserOptions[$oname];
2005 $this->mOptions
[$oname] = $val;
2009 * Reset all options to the site defaults
2011 function resetOptions() {
2012 $this->mOptions
= User
::getDefaultOptions();
2016 * Get the user's preferred date format.
2017 * @return \string User's preferred date format
2019 function getDatePreference() {
2020 // Important migration for old data rows
2021 if ( is_null( $this->mDatePreference
) ) {
2023 $value = $this->getOption( 'date' );
2024 $map = $wgLang->getDatePreferenceMigrationMap();
2025 if ( isset( $map[$value] ) ) {
2026 $value = $map[$value];
2028 $this->mDatePreference
= $value;
2030 return $this->mDatePreference
;
2034 * Get the permissions this user has.
2035 * @return \type{\arrayof{\string}} Array of permission names
2037 function getRights() {
2038 if ( is_null( $this->mRights
) ) {
2039 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2040 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2041 // Force reindexation of rights when a hook has unset one of them
2042 $this->mRights
= array_values( $this->mRights
);
2044 return $this->mRights
;
2048 * Get the list of explicit group memberships this user has.
2049 * The implicit * and user groups are not included.
2050 * @return \type{\arrayof{\string}} Array of internal group names
2052 function getGroups() {
2054 return $this->mGroups
;
2058 * Get the list of implicit group memberships this user has.
2059 * This includes all explicit groups, plus 'user' if logged in,
2060 * '*' for all accounts and autopromoted groups
2061 * @param $recache \bool Whether to avoid the cache
2062 * @return \type{\arrayof{\string}} Array of internal group names
2064 function getEffectiveGroups( $recache = false ) {
2065 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2066 wfProfileIn( __METHOD__
);
2067 $this->mEffectiveGroups
= $this->getGroups();
2068 $this->mEffectiveGroups
[] = '*';
2069 if( $this->getId() ) {
2070 $this->mEffectiveGroups
[] = 'user';
2072 $this->mEffectiveGroups
= array_unique( array_merge(
2073 $this->mEffectiveGroups
,
2074 Autopromote
::getAutopromoteGroups( $this )
2077 # Hook for additional groups
2078 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2080 wfProfileOut( __METHOD__
);
2082 return $this->mEffectiveGroups
;
2086 * Get the user's edit count.
2087 * @return \int User'e edit count
2089 function getEditCount() {
2090 if( $this->getId() ) {
2091 if ( !isset( $this->mEditCount
) ) {
2092 /* Populate the count, if it has not been populated yet */
2093 $this->mEditCount
= User
::edits( $this->mId
);
2095 return $this->mEditCount
;
2103 * Add the user to the given group.
2104 * This takes immediate effect.
2105 * @param $group \string Name of the group to add
2107 function addGroup( $group ) {
2108 $dbw = wfGetDB( DB_MASTER
);
2109 if( $this->getId() ) {
2110 $dbw->insert( 'user_groups',
2112 'ug_user' => $this->getID(),
2113 'ug_group' => $group,
2116 array( 'IGNORE' ) );
2119 $this->loadGroups();
2120 $this->mGroups
[] = $group;
2121 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2123 $this->invalidateCache();
2127 * Remove the user from the given group.
2128 * This takes immediate effect.
2129 * @param $group \string Name of the group to remove
2131 function removeGroup( $group ) {
2133 $dbw = wfGetDB( DB_MASTER
);
2134 $dbw->delete( 'user_groups',
2136 'ug_user' => $this->getID(),
2137 'ug_group' => $group,
2139 'User::removeGroup' );
2141 $this->loadGroups();
2142 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2143 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2145 $this->invalidateCache();
2149 * Get whether the user is logged in
2150 * @return \bool True or false
2152 function isLoggedIn() {
2153 return $this->getID() != 0;
2157 * Get whether the user is anonymous
2158 * @return \bool True or false
2161 return !$this->isLoggedIn();
2165 * Get whether the user is a bot
2166 * @return \bool True or false
2170 wfDeprecated( __METHOD__
);
2171 return $this->isAllowed( 'bot' );
2175 * Check if user is allowed to access a feature / make an action
2176 * @param $action \string action to be checked
2177 * @return \bool True if action is allowed, else false
2179 function isAllowed( $action = '' ) {
2180 if ( $action === '' )
2181 return true; // In the spirit of DWIM
2182 # Patrolling may not be enabled
2183 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2184 global $wgUseRCPatrol, $wgUseNPPatrol;
2185 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2188 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2189 # by misconfiguration: 0 == 'foo'
2190 return in_array( $action, $this->getRights(), true );
2194 * Check whether to enable recent changes patrol features for this user
2195 * @return \bool True or false
2197 public function useRCPatrol() {
2198 global $wgUseRCPatrol;
2199 return( $wgUseRCPatrol && ( $this->isAllowed( 'patrol' ) ||
$this->isAllowed( 'patrolmarks' ) ) );
2203 * Check whether to enable new pages patrol features for this user
2204 * @return \bool True or false
2206 public function useNPPatrol() {
2207 global $wgUseRCPatrol, $wgUseNPPatrol;
2208 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowed( 'patrol' ) ||
$this->isAllowed( 'patrolmarks' ) ) );
2212 * Get the current skin, loading it if required, and setting a title
2213 * @param $t Title: the title to use in the skin
2214 * @return Skin The current skin
2215 * @todo FIXME : need to check the old failback system [AV]
2217 function &getSkin( $t = null ) {
2218 if ( !isset( $this->mSkin
) ) {
2219 wfProfileIn( __METHOD__
);
2221 global $wgHiddenPrefs;
2222 if( !in_array( 'skin', $wgHiddenPrefs ) ) {
2225 $userSkin = $this->getOption( 'skin' );
2226 $userSkin = $wgRequest->getVal( 'useskin', $userSkin );
2228 # if we're not allowing users to override, then use the default
2229 global $wgDefaultSkin;
2230 $userSkin = $wgDefaultSkin;
2233 $this->mSkin
=& Skin
::newFromKey( $userSkin );
2234 wfProfileOut( __METHOD__
);
2236 if( $t ||
!$this->mSkin
->getTitle() ) {
2239 $t = $wgOut->getTitle();
2241 $this->mSkin
->setTitle( $t );
2243 return $this->mSkin
;
2247 * Check the watched status of an article.
2248 * @param $title \type{Title} Title of the article to look at
2249 * @return \bool True if article is watched
2251 function isWatched( $title ) {
2252 $wl = WatchedItem
::fromUserTitle( $this, $title );
2253 return $wl->isWatched();
2258 * @param $title \type{Title} Title of the article to look at
2260 function addWatch( $title ) {
2261 $wl = WatchedItem
::fromUserTitle( $this, $title );
2263 $this->invalidateCache();
2267 * Stop watching an article.
2268 * @param $title \type{Title} Title of the article to look at
2270 function removeWatch( $title ) {
2271 $wl = WatchedItem
::fromUserTitle( $this, $title );
2273 $this->invalidateCache();
2277 * Clear the user's notification timestamp for the given title.
2278 * If e-notif e-mails are on, they will receive notification mails on
2279 * the next change of the page if it's watched etc.
2280 * @param $title \type{Title} Title of the article to look at
2282 function clearNotification( &$title ) {
2283 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2285 # Do nothing if the database is locked to writes
2286 if( wfReadOnly() ) {
2290 if( $title->getNamespace() == NS_USER_TALK
&&
2291 $title->getText() == $this->getName() ) {
2292 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2294 $this->setNewtalk( false );
2297 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2301 if( $this->isAnon() ) {
2302 // Nothing else to do...
2306 // Only update the timestamp if the page is being watched.
2307 // The query to find out if it is watched is cached both in memcached and per-invocation,
2308 // and when it does have to be executed, it can be on a slave
2309 // If this is the user's newtalk page, we always update the timestamp
2310 if( $title->getNamespace() == NS_USER_TALK
&&
2311 $title->getText() == $wgUser->getName() )
2314 } elseif ( $this->getId() == $wgUser->getId() ) {
2315 $watched = $title->userIsWatching();
2320 // If the page is watched by the user (or may be watched), update the timestamp on any
2321 // any matching rows
2323 $dbw = wfGetDB( DB_MASTER
);
2324 $dbw->update( 'watchlist',
2326 'wl_notificationtimestamp' => NULL
2327 ), array( /* WHERE */
2328 'wl_title' => $title->getDBkey(),
2329 'wl_namespace' => $title->getNamespace(),
2330 'wl_user' => $this->getID()
2337 * Resets all of the given user's page-change notification timestamps.
2338 * If e-notif e-mails are on, they will receive notification mails on
2339 * the next change of any watched page.
2341 * @param $currentUser \int User ID
2343 function clearAllNotifications( $currentUser ) {
2344 global $wgUseEnotif, $wgShowUpdatedMarker;
2345 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2346 $this->setNewtalk( false );
2349 if( $currentUser != 0 ) {
2350 $dbw = wfGetDB( DB_MASTER
);
2351 $dbw->update( 'watchlist',
2353 'wl_notificationtimestamp' => NULL
2354 ), array( /* WHERE */
2355 'wl_user' => $currentUser
2358 # We also need to clear here the "you have new message" notification for the own user_talk page
2359 # This is cleared one page view later in Article::viewUpdates();
2364 * Set this user's options from an encoded string
2365 * @param $str \string Encoded options to import
2368 function decodeOptions( $str ) {
2372 $this->mOptionsLoaded
= true;
2373 $this->mOptionOverrides
= array();
2375 $this->mOptions
= array();
2376 $a = explode( "\n", $str );
2377 foreach ( $a as $s ) {
2379 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2380 $this->mOptions
[$m[1]] = $m[2];
2381 $this->mOptionOverrides
[$m[1]] = $m[2];
2387 * Set a cookie on the user's client. Wrapper for
2388 * WebResponse::setCookie
2389 * @param $name \string Name of the cookie to set
2390 * @param $value \string Value to set
2391 * @param $exp \int Expiration time, as a UNIX time value;
2392 * if 0 or not specified, use the default $wgCookieExpiration
2394 protected function setCookie( $name, $value, $exp = 0 ) {
2396 $wgRequest->response()->setcookie( $name, $value, $exp );
2400 * Clear a cookie on the user's client
2401 * @param $name \string Name of the cookie to clear
2403 protected function clearCookie( $name ) {
2404 $this->setCookie( $name, '', time() - 86400 );
2408 * Set the default cookies for this session on the user's client.
2410 function setCookies() {
2412 if ( 0 == $this->mId
) return;
2414 'wsUserID' => $this->mId
,
2415 'wsToken' => $this->mToken
,
2416 'wsUserName' => $this->getName()
2419 'UserID' => $this->mId
,
2420 'UserName' => $this->getName(),
2422 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2423 $cookies['Token'] = $this->mToken
;
2425 $cookies['Token'] = false;
2428 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2429 #check for null, since the hook could cause a null value
2430 if ( !is_null( $session ) && isset( $_SESSION ) ){
2431 $_SESSION = $session +
$_SESSION;
2433 foreach ( $cookies as $name => $value ) {
2434 if ( $value === false ) {
2435 $this->clearCookie( $name );
2437 $this->setCookie( $name, $value );
2443 * Log this user out.
2446 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2452 * Clear the user's cookies and session, and reset the instance cache.
2456 function doLogout() {
2457 $this->clearInstanceCache( 'defaults' );
2459 $_SESSION['wsUserID'] = 0;
2461 $this->clearCookie( 'UserID' );
2462 $this->clearCookie( 'Token' );
2464 # Remember when user logged out, to prevent seeing cached pages
2465 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2469 * Save this user's settings into the database.
2470 * @todo Only rarely do all these fields need to be set!
2472 function saveSettings() {
2474 if ( wfReadOnly() ) { return; }
2475 if ( 0 == $this->mId
) { return; }
2477 $this->mTouched
= self
::newTouchedTimestamp();
2479 $dbw = wfGetDB( DB_MASTER
);
2480 $dbw->update( 'user',
2482 'user_name' => $this->mName
,
2483 'user_password' => $this->mPassword
,
2484 'user_newpassword' => $this->mNewpassword
,
2485 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2486 'user_real_name' => $this->mRealName
,
2487 'user_email' => $this->mEmail
,
2488 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2489 'user_options' => '',
2490 'user_touched' => $dbw->timestamp( $this->mTouched
),
2491 'user_token' => $this->mToken
,
2492 'user_email_token' => $this->mEmailToken
,
2493 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2494 ), array( /* WHERE */
2495 'user_id' => $this->mId
2499 $this->saveOptions();
2501 wfRunHooks( 'UserSaveSettings', array( $this ) );
2502 $this->clearSharedCache();
2503 $this->getUserPage()->invalidateCache();
2507 * If only this user's username is known, and it exists, return the user ID.
2509 function idForName() {
2510 $s = trim( $this->getName() );
2511 if ( $s === '' ) return 0;
2513 $dbr = wfGetDB( DB_SLAVE
);
2514 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2515 if ( $id === false ) {
2522 * Add a user to the database, return the user object
2524 * @param $name \string Username to add
2525 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2526 * - password The user's password. Password logins will be disabled if this is omitted.
2527 * - newpassword A temporary password mailed to the user
2528 * - email The user's email address
2529 * - email_authenticated The email authentication timestamp
2530 * - real_name The user's real name
2531 * - options An associative array of non-default options
2532 * - token Random authentication token. Do not set.
2533 * - registration Registration timestamp. Do not set.
2535 * @return \type{User} A new User object, or null if the username already exists
2537 static function createNew( $name, $params = array() ) {
2540 if ( isset( $params['options'] ) ) {
2541 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
2542 unset( $params['options'] );
2544 $dbw = wfGetDB( DB_MASTER
);
2545 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2547 'user_id' => $seqVal,
2548 'user_name' => $name,
2549 'user_password' => $user->mPassword
,
2550 'user_newpassword' => $user->mNewpassword
,
2551 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2552 'user_email' => $user->mEmail
,
2553 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2554 'user_real_name' => $user->mRealName
,
2555 'user_options' => '',
2556 'user_token' => $user->mToken
,
2557 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2558 'user_editcount' => 0,
2560 foreach ( $params as $name => $value ) {
2561 $fields["user_$name"] = $value;
2563 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2564 if ( $dbw->affectedRows() ) {
2565 $newUser = User
::newFromId( $dbw->insertId() );
2573 * Add this existing user object to the database
2575 function addToDatabase() {
2577 $dbw = wfGetDB( DB_MASTER
);
2578 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2579 $dbw->insert( 'user',
2581 'user_id' => $seqVal,
2582 'user_name' => $this->mName
,
2583 'user_password' => $this->mPassword
,
2584 'user_newpassword' => $this->mNewpassword
,
2585 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2586 'user_email' => $this->mEmail
,
2587 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2588 'user_real_name' => $this->mRealName
,
2589 'user_options' => '',
2590 'user_token' => $this->mToken
,
2591 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2592 'user_editcount' => 0,
2595 $this->mId
= $dbw->insertId();
2597 // Clear instance cache other than user table data, which is already accurate
2598 $this->clearInstanceCache();
2600 $this->saveOptions();
2604 * If this (non-anonymous) user is blocked, block any IP address
2605 * they've successfully logged in from.
2607 function spreadBlock() {
2608 wfDebug( __METHOD__
. "()\n" );
2610 if ( $this->mId
== 0 ) {
2614 $userblock = Block
::newFromDB( '', $this->mId
);
2615 if ( !$userblock ) {
2619 $userblock->doAutoblock( wfGetIP() );
2623 * Generate a string which will be different for any combination of
2624 * user options which would produce different parser output.
2625 * This will be used as part of the hash key for the parser cache,
2626 * so users with the same options can share the same cached data
2629 * Extensions which require it should install 'PageRenderingHash' hook,
2630 * which will give them a chance to modify this key based on their own
2633 * @return \string Page rendering hash
2635 function getPageRenderingHash() {
2636 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2638 return $this->mHash
;
2641 // stubthreshold is only included below for completeness,
2642 // it will always be 0 when this function is called by parsercache.
2644 $confstr = $this->getOption( 'math' );
2645 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2646 if ( $wgUseDynamicDates ) {
2647 $confstr .= '!' . $this->getDatePreference();
2649 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
2650 $confstr .= '!' . $wgLang->getCode();
2651 $confstr .= '!' . $this->getOption( 'thumbsize' );
2652 // add in language specific options, if any
2653 $extra = $wgContLang->getExtraHashOptions();
2656 $confstr .= $wgRenderHashAppend;
2658 // Give a chance for extensions to modify the hash, if they have
2659 // extra options or other effects on the parser cache.
2660 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2662 // Make it a valid memcached key fragment
2663 $confstr = str_replace( ' ', '_', $confstr );
2664 $this->mHash
= $confstr;
2669 * Get whether the user is explicitly blocked from account creation.
2670 * @return \bool True if blocked
2672 function isBlockedFromCreateAccount() {
2673 $this->getBlockedStatus();
2674 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2678 * Get whether the user is blocked from using Special:Emailuser.
2679 * @return \bool True if blocked
2681 function isBlockedFromEmailuser() {
2682 $this->getBlockedStatus();
2683 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2687 * Get whether the user is allowed to create an account.
2688 * @return \bool True if allowed
2690 function isAllowedToCreateAccount() {
2691 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2697 function setLoaded( $loaded ) {
2698 wfDeprecated( __METHOD__
);
2702 * Get this user's personal page title.
2704 * @return \type{Title} User's personal page title
2706 function getUserPage() {
2707 return Title
::makeTitle( NS_USER
, $this->getName() );
2711 * Get this user's talk page title.
2713 * @return \type{Title} User's talk page title
2715 function getTalkPage() {
2716 $title = $this->getUserPage();
2717 return $title->getTalkPage();
2721 * Get the maximum valid user ID.
2722 * @return \int User ID
2725 function getMaxID() {
2726 static $res; // cache
2728 if ( isset( $res ) )
2731 $dbr = wfGetDB( DB_SLAVE
);
2732 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2737 * Determine whether the user is a newbie. Newbies are either
2738 * anonymous IPs, or the most recently created accounts.
2739 * @return \bool True if the user is a newbie
2741 function isNewbie() {
2742 return !$this->isAllowed( 'autoconfirmed' );
2746 * Check to see if the given clear-text password is one of the accepted passwords
2747 * @param $password \string user password.
2748 * @return \bool True if the given password is correct, otherwise False.
2750 function checkPassword( $password ) {
2754 // Even though we stop people from creating passwords that
2755 // are shorter than this, doesn't mean people wont be able
2756 // to. Certain authentication plugins do NOT want to save
2757 // domain passwords in a mysql database, so we should
2758 // check this (incase $wgAuth->strict() is false).
2759 if( !$this->isValidPassword( $password ) ) {
2763 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2765 } elseif( $wgAuth->strict() ) {
2766 /* Auth plugin doesn't allow local authentication */
2768 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2769 /* Auth plugin doesn't allow local authentication for this user name */
2772 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2774 } elseif ( function_exists( 'iconv' ) ) {
2775 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2776 # Check for this with iconv
2777 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2778 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2786 * Check if the given clear-text password matches the temporary password
2787 * sent by e-mail for password reset operations.
2788 * @return \bool True if matches, false otherwise
2790 function checkTemporaryPassword( $plaintext ) {
2791 global $wgNewPasswordExpiry;
2792 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
2794 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
2795 return ( time() < $expiry );
2802 * Initialize (if necessary) and return a session token value
2803 * which can be used in edit forms to show that the user's
2804 * login credentials aren't being hijacked with a foreign form
2807 * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2808 * @return \string The new edit token
2810 function editToken( $salt = '' ) {
2811 if ( $this->isAnon() ) {
2812 return EDIT_TOKEN_SUFFIX
;
2814 if( !isset( $_SESSION['wsEditToken'] ) ) {
2815 $token = $this->generateToken();
2816 $_SESSION['wsEditToken'] = $token;
2818 $token = $_SESSION['wsEditToken'];
2820 if( is_array( $salt ) ) {
2821 $salt = implode( '|', $salt );
2823 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2828 * Generate a looking random token for various uses.
2830 * @param $salt \string Optional salt value
2831 * @return \string The new random token
2833 function generateToken( $salt = '' ) {
2834 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2835 return md5( $token . $salt );
2839 * Check given value against the token value stored in the session.
2840 * A match should confirm that the form was submitted from the
2841 * user's own login session, not a form submission from a third-party
2844 * @param $val \string Input value to compare
2845 * @param $salt \string Optional function-specific data for hashing
2846 * @return \bool Whether the token matches
2848 function matchEditToken( $val, $salt = '' ) {
2849 $sessionToken = $this->editToken( $salt );
2850 if ( $val != $sessionToken ) {
2851 wfDebug( "User::matchEditToken: broken session data\n" );
2853 return $val == $sessionToken;
2857 * Check given value against the token value stored in the session,
2858 * ignoring the suffix.
2860 * @param $val \string Input value to compare
2861 * @param $salt \string Optional function-specific data for hashing
2862 * @return \bool Whether the token matches
2864 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2865 $sessionToken = $this->editToken( $salt );
2866 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2870 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2871 * mail to the user's given address.
2873 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure.
2875 function sendConfirmationMail() {
2877 $expiration = null; // gets passed-by-ref and defined in next line.
2878 $token = $this->confirmationToken( $expiration );
2879 $url = $this->confirmationTokenUrl( $token );
2880 $invalidateURL = $this->invalidationTokenUrl( $token );
2881 $this->saveSettings();
2883 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2884 wfMsg( 'confirmemail_body',
2888 $wgLang->timeanddate( $expiration, false ),
2890 $wgLang->date( $expiration, false ),
2891 $wgLang->time( $expiration, false ) ) );
2895 * Send an e-mail to this user's account. Does not check for
2896 * confirmed status or validity.
2898 * @param $subject \string Message subject
2899 * @param $body \string Message body
2900 * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2901 * @param $replyto \string Reply-To address
2902 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure
2904 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2905 if( is_null( $from ) ) {
2906 global $wgPasswordSender;
2907 $from = $wgPasswordSender;
2910 $to = new MailAddress( $this );
2911 $sender = new MailAddress( $from );
2912 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2916 * Generate, store, and return a new e-mail confirmation code.
2917 * A hash (unsalted, since it's used as a key) is stored.
2919 * @note Call saveSettings() after calling this function to commit
2920 * this change to the database.
2922 * @param[out] &$expiration \mixed Accepts the expiration time
2923 * @return \string New token
2926 function confirmationToken( &$expiration ) {
2928 $expires = $now +
7 * 24 * 60 * 60;
2929 $expiration = wfTimestamp( TS_MW
, $expires );
2930 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2931 $hash = md5( $token );
2933 $this->mEmailToken
= $hash;
2934 $this->mEmailTokenExpires
= $expiration;
2939 * Return a URL the user can use to confirm their email address.
2940 * @param $token \string Accepts the email confirmation token
2941 * @return \string New token URL
2944 function confirmationTokenUrl( $token ) {
2945 return $this->getTokenUrl( 'ConfirmEmail', $token );
2949 * Return a URL the user can use to invalidate their email address.
2950 * @param $token \string Accepts the email confirmation token
2951 * @return \string New token URL
2954 function invalidationTokenUrl( $token ) {
2955 return $this->getTokenUrl( 'Invalidateemail', $token );
2959 * Internal function to format the e-mail validation/invalidation URLs.
2960 * This uses $wgArticlePath directly as a quickie hack to use the
2961 * hardcoded English names of the Special: pages, for ASCII safety.
2963 * @note Since these URLs get dropped directly into emails, using the
2964 * short English names avoids insanely long URL-encoded links, which
2965 * also sometimes can get corrupted in some browsers/mailers
2966 * (bug 6957 with Gmail and Internet Explorer).
2968 * @param $page \string Special page
2969 * @param $token \string Token
2970 * @return \string Formatted URL
2972 protected function getTokenUrl( $page, $token ) {
2973 global $wgArticlePath;
2977 "Special:$page/$token",
2982 * Mark the e-mail address confirmed.
2984 * @note Call saveSettings() after calling this function to commit the change.
2986 function confirmEmail() {
2987 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2988 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
2993 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2994 * address if it was already confirmed.
2996 * @note Call saveSettings() after calling this function to commit the change.
2998 function invalidateEmail() {
3000 $this->mEmailToken
= null;
3001 $this->mEmailTokenExpires
= null;
3002 $this->setEmailAuthenticationTimestamp( null );
3003 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3008 * Set the e-mail authentication timestamp.
3009 * @param $timestamp \string TS_MW timestamp
3011 function setEmailAuthenticationTimestamp( $timestamp ) {
3013 $this->mEmailAuthenticated
= $timestamp;
3014 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3018 * Is this user allowed to send e-mails within limits of current
3019 * site configuration?
3020 * @return \bool True if allowed
3022 function canSendEmail() {
3023 global $wgEnableEmail, $wgEnableUserEmail, $wgUser;
3024 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$wgUser->isAllowed( 'sendemail' ) ) {
3027 $canSend = $this->isEmailConfirmed();
3028 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3033 * Is this user allowed to receive e-mails within limits of current
3034 * site configuration?
3035 * @return \bool True if allowed
3037 function canReceiveEmail() {
3038 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3042 * Is this user's e-mail address valid-looking and confirmed within
3043 * limits of the current site configuration?
3045 * @note If $wgEmailAuthentication is on, this may require the user to have
3046 * confirmed their address by returning a code or using a password
3047 * sent to the address from the wiki.
3049 * @return \bool True if confirmed
3051 function isEmailConfirmed() {
3052 global $wgEmailAuthentication;
3055 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3056 if( $this->isAnon() )
3058 if( !self
::isValidEmailAddr( $this->mEmail
) )
3060 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3069 * Check whether there is an outstanding request for e-mail confirmation.
3070 * @return \bool True if pending
3072 function isEmailConfirmationPending() {
3073 global $wgEmailAuthentication;
3074 return $wgEmailAuthentication &&
3075 !$this->isEmailConfirmed() &&
3076 $this->mEmailToken
&&
3077 $this->mEmailTokenExpires
> wfTimestamp();
3081 * Get the timestamp of account creation.
3083 * @return \types{\string,\bool} string Timestamp of account creation, or false for
3084 * non-existent/anonymous user accounts.
3086 public function getRegistration() {
3087 return $this->getId() > 0
3088 ?
$this->mRegistration
3093 * Get the timestamp of the first edit
3095 * @return \types{\string,\bool} string Timestamp of first edit, or false for
3096 * non-existent/anonymous user accounts.
3098 public function getFirstEditTimestamp() {
3099 if( $this->getId() == 0 ) return false; // anons
3100 $dbr = wfGetDB( DB_SLAVE
);
3101 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3102 array( 'rev_user' => $this->getId() ),
3104 array( 'ORDER BY' => 'rev_timestamp ASC' )
3106 if( !$time ) return false; // no edits
3107 return wfTimestamp( TS_MW
, $time );
3111 * Get the permissions associated with a given list of groups
3113 * @param $groups \type{\arrayof{\string}} List of internal group names
3114 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3116 static function getGroupPermissions( $groups ) {
3117 global $wgGroupPermissions, $wgRevokePermissions;
3119 // grant every granted permission first
3120 foreach( $groups as $group ) {
3121 if( isset( $wgGroupPermissions[$group] ) ) {
3122 $rights = array_merge( $rights,
3123 // array_filter removes empty items
3124 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3127 // now revoke the revoked permissions
3128 foreach( $groups as $group ) {
3129 if( isset( $wgRevokePermissions[$group] ) ) {
3130 $rights = array_diff( $rights,
3131 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3134 return array_unique( $rights );
3138 * Get all the groups who have a given permission
3140 * @param $role \string Role to check
3141 * @return \type{\arrayof{\string}} List of internal group names with the given permission
3143 static function getGroupsWithPermission( $role ) {
3144 global $wgGroupPermissions;
3145 $allowedGroups = array();
3146 foreach ( $wgGroupPermissions as $group => $rights ) {
3147 if ( isset( $rights[$role] ) && $rights[$role] ) {
3148 $allowedGroups[] = $group;
3151 return $allowedGroups;
3155 * Get the localized descriptive name for a group, if it exists
3157 * @param $group \string Internal group name
3158 * @return \string Localized descriptive group name
3160 static function getGroupName( $group ) {
3161 global $wgMessageCache;
3162 $wgMessageCache->loadAllMessages();
3163 $key = "group-$group";
3164 $name = wfMsg( $key );
3165 return $name == '' ||
wfEmptyMsg( $key, $name )
3171 * Get the localized descriptive name for a member of a group, if it exists
3173 * @param $group \string Internal group name
3174 * @return \string Localized name for group member
3176 static function getGroupMember( $group ) {
3177 global $wgMessageCache;
3178 $wgMessageCache->loadAllMessages();
3179 $key = "group-$group-member";
3180 $name = wfMsg( $key );
3181 return $name == '' ||
wfEmptyMsg( $key, $name )
3187 * Return the set of defined explicit groups.
3188 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3189 * are not included, as they are defined automatically, not in the database.
3190 * @return \type{\arrayof{\string}} Array of internal group names
3192 static function getAllGroups() {
3193 global $wgGroupPermissions, $wgRevokePermissions;
3195 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3196 self
::getImplicitGroups()
3201 * Get a list of all available permissions.
3202 * @return \type{\arrayof{\string}} Array of permission names
3204 static function getAllRights() {
3205 if ( self
::$mAllRights === false ) {
3206 global $wgAvailableRights;
3207 if ( count( $wgAvailableRights ) ) {
3208 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3210 self
::$mAllRights = self
::$mCoreRights;
3212 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3214 return self
::$mAllRights;
3218 * Get a list of implicit groups
3219 * @return \type{\arrayof{\string}} Array of internal group names
3221 public static function getImplicitGroups() {
3222 global $wgImplicitGroups;
3223 $groups = $wgImplicitGroups;
3224 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3229 * Get the title of a page describing a particular group
3231 * @param $group \string Internal group name
3232 * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3234 static function getGroupPage( $group ) {
3235 global $wgMessageCache;
3236 $wgMessageCache->loadAllMessages();
3237 $page = wfMsgForContent( 'grouppage-' . $group );
3238 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3239 $title = Title
::newFromText( $page );
3240 if( is_object( $title ) )
3247 * Create a link to the group in HTML, if available;
3248 * else return the group name.
3250 * @param $group \string Internal name of the group
3251 * @param $text \string The text of the link
3252 * @return \string HTML link to the group
3254 static function makeGroupLinkHTML( $group, $text = '' ) {
3256 $text = self
::getGroupName( $group );
3258 $title = self
::getGroupPage( $group );
3261 $sk = $wgUser->getSkin();
3262 return $sk->link( $title, htmlspecialchars( $text ) );
3269 * Create a link to the group in Wikitext, if available;
3270 * else return the group name.
3272 * @param $group \string Internal name of the group
3273 * @param $text \string The text of the link
3274 * @return \string Wikilink to the group
3276 static function makeGroupLinkWiki( $group, $text = '' ) {
3278 $text = self
::getGroupName( $group );
3280 $title = self
::getGroupPage( $group );
3282 $page = $title->getPrefixedText();
3283 return "[[$page|$text]]";
3290 * Returns an array of the groups that a particular group can add/remove.
3292 * @param $group String: the group to check for whether it can add/remove
3293 * @return Array array( 'add' => array( addablegroups ),
3294 * 'remove' => array( removablegroups ),
3295 * 'add-self' => array( addablegroups to self),
3296 * 'remove-self' => array( removable groups from self) )
3298 static function changeableByGroup( $group ) {
3299 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3301 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3302 if( empty( $wgAddGroups[$group] ) ) {
3303 // Don't add anything to $groups
3304 } elseif( $wgAddGroups[$group] === true ) {
3305 // You get everything
3306 $groups['add'] = self
::getAllGroups();
3307 } elseif( is_array( $wgAddGroups[$group] ) ) {
3308 $groups['add'] = $wgAddGroups[$group];
3311 // Same thing for remove
3312 if( empty( $wgRemoveGroups[$group] ) ) {
3313 } elseif( $wgRemoveGroups[$group] === true ) {
3314 $groups['remove'] = self
::getAllGroups();
3315 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3316 $groups['remove'] = $wgRemoveGroups[$group];
3319 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3320 if( empty( $wgGroupsAddToSelf['user']) ||
$wgGroupsAddToSelf['user'] !== true ) {
3321 foreach( $wgGroupsAddToSelf as $key => $value ) {
3322 if( is_int( $key ) ) {
3323 $wgGroupsAddToSelf['user'][] = $value;
3328 if( empty( $wgGroupsRemoveFromSelf['user']) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
3329 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3330 if( is_int( $key ) ) {
3331 $wgGroupsRemoveFromSelf['user'][] = $value;
3336 // Now figure out what groups the user can add to him/herself
3337 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3338 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3339 // No idea WHY this would be used, but it's there
3340 $groups['add-self'] = User
::getAllGroups();
3341 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3342 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3345 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3346 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3347 $groups['remove-self'] = User
::getAllGroups();
3348 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3349 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3356 * Returns an array of groups that this user can add and remove
3357 * @return Array array( 'add' => array( addablegroups ),
3358 * 'remove' => array( removablegroups ),
3359 * 'add-self' => array( addablegroups to self),
3360 * 'remove-self' => array( removable groups from self) )
3362 function changeableGroups() {
3363 if( $this->isAllowed( 'userrights' ) ) {
3364 // This group gives the right to modify everything (reverse-
3365 // compatibility with old "userrights lets you change
3367 // Using array_merge to make the groups reindexed
3368 $all = array_merge( User
::getAllGroups() );
3372 'add-self' => array(),
3373 'remove-self' => array()
3377 // Okay, it's not so simple, we will have to go through the arrays
3380 'remove' => array(),
3381 'add-self' => array(),
3382 'remove-self' => array()
3384 $addergroups = $this->getEffectiveGroups();
3386 foreach( $addergroups as $addergroup ) {
3387 $groups = array_merge_recursive(
3388 $groups, $this->changeableByGroup( $addergroup )
3390 $groups['add'] = array_unique( $groups['add'] );
3391 $groups['remove'] = array_unique( $groups['remove'] );
3392 $groups['add-self'] = array_unique( $groups['add-self'] );
3393 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3399 * Increment the user's edit-count field.
3400 * Will have no effect for anonymous users.
3402 function incEditCount() {
3403 if( !$this->isAnon() ) {
3404 $dbw = wfGetDB( DB_MASTER
);
3405 $dbw->update( 'user',
3406 array( 'user_editcount=user_editcount+1' ),
3407 array( 'user_id' => $this->getId() ),
3410 // Lazy initialization check...
3411 if( $dbw->affectedRows() == 0 ) {
3412 // Pull from a slave to be less cruel to servers
3413 // Accuracy isn't the point anyway here
3414 $dbr = wfGetDB( DB_SLAVE
);
3415 $count = $dbr->selectField( 'revision',
3417 array( 'rev_user' => $this->getId() ),
3420 // Now here's a goddamn hack...
3421 if( $dbr !== $dbw ) {
3422 // If we actually have a slave server, the count is
3423 // at least one behind because the current transaction
3424 // has not been committed and replicated.
3427 // But if DB_SLAVE is selecting the master, then the
3428 // count we just read includes the revision that was
3429 // just added in the working transaction.
3432 $dbw->update( 'user',
3433 array( 'user_editcount' => $count ),
3434 array( 'user_id' => $this->getId() ),
3438 // edit count in user cache too
3439 $this->invalidateCache();
3443 * Get the description of a given right
3445 * @param $right \string Right to query
3446 * @return \string Localized description of the right
3448 static function getRightDescription( $right ) {
3449 global $wgMessageCache;
3450 $wgMessageCache->loadAllMessages();
3451 $key = "right-$right";
3452 $name = wfMsg( $key );
3453 return $name == '' ||
wfEmptyMsg( $key, $name )
3459 * Make an old-style password hash
3461 * @param $password \string Plain-text password
3462 * @param $userId \string User ID
3463 * @return \string Password hash
3465 static function oldCrypt( $password, $userId ) {
3466 global $wgPasswordSalt;
3467 if ( $wgPasswordSalt ) {
3468 return md5( $userId . '-' . md5( $password ) );
3470 return md5( $password );
3475 * Make a new-style password hash
3477 * @param $password \string Plain-text password
3478 * @param $salt \string Optional salt, may be random or the user ID.
3479 * If unspecified or false, will generate one automatically
3480 * @return \string Password hash
3482 static function crypt( $password, $salt = false ) {
3483 global $wgPasswordSalt;
3486 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3490 if( $wgPasswordSalt ) {
3491 if ( $salt === false ) {
3492 $salt = substr( wfGenerateToken(), 0, 8 );
3494 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3496 return ':A:' . md5( $password );
3501 * Compare a password hash with a plain-text password. Requires the user
3502 * ID if there's a chance that the hash is an old-style hash.
3504 * @param $hash \string Password hash
3505 * @param $password \string Plain-text password to compare
3506 * @param $userId \string User ID for old-style password salt
3509 static function comparePasswords( $hash, $password, $userId = false ) {
3511 $type = substr( $hash, 0, 3 );
3514 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3518 if ( $type == ':A:' ) {
3520 return md5( $password ) === substr( $hash, 3 );
3521 } elseif ( $type == ':B:' ) {
3523 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3524 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3527 return self
::oldCrypt( $password, $userId ) === $hash;
3532 * Add a newuser log entry for this user
3533 * @param $byEmail Boolean: account made by email?
3535 public function addNewUserLogEntry( $byEmail = false ) {
3536 global $wgUser, $wgContLang, $wgNewUserLog;
3537 if( empty( $wgNewUserLog ) ) {
3538 return true; // disabled
3540 $talk = $wgContLang->getFormattedNsText( NS_TALK
);
3541 if( $this->getName() == $wgUser->getName() ) {
3545 $action = 'create2';
3547 ?
wfMsgForContent( 'newuserlog-byemail' )
3550 $log = new LogPage( 'newusers' );
3553 $this->getUserPage(),
3555 array( $this->getId() )
3561 * Add an autocreate newuser log entry for this user
3562 * Used by things like CentralAuth and perhaps other authplugins.
3564 public function addNewUserLogEntryAutoCreate() {
3565 global $wgNewUserLog;
3566 if( empty( $wgNewUserLog ) ) {
3567 return true; // disabled
3569 $log = new LogPage( 'newusers', false );
3570 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3574 protected function loadOptions() {
3576 if ( $this->mOptionsLoaded ||
!$this->getId() )
3579 $this->mOptions
= self
::getDefaultOptions();
3581 // Maybe load from the object
3582 if ( !is_null( $this->mOptionOverrides
) ) {
3583 wfDebug( "Loading options for user " . $this->getId() . " from override cache.\n" );
3584 foreach( $this->mOptionOverrides
as $key => $value ) {
3585 $this->mOptions
[$key] = $value;
3588 wfDebug( "Loading options for user " . $this->getId() . " from database.\n" );
3589 // Load from database
3590 $dbr = wfGetDB( DB_SLAVE
);
3592 $res = $dbr->select(
3595 array( 'up_user' => $this->getId() ),
3599 while( $row = $dbr->fetchObject( $res ) ) {
3600 $this->mOptionOverrides
[$row->up_property
] = $row->up_value
;
3601 $this->mOptions
[$row->up_property
] = $row->up_value
;
3605 $this->mOptionsLoaded
= true;
3607 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
3610 protected function saveOptions() {
3611 global $wgAllowPrefChange;
3613 $extuser = ExternalUser
::newFromUser( $this );
3615 $this->loadOptions();
3616 $dbw = wfGetDB( DB_MASTER
);
3618 $insert_rows = array();
3620 $saveOptions = $this->mOptions
;
3622 // Allow hooks to abort, for instance to save to a global profile.
3623 // Reset options to default state before saving.
3624 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3627 foreach( $saveOptions as $key => $value ) {
3628 # Don't bother storing default values
3629 if ( ( is_null( self
::getDefaultOption( $key ) ) &&
3630 !( $value === false ||
is_null($value) ) ) ||
3631 $value != self
::getDefaultOption( $key ) ) {
3632 $insert_rows[] = array(
3633 'up_user' => $this->getId(),
3634 'up_property' => $key,
3635 'up_value' => $value,
3638 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3639 switch ( $wgAllowPrefChange[$key] ) {
3645 $extuser->setPref( $key, $value );
3651 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__
);
3652 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
);
3657 * Provide an array of HTML 5 attributes to put on an input element
3658 * intended for the user to enter a new password. This may include
3659 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3661 * Do *not* use this when asking the user to enter his current password!
3662 * Regardless of configuration, users may have invalid passwords for whatever
3663 * reason (e.g., they were set before requirements were tightened up).
3664 * Only use it when asking for a new password, like on account creation or
3667 * Obviously, you still need to do server-side checking.
3669 * @return array Array of HTML attributes suitable for feeding to
3670 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3671 * That will potentially output invalid XHTML 1.0 Transitional, and will
3672 * get confused by the boolean attribute syntax used.)
3674 public static function passwordChangeInputAttribs() {
3675 global $wgMinimalPasswordLength;
3677 if ( $wgMinimalPasswordLength == 0 ) {
3681 # Note that the pattern requirement will always be satisfied if the
3682 # input is empty, so we need required in all cases.
3683 $ret = array( 'required' );
3685 # We can't actually do this right now, because Opera 9.6 will print out
3686 # the entered password visibly in its error message! When other
3687 # browsers add support for this attribute, or Opera fixes its support,
3688 # we can add support with a version check to avoid doing this on Opera
3689 # versions where it will be a problem. Reported to Opera as
3690 # DSK-262266, but they don't have a public bug tracker for us to follow.
3692 if ( $wgMinimalPasswordLength > 1 ) {
3693 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3694 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3695 $wgMinimalPasswordLength );