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(
173 * \string Cached results of getAllRights()
175 static $mAllRights = false;
177 /** @name Cache variables */
179 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
180 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
181 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
185 * \bool Whether the cache variables have been loaded.
187 var $mDataLoaded, $mAuthLoaded;
190 * \string Initialization data source if mDataLoaded==false. May be one of:
191 * - 'defaults' anonymous user initialised from class defaults
192 * - 'name' initialise from mName
193 * - 'id' initialise from mId
194 * - 'session' log in from cookies or session if possible
196 * Use the User::newFrom*() family of functions to set this.
200 /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
202 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
203 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
204 $mLocked, $mHideName;
208 * Lightweight constructor for an anonymous user.
209 * Use the User::newFrom* factory functions for other kinds of users.
213 * @see newFromConfirmationCode()
214 * @see newFromSession()
218 $this->clearInstanceCache( 'defaults' );
222 * Load the user table data for this object from the source given by mFrom.
225 if ( $this->mDataLoaded
) {
228 wfProfileIn( __METHOD__
);
230 # Set it now to avoid infinite recursion in accessors
231 $this->mDataLoaded
= true;
233 switch ( $this->mFrom
) {
235 $this->loadDefaults();
238 $this->mId
= self
::idFromName( $this->mName
);
240 # Nonexistent user placeholder object
241 $this->loadDefaults( $this->mName
);
250 $this->loadFromSession();
251 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
254 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
256 wfProfileOut( __METHOD__
);
260 * Load user table data, given mId has already been set.
261 * @return \bool false if the ID does not exist, true otherwise
264 function loadFromId() {
266 if ( $this->mId
== 0 ) {
267 $this->loadDefaults();
272 $key = wfMemcKey( 'user', 'id', $this->mId
);
273 $data = $wgMemc->get( $key );
274 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
275 # Object is expired, load from DB
280 wfDebug( "Cache miss for user {$this->mId}\n" );
282 if ( !$this->loadFromDatabase() ) {
283 # Can't load from ID, user is anonymous
286 $this->saveToCache();
288 wfDebug( "Got user {$this->mId} from cache\n" );
290 foreach ( self
::$mCacheVars as $name ) {
291 $this->$name = $data[$name];
298 * Save user data to the shared cache
300 function saveToCache() {
303 if ( $this->isAnon() ) {
304 // Anonymous users are uncached
308 foreach ( self
::$mCacheVars as $name ) {
309 $data[$name] = $this->$name;
311 $data['mVersion'] = MW_USER_VERSION
;
312 $key = wfMemcKey( 'user', 'id', $this->mId
);
314 $wgMemc->set( $key, $data );
318 /** @name newFrom*() static factory methods */
322 * Static factory method for creation from username.
324 * This is slightly less efficient than newFromId(), so use newFromId() if
325 * you have both an ID and a name handy.
327 * @param $name \string Username, validated by Title::newFromText()
328 * @param $validate \mixed Validate username. Takes the same parameters as
329 * User::getCanonicalName(), except that true is accepted as an alias
330 * for 'valid', for BC.
332 * @return \type{User} The User object, or null if the username is invalid. If the
333 * username is not present in the database, the result will be a user object
334 * with a name, zero user ID and default settings.
336 static function newFromName( $name, $validate = 'valid' ) {
337 if ( $validate === true ) {
340 $name = self
::getCanonicalName( $name, $validate );
341 if ( $name === false ) {
344 # Create unloaded user object
353 * Static factory method for creation from a given user ID.
355 * @param $id \int Valid user ID
356 * @return \type{User} The corresponding User object
358 static function newFromId( $id ) {
366 * Factory method to fetch whichever user has a given email confirmation code.
367 * This code is generated when an account is created or its e-mail address
370 * If the code is invalid or has expired, returns NULL.
372 * @param $code \string Confirmation code
373 * @return \type{User}
375 static function newFromConfirmationCode( $code ) {
376 $dbr = wfGetDB( DB_SLAVE
);
377 $id = $dbr->selectField( 'user', 'user_id', array(
378 'user_email_token' => md5( $code ),
379 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
381 if( $id !== false ) {
382 return User
::newFromId( $id );
389 * Create a new user object using data from session or cookies. If the
390 * login credentials are invalid, the result is an anonymous user.
392 * @return \type{User}
394 static function newFromSession() {
396 $user->mFrom
= 'session';
401 * Create a new user object from a user row.
402 * The row should have all fields from the user table in it.
403 * @param $row array A row from the user table
404 * @return \type{User}
406 static function newFromRow( $row ) {
408 $user->loadFromRow( $row );
416 * Get the username corresponding to a given user ID
417 * @param $id \int User ID
418 * @return \string The corresponding username
420 static function whoIs( $id ) {
421 $dbr = wfGetDB( DB_SLAVE
);
422 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
426 * Get the real name of a user given their user ID
428 * @param $id \int User ID
429 * @return \string The corresponding user's real name
431 static function whoIsReal( $id ) {
432 $dbr = wfGetDB( DB_SLAVE
);
433 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
437 * Get database id given a user name
438 * @param $name \string Username
439 * @return \types{\int,\null} The corresponding user's ID, or null if user is nonexistent
441 static function idFromName( $name ) {
442 $nt = Title
::makeTitleSafe( NS_USER
, $name );
443 if( is_null( $nt ) ) {
447 $dbr = wfGetDB( DB_SLAVE
);
448 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
450 if ( $s === false ) {
458 * Does the string match an anonymous IPv4 address?
460 * This function exists for username validation, in order to reject
461 * usernames which are similar in form to IP addresses. Strings such
462 * as 300.300.300.300 will return true because it looks like an IP
463 * address, despite not being strictly valid.
465 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
466 * address because the usemod software would "cloak" anonymous IP
467 * addresses like this, if we allowed accounts like this to be created
468 * new users could get the old edits of these anonymous users.
470 * @param $name \string String to match
471 * @return \bool True or false
473 static function isIP( $name ) {
474 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
478 * Is the input a valid username?
480 * Checks if the input is a valid username, we don't want an empty string,
481 * an IP address, anything that containins slashes (would mess up subpages),
482 * is longer than the maximum allowed username size or doesn't begin with
485 * @param $name \string String to match
486 * @return \bool True or false
488 static function isValidUserName( $name ) {
489 global $wgContLang, $wgMaxNameChars;
492 || User
::isIP( $name )
493 ||
strpos( $name, '/' ) !== false
494 ||
strlen( $name ) > $wgMaxNameChars
495 ||
$name != $wgContLang->ucfirst( $name ) ) {
496 wfDebugLog( 'username', __METHOD__
.
497 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
501 // Ensure that the name can't be misresolved as a different title,
502 // such as with extra namespace keys at the start.
503 $parsed = Title
::newFromText( $name );
504 if( is_null( $parsed )
505 ||
$parsed->getNamespace()
506 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
507 wfDebugLog( 'username', __METHOD__
.
508 ": '$name' invalid due to ambiguous prefixes" );
512 // Check an additional blacklist of troublemaker characters.
513 // Should these be merged into the title char list?
514 $unicodeBlacklist = '/[' .
515 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
516 '\x{00a0}' . # non-breaking space
517 '\x{2000}-\x{200f}' . # various whitespace
518 '\x{2028}-\x{202f}' . # breaks and control chars
519 '\x{3000}' . # ideographic space
520 '\x{e000}-\x{f8ff}' . # private use
522 if( preg_match( $unicodeBlacklist, $name ) ) {
523 wfDebugLog( 'username', __METHOD__
.
524 ": '$name' invalid due to blacklisted characters" );
532 * Usernames which fail to pass this function will be blocked
533 * from user login and new account registrations, but may be used
534 * internally by batch processes.
536 * If an account already exists in this form, login will be blocked
537 * by a failure to pass this function.
539 * @param $name \string String to match
540 * @return \bool True or false
542 static function isUsableName( $name ) {
543 global $wgReservedUsernames;
544 // Must be a valid username, obviously ;)
545 if ( !self
::isValidUserName( $name ) ) {
549 static $reservedUsernames = false;
550 if ( !$reservedUsernames ) {
551 $reservedUsernames = $wgReservedUsernames;
552 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
555 // Certain names may be reserved for batch processes.
556 foreach ( $reservedUsernames as $reserved ) {
557 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
558 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
560 if ( $reserved == $name ) {
568 * Usernames which fail to pass this function will be blocked
569 * from new account registrations, but may be used internally
570 * either by batch processes or by user accounts which have
571 * already been created.
573 * Additional character blacklisting may be added here
574 * rather than in isValidUserName() to avoid disrupting
577 * @param $name \string String to match
578 * @return \bool True or false
580 static function isCreatableName( $name ) {
582 self
::isUsableName( $name ) &&
584 // Registration-time character blacklisting...
585 strpos( $name, '@' ) === false;
589 * Is the input a valid password for this user?
591 * @param $password \string Desired password
592 * @return \bool True or false
594 function isValidPassword( $password ) {
595 global $wgMinimalPasswordLength, $wgContLang;
598 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
600 if( $result === false )
603 // Password needs to be long enough, and can't be the same as the username
604 return strlen( $password ) >= $wgMinimalPasswordLength
605 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
609 * Does a string look like an e-mail address?
611 * There used to be a regular expression here, it got removed because it
612 * rejected valid addresses. Actually just check if there is '@' somewhere
613 * in the given address.
615 * @todo Check for RFC 2822 compilance (bug 959)
617 * @param $addr \string E-mail address
618 * @return \bool True or false
620 public static function isValidEmailAddr( $addr ) {
622 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
626 return strpos( $addr, '@' ) !== false;
630 * Given unvalidated user input, return a canonical username, or false if
631 * the username is invalid.
632 * @param $name \string User input
633 * @param $validate \types{\string,\bool} Type of validation to use:
634 * - false No validation
635 * - 'valid' Valid for batch processes
636 * - 'usable' Valid for batch processes and login
637 * - 'creatable' Valid for batch processes, login and account creation
639 static function getCanonicalName( $name, $validate = 'valid' ) {
640 # Force usernames to capital
642 $name = $wgContLang->ucfirst( $name );
644 # Reject names containing '#'; these will be cleaned up
645 # with title normalisation, but then it's too late to
647 if( strpos( $name, '#' ) !== false )
650 # Clean up name according to title rules
651 $t = ($validate === 'valid') ?
652 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
653 # Check for invalid titles
654 if( is_null( $t ) ) {
658 # Reject various classes of invalid names
659 $name = $t->getText();
661 $name = $wgAuth->getCanonicalName( $t->getText() );
663 switch ( $validate ) {
667 if ( !User
::isValidUserName( $name ) ) {
672 if ( !User
::isUsableName( $name ) ) {
677 if ( !User
::isCreatableName( $name ) ) {
682 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
688 * Count the number of edits of a user
689 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
691 * @param $uid \int User ID to check
692 * @return \int The user's edit count
694 static function edits( $uid ) {
695 wfProfileIn( __METHOD__
);
696 $dbr = wfGetDB( DB_SLAVE
);
697 // check if the user_editcount field has been initialized
698 $field = $dbr->selectField(
699 'user', 'user_editcount',
700 array( 'user_id' => $uid ),
704 if( $field === null ) { // it has not been initialized. do so.
705 $dbw = wfGetDB( DB_MASTER
);
706 $count = $dbr->selectField(
707 'revision', 'count(*)',
708 array( 'rev_user' => $uid ),
713 array( 'user_editcount' => $count ),
714 array( 'user_id' => $uid ),
720 wfProfileOut( __METHOD__
);
725 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
726 * @todo hash random numbers to improve security, like generateToken()
728 * @return \string New random password
730 static function randomPassword() {
731 global $wgMinimalPasswordLength;
732 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
733 $l = strlen( $pwchars ) - 1;
735 $pwlength = max( 7, $wgMinimalPasswordLength );
736 $digit = mt_rand(0, $pwlength - 1);
738 for ( $i = 0; $i < $pwlength; $i++
) {
739 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
745 * Set cached properties to default.
747 * @note This no longer clears uncached lazy-initialised properties;
748 * the constructor does that instead.
751 function loadDefaults( $name = false ) {
752 wfProfileIn( __METHOD__
);
754 global $wgCookiePrefix;
757 $this->mName
= $name;
758 $this->mRealName
= '';
759 $this->mPassword
= $this->mNewpassword
= '';
760 $this->mNewpassTime
= null;
762 $this->mOptions
= null; # Defer init
764 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
765 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
767 $this->mTouched
= '0'; # Allow any pages to be cached
770 $this->setToken(); # Random
771 $this->mEmailAuthenticated
= null;
772 $this->mEmailToken
= '';
773 $this->mEmailTokenExpires
= null;
774 $this->mRegistration
= wfTimestamp( TS_MW
);
775 $this->mGroups
= array();
777 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
779 wfProfileOut( __METHOD__
);
783 * @deprecated Use wfSetupSession().
785 function SetupSession() {
786 wfDeprecated( __METHOD__
);
791 * Load user data from the session or login cookie. If there are no valid
792 * credentials, initialises the user as an anonymous user.
793 * @return \bool True if the user is logged in, false otherwise.
795 private function loadFromSession() {
796 global $wgMemc, $wgCookiePrefix;
799 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
800 if ( $result !== null ) {
804 if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
805 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
806 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
807 $this->loadDefaults(); // Possible collision!
808 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
809 cookie user ID ($sId) don't match!" );
812 $_SESSION['wsUserID'] = $sId;
813 } else if ( isset( $_SESSION['wsUserID'] ) ) {
814 if ( $_SESSION['wsUserID'] != 0 ) {
815 $sId = $_SESSION['wsUserID'];
817 $this->loadDefaults();
821 $this->loadDefaults();
825 if ( isset( $_SESSION['wsUserName'] ) ) {
826 $sName = $_SESSION['wsUserName'];
827 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
828 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
829 $_SESSION['wsUserName'] = $sName;
831 $this->loadDefaults();
835 $passwordCorrect = FALSE;
837 if ( !$this->loadFromId() ) {
838 # Not a valid ID, loadFromId has switched the object to anon for us
842 if ( isset( $_SESSION['wsToken'] ) ) {
843 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
845 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
846 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
849 # No session or persistent login cookie
850 $this->loadDefaults();
854 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
855 $_SESSION['wsToken'] = $this->mToken
;
856 wfDebug( "Logged in from $from\n" );
859 # Invalid credentials
860 wfDebug( "Can't log in from $from, invalid credentials\n" );
861 $this->loadDefaults();
867 * Load user and user_group data from the database.
868 * $this::mId must be set, this is how the user is identified.
870 * @return \bool True if the user exists, false if the user is anonymous
873 function loadFromDatabase() {
875 $this->mId
= intval( $this->mId
);
877 /** Anonymous user */
879 $this->loadDefaults();
883 $dbr = wfGetDB( DB_MASTER
);
884 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
886 if ( $s !== false ) {
887 # Initialise user table data
888 $this->loadFromRow( $s );
889 $this->mGroups
= null; // deferred
890 $this->getEditCount(); // revalidation for nulls
895 $this->loadDefaults();
901 * Initialize this object from a row from the user table.
903 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
905 function loadFromRow( $row ) {
906 $this->mDataLoaded
= true;
908 if ( isset( $row->user_id
) ) {
909 $this->mId
= $row->user_id
;
911 $this->mName
= $row->user_name
;
912 $this->mRealName
= $row->user_real_name
;
913 $this->mPassword
= $row->user_password
;
914 $this->mNewpassword
= $row->user_newpassword
;
915 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
916 $this->mEmail
= $row->user_email
;
917 $this->decodeOptions( $row->user_options
);
918 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
919 $this->mToken
= $row->user_token
;
920 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
921 $this->mEmailToken
= $row->user_email_token
;
922 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
923 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
924 $this->mEditCount
= $row->user_editcount
;
928 * Load the groups from the database if they aren't already loaded.
931 function loadGroups() {
932 if ( is_null( $this->mGroups
) ) {
933 $dbr = wfGetDB( DB_MASTER
);
934 $res = $dbr->select( 'user_groups',
936 array( 'ug_user' => $this->mId
),
938 $this->mGroups
= array();
939 while( $row = $dbr->fetchObject( $res ) ) {
940 $this->mGroups
[] = $row->ug_group
;
946 * Clear various cached data stored in this object.
947 * @param $reloadFrom \string Reload user and user_groups table data from a
948 * given source. May be "name", "id", "defaults", "session", or false for
951 function clearInstanceCache( $reloadFrom = false ) {
952 $this->mNewtalk
= -1;
953 $this->mDatePreference
= null;
954 $this->mBlockedby
= -1; # Unset
955 $this->mHash
= false;
957 $this->mRights
= null;
958 $this->mEffectiveGroups
= null;
961 $this->mDataLoaded
= false;
962 $this->mFrom
= $reloadFrom;
967 * Combine the language default options with any site-specific options
968 * and add the default language variants.
970 * @return \type{\arrayof{\string}} Array of options
972 static function getDefaultOptions() {
973 global $wgNamespacesToBeSearchedDefault;
975 * Site defaults will override the global/language defaults
977 global $wgDefaultUserOptions, $wgContLang;
978 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
981 * default language setting
983 $variant = $wgContLang->getPreferredVariant( false );
984 $defOpt['variant'] = $variant;
985 $defOpt['language'] = $variant;
987 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
988 $defOpt['searchNs'.$nsnum] = $val;
994 * Get a given default option value.
996 * @param $opt \string Name of option to retrieve
997 * @return \string Default option value
999 public static function getDefaultOption( $opt ) {
1000 $defOpts = self
::getDefaultOptions();
1001 if( isset( $defOpts[$opt] ) ) {
1002 return $defOpts[$opt];
1009 * Get a list of user toggle names
1010 * @return \type{\arrayof{\string}} Array of user toggle names
1012 static function getToggles() {
1014 $extraToggles = array();
1015 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1016 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1021 * Get blocking information
1023 * @param $bFromSlave \bool Whether to check the slave database first. To
1024 * improve performance, non-critical checks are done
1025 * against slaves. Check when actually saving should be
1026 * done against master.
1028 function getBlockedStatus( $bFromSlave = true ) {
1029 global $wgEnableSorbs, $wgProxyWhitelist;
1031 if ( -1 != $this->mBlockedby
) {
1032 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1036 wfProfileIn( __METHOD__
);
1037 wfDebug( __METHOD__
.": checking...\n" );
1039 // Initialize data...
1040 // Otherwise something ends up stomping on $this->mBlockedby when
1041 // things get lazy-loaded later, causing false positive block hits
1042 // due to -1 !== 0. Probably session-related... Nothing should be
1043 // overwriting mBlockedby, surely?
1046 $this->mBlockedby
= 0;
1047 $this->mHideName
= 0;
1048 $this->mAllowUsertalk
= 0;
1051 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1052 # Exempt from all types of IP-block
1057 $this->mBlock
= new Block();
1058 $this->mBlock
->fromMaster( !$bFromSlave );
1059 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1060 wfDebug( __METHOD__
.": Found block.\n" );
1061 $this->mBlockedby
= $this->mBlock
->mBy
;
1062 $this->mBlockreason
= $this->mBlock
->mReason
;
1063 $this->mHideName
= $this->mBlock
->mHideName
;
1064 $this->mAllowUsertalk
= $this->mBlock
->mAllowUsertalk
;
1065 if ( $this->isLoggedIn() ) {
1066 $this->spreadBlock();
1069 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1070 // apply to users. Note that the existence of $this->mBlock is not used to
1071 // check for edit blocks, $this->mBlockedby is instead.
1075 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1077 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1078 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1079 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1083 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1084 if ( $this->inSorbsBlacklist( $ip ) ) {
1085 $this->mBlockedby
= wfMsg( 'sorbs' );
1086 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1092 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1094 wfProfileOut( __METHOD__
);
1098 * Whether the given IP is in the SORBS blacklist.
1100 * @param $ip \string IP to check
1101 * @return \bool True if blacklisted.
1103 function inSorbsBlacklist( $ip ) {
1104 global $wgEnableSorbs, $wgSorbsUrl;
1106 return $wgEnableSorbs &&
1107 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1111 * Whether the given IP is in a given DNS blacklist.
1113 * @param $ip \string IP to check
1114 * @param $base \string URL of the DNS blacklist
1115 * @return \bool True if blacklisted.
1117 function inDnsBlacklist( $ip, $base ) {
1118 wfProfileIn( __METHOD__
);
1122 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1123 if( IP
::isIPv4($ip) ) {
1125 $host = "$ip.$base";
1128 $ipList = gethostbynamel( $host );
1131 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1134 wfDebug( "Requested $host, not found in $base.\n" );
1138 wfProfileOut( __METHOD__
);
1143 * Is this user subject to rate limiting?
1145 * @return \bool True if rate limited
1147 public function isPingLimitable() {
1148 global $wgRateLimitsExcludedGroups;
1149 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1150 // Deprecated, but kept for backwards-compatibility config
1153 return !$this->isAllowed('noratelimit');
1157 * Primitive rate limits: enforce maximum actions per time period
1158 * to put a brake on flooding.
1160 * @note When using a shared cache like memcached, IP-address
1161 * last-hit counters will be shared across wikis.
1163 * @param $action \string Action to enforce; 'edit' if unspecified
1164 * @return \bool True if a rate limiter was tripped
1166 function pingLimiter( $action='edit' ) {
1168 # Call the 'PingLimiter' hook
1170 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1174 global $wgRateLimits;
1175 if( !isset( $wgRateLimits[$action] ) ) {
1179 # Some groups shouldn't trigger the ping limiter, ever
1180 if( !$this->isPingLimitable() )
1183 global $wgMemc, $wgRateLimitLog;
1184 wfProfileIn( __METHOD__
);
1186 $limits = $wgRateLimits[$action];
1188 $id = $this->getId();
1192 if( isset( $limits['anon'] ) && $id == 0 ) {
1193 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1196 if( isset( $limits['user'] ) && $id != 0 ) {
1197 $userLimit = $limits['user'];
1199 if( $this->isNewbie() ) {
1200 if( isset( $limits['newbie'] ) && $id != 0 ) {
1201 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1203 if( isset( $limits['ip'] ) ) {
1204 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1207 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1208 $subnet = $matches[1];
1209 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1212 // Check for group-specific permissions
1213 // If more than one group applies, use the group with the highest limit
1214 foreach ( $this->getGroups() as $group ) {
1215 if ( isset( $limits[$group] ) ) {
1216 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1217 $userLimit = $limits[$group];
1221 // Set the user limit key
1222 if ( $userLimit !== false ) {
1223 wfDebug( __METHOD__
.": effective user limit: $userLimit\n" );
1224 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1228 foreach( $keys as $key => $limit ) {
1229 list( $max, $period ) = $limit;
1230 $summary = "(limit $max in {$period}s)";
1231 $count = $wgMemc->get( $key );
1233 if( $count > $max ) {
1234 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1235 if( $wgRateLimitLog ) {
1236 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1240 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1243 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1244 $wgMemc->add( $key, 1, intval( $period ) );
1246 $wgMemc->incr( $key );
1249 wfProfileOut( __METHOD__
);
1254 * Check if user is blocked
1256 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1257 * @return \bool True if blocked, false otherwise
1259 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1260 wfDebug( "User::isBlocked: enter\n" );
1261 $this->getBlockedStatus( $bFromSlave );
1262 return $this->mBlockedby
!== 0;
1266 * Check if user is blocked from editing a particular article
1268 * @param $title \string Title to check
1269 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1270 * @return \bool True if blocked, false otherwise
1272 function isBlockedFrom( $title, $bFromSlave = false ) {
1273 global $wgBlockAllowsUTEdit;
1274 wfProfileIn( __METHOD__
);
1275 wfDebug( __METHOD__
.": enter\n" );
1277 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1278 $blocked = $this->isBlocked( $bFromSlave );
1279 $allowUsertalk = ($wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false);
1280 # If a user's name is suppressed, they cannot make edits anywhere
1281 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1282 $title->getNamespace() == NS_USER_TALK
) {
1284 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1286 wfProfileOut( __METHOD__
);
1291 * If user is blocked, return the name of the user who placed the block
1292 * @return \string name of blocker
1294 function blockedBy() {
1295 $this->getBlockedStatus();
1296 return $this->mBlockedby
;
1300 * If user is blocked, return the specified reason for the block
1301 * @return \string Blocking reason
1303 function blockedFor() {
1304 $this->getBlockedStatus();
1305 return $this->mBlockreason
;
1309 * Check if user is blocked on all wikis.
1310 * Do not use for actual edit permission checks!
1311 * This is intented for quick UI checks.
1313 * @param $ip \type{\string} IP address, uses current client if none given
1314 * @return \type{\bool} True if blocked, false otherwise
1316 function isBlockedGlobally( $ip = '' ) {
1317 if( $this->mBlockedGlobally
!== null ) {
1318 return $this->mBlockedGlobally
;
1320 // User is already an IP?
1321 if( IP
::isIPAddress( $this->getName() ) ) {
1322 $ip = $this->getName();
1327 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1328 $this->mBlockedGlobally
= (bool)$blocked;
1329 return $this->mBlockedGlobally
;
1333 * Check if user account is locked
1335 * @return \type{\bool} True if locked, false otherwise
1337 function isLocked() {
1338 if( $this->mLocked
!== null ) {
1339 return $this->mLocked
;
1342 $authUser = $wgAuth->getUserInstance( $this );
1343 $this->mLocked
= (bool)$authUser->isLocked();
1344 return $this->mLocked
;
1348 * Check if user account is hidden
1350 * @return \type{\bool} True if hidden, false otherwise
1352 function isHidden() {
1353 if( $this->mHideName
!== null ) {
1354 return $this->mHideName
;
1356 $this->getBlockedStatus();
1357 if( !$this->mHideName
) {
1359 $authUser = $wgAuth->getUserInstance( $this );
1360 $this->mHideName
= (bool)$authUser->isHidden();
1362 return $this->mHideName
;
1366 * Get the user's ID.
1367 * @return \int The user's ID; 0 if the user is anonymous or nonexistent
1370 if( $this->mId
=== null and $this->mName
!== null
1371 and User
::isIP( $this->mName
) ) {
1372 // Special case, we know the user is anonymous
1374 } elseif( $this->mId
=== null ) {
1375 // Don't load if this was initialized from an ID
1382 * Set the user and reload all fields according to a given ID
1383 * @param $v \int User ID to reload
1385 function setId( $v ) {
1387 $this->clearInstanceCache( 'id' );
1391 * Get the user name, or the IP of an anonymous user
1392 * @return \string User's name or IP address
1394 function getName() {
1395 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1396 # Special case optimisation
1397 return $this->mName
;
1400 if ( $this->mName
=== false ) {
1402 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1404 return $this->mName
;
1409 * Set the user name.
1411 * This does not reload fields from the database according to the given
1412 * name. Rather, it is used to create a temporary "nonexistent user" for
1413 * later addition to the database. It can also be used to set the IP
1414 * address for an anonymous user to something other than the current
1417 * @note User::newFromName() has rougly the same function, when the named user
1419 * @param $str \string New user name to set
1421 function setName( $str ) {
1423 $this->mName
= $str;
1427 * Get the user's name escaped by underscores.
1428 * @return \string Username escaped by underscores.
1430 function getTitleKey() {
1431 return str_replace( ' ', '_', $this->getName() );
1435 * Check if the user has new messages.
1436 * @return \bool True if the user has new messages
1438 function getNewtalk() {
1441 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1442 if( $this->mNewtalk
=== -1 ) {
1443 $this->mNewtalk
= false; # reset talk page status
1445 # Check memcached separately for anons, who have no
1446 # entire User object stored in there.
1449 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1450 $newtalk = $wgMemc->get( $key );
1451 if( strval( $newtalk ) !== '' ) {
1452 $this->mNewtalk
= (bool)$newtalk;
1454 // Since we are caching this, make sure it is up to date by getting it
1456 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1457 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1460 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1464 return (bool)$this->mNewtalk
;
1468 * Return the talk page(s) this user has new messages on.
1469 * @return \type{\arrayof{\string}} Array of page URLs
1471 function getNewMessageLinks() {
1473 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1476 if (!$this->getNewtalk())
1478 $up = $this->getUserPage();
1479 $utp = $up->getTalkPage();
1480 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1485 * Internal uncached check for new messages
1488 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1489 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1490 * @param $fromMaster \bool true to fetch from the master, false for a slave
1491 * @return \bool True if the user has new messages
1494 function checkNewtalk( $field, $id, $fromMaster = false ) {
1495 if ( $fromMaster ) {
1496 $db = wfGetDB( DB_MASTER
);
1498 $db = wfGetDB( DB_SLAVE
);
1500 $ok = $db->selectField( 'user_newtalk', $field,
1501 array( $field => $id ), __METHOD__
);
1502 return $ok !== false;
1506 * Add or update the new messages flag
1507 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1508 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1509 * @return \bool True if successful, false otherwise
1512 function updateNewtalk( $field, $id ) {
1513 $dbw = wfGetDB( DB_MASTER
);
1514 $dbw->insert( 'user_newtalk',
1515 array( $field => $id ),
1518 if ( $dbw->affectedRows() ) {
1519 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1522 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1528 * Clear the new messages flag for the given user
1529 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1530 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1531 * @return \bool True if successful, false otherwise
1534 function deleteNewtalk( $field, $id ) {
1535 $dbw = wfGetDB( DB_MASTER
);
1536 $dbw->delete( 'user_newtalk',
1537 array( $field => $id ),
1539 if ( $dbw->affectedRows() ) {
1540 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1543 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1549 * Update the 'You have new messages!' status.
1550 * @param $val \bool Whether the user has new messages
1552 function setNewtalk( $val ) {
1553 if( wfReadOnly() ) {
1558 $this->mNewtalk
= $val;
1560 if( $this->isAnon() ) {
1562 $id = $this->getName();
1565 $id = $this->getId();
1570 $changed = $this->updateNewtalk( $field, $id );
1572 $changed = $this->deleteNewtalk( $field, $id );
1575 if( $this->isAnon() ) {
1576 // Anons have a separate memcached space, since
1577 // user records aren't kept for them.
1578 $key = wfMemcKey( 'newtalk', 'ip', $id );
1579 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1582 $this->invalidateCache();
1587 * Generate a current or new-future timestamp to be stored in the
1588 * user_touched field when we update things.
1589 * @return \string Timestamp in TS_MW format
1591 private static function newTouchedTimestamp() {
1592 global $wgClockSkewFudge;
1593 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1597 * Clear user data from memcached.
1598 * Use after applying fun updates to the database; caller's
1599 * responsibility to update user_touched if appropriate.
1601 * Called implicitly from invalidateCache() and saveSettings().
1603 private function clearSharedCache() {
1607 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1612 * Immediately touch the user data cache for this account.
1613 * Updates user_touched field, and removes account data from memcached
1614 * for reload on the next hit.
1616 function invalidateCache() {
1619 $this->mTouched
= self
::newTouchedTimestamp();
1621 $dbw = wfGetDB( DB_MASTER
);
1622 $dbw->update( 'user',
1623 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1624 array( 'user_id' => $this->mId
),
1627 $this->clearSharedCache();
1632 * Validate the cache for this account.
1633 * @param $timestamp \string A timestamp in TS_MW format
1635 function validateCache( $timestamp ) {
1637 return ($timestamp >= $this->mTouched
);
1641 * Get the user touched timestamp
1643 function getTouched() {
1645 return $this->mTouched
;
1649 * Set the password and reset the random token.
1650 * Calls through to authentication plugin if necessary;
1651 * will have no effect if the auth plugin refuses to
1652 * pass the change through or if the legal password
1655 * As a special case, setting the password to null
1656 * wipes it, so the account cannot be logged in until
1657 * a new password is set, for instance via e-mail.
1659 * @param $str \string New password to set
1660 * @throws PasswordError on failure
1662 function setPassword( $str ) {
1665 if( $str !== null ) {
1666 if( !$wgAuth->allowPasswordChange() ) {
1667 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1670 if( !$this->isValidPassword( $str ) ) {
1671 global $wgMinimalPasswordLength;
1672 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1673 $wgMinimalPasswordLength ) );
1677 if( !$wgAuth->setPassword( $this, $str ) ) {
1678 throw new PasswordError( wfMsg( 'externaldberror' ) );
1681 $this->setInternalPassword( $str );
1687 * Set the password and reset the random token unconditionally.
1689 * @param $str \string New password to set
1691 function setInternalPassword( $str ) {
1695 if( $str === null ) {
1696 // Save an invalid hash...
1697 $this->mPassword
= '';
1699 $this->mPassword
= self
::crypt( $str );
1701 $this->mNewpassword
= '';
1702 $this->mNewpassTime
= null;
1706 * Get the user's current token.
1707 * @return \string Token
1709 function getToken() {
1711 return $this->mToken
;
1715 * Set the random token (used for persistent authentication)
1716 * Called from loadDefaults() among other places.
1718 * @param $token \string If specified, set the token to this value
1721 function setToken( $token = false ) {
1722 global $wgSecretKey, $wgProxyKey;
1725 if ( $wgSecretKey ) {
1726 $key = $wgSecretKey;
1727 } elseif ( $wgProxyKey ) {
1732 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1734 $this->mToken
= $token;
1739 * Set the cookie password
1741 * @param $str \string New cookie password
1744 function setCookiePassword( $str ) {
1746 $this->mCookiePassword
= md5( $str );
1750 * Set the password for a password reminder or new account email
1752 * @param $str \string New password to set
1753 * @param $throttle \bool If true, reset the throttle timestamp to the present
1755 function setNewpassword( $str, $throttle = true ) {
1757 $this->mNewpassword
= self
::crypt( $str );
1759 $this->mNewpassTime
= wfTimestampNow();
1764 * Has password reminder email been sent within the last
1765 * $wgPasswordReminderResendTime hours?
1766 * @return \bool True or false
1768 function isPasswordReminderThrottled() {
1769 global $wgPasswordReminderResendTime;
1771 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1774 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1775 return time() < $expiry;
1779 * Get the user's e-mail address
1780 * @return \string User's email address
1782 function getEmail() {
1784 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1785 return $this->mEmail
;
1789 * Get the timestamp of the user's e-mail authentication
1790 * @return \string TS_MW timestamp
1792 function getEmailAuthenticationTimestamp() {
1794 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1795 return $this->mEmailAuthenticated
;
1799 * Set the user's e-mail address
1800 * @param $str \string New e-mail address
1802 function setEmail( $str ) {
1804 $this->mEmail
= $str;
1805 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1809 * Get the user's real name
1810 * @return \string User's real name
1812 function getRealName() {
1814 return $this->mRealName
;
1818 * Set the user's real name
1819 * @param $str \string New real name
1821 function setRealName( $str ) {
1823 $this->mRealName
= $str;
1827 * Get the user's current setting for a given option.
1829 * @param $oname \string The option to check
1830 * @param $defaultOverride \string A default value returned if the option does not exist
1831 * @return \string User's current value for the option
1832 * @see getBoolOption()
1833 * @see getIntOption()
1835 function getOption( $oname, $defaultOverride = '' ) {
1838 if ( is_null( $this->mOptions
) ) {
1839 if($defaultOverride != '') {
1840 return $defaultOverride;
1842 $this->mOptions
= User
::getDefaultOptions();
1845 if ( array_key_exists( $oname, $this->mOptions
) ) {
1846 return trim( $this->mOptions
[$oname] );
1848 return $defaultOverride;
1853 * Get the user's current setting for a given option, as a boolean value.
1855 * @param $oname \string The option to check
1856 * @return \bool User's current value for the option
1859 function getBoolOption( $oname ) {
1860 return (bool)$this->getOption( $oname );
1865 * Get the user's current setting for a given option, as a boolean value.
1867 * @param $oname \string The option to check
1868 * @param $defaultOverride \int A default value returned if the option does not exist
1869 * @return \int User's current value for the option
1872 function getIntOption( $oname, $defaultOverride=0 ) {
1873 $val = $this->getOption( $oname );
1875 $val = $defaultOverride;
1877 return intval( $val );
1881 * Set the given option for a user.
1883 * @param $oname \string The option to set
1884 * @param $val \mixed New value to set
1886 function setOption( $oname, $val ) {
1888 if ( is_null( $this->mOptions
) ) {
1889 $this->mOptions
= User
::getDefaultOptions();
1891 if ( $oname == 'skin' ) {
1892 # Clear cached skin, so the new one displays immediately in Special:Preferences
1893 unset( $this->mSkin
);
1895 // Filter out any newlines that may have passed through input validation.
1896 // Newlines are used to separate items in the options blob.
1898 $val = str_replace( "\r\n", "\n", $val );
1899 $val = str_replace( "\r", "\n", $val );
1900 $val = str_replace( "\n", " ", $val );
1902 // Explicitly NULL values should refer to defaults
1903 global $wgDefaultUserOptions;
1904 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1905 $val = $wgDefaultUserOptions[$oname];
1907 $this->mOptions
[$oname] = $val;
1911 * Get the user's preferred date format.
1912 * @return \string User's preferred date format
1914 function getDatePreference() {
1915 // Important migration for old data rows
1916 if ( is_null( $this->mDatePreference
) ) {
1918 $value = $this->getOption( 'date' );
1919 $map = $wgLang->getDatePreferenceMigrationMap();
1920 if ( isset( $map[$value] ) ) {
1921 $value = $map[$value];
1923 $this->mDatePreference
= $value;
1925 return $this->mDatePreference
;
1929 * Get the permissions this user has.
1930 * @return \type{\arrayof{\string}} Array of permission names
1932 function getRights() {
1933 if ( is_null( $this->mRights
) ) {
1934 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1935 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1936 // Force reindexation of rights when a hook has unset one of them
1937 $this->mRights
= array_values( $this->mRights
);
1939 return $this->mRights
;
1943 * Get the list of explicit group memberships this user has.
1944 * The implicit * and user groups are not included.
1945 * @return \type{\arrayof{\string}} Array of internal group names
1947 function getGroups() {
1949 return $this->mGroups
;
1953 * Get the list of implicit group memberships this user has.
1954 * This includes all explicit groups, plus 'user' if logged in,
1955 * '*' for all accounts and autopromoted groups
1956 * @param $recache \bool Whether to avoid the cache
1957 * @return \type{\arrayof{\string}} Array of internal group names
1959 function getEffectiveGroups( $recache = false ) {
1960 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1961 $this->mEffectiveGroups
= $this->getGroups();
1962 $this->mEffectiveGroups
[] = '*';
1963 if( $this->getId() ) {
1964 $this->mEffectiveGroups
[] = 'user';
1966 $this->mEffectiveGroups
= array_unique( array_merge(
1967 $this->mEffectiveGroups
,
1968 Autopromote
::getAutopromoteGroups( $this )
1971 # Hook for additional groups
1972 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1975 return $this->mEffectiveGroups
;
1979 * Get the user's edit count.
1980 * @return \int User'e edit count
1982 function getEditCount() {
1984 if ( !isset( $this->mEditCount
) ) {
1985 /* Populate the count, if it has not been populated yet */
1986 $this->mEditCount
= User
::edits($this->mId
);
1988 return $this->mEditCount
;
1996 * Add the user to the given group.
1997 * This takes immediate effect.
1998 * @param $group \string Name of the group to add
2000 function addGroup( $group ) {
2001 $dbw = wfGetDB( DB_MASTER
);
2002 if( $this->getId() ) {
2003 $dbw->insert( 'user_groups',
2005 'ug_user' => $this->getID(),
2006 'ug_group' => $group,
2009 array( 'IGNORE' ) );
2012 $this->loadGroups();
2013 $this->mGroups
[] = $group;
2014 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2016 $this->invalidateCache();
2020 * Remove the user from the given group.
2021 * This takes immediate effect.
2022 * @param $group \string Name of the group to remove
2024 function removeGroup( $group ) {
2026 $dbw = wfGetDB( DB_MASTER
);
2027 $dbw->delete( 'user_groups',
2029 'ug_user' => $this->getID(),
2030 'ug_group' => $group,
2032 'User::removeGroup' );
2034 $this->loadGroups();
2035 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2036 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2038 $this->invalidateCache();
2043 * Get whether the user is logged in
2044 * @return \bool True or false
2046 function isLoggedIn() {
2047 return $this->getID() != 0;
2051 * Get whether the user is anonymous
2052 * @return \bool True or false
2055 return !$this->isLoggedIn();
2059 * Get whether the user is a bot
2060 * @return \bool True or false
2064 wfDeprecated( __METHOD__
);
2065 return $this->isAllowed( 'bot' );
2069 * Check if user is allowed to access a feature / make an action
2070 * @param $action \string action to be checked
2071 * @return \bool True if action is allowed, else false
2073 function isAllowed($action='') {
2074 if ( $action === '' )
2075 // In the spirit of DWIM
2078 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2079 # by misconfiguration: 0 == 'foo'
2080 return in_array( $action, $this->getRights(), true );
2084 * Check whether to enable recent changes patrol features for this user
2085 * @return \bool True or false
2087 public function useRCPatrol() {
2088 global $wgUseRCPatrol;
2089 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2093 * Check whether to enable new pages patrol features for this user
2094 * @return \bool True or false
2096 public function useNPPatrol() {
2097 global $wgUseRCPatrol, $wgUseNPPatrol;
2098 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2102 * Get the current skin, loading it if required
2103 * @return \type{Skin} Current skin
2104 * @todo FIXME : need to check the old failback system [AV]
2106 function &getSkin() {
2107 global $wgRequest, $wgAllowUserSkin, $wgDefaultSkin;
2108 if ( ! isset( $this->mSkin
) ) {
2109 wfProfileIn( __METHOD__
);
2111 if( $wgAllowUserSkin ) {
2113 $userSkin = $this->getOption( 'skin' );
2114 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2116 # if we're not allowing users to override, then use the default
2117 $userSkin = $wgDefaultSkin;
2120 $this->mSkin
=& Skin
::newFromKey( $userSkin );
2121 wfProfileOut( __METHOD__
);
2123 return $this->mSkin
;
2127 * Check the watched status of an article.
2128 * @param $title \type{Title} Title of the article to look at
2129 * @return \bool True if article is watched
2131 function isWatched( $title ) {
2132 $wl = WatchedItem
::fromUserTitle( $this, $title );
2133 return $wl->isWatched();
2138 * @param $title \type{Title} Title of the article to look at
2140 function addWatch( $title ) {
2141 $wl = WatchedItem
::fromUserTitle( $this, $title );
2143 $this->invalidateCache();
2147 * Stop watching an article.
2148 * @param $title \type{Title} Title of the article to look at
2150 function removeWatch( $title ) {
2151 $wl = WatchedItem
::fromUserTitle( $this, $title );
2153 $this->invalidateCache();
2157 * Clear the user's notification timestamp for the given title.
2158 * If e-notif e-mails are on, they will receive notification mails on
2159 * the next change of the page if it's watched etc.
2160 * @param $title \type{Title} Title of the article to look at
2162 function clearNotification( &$title ) {
2163 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2165 # Do nothing if the database is locked to writes
2166 if( wfReadOnly() ) {
2170 if ($title->getNamespace() == NS_USER_TALK
&&
2171 $title->getText() == $this->getName() ) {
2172 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2174 $this->setNewtalk( false );
2177 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2181 if( $this->isAnon() ) {
2182 // Nothing else to do...
2186 // Only update the timestamp if the page is being watched.
2187 // The query to find out if it is watched is cached both in memcached and per-invocation,
2188 // and when it does have to be executed, it can be on a slave
2189 // If this is the user's newtalk page, we always update the timestamp
2190 if ($title->getNamespace() == NS_USER_TALK
&&
2191 $title->getText() == $wgUser->getName())
2194 } elseif ( $this->getId() == $wgUser->getId() ) {
2195 $watched = $title->userIsWatching();
2200 // If the page is watched by the user (or may be watched), update the timestamp on any
2201 // any matching rows
2203 $dbw = wfGetDB( DB_MASTER
);
2204 $dbw->update( 'watchlist',
2206 'wl_notificationtimestamp' => NULL
2207 ), array( /* WHERE */
2208 'wl_title' => $title->getDBkey(),
2209 'wl_namespace' => $title->getNamespace(),
2210 'wl_user' => $this->getID()
2217 * Resets all of the given user's page-change notification timestamps.
2218 * If e-notif e-mails are on, they will receive notification mails on
2219 * the next change of any watched page.
2221 * @param $currentUser \int User ID
2223 function clearAllNotifications( $currentUser ) {
2224 global $wgUseEnotif, $wgShowUpdatedMarker;
2225 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2226 $this->setNewtalk( false );
2229 if( $currentUser != 0 ) {
2230 $dbw = wfGetDB( DB_MASTER
);
2231 $dbw->update( 'watchlist',
2233 'wl_notificationtimestamp' => NULL
2234 ), array( /* WHERE */
2235 'wl_user' => $currentUser
2238 # We also need to clear here the "you have new message" notification for the own user_talk page
2239 # This is cleared one page view later in Article::viewUpdates();
2244 * Encode this user's options as a string
2245 * @return \string Encoded options
2248 function encodeOptions() {
2250 if ( is_null( $this->mOptions
) ) {
2251 $this->mOptions
= User
::getDefaultOptions();
2254 foreach ( $this->mOptions
as $oname => $oval ) {
2255 array_push( $a, $oname.'='.$oval );
2257 $s = implode( "\n", $a );
2262 * Set this user's options from an encoded string
2263 * @param $str \string Encoded options to import
2266 function decodeOptions( $str ) {
2267 $this->mOptions
= array();
2268 $a = explode( "\n", $str );
2269 foreach ( $a as $s ) {
2271 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2272 $this->mOptions
[$m[1]] = $m[2];
2278 * Set a cookie on the user's client. Wrapper for
2279 * WebResponse::setCookie
2280 * @param $name \string Name of the cookie to set
2281 * @param $value \string Value to set
2282 * @param $exp \int Expiration time, as a UNIX time value;
2283 * if 0 or not specified, use the default $wgCookieExpiration
2285 protected function setCookie( $name, $value, $exp=0 ) {
2287 $wgRequest->response()->setcookie( $name, $value, $exp );
2291 * Clear a cookie on the user's client
2292 * @param $name \string Name of the cookie to clear
2294 protected function clearCookie( $name ) {
2295 $this->setCookie( $name, '', time() - 86400 );
2299 * Set the default cookies for this session on the user's client.
2301 function setCookies() {
2303 if ( 0 == $this->mId
) return;
2305 'wsUserID' => $this->mId
,
2306 'wsToken' => $this->mToken
,
2307 'wsUserName' => $this->getName()
2310 'UserID' => $this->mId
,
2311 'UserName' => $this->getName(),
2313 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2314 $cookies['Token'] = $this->mToken
;
2316 $cookies['Token'] = false;
2319 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2320 #check for null, since the hook could cause a null value
2321 if ( !is_null( $session ) && !is_null( $_SESSION ) ){
2322 $_SESSION = $session +
$_SESSION;
2324 foreach ( $cookies as $name => $value ) {
2325 if ( $value === false ) {
2326 $this->clearCookie( $name );
2328 $this->setCookie( $name, $value );
2334 * Log this user out.
2338 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2344 * Clear the user's cookies and session, and reset the instance cache.
2348 function doLogout() {
2349 $this->clearInstanceCache( 'defaults' );
2351 $_SESSION['wsUserID'] = 0;
2353 $this->clearCookie( 'UserID' );
2354 $this->clearCookie( 'Token' );
2356 # Remember when user logged out, to prevent seeing cached pages
2357 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2361 * Save this user's settings into the database.
2362 * @todo Only rarely do all these fields need to be set!
2364 function saveSettings() {
2366 if ( wfReadOnly() ) { return; }
2367 if ( 0 == $this->mId
) { return; }
2369 $this->mTouched
= self
::newTouchedTimestamp();
2371 $dbw = wfGetDB( DB_MASTER
);
2372 $dbw->update( 'user',
2374 'user_name' => $this->mName
,
2375 'user_password' => $this->mPassword
,
2376 'user_newpassword' => $this->mNewpassword
,
2377 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2378 'user_real_name' => $this->mRealName
,
2379 'user_email' => $this->mEmail
,
2380 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2381 'user_options' => $this->encodeOptions(),
2382 'user_touched' => $dbw->timestamp($this->mTouched
),
2383 'user_token' => $this->mToken
,
2384 'user_email_token' => $this->mEmailToken
,
2385 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2386 ), array( /* WHERE */
2387 'user_id' => $this->mId
2390 wfRunHooks( 'UserSaveSettings', array( $this ) );
2391 $this->clearSharedCache();
2392 $this->getUserPage()->invalidateCache();
2396 * If only this user's username is known, and it exists, return the user ID.
2398 function idForName() {
2399 $s = trim( $this->getName() );
2400 if ( $s === '' ) return 0;
2402 $dbr = wfGetDB( DB_SLAVE
);
2403 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2404 if ( $id === false ) {
2411 * Add a user to the database, return the user object
2413 * @param $name \string Username to add
2414 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2415 * - password The user's password. Password logins will be disabled if this is omitted.
2416 * - newpassword A temporary password mailed to the user
2417 * - email The user's email address
2418 * - email_authenticated The email authentication timestamp
2419 * - real_name The user's real name
2420 * - options An associative array of non-default options
2421 * - token Random authentication token. Do not set.
2422 * - registration Registration timestamp. Do not set.
2424 * @return \type{User} A new User object, or null if the username already exists
2426 static function createNew( $name, $params = array() ) {
2429 if ( isset( $params['options'] ) ) {
2430 $user->mOptions
= $params['options'] +
$user->mOptions
;
2431 unset( $params['options'] );
2433 $dbw = wfGetDB( DB_MASTER
);
2434 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2436 'user_id' => $seqVal,
2437 'user_name' => $name,
2438 'user_password' => $user->mPassword
,
2439 'user_newpassword' => $user->mNewpassword
,
2440 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2441 'user_email' => $user->mEmail
,
2442 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2443 'user_real_name' => $user->mRealName
,
2444 'user_options' => $user->encodeOptions(),
2445 'user_token' => $user->mToken
,
2446 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2447 'user_editcount' => 0,
2449 foreach ( $params as $name => $value ) {
2450 $fields["user_$name"] = $value;
2452 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2453 if ( $dbw->affectedRows() ) {
2454 $newUser = User
::newFromId( $dbw->insertId() );
2462 * Add this existing user object to the database
2464 function addToDatabase() {
2466 $dbw = wfGetDB( DB_MASTER
);
2467 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2468 $dbw->insert( 'user',
2470 'user_id' => $seqVal,
2471 'user_name' => $this->mName
,
2472 'user_password' => $this->mPassword
,
2473 'user_newpassword' => $this->mNewpassword
,
2474 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2475 'user_email' => $this->mEmail
,
2476 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2477 'user_real_name' => $this->mRealName
,
2478 'user_options' => $this->encodeOptions(),
2479 'user_token' => $this->mToken
,
2480 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2481 'user_editcount' => 0,
2484 $this->mId
= $dbw->insertId();
2486 // Clear instance cache other than user table data, which is already accurate
2487 $this->clearInstanceCache();
2491 * If this (non-anonymous) user is blocked, block any IP address
2492 * they've successfully logged in from.
2494 function spreadBlock() {
2495 wfDebug( __METHOD__
."()\n" );
2497 if ( $this->mId
== 0 ) {
2501 $userblock = Block
::newFromDB( '', $this->mId
);
2502 if ( !$userblock ) {
2506 $userblock->doAutoblock( wfGetIp() );
2511 * Generate a string which will be different for any combination of
2512 * user options which would produce different parser output.
2513 * This will be used as part of the hash key for the parser cache,
2514 * so users will the same options can share the same cached data
2517 * Extensions which require it should install 'PageRenderingHash' hook,
2518 * which will give them a chance to modify this key based on their own
2521 * @return \string Page rendering hash
2523 function getPageRenderingHash() {
2524 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2526 return $this->mHash
;
2529 // stubthreshold is only included below for completeness,
2530 // it will always be 0 when this function is called by parsercache.
2532 $confstr = $this->getOption( 'math' );
2533 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2534 if ( $wgUseDynamicDates ) {
2535 $confstr .= '!' . $this->getDatePreference();
2537 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2538 $confstr .= '!' . $wgLang->getCode();
2539 $confstr .= '!' . $this->getOption( 'thumbsize' );
2540 // add in language specific options, if any
2541 $extra = $wgContLang->getExtraHashOptions();
2544 $confstr .= $wgRenderHashAppend;
2546 // Give a chance for extensions to modify the hash, if they have
2547 // extra options or other effects on the parser cache.
2548 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2550 // Make it a valid memcached key fragment
2551 $confstr = str_replace( ' ', '_', $confstr );
2552 $this->mHash
= $confstr;
2557 * Get whether the user is explicitly blocked from account creation.
2558 * @return \bool True if blocked
2560 function isBlockedFromCreateAccount() {
2561 $this->getBlockedStatus();
2562 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2566 * Get whether the user is blocked from using Special:Emailuser.
2567 * @return \bool True if blocked
2569 function isBlockedFromEmailuser() {
2570 $this->getBlockedStatus();
2571 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2575 * Get whether the user is allowed to create an account.
2576 * @return \bool True if allowed
2578 function isAllowedToCreateAccount() {
2579 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2585 function setLoaded( $loaded ) {
2586 wfDeprecated( __METHOD__
);
2590 * Get this user's personal page title.
2592 * @return \type{Title} User's personal page title
2594 function getUserPage() {
2595 return Title
::makeTitle( NS_USER
, $this->getName() );
2599 * Get this user's talk page title.
2601 * @return \type{Title} User's talk page title
2603 function getTalkPage() {
2604 $title = $this->getUserPage();
2605 return $title->getTalkPage();
2609 * Get the maximum valid user ID.
2610 * @return \int User ID
2613 function getMaxID() {
2614 static $res; // cache
2616 if ( isset( $res ) )
2619 $dbr = wfGetDB( DB_SLAVE
);
2620 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2625 * Determine whether the user is a newbie. Newbies are either
2626 * anonymous IPs, or the most recently created accounts.
2627 * @return \bool True if the user is a newbie
2629 function isNewbie() {
2630 return !$this->isAllowed( 'autoconfirmed' );
2634 * Is the user active? We check to see if they've made at least
2635 * X number of edits in the last Y days.
2637 * @return \bool True if the user is active, false if not.
2639 public function isActiveEditor() {
2640 global $wgActiveUserEditCount, $wgActiveUserDays;
2641 $dbr = wfGetDB( DB_SLAVE
);
2643 // Stolen without shame from RC
2644 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2645 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
2646 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2648 $res = $dbr->select( 'revision', '1',
2649 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2651 array('LIMIT' => $wgActiveUserEditCount ) );
2653 $count = $dbr->numRows($res);
2654 $dbr->freeResult($res);
2656 return $count == $wgActiveUserEditCount;
2660 * Check to see if the given clear-text password is one of the accepted passwords
2661 * @param $password \string user password.
2662 * @return \bool True if the given password is correct, otherwise False.
2664 function checkPassword( $password ) {
2668 // Even though we stop people from creating passwords that
2669 // are shorter than this, doesn't mean people wont be able
2670 // to. Certain authentication plugins do NOT want to save
2671 // domain passwords in a mysql database, so we should
2672 // check this (incase $wgAuth->strict() is false).
2673 if( !$this->isValidPassword( $password ) ) {
2677 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2679 } elseif( $wgAuth->strict() ) {
2680 /* Auth plugin doesn't allow local authentication */
2682 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2683 /* Auth plugin doesn't allow local authentication for this user name */
2686 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2688 } elseif ( function_exists( 'iconv' ) ) {
2689 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2690 # Check for this with iconv
2691 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2692 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2700 * Check if the given clear-text password matches the temporary password
2701 * sent by e-mail for password reset operations.
2702 * @return \bool True if matches, false otherwise
2704 function checkTemporaryPassword( $plaintext ) {
2705 return self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() );
2709 * Initialize (if necessary) and return a session token value
2710 * which can be used in edit forms to show that the user's
2711 * login credentials aren't being hijacked with a foreign form
2714 * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2715 * @return \string The new edit token
2717 function editToken( $salt = '' ) {
2718 if ( $this->isAnon() ) {
2719 return EDIT_TOKEN_SUFFIX
;
2721 if( !isset( $_SESSION['wsEditToken'] ) ) {
2722 $token = $this->generateToken();
2723 $_SESSION['wsEditToken'] = $token;
2725 $token = $_SESSION['wsEditToken'];
2727 if( is_array( $salt ) ) {
2728 $salt = implode( '|', $salt );
2730 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2735 * Generate a looking random token for various uses.
2737 * @param $salt \string Optional salt value
2738 * @return \string The new random token
2740 function generateToken( $salt = '' ) {
2741 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2742 return md5( $token . $salt );
2746 * Check given value against the token value stored in the session.
2747 * A match should confirm that the form was submitted from the
2748 * user's own login session, not a form submission from a third-party
2751 * @param $val \string Input value to compare
2752 * @param $salt \string Optional function-specific data for hashing
2753 * @return \bool Whether the token matches
2755 function matchEditToken( $val, $salt = '' ) {
2756 $sessionToken = $this->editToken( $salt );
2757 if ( $val != $sessionToken ) {
2758 wfDebug( "User::matchEditToken: broken session data\n" );
2760 return $val == $sessionToken;
2764 * Check given value against the token value stored in the session,
2765 * ignoring the suffix.
2767 * @param $val \string Input value to compare
2768 * @param $salt \string Optional function-specific data for hashing
2769 * @return \bool Whether the token matches
2771 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2772 $sessionToken = $this->editToken( $salt );
2773 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2777 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2778 * mail to the user's given address.
2780 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure.
2782 function sendConfirmationMail() {
2784 $expiration = null; // gets passed-by-ref and defined in next line.
2785 $token = $this->confirmationToken( $expiration );
2786 $url = $this->confirmationTokenUrl( $token );
2787 $invalidateURL = $this->invalidationTokenUrl( $token );
2788 $this->saveSettings();
2790 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2791 wfMsg( 'confirmemail_body',
2795 $wgLang->timeanddate( $expiration, false ),
2800 * Send an e-mail to this user's account. Does not check for
2801 * confirmed status or validity.
2803 * @param $subject \string Message subject
2804 * @param $body \string Message body
2805 * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2806 * @param $replyto \string Reply-To address
2807 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure
2809 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2810 if( is_null( $from ) ) {
2811 global $wgPasswordSender;
2812 $from = $wgPasswordSender;
2815 $to = new MailAddress( $this );
2816 $sender = new MailAddress( $from );
2817 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2821 * Generate, store, and return a new e-mail confirmation code.
2822 * A hash (unsalted, since it's used as a key) is stored.
2824 * @note Call saveSettings() after calling this function to commit
2825 * this change to the database.
2827 * @param[out] &$expiration \mixed Accepts the expiration time
2828 * @return \string New token
2831 function confirmationToken( &$expiration ) {
2833 $expires = $now +
7 * 24 * 60 * 60;
2834 $expiration = wfTimestamp( TS_MW
, $expires );
2835 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2836 $hash = md5( $token );
2838 $this->mEmailToken
= $hash;
2839 $this->mEmailTokenExpires
= $expiration;
2844 * Return a URL the user can use to confirm their email address.
2845 * @param $token \string Accepts the email confirmation token
2846 * @return \string New token URL
2849 function confirmationTokenUrl( $token ) {
2850 return $this->getTokenUrl( 'ConfirmEmail', $token );
2853 * Return a URL the user can use to invalidate their email address.
2854 * @param $token \string Accepts the email confirmation token
2855 * @return \string New token URL
2858 function invalidationTokenUrl( $token ) {
2859 return $this->getTokenUrl( 'Invalidateemail', $token );
2863 * Internal function to format the e-mail validation/invalidation URLs.
2864 * This uses $wgArticlePath directly as a quickie hack to use the
2865 * hardcoded English names of the Special: pages, for ASCII safety.
2867 * @note Since these URLs get dropped directly into emails, using the
2868 * short English names avoids insanely long URL-encoded links, which
2869 * also sometimes can get corrupted in some browsers/mailers
2870 * (bug 6957 with Gmail and Internet Explorer).
2872 * @param $page \string Special page
2873 * @param $token \string Token
2874 * @return \string Formatted URL
2876 protected function getTokenUrl( $page, $token ) {
2877 global $wgArticlePath;
2881 "Special:$page/$token",
2886 * Mark the e-mail address confirmed.
2888 * @note Call saveSettings() after calling this function to commit the change.
2890 function confirmEmail() {
2891 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2896 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2897 * address if it was already confirmed.
2899 * @note Call saveSettings() after calling this function to commit the change.
2901 function invalidateEmail() {
2903 $this->mEmailToken
= null;
2904 $this->mEmailTokenExpires
= null;
2905 $this->setEmailAuthenticationTimestamp( null );
2910 * Set the e-mail authentication timestamp.
2911 * @param $timestamp \string TS_MW timestamp
2913 function setEmailAuthenticationTimestamp( $timestamp ) {
2915 $this->mEmailAuthenticated
= $timestamp;
2916 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2920 * Is this user allowed to send e-mails within limits of current
2921 * site configuration?
2922 * @return \bool True if allowed
2924 function canSendEmail() {
2925 global $wgEnableEmail, $wgEnableUserEmail;
2926 if( !$wgEnableEmail ||
!$wgEnableUserEmail ) {
2929 $canSend = $this->isEmailConfirmed();
2930 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2935 * Is this user allowed to receive e-mails within limits of current
2936 * site configuration?
2937 * @return \bool True if allowed
2939 function canReceiveEmail() {
2940 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2944 * Is this user's e-mail address valid-looking and confirmed within
2945 * limits of the current site configuration?
2947 * @note If $wgEmailAuthentication is on, this may require the user to have
2948 * confirmed their address by returning a code or using a password
2949 * sent to the address from the wiki.
2951 * @return \bool True if confirmed
2953 function isEmailConfirmed() {
2954 global $wgEmailAuthentication;
2957 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2958 if( $this->isAnon() )
2960 if( !self
::isValidEmailAddr( $this->mEmail
) )
2962 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2971 * Check whether there is an outstanding request for e-mail confirmation.
2972 * @return \bool True if pending
2974 function isEmailConfirmationPending() {
2975 global $wgEmailAuthentication;
2976 return $wgEmailAuthentication &&
2977 !$this->isEmailConfirmed() &&
2978 $this->mEmailToken
&&
2979 $this->mEmailTokenExpires
> wfTimestamp();
2983 * Get the timestamp of account creation.
2985 * @return \types{\string,\bool} string Timestamp of account creation, or false for
2986 * non-existent/anonymous user accounts.
2988 public function getRegistration() {
2989 return $this->mId
> 0
2990 ?
$this->mRegistration
2995 * Get the permissions associated with a given list of groups
2997 * @param $groups \type{\arrayof{\string}} List of internal group names
2998 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3000 static function getGroupPermissions( $groups ) {
3001 global $wgGroupPermissions;
3003 foreach( $groups as $group ) {
3004 if( isset( $wgGroupPermissions[$group] ) ) {
3005 $rights = array_merge( $rights,
3006 // array_filter removes empty items
3007 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3010 return array_unique($rights);
3014 * Get all the groups who have a given permission
3016 * @param $role \string Role to check
3017 * @return \type{\arrayof{\string}} List of internal group names with the given permission
3019 static function getGroupsWithPermission( $role ) {
3020 global $wgGroupPermissions;
3021 $allowedGroups = array();
3022 foreach ( $wgGroupPermissions as $group => $rights ) {
3023 if ( isset( $rights[$role] ) && $rights[$role] ) {
3024 $allowedGroups[] = $group;
3027 return $allowedGroups;
3031 * Get the localized descriptive name for a group, if it exists
3033 * @param $group \string Internal group name
3034 * @return \string Localized descriptive group name
3036 static function getGroupName( $group ) {
3037 global $wgMessageCache;
3038 $wgMessageCache->loadAllMessages();
3039 $key = "group-$group";
3040 $name = wfMsg( $key );
3041 return $name == '' ||
wfEmptyMsg( $key, $name )
3047 * Get the localized descriptive name for a member of a group, if it exists
3049 * @param $group \string Internal group name
3050 * @return \string Localized name for group member
3052 static function getGroupMember( $group ) {
3053 global $wgMessageCache;
3054 $wgMessageCache->loadAllMessages();
3055 $key = "group-$group-member";
3056 $name = wfMsg( $key );
3057 return $name == '' ||
wfEmptyMsg( $key, $name )
3063 * Return the set of defined explicit groups.
3064 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3065 * are not included, as they are defined automatically, not in the database.
3066 * @return \type{\arrayof{\string}} Array of internal group names
3068 static function getAllGroups() {
3069 global $wgGroupPermissions;
3071 array_keys( $wgGroupPermissions ),
3072 self
::getImplicitGroups()
3077 * Get a list of all available permissions.
3078 * @return \type{\arrayof{\string}} Array of permission names
3080 static function getAllRights() {
3081 if ( self
::$mAllRights === false ) {
3082 global $wgAvailableRights;
3083 if ( count( $wgAvailableRights ) ) {
3084 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3086 self
::$mAllRights = self
::$mCoreRights;
3088 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3090 return self
::$mAllRights;
3094 * Get a list of implicit groups
3095 * @return \type{\arrayof{\string}} Array of internal group names
3097 public static function getImplicitGroups() {
3098 global $wgImplicitGroups;
3099 $groups = $wgImplicitGroups;
3100 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3105 * Get the title of a page describing a particular group
3107 * @param $group \string Internal group name
3108 * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3110 static function getGroupPage( $group ) {
3111 global $wgMessageCache;
3112 $wgMessageCache->loadAllMessages();
3113 $page = wfMsgForContent( 'grouppage-' . $group );
3114 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3115 $title = Title
::newFromText( $page );
3116 if( is_object( $title ) )
3123 * Create a link to the group in HTML, if available;
3124 * else return the group name.
3126 * @param $group \string Internal name of the group
3127 * @param $text \string The text of the link
3128 * @return \string HTML link to the group
3130 static function makeGroupLinkHTML( $group, $text = '' ) {
3132 $text = self
::getGroupName( $group );
3134 $title = self
::getGroupPage( $group );
3137 $sk = $wgUser->getSkin();
3138 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3145 * Create a link to the group in Wikitext, if available;
3146 * else return the group name.
3148 * @param $group \string Internal name of the group
3149 * @param $text \string The text of the link
3150 * @return \string Wikilink to the group
3152 static function makeGroupLinkWiki( $group, $text = '' ) {
3154 $text = self
::getGroupName( $group );
3156 $title = self
::getGroupPage( $group );
3158 $page = $title->getPrefixedText();
3159 return "[[$page|$text]]";
3166 * Increment the user's edit-count field.
3167 * Will have no effect for anonymous users.
3169 function incEditCount() {
3170 if( !$this->isAnon() ) {
3171 $dbw = wfGetDB( DB_MASTER
);
3172 $dbw->update( 'user',
3173 array( 'user_editcount=user_editcount+1' ),
3174 array( 'user_id' => $this->getId() ),
3177 // Lazy initialization check...
3178 if( $dbw->affectedRows() == 0 ) {
3179 // Pull from a slave to be less cruel to servers
3180 // Accuracy isn't the point anyway here
3181 $dbr = wfGetDB( DB_SLAVE
);
3182 $count = $dbr->selectField( 'revision',
3184 array( 'rev_user' => $this->getId() ),
3187 // Now here's a goddamn hack...
3188 if( $dbr !== $dbw ) {
3189 // If we actually have a slave server, the count is
3190 // at least one behind because the current transaction
3191 // has not been committed and replicated.
3194 // But if DB_SLAVE is selecting the master, then the
3195 // count we just read includes the revision that was
3196 // just added in the working transaction.
3199 $dbw->update( 'user',
3200 array( 'user_editcount' => $count ),
3201 array( 'user_id' => $this->getId() ),
3205 // edit count in user cache too
3206 $this->invalidateCache();
3210 * Get the description of a given right
3212 * @param $right \string Right to query
3213 * @return \string Localized description of the right
3215 static function getRightDescription( $right ) {
3216 global $wgMessageCache;
3217 $wgMessageCache->loadAllMessages();
3218 $key = "right-$right";
3219 $name = wfMsg( $key );
3220 return $name == '' ||
wfEmptyMsg( $key, $name )
3226 * Make an old-style password hash
3228 * @param $password \string Plain-text password
3229 * @param $userId \string User ID
3230 * @return \string Password hash
3232 static function oldCrypt( $password, $userId ) {
3233 global $wgPasswordSalt;
3234 if ( $wgPasswordSalt ) {
3235 return md5( $userId . '-' . md5( $password ) );
3237 return md5( $password );
3242 * Make a new-style password hash
3244 * @param $password \string Plain-text password
3245 * @param $salt \string Optional salt, may be random or the user ID.
3246 * If unspecified or false, will generate one automatically
3247 * @return \string Password hash
3249 static function crypt( $password, $salt = false ) {
3250 global $wgPasswordSalt;
3253 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3257 if( $wgPasswordSalt ) {
3258 if ( $salt === false ) {
3259 $salt = substr( wfGenerateToken(), 0, 8 );
3261 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3263 return ':A:' . md5( $password );
3268 * Compare a password hash with a plain-text password. Requires the user
3269 * ID if there's a chance that the hash is an old-style hash.
3271 * @param $hash \string Password hash
3272 * @param $password \string Plain-text password to compare
3273 * @param $userId \string User ID for old-style password salt
3276 static function comparePasswords( $hash, $password, $userId = false ) {
3278 $type = substr( $hash, 0, 3 );
3281 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3285 if ( $type == ':A:' ) {
3287 return md5( $password ) === substr( $hash, 3 );
3288 } elseif ( $type == ':B:' ) {
3290 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3291 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3294 return self
::oldCrypt( $password, $userId ) === $hash;
3299 * Add a newuser log entry for this user
3300 * @param $byEmail Boolean: account made by email?
3302 public function addNewUserLogEntry( $byEmail = false ) {
3303 global $wgUser, $wgContLang, $wgNewUserLog;
3304 if( empty($wgNewUserLog) ) {
3305 return true; // disabled
3307 $talk = $wgContLang->getFormattedNsText( NS_TALK
);
3308 if( $this->getName() == $wgUser->getName() ) {
3312 $action = 'create2';
3313 $message = $byEmail ?
wfMsgForContent( 'newuserlog-byemail' ) : '';
3315 $log = new LogPage( 'newusers' );
3316 $log->addEntry( $action, $this->getUserPage(), $message, array( $this->getId() ) );
3321 * Add an autocreate newuser log entry for this user
3322 * Used by things like CentralAuth and perhaps other authplugins.
3324 public function addNewUserLogEntryAutoCreate() {
3325 global $wgNewUserLog;
3326 if( empty($wgNewUserLog) ) {
3327 return true; // disabled
3329 $log = new LogPage( 'newusers', false );
3330 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );