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', 6 );
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(
115 'mEmailAuthenticated',
117 'mEmailTokenExpires',
125 * \type{\arrayof{\string}} Core rights.
126 * Each of these should have a corresponding message of the form
130 static $mCoreRights = array(
156 'move-rootuserpages',
180 * \string Cached results of getAllRights()
182 static $mAllRights = false;
184 /** @name Cache variables */
186 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
187 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
188 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
192 * \bool Whether the cache variables have been loaded.
194 var $mDataLoaded, $mAuthLoaded;
197 * \string Initialization data source if mDataLoaded==false. May be one of:
198 * - 'defaults' anonymous user initialised from class defaults
199 * - 'name' initialise from mName
200 * - 'id' initialise from mId
201 * - 'session' log in from cookies or session if possible
203 * Use the User::newFrom*() family of functions to set this.
207 /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
209 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
210 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
211 $mLocked, $mHideName;
215 * Lightweight constructor for an anonymous user.
216 * Use the User::newFrom* factory functions for other kinds of users.
220 * @see newFromConfirmationCode()
221 * @see newFromSession()
225 $this->clearInstanceCache( 'defaults' );
229 * Load the user table data for this object from the source given by mFrom.
232 if ( $this->mDataLoaded
) {
235 wfProfileIn( __METHOD__
);
237 # Set it now to avoid infinite recursion in accessors
238 $this->mDataLoaded
= true;
240 switch ( $this->mFrom
) {
242 $this->loadDefaults();
245 $this->mId
= self
::idFromName( $this->mName
);
247 # Nonexistent user placeholder object
248 $this->loadDefaults( $this->mName
);
257 $this->loadFromSession();
258 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
261 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
263 wfProfileOut( __METHOD__
);
267 * Load user table data, given mId has already been set.
268 * @return \bool false if the ID does not exist, true otherwise
271 function loadFromId() {
273 if ( $this->mId
== 0 ) {
274 $this->loadDefaults();
279 $key = wfMemcKey( 'user', 'id', $this->mId
);
280 $data = $wgMemc->get( $key );
281 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
282 # Object is expired, load from DB
287 wfDebug( "Cache miss for user {$this->mId}\n" );
289 if ( !$this->loadFromDatabase() ) {
290 # Can't load from ID, user is anonymous
293 $this->saveToCache();
295 wfDebug( "Got user {$this->mId} from cache\n" );
297 foreach ( self
::$mCacheVars as $name ) {
298 $this->$name = $data[$name];
305 * Save user data to the shared cache
307 function saveToCache() {
310 if ( $this->isAnon() ) {
311 // Anonymous users are uncached
315 foreach ( self
::$mCacheVars as $name ) {
316 $data[$name] = $this->$name;
318 $data['mVersion'] = MW_USER_VERSION
;
319 $key = wfMemcKey( 'user', 'id', $this->mId
);
321 $wgMemc->set( $key, $data );
325 /** @name newFrom*() static factory methods */
329 * Static factory method for creation from username.
331 * This is slightly less efficient than newFromId(), so use newFromId() if
332 * you have both an ID and a name handy.
334 * @param $name \string Username, validated by Title::newFromText()
335 * @param $validate \mixed Validate username. Takes the same parameters as
336 * User::getCanonicalName(), except that true is accepted as an alias
337 * for 'valid', for BC.
339 * @return \type{User} The User object, or null if the username is invalid. If the
340 * username is not present in the database, the result will be a user object
341 * with a name, zero user ID and default settings.
343 static function newFromName( $name, $validate = 'valid' ) {
344 if ( $validate === true ) {
347 $name = self
::getCanonicalName( $name, $validate );
348 if ( $name === false ) {
351 # Create unloaded user object
360 * Static factory method for creation from a given user ID.
362 * @param $id \int Valid user ID
363 * @return \type{User} The corresponding User object
365 static function newFromId( $id ) {
373 * Factory method to fetch whichever user has a given email confirmation code.
374 * This code is generated when an account is created or its e-mail address
377 * If the code is invalid or has expired, returns NULL.
379 * @param $code \string Confirmation code
380 * @return \type{User}
382 static function newFromConfirmationCode( $code ) {
383 $dbr = wfGetDB( DB_SLAVE
);
384 $id = $dbr->selectField( 'user', 'user_id', array(
385 'user_email_token' => md5( $code ),
386 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
388 if( $id !== false ) {
389 return User
::newFromId( $id );
396 * Create a new user object using data from session or cookies. If the
397 * login credentials are invalid, the result is an anonymous user.
399 * @return \type{User}
401 static function newFromSession() {
403 $user->mFrom
= 'session';
408 * Create a new user object from a user row.
409 * The row should have all fields from the user table in it.
410 * @param $row array A row from the user table
411 * @return \type{User}
413 static function newFromRow( $row ) {
415 $user->loadFromRow( $row );
423 * Get the username corresponding to a given user ID
424 * @param $id \int User ID
425 * @return \string The corresponding username
427 static function whoIs( $id ) {
428 $dbr = wfGetDB( DB_SLAVE
);
429 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
433 * Get the real name of a user given their user ID
435 * @param $id \int User ID
436 * @return \string The corresponding user's real name
438 static function whoIsReal( $id ) {
439 $dbr = wfGetDB( DB_SLAVE
);
440 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
444 * Get database id given a user name
445 * @param $name \string Username
446 * @return \types{\int,\null} The corresponding user's ID, or null if user is nonexistent
448 static function idFromName( $name ) {
449 $nt = Title
::makeTitleSafe( NS_USER
, $name );
450 if( is_null( $nt ) ) {
454 $dbr = wfGetDB( DB_SLAVE
);
455 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
457 if ( $s === false ) {
465 * Does the string match an anonymous IPv4 address?
467 * This function exists for username validation, in order to reject
468 * usernames which are similar in form to IP addresses. Strings such
469 * as 300.300.300.300 will return true because it looks like an IP
470 * address, despite not being strictly valid.
472 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
473 * address because the usemod software would "cloak" anonymous IP
474 * addresses like this, if we allowed accounts like this to be created
475 * new users could get the old edits of these anonymous users.
477 * @param $name \string String to match
478 * @return \bool True or false
480 static function isIP( $name ) {
481 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
485 * Is the input a valid username?
487 * Checks if the input is a valid username, we don't want an empty string,
488 * an IP address, anything that containins slashes (would mess up subpages),
489 * is longer than the maximum allowed username size or doesn't begin with
492 * @param $name \string String to match
493 * @return \bool True or false
495 static function isValidUserName( $name ) {
496 global $wgContLang, $wgMaxNameChars;
499 || User
::isIP( $name )
500 ||
strpos( $name, '/' ) !== false
501 ||
strlen( $name ) > $wgMaxNameChars
502 ||
$name != $wgContLang->ucfirst( $name ) ) {
503 wfDebugLog( 'username', __METHOD__
.
504 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
508 // Ensure that the name can't be misresolved as a different title,
509 // such as with extra namespace keys at the start.
510 $parsed = Title
::newFromText( $name );
511 if( is_null( $parsed )
512 ||
$parsed->getNamespace()
513 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
514 wfDebugLog( 'username', __METHOD__
.
515 ": '$name' invalid due to ambiguous prefixes" );
519 // Check an additional blacklist of troublemaker characters.
520 // Should these be merged into the title char list?
521 $unicodeBlacklist = '/[' .
522 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
523 '\x{00a0}' . # non-breaking space
524 '\x{2000}-\x{200f}' . # various whitespace
525 '\x{2028}-\x{202f}' . # breaks and control chars
526 '\x{3000}' . # ideographic space
527 '\x{e000}-\x{f8ff}' . # private use
529 if( preg_match( $unicodeBlacklist, $name ) ) {
530 wfDebugLog( 'username', __METHOD__
.
531 ": '$name' invalid due to blacklisted characters" );
539 * Usernames which fail to pass this function will be blocked
540 * from user login and new account registrations, but may be used
541 * internally by batch processes.
543 * If an account already exists in this form, login will be blocked
544 * by a failure to pass this function.
546 * @param $name \string String to match
547 * @return \bool True or false
549 static function isUsableName( $name ) {
550 global $wgReservedUsernames;
551 // Must be a valid username, obviously ;)
552 if ( !self
::isValidUserName( $name ) ) {
556 static $reservedUsernames = false;
557 if ( !$reservedUsernames ) {
558 $reservedUsernames = $wgReservedUsernames;
559 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
562 // Certain names may be reserved for batch processes.
563 foreach ( $reservedUsernames as $reserved ) {
564 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
565 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
567 if ( $reserved == $name ) {
575 * Usernames which fail to pass this function will be blocked
576 * from new account registrations, but may be used internally
577 * either by batch processes or by user accounts which have
578 * already been created.
580 * Additional character blacklisting may be added here
581 * rather than in isValidUserName() to avoid disrupting
584 * @param $name \string String to match
585 * @return \bool True or false
587 static function isCreatableName( $name ) {
589 self
::isUsableName( $name ) &&
591 // Registration-time character blacklisting...
592 strpos( $name, '@' ) === false;
596 * Is the input a valid password for this user?
598 * @param $password \string Desired password
599 * @return \bool True or false
601 function isValidPassword( $password ) {
602 global $wgMinimalPasswordLength, $wgContLang;
605 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
607 if( $result === false )
610 // Password needs to be long enough, and can't be the same as the username
611 return strlen( $password ) >= $wgMinimalPasswordLength
612 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
616 * Does a string look like an e-mail address?
618 * There used to be a regular expression here, it got removed because it
619 * rejected valid addresses. Actually just check if there is '@' somewhere
620 * in the given address.
622 * @todo Check for RFC 2822 compilance (bug 959)
624 * @param $addr \string E-mail address
625 * @return \bool True or false
627 public static function isValidEmailAddr( $addr ) {
629 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
633 return strpos( $addr, '@' ) !== false;
637 * Given unvalidated user input, return a canonical username, or false if
638 * the username is invalid.
639 * @param $name \string User input
640 * @param $validate \types{\string,\bool} Type of validation to use:
641 * - false No validation
642 * - 'valid' Valid for batch processes
643 * - 'usable' Valid for batch processes and login
644 * - 'creatable' Valid for batch processes, login and account creation
646 static function getCanonicalName( $name, $validate = 'valid' ) {
647 # Force usernames to capital
649 $name = $wgContLang->ucfirst( $name );
651 # Reject names containing '#'; these will be cleaned up
652 # with title normalisation, but then it's too late to
654 if( strpos( $name, '#' ) !== false )
657 # Clean up name according to title rules
658 $t = ($validate === 'valid') ?
659 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
660 # Check for invalid titles
661 if( is_null( $t ) ) {
665 # Reject various classes of invalid names
666 $name = $t->getText();
668 $name = $wgAuth->getCanonicalName( $t->getText() );
670 switch ( $validate ) {
674 if ( !User
::isValidUserName( $name ) ) {
679 if ( !User
::isUsableName( $name ) ) {
684 if ( !User
::isCreatableName( $name ) ) {
689 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
695 * Count the number of edits of a user
696 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
698 * @param $uid \int User ID to check
699 * @return \int The user's edit count
701 static function edits( $uid ) {
702 wfProfileIn( __METHOD__
);
703 $dbr = wfGetDB( DB_SLAVE
);
704 // check if the user_editcount field has been initialized
705 $field = $dbr->selectField(
706 'user', 'user_editcount',
707 array( 'user_id' => $uid ),
711 if( $field === null ) { // it has not been initialized. do so.
712 $dbw = wfGetDB( DB_MASTER
);
713 $count = $dbr->selectField(
714 'revision', 'count(*)',
715 array( 'rev_user' => $uid ),
720 array( 'user_editcount' => $count ),
721 array( 'user_id' => $uid ),
727 wfProfileOut( __METHOD__
);
732 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
733 * @todo hash random numbers to improve security, like generateToken()
735 * @return \string New random password
737 static function randomPassword() {
738 global $wgMinimalPasswordLength;
739 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
740 $l = strlen( $pwchars ) - 1;
742 $pwlength = max( 7, $wgMinimalPasswordLength );
743 $digit = mt_rand(0, $pwlength - 1);
745 for ( $i = 0; $i < $pwlength; $i++
) {
746 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
752 * Set cached properties to default.
754 * @note This no longer clears uncached lazy-initialised properties;
755 * the constructor does that instead.
758 function loadDefaults( $name = false ) {
759 wfProfileIn( __METHOD__
);
761 global $wgCookiePrefix;
764 $this->mName
= $name;
765 $this->mRealName
= '';
766 $this->mPassword
= $this->mNewpassword
= '';
767 $this->mNewpassTime
= null;
769 $this->mOptions
= null; # Defer init
771 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
772 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
774 $this->mTouched
= '0'; # Allow any pages to be cached
777 $this->setToken(); # Random
778 $this->mEmailAuthenticated
= null;
779 $this->mEmailToken
= '';
780 $this->mEmailTokenExpires
= null;
781 $this->mRegistration
= wfTimestamp( TS_MW
);
782 $this->mGroups
= array();
784 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
786 wfProfileOut( __METHOD__
);
790 * @deprecated Use wfSetupSession().
792 function SetupSession() {
793 wfDeprecated( __METHOD__
);
798 * Load user data from the session or login cookie. If there are no valid
799 * credentials, initialises the user as an anonymous user.
800 * @return \bool True if the user is logged in, false otherwise.
802 private function loadFromSession() {
803 global $wgMemc, $wgCookiePrefix;
806 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
807 if ( $result !== null ) {
811 if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
812 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
813 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
814 $this->loadDefaults(); // Possible collision!
815 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
816 cookie user ID ($sId) don't match!" );
819 $_SESSION['wsUserID'] = $sId;
820 } else if ( isset( $_SESSION['wsUserID'] ) ) {
821 if ( $_SESSION['wsUserID'] != 0 ) {
822 $sId = $_SESSION['wsUserID'];
824 $this->loadDefaults();
828 $this->loadDefaults();
832 if ( isset( $_SESSION['wsUserName'] ) ) {
833 $sName = $_SESSION['wsUserName'];
834 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
835 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
836 $_SESSION['wsUserName'] = $sName;
838 $this->loadDefaults();
842 $passwordCorrect = FALSE;
844 if ( !$this->loadFromId() ) {
845 # Not a valid ID, loadFromId has switched the object to anon for us
849 if ( isset( $_SESSION['wsToken'] ) ) {
850 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
852 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
853 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
856 # No session or persistent login cookie
857 $this->loadDefaults();
861 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
862 $_SESSION['wsToken'] = $this->mToken
;
863 wfDebug( "Logged in from $from\n" );
866 # Invalid credentials
867 wfDebug( "Can't log in from $from, invalid credentials\n" );
868 $this->loadDefaults();
874 * Load user and user_group data from the database.
875 * $this::mId must be set, this is how the user is identified.
877 * @return \bool True if the user exists, false if the user is anonymous
880 function loadFromDatabase() {
882 $this->mId
= intval( $this->mId
);
884 /** Anonymous user */
886 $this->loadDefaults();
890 $dbr = wfGetDB( DB_MASTER
);
891 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
893 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
895 if ( $s !== false ) {
896 # Initialise user table data
897 $this->loadFromRow( $s );
898 $this->mGroups
= null; // deferred
899 $this->getEditCount(); // revalidation for nulls
904 $this->loadDefaults();
910 * Initialize this object from a row from the user table.
912 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
914 function loadFromRow( $row ) {
915 $this->mDataLoaded
= true;
917 if ( isset( $row->user_id
) ) {
918 $this->mId
= $row->user_id
;
920 $this->mName
= $row->user_name
;
921 $this->mRealName
= $row->user_real_name
;
922 $this->mPassword
= $row->user_password
;
923 $this->mNewpassword
= $row->user_newpassword
;
924 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
925 $this->mEmail
= $row->user_email
;
926 $this->decodeOptions( $row->user_options
);
927 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
928 $this->mToken
= $row->user_token
;
929 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
930 $this->mEmailToken
= $row->user_email_token
;
931 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
932 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
933 $this->mEditCount
= $row->user_editcount
;
937 * Load the groups from the database if they aren't already loaded.
940 function loadGroups() {
941 if ( is_null( $this->mGroups
) ) {
942 $dbr = wfGetDB( DB_MASTER
);
943 $res = $dbr->select( 'user_groups',
945 array( 'ug_user' => $this->mId
),
947 $this->mGroups
= array();
948 while( $row = $dbr->fetchObject( $res ) ) {
949 $this->mGroups
[] = $row->ug_group
;
955 * Clear various cached data stored in this object.
956 * @param $reloadFrom \string Reload user and user_groups table data from a
957 * given source. May be "name", "id", "defaults", "session", or false for
960 function clearInstanceCache( $reloadFrom = false ) {
961 $this->mNewtalk
= -1;
962 $this->mDatePreference
= null;
963 $this->mBlockedby
= -1; # Unset
964 $this->mHash
= false;
966 $this->mRights
= null;
967 $this->mEffectiveGroups
= null;
970 $this->mDataLoaded
= false;
971 $this->mFrom
= $reloadFrom;
976 * Combine the language default options with any site-specific options
977 * and add the default language variants.
979 * @return \type{\arrayof{\string}} Array of options
981 static function getDefaultOptions() {
982 global $wgNamespacesToBeSearchedDefault;
984 * Site defaults will override the global/language defaults
986 global $wgDefaultUserOptions, $wgContLang;
987 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
990 * default language setting
992 $variant = $wgContLang->getPreferredVariant( false );
993 $defOpt['variant'] = $variant;
994 $defOpt['language'] = $variant;
996 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
997 $defOpt['searchNs'.$nsnum] = $val;
1003 * Get a given default option value.
1005 * @param $opt \string Name of option to retrieve
1006 * @return \string Default option value
1008 public static function getDefaultOption( $opt ) {
1009 $defOpts = self
::getDefaultOptions();
1010 if( isset( $defOpts[$opt] ) ) {
1011 return $defOpts[$opt];
1018 * Get a list of user toggle names
1019 * @return \type{\arrayof{\string}} Array of user toggle names
1021 static function getToggles() {
1022 global $wgContLang, $wgUseRCPatrol;
1023 $extraToggles = array();
1024 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1025 if( $wgUseRCPatrol ) {
1026 $extraToggles[] = 'hidepatrolled';
1027 $extraToggles[] = 'newpageshidepatrolled';
1028 $extraToggles[] = 'watchlisthidepatrolled';
1030 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1035 * Get blocking information
1037 * @param $bFromSlave \bool Whether to check the slave database first. To
1038 * improve performance, non-critical checks are done
1039 * against slaves. Check when actually saving should be
1040 * done against master.
1042 function getBlockedStatus( $bFromSlave = true ) {
1043 global $wgEnableSorbs, $wgProxyWhitelist;
1045 if ( -1 != $this->mBlockedby
) {
1046 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1050 wfProfileIn( __METHOD__
);
1051 wfDebug( __METHOD__
.": checking...\n" );
1053 // Initialize data...
1054 // Otherwise something ends up stomping on $this->mBlockedby when
1055 // things get lazy-loaded later, causing false positive block hits
1056 // due to -1 !== 0. Probably session-related... Nothing should be
1057 // overwriting mBlockedby, surely?
1060 $this->mBlockedby
= 0;
1061 $this->mHideName
= 0;
1062 $this->mAllowUsertalk
= 0;
1065 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1066 # Exempt from all types of IP-block
1071 $this->mBlock
= new Block();
1072 $this->mBlock
->fromMaster( !$bFromSlave );
1073 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1074 wfDebug( __METHOD__
.": Found block.\n" );
1075 $this->mBlockedby
= $this->mBlock
->mBy
;
1076 $this->mBlockreason
= $this->mBlock
->mReason
;
1077 $this->mHideName
= $this->mBlock
->mHideName
;
1078 $this->mAllowUsertalk
= $this->mBlock
->mAllowUsertalk
;
1079 if ( $this->isLoggedIn() ) {
1080 $this->spreadBlock();
1083 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1084 // apply to users. Note that the existence of $this->mBlock is not used to
1085 // check for edit blocks, $this->mBlockedby is instead.
1089 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1091 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1092 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1093 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1097 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1098 if ( $this->inSorbsBlacklist( $ip ) ) {
1099 $this->mBlockedby
= wfMsg( 'sorbs' );
1100 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1106 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1108 wfProfileOut( __METHOD__
);
1112 * Whether the given IP is in the SORBS blacklist.
1114 * @param $ip \string IP to check
1115 * @return \bool True if blacklisted.
1117 function inSorbsBlacklist( $ip ) {
1118 global $wgEnableSorbs, $wgSorbsUrl;
1120 return $wgEnableSorbs &&
1121 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1125 * Whether the given IP is in a given DNS blacklist.
1127 * @param $ip \string IP to check
1128 * @param $base \string URL of the DNS blacklist
1129 * @return \bool True if blacklisted.
1131 function inDnsBlacklist( $ip, $base ) {
1132 wfProfileIn( __METHOD__
);
1136 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1137 if( IP
::isIPv4($ip) ) {
1139 $host = "$ip.$base";
1142 $ipList = gethostbynamel( $host );
1145 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1148 wfDebug( "Requested $host, not found in $base.\n" );
1152 wfProfileOut( __METHOD__
);
1157 * Is this user subject to rate limiting?
1159 * @return \bool True if rate limited
1161 public function isPingLimitable() {
1162 global $wgRateLimitsExcludedGroups;
1163 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1164 // Deprecated, but kept for backwards-compatibility config
1167 return !$this->isAllowed('noratelimit');
1171 * Primitive rate limits: enforce maximum actions per time period
1172 * to put a brake on flooding.
1174 * @note When using a shared cache like memcached, IP-address
1175 * last-hit counters will be shared across wikis.
1177 * @param $action \string Action to enforce; 'edit' if unspecified
1178 * @return \bool True if a rate limiter was tripped
1180 function pingLimiter( $action='edit' ) {
1182 # Call the 'PingLimiter' hook
1184 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1188 global $wgRateLimits;
1189 if( !isset( $wgRateLimits[$action] ) ) {
1193 # Some groups shouldn't trigger the ping limiter, ever
1194 if( !$this->isPingLimitable() )
1197 global $wgMemc, $wgRateLimitLog;
1198 wfProfileIn( __METHOD__
);
1200 $limits = $wgRateLimits[$action];
1202 $id = $this->getId();
1206 if( isset( $limits['anon'] ) && $id == 0 ) {
1207 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1210 if( isset( $limits['user'] ) && $id != 0 ) {
1211 $userLimit = $limits['user'];
1213 if( $this->isNewbie() ) {
1214 if( isset( $limits['newbie'] ) && $id != 0 ) {
1215 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1217 if( isset( $limits['ip'] ) ) {
1218 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1221 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1222 $subnet = $matches[1];
1223 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1226 // Check for group-specific permissions
1227 // If more than one group applies, use the group with the highest limit
1228 foreach ( $this->getGroups() as $group ) {
1229 if ( isset( $limits[$group] ) ) {
1230 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1231 $userLimit = $limits[$group];
1235 // Set the user limit key
1236 if ( $userLimit !== false ) {
1237 wfDebug( __METHOD__
.": effective user limit: $userLimit\n" );
1238 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1242 foreach( $keys as $key => $limit ) {
1243 list( $max, $period ) = $limit;
1244 $summary = "(limit $max in {$period}s)";
1245 $count = $wgMemc->get( $key );
1247 if( $count > $max ) {
1248 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1249 if( $wgRateLimitLog ) {
1250 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1254 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1257 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1258 $wgMemc->add( $key, 1, intval( $period ) );
1260 $wgMemc->incr( $key );
1263 wfProfileOut( __METHOD__
);
1268 * Check if user is blocked
1270 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1271 * @return \bool True if blocked, false otherwise
1273 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1274 wfDebug( "User::isBlocked: enter\n" );
1275 $this->getBlockedStatus( $bFromSlave );
1276 return $this->mBlockedby
!== 0;
1280 * Check if user is blocked from editing a particular article
1282 * @param $title \string Title to check
1283 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1284 * @return \bool True if blocked, false otherwise
1286 function isBlockedFrom( $title, $bFromSlave = false ) {
1287 global $wgBlockAllowsUTEdit;
1288 wfProfileIn( __METHOD__
);
1289 wfDebug( __METHOD__
.": enter\n" );
1291 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1292 $blocked = $this->isBlocked( $bFromSlave );
1293 $allowUsertalk = ($wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false);
1294 # If a user's name is suppressed, they cannot make edits anywhere
1295 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1296 $title->getNamespace() == NS_USER_TALK
) {
1298 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1300 wfProfileOut( __METHOD__
);
1305 * If user is blocked, return the name of the user who placed the block
1306 * @return \string name of blocker
1308 function blockedBy() {
1309 $this->getBlockedStatus();
1310 return $this->mBlockedby
;
1314 * If user is blocked, return the specified reason for the block
1315 * @return \string Blocking reason
1317 function blockedFor() {
1318 $this->getBlockedStatus();
1319 return $this->mBlockreason
;
1323 * Check if user is blocked on all wikis.
1324 * Do not use for actual edit permission checks!
1325 * This is intented for quick UI checks.
1327 * @param $ip \type{\string} IP address, uses current client if none given
1328 * @return \type{\bool} True if blocked, false otherwise
1330 function isBlockedGlobally( $ip = '' ) {
1331 if( $this->mBlockedGlobally
!== null ) {
1332 return $this->mBlockedGlobally
;
1334 // User is already an IP?
1335 if( IP
::isIPAddress( $this->getName() ) ) {
1336 $ip = $this->getName();
1341 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1342 $this->mBlockedGlobally
= (bool)$blocked;
1343 return $this->mBlockedGlobally
;
1347 * Check if user account is locked
1349 * @return \type{\bool} True if locked, false otherwise
1351 function isLocked() {
1352 if( $this->mLocked
!== null ) {
1353 return $this->mLocked
;
1356 $authUser = $wgAuth->getUserInstance( $this );
1357 $this->mLocked
= (bool)$authUser->isLocked();
1358 return $this->mLocked
;
1362 * Check if user account is hidden
1364 * @return \type{\bool} True if hidden, false otherwise
1366 function isHidden() {
1367 if( $this->mHideName
!== null ) {
1368 return $this->mHideName
;
1370 $this->getBlockedStatus();
1371 if( !$this->mHideName
) {
1373 $authUser = $wgAuth->getUserInstance( $this );
1374 $this->mHideName
= (bool)$authUser->isHidden();
1376 return $this->mHideName
;
1380 * Get the user's ID.
1381 * @return \int The user's ID; 0 if the user is anonymous or nonexistent
1384 if( $this->mId
=== null and $this->mName
!== null
1385 and User
::isIP( $this->mName
) ) {
1386 // Special case, we know the user is anonymous
1388 } elseif( $this->mId
=== null ) {
1389 // Don't load if this was initialized from an ID
1396 * Set the user and reload all fields according to a given ID
1397 * @param $v \int User ID to reload
1399 function setId( $v ) {
1401 $this->clearInstanceCache( 'id' );
1405 * Get the user name, or the IP of an anonymous user
1406 * @return \string User's name or IP address
1408 function getName() {
1409 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1410 # Special case optimisation
1411 return $this->mName
;
1414 if ( $this->mName
=== false ) {
1416 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1418 return $this->mName
;
1423 * Set the user name.
1425 * This does not reload fields from the database according to the given
1426 * name. Rather, it is used to create a temporary "nonexistent user" for
1427 * later addition to the database. It can also be used to set the IP
1428 * address for an anonymous user to something other than the current
1431 * @note User::newFromName() has rougly the same function, when the named user
1433 * @param $str \string New user name to set
1435 function setName( $str ) {
1437 $this->mName
= $str;
1441 * Get the user's name escaped by underscores.
1442 * @return \string Username escaped by underscores.
1444 function getTitleKey() {
1445 return str_replace( ' ', '_', $this->getName() );
1449 * Check if the user has new messages.
1450 * @return \bool True if the user has new messages
1452 function getNewtalk() {
1455 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1456 if( $this->mNewtalk
=== -1 ) {
1457 $this->mNewtalk
= false; # reset talk page status
1459 # Check memcached separately for anons, who have no
1460 # entire User object stored in there.
1463 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1464 $newtalk = $wgMemc->get( $key );
1465 if( strval( $newtalk ) !== '' ) {
1466 $this->mNewtalk
= (bool)$newtalk;
1468 // Since we are caching this, make sure it is up to date by getting it
1470 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1471 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1474 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1478 return (bool)$this->mNewtalk
;
1482 * Return the talk page(s) this user has new messages on.
1483 * @return \type{\arrayof{\string}} Array of page URLs
1485 function getNewMessageLinks() {
1487 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1490 if (!$this->getNewtalk())
1492 $up = $this->getUserPage();
1493 $utp = $up->getTalkPage();
1494 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1499 * Internal uncached check for new messages
1502 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1503 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1504 * @param $fromMaster \bool true to fetch from the master, false for a slave
1505 * @return \bool True if the user has new messages
1508 function checkNewtalk( $field, $id, $fromMaster = false ) {
1509 if ( $fromMaster ) {
1510 $db = wfGetDB( DB_MASTER
);
1512 $db = wfGetDB( DB_SLAVE
);
1514 $ok = $db->selectField( 'user_newtalk', $field,
1515 array( $field => $id ), __METHOD__
);
1516 return $ok !== false;
1520 * Add or update the new messages flag
1521 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1522 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1523 * @return \bool True if successful, false otherwise
1526 function updateNewtalk( $field, $id ) {
1527 $dbw = wfGetDB( DB_MASTER
);
1528 $dbw->insert( 'user_newtalk',
1529 array( $field => $id ),
1532 if ( $dbw->affectedRows() ) {
1533 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1536 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1542 * Clear the new messages flag for the given user
1543 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1544 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1545 * @return \bool True if successful, false otherwise
1548 function deleteNewtalk( $field, $id ) {
1549 $dbw = wfGetDB( DB_MASTER
);
1550 $dbw->delete( 'user_newtalk',
1551 array( $field => $id ),
1553 if ( $dbw->affectedRows() ) {
1554 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1557 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1563 * Update the 'You have new messages!' status.
1564 * @param $val \bool Whether the user has new messages
1566 function setNewtalk( $val ) {
1567 if( wfReadOnly() ) {
1572 $this->mNewtalk
= $val;
1574 if( $this->isAnon() ) {
1576 $id = $this->getName();
1579 $id = $this->getId();
1584 $changed = $this->updateNewtalk( $field, $id );
1586 $changed = $this->deleteNewtalk( $field, $id );
1589 if( $this->isAnon() ) {
1590 // Anons have a separate memcached space, since
1591 // user records aren't kept for them.
1592 $key = wfMemcKey( 'newtalk', 'ip', $id );
1593 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1596 $this->invalidateCache();
1601 * Generate a current or new-future timestamp to be stored in the
1602 * user_touched field when we update things.
1603 * @return \string Timestamp in TS_MW format
1605 private static function newTouchedTimestamp() {
1606 global $wgClockSkewFudge;
1607 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1611 * Clear user data from memcached.
1612 * Use after applying fun updates to the database; caller's
1613 * responsibility to update user_touched if appropriate.
1615 * Called implicitly from invalidateCache() and saveSettings().
1617 private function clearSharedCache() {
1621 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1626 * Immediately touch the user data cache for this account.
1627 * Updates user_touched field, and removes account data from memcached
1628 * for reload on the next hit.
1630 function invalidateCache() {
1633 $this->mTouched
= self
::newTouchedTimestamp();
1635 $dbw = wfGetDB( DB_MASTER
);
1636 $dbw->update( 'user',
1637 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1638 array( 'user_id' => $this->mId
),
1641 $this->clearSharedCache();
1646 * Validate the cache for this account.
1647 * @param $timestamp \string A timestamp in TS_MW format
1649 function validateCache( $timestamp ) {
1651 return ($timestamp >= $this->mTouched
);
1655 * Get the user touched timestamp
1657 function getTouched() {
1659 return $this->mTouched
;
1663 * Set the password and reset the random token.
1664 * Calls through to authentication plugin if necessary;
1665 * will have no effect if the auth plugin refuses to
1666 * pass the change through or if the legal password
1669 * As a special case, setting the password to null
1670 * wipes it, so the account cannot be logged in until
1671 * a new password is set, for instance via e-mail.
1673 * @param $str \string New password to set
1674 * @throws PasswordError on failure
1676 function setPassword( $str ) {
1679 if( $str !== null ) {
1680 if( !$wgAuth->allowPasswordChange() ) {
1681 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1684 if( !$this->isValidPassword( $str ) ) {
1685 global $wgMinimalPasswordLength;
1686 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1687 $wgMinimalPasswordLength ) );
1691 if( !$wgAuth->setPassword( $this, $str ) ) {
1692 throw new PasswordError( wfMsg( 'externaldberror' ) );
1695 $this->setInternalPassword( $str );
1701 * Set the password and reset the random token unconditionally.
1703 * @param $str \string New password to set
1705 function setInternalPassword( $str ) {
1709 if( $str === null ) {
1710 // Save an invalid hash...
1711 $this->mPassword
= '';
1713 $this->mPassword
= self
::crypt( $str );
1715 $this->mNewpassword
= '';
1716 $this->mNewpassTime
= null;
1720 * Get the user's current token.
1721 * @return \string Token
1723 function getToken() {
1725 return $this->mToken
;
1729 * Set the random token (used for persistent authentication)
1730 * Called from loadDefaults() among other places.
1732 * @param $token \string If specified, set the token to this value
1735 function setToken( $token = false ) {
1736 global $wgSecretKey, $wgProxyKey;
1739 if ( $wgSecretKey ) {
1740 $key = $wgSecretKey;
1741 } elseif ( $wgProxyKey ) {
1746 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1748 $this->mToken
= $token;
1753 * Set the cookie password
1755 * @param $str \string New cookie password
1758 function setCookiePassword( $str ) {
1760 $this->mCookiePassword
= md5( $str );
1764 * Set the password for a password reminder or new account email
1766 * @param $str \string New password to set
1767 * @param $throttle \bool If true, reset the throttle timestamp to the present
1769 function setNewpassword( $str, $throttle = true ) {
1771 $this->mNewpassword
= self
::crypt( $str );
1773 $this->mNewpassTime
= wfTimestampNow();
1778 * Has password reminder email been sent within the last
1779 * $wgPasswordReminderResendTime hours?
1780 * @return \bool True or false
1782 function isPasswordReminderThrottled() {
1783 global $wgPasswordReminderResendTime;
1785 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1788 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1789 return time() < $expiry;
1793 * Get the user's e-mail address
1794 * @return \string User's email address
1796 function getEmail() {
1798 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1799 return $this->mEmail
;
1803 * Get the timestamp of the user's e-mail authentication
1804 * @return \string TS_MW timestamp
1806 function getEmailAuthenticationTimestamp() {
1808 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1809 return $this->mEmailAuthenticated
;
1813 * Set the user's e-mail address
1814 * @param $str \string New e-mail address
1816 function setEmail( $str ) {
1818 $this->mEmail
= $str;
1819 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1823 * Get the user's real name
1824 * @return \string User's real name
1826 function getRealName() {
1828 return $this->mRealName
;
1832 * Set the user's real name
1833 * @param $str \string New real name
1835 function setRealName( $str ) {
1837 $this->mRealName
= $str;
1841 * Get the user's current setting for a given option.
1843 * @param $oname \string The option to check
1844 * @param $defaultOverride \string A default value returned if the option does not exist
1845 * @return \string User's current value for the option
1846 * @see getBoolOption()
1847 * @see getIntOption()
1849 function getOption( $oname, $defaultOverride = '' ) {
1852 if ( is_null( $this->mOptions
) ) {
1853 if($defaultOverride != '') {
1854 return $defaultOverride;
1856 $this->mOptions
= User
::getDefaultOptions();
1859 if ( array_key_exists( $oname, $this->mOptions
) ) {
1860 return trim( $this->mOptions
[$oname] );
1862 return $defaultOverride;
1867 * Get the user's current setting for a given option, as a boolean value.
1869 * @param $oname \string The option to check
1870 * @return \bool User's current value for the option
1873 function getBoolOption( $oname ) {
1874 return (bool)$this->getOption( $oname );
1879 * Get the user's current setting for a given option, as a boolean value.
1881 * @param $oname \string The option to check
1882 * @param $defaultOverride \int A default value returned if the option does not exist
1883 * @return \int User's current value for the option
1886 function getIntOption( $oname, $defaultOverride=0 ) {
1887 $val = $this->getOption( $oname );
1889 $val = $defaultOverride;
1891 return intval( $val );
1895 * Set the given option for a user.
1897 * @param $oname \string The option to set
1898 * @param $val \mixed New value to set
1900 function setOption( $oname, $val ) {
1902 if ( is_null( $this->mOptions
) ) {
1903 $this->mOptions
= User
::getDefaultOptions();
1905 if ( $oname == 'skin' ) {
1906 # Clear cached skin, so the new one displays immediately in Special:Preferences
1907 unset( $this->mSkin
);
1909 // Filter out any newlines that may have passed through input validation.
1910 // Newlines are used to separate items in the options blob.
1912 $val = str_replace( "\r\n", "\n", $val );
1913 $val = str_replace( "\r", "\n", $val );
1914 $val = str_replace( "\n", " ", $val );
1916 // Explicitly NULL values should refer to defaults
1917 global $wgDefaultUserOptions;
1918 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1919 $val = $wgDefaultUserOptions[$oname];
1921 $this->mOptions
[$oname] = $val;
1925 * Reset all options to the site defaults
1927 function restoreOptions() {
1928 $this->mOptions
= User
::getDefaultOptions();
1932 * Get the user's preferred date format.
1933 * @return \string User's preferred date format
1935 function getDatePreference() {
1936 // Important migration for old data rows
1937 if ( is_null( $this->mDatePreference
) ) {
1939 $value = $this->getOption( 'date' );
1940 $map = $wgLang->getDatePreferenceMigrationMap();
1941 if ( isset( $map[$value] ) ) {
1942 $value = $map[$value];
1944 $this->mDatePreference
= $value;
1946 return $this->mDatePreference
;
1950 * Get the permissions this user has.
1951 * @return \type{\arrayof{\string}} Array of permission names
1953 function getRights() {
1954 if ( is_null( $this->mRights
) ) {
1955 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1956 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1957 // Force reindexation of rights when a hook has unset one of them
1958 $this->mRights
= array_values( $this->mRights
);
1960 return $this->mRights
;
1964 * Get the list of explicit group memberships this user has.
1965 * The implicit * and user groups are not included.
1966 * @return \type{\arrayof{\string}} Array of internal group names
1968 function getGroups() {
1970 return $this->mGroups
;
1974 * Get the list of implicit group memberships this user has.
1975 * This includes all explicit groups, plus 'user' if logged in,
1976 * '*' for all accounts and autopromoted groups
1977 * @param $recache \bool Whether to avoid the cache
1978 * @return \type{\arrayof{\string}} Array of internal group names
1980 function getEffectiveGroups( $recache = false ) {
1981 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1982 $this->mEffectiveGroups
= $this->getGroups();
1983 $this->mEffectiveGroups
[] = '*';
1984 if( $this->getId() ) {
1985 $this->mEffectiveGroups
[] = 'user';
1987 $this->mEffectiveGroups
= array_unique( array_merge(
1988 $this->mEffectiveGroups
,
1989 Autopromote
::getAutopromoteGroups( $this )
1992 # Hook for additional groups
1993 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1996 return $this->mEffectiveGroups
;
2000 * Get the user's edit count.
2001 * @return \int User'e edit count
2003 function getEditCount() {
2005 if ( !isset( $this->mEditCount
) ) {
2006 /* Populate the count, if it has not been populated yet */
2007 $this->mEditCount
= User
::edits($this->mId
);
2009 return $this->mEditCount
;
2017 * Add the user to the given group.
2018 * This takes immediate effect.
2019 * @param $group \string Name of the group to add
2021 function addGroup( $group ) {
2022 $dbw = wfGetDB( DB_MASTER
);
2023 if( $this->getId() ) {
2024 $dbw->insert( 'user_groups',
2026 'ug_user' => $this->getID(),
2027 'ug_group' => $group,
2030 array( 'IGNORE' ) );
2033 $this->loadGroups();
2034 $this->mGroups
[] = $group;
2035 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2037 $this->invalidateCache();
2041 * Remove the user from the given group.
2042 * This takes immediate effect.
2043 * @param $group \string Name of the group to remove
2045 function removeGroup( $group ) {
2047 $dbw = wfGetDB( DB_MASTER
);
2048 $dbw->delete( 'user_groups',
2050 'ug_user' => $this->getID(),
2051 'ug_group' => $group,
2053 'User::removeGroup' );
2055 $this->loadGroups();
2056 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2057 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2059 $this->invalidateCache();
2064 * Get whether the user is logged in
2065 * @return \bool True or false
2067 function isLoggedIn() {
2068 return $this->getID() != 0;
2072 * Get whether the user is anonymous
2073 * @return \bool True or false
2076 return !$this->isLoggedIn();
2080 * Get whether the user is a bot
2081 * @return \bool True or false
2085 wfDeprecated( __METHOD__
);
2086 return $this->isAllowed( 'bot' );
2090 * Check if user is allowed to access a feature / make an action
2091 * @param $action \string action to be checked
2092 * @return \bool True if action is allowed, else false
2094 function isAllowed( $action = '' ) {
2095 if ( $action === '' )
2096 return true; // In the spirit of DWIM
2097 # Patrolling may not be enabled
2098 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2099 global $wgUseRCPatrol, $wgUseNPPatrol;
2100 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2103 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2104 # by misconfiguration: 0 == 'foo'
2105 return in_array( $action, $this->getRights(), true );
2109 * Check whether to enable recent changes patrol features for this user
2110 * @return \bool True or false
2112 public function useRCPatrol() {
2113 global $wgUseRCPatrol;
2114 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2118 * Check whether to enable new pages patrol features for this user
2119 * @return \bool True or false
2121 public function useNPPatrol() {
2122 global $wgUseRCPatrol, $wgUseNPPatrol;
2123 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2127 * Get the current skin, loading it if required
2128 * @return \type{Skin} Current skin
2129 * @todo FIXME : need to check the old failback system [AV]
2131 function &getSkin() {
2132 global $wgRequest, $wgAllowUserSkin, $wgDefaultSkin;
2133 if ( ! isset( $this->mSkin
) ) {
2134 wfProfileIn( __METHOD__
);
2136 if( $wgAllowUserSkin ) {
2138 $userSkin = $this->getOption( 'skin' );
2139 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2141 # if we're not allowing users to override, then use the default
2142 $userSkin = $wgDefaultSkin;
2145 $this->mSkin
=& Skin
::newFromKey( $userSkin );
2146 wfProfileOut( __METHOD__
);
2148 return $this->mSkin
;
2152 * Check the watched status of an article.
2153 * @param $title \type{Title} Title of the article to look at
2154 * @return \bool True if article is watched
2156 function isWatched( $title ) {
2157 $wl = WatchedItem
::fromUserTitle( $this, $title );
2158 return $wl->isWatched();
2163 * @param $title \type{Title} Title of the article to look at
2165 function addWatch( $title ) {
2166 $wl = WatchedItem
::fromUserTitle( $this, $title );
2168 $this->invalidateCache();
2172 * Stop watching an article.
2173 * @param $title \type{Title} Title of the article to look at
2175 function removeWatch( $title ) {
2176 $wl = WatchedItem
::fromUserTitle( $this, $title );
2178 $this->invalidateCache();
2182 * Clear the user's notification timestamp for the given title.
2183 * If e-notif e-mails are on, they will receive notification mails on
2184 * the next change of the page if it's watched etc.
2185 * @param $title \type{Title} Title of the article to look at
2187 function clearNotification( &$title ) {
2188 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2190 # Do nothing if the database is locked to writes
2191 if( wfReadOnly() ) {
2195 if ($title->getNamespace() == NS_USER_TALK
&&
2196 $title->getText() == $this->getName() ) {
2197 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2199 $this->setNewtalk( false );
2202 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2206 if( $this->isAnon() ) {
2207 // Nothing else to do...
2211 // Only update the timestamp if the page is being watched.
2212 // The query to find out if it is watched is cached both in memcached and per-invocation,
2213 // and when it does have to be executed, it can be on a slave
2214 // If this is the user's newtalk page, we always update the timestamp
2215 if ($title->getNamespace() == NS_USER_TALK
&&
2216 $title->getText() == $wgUser->getName())
2219 } elseif ( $this->getId() == $wgUser->getId() ) {
2220 $watched = $title->userIsWatching();
2225 // If the page is watched by the user (or may be watched), update the timestamp on any
2226 // any matching rows
2228 $dbw = wfGetDB( DB_MASTER
);
2229 $dbw->update( 'watchlist',
2231 'wl_notificationtimestamp' => NULL
2232 ), array( /* WHERE */
2233 'wl_title' => $title->getDBkey(),
2234 'wl_namespace' => $title->getNamespace(),
2235 'wl_user' => $this->getID()
2242 * Resets all of the given user's page-change notification timestamps.
2243 * If e-notif e-mails are on, they will receive notification mails on
2244 * the next change of any watched page.
2246 * @param $currentUser \int User ID
2248 function clearAllNotifications( $currentUser ) {
2249 global $wgUseEnotif, $wgShowUpdatedMarker;
2250 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2251 $this->setNewtalk( false );
2254 if( $currentUser != 0 ) {
2255 $dbw = wfGetDB( DB_MASTER
);
2256 $dbw->update( 'watchlist',
2258 'wl_notificationtimestamp' => NULL
2259 ), array( /* WHERE */
2260 'wl_user' => $currentUser
2263 # We also need to clear here the "you have new message" notification for the own user_talk page
2264 # This is cleared one page view later in Article::viewUpdates();
2269 * Encode this user's options as a string
2270 * @return \string Encoded options
2273 function encodeOptions() {
2275 if ( is_null( $this->mOptions
) ) {
2276 $this->mOptions
= User
::getDefaultOptions();
2279 foreach ( $this->mOptions
as $oname => $oval ) {
2280 array_push( $a, $oname.'='.$oval );
2282 $s = implode( "\n", $a );
2287 * Set this user's options from an encoded string
2288 * @param $str \string Encoded options to import
2291 function decodeOptions( $str ) {
2292 $this->mOptions
= array();
2293 $a = explode( "\n", $str );
2294 foreach ( $a as $s ) {
2296 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2297 $this->mOptions
[$m[1]] = $m[2];
2303 * Set a cookie on the user's client. Wrapper for
2304 * WebResponse::setCookie
2305 * @param $name \string Name of the cookie to set
2306 * @param $value \string Value to set
2307 * @param $exp \int Expiration time, as a UNIX time value;
2308 * if 0 or not specified, use the default $wgCookieExpiration
2310 protected function setCookie( $name, $value, $exp=0 ) {
2312 $wgRequest->response()->setcookie( $name, $value, $exp );
2316 * Clear a cookie on the user's client
2317 * @param $name \string Name of the cookie to clear
2319 protected function clearCookie( $name ) {
2320 $this->setCookie( $name, '', time() - 86400 );
2324 * Set the default cookies for this session on the user's client.
2326 function setCookies() {
2328 if ( 0 == $this->mId
) return;
2330 'wsUserID' => $this->mId
,
2331 'wsToken' => $this->mToken
,
2332 'wsUserName' => $this->getName()
2335 'UserID' => $this->mId
,
2336 'UserName' => $this->getName(),
2338 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2339 $cookies['Token'] = $this->mToken
;
2341 $cookies['Token'] = false;
2344 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2345 #check for null, since the hook could cause a null value
2346 if ( !is_null( $session ) && isset( $_SESSION ) ){
2347 $_SESSION = $session +
$_SESSION;
2349 foreach ( $cookies as $name => $value ) {
2350 if ( $value === false ) {
2351 $this->clearCookie( $name );
2353 $this->setCookie( $name, $value );
2359 * Log this user out.
2363 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2369 * Clear the user's cookies and session, and reset the instance cache.
2373 function doLogout() {
2374 $this->clearInstanceCache( 'defaults' );
2376 $_SESSION['wsUserID'] = 0;
2378 $this->clearCookie( 'UserID' );
2379 $this->clearCookie( 'Token' );
2381 # Remember when user logged out, to prevent seeing cached pages
2382 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2386 * Save this user's settings into the database.
2387 * @todo Only rarely do all these fields need to be set!
2389 function saveSettings() {
2391 if ( wfReadOnly() ) { return; }
2392 if ( 0 == $this->mId
) { return; }
2394 $this->mTouched
= self
::newTouchedTimestamp();
2396 $dbw = wfGetDB( DB_MASTER
);
2397 $dbw->update( 'user',
2399 'user_name' => $this->mName
,
2400 'user_password' => $this->mPassword
,
2401 'user_newpassword' => $this->mNewpassword
,
2402 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2403 'user_real_name' => $this->mRealName
,
2404 'user_email' => $this->mEmail
,
2405 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2406 'user_options' => $this->encodeOptions(),
2407 'user_touched' => $dbw->timestamp($this->mTouched
),
2408 'user_token' => $this->mToken
,
2409 'user_email_token' => $this->mEmailToken
,
2410 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2411 ), array( /* WHERE */
2412 'user_id' => $this->mId
2415 wfRunHooks( 'UserSaveSettings', array( $this ) );
2416 $this->clearSharedCache();
2417 $this->getUserPage()->invalidateCache();
2421 * If only this user's username is known, and it exists, return the user ID.
2423 function idForName() {
2424 $s = trim( $this->getName() );
2425 if ( $s === '' ) return 0;
2427 $dbr = wfGetDB( DB_SLAVE
);
2428 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2429 if ( $id === false ) {
2436 * Add a user to the database, return the user object
2438 * @param $name \string Username to add
2439 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2440 * - password The user's password. Password logins will be disabled if this is omitted.
2441 * - newpassword A temporary password mailed to the user
2442 * - email The user's email address
2443 * - email_authenticated The email authentication timestamp
2444 * - real_name The user's real name
2445 * - options An associative array of non-default options
2446 * - token Random authentication token. Do not set.
2447 * - registration Registration timestamp. Do not set.
2449 * @return \type{User} A new User object, or null if the username already exists
2451 static function createNew( $name, $params = array() ) {
2454 if ( isset( $params['options'] ) ) {
2455 $user->mOptions
= $params['options'] +
$user->mOptions
;
2456 unset( $params['options'] );
2458 $dbw = wfGetDB( DB_MASTER
);
2459 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2461 'user_id' => $seqVal,
2462 'user_name' => $name,
2463 'user_password' => $user->mPassword
,
2464 'user_newpassword' => $user->mNewpassword
,
2465 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2466 'user_email' => $user->mEmail
,
2467 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2468 'user_real_name' => $user->mRealName
,
2469 'user_options' => $user->encodeOptions(),
2470 'user_token' => $user->mToken
,
2471 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2472 'user_editcount' => 0,
2474 foreach ( $params as $name => $value ) {
2475 $fields["user_$name"] = $value;
2477 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2478 if ( $dbw->affectedRows() ) {
2479 $newUser = User
::newFromId( $dbw->insertId() );
2487 * Add this existing user object to the database
2489 function addToDatabase() {
2491 $dbw = wfGetDB( DB_MASTER
);
2492 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2493 $dbw->insert( 'user',
2495 'user_id' => $seqVal,
2496 'user_name' => $this->mName
,
2497 'user_password' => $this->mPassword
,
2498 'user_newpassword' => $this->mNewpassword
,
2499 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2500 'user_email' => $this->mEmail
,
2501 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2502 'user_real_name' => $this->mRealName
,
2503 'user_options' => $this->encodeOptions(),
2504 'user_token' => $this->mToken
,
2505 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2506 'user_editcount' => 0,
2509 $this->mId
= $dbw->insertId();
2511 // Clear instance cache other than user table data, which is already accurate
2512 $this->clearInstanceCache();
2516 * If this (non-anonymous) user is blocked, block any IP address
2517 * they've successfully logged in from.
2519 function spreadBlock() {
2520 wfDebug( __METHOD__
."()\n" );
2522 if ( $this->mId
== 0 ) {
2526 $userblock = Block
::newFromDB( '', $this->mId
);
2527 if ( !$userblock ) {
2531 $userblock->doAutoblock( wfGetIp() );
2536 * Generate a string which will be different for any combination of
2537 * user options which would produce different parser output.
2538 * This will be used as part of the hash key for the parser cache,
2539 * so users will the same options can share the same cached data
2542 * Extensions which require it should install 'PageRenderingHash' hook,
2543 * which will give them a chance to modify this key based on their own
2546 * @return \string Page rendering hash
2548 function getPageRenderingHash() {
2549 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2551 return $this->mHash
;
2554 // stubthreshold is only included below for completeness,
2555 // it will always be 0 when this function is called by parsercache.
2557 $confstr = $this->getOption( 'math' );
2558 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2559 if ( $wgUseDynamicDates ) {
2560 $confstr .= '!' . $this->getDatePreference();
2562 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2563 $confstr .= '!' . $wgLang->getCode();
2564 $confstr .= '!' . $this->getOption( 'thumbsize' );
2565 // add in language specific options, if any
2566 $extra = $wgContLang->getExtraHashOptions();
2569 $confstr .= $wgRenderHashAppend;
2571 // Give a chance for extensions to modify the hash, if they have
2572 // extra options or other effects on the parser cache.
2573 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2575 // Make it a valid memcached key fragment
2576 $confstr = str_replace( ' ', '_', $confstr );
2577 $this->mHash
= $confstr;
2582 * Get whether the user is explicitly blocked from account creation.
2583 * @return \bool True if blocked
2585 function isBlockedFromCreateAccount() {
2586 $this->getBlockedStatus();
2587 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2591 * Get whether the user is blocked from using Special:Emailuser.
2592 * @return \bool True if blocked
2594 function isBlockedFromEmailuser() {
2595 $this->getBlockedStatus();
2596 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2600 * Get whether the user is allowed to create an account.
2601 * @return \bool True if allowed
2603 function isAllowedToCreateAccount() {
2604 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2610 function setLoaded( $loaded ) {
2611 wfDeprecated( __METHOD__
);
2615 * Get this user's personal page title.
2617 * @return \type{Title} User's personal page title
2619 function getUserPage() {
2620 return Title
::makeTitle( NS_USER
, $this->getName() );
2624 * Get this user's talk page title.
2626 * @return \type{Title} User's talk page title
2628 function getTalkPage() {
2629 $title = $this->getUserPage();
2630 return $title->getTalkPage();
2634 * Get the maximum valid user ID.
2635 * @return \int User ID
2638 function getMaxID() {
2639 static $res; // cache
2641 if ( isset( $res ) )
2644 $dbr = wfGetDB( DB_SLAVE
);
2645 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2650 * Determine whether the user is a newbie. Newbies are either
2651 * anonymous IPs, or the most recently created accounts.
2652 * @return \bool True if the user is a newbie
2654 function isNewbie() {
2655 return !$this->isAllowed( 'autoconfirmed' );
2659 * Is the user active? We check to see if they've made at least
2660 * X number of edits in the last Y days.
2662 * @return \bool True if the user is active, false if not.
2664 public function isActiveEditor() {
2665 global $wgActiveUserEditCount, $wgActiveUserDays;
2666 $dbr = wfGetDB( DB_SLAVE
);
2668 // Stolen without shame from RC
2669 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2670 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
2671 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2673 $res = $dbr->select( 'revision', '1',
2674 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2676 array('LIMIT' => $wgActiveUserEditCount ) );
2678 $count = $dbr->numRows($res);
2679 $dbr->freeResult($res);
2681 return $count == $wgActiveUserEditCount;
2685 * Check to see if the given clear-text password is one of the accepted passwords
2686 * @param $password \string user password.
2687 * @return \bool True if the given password is correct, otherwise False.
2689 function checkPassword( $password ) {
2693 // Even though we stop people from creating passwords that
2694 // are shorter than this, doesn't mean people wont be able
2695 // to. Certain authentication plugins do NOT want to save
2696 // domain passwords in a mysql database, so we should
2697 // check this (incase $wgAuth->strict() is false).
2698 if( !$this->isValidPassword( $password ) ) {
2702 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2704 } elseif( $wgAuth->strict() ) {
2705 /* Auth plugin doesn't allow local authentication */
2707 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2708 /* Auth plugin doesn't allow local authentication for this user name */
2711 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2713 } elseif ( function_exists( 'iconv' ) ) {
2714 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2715 # Check for this with iconv
2716 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2717 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2725 * Check if the given clear-text password matches the temporary password
2726 * sent by e-mail for password reset operations.
2727 * @return \bool True if matches, false otherwise
2729 function checkTemporaryPassword( $plaintext ) {
2730 global $wgNewPasswordExpiry;
2731 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
2733 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
2734 return ( time() < $expiry );
2741 * Initialize (if necessary) and return a session token value
2742 * which can be used in edit forms to show that the user's
2743 * login credentials aren't being hijacked with a foreign form
2746 * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2747 * @return \string The new edit token
2749 function editToken( $salt = '' ) {
2750 if ( $this->isAnon() ) {
2751 return EDIT_TOKEN_SUFFIX
;
2753 if( !isset( $_SESSION['wsEditToken'] ) ) {
2754 $token = $this->generateToken();
2755 $_SESSION['wsEditToken'] = $token;
2757 $token = $_SESSION['wsEditToken'];
2759 if( is_array( $salt ) ) {
2760 $salt = implode( '|', $salt );
2762 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2767 * Generate a looking random token for various uses.
2769 * @param $salt \string Optional salt value
2770 * @return \string The new random token
2772 function generateToken( $salt = '' ) {
2773 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2774 return md5( $token . $salt );
2778 * Check given value against the token value stored in the session.
2779 * A match should confirm that the form was submitted from the
2780 * user's own login session, not a form submission from a third-party
2783 * @param $val \string Input value to compare
2784 * @param $salt \string Optional function-specific data for hashing
2785 * @return \bool Whether the token matches
2787 function matchEditToken( $val, $salt = '' ) {
2788 $sessionToken = $this->editToken( $salt );
2789 if ( $val != $sessionToken ) {
2790 wfDebug( "User::matchEditToken: broken session data\n" );
2792 return $val == $sessionToken;
2796 * Check given value against the token value stored in the session,
2797 * ignoring the suffix.
2799 * @param $val \string Input value to compare
2800 * @param $salt \string Optional function-specific data for hashing
2801 * @return \bool Whether the token matches
2803 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2804 $sessionToken = $this->editToken( $salt );
2805 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2809 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2810 * mail to the user's given address.
2812 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure.
2814 function sendConfirmationMail() {
2816 $expiration = null; // gets passed-by-ref and defined in next line.
2817 $token = $this->confirmationToken( $expiration );
2818 $url = $this->confirmationTokenUrl( $token );
2819 $invalidateURL = $this->invalidationTokenUrl( $token );
2820 $this->saveSettings();
2822 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2823 wfMsg( 'confirmemail_body',
2827 $wgLang->timeanddate( $expiration, false ),
2832 * Send an e-mail to this user's account. Does not check for
2833 * confirmed status or validity.
2835 * @param $subject \string Message subject
2836 * @param $body \string Message body
2837 * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2838 * @param $replyto \string Reply-To address
2839 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure
2841 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2842 if( is_null( $from ) ) {
2843 global $wgPasswordSender;
2844 $from = $wgPasswordSender;
2847 $to = new MailAddress( $this );
2848 $sender = new MailAddress( $from );
2849 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2853 * Generate, store, and return a new e-mail confirmation code.
2854 * A hash (unsalted, since it's used as a key) is stored.
2856 * @note Call saveSettings() after calling this function to commit
2857 * this change to the database.
2859 * @param[out] &$expiration \mixed Accepts the expiration time
2860 * @return \string New token
2863 function confirmationToken( &$expiration ) {
2865 $expires = $now +
7 * 24 * 60 * 60;
2866 $expiration = wfTimestamp( TS_MW
, $expires );
2867 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2868 $hash = md5( $token );
2870 $this->mEmailToken
= $hash;
2871 $this->mEmailTokenExpires
= $expiration;
2876 * Return a URL the user can use to confirm their email address.
2877 * @param $token \string Accepts the email confirmation token
2878 * @return \string New token URL
2881 function confirmationTokenUrl( $token ) {
2882 return $this->getTokenUrl( 'ConfirmEmail', $token );
2885 * Return a URL the user can use to invalidate their email address.
2886 * @param $token \string Accepts the email confirmation token
2887 * @return \string New token URL
2890 function invalidationTokenUrl( $token ) {
2891 return $this->getTokenUrl( 'Invalidateemail', $token );
2895 * Internal function to format the e-mail validation/invalidation URLs.
2896 * This uses $wgArticlePath directly as a quickie hack to use the
2897 * hardcoded English names of the Special: pages, for ASCII safety.
2899 * @note Since these URLs get dropped directly into emails, using the
2900 * short English names avoids insanely long URL-encoded links, which
2901 * also sometimes can get corrupted in some browsers/mailers
2902 * (bug 6957 with Gmail and Internet Explorer).
2904 * @param $page \string Special page
2905 * @param $token \string Token
2906 * @return \string Formatted URL
2908 protected function getTokenUrl( $page, $token ) {
2909 global $wgArticlePath;
2913 "Special:$page/$token",
2918 * Mark the e-mail address confirmed.
2920 * @note Call saveSettings() after calling this function to commit the change.
2922 function confirmEmail() {
2923 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2928 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2929 * address if it was already confirmed.
2931 * @note Call saveSettings() after calling this function to commit the change.
2933 function invalidateEmail() {
2935 $this->mEmailToken
= null;
2936 $this->mEmailTokenExpires
= null;
2937 $this->setEmailAuthenticationTimestamp( null );
2942 * Set the e-mail authentication timestamp.
2943 * @param $timestamp \string TS_MW timestamp
2945 function setEmailAuthenticationTimestamp( $timestamp ) {
2947 $this->mEmailAuthenticated
= $timestamp;
2948 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2952 * Is this user allowed to send e-mails within limits of current
2953 * site configuration?
2954 * @return \bool True if allowed
2956 function canSendEmail() {
2957 global $wgEnableEmail, $wgEnableUserEmail;
2958 if( !$wgEnableEmail ||
!$wgEnableUserEmail ) {
2961 $canSend = $this->isEmailConfirmed();
2962 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2967 * Is this user allowed to receive e-mails within limits of current
2968 * site configuration?
2969 * @return \bool True if allowed
2971 function canReceiveEmail() {
2972 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2976 * Is this user's e-mail address valid-looking and confirmed within
2977 * limits of the current site configuration?
2979 * @note If $wgEmailAuthentication is on, this may require the user to have
2980 * confirmed their address by returning a code or using a password
2981 * sent to the address from the wiki.
2983 * @return \bool True if confirmed
2985 function isEmailConfirmed() {
2986 global $wgEmailAuthentication;
2989 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2990 if( $this->isAnon() )
2992 if( !self
::isValidEmailAddr( $this->mEmail
) )
2994 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3003 * Check whether there is an outstanding request for e-mail confirmation.
3004 * @return \bool True if pending
3006 function isEmailConfirmationPending() {
3007 global $wgEmailAuthentication;
3008 return $wgEmailAuthentication &&
3009 !$this->isEmailConfirmed() &&
3010 $this->mEmailToken
&&
3011 $this->mEmailTokenExpires
> wfTimestamp();
3015 * Get the timestamp of account creation.
3017 * @return \types{\string,\bool} string Timestamp of account creation, or false for
3018 * non-existent/anonymous user accounts.
3020 public function getRegistration() {
3021 return $this->getId() > 0
3022 ?
$this->mRegistration
3027 * Get the timestamp of the first edit
3029 * @return \types{\string,\bool} string Timestamp of first edit, or false for
3030 * non-existent/anonymous user accounts.
3032 public function getFirstEditTimestamp() {
3033 if( $this->getId() == 0 ) return false; // anons
3034 $dbr = wfGetDB( DB_SLAVE
);
3035 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3036 array( 'rev_user' => $this->getId() ),
3038 array( 'ORDER BY' => 'rev_timestamp ASC' )
3040 if( !$time ) return false; // no edits
3041 return wfTimestamp( TS_MW
, $time );
3045 * Get the permissions associated with a given list of groups
3047 * @param $groups \type{\arrayof{\string}} List of internal group names
3048 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3050 static function getGroupPermissions( $groups ) {
3051 global $wgGroupPermissions;
3053 foreach( $groups as $group ) {
3054 if( isset( $wgGroupPermissions[$group] ) ) {
3055 $rights = array_merge( $rights,
3056 // array_filter removes empty items
3057 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3060 return array_unique($rights);
3064 * Get all the groups who have a given permission
3066 * @param $role \string Role to check
3067 * @return \type{\arrayof{\string}} List of internal group names with the given permission
3069 static function getGroupsWithPermission( $role ) {
3070 global $wgGroupPermissions;
3071 $allowedGroups = array();
3072 foreach ( $wgGroupPermissions as $group => $rights ) {
3073 if ( isset( $rights[$role] ) && $rights[$role] ) {
3074 $allowedGroups[] = $group;
3077 return $allowedGroups;
3081 * Get the localized descriptive name for a group, if it exists
3083 * @param $group \string Internal group name
3084 * @return \string Localized descriptive group name
3086 static function getGroupName( $group ) {
3087 global $wgMessageCache;
3088 $wgMessageCache->loadAllMessages();
3089 $key = "group-$group";
3090 $name = wfMsg( $key );
3091 return $name == '' ||
wfEmptyMsg( $key, $name )
3097 * Get the localized descriptive name for a member of a group, if it exists
3099 * @param $group \string Internal group name
3100 * @return \string Localized name for group member
3102 static function getGroupMember( $group ) {
3103 global $wgMessageCache;
3104 $wgMessageCache->loadAllMessages();
3105 $key = "group-$group-member";
3106 $name = wfMsg( $key );
3107 return $name == '' ||
wfEmptyMsg( $key, $name )
3113 * Return the set of defined explicit groups.
3114 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3115 * are not included, as they are defined automatically, not in the database.
3116 * @return \type{\arrayof{\string}} Array of internal group names
3118 static function getAllGroups() {
3119 global $wgGroupPermissions;
3121 array_keys( $wgGroupPermissions ),
3122 self
::getImplicitGroups()
3127 * Get a list of all available permissions.
3128 * @return \type{\arrayof{\string}} Array of permission names
3130 static function getAllRights() {
3131 if ( self
::$mAllRights === false ) {
3132 global $wgAvailableRights;
3133 if ( count( $wgAvailableRights ) ) {
3134 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3136 self
::$mAllRights = self
::$mCoreRights;
3138 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3140 return self
::$mAllRights;
3144 * Get a list of implicit groups
3145 * @return \type{\arrayof{\string}} Array of internal group names
3147 public static function getImplicitGroups() {
3148 global $wgImplicitGroups;
3149 $groups = $wgImplicitGroups;
3150 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3155 * Get the title of a page describing a particular group
3157 * @param $group \string Internal group name
3158 * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3160 static function getGroupPage( $group ) {
3161 global $wgMessageCache;
3162 $wgMessageCache->loadAllMessages();
3163 $page = wfMsgForContent( 'grouppage-' . $group );
3164 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3165 $title = Title
::newFromText( $page );
3166 if( is_object( $title ) )
3173 * Create a link to the group in HTML, if available;
3174 * else return the group name.
3176 * @param $group \string Internal name of the group
3177 * @param $text \string The text of the link
3178 * @return \string HTML link to the group
3180 static function makeGroupLinkHTML( $group, $text = '' ) {
3182 $text = self
::getGroupName( $group );
3184 $title = self
::getGroupPage( $group );
3187 $sk = $wgUser->getSkin();
3188 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3195 * Create a link to the group in Wikitext, if available;
3196 * else return the group name.
3198 * @param $group \string Internal name of the group
3199 * @param $text \string The text of the link
3200 * @return \string Wikilink to the group
3202 static function makeGroupLinkWiki( $group, $text = '' ) {
3204 $text = self
::getGroupName( $group );
3206 $title = self
::getGroupPage( $group );
3208 $page = $title->getPrefixedText();
3209 return "[[$page|$text]]";
3216 * Increment the user's edit-count field.
3217 * Will have no effect for anonymous users.
3219 function incEditCount() {
3220 if( !$this->isAnon() ) {
3221 $dbw = wfGetDB( DB_MASTER
);
3222 $dbw->update( 'user',
3223 array( 'user_editcount=user_editcount+1' ),
3224 array( 'user_id' => $this->getId() ),
3227 // Lazy initialization check...
3228 if( $dbw->affectedRows() == 0 ) {
3229 // Pull from a slave to be less cruel to servers
3230 // Accuracy isn't the point anyway here
3231 $dbr = wfGetDB( DB_SLAVE
);
3232 $count = $dbr->selectField( 'revision',
3234 array( 'rev_user' => $this->getId() ),
3237 // Now here's a goddamn hack...
3238 if( $dbr !== $dbw ) {
3239 // If we actually have a slave server, the count is
3240 // at least one behind because the current transaction
3241 // has not been committed and replicated.
3244 // But if DB_SLAVE is selecting the master, then the
3245 // count we just read includes the revision that was
3246 // just added in the working transaction.
3249 $dbw->update( 'user',
3250 array( 'user_editcount' => $count ),
3251 array( 'user_id' => $this->getId() ),
3255 // edit count in user cache too
3256 $this->invalidateCache();
3260 * Get the description of a given right
3262 * @param $right \string Right to query
3263 * @return \string Localized description of the right
3265 static function getRightDescription( $right ) {
3266 global $wgMessageCache;
3267 $wgMessageCache->loadAllMessages();
3268 $key = "right-$right";
3269 $name = wfMsg( $key );
3270 return $name == '' ||
wfEmptyMsg( $key, $name )
3276 * Make an old-style password hash
3278 * @param $password \string Plain-text password
3279 * @param $userId \string User ID
3280 * @return \string Password hash
3282 static function oldCrypt( $password, $userId ) {
3283 global $wgPasswordSalt;
3284 if ( $wgPasswordSalt ) {
3285 return md5( $userId . '-' . md5( $password ) );
3287 return md5( $password );
3292 * Make a new-style password hash
3294 * @param $password \string Plain-text password
3295 * @param $salt \string Optional salt, may be random or the user ID.
3296 * If unspecified or false, will generate one automatically
3297 * @return \string Password hash
3299 static function crypt( $password, $salt = false ) {
3300 global $wgPasswordSalt;
3303 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3307 if( $wgPasswordSalt ) {
3308 if ( $salt === false ) {
3309 $salt = substr( wfGenerateToken(), 0, 8 );
3311 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3313 return ':A:' . md5( $password );
3318 * Compare a password hash with a plain-text password. Requires the user
3319 * ID if there's a chance that the hash is an old-style hash.
3321 * @param $hash \string Password hash
3322 * @param $password \string Plain-text password to compare
3323 * @param $userId \string User ID for old-style password salt
3326 static function comparePasswords( $hash, $password, $userId = false ) {
3328 $type = substr( $hash, 0, 3 );
3331 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3335 if ( $type == ':A:' ) {
3337 return md5( $password ) === substr( $hash, 3 );
3338 } elseif ( $type == ':B:' ) {
3340 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3341 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3344 return self
::oldCrypt( $password, $userId ) === $hash;
3349 * Add a newuser log entry for this user
3350 * @param $byEmail Boolean: account made by email?
3352 public function addNewUserLogEntry( $byEmail = false ) {
3353 global $wgUser, $wgContLang, $wgNewUserLog;
3354 if( empty($wgNewUserLog) ) {
3355 return true; // disabled
3357 $talk = $wgContLang->getFormattedNsText( NS_TALK
);
3358 if( $this->getName() == $wgUser->getName() ) {
3362 $action = 'create2';
3363 $message = $byEmail ?
wfMsgForContent( 'newuserlog-byemail' ) : '';
3365 $log = new LogPage( 'newusers' );
3366 $log->addEntry( $action, $this->getUserPage(), $message, array( $this->getId() ) );
3371 * Add an autocreate newuser log entry for this user
3372 * Used by things like CentralAuth and perhaps other authplugins.
3374 public function addNewUserLogEntryAutoCreate() {
3375 global $wgNewUserLog;
3376 if( empty($wgNewUserLog) ) {
3377 return true; // disabled
3379 $log = new LogPage( 'newusers', false );
3380 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );