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 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
891 if ( $s !== false ) {
892 # Initialise user table data
893 $this->loadFromRow( $s );
894 $this->mGroups
= null; // deferred
895 $this->getEditCount(); // revalidation for nulls
900 $this->loadDefaults();
906 * Initialize this object from a row from the user table.
908 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
910 function loadFromRow( $row ) {
911 $this->mDataLoaded
= true;
913 if ( isset( $row->user_id
) ) {
914 $this->mId
= $row->user_id
;
916 $this->mName
= $row->user_name
;
917 $this->mRealName
= $row->user_real_name
;
918 $this->mPassword
= $row->user_password
;
919 $this->mNewpassword
= $row->user_newpassword
;
920 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
921 $this->mEmail
= $row->user_email
;
922 $this->decodeOptions( $row->user_options
);
923 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
924 $this->mToken
= $row->user_token
;
925 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
926 $this->mEmailToken
= $row->user_email_token
;
927 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
928 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
929 $this->mEditCount
= $row->user_editcount
;
933 * Load the groups from the database if they aren't already loaded.
936 function loadGroups() {
937 if ( is_null( $this->mGroups
) ) {
938 $dbr = wfGetDB( DB_MASTER
);
939 $res = $dbr->select( 'user_groups',
941 array( 'ug_user' => $this->mId
),
943 $this->mGroups
= array();
944 while( $row = $dbr->fetchObject( $res ) ) {
945 $this->mGroups
[] = $row->ug_group
;
951 * Clear various cached data stored in this object.
952 * @param $reloadFrom \string Reload user and user_groups table data from a
953 * given source. May be "name", "id", "defaults", "session", or false for
956 function clearInstanceCache( $reloadFrom = false ) {
957 $this->mNewtalk
= -1;
958 $this->mDatePreference
= null;
959 $this->mBlockedby
= -1; # Unset
960 $this->mHash
= false;
962 $this->mRights
= null;
963 $this->mEffectiveGroups
= null;
966 $this->mDataLoaded
= false;
967 $this->mFrom
= $reloadFrom;
972 * Combine the language default options with any site-specific options
973 * and add the default language variants.
975 * @return \type{\arrayof{\string}} Array of options
977 static function getDefaultOptions() {
978 global $wgNamespacesToBeSearchedDefault;
980 * Site defaults will override the global/language defaults
982 global $wgDefaultUserOptions, $wgContLang;
983 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
986 * default language setting
988 $variant = $wgContLang->getPreferredVariant( false );
989 $defOpt['variant'] = $variant;
990 $defOpt['language'] = $variant;
992 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
993 $defOpt['searchNs'.$nsnum] = $val;
999 * Get a given default option value.
1001 * @param $opt \string Name of option to retrieve
1002 * @return \string Default option value
1004 public static function getDefaultOption( $opt ) {
1005 $defOpts = self
::getDefaultOptions();
1006 if( isset( $defOpts[$opt] ) ) {
1007 return $defOpts[$opt];
1014 * Get a list of user toggle names
1015 * @return \type{\arrayof{\string}} Array of user toggle names
1017 static function getToggles() {
1018 global $wgContLang, $wgUseRCPatrol;
1019 $extraToggles = array();
1020 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1021 if( $wgUseRCPatrol ) {
1022 $extraToggles[] = 'hidepatrolled';
1023 $extraToggles[] = 'watchlisthidepatrolled';
1025 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1030 * Get blocking information
1032 * @param $bFromSlave \bool Whether to check the slave database first. To
1033 * improve performance, non-critical checks are done
1034 * against slaves. Check when actually saving should be
1035 * done against master.
1037 function getBlockedStatus( $bFromSlave = true ) {
1038 global $wgEnableSorbs, $wgProxyWhitelist;
1040 if ( -1 != $this->mBlockedby
) {
1041 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1045 wfProfileIn( __METHOD__
);
1046 wfDebug( __METHOD__
.": checking...\n" );
1048 // Initialize data...
1049 // Otherwise something ends up stomping on $this->mBlockedby when
1050 // things get lazy-loaded later, causing false positive block hits
1051 // due to -1 !== 0. Probably session-related... Nothing should be
1052 // overwriting mBlockedby, surely?
1055 $this->mBlockedby
= 0;
1056 $this->mHideName
= 0;
1057 $this->mAllowUsertalk
= 0;
1060 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1061 # Exempt from all types of IP-block
1066 $this->mBlock
= new Block();
1067 $this->mBlock
->fromMaster( !$bFromSlave );
1068 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1069 wfDebug( __METHOD__
.": Found block.\n" );
1070 $this->mBlockedby
= $this->mBlock
->mBy
;
1071 $this->mBlockreason
= $this->mBlock
->mReason
;
1072 $this->mHideName
= $this->mBlock
->mHideName
;
1073 $this->mAllowUsertalk
= $this->mBlock
->mAllowUsertalk
;
1074 if ( $this->isLoggedIn() ) {
1075 $this->spreadBlock();
1078 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1079 // apply to users. Note that the existence of $this->mBlock is not used to
1080 // check for edit blocks, $this->mBlockedby is instead.
1084 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1086 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1087 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1088 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1092 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1093 if ( $this->inSorbsBlacklist( $ip ) ) {
1094 $this->mBlockedby
= wfMsg( 'sorbs' );
1095 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1101 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1103 wfProfileOut( __METHOD__
);
1107 * Whether the given IP is in the SORBS blacklist.
1109 * @param $ip \string IP to check
1110 * @return \bool True if blacklisted.
1112 function inSorbsBlacklist( $ip ) {
1113 global $wgEnableSorbs, $wgSorbsUrl;
1115 return $wgEnableSorbs &&
1116 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1120 * Whether the given IP is in a given DNS blacklist.
1122 * @param $ip \string IP to check
1123 * @param $base \string URL of the DNS blacklist
1124 * @return \bool True if blacklisted.
1126 function inDnsBlacklist( $ip, $base ) {
1127 wfProfileIn( __METHOD__
);
1131 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1132 if( IP
::isIPv4($ip) ) {
1134 $host = "$ip.$base";
1137 $ipList = gethostbynamel( $host );
1140 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1143 wfDebug( "Requested $host, not found in $base.\n" );
1147 wfProfileOut( __METHOD__
);
1152 * Is this user subject to rate limiting?
1154 * @return \bool True if rate limited
1156 public function isPingLimitable() {
1157 global $wgRateLimitsExcludedGroups;
1158 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1159 // Deprecated, but kept for backwards-compatibility config
1162 return !$this->isAllowed('noratelimit');
1166 * Primitive rate limits: enforce maximum actions per time period
1167 * to put a brake on flooding.
1169 * @note When using a shared cache like memcached, IP-address
1170 * last-hit counters will be shared across wikis.
1172 * @param $action \string Action to enforce; 'edit' if unspecified
1173 * @return \bool True if a rate limiter was tripped
1175 function pingLimiter( $action='edit' ) {
1177 # Call the 'PingLimiter' hook
1179 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1183 global $wgRateLimits;
1184 if( !isset( $wgRateLimits[$action] ) ) {
1188 # Some groups shouldn't trigger the ping limiter, ever
1189 if( !$this->isPingLimitable() )
1192 global $wgMemc, $wgRateLimitLog;
1193 wfProfileIn( __METHOD__
);
1195 $limits = $wgRateLimits[$action];
1197 $id = $this->getId();
1201 if( isset( $limits['anon'] ) && $id == 0 ) {
1202 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1205 if( isset( $limits['user'] ) && $id != 0 ) {
1206 $userLimit = $limits['user'];
1208 if( $this->isNewbie() ) {
1209 if( isset( $limits['newbie'] ) && $id != 0 ) {
1210 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1212 if( isset( $limits['ip'] ) ) {
1213 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1216 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1217 $subnet = $matches[1];
1218 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1221 // Check for group-specific permissions
1222 // If more than one group applies, use the group with the highest limit
1223 foreach ( $this->getGroups() as $group ) {
1224 if ( isset( $limits[$group] ) ) {
1225 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1226 $userLimit = $limits[$group];
1230 // Set the user limit key
1231 if ( $userLimit !== false ) {
1232 wfDebug( __METHOD__
.": effective user limit: $userLimit\n" );
1233 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1237 foreach( $keys as $key => $limit ) {
1238 list( $max, $period ) = $limit;
1239 $summary = "(limit $max in {$period}s)";
1240 $count = $wgMemc->get( $key );
1242 if( $count > $max ) {
1243 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1244 if( $wgRateLimitLog ) {
1245 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1249 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1252 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1253 $wgMemc->add( $key, 1, intval( $period ) );
1255 $wgMemc->incr( $key );
1258 wfProfileOut( __METHOD__
);
1263 * Check if user is blocked
1265 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1266 * @return \bool True if blocked, false otherwise
1268 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1269 wfDebug( "User::isBlocked: enter\n" );
1270 $this->getBlockedStatus( $bFromSlave );
1271 return $this->mBlockedby
!== 0;
1275 * Check if user is blocked from editing a particular article
1277 * @param $title \string Title to check
1278 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1279 * @return \bool True if blocked, false otherwise
1281 function isBlockedFrom( $title, $bFromSlave = false ) {
1282 global $wgBlockAllowsUTEdit;
1283 wfProfileIn( __METHOD__
);
1284 wfDebug( __METHOD__
.": enter\n" );
1286 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1287 $blocked = $this->isBlocked( $bFromSlave );
1288 $allowUsertalk = ($wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false);
1289 # If a user's name is suppressed, they cannot make edits anywhere
1290 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1291 $title->getNamespace() == NS_USER_TALK
) {
1293 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1295 wfProfileOut( __METHOD__
);
1300 * If user is blocked, return the name of the user who placed the block
1301 * @return \string name of blocker
1303 function blockedBy() {
1304 $this->getBlockedStatus();
1305 return $this->mBlockedby
;
1309 * If user is blocked, return the specified reason for the block
1310 * @return \string Blocking reason
1312 function blockedFor() {
1313 $this->getBlockedStatus();
1314 return $this->mBlockreason
;
1318 * Check if user is blocked on all wikis.
1319 * Do not use for actual edit permission checks!
1320 * This is intented for quick UI checks.
1322 * @param $ip \type{\string} IP address, uses current client if none given
1323 * @return \type{\bool} True if blocked, false otherwise
1325 function isBlockedGlobally( $ip = '' ) {
1326 if( $this->mBlockedGlobally
!== null ) {
1327 return $this->mBlockedGlobally
;
1329 // User is already an IP?
1330 if( IP
::isIPAddress( $this->getName() ) ) {
1331 $ip = $this->getName();
1336 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1337 $this->mBlockedGlobally
= (bool)$blocked;
1338 return $this->mBlockedGlobally
;
1342 * Check if user account is locked
1344 * @return \type{\bool} True if locked, false otherwise
1346 function isLocked() {
1347 if( $this->mLocked
!== null ) {
1348 return $this->mLocked
;
1351 $authUser = $wgAuth->getUserInstance( $this );
1352 $this->mLocked
= (bool)$authUser->isLocked();
1353 return $this->mLocked
;
1357 * Check if user account is hidden
1359 * @return \type{\bool} True if hidden, false otherwise
1361 function isHidden() {
1362 if( $this->mHideName
!== null ) {
1363 return $this->mHideName
;
1365 $this->getBlockedStatus();
1366 if( !$this->mHideName
) {
1368 $authUser = $wgAuth->getUserInstance( $this );
1369 $this->mHideName
= (bool)$authUser->isHidden();
1371 return $this->mHideName
;
1375 * Get the user's ID.
1376 * @return \int The user's ID; 0 if the user is anonymous or nonexistent
1379 if( $this->mId
=== null and $this->mName
!== null
1380 and User
::isIP( $this->mName
) ) {
1381 // Special case, we know the user is anonymous
1383 } elseif( $this->mId
=== null ) {
1384 // Don't load if this was initialized from an ID
1391 * Set the user and reload all fields according to a given ID
1392 * @param $v \int User ID to reload
1394 function setId( $v ) {
1396 $this->clearInstanceCache( 'id' );
1400 * Get the user name, or the IP of an anonymous user
1401 * @return \string User's name or IP address
1403 function getName() {
1404 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1405 # Special case optimisation
1406 return $this->mName
;
1409 if ( $this->mName
=== false ) {
1411 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1413 return $this->mName
;
1418 * Set the user name.
1420 * This does not reload fields from the database according to the given
1421 * name. Rather, it is used to create a temporary "nonexistent user" for
1422 * later addition to the database. It can also be used to set the IP
1423 * address for an anonymous user to something other than the current
1426 * @note User::newFromName() has rougly the same function, when the named user
1428 * @param $str \string New user name to set
1430 function setName( $str ) {
1432 $this->mName
= $str;
1436 * Get the user's name escaped by underscores.
1437 * @return \string Username escaped by underscores.
1439 function getTitleKey() {
1440 return str_replace( ' ', '_', $this->getName() );
1444 * Check if the user has new messages.
1445 * @return \bool True if the user has new messages
1447 function getNewtalk() {
1450 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1451 if( $this->mNewtalk
=== -1 ) {
1452 $this->mNewtalk
= false; # reset talk page status
1454 # Check memcached separately for anons, who have no
1455 # entire User object stored in there.
1458 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1459 $newtalk = $wgMemc->get( $key );
1460 if( strval( $newtalk ) !== '' ) {
1461 $this->mNewtalk
= (bool)$newtalk;
1463 // Since we are caching this, make sure it is up to date by getting it
1465 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1466 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1469 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1473 return (bool)$this->mNewtalk
;
1477 * Return the talk page(s) this user has new messages on.
1478 * @return \type{\arrayof{\string}} Array of page URLs
1480 function getNewMessageLinks() {
1482 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1485 if (!$this->getNewtalk())
1487 $up = $this->getUserPage();
1488 $utp = $up->getTalkPage();
1489 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1494 * Internal uncached check for new messages
1497 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1498 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1499 * @param $fromMaster \bool true to fetch from the master, false for a slave
1500 * @return \bool True if the user has new messages
1503 function checkNewtalk( $field, $id, $fromMaster = false ) {
1504 if ( $fromMaster ) {
1505 $db = wfGetDB( DB_MASTER
);
1507 $db = wfGetDB( DB_SLAVE
);
1509 $ok = $db->selectField( 'user_newtalk', $field,
1510 array( $field => $id ), __METHOD__
);
1511 return $ok !== false;
1515 * Add or update the new messages flag
1516 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1517 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1518 * @return \bool True if successful, false otherwise
1521 function updateNewtalk( $field, $id ) {
1522 $dbw = wfGetDB( DB_MASTER
);
1523 $dbw->insert( 'user_newtalk',
1524 array( $field => $id ),
1527 if ( $dbw->affectedRows() ) {
1528 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1531 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1537 * Clear the new messages flag for the given user
1538 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1539 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1540 * @return \bool True if successful, false otherwise
1543 function deleteNewtalk( $field, $id ) {
1544 $dbw = wfGetDB( DB_MASTER
);
1545 $dbw->delete( 'user_newtalk',
1546 array( $field => $id ),
1548 if ( $dbw->affectedRows() ) {
1549 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1552 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1558 * Update the 'You have new messages!' status.
1559 * @param $val \bool Whether the user has new messages
1561 function setNewtalk( $val ) {
1562 if( wfReadOnly() ) {
1567 $this->mNewtalk
= $val;
1569 if( $this->isAnon() ) {
1571 $id = $this->getName();
1574 $id = $this->getId();
1579 $changed = $this->updateNewtalk( $field, $id );
1581 $changed = $this->deleteNewtalk( $field, $id );
1584 if( $this->isAnon() ) {
1585 // Anons have a separate memcached space, since
1586 // user records aren't kept for them.
1587 $key = wfMemcKey( 'newtalk', 'ip', $id );
1588 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1591 $this->invalidateCache();
1596 * Generate a current or new-future timestamp to be stored in the
1597 * user_touched field when we update things.
1598 * @return \string Timestamp in TS_MW format
1600 private static function newTouchedTimestamp() {
1601 global $wgClockSkewFudge;
1602 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1606 * Clear user data from memcached.
1607 * Use after applying fun updates to the database; caller's
1608 * responsibility to update user_touched if appropriate.
1610 * Called implicitly from invalidateCache() and saveSettings().
1612 private function clearSharedCache() {
1616 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1621 * Immediately touch the user data cache for this account.
1622 * Updates user_touched field, and removes account data from memcached
1623 * for reload on the next hit.
1625 function invalidateCache() {
1628 $this->mTouched
= self
::newTouchedTimestamp();
1630 $dbw = wfGetDB( DB_MASTER
);
1631 $dbw->update( 'user',
1632 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1633 array( 'user_id' => $this->mId
),
1636 $this->clearSharedCache();
1641 * Validate the cache for this account.
1642 * @param $timestamp \string A timestamp in TS_MW format
1644 function validateCache( $timestamp ) {
1646 return ($timestamp >= $this->mTouched
);
1650 * Get the user touched timestamp
1652 function getTouched() {
1654 return $this->mTouched
;
1658 * Set the password and reset the random token.
1659 * Calls through to authentication plugin if necessary;
1660 * will have no effect if the auth plugin refuses to
1661 * pass the change through or if the legal password
1664 * As a special case, setting the password to null
1665 * wipes it, so the account cannot be logged in until
1666 * a new password is set, for instance via e-mail.
1668 * @param $str \string New password to set
1669 * @throws PasswordError on failure
1671 function setPassword( $str ) {
1674 if( $str !== null ) {
1675 if( !$wgAuth->allowPasswordChange() ) {
1676 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1679 if( !$this->isValidPassword( $str ) ) {
1680 global $wgMinimalPasswordLength;
1681 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1682 $wgMinimalPasswordLength ) );
1686 if( !$wgAuth->setPassword( $this, $str ) ) {
1687 throw new PasswordError( wfMsg( 'externaldberror' ) );
1690 $this->setInternalPassword( $str );
1696 * Set the password and reset the random token unconditionally.
1698 * @param $str \string New password to set
1700 function setInternalPassword( $str ) {
1704 if( $str === null ) {
1705 // Save an invalid hash...
1706 $this->mPassword
= '';
1708 $this->mPassword
= self
::crypt( $str );
1710 $this->mNewpassword
= '';
1711 $this->mNewpassTime
= null;
1715 * Get the user's current token.
1716 * @return \string Token
1718 function getToken() {
1720 return $this->mToken
;
1724 * Set the random token (used for persistent authentication)
1725 * Called from loadDefaults() among other places.
1727 * @param $token \string If specified, set the token to this value
1730 function setToken( $token = false ) {
1731 global $wgSecretKey, $wgProxyKey;
1734 if ( $wgSecretKey ) {
1735 $key = $wgSecretKey;
1736 } elseif ( $wgProxyKey ) {
1741 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1743 $this->mToken
= $token;
1748 * Set the cookie password
1750 * @param $str \string New cookie password
1753 function setCookiePassword( $str ) {
1755 $this->mCookiePassword
= md5( $str );
1759 * Set the password for a password reminder or new account email
1761 * @param $str \string New password to set
1762 * @param $throttle \bool If true, reset the throttle timestamp to the present
1764 function setNewpassword( $str, $throttle = true ) {
1766 $this->mNewpassword
= self
::crypt( $str );
1768 $this->mNewpassTime
= wfTimestampNow();
1773 * Has password reminder email been sent within the last
1774 * $wgPasswordReminderResendTime hours?
1775 * @return \bool True or false
1777 function isPasswordReminderThrottled() {
1778 global $wgPasswordReminderResendTime;
1780 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1783 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1784 return time() < $expiry;
1788 * Get the user's e-mail address
1789 * @return \string User's email address
1791 function getEmail() {
1793 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1794 return $this->mEmail
;
1798 * Get the timestamp of the user's e-mail authentication
1799 * @return \string TS_MW timestamp
1801 function getEmailAuthenticationTimestamp() {
1803 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1804 return $this->mEmailAuthenticated
;
1808 * Set the user's e-mail address
1809 * @param $str \string New e-mail address
1811 function setEmail( $str ) {
1813 $this->mEmail
= $str;
1814 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1818 * Get the user's real name
1819 * @return \string User's real name
1821 function getRealName() {
1823 return $this->mRealName
;
1827 * Set the user's real name
1828 * @param $str \string New real name
1830 function setRealName( $str ) {
1832 $this->mRealName
= $str;
1836 * Get the user's current setting for a given option.
1838 * @param $oname \string The option to check
1839 * @param $defaultOverride \string A default value returned if the option does not exist
1840 * @return \string User's current value for the option
1841 * @see getBoolOption()
1842 * @see getIntOption()
1844 function getOption( $oname, $defaultOverride = '' ) {
1847 if ( is_null( $this->mOptions
) ) {
1848 if($defaultOverride != '') {
1849 return $defaultOverride;
1851 $this->mOptions
= User
::getDefaultOptions();
1854 if ( array_key_exists( $oname, $this->mOptions
) ) {
1855 return trim( $this->mOptions
[$oname] );
1857 return $defaultOverride;
1862 * Get the user's current setting for a given option, as a boolean value.
1864 * @param $oname \string The option to check
1865 * @return \bool User's current value for the option
1868 function getBoolOption( $oname ) {
1869 return (bool)$this->getOption( $oname );
1874 * Get the user's current setting for a given option, as a boolean value.
1876 * @param $oname \string The option to check
1877 * @param $defaultOverride \int A default value returned if the option does not exist
1878 * @return \int User's current value for the option
1881 function getIntOption( $oname, $defaultOverride=0 ) {
1882 $val = $this->getOption( $oname );
1884 $val = $defaultOverride;
1886 return intval( $val );
1890 * Set the given option for a user.
1892 * @param $oname \string The option to set
1893 * @param $val \mixed New value to set
1895 function setOption( $oname, $val ) {
1897 if ( is_null( $this->mOptions
) ) {
1898 $this->mOptions
= User
::getDefaultOptions();
1900 if ( $oname == 'skin' ) {
1901 # Clear cached skin, so the new one displays immediately in Special:Preferences
1902 unset( $this->mSkin
);
1904 // Filter out any newlines that may have passed through input validation.
1905 // Newlines are used to separate items in the options blob.
1907 $val = str_replace( "\r\n", "\n", $val );
1908 $val = str_replace( "\r", "\n", $val );
1909 $val = str_replace( "\n", " ", $val );
1911 // Explicitly NULL values should refer to defaults
1912 global $wgDefaultUserOptions;
1913 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1914 $val = $wgDefaultUserOptions[$oname];
1916 $this->mOptions
[$oname] = $val;
1920 * Reset all options to the site defaults
1922 function restoreOptions() {
1923 $this->mOptions
= User
::getDefaultOptions();
1927 * Get the user's preferred date format.
1928 * @return \string User's preferred date format
1930 function getDatePreference() {
1931 // Important migration for old data rows
1932 if ( is_null( $this->mDatePreference
) ) {
1934 $value = $this->getOption( 'date' );
1935 $map = $wgLang->getDatePreferenceMigrationMap();
1936 if ( isset( $map[$value] ) ) {
1937 $value = $map[$value];
1939 $this->mDatePreference
= $value;
1941 return $this->mDatePreference
;
1945 * Get the permissions this user has.
1946 * @return \type{\arrayof{\string}} Array of permission names
1948 function getRights() {
1949 if ( is_null( $this->mRights
) ) {
1950 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1951 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1952 // Force reindexation of rights when a hook has unset one of them
1953 $this->mRights
= array_values( $this->mRights
);
1955 return $this->mRights
;
1959 * Get the list of explicit group memberships this user has.
1960 * The implicit * and user groups are not included.
1961 * @return \type{\arrayof{\string}} Array of internal group names
1963 function getGroups() {
1965 return $this->mGroups
;
1969 * Get the list of implicit group memberships this user has.
1970 * This includes all explicit groups, plus 'user' if logged in,
1971 * '*' for all accounts and autopromoted groups
1972 * @param $recache \bool Whether to avoid the cache
1973 * @return \type{\arrayof{\string}} Array of internal group names
1975 function getEffectiveGroups( $recache = false ) {
1976 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1977 $this->mEffectiveGroups
= $this->getGroups();
1978 $this->mEffectiveGroups
[] = '*';
1979 if( $this->getId() ) {
1980 $this->mEffectiveGroups
[] = 'user';
1982 $this->mEffectiveGroups
= array_unique( array_merge(
1983 $this->mEffectiveGroups
,
1984 Autopromote
::getAutopromoteGroups( $this )
1987 # Hook for additional groups
1988 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1991 return $this->mEffectiveGroups
;
1995 * Get the user's edit count.
1996 * @return \int User'e edit count
1998 function getEditCount() {
2000 if ( !isset( $this->mEditCount
) ) {
2001 /* Populate the count, if it has not been populated yet */
2002 $this->mEditCount
= User
::edits($this->mId
);
2004 return $this->mEditCount
;
2012 * Add the user to the given group.
2013 * This takes immediate effect.
2014 * @param $group \string Name of the group to add
2016 function addGroup( $group ) {
2017 $dbw = wfGetDB( DB_MASTER
);
2018 if( $this->getId() ) {
2019 $dbw->insert( 'user_groups',
2021 'ug_user' => $this->getID(),
2022 'ug_group' => $group,
2025 array( 'IGNORE' ) );
2028 $this->loadGroups();
2029 $this->mGroups
[] = $group;
2030 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2032 $this->invalidateCache();
2036 * Remove the user from the given group.
2037 * This takes immediate effect.
2038 * @param $group \string Name of the group to remove
2040 function removeGroup( $group ) {
2042 $dbw = wfGetDB( DB_MASTER
);
2043 $dbw->delete( 'user_groups',
2045 'ug_user' => $this->getID(),
2046 'ug_group' => $group,
2048 'User::removeGroup' );
2050 $this->loadGroups();
2051 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2052 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2054 $this->invalidateCache();
2059 * Get whether the user is logged in
2060 * @return \bool True or false
2062 function isLoggedIn() {
2063 return $this->getID() != 0;
2067 * Get whether the user is anonymous
2068 * @return \bool True or false
2071 return !$this->isLoggedIn();
2075 * Get whether the user is a bot
2076 * @return \bool True or false
2080 wfDeprecated( __METHOD__
);
2081 return $this->isAllowed( 'bot' );
2085 * Check if user is allowed to access a feature / make an action
2086 * @param $action \string action to be checked
2087 * @return \bool True if action is allowed, else false
2089 function isAllowed( $action = '' ) {
2090 if ( $action === '' )
2091 return true; // In the spirit of DWIM
2092 # Patrolling may not be enabled
2093 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2094 global $wgUseRCPatrol, $wgUseNPPatrol;
2095 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2098 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2099 # by misconfiguration: 0 == 'foo'
2100 return in_array( $action, $this->getRights(), true );
2104 * Check whether to enable recent changes patrol features for this user
2105 * @return \bool True or false
2107 public function useRCPatrol() {
2108 global $wgUseRCPatrol;
2109 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2113 * Check whether to enable new pages patrol features for this user
2114 * @return \bool True or false
2116 public function useNPPatrol() {
2117 global $wgUseRCPatrol, $wgUseNPPatrol;
2118 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2122 * Get the current skin, loading it if required
2123 * @return \type{Skin} Current skin
2124 * @todo FIXME : need to check the old failback system [AV]
2126 function &getSkin() {
2127 global $wgRequest, $wgAllowUserSkin, $wgDefaultSkin;
2128 if ( ! isset( $this->mSkin
) ) {
2129 wfProfileIn( __METHOD__
);
2131 if( $wgAllowUserSkin ) {
2133 $userSkin = $this->getOption( 'skin' );
2134 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2136 # if we're not allowing users to override, then use the default
2137 $userSkin = $wgDefaultSkin;
2140 $this->mSkin
=& Skin
::newFromKey( $userSkin );
2141 wfProfileOut( __METHOD__
);
2143 return $this->mSkin
;
2147 * Check the watched status of an article.
2148 * @param $title \type{Title} Title of the article to look at
2149 * @return \bool True if article is watched
2151 function isWatched( $title ) {
2152 $wl = WatchedItem
::fromUserTitle( $this, $title );
2153 return $wl->isWatched();
2158 * @param $title \type{Title} Title of the article to look at
2160 function addWatch( $title ) {
2161 $wl = WatchedItem
::fromUserTitle( $this, $title );
2163 $this->invalidateCache();
2167 * Stop watching an article.
2168 * @param $title \type{Title} Title of the article to look at
2170 function removeWatch( $title ) {
2171 $wl = WatchedItem
::fromUserTitle( $this, $title );
2173 $this->invalidateCache();
2177 * Clear the user's notification timestamp for the given title.
2178 * If e-notif e-mails are on, they will receive notification mails on
2179 * the next change of the page if it's watched etc.
2180 * @param $title \type{Title} Title of the article to look at
2182 function clearNotification( &$title ) {
2183 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2185 # Do nothing if the database is locked to writes
2186 if( wfReadOnly() ) {
2190 if ($title->getNamespace() == NS_USER_TALK
&&
2191 $title->getText() == $this->getName() ) {
2192 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2194 $this->setNewtalk( false );
2197 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2201 if( $this->isAnon() ) {
2202 // Nothing else to do...
2206 // Only update the timestamp if the page is being watched.
2207 // The query to find out if it is watched is cached both in memcached and per-invocation,
2208 // and when it does have to be executed, it can be on a slave
2209 // If this is the user's newtalk page, we always update the timestamp
2210 if ($title->getNamespace() == NS_USER_TALK
&&
2211 $title->getText() == $wgUser->getName())
2214 } elseif ( $this->getId() == $wgUser->getId() ) {
2215 $watched = $title->userIsWatching();
2220 // If the page is watched by the user (or may be watched), update the timestamp on any
2221 // any matching rows
2223 $dbw = wfGetDB( DB_MASTER
);
2224 $dbw->update( 'watchlist',
2226 'wl_notificationtimestamp' => NULL
2227 ), array( /* WHERE */
2228 'wl_title' => $title->getDBkey(),
2229 'wl_namespace' => $title->getNamespace(),
2230 'wl_user' => $this->getID()
2237 * Resets all of the given user's page-change notification timestamps.
2238 * If e-notif e-mails are on, they will receive notification mails on
2239 * the next change of any watched page.
2241 * @param $currentUser \int User ID
2243 function clearAllNotifications( $currentUser ) {
2244 global $wgUseEnotif, $wgShowUpdatedMarker;
2245 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2246 $this->setNewtalk( false );
2249 if( $currentUser != 0 ) {
2250 $dbw = wfGetDB( DB_MASTER
);
2251 $dbw->update( 'watchlist',
2253 'wl_notificationtimestamp' => NULL
2254 ), array( /* WHERE */
2255 'wl_user' => $currentUser
2258 # We also need to clear here the "you have new message" notification for the own user_talk page
2259 # This is cleared one page view later in Article::viewUpdates();
2264 * Encode this user's options as a string
2265 * @return \string Encoded options
2268 function encodeOptions() {
2270 if ( is_null( $this->mOptions
) ) {
2271 $this->mOptions
= User
::getDefaultOptions();
2274 foreach ( $this->mOptions
as $oname => $oval ) {
2275 array_push( $a, $oname.'='.$oval );
2277 $s = implode( "\n", $a );
2282 * Set this user's options from an encoded string
2283 * @param $str \string Encoded options to import
2286 function decodeOptions( $str ) {
2287 $this->mOptions
= array();
2288 $a = explode( "\n", $str );
2289 foreach ( $a as $s ) {
2291 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2292 $this->mOptions
[$m[1]] = $m[2];
2298 * Set a cookie on the user's client. Wrapper for
2299 * WebResponse::setCookie
2300 * @param $name \string Name of the cookie to set
2301 * @param $value \string Value to set
2302 * @param $exp \int Expiration time, as a UNIX time value;
2303 * if 0 or not specified, use the default $wgCookieExpiration
2305 protected function setCookie( $name, $value, $exp=0 ) {
2307 $wgRequest->response()->setcookie( $name, $value, $exp );
2311 * Clear a cookie on the user's client
2312 * @param $name \string Name of the cookie to clear
2314 protected function clearCookie( $name ) {
2315 $this->setCookie( $name, '', time() - 86400 );
2319 * Set the default cookies for this session on the user's client.
2321 function setCookies() {
2323 if ( 0 == $this->mId
) return;
2325 'wsUserID' => $this->mId
,
2326 'wsToken' => $this->mToken
,
2327 'wsUserName' => $this->getName()
2330 'UserID' => $this->mId
,
2331 'UserName' => $this->getName(),
2333 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2334 $cookies['Token'] = $this->mToken
;
2336 $cookies['Token'] = false;
2339 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2340 #check for null, since the hook could cause a null value
2341 if ( !is_null( $session ) && isset( $_SESSION ) ){
2342 $_SESSION = $session +
$_SESSION;
2344 foreach ( $cookies as $name => $value ) {
2345 if ( $value === false ) {
2346 $this->clearCookie( $name );
2348 $this->setCookie( $name, $value );
2354 * Log this user out.
2358 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2364 * Clear the user's cookies and session, and reset the instance cache.
2368 function doLogout() {
2369 $this->clearInstanceCache( 'defaults' );
2371 $_SESSION['wsUserID'] = 0;
2373 $this->clearCookie( 'UserID' );
2374 $this->clearCookie( 'Token' );
2376 # Remember when user logged out, to prevent seeing cached pages
2377 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2381 * Save this user's settings into the database.
2382 * @todo Only rarely do all these fields need to be set!
2384 function saveSettings() {
2386 if ( wfReadOnly() ) { return; }
2387 if ( 0 == $this->mId
) { return; }
2389 $this->mTouched
= self
::newTouchedTimestamp();
2391 $dbw = wfGetDB( DB_MASTER
);
2392 $dbw->update( 'user',
2394 'user_name' => $this->mName
,
2395 'user_password' => $this->mPassword
,
2396 'user_newpassword' => $this->mNewpassword
,
2397 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2398 'user_real_name' => $this->mRealName
,
2399 'user_email' => $this->mEmail
,
2400 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2401 'user_options' => $this->encodeOptions(),
2402 'user_touched' => $dbw->timestamp($this->mTouched
),
2403 'user_token' => $this->mToken
,
2404 'user_email_token' => $this->mEmailToken
,
2405 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2406 ), array( /* WHERE */
2407 'user_id' => $this->mId
2410 wfRunHooks( 'UserSaveSettings', array( $this ) );
2411 $this->clearSharedCache();
2412 $this->getUserPage()->invalidateCache();
2416 * If only this user's username is known, and it exists, return the user ID.
2418 function idForName() {
2419 $s = trim( $this->getName() );
2420 if ( $s === '' ) return 0;
2422 $dbr = wfGetDB( DB_SLAVE
);
2423 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2424 if ( $id === false ) {
2431 * Add a user to the database, return the user object
2433 * @param $name \string Username to add
2434 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2435 * - password The user's password. Password logins will be disabled if this is omitted.
2436 * - newpassword A temporary password mailed to the user
2437 * - email The user's email address
2438 * - email_authenticated The email authentication timestamp
2439 * - real_name The user's real name
2440 * - options An associative array of non-default options
2441 * - token Random authentication token. Do not set.
2442 * - registration Registration timestamp. Do not set.
2444 * @return \type{User} A new User object, or null if the username already exists
2446 static function createNew( $name, $params = array() ) {
2449 if ( isset( $params['options'] ) ) {
2450 $user->mOptions
= $params['options'] +
$user->mOptions
;
2451 unset( $params['options'] );
2453 $dbw = wfGetDB( DB_MASTER
);
2454 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2456 'user_id' => $seqVal,
2457 'user_name' => $name,
2458 'user_password' => $user->mPassword
,
2459 'user_newpassword' => $user->mNewpassword
,
2460 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2461 'user_email' => $user->mEmail
,
2462 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2463 'user_real_name' => $user->mRealName
,
2464 'user_options' => $user->encodeOptions(),
2465 'user_token' => $user->mToken
,
2466 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2467 'user_editcount' => 0,
2469 foreach ( $params as $name => $value ) {
2470 $fields["user_$name"] = $value;
2472 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2473 if ( $dbw->affectedRows() ) {
2474 $newUser = User
::newFromId( $dbw->insertId() );
2482 * Add this existing user object to the database
2484 function addToDatabase() {
2486 $dbw = wfGetDB( DB_MASTER
);
2487 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2488 $dbw->insert( 'user',
2490 'user_id' => $seqVal,
2491 'user_name' => $this->mName
,
2492 'user_password' => $this->mPassword
,
2493 'user_newpassword' => $this->mNewpassword
,
2494 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2495 'user_email' => $this->mEmail
,
2496 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2497 'user_real_name' => $this->mRealName
,
2498 'user_options' => $this->encodeOptions(),
2499 'user_token' => $this->mToken
,
2500 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2501 'user_editcount' => 0,
2504 $this->mId
= $dbw->insertId();
2506 // Clear instance cache other than user table data, which is already accurate
2507 $this->clearInstanceCache();
2511 * If this (non-anonymous) user is blocked, block any IP address
2512 * they've successfully logged in from.
2514 function spreadBlock() {
2515 wfDebug( __METHOD__
."()\n" );
2517 if ( $this->mId
== 0 ) {
2521 $userblock = Block
::newFromDB( '', $this->mId
);
2522 if ( !$userblock ) {
2526 $userblock->doAutoblock( wfGetIp() );
2531 * Generate a string which will be different for any combination of
2532 * user options which would produce different parser output.
2533 * This will be used as part of the hash key for the parser cache,
2534 * so users will the same options can share the same cached data
2537 * Extensions which require it should install 'PageRenderingHash' hook,
2538 * which will give them a chance to modify this key based on their own
2541 * @return \string Page rendering hash
2543 function getPageRenderingHash() {
2544 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2546 return $this->mHash
;
2549 // stubthreshold is only included below for completeness,
2550 // it will always be 0 when this function is called by parsercache.
2552 $confstr = $this->getOption( 'math' );
2553 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2554 if ( $wgUseDynamicDates ) {
2555 $confstr .= '!' . $this->getDatePreference();
2557 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2558 $confstr .= '!' . $wgLang->getCode();
2559 $confstr .= '!' . $this->getOption( 'thumbsize' );
2560 // add in language specific options, if any
2561 $extra = $wgContLang->getExtraHashOptions();
2564 $confstr .= $wgRenderHashAppend;
2566 // Give a chance for extensions to modify the hash, if they have
2567 // extra options or other effects on the parser cache.
2568 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2570 // Make it a valid memcached key fragment
2571 $confstr = str_replace( ' ', '_', $confstr );
2572 $this->mHash
= $confstr;
2577 * Get whether the user is explicitly blocked from account creation.
2578 * @return \bool True if blocked
2580 function isBlockedFromCreateAccount() {
2581 $this->getBlockedStatus();
2582 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2586 * Get whether the user is blocked from using Special:Emailuser.
2587 * @return \bool True if blocked
2589 function isBlockedFromEmailuser() {
2590 $this->getBlockedStatus();
2591 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2595 * Get whether the user is allowed to create an account.
2596 * @return \bool True if allowed
2598 function isAllowedToCreateAccount() {
2599 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2605 function setLoaded( $loaded ) {
2606 wfDeprecated( __METHOD__
);
2610 * Get this user's personal page title.
2612 * @return \type{Title} User's personal page title
2614 function getUserPage() {
2615 return Title
::makeTitle( NS_USER
, $this->getName() );
2619 * Get this user's talk page title.
2621 * @return \type{Title} User's talk page title
2623 function getTalkPage() {
2624 $title = $this->getUserPage();
2625 return $title->getTalkPage();
2629 * Get the maximum valid user ID.
2630 * @return \int User ID
2633 function getMaxID() {
2634 static $res; // cache
2636 if ( isset( $res ) )
2639 $dbr = wfGetDB( DB_SLAVE
);
2640 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2645 * Determine whether the user is a newbie. Newbies are either
2646 * anonymous IPs, or the most recently created accounts.
2647 * @return \bool True if the user is a newbie
2649 function isNewbie() {
2650 return !$this->isAllowed( 'autoconfirmed' );
2654 * Is the user active? We check to see if they've made at least
2655 * X number of edits in the last Y days.
2657 * @return \bool True if the user is active, false if not.
2659 public function isActiveEditor() {
2660 global $wgActiveUserEditCount, $wgActiveUserDays;
2661 $dbr = wfGetDB( DB_SLAVE
);
2663 // Stolen without shame from RC
2664 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2665 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
2666 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2668 $res = $dbr->select( 'revision', '1',
2669 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2671 array('LIMIT' => $wgActiveUserEditCount ) );
2673 $count = $dbr->numRows($res);
2674 $dbr->freeResult($res);
2676 return $count == $wgActiveUserEditCount;
2680 * Check to see if the given clear-text password is one of the accepted passwords
2681 * @param $password \string user password.
2682 * @return \bool True if the given password is correct, otherwise False.
2684 function checkPassword( $password ) {
2688 // Even though we stop people from creating passwords that
2689 // are shorter than this, doesn't mean people wont be able
2690 // to. Certain authentication plugins do NOT want to save
2691 // domain passwords in a mysql database, so we should
2692 // check this (incase $wgAuth->strict() is false).
2693 if( !$this->isValidPassword( $password ) ) {
2697 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2699 } elseif( $wgAuth->strict() ) {
2700 /* Auth plugin doesn't allow local authentication */
2702 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2703 /* Auth plugin doesn't allow local authentication for this user name */
2706 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2708 } elseif ( function_exists( 'iconv' ) ) {
2709 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2710 # Check for this with iconv
2711 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2712 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2720 * Check if the given clear-text password matches the temporary password
2721 * sent by e-mail for password reset operations.
2722 * @return \bool True if matches, false otherwise
2724 function checkTemporaryPassword( $plaintext ) {
2725 global $wgNewPasswordExpiry;
2726 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
2728 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
2729 return ( time() < $expiry );
2736 * Initialize (if necessary) and return a session token value
2737 * which can be used in edit forms to show that the user's
2738 * login credentials aren't being hijacked with a foreign form
2741 * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2742 * @return \string The new edit token
2744 function editToken( $salt = '' ) {
2745 if ( $this->isAnon() ) {
2746 return EDIT_TOKEN_SUFFIX
;
2748 if( !isset( $_SESSION['wsEditToken'] ) ) {
2749 $token = $this->generateToken();
2750 $_SESSION['wsEditToken'] = $token;
2752 $token = $_SESSION['wsEditToken'];
2754 if( is_array( $salt ) ) {
2755 $salt = implode( '|', $salt );
2757 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2762 * Generate a looking random token for various uses.
2764 * @param $salt \string Optional salt value
2765 * @return \string The new random token
2767 function generateToken( $salt = '' ) {
2768 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2769 return md5( $token . $salt );
2773 * Check given value against the token value stored in the session.
2774 * A match should confirm that the form was submitted from the
2775 * user's own login session, not a form submission from a third-party
2778 * @param $val \string Input value to compare
2779 * @param $salt \string Optional function-specific data for hashing
2780 * @return \bool Whether the token matches
2782 function matchEditToken( $val, $salt = '' ) {
2783 $sessionToken = $this->editToken( $salt );
2784 if ( $val != $sessionToken ) {
2785 wfDebug( "User::matchEditToken: broken session data\n" );
2787 return $val == $sessionToken;
2791 * Check given value against the token value stored in the session,
2792 * ignoring the suffix.
2794 * @param $val \string Input value to compare
2795 * @param $salt \string Optional function-specific data for hashing
2796 * @return \bool Whether the token matches
2798 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2799 $sessionToken = $this->editToken( $salt );
2800 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2804 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2805 * mail to the user's given address.
2807 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure.
2809 function sendConfirmationMail() {
2811 $expiration = null; // gets passed-by-ref and defined in next line.
2812 $token = $this->confirmationToken( $expiration );
2813 $url = $this->confirmationTokenUrl( $token );
2814 $invalidateURL = $this->invalidationTokenUrl( $token );
2815 $this->saveSettings();
2817 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2818 wfMsg( 'confirmemail_body',
2822 $wgLang->timeanddate( $expiration, false ),
2827 * Send an e-mail to this user's account. Does not check for
2828 * confirmed status or validity.
2830 * @param $subject \string Message subject
2831 * @param $body \string Message body
2832 * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2833 * @param $replyto \string Reply-To address
2834 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure
2836 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2837 if( is_null( $from ) ) {
2838 global $wgPasswordSender;
2839 $from = $wgPasswordSender;
2842 $to = new MailAddress( $this );
2843 $sender = new MailAddress( $from );
2844 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2848 * Generate, store, and return a new e-mail confirmation code.
2849 * A hash (unsalted, since it's used as a key) is stored.
2851 * @note Call saveSettings() after calling this function to commit
2852 * this change to the database.
2854 * @param[out] &$expiration \mixed Accepts the expiration time
2855 * @return \string New token
2858 function confirmationToken( &$expiration ) {
2860 $expires = $now +
7 * 24 * 60 * 60;
2861 $expiration = wfTimestamp( TS_MW
, $expires );
2862 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2863 $hash = md5( $token );
2865 $this->mEmailToken
= $hash;
2866 $this->mEmailTokenExpires
= $expiration;
2871 * Return a URL the user can use to confirm their email address.
2872 * @param $token \string Accepts the email confirmation token
2873 * @return \string New token URL
2876 function confirmationTokenUrl( $token ) {
2877 return $this->getTokenUrl( 'ConfirmEmail', $token );
2880 * Return a URL the user can use to invalidate their email address.
2881 * @param $token \string Accepts the email confirmation token
2882 * @return \string New token URL
2885 function invalidationTokenUrl( $token ) {
2886 return $this->getTokenUrl( 'Invalidateemail', $token );
2890 * Internal function to format the e-mail validation/invalidation URLs.
2891 * This uses $wgArticlePath directly as a quickie hack to use the
2892 * hardcoded English names of the Special: pages, for ASCII safety.
2894 * @note Since these URLs get dropped directly into emails, using the
2895 * short English names avoids insanely long URL-encoded links, which
2896 * also sometimes can get corrupted in some browsers/mailers
2897 * (bug 6957 with Gmail and Internet Explorer).
2899 * @param $page \string Special page
2900 * @param $token \string Token
2901 * @return \string Formatted URL
2903 protected function getTokenUrl( $page, $token ) {
2904 global $wgArticlePath;
2908 "Special:$page/$token",
2913 * Mark the e-mail address confirmed.
2915 * @note Call saveSettings() after calling this function to commit the change.
2917 function confirmEmail() {
2918 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2923 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2924 * address if it was already confirmed.
2926 * @note Call saveSettings() after calling this function to commit the change.
2928 function invalidateEmail() {
2930 $this->mEmailToken
= null;
2931 $this->mEmailTokenExpires
= null;
2932 $this->setEmailAuthenticationTimestamp( null );
2937 * Set the e-mail authentication timestamp.
2938 * @param $timestamp \string TS_MW timestamp
2940 function setEmailAuthenticationTimestamp( $timestamp ) {
2942 $this->mEmailAuthenticated
= $timestamp;
2943 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2947 * Is this user allowed to send e-mails within limits of current
2948 * site configuration?
2949 * @return \bool True if allowed
2951 function canSendEmail() {
2952 global $wgEnableEmail, $wgEnableUserEmail;
2953 if( !$wgEnableEmail ||
!$wgEnableUserEmail ) {
2956 $canSend = $this->isEmailConfirmed();
2957 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2962 * Is this user allowed to receive e-mails within limits of current
2963 * site configuration?
2964 * @return \bool True if allowed
2966 function canReceiveEmail() {
2967 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2971 * Is this user's e-mail address valid-looking and confirmed within
2972 * limits of the current site configuration?
2974 * @note If $wgEmailAuthentication is on, this may require the user to have
2975 * confirmed their address by returning a code or using a password
2976 * sent to the address from the wiki.
2978 * @return \bool True if confirmed
2980 function isEmailConfirmed() {
2981 global $wgEmailAuthentication;
2984 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2985 if( $this->isAnon() )
2987 if( !self
::isValidEmailAddr( $this->mEmail
) )
2989 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2998 * Check whether there is an outstanding request for e-mail confirmation.
2999 * @return \bool True if pending
3001 function isEmailConfirmationPending() {
3002 global $wgEmailAuthentication;
3003 return $wgEmailAuthentication &&
3004 !$this->isEmailConfirmed() &&
3005 $this->mEmailToken
&&
3006 $this->mEmailTokenExpires
> wfTimestamp();
3010 * Get the timestamp of account creation.
3012 * @return \types{\string,\bool} string Timestamp of account creation, or false for
3013 * non-existent/anonymous user accounts.
3015 public function getRegistration() {
3016 return $this->getId() > 0
3017 ?
$this->mRegistration
3022 * Get the timestamp of the first edit
3024 * @return \types{\string,\bool} string Timestamp of first edit, or false for
3025 * non-existent/anonymous user accounts.
3027 public function getFirstEditTimestamp() {
3028 if( $this->getId() == 0 ) return false; // anons
3029 $dbr = wfGetDB( DB_SLAVE
);
3030 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3031 array( 'rev_user' => $this->getId() ),
3033 array( 'ORDER BY' => 'rev_timestamp ASC' )
3035 if( !$time ) return false; // no edits
3036 return wfTimestamp( TS_MW
, $time );
3040 * Get the permissions associated with a given list of groups
3042 * @param $groups \type{\arrayof{\string}} List of internal group names
3043 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3045 static function getGroupPermissions( $groups ) {
3046 global $wgGroupPermissions;
3048 foreach( $groups as $group ) {
3049 if( isset( $wgGroupPermissions[$group] ) ) {
3050 $rights = array_merge( $rights,
3051 // array_filter removes empty items
3052 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3055 return array_unique($rights);
3059 * Get all the groups who have a given permission
3061 * @param $role \string Role to check
3062 * @return \type{\arrayof{\string}} List of internal group names with the given permission
3064 static function getGroupsWithPermission( $role ) {
3065 global $wgGroupPermissions;
3066 $allowedGroups = array();
3067 foreach ( $wgGroupPermissions as $group => $rights ) {
3068 if ( isset( $rights[$role] ) && $rights[$role] ) {
3069 $allowedGroups[] = $group;
3072 return $allowedGroups;
3076 * Get the localized descriptive name for a group, if it exists
3078 * @param $group \string Internal group name
3079 * @return \string Localized descriptive group name
3081 static function getGroupName( $group ) {
3082 global $wgMessageCache;
3083 $wgMessageCache->loadAllMessages();
3084 $key = "group-$group";
3085 $name = wfMsg( $key );
3086 return $name == '' ||
wfEmptyMsg( $key, $name )
3092 * Get the localized descriptive name for a member of a group, if it exists
3094 * @param $group \string Internal group name
3095 * @return \string Localized name for group member
3097 static function getGroupMember( $group ) {
3098 global $wgMessageCache;
3099 $wgMessageCache->loadAllMessages();
3100 $key = "group-$group-member";
3101 $name = wfMsg( $key );
3102 return $name == '' ||
wfEmptyMsg( $key, $name )
3108 * Return the set of defined explicit groups.
3109 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3110 * are not included, as they are defined automatically, not in the database.
3111 * @return \type{\arrayof{\string}} Array of internal group names
3113 static function getAllGroups() {
3114 global $wgGroupPermissions;
3116 array_keys( $wgGroupPermissions ),
3117 self
::getImplicitGroups()
3122 * Get a list of all available permissions.
3123 * @return \type{\arrayof{\string}} Array of permission names
3125 static function getAllRights() {
3126 if ( self
::$mAllRights === false ) {
3127 global $wgAvailableRights;
3128 if ( count( $wgAvailableRights ) ) {
3129 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3131 self
::$mAllRights = self
::$mCoreRights;
3133 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3135 return self
::$mAllRights;
3139 * Get a list of implicit groups
3140 * @return \type{\arrayof{\string}} Array of internal group names
3142 public static function getImplicitGroups() {
3143 global $wgImplicitGroups;
3144 $groups = $wgImplicitGroups;
3145 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3150 * Get the title of a page describing a particular group
3152 * @param $group \string Internal group name
3153 * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3155 static function getGroupPage( $group ) {
3156 global $wgMessageCache;
3157 $wgMessageCache->loadAllMessages();
3158 $page = wfMsgForContent( 'grouppage-' . $group );
3159 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3160 $title = Title
::newFromText( $page );
3161 if( is_object( $title ) )
3168 * Create a link to the group in HTML, if available;
3169 * else return the group name.
3171 * @param $group \string Internal name of the group
3172 * @param $text \string The text of the link
3173 * @return \string HTML link to the group
3175 static function makeGroupLinkHTML( $group, $text = '' ) {
3177 $text = self
::getGroupName( $group );
3179 $title = self
::getGroupPage( $group );
3182 $sk = $wgUser->getSkin();
3183 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3190 * Create a link to the group in Wikitext, if available;
3191 * else return the group name.
3193 * @param $group \string Internal name of the group
3194 * @param $text \string The text of the link
3195 * @return \string Wikilink to the group
3197 static function makeGroupLinkWiki( $group, $text = '' ) {
3199 $text = self
::getGroupName( $group );
3201 $title = self
::getGroupPage( $group );
3203 $page = $title->getPrefixedText();
3204 return "[[$page|$text]]";
3211 * Increment the user's edit-count field.
3212 * Will have no effect for anonymous users.
3214 function incEditCount() {
3215 if( !$this->isAnon() ) {
3216 $dbw = wfGetDB( DB_MASTER
);
3217 $dbw->update( 'user',
3218 array( 'user_editcount=user_editcount+1' ),
3219 array( 'user_id' => $this->getId() ),
3222 // Lazy initialization check...
3223 if( $dbw->affectedRows() == 0 ) {
3224 // Pull from a slave to be less cruel to servers
3225 // Accuracy isn't the point anyway here
3226 $dbr = wfGetDB( DB_SLAVE
);
3227 $count = $dbr->selectField( 'revision',
3229 array( 'rev_user' => $this->getId() ),
3232 // Now here's a goddamn hack...
3233 if( $dbr !== $dbw ) {
3234 // If we actually have a slave server, the count is
3235 // at least one behind because the current transaction
3236 // has not been committed and replicated.
3239 // But if DB_SLAVE is selecting the master, then the
3240 // count we just read includes the revision that was
3241 // just added in the working transaction.
3244 $dbw->update( 'user',
3245 array( 'user_editcount' => $count ),
3246 array( 'user_id' => $this->getId() ),
3250 // edit count in user cache too
3251 $this->invalidateCache();
3255 * Get the description of a given right
3257 * @param $right \string Right to query
3258 * @return \string Localized description of the right
3260 static function getRightDescription( $right ) {
3261 global $wgMessageCache;
3262 $wgMessageCache->loadAllMessages();
3263 $key = "right-$right";
3264 $name = wfMsg( $key );
3265 return $name == '' ||
wfEmptyMsg( $key, $name )
3271 * Make an old-style password hash
3273 * @param $password \string Plain-text password
3274 * @param $userId \string User ID
3275 * @return \string Password hash
3277 static function oldCrypt( $password, $userId ) {
3278 global $wgPasswordSalt;
3279 if ( $wgPasswordSalt ) {
3280 return md5( $userId . '-' . md5( $password ) );
3282 return md5( $password );
3287 * Make a new-style password hash
3289 * @param $password \string Plain-text password
3290 * @param $salt \string Optional salt, may be random or the user ID.
3291 * If unspecified or false, will generate one automatically
3292 * @return \string Password hash
3294 static function crypt( $password, $salt = false ) {
3295 global $wgPasswordSalt;
3298 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3302 if( $wgPasswordSalt ) {
3303 if ( $salt === false ) {
3304 $salt = substr( wfGenerateToken(), 0, 8 );
3306 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3308 return ':A:' . md5( $password );
3313 * Compare a password hash with a plain-text password. Requires the user
3314 * ID if there's a chance that the hash is an old-style hash.
3316 * @param $hash \string Password hash
3317 * @param $password \string Plain-text password to compare
3318 * @param $userId \string User ID for old-style password salt
3321 static function comparePasswords( $hash, $password, $userId = false ) {
3323 $type = substr( $hash, 0, 3 );
3326 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3330 if ( $type == ':A:' ) {
3332 return md5( $password ) === substr( $hash, 3 );
3333 } elseif ( $type == ':B:' ) {
3335 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3336 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3339 return self
::oldCrypt( $password, $userId ) === $hash;
3344 * Add a newuser log entry for this user
3345 * @param $byEmail Boolean: account made by email?
3347 public function addNewUserLogEntry( $byEmail = false ) {
3348 global $wgUser, $wgContLang, $wgNewUserLog;
3349 if( empty($wgNewUserLog) ) {
3350 return true; // disabled
3352 $talk = $wgContLang->getFormattedNsText( NS_TALK
);
3353 if( $this->getName() == $wgUser->getName() ) {
3357 $action = 'create2';
3358 $message = $byEmail ?
wfMsgForContent( 'newuserlog-byemail' ) : '';
3360 $log = new LogPage( 'newusers' );
3361 $log->addEntry( $action, $this->getUserPage(), $message, array( $this->getId() ) );
3366 * Add an autocreate newuser log entry for this user
3367 * Used by things like CentralAuth and perhaps other authplugins.
3369 public function addNewUserLogEntryAutoCreate() {
3370 global $wgNewUserLog;
3371 if( empty($wgNewUserLog) ) {
3372 return true; // disabled
3374 $log = new LogPage( 'newusers', false );
3375 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );