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(
154 'move-rootuserpages',
176 * \string Cached results of getAllRights()
178 static $mAllRights = false;
180 /** @name Cache variables */
182 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
183 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
184 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
188 * \bool Whether the cache variables have been loaded.
190 var $mDataLoaded, $mAuthLoaded;
193 * \string Initialization data source if mDataLoaded==false. May be one of:
194 * - 'defaults' anonymous user initialised from class defaults
195 * - 'name' initialise from mName
196 * - 'id' initialise from mId
197 * - 'session' log in from cookies or session if possible
199 * Use the User::newFrom*() family of functions to set this.
203 /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
205 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
206 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
207 $mLocked, $mHideName;
211 * Lightweight constructor for an anonymous user.
212 * Use the User::newFrom* factory functions for other kinds of users.
216 * @see newFromConfirmationCode()
217 * @see newFromSession()
221 $this->clearInstanceCache( 'defaults' );
225 * Load the user table data for this object from the source given by mFrom.
228 if ( $this->mDataLoaded
) {
231 wfProfileIn( __METHOD__
);
233 # Set it now to avoid infinite recursion in accessors
234 $this->mDataLoaded
= true;
236 switch ( $this->mFrom
) {
238 $this->loadDefaults();
241 $this->mId
= self
::idFromName( $this->mName
);
243 # Nonexistent user placeholder object
244 $this->loadDefaults( $this->mName
);
253 $this->loadFromSession();
254 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
257 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
259 wfProfileOut( __METHOD__
);
263 * Load user table data, given mId has already been set.
264 * @return \bool false if the ID does not exist, true otherwise
267 function loadFromId() {
269 if ( $this->mId
== 0 ) {
270 $this->loadDefaults();
275 $key = wfMemcKey( 'user', 'id', $this->mId
);
276 $data = $wgMemc->get( $key );
277 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
278 # Object is expired, load from DB
283 wfDebug( "Cache miss for user {$this->mId}\n" );
285 if ( !$this->loadFromDatabase() ) {
286 # Can't load from ID, user is anonymous
289 $this->saveToCache();
291 wfDebug( "Got user {$this->mId} from cache\n" );
293 foreach ( self
::$mCacheVars as $name ) {
294 $this->$name = $data[$name];
301 * Save user data to the shared cache
303 function saveToCache() {
306 if ( $this->isAnon() ) {
307 // Anonymous users are uncached
311 foreach ( self
::$mCacheVars as $name ) {
312 $data[$name] = $this->$name;
314 $data['mVersion'] = MW_USER_VERSION
;
315 $key = wfMemcKey( 'user', 'id', $this->mId
);
317 $wgMemc->set( $key, $data );
321 /** @name newFrom*() static factory methods */
325 * Static factory method for creation from username.
327 * This is slightly less efficient than newFromId(), so use newFromId() if
328 * you have both an ID and a name handy.
330 * @param $name \string Username, validated by Title::newFromText()
331 * @param $validate \mixed Validate username. Takes the same parameters as
332 * User::getCanonicalName(), except that true is accepted as an alias
333 * for 'valid', for BC.
335 * @return \type{User} The User object, or null if the username is invalid. If the
336 * username is not present in the database, the result will be a user object
337 * with a name, zero user ID and default settings.
339 static function newFromName( $name, $validate = 'valid' ) {
340 if ( $validate === true ) {
343 $name = self
::getCanonicalName( $name, $validate );
344 if ( $name === false ) {
347 # Create unloaded user object
356 * Static factory method for creation from a given user ID.
358 * @param $id \int Valid user ID
359 * @return \type{User} The corresponding User object
361 static function newFromId( $id ) {
369 * Factory method to fetch whichever user has a given email confirmation code.
370 * This code is generated when an account is created or its e-mail address
373 * If the code is invalid or has expired, returns NULL.
375 * @param $code \string Confirmation code
376 * @return \type{User}
378 static function newFromConfirmationCode( $code ) {
379 $dbr = wfGetDB( DB_SLAVE
);
380 $id = $dbr->selectField( 'user', 'user_id', array(
381 'user_email_token' => md5( $code ),
382 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
384 if( $id !== false ) {
385 return User
::newFromId( $id );
392 * Create a new user object using data from session or cookies. If the
393 * login credentials are invalid, the result is an anonymous user.
395 * @return \type{User}
397 static function newFromSession() {
399 $user->mFrom
= 'session';
404 * Create a new user object from a user row.
405 * The row should have all fields from the user table in it.
406 * @param $row array A row from the user table
407 * @return \type{User}
409 static function newFromRow( $row ) {
411 $user->loadFromRow( $row );
419 * Get the username corresponding to a given user ID
420 * @param $id \int User ID
421 * @return \string The corresponding username
423 static function whoIs( $id ) {
424 $dbr = wfGetDB( DB_SLAVE
);
425 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
429 * Get the real name of a user given their user ID
431 * @param $id \int User ID
432 * @return \string The corresponding user's real name
434 static function whoIsReal( $id ) {
435 $dbr = wfGetDB( DB_SLAVE
);
436 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
440 * Get database id given a user name
441 * @param $name \string Username
442 * @return \types{\int,\null} The corresponding user's ID, or null if user is nonexistent
444 static function idFromName( $name ) {
445 $nt = Title
::makeTitleSafe( NS_USER
, $name );
446 if( is_null( $nt ) ) {
450 $dbr = wfGetDB( DB_SLAVE
);
451 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
453 if ( $s === false ) {
461 * Does the string match an anonymous IPv4 address?
463 * This function exists for username validation, in order to reject
464 * usernames which are similar in form to IP addresses. Strings such
465 * as 300.300.300.300 will return true because it looks like an IP
466 * address, despite not being strictly valid.
468 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
469 * address because the usemod software would "cloak" anonymous IP
470 * addresses like this, if we allowed accounts like this to be created
471 * new users could get the old edits of these anonymous users.
473 * @param $name \string String to match
474 * @return \bool True or false
476 static function isIP( $name ) {
477 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
481 * Is the input a valid username?
483 * Checks if the input is a valid username, we don't want an empty string,
484 * an IP address, anything that containins slashes (would mess up subpages),
485 * is longer than the maximum allowed username size or doesn't begin with
488 * @param $name \string String to match
489 * @return \bool True or false
491 static function isValidUserName( $name ) {
492 global $wgContLang, $wgMaxNameChars;
495 || User
::isIP( $name )
496 ||
strpos( $name, '/' ) !== false
497 ||
strlen( $name ) > $wgMaxNameChars
498 ||
$name != $wgContLang->ucfirst( $name ) ) {
499 wfDebugLog( 'username', __METHOD__
.
500 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
504 // Ensure that the name can't be misresolved as a different title,
505 // such as with extra namespace keys at the start.
506 $parsed = Title
::newFromText( $name );
507 if( is_null( $parsed )
508 ||
$parsed->getNamespace()
509 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
510 wfDebugLog( 'username', __METHOD__
.
511 ": '$name' invalid due to ambiguous prefixes" );
515 // Check an additional blacklist of troublemaker characters.
516 // Should these be merged into the title char list?
517 $unicodeBlacklist = '/[' .
518 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
519 '\x{00a0}' . # non-breaking space
520 '\x{2000}-\x{200f}' . # various whitespace
521 '\x{2028}-\x{202f}' . # breaks and control chars
522 '\x{3000}' . # ideographic space
523 '\x{e000}-\x{f8ff}' . # private use
525 if( preg_match( $unicodeBlacklist, $name ) ) {
526 wfDebugLog( 'username', __METHOD__
.
527 ": '$name' invalid due to blacklisted characters" );
535 * Usernames which fail to pass this function will be blocked
536 * from user login and new account registrations, but may be used
537 * internally by batch processes.
539 * If an account already exists in this form, login will be blocked
540 * by a failure to pass this function.
542 * @param $name \string String to match
543 * @return \bool True or false
545 static function isUsableName( $name ) {
546 global $wgReservedUsernames;
547 // Must be a valid username, obviously ;)
548 if ( !self
::isValidUserName( $name ) ) {
552 static $reservedUsernames = false;
553 if ( !$reservedUsernames ) {
554 $reservedUsernames = $wgReservedUsernames;
555 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
558 // Certain names may be reserved for batch processes.
559 foreach ( $reservedUsernames as $reserved ) {
560 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
561 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
563 if ( $reserved == $name ) {
571 * Usernames which fail to pass this function will be blocked
572 * from new account registrations, but may be used internally
573 * either by batch processes or by user accounts which have
574 * already been created.
576 * Additional character blacklisting may be added here
577 * rather than in isValidUserName() to avoid disrupting
580 * @param $name \string String to match
581 * @return \bool True or false
583 static function isCreatableName( $name ) {
585 self
::isUsableName( $name ) &&
587 // Registration-time character blacklisting...
588 strpos( $name, '@' ) === false;
592 * Is the input a valid password for this user?
594 * @param $password \string Desired password
595 * @return \bool True or false
597 function isValidPassword( $password ) {
598 global $wgMinimalPasswordLength, $wgContLang;
601 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
603 if( $result === false )
606 // Password needs to be long enough, and can't be the same as the username
607 return strlen( $password ) >= $wgMinimalPasswordLength
608 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
612 * Does a string look like an e-mail address?
614 * There used to be a regular expression here, it got removed because it
615 * rejected valid addresses. Actually just check if there is '@' somewhere
616 * in the given address.
618 * @todo Check for RFC 2822 compilance (bug 959)
620 * @param $addr \string E-mail address
621 * @return \bool True or false
623 public static function isValidEmailAddr( $addr ) {
625 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
629 return strpos( $addr, '@' ) !== false;
633 * Given unvalidated user input, return a canonical username, or false if
634 * the username is invalid.
635 * @param $name \string User input
636 * @param $validate \types{\string,\bool} Type of validation to use:
637 * - false No validation
638 * - 'valid' Valid for batch processes
639 * - 'usable' Valid for batch processes and login
640 * - 'creatable' Valid for batch processes, login and account creation
642 static function getCanonicalName( $name, $validate = 'valid' ) {
643 # Force usernames to capital
645 $name = $wgContLang->ucfirst( $name );
647 # Reject names containing '#'; these will be cleaned up
648 # with title normalisation, but then it's too late to
650 if( strpos( $name, '#' ) !== false )
653 # Clean up name according to title rules
654 $t = ($validate === 'valid') ?
655 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
656 # Check for invalid titles
657 if( is_null( $t ) ) {
661 # Reject various classes of invalid names
662 $name = $t->getText();
664 $name = $wgAuth->getCanonicalName( $t->getText() );
666 switch ( $validate ) {
670 if ( !User
::isValidUserName( $name ) ) {
675 if ( !User
::isUsableName( $name ) ) {
680 if ( !User
::isCreatableName( $name ) ) {
685 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
691 * Count the number of edits of a user
692 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
694 * @param $uid \int User ID to check
695 * @return \int The user's edit count
697 static function edits( $uid ) {
698 wfProfileIn( __METHOD__
);
699 $dbr = wfGetDB( DB_SLAVE
);
700 // check if the user_editcount field has been initialized
701 $field = $dbr->selectField(
702 'user', 'user_editcount',
703 array( 'user_id' => $uid ),
707 if( $field === null ) { // it has not been initialized. do so.
708 $dbw = wfGetDB( DB_MASTER
);
709 $count = $dbr->selectField(
710 'revision', 'count(*)',
711 array( 'rev_user' => $uid ),
716 array( 'user_editcount' => $count ),
717 array( 'user_id' => $uid ),
723 wfProfileOut( __METHOD__
);
728 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
729 * @todo hash random numbers to improve security, like generateToken()
731 * @return \string New random password
733 static function randomPassword() {
734 global $wgMinimalPasswordLength;
735 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
736 $l = strlen( $pwchars ) - 1;
738 $pwlength = max( 7, $wgMinimalPasswordLength );
739 $digit = mt_rand(0, $pwlength - 1);
741 for ( $i = 0; $i < $pwlength; $i++
) {
742 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
748 * Set cached properties to default.
750 * @note This no longer clears uncached lazy-initialised properties;
751 * the constructor does that instead.
754 function loadDefaults( $name = false ) {
755 wfProfileIn( __METHOD__
);
757 global $wgCookiePrefix;
760 $this->mName
= $name;
761 $this->mRealName
= '';
762 $this->mPassword
= $this->mNewpassword
= '';
763 $this->mNewpassTime
= null;
765 $this->mOptions
= null; # Defer init
767 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
768 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
770 $this->mTouched
= '0'; # Allow any pages to be cached
773 $this->setToken(); # Random
774 $this->mEmailAuthenticated
= null;
775 $this->mEmailToken
= '';
776 $this->mEmailTokenExpires
= null;
777 $this->mRegistration
= wfTimestamp( TS_MW
);
778 $this->mGroups
= array();
780 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
782 wfProfileOut( __METHOD__
);
786 * @deprecated Use wfSetupSession().
788 function SetupSession() {
789 wfDeprecated( __METHOD__
);
794 * Load user data from the session or login cookie. If there are no valid
795 * credentials, initialises the user as an anonymous user.
796 * @return \bool True if the user is logged in, false otherwise.
798 private function loadFromSession() {
799 global $wgMemc, $wgCookiePrefix;
802 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
803 if ( $result !== null ) {
807 if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
808 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
809 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
810 $this->loadDefaults(); // Possible collision!
811 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
812 cookie user ID ($sId) don't match!" );
815 $_SESSION['wsUserID'] = $sId;
816 } else if ( isset( $_SESSION['wsUserID'] ) ) {
817 if ( $_SESSION['wsUserID'] != 0 ) {
818 $sId = $_SESSION['wsUserID'];
820 $this->loadDefaults();
824 $this->loadDefaults();
828 if ( isset( $_SESSION['wsUserName'] ) ) {
829 $sName = $_SESSION['wsUserName'];
830 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
831 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
832 $_SESSION['wsUserName'] = $sName;
834 $this->loadDefaults();
838 $passwordCorrect = FALSE;
840 if ( !$this->loadFromId() ) {
841 # Not a valid ID, loadFromId has switched the object to anon for us
845 if ( isset( $_SESSION['wsToken'] ) ) {
846 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
848 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
849 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
852 # No session or persistent login cookie
853 $this->loadDefaults();
857 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
858 $_SESSION['wsToken'] = $this->mToken
;
859 wfDebug( "Logged in from $from\n" );
862 # Invalid credentials
863 wfDebug( "Can't log in from $from, invalid credentials\n" );
864 $this->loadDefaults();
870 * Load user and user_group data from the database.
871 * $this::mId must be set, this is how the user is identified.
873 * @return \bool True if the user exists, false if the user is anonymous
876 function loadFromDatabase() {
878 $this->mId
= intval( $this->mId
);
880 /** Anonymous user */
882 $this->loadDefaults();
886 $dbr = wfGetDB( DB_MASTER
);
887 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
889 if ( $s !== false ) {
890 # Initialise user table data
891 $this->loadFromRow( $s );
892 $this->mGroups
= null; // deferred
893 $this->getEditCount(); // revalidation for nulls
898 $this->loadDefaults();
904 * Initialize this object from a row from the user table.
906 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
908 function loadFromRow( $row ) {
909 $this->mDataLoaded
= true;
911 if ( isset( $row->user_id
) ) {
912 $this->mId
= $row->user_id
;
914 $this->mName
= $row->user_name
;
915 $this->mRealName
= $row->user_real_name
;
916 $this->mPassword
= $row->user_password
;
917 $this->mNewpassword
= $row->user_newpassword
;
918 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
919 $this->mEmail
= $row->user_email
;
920 $this->decodeOptions( $row->user_options
);
921 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
922 $this->mToken
= $row->user_token
;
923 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
924 $this->mEmailToken
= $row->user_email_token
;
925 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
926 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
927 $this->mEditCount
= $row->user_editcount
;
931 * Load the groups from the database if they aren't already loaded.
934 function loadGroups() {
935 if ( is_null( $this->mGroups
) ) {
936 $dbr = wfGetDB( DB_MASTER
);
937 $res = $dbr->select( 'user_groups',
939 array( 'ug_user' => $this->mId
),
941 $this->mGroups
= array();
942 while( $row = $dbr->fetchObject( $res ) ) {
943 $this->mGroups
[] = $row->ug_group
;
949 * Clear various cached data stored in this object.
950 * @param $reloadFrom \string Reload user and user_groups table data from a
951 * given source. May be "name", "id", "defaults", "session", or false for
954 function clearInstanceCache( $reloadFrom = false ) {
955 $this->mNewtalk
= -1;
956 $this->mDatePreference
= null;
957 $this->mBlockedby
= -1; # Unset
958 $this->mHash
= false;
960 $this->mRights
= null;
961 $this->mEffectiveGroups
= null;
964 $this->mDataLoaded
= false;
965 $this->mFrom
= $reloadFrom;
970 * Combine the language default options with any site-specific options
971 * and add the default language variants.
973 * @return \type{\arrayof{\string}} Array of options
975 static function getDefaultOptions() {
976 global $wgNamespacesToBeSearchedDefault;
978 * Site defaults will override the global/language defaults
980 global $wgDefaultUserOptions, $wgContLang;
981 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
984 * default language setting
986 $variant = $wgContLang->getPreferredVariant( false );
987 $defOpt['variant'] = $variant;
988 $defOpt['language'] = $variant;
990 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
991 $defOpt['searchNs'.$nsnum] = $val;
997 * Get a given default option value.
999 * @param $opt \string Name of option to retrieve
1000 * @return \string Default option value
1002 public static function getDefaultOption( $opt ) {
1003 $defOpts = self
::getDefaultOptions();
1004 if( isset( $defOpts[$opt] ) ) {
1005 return $defOpts[$opt];
1012 * Get a list of user toggle names
1013 * @return \type{\arrayof{\string}} Array of user toggle names
1015 static function getToggles() {
1017 $extraToggles = array();
1018 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1019 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1024 * Get blocking information
1026 * @param $bFromSlave \bool Whether to check the slave database first. To
1027 * improve performance, non-critical checks are done
1028 * against slaves. Check when actually saving should be
1029 * done against master.
1031 function getBlockedStatus( $bFromSlave = true ) {
1032 global $wgEnableSorbs, $wgProxyWhitelist;
1034 if ( -1 != $this->mBlockedby
) {
1035 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1039 wfProfileIn( __METHOD__
);
1040 wfDebug( __METHOD__
.": checking...\n" );
1042 // Initialize data...
1043 // Otherwise something ends up stomping on $this->mBlockedby when
1044 // things get lazy-loaded later, causing false positive block hits
1045 // due to -1 !== 0. Probably session-related... Nothing should be
1046 // overwriting mBlockedby, surely?
1049 $this->mBlockedby
= 0;
1050 $this->mHideName
= 0;
1051 $this->mAllowUsertalk
= 0;
1054 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1055 # Exempt from all types of IP-block
1060 $this->mBlock
= new Block();
1061 $this->mBlock
->fromMaster( !$bFromSlave );
1062 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1063 wfDebug( __METHOD__
.": Found block.\n" );
1064 $this->mBlockedby
= $this->mBlock
->mBy
;
1065 $this->mBlockreason
= $this->mBlock
->mReason
;
1066 $this->mHideName
= $this->mBlock
->mHideName
;
1067 $this->mAllowUsertalk
= $this->mBlock
->mAllowUsertalk
;
1068 if ( $this->isLoggedIn() ) {
1069 $this->spreadBlock();
1072 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1073 // apply to users. Note that the existence of $this->mBlock is not used to
1074 // check for edit blocks, $this->mBlockedby is instead.
1078 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1080 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1081 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1082 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1086 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1087 if ( $this->inSorbsBlacklist( $ip ) ) {
1088 $this->mBlockedby
= wfMsg( 'sorbs' );
1089 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1095 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1097 wfProfileOut( __METHOD__
);
1101 * Whether the given IP is in the SORBS blacklist.
1103 * @param $ip \string IP to check
1104 * @return \bool True if blacklisted.
1106 function inSorbsBlacklist( $ip ) {
1107 global $wgEnableSorbs, $wgSorbsUrl;
1109 return $wgEnableSorbs &&
1110 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1114 * Whether the given IP is in a given DNS blacklist.
1116 * @param $ip \string IP to check
1117 * @param $base \string URL of the DNS blacklist
1118 * @return \bool True if blacklisted.
1120 function inDnsBlacklist( $ip, $base ) {
1121 wfProfileIn( __METHOD__
);
1125 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1126 if( IP
::isIPv4($ip) ) {
1128 $host = "$ip.$base";
1131 $ipList = gethostbynamel( $host );
1134 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1137 wfDebug( "Requested $host, not found in $base.\n" );
1141 wfProfileOut( __METHOD__
);
1146 * Is this user subject to rate limiting?
1148 * @return \bool True if rate limited
1150 public function isPingLimitable() {
1151 global $wgRateLimitsExcludedGroups;
1152 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1153 // Deprecated, but kept for backwards-compatibility config
1156 return !$this->isAllowed('noratelimit');
1160 * Primitive rate limits: enforce maximum actions per time period
1161 * to put a brake on flooding.
1163 * @note When using a shared cache like memcached, IP-address
1164 * last-hit counters will be shared across wikis.
1166 * @param $action \string Action to enforce; 'edit' if unspecified
1167 * @return \bool True if a rate limiter was tripped
1169 function pingLimiter( $action='edit' ) {
1171 # Call the 'PingLimiter' hook
1173 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1177 global $wgRateLimits;
1178 if( !isset( $wgRateLimits[$action] ) ) {
1182 # Some groups shouldn't trigger the ping limiter, ever
1183 if( !$this->isPingLimitable() )
1186 global $wgMemc, $wgRateLimitLog;
1187 wfProfileIn( __METHOD__
);
1189 $limits = $wgRateLimits[$action];
1191 $id = $this->getId();
1195 if( isset( $limits['anon'] ) && $id == 0 ) {
1196 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1199 if( isset( $limits['user'] ) && $id != 0 ) {
1200 $userLimit = $limits['user'];
1202 if( $this->isNewbie() ) {
1203 if( isset( $limits['newbie'] ) && $id != 0 ) {
1204 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1206 if( isset( $limits['ip'] ) ) {
1207 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1210 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1211 $subnet = $matches[1];
1212 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1215 // Check for group-specific permissions
1216 // If more than one group applies, use the group with the highest limit
1217 foreach ( $this->getGroups() as $group ) {
1218 if ( isset( $limits[$group] ) ) {
1219 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1220 $userLimit = $limits[$group];
1224 // Set the user limit key
1225 if ( $userLimit !== false ) {
1226 wfDebug( __METHOD__
.": effective user limit: $userLimit\n" );
1227 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1231 foreach( $keys as $key => $limit ) {
1232 list( $max, $period ) = $limit;
1233 $summary = "(limit $max in {$period}s)";
1234 $count = $wgMemc->get( $key );
1236 if( $count > $max ) {
1237 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1238 if( $wgRateLimitLog ) {
1239 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1243 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1246 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1247 $wgMemc->add( $key, 1, intval( $period ) );
1249 $wgMemc->incr( $key );
1252 wfProfileOut( __METHOD__
);
1257 * Check if user is blocked
1259 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1260 * @return \bool True if blocked, false otherwise
1262 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1263 wfDebug( "User::isBlocked: enter\n" );
1264 $this->getBlockedStatus( $bFromSlave );
1265 return $this->mBlockedby
!== 0;
1269 * Check if user is blocked from editing a particular article
1271 * @param $title \string Title to check
1272 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1273 * @return \bool True if blocked, false otherwise
1275 function isBlockedFrom( $title, $bFromSlave = false ) {
1276 global $wgBlockAllowsUTEdit;
1277 wfProfileIn( __METHOD__
);
1278 wfDebug( __METHOD__
.": enter\n" );
1280 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1281 $blocked = $this->isBlocked( $bFromSlave );
1282 $allowUsertalk = ($wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false);
1283 # If a user's name is suppressed, they cannot make edits anywhere
1284 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1285 $title->getNamespace() == NS_USER_TALK
) {
1287 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1289 wfProfileOut( __METHOD__
);
1294 * If user is blocked, return the name of the user who placed the block
1295 * @return \string name of blocker
1297 function blockedBy() {
1298 $this->getBlockedStatus();
1299 return $this->mBlockedby
;
1303 * If user is blocked, return the specified reason for the block
1304 * @return \string Blocking reason
1306 function blockedFor() {
1307 $this->getBlockedStatus();
1308 return $this->mBlockreason
;
1312 * Check if user is blocked on all wikis.
1313 * Do not use for actual edit permission checks!
1314 * This is intented for quick UI checks.
1316 * @param $ip \type{\string} IP address, uses current client if none given
1317 * @return \type{\bool} True if blocked, false otherwise
1319 function isBlockedGlobally( $ip = '' ) {
1320 if( $this->mBlockedGlobally
!== null ) {
1321 return $this->mBlockedGlobally
;
1323 // User is already an IP?
1324 if( IP
::isIPAddress( $this->getName() ) ) {
1325 $ip = $this->getName();
1330 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1331 $this->mBlockedGlobally
= (bool)$blocked;
1332 return $this->mBlockedGlobally
;
1336 * Check if user account is locked
1338 * @return \type{\bool} True if locked, false otherwise
1340 function isLocked() {
1341 if( $this->mLocked
!== null ) {
1342 return $this->mLocked
;
1345 $authUser = $wgAuth->getUserInstance( $this );
1346 $this->mLocked
= (bool)$authUser->isLocked();
1347 return $this->mLocked
;
1351 * Check if user account is hidden
1353 * @return \type{\bool} True if hidden, false otherwise
1355 function isHidden() {
1356 if( $this->mHideName
!== null ) {
1357 return $this->mHideName
;
1359 $this->getBlockedStatus();
1360 if( !$this->mHideName
) {
1362 $authUser = $wgAuth->getUserInstance( $this );
1363 $this->mHideName
= (bool)$authUser->isHidden();
1365 return $this->mHideName
;
1369 * Get the user's ID.
1370 * @return \int The user's ID; 0 if the user is anonymous or nonexistent
1373 if( $this->mId
=== null and $this->mName
!== null
1374 and User
::isIP( $this->mName
) ) {
1375 // Special case, we know the user is anonymous
1377 } elseif( $this->mId
=== null ) {
1378 // Don't load if this was initialized from an ID
1385 * Set the user and reload all fields according to a given ID
1386 * @param $v \int User ID to reload
1388 function setId( $v ) {
1390 $this->clearInstanceCache( 'id' );
1394 * Get the user name, or the IP of an anonymous user
1395 * @return \string User's name or IP address
1397 function getName() {
1398 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1399 # Special case optimisation
1400 return $this->mName
;
1403 if ( $this->mName
=== false ) {
1405 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1407 return $this->mName
;
1412 * Set the user name.
1414 * This does not reload fields from the database according to the given
1415 * name. Rather, it is used to create a temporary "nonexistent user" for
1416 * later addition to the database. It can also be used to set the IP
1417 * address for an anonymous user to something other than the current
1420 * @note User::newFromName() has rougly the same function, when the named user
1422 * @param $str \string New user name to set
1424 function setName( $str ) {
1426 $this->mName
= $str;
1430 * Get the user's name escaped by underscores.
1431 * @return \string Username escaped by underscores.
1433 function getTitleKey() {
1434 return str_replace( ' ', '_', $this->getName() );
1438 * Check if the user has new messages.
1439 * @return \bool True if the user has new messages
1441 function getNewtalk() {
1444 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1445 if( $this->mNewtalk
=== -1 ) {
1446 $this->mNewtalk
= false; # reset talk page status
1448 # Check memcached separately for anons, who have no
1449 # entire User object stored in there.
1452 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1453 $newtalk = $wgMemc->get( $key );
1454 if( strval( $newtalk ) !== '' ) {
1455 $this->mNewtalk
= (bool)$newtalk;
1457 // Since we are caching this, make sure it is up to date by getting it
1459 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1460 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1463 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1467 return (bool)$this->mNewtalk
;
1471 * Return the talk page(s) this user has new messages on.
1472 * @return \type{\arrayof{\string}} Array of page URLs
1474 function getNewMessageLinks() {
1476 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1479 if (!$this->getNewtalk())
1481 $up = $this->getUserPage();
1482 $utp = $up->getTalkPage();
1483 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1488 * Internal uncached check for new messages
1491 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1492 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1493 * @param $fromMaster \bool true to fetch from the master, false for a slave
1494 * @return \bool True if the user has new messages
1497 function checkNewtalk( $field, $id, $fromMaster = false ) {
1498 if ( $fromMaster ) {
1499 $db = wfGetDB( DB_MASTER
);
1501 $db = wfGetDB( DB_SLAVE
);
1503 $ok = $db->selectField( 'user_newtalk', $field,
1504 array( $field => $id ), __METHOD__
);
1505 return $ok !== false;
1509 * Add or update the new messages flag
1510 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1511 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1512 * @return \bool True if successful, false otherwise
1515 function updateNewtalk( $field, $id ) {
1516 $dbw = wfGetDB( DB_MASTER
);
1517 $dbw->insert( 'user_newtalk',
1518 array( $field => $id ),
1521 if ( $dbw->affectedRows() ) {
1522 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1525 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1531 * Clear the new messages flag for the given user
1532 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1533 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1534 * @return \bool True if successful, false otherwise
1537 function deleteNewtalk( $field, $id ) {
1538 $dbw = wfGetDB( DB_MASTER
);
1539 $dbw->delete( 'user_newtalk',
1540 array( $field => $id ),
1542 if ( $dbw->affectedRows() ) {
1543 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1546 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1552 * Update the 'You have new messages!' status.
1553 * @param $val \bool Whether the user has new messages
1555 function setNewtalk( $val ) {
1556 if( wfReadOnly() ) {
1561 $this->mNewtalk
= $val;
1563 if( $this->isAnon() ) {
1565 $id = $this->getName();
1568 $id = $this->getId();
1573 $changed = $this->updateNewtalk( $field, $id );
1575 $changed = $this->deleteNewtalk( $field, $id );
1578 if( $this->isAnon() ) {
1579 // Anons have a separate memcached space, since
1580 // user records aren't kept for them.
1581 $key = wfMemcKey( 'newtalk', 'ip', $id );
1582 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1585 $this->invalidateCache();
1590 * Generate a current or new-future timestamp to be stored in the
1591 * user_touched field when we update things.
1592 * @return \string Timestamp in TS_MW format
1594 private static function newTouchedTimestamp() {
1595 global $wgClockSkewFudge;
1596 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1600 * Clear user data from memcached.
1601 * Use after applying fun updates to the database; caller's
1602 * responsibility to update user_touched if appropriate.
1604 * Called implicitly from invalidateCache() and saveSettings().
1606 private function clearSharedCache() {
1610 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1615 * Immediately touch the user data cache for this account.
1616 * Updates user_touched field, and removes account data from memcached
1617 * for reload on the next hit.
1619 function invalidateCache() {
1622 $this->mTouched
= self
::newTouchedTimestamp();
1624 $dbw = wfGetDB( DB_MASTER
);
1625 $dbw->update( 'user',
1626 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1627 array( 'user_id' => $this->mId
),
1630 $this->clearSharedCache();
1635 * Validate the cache for this account.
1636 * @param $timestamp \string A timestamp in TS_MW format
1638 function validateCache( $timestamp ) {
1640 return ($timestamp >= $this->mTouched
);
1644 * Get the user touched timestamp
1646 function getTouched() {
1648 return $this->mTouched
;
1652 * Set the password and reset the random token.
1653 * Calls through to authentication plugin if necessary;
1654 * will have no effect if the auth plugin refuses to
1655 * pass the change through or if the legal password
1658 * As a special case, setting the password to null
1659 * wipes it, so the account cannot be logged in until
1660 * a new password is set, for instance via e-mail.
1662 * @param $str \string New password to set
1663 * @throws PasswordError on failure
1665 function setPassword( $str ) {
1668 if( $str !== null ) {
1669 if( !$wgAuth->allowPasswordChange() ) {
1670 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1673 if( !$this->isValidPassword( $str ) ) {
1674 global $wgMinimalPasswordLength;
1675 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1676 $wgMinimalPasswordLength ) );
1680 if( !$wgAuth->setPassword( $this, $str ) ) {
1681 throw new PasswordError( wfMsg( 'externaldberror' ) );
1684 $this->setInternalPassword( $str );
1690 * Set the password and reset the random token unconditionally.
1692 * @param $str \string New password to set
1694 function setInternalPassword( $str ) {
1698 if( $str === null ) {
1699 // Save an invalid hash...
1700 $this->mPassword
= '';
1702 $this->mPassword
= self
::crypt( $str );
1704 $this->mNewpassword
= '';
1705 $this->mNewpassTime
= null;
1709 * Get the user's current token.
1710 * @return \string Token
1712 function getToken() {
1714 return $this->mToken
;
1718 * Set the random token (used for persistent authentication)
1719 * Called from loadDefaults() among other places.
1721 * @param $token \string If specified, set the token to this value
1724 function setToken( $token = false ) {
1725 global $wgSecretKey, $wgProxyKey;
1728 if ( $wgSecretKey ) {
1729 $key = $wgSecretKey;
1730 } elseif ( $wgProxyKey ) {
1735 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1737 $this->mToken
= $token;
1742 * Set the cookie password
1744 * @param $str \string New cookie password
1747 function setCookiePassword( $str ) {
1749 $this->mCookiePassword
= md5( $str );
1753 * Set the password for a password reminder or new account email
1755 * @param $str \string New password to set
1756 * @param $throttle \bool If true, reset the throttle timestamp to the present
1758 function setNewpassword( $str, $throttle = true ) {
1760 $this->mNewpassword
= self
::crypt( $str );
1762 $this->mNewpassTime
= wfTimestampNow();
1767 * Has password reminder email been sent within the last
1768 * $wgPasswordReminderResendTime hours?
1769 * @return \bool True or false
1771 function isPasswordReminderThrottled() {
1772 global $wgPasswordReminderResendTime;
1774 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1777 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1778 return time() < $expiry;
1782 * Get the user's e-mail address
1783 * @return \string User's email address
1785 function getEmail() {
1787 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1788 return $this->mEmail
;
1792 * Get the timestamp of the user's e-mail authentication
1793 * @return \string TS_MW timestamp
1795 function getEmailAuthenticationTimestamp() {
1797 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1798 return $this->mEmailAuthenticated
;
1802 * Set the user's e-mail address
1803 * @param $str \string New e-mail address
1805 function setEmail( $str ) {
1807 $this->mEmail
= $str;
1808 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1812 * Get the user's real name
1813 * @return \string User's real name
1815 function getRealName() {
1817 return $this->mRealName
;
1821 * Set the user's real name
1822 * @param $str \string New real name
1824 function setRealName( $str ) {
1826 $this->mRealName
= $str;
1830 * Get the user's current setting for a given option.
1832 * @param $oname \string The option to check
1833 * @param $defaultOverride \string A default value returned if the option does not exist
1834 * @return \string User's current value for the option
1835 * @see getBoolOption()
1836 * @see getIntOption()
1838 function getOption( $oname, $defaultOverride = '' ) {
1841 if ( is_null( $this->mOptions
) ) {
1842 if($defaultOverride != '') {
1843 return $defaultOverride;
1845 $this->mOptions
= User
::getDefaultOptions();
1848 if ( array_key_exists( $oname, $this->mOptions
) ) {
1849 return trim( $this->mOptions
[$oname] );
1851 return $defaultOverride;
1856 * Get the user's current setting for a given option, as a boolean value.
1858 * @param $oname \string The option to check
1859 * @return \bool User's current value for the option
1862 function getBoolOption( $oname ) {
1863 return (bool)$this->getOption( $oname );
1868 * Get the user's current setting for a given option, as a boolean value.
1870 * @param $oname \string The option to check
1871 * @param $defaultOverride \int A default value returned if the option does not exist
1872 * @return \int User's current value for the option
1875 function getIntOption( $oname, $defaultOverride=0 ) {
1876 $val = $this->getOption( $oname );
1878 $val = $defaultOverride;
1880 return intval( $val );
1884 * Set the given option for a user.
1886 * @param $oname \string The option to set
1887 * @param $val \mixed New value to set
1889 function setOption( $oname, $val ) {
1891 if ( is_null( $this->mOptions
) ) {
1892 $this->mOptions
= User
::getDefaultOptions();
1894 if ( $oname == 'skin' ) {
1895 # Clear cached skin, so the new one displays immediately in Special:Preferences
1896 unset( $this->mSkin
);
1898 // Filter out any newlines that may have passed through input validation.
1899 // Newlines are used to separate items in the options blob.
1901 $val = str_replace( "\r\n", "\n", $val );
1902 $val = str_replace( "\r", "\n", $val );
1903 $val = str_replace( "\n", " ", $val );
1905 // Explicitly NULL values should refer to defaults
1906 global $wgDefaultUserOptions;
1907 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1908 $val = $wgDefaultUserOptions[$oname];
1910 $this->mOptions
[$oname] = $val;
1914 * Get the user's preferred date format.
1915 * @return \string User's preferred date format
1917 function getDatePreference() {
1918 // Important migration for old data rows
1919 if ( is_null( $this->mDatePreference
) ) {
1921 $value = $this->getOption( 'date' );
1922 $map = $wgLang->getDatePreferenceMigrationMap();
1923 if ( isset( $map[$value] ) ) {
1924 $value = $map[$value];
1926 $this->mDatePreference
= $value;
1928 return $this->mDatePreference
;
1932 * Get the permissions this user has.
1933 * @return \type{\arrayof{\string}} Array of permission names
1935 function getRights() {
1936 if ( is_null( $this->mRights
) ) {
1937 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1938 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1939 // Force reindexation of rights when a hook has unset one of them
1940 $this->mRights
= array_values( $this->mRights
);
1942 return $this->mRights
;
1946 * Get the list of explicit group memberships this user has.
1947 * The implicit * and user groups are not included.
1948 * @return \type{\arrayof{\string}} Array of internal group names
1950 function getGroups() {
1952 return $this->mGroups
;
1956 * Get the list of implicit group memberships this user has.
1957 * This includes all explicit groups, plus 'user' if logged in,
1958 * '*' for all accounts and autopromoted groups
1959 * @param $recache \bool Whether to avoid the cache
1960 * @return \type{\arrayof{\string}} Array of internal group names
1962 function getEffectiveGroups( $recache = false ) {
1963 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1964 $this->mEffectiveGroups
= $this->getGroups();
1965 $this->mEffectiveGroups
[] = '*';
1966 if( $this->getId() ) {
1967 $this->mEffectiveGroups
[] = 'user';
1969 $this->mEffectiveGroups
= array_unique( array_merge(
1970 $this->mEffectiveGroups
,
1971 Autopromote
::getAutopromoteGroups( $this )
1974 # Hook for additional groups
1975 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1978 return $this->mEffectiveGroups
;
1982 * Get the user's edit count.
1983 * @return \int User'e edit count
1985 function getEditCount() {
1987 if ( !isset( $this->mEditCount
) ) {
1988 /* Populate the count, if it has not been populated yet */
1989 $this->mEditCount
= User
::edits($this->mId
);
1991 return $this->mEditCount
;
1999 * Add the user to the given group.
2000 * This takes immediate effect.
2001 * @param $group \string Name of the group to add
2003 function addGroup( $group ) {
2004 $dbw = wfGetDB( DB_MASTER
);
2005 if( $this->getId() ) {
2006 $dbw->insert( 'user_groups',
2008 'ug_user' => $this->getID(),
2009 'ug_group' => $group,
2012 array( 'IGNORE' ) );
2015 $this->loadGroups();
2016 $this->mGroups
[] = $group;
2017 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2019 $this->invalidateCache();
2023 * Remove the user from the given group.
2024 * This takes immediate effect.
2025 * @param $group \string Name of the group to remove
2027 function removeGroup( $group ) {
2029 $dbw = wfGetDB( DB_MASTER
);
2030 $dbw->delete( 'user_groups',
2032 'ug_user' => $this->getID(),
2033 'ug_group' => $group,
2035 'User::removeGroup' );
2037 $this->loadGroups();
2038 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2039 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2041 $this->invalidateCache();
2046 * Get whether the user is logged in
2047 * @return \bool True or false
2049 function isLoggedIn() {
2050 return $this->getID() != 0;
2054 * Get whether the user is anonymous
2055 * @return \bool True or false
2058 return !$this->isLoggedIn();
2062 * Get whether the user is a bot
2063 * @return \bool True or false
2067 wfDeprecated( __METHOD__
);
2068 return $this->isAllowed( 'bot' );
2072 * Check if user is allowed to access a feature / make an action
2073 * @param $action \string action to be checked
2074 * @return \bool True if action is allowed, else false
2076 function isAllowed($action='') {
2077 if ( $action === '' )
2078 // In the spirit of DWIM
2081 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2082 # by misconfiguration: 0 == 'foo'
2083 return in_array( $action, $this->getRights(), true );
2087 * Check whether to enable recent changes patrol features for this user
2088 * @return \bool True or false
2090 public function useRCPatrol() {
2091 global $wgUseRCPatrol;
2092 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2096 * Check whether to enable new pages patrol features for this user
2097 * @return \bool True or false
2099 public function useNPPatrol() {
2100 global $wgUseRCPatrol, $wgUseNPPatrol;
2101 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2105 * Get the current skin, loading it if required
2106 * @return \type{Skin} Current skin
2107 * @todo FIXME : need to check the old failback system [AV]
2109 function &getSkin() {
2110 global $wgRequest, $wgAllowUserSkin, $wgDefaultSkin;
2111 if ( ! isset( $this->mSkin
) ) {
2112 wfProfileIn( __METHOD__
);
2114 if( $wgAllowUserSkin ) {
2116 $userSkin = $this->getOption( 'skin' );
2117 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2119 # if we're not allowing users to override, then use the default
2120 $userSkin = $wgDefaultSkin;
2123 $this->mSkin
=& Skin
::newFromKey( $userSkin );
2124 wfProfileOut( __METHOD__
);
2126 return $this->mSkin
;
2130 * Check the watched status of an article.
2131 * @param $title \type{Title} Title of the article to look at
2132 * @return \bool True if article is watched
2134 function isWatched( $title ) {
2135 $wl = WatchedItem
::fromUserTitle( $this, $title );
2136 return $wl->isWatched();
2141 * @param $title \type{Title} Title of the article to look at
2143 function addWatch( $title ) {
2144 $wl = WatchedItem
::fromUserTitle( $this, $title );
2146 $this->invalidateCache();
2150 * Stop watching an article.
2151 * @param $title \type{Title} Title of the article to look at
2153 function removeWatch( $title ) {
2154 $wl = WatchedItem
::fromUserTitle( $this, $title );
2156 $this->invalidateCache();
2160 * Clear the user's notification timestamp for the given title.
2161 * If e-notif e-mails are on, they will receive notification mails on
2162 * the next change of the page if it's watched etc.
2163 * @param $title \type{Title} Title of the article to look at
2165 function clearNotification( &$title ) {
2166 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2168 # Do nothing if the database is locked to writes
2169 if( wfReadOnly() ) {
2173 if ($title->getNamespace() == NS_USER_TALK
&&
2174 $title->getText() == $this->getName() ) {
2175 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2177 $this->setNewtalk( false );
2180 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2184 if( $this->isAnon() ) {
2185 // Nothing else to do...
2189 // Only update the timestamp if the page is being watched.
2190 // The query to find out if it is watched is cached both in memcached and per-invocation,
2191 // and when it does have to be executed, it can be on a slave
2192 // If this is the user's newtalk page, we always update the timestamp
2193 if ($title->getNamespace() == NS_USER_TALK
&&
2194 $title->getText() == $wgUser->getName())
2197 } elseif ( $this->getId() == $wgUser->getId() ) {
2198 $watched = $title->userIsWatching();
2203 // If the page is watched by the user (or may be watched), update the timestamp on any
2204 // any matching rows
2206 $dbw = wfGetDB( DB_MASTER
);
2207 $dbw->update( 'watchlist',
2209 'wl_notificationtimestamp' => NULL
2210 ), array( /* WHERE */
2211 'wl_title' => $title->getDBkey(),
2212 'wl_namespace' => $title->getNamespace(),
2213 'wl_user' => $this->getID()
2220 * Resets all of the given user's page-change notification timestamps.
2221 * If e-notif e-mails are on, they will receive notification mails on
2222 * the next change of any watched page.
2224 * @param $currentUser \int User ID
2226 function clearAllNotifications( $currentUser ) {
2227 global $wgUseEnotif, $wgShowUpdatedMarker;
2228 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2229 $this->setNewtalk( false );
2232 if( $currentUser != 0 ) {
2233 $dbw = wfGetDB( DB_MASTER
);
2234 $dbw->update( 'watchlist',
2236 'wl_notificationtimestamp' => NULL
2237 ), array( /* WHERE */
2238 'wl_user' => $currentUser
2241 # We also need to clear here the "you have new message" notification for the own user_talk page
2242 # This is cleared one page view later in Article::viewUpdates();
2247 * Encode this user's options as a string
2248 * @return \string Encoded options
2251 function encodeOptions() {
2253 if ( is_null( $this->mOptions
) ) {
2254 $this->mOptions
= User
::getDefaultOptions();
2257 foreach ( $this->mOptions
as $oname => $oval ) {
2258 array_push( $a, $oname.'='.$oval );
2260 $s = implode( "\n", $a );
2265 * Set this user's options from an encoded string
2266 * @param $str \string Encoded options to import
2269 function decodeOptions( $str ) {
2270 $this->mOptions
= array();
2271 $a = explode( "\n", $str );
2272 foreach ( $a as $s ) {
2274 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2275 $this->mOptions
[$m[1]] = $m[2];
2281 * Set a cookie on the user's client. Wrapper for
2282 * WebResponse::setCookie
2283 * @param $name \string Name of the cookie to set
2284 * @param $value \string Value to set
2285 * @param $exp \int Expiration time, as a UNIX time value;
2286 * if 0 or not specified, use the default $wgCookieExpiration
2288 protected function setCookie( $name, $value, $exp=0 ) {
2290 $wgRequest->response()->setcookie( $name, $value, $exp );
2294 * Clear a cookie on the user's client
2295 * @param $name \string Name of the cookie to clear
2297 protected function clearCookie( $name ) {
2298 $this->setCookie( $name, '', time() - 86400 );
2302 * Set the default cookies for this session on the user's client.
2304 function setCookies() {
2306 if ( 0 == $this->mId
) return;
2308 'wsUserID' => $this->mId
,
2309 'wsToken' => $this->mToken
,
2310 'wsUserName' => $this->getName()
2313 'UserID' => $this->mId
,
2314 'UserName' => $this->getName(),
2316 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2317 $cookies['Token'] = $this->mToken
;
2319 $cookies['Token'] = false;
2322 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2323 #check for null, since the hook could cause a null value
2324 if ( !is_null( $session ) && !is_null( $_SESSION ) ){
2325 $_SESSION = $session +
$_SESSION;
2327 foreach ( $cookies as $name => $value ) {
2328 if ( $value === false ) {
2329 $this->clearCookie( $name );
2331 $this->setCookie( $name, $value );
2337 * Log this user out.
2341 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2347 * Clear the user's cookies and session, and reset the instance cache.
2351 function doLogout() {
2352 $this->clearInstanceCache( 'defaults' );
2354 $_SESSION['wsUserID'] = 0;
2356 $this->clearCookie( 'UserID' );
2357 $this->clearCookie( 'Token' );
2359 # Remember when user logged out, to prevent seeing cached pages
2360 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2364 * Save this user's settings into the database.
2365 * @todo Only rarely do all these fields need to be set!
2367 function saveSettings() {
2369 if ( wfReadOnly() ) { return; }
2370 if ( 0 == $this->mId
) { return; }
2372 $this->mTouched
= self
::newTouchedTimestamp();
2374 $dbw = wfGetDB( DB_MASTER
);
2375 $dbw->update( 'user',
2377 'user_name' => $this->mName
,
2378 'user_password' => $this->mPassword
,
2379 'user_newpassword' => $this->mNewpassword
,
2380 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2381 'user_real_name' => $this->mRealName
,
2382 'user_email' => $this->mEmail
,
2383 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2384 'user_options' => $this->encodeOptions(),
2385 'user_touched' => $dbw->timestamp($this->mTouched
),
2386 'user_token' => $this->mToken
,
2387 'user_email_token' => $this->mEmailToken
,
2388 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2389 ), array( /* WHERE */
2390 'user_id' => $this->mId
2393 wfRunHooks( 'UserSaveSettings', array( $this ) );
2394 $this->clearSharedCache();
2395 $this->getUserPage()->invalidateCache();
2399 * If only this user's username is known, and it exists, return the user ID.
2401 function idForName() {
2402 $s = trim( $this->getName() );
2403 if ( $s === '' ) return 0;
2405 $dbr = wfGetDB( DB_SLAVE
);
2406 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2407 if ( $id === false ) {
2414 * Add a user to the database, return the user object
2416 * @param $name \string Username to add
2417 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2418 * - password The user's password. Password logins will be disabled if this is omitted.
2419 * - newpassword A temporary password mailed to the user
2420 * - email The user's email address
2421 * - email_authenticated The email authentication timestamp
2422 * - real_name The user's real name
2423 * - options An associative array of non-default options
2424 * - token Random authentication token. Do not set.
2425 * - registration Registration timestamp. Do not set.
2427 * @return \type{User} A new User object, or null if the username already exists
2429 static function createNew( $name, $params = array() ) {
2432 if ( isset( $params['options'] ) ) {
2433 $user->mOptions
= $params['options'] +
$user->mOptions
;
2434 unset( $params['options'] );
2436 $dbw = wfGetDB( DB_MASTER
);
2437 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2439 'user_id' => $seqVal,
2440 'user_name' => $name,
2441 'user_password' => $user->mPassword
,
2442 'user_newpassword' => $user->mNewpassword
,
2443 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2444 'user_email' => $user->mEmail
,
2445 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2446 'user_real_name' => $user->mRealName
,
2447 'user_options' => $user->encodeOptions(),
2448 'user_token' => $user->mToken
,
2449 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2450 'user_editcount' => 0,
2452 foreach ( $params as $name => $value ) {
2453 $fields["user_$name"] = $value;
2455 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2456 if ( $dbw->affectedRows() ) {
2457 $newUser = User
::newFromId( $dbw->insertId() );
2465 * Add this existing user object to the database
2467 function addToDatabase() {
2469 $dbw = wfGetDB( DB_MASTER
);
2470 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2471 $dbw->insert( 'user',
2473 'user_id' => $seqVal,
2474 'user_name' => $this->mName
,
2475 'user_password' => $this->mPassword
,
2476 'user_newpassword' => $this->mNewpassword
,
2477 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2478 'user_email' => $this->mEmail
,
2479 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2480 'user_real_name' => $this->mRealName
,
2481 'user_options' => $this->encodeOptions(),
2482 'user_token' => $this->mToken
,
2483 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2484 'user_editcount' => 0,
2487 $this->mId
= $dbw->insertId();
2489 // Clear instance cache other than user table data, which is already accurate
2490 $this->clearInstanceCache();
2494 * If this (non-anonymous) user is blocked, block any IP address
2495 * they've successfully logged in from.
2497 function spreadBlock() {
2498 wfDebug( __METHOD__
."()\n" );
2500 if ( $this->mId
== 0 ) {
2504 $userblock = Block
::newFromDB( '', $this->mId
);
2505 if ( !$userblock ) {
2509 $userblock->doAutoblock( wfGetIp() );
2514 * Generate a string which will be different for any combination of
2515 * user options which would produce different parser output.
2516 * This will be used as part of the hash key for the parser cache,
2517 * so users will the same options can share the same cached data
2520 * Extensions which require it should install 'PageRenderingHash' hook,
2521 * which will give them a chance to modify this key based on their own
2524 * @return \string Page rendering hash
2526 function getPageRenderingHash() {
2527 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2529 return $this->mHash
;
2532 // stubthreshold is only included below for completeness,
2533 // it will always be 0 when this function is called by parsercache.
2535 $confstr = $this->getOption( 'math' );
2536 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2537 if ( $wgUseDynamicDates ) {
2538 $confstr .= '!' . $this->getDatePreference();
2540 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2541 $confstr .= '!' . $wgLang->getCode();
2542 $confstr .= '!' . $this->getOption( 'thumbsize' );
2543 // add in language specific options, if any
2544 $extra = $wgContLang->getExtraHashOptions();
2547 $confstr .= $wgRenderHashAppend;
2549 // Give a chance for extensions to modify the hash, if they have
2550 // extra options or other effects on the parser cache.
2551 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2553 // Make it a valid memcached key fragment
2554 $confstr = str_replace( ' ', '_', $confstr );
2555 $this->mHash
= $confstr;
2560 * Get whether the user is explicitly blocked from account creation.
2561 * @return \bool True if blocked
2563 function isBlockedFromCreateAccount() {
2564 $this->getBlockedStatus();
2565 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2569 * Get whether the user is blocked from using Special:Emailuser.
2570 * @return \bool True if blocked
2572 function isBlockedFromEmailuser() {
2573 $this->getBlockedStatus();
2574 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2578 * Get whether the user is allowed to create an account.
2579 * @return \bool True if allowed
2581 function isAllowedToCreateAccount() {
2582 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2588 function setLoaded( $loaded ) {
2589 wfDeprecated( __METHOD__
);
2593 * Get this user's personal page title.
2595 * @return \type{Title} User's personal page title
2597 function getUserPage() {
2598 return Title
::makeTitle( NS_USER
, $this->getName() );
2602 * Get this user's talk page title.
2604 * @return \type{Title} User's talk page title
2606 function getTalkPage() {
2607 $title = $this->getUserPage();
2608 return $title->getTalkPage();
2612 * Get the maximum valid user ID.
2613 * @return \int User ID
2616 function getMaxID() {
2617 static $res; // cache
2619 if ( isset( $res ) )
2622 $dbr = wfGetDB( DB_SLAVE
);
2623 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2628 * Determine whether the user is a newbie. Newbies are either
2629 * anonymous IPs, or the most recently created accounts.
2630 * @return \bool True if the user is a newbie
2632 function isNewbie() {
2633 return !$this->isAllowed( 'autoconfirmed' );
2637 * Is the user active? We check to see if they've made at least
2638 * X number of edits in the last Y days.
2640 * @return \bool True if the user is active, false if not.
2642 public function isActiveEditor() {
2643 global $wgActiveUserEditCount, $wgActiveUserDays;
2644 $dbr = wfGetDB( DB_SLAVE
);
2646 // Stolen without shame from RC
2647 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2648 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
2649 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2651 $res = $dbr->select( 'revision', '1',
2652 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2654 array('LIMIT' => $wgActiveUserEditCount ) );
2656 $count = $dbr->numRows($res);
2657 $dbr->freeResult($res);
2659 return $count == $wgActiveUserEditCount;
2663 * Check to see if the given clear-text password is one of the accepted passwords
2664 * @param $password \string user password.
2665 * @return \bool True if the given password is correct, otherwise False.
2667 function checkPassword( $password ) {
2671 // Even though we stop people from creating passwords that
2672 // are shorter than this, doesn't mean people wont be able
2673 // to. Certain authentication plugins do NOT want to save
2674 // domain passwords in a mysql database, so we should
2675 // check this (incase $wgAuth->strict() is false).
2676 if( !$this->isValidPassword( $password ) ) {
2680 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2682 } elseif( $wgAuth->strict() ) {
2683 /* Auth plugin doesn't allow local authentication */
2685 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2686 /* Auth plugin doesn't allow local authentication for this user name */
2689 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2691 } elseif ( function_exists( 'iconv' ) ) {
2692 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2693 # Check for this with iconv
2694 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2695 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2703 * Check if the given clear-text password matches the temporary password
2704 * sent by e-mail for password reset operations.
2705 * @return \bool True if matches, false otherwise
2707 function checkTemporaryPassword( $plaintext ) {
2708 return self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() );
2712 * Initialize (if necessary) and return a session token value
2713 * which can be used in edit forms to show that the user's
2714 * login credentials aren't being hijacked with a foreign form
2717 * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2718 * @return \string The new edit token
2720 function editToken( $salt = '' ) {
2721 if ( $this->isAnon() ) {
2722 return EDIT_TOKEN_SUFFIX
;
2724 if( !isset( $_SESSION['wsEditToken'] ) ) {
2725 $token = $this->generateToken();
2726 $_SESSION['wsEditToken'] = $token;
2728 $token = $_SESSION['wsEditToken'];
2730 if( is_array( $salt ) ) {
2731 $salt = implode( '|', $salt );
2733 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2738 * Generate a looking random token for various uses.
2740 * @param $salt \string Optional salt value
2741 * @return \string The new random token
2743 function generateToken( $salt = '' ) {
2744 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2745 return md5( $token . $salt );
2749 * Check given value against the token value stored in the session.
2750 * A match should confirm that the form was submitted from the
2751 * user's own login session, not a form submission from a third-party
2754 * @param $val \string Input value to compare
2755 * @param $salt \string Optional function-specific data for hashing
2756 * @return \bool Whether the token matches
2758 function matchEditToken( $val, $salt = '' ) {
2759 $sessionToken = $this->editToken( $salt );
2760 if ( $val != $sessionToken ) {
2761 wfDebug( "User::matchEditToken: broken session data\n" );
2763 return $val == $sessionToken;
2767 * Check given value against the token value stored in the session,
2768 * ignoring the suffix.
2770 * @param $val \string Input value to compare
2771 * @param $salt \string Optional function-specific data for hashing
2772 * @return \bool Whether the token matches
2774 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2775 $sessionToken = $this->editToken( $salt );
2776 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2780 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2781 * mail to the user's given address.
2783 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure.
2785 function sendConfirmationMail() {
2787 $expiration = null; // gets passed-by-ref and defined in next line.
2788 $token = $this->confirmationToken( $expiration );
2789 $url = $this->confirmationTokenUrl( $token );
2790 $invalidateURL = $this->invalidationTokenUrl( $token );
2791 $this->saveSettings();
2793 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2794 wfMsg( 'confirmemail_body',
2798 $wgLang->timeanddate( $expiration, false ),
2803 * Send an e-mail to this user's account. Does not check for
2804 * confirmed status or validity.
2806 * @param $subject \string Message subject
2807 * @param $body \string Message body
2808 * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2809 * @param $replyto \string Reply-To address
2810 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure
2812 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2813 if( is_null( $from ) ) {
2814 global $wgPasswordSender;
2815 $from = $wgPasswordSender;
2818 $to = new MailAddress( $this );
2819 $sender = new MailAddress( $from );
2820 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2824 * Generate, store, and return a new e-mail confirmation code.
2825 * A hash (unsalted, since it's used as a key) is stored.
2827 * @note Call saveSettings() after calling this function to commit
2828 * this change to the database.
2830 * @param[out] &$expiration \mixed Accepts the expiration time
2831 * @return \string New token
2834 function confirmationToken( &$expiration ) {
2836 $expires = $now +
7 * 24 * 60 * 60;
2837 $expiration = wfTimestamp( TS_MW
, $expires );
2838 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2839 $hash = md5( $token );
2841 $this->mEmailToken
= $hash;
2842 $this->mEmailTokenExpires
= $expiration;
2847 * Return a URL the user can use to confirm their email address.
2848 * @param $token \string Accepts the email confirmation token
2849 * @return \string New token URL
2852 function confirmationTokenUrl( $token ) {
2853 return $this->getTokenUrl( 'ConfirmEmail', $token );
2856 * Return a URL the user can use to invalidate their email address.
2857 * @param $token \string Accepts the email confirmation token
2858 * @return \string New token URL
2861 function invalidationTokenUrl( $token ) {
2862 return $this->getTokenUrl( 'Invalidateemail', $token );
2866 * Internal function to format the e-mail validation/invalidation URLs.
2867 * This uses $wgArticlePath directly as a quickie hack to use the
2868 * hardcoded English names of the Special: pages, for ASCII safety.
2870 * @note Since these URLs get dropped directly into emails, using the
2871 * short English names avoids insanely long URL-encoded links, which
2872 * also sometimes can get corrupted in some browsers/mailers
2873 * (bug 6957 with Gmail and Internet Explorer).
2875 * @param $page \string Special page
2876 * @param $token \string Token
2877 * @return \string Formatted URL
2879 protected function getTokenUrl( $page, $token ) {
2880 global $wgArticlePath;
2884 "Special:$page/$token",
2889 * Mark the e-mail address confirmed.
2891 * @note Call saveSettings() after calling this function to commit the change.
2893 function confirmEmail() {
2894 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2899 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2900 * address if it was already confirmed.
2902 * @note Call saveSettings() after calling this function to commit the change.
2904 function invalidateEmail() {
2906 $this->mEmailToken
= null;
2907 $this->mEmailTokenExpires
= null;
2908 $this->setEmailAuthenticationTimestamp( null );
2913 * Set the e-mail authentication timestamp.
2914 * @param $timestamp \string TS_MW timestamp
2916 function setEmailAuthenticationTimestamp( $timestamp ) {
2918 $this->mEmailAuthenticated
= $timestamp;
2919 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2923 * Is this user allowed to send e-mails within limits of current
2924 * site configuration?
2925 * @return \bool True if allowed
2927 function canSendEmail() {
2928 global $wgEnableEmail, $wgEnableUserEmail;
2929 if( !$wgEnableEmail ||
!$wgEnableUserEmail ) {
2932 $canSend = $this->isEmailConfirmed();
2933 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2938 * Is this user allowed to receive e-mails within limits of current
2939 * site configuration?
2940 * @return \bool True if allowed
2942 function canReceiveEmail() {
2943 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2947 * Is this user's e-mail address valid-looking and confirmed within
2948 * limits of the current site configuration?
2950 * @note If $wgEmailAuthentication is on, this may require the user to have
2951 * confirmed their address by returning a code or using a password
2952 * sent to the address from the wiki.
2954 * @return \bool True if confirmed
2956 function isEmailConfirmed() {
2957 global $wgEmailAuthentication;
2960 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2961 if( $this->isAnon() )
2963 if( !self
::isValidEmailAddr( $this->mEmail
) )
2965 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2974 * Check whether there is an outstanding request for e-mail confirmation.
2975 * @return \bool True if pending
2977 function isEmailConfirmationPending() {
2978 global $wgEmailAuthentication;
2979 return $wgEmailAuthentication &&
2980 !$this->isEmailConfirmed() &&
2981 $this->mEmailToken
&&
2982 $this->mEmailTokenExpires
> wfTimestamp();
2986 * Get the timestamp of account creation.
2988 * @return \types{\string,\bool} string Timestamp of account creation, or false for
2989 * non-existent/anonymous user accounts.
2991 public function getRegistration() {
2992 return $this->getId() > 0
2993 ?
$this->mRegistration
2998 * Get the timestamp of the first edit
3000 * @return \types{\string,\bool} string Timestamp of first edit, or false for
3001 * non-existent/anonymous user accounts.
3003 public function getFirstEditTimestamp() {
3004 if( $this->getId() == 0 ) return false; // anons
3005 $dbr = wfGetDB( DB_SLAVE
);
3006 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3007 array( 'rev_user' => $this->getId() ),
3009 array( 'ORDER BY' => 'rev_timestamp ASC' )
3011 if( !$time ) return false; // no edits
3012 return wfTimestamp( TS_MW
, $time );
3016 * Get the permissions associated with a given list of groups
3018 * @param $groups \type{\arrayof{\string}} List of internal group names
3019 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3021 static function getGroupPermissions( $groups ) {
3022 global $wgGroupPermissions;
3024 foreach( $groups as $group ) {
3025 if( isset( $wgGroupPermissions[$group] ) ) {
3026 $rights = array_merge( $rights,
3027 // array_filter removes empty items
3028 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3031 return array_unique($rights);
3035 * Get all the groups who have a given permission
3037 * @param $role \string Role to check
3038 * @return \type{\arrayof{\string}} List of internal group names with the given permission
3040 static function getGroupsWithPermission( $role ) {
3041 global $wgGroupPermissions;
3042 $allowedGroups = array();
3043 foreach ( $wgGroupPermissions as $group => $rights ) {
3044 if ( isset( $rights[$role] ) && $rights[$role] ) {
3045 $allowedGroups[] = $group;
3048 return $allowedGroups;
3052 * Get the localized descriptive name for a group, if it exists
3054 * @param $group \string Internal group name
3055 * @return \string Localized descriptive group name
3057 static function getGroupName( $group ) {
3058 global $wgMessageCache;
3059 $wgMessageCache->loadAllMessages();
3060 $key = "group-$group";
3061 $name = wfMsg( $key );
3062 return $name == '' ||
wfEmptyMsg( $key, $name )
3068 * Get the localized descriptive name for a member of a group, if it exists
3070 * @param $group \string Internal group name
3071 * @return \string Localized name for group member
3073 static function getGroupMember( $group ) {
3074 global $wgMessageCache;
3075 $wgMessageCache->loadAllMessages();
3076 $key = "group-$group-member";
3077 $name = wfMsg( $key );
3078 return $name == '' ||
wfEmptyMsg( $key, $name )
3084 * Return the set of defined explicit groups.
3085 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3086 * are not included, as they are defined automatically, not in the database.
3087 * @return \type{\arrayof{\string}} Array of internal group names
3089 static function getAllGroups() {
3090 global $wgGroupPermissions;
3092 array_keys( $wgGroupPermissions ),
3093 self
::getImplicitGroups()
3098 * Get a list of all available permissions.
3099 * @return \type{\arrayof{\string}} Array of permission names
3101 static function getAllRights() {
3102 if ( self
::$mAllRights === false ) {
3103 global $wgAvailableRights;
3104 if ( count( $wgAvailableRights ) ) {
3105 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3107 self
::$mAllRights = self
::$mCoreRights;
3109 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3111 return self
::$mAllRights;
3115 * Get a list of implicit groups
3116 * @return \type{\arrayof{\string}} Array of internal group names
3118 public static function getImplicitGroups() {
3119 global $wgImplicitGroups;
3120 $groups = $wgImplicitGroups;
3121 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3126 * Get the title of a page describing a particular group
3128 * @param $group \string Internal group name
3129 * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3131 static function getGroupPage( $group ) {
3132 global $wgMessageCache;
3133 $wgMessageCache->loadAllMessages();
3134 $page = wfMsgForContent( 'grouppage-' . $group );
3135 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3136 $title = Title
::newFromText( $page );
3137 if( is_object( $title ) )
3144 * Create a link to the group in HTML, if available;
3145 * else return the group name.
3147 * @param $group \string Internal name of the group
3148 * @param $text \string The text of the link
3149 * @return \string HTML link to the group
3151 static function makeGroupLinkHTML( $group, $text = '' ) {
3153 $text = self
::getGroupName( $group );
3155 $title = self
::getGroupPage( $group );
3158 $sk = $wgUser->getSkin();
3159 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3166 * Create a link to the group in Wikitext, if available;
3167 * else return the group name.
3169 * @param $group \string Internal name of the group
3170 * @param $text \string The text of the link
3171 * @return \string Wikilink to the group
3173 static function makeGroupLinkWiki( $group, $text = '' ) {
3175 $text = self
::getGroupName( $group );
3177 $title = self
::getGroupPage( $group );
3179 $page = $title->getPrefixedText();
3180 return "[[$page|$text]]";
3187 * Increment the user's edit-count field.
3188 * Will have no effect for anonymous users.
3190 function incEditCount() {
3191 if( !$this->isAnon() ) {
3192 $dbw = wfGetDB( DB_MASTER
);
3193 $dbw->update( 'user',
3194 array( 'user_editcount=user_editcount+1' ),
3195 array( 'user_id' => $this->getId() ),
3198 // Lazy initialization check...
3199 if( $dbw->affectedRows() == 0 ) {
3200 // Pull from a slave to be less cruel to servers
3201 // Accuracy isn't the point anyway here
3202 $dbr = wfGetDB( DB_SLAVE
);
3203 $count = $dbr->selectField( 'revision',
3205 array( 'rev_user' => $this->getId() ),
3208 // Now here's a goddamn hack...
3209 if( $dbr !== $dbw ) {
3210 // If we actually have a slave server, the count is
3211 // at least one behind because the current transaction
3212 // has not been committed and replicated.
3215 // But if DB_SLAVE is selecting the master, then the
3216 // count we just read includes the revision that was
3217 // just added in the working transaction.
3220 $dbw->update( 'user',
3221 array( 'user_editcount' => $count ),
3222 array( 'user_id' => $this->getId() ),
3226 // edit count in user cache too
3227 $this->invalidateCache();
3231 * Get the description of a given right
3233 * @param $right \string Right to query
3234 * @return \string Localized description of the right
3236 static function getRightDescription( $right ) {
3237 global $wgMessageCache;
3238 $wgMessageCache->loadAllMessages();
3239 $key = "right-$right";
3240 $name = wfMsg( $key );
3241 return $name == '' ||
wfEmptyMsg( $key, $name )
3247 * Make an old-style password hash
3249 * @param $password \string Plain-text password
3250 * @param $userId \string User ID
3251 * @return \string Password hash
3253 static function oldCrypt( $password, $userId ) {
3254 global $wgPasswordSalt;
3255 if ( $wgPasswordSalt ) {
3256 return md5( $userId . '-' . md5( $password ) );
3258 return md5( $password );
3263 * Make a new-style password hash
3265 * @param $password \string Plain-text password
3266 * @param $salt \string Optional salt, may be random or the user ID.
3267 * If unspecified or false, will generate one automatically
3268 * @return \string Password hash
3270 static function crypt( $password, $salt = false ) {
3271 global $wgPasswordSalt;
3274 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3278 if( $wgPasswordSalt ) {
3279 if ( $salt === false ) {
3280 $salt = substr( wfGenerateToken(), 0, 8 );
3282 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3284 return ':A:' . md5( $password );
3289 * Compare a password hash with a plain-text password. Requires the user
3290 * ID if there's a chance that the hash is an old-style hash.
3292 * @param $hash \string Password hash
3293 * @param $password \string Plain-text password to compare
3294 * @param $userId \string User ID for old-style password salt
3297 static function comparePasswords( $hash, $password, $userId = false ) {
3299 $type = substr( $hash, 0, 3 );
3302 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3306 if ( $type == ':A:' ) {
3308 return md5( $password ) === substr( $hash, 3 );
3309 } elseif ( $type == ':B:' ) {
3311 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3312 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3315 return self
::oldCrypt( $password, $userId ) === $hash;
3320 * Add a newuser log entry for this user
3321 * @param $byEmail Boolean: account made by email?
3323 public function addNewUserLogEntry( $byEmail = false ) {
3324 global $wgUser, $wgContLang, $wgNewUserLog;
3325 if( empty($wgNewUserLog) ) {
3326 return true; // disabled
3328 $talk = $wgContLang->getFormattedNsText( NS_TALK
);
3329 if( $this->getName() == $wgUser->getName() ) {
3333 $action = 'create2';
3334 $message = $byEmail ?
wfMsgForContent( 'newuserlog-byemail' ) : '';
3336 $log = new LogPage( 'newusers' );
3337 $log->addEntry( $action, $this->getUserPage(), $message, array( $this->getId() ) );
3342 * Add an autocreate newuser log entry for this user
3343 * Used by things like CentralAuth and perhaps other authplugins.
3345 public function addNewUserLogEntryAutoCreate() {
3346 global $wgNewUserLog;
3347 if( empty($wgNewUserLog) ) {
3348 return true; // disabled
3350 $log = new LogPage( 'newusers', false );
3351 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );