3 * Implements the User class for the %MediaWiki software.
8 * \type{\int} Number of characters in user_token field.
11 define( 'USER_TOKEN_LENGTH', 32 );
14 * \type{\int} Serialized record version.
17 define( 'MW_USER_VERSION', 6 );
20 * \type{\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',
97 * \type{\arrayof{\string}} List of member variables which are saved to the
98 * shared cache (memcached). Any operation which changes the
99 * corresponding database fields must call a cache-clearing function.
102 static $mCacheVars = array(
114 'mEmailAuthenticated',
116 'mEmailTokenExpires',
124 * \type{\arrayof{\string}} Core rights.
125 * Each of these should have a corresponding message of the form
129 static $mCoreRights = array(
172 * \type{\string} Cached results of getAllRights()
174 static $mAllRights = false;
176 /** @name Cache variables */
178 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
179 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
180 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
184 * \type{\bool} Whether the cache variables have been loaded.
186 var $mDataLoaded, $mAuthLoaded;
189 * \type{\string} Initialization data source if mDataLoaded==false. May be one of:
190 * - 'defaults' anonymous user initialised from class defaults
191 * - 'name' initialise from mName
192 * - 'id' initialise from mId
193 * - 'session' log in from cookies or session if possible
195 * Use the User::newFrom*() family of functions to set this.
199 /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
201 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
202 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
203 $mLocked, $mHideName;
207 * Lightweight constructor for an anonymous user.
208 * Use the User::newFrom* factory functions for other kinds of users.
212 * @see newFromConfirmationCode()
213 * @see newFromSession()
217 $this->clearInstanceCache( 'defaults' );
221 * Load the user table data for this object from the source given by mFrom.
224 if ( $this->mDataLoaded
) {
227 wfProfileIn( __METHOD__
);
229 # Set it now to avoid infinite recursion in accessors
230 $this->mDataLoaded
= true;
232 switch ( $this->mFrom
) {
234 $this->loadDefaults();
237 $this->mId
= self
::idFromName( $this->mName
);
239 # Nonexistent user placeholder object
240 $this->loadDefaults( $this->mName
);
249 $this->loadFromSession();
252 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
254 wfProfileOut( __METHOD__
);
258 * Load user table data, given mId has already been set.
259 * @return \type{\bool} false if the ID does not exist, true otherwise
262 function loadFromId() {
264 if ( $this->mId
== 0 ) {
265 $this->loadDefaults();
270 $key = wfMemcKey( 'user', 'id', $this->mId
);
271 $data = $wgMemc->get( $key );
272 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
273 # Object is expired, load from DB
278 wfDebug( "Cache miss for user {$this->mId}\n" );
280 if ( !$this->loadFromDatabase() ) {
281 # Can't load from ID, user is anonymous
284 $this->saveToCache();
286 wfDebug( "Got user {$this->mId} from cache\n" );
288 foreach ( self
::$mCacheVars as $name ) {
289 $this->$name = $data[$name];
296 * Save user data to the shared cache
298 function saveToCache() {
301 if ( $this->isAnon() ) {
302 // Anonymous users are uncached
306 foreach ( self
::$mCacheVars as $name ) {
307 $data[$name] = $this->$name;
309 $data['mVersion'] = MW_USER_VERSION
;
310 $key = wfMemcKey( 'user', 'id', $this->mId
);
312 $wgMemc->set( $key, $data );
316 /** @name newFrom*() static factory methods */
320 * Static factory method for creation from username.
322 * This is slightly less efficient than newFromId(), so use newFromId() if
323 * you have both an ID and a name handy.
325 * @param $name \type{\string} Username, validated by Title::newFromText()
326 * @param $validate \type{\mixed} Validate username. Takes the same parameters as
327 * User::getCanonicalName(), except that true is accepted as an alias
328 * for 'valid', for BC.
330 * @return \type{User} The User object, or null if the username is invalid. If the
331 * username is not present in the database, the result will be a user object
332 * with a name, zero user ID and default settings.
334 static function newFromName( $name, $validate = 'valid' ) {
335 if ( $validate === true ) {
338 $name = self
::getCanonicalName( $name, $validate );
339 if ( $name === false ) {
342 # Create unloaded user object
351 * Static factory method for creation from a given user ID.
353 * @param $id \type{\int} Valid user ID
354 * @return \type{User} The corresponding User object
356 static function newFromId( $id ) {
364 * Factory method to fetch whichever user has a given email confirmation code.
365 * This code is generated when an account is created or its e-mail address
368 * If the code is invalid or has expired, returns NULL.
370 * @param $code \type{\string} Confirmation code
371 * @return \type{User}
373 static function newFromConfirmationCode( $code ) {
374 $dbr = wfGetDB( DB_SLAVE
);
375 $id = $dbr->selectField( 'user', 'user_id', array(
376 'user_email_token' => md5( $code ),
377 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
379 if( $id !== false ) {
380 return User
::newFromId( $id );
387 * Create a new user object using data from session or cookies. If the
388 * login credentials are invalid, the result is an anonymous user.
390 * @return \type{User}
392 static function newFromSession() {
394 $user->mFrom
= 'session';
399 * Create a new user object from a user row.
400 * The row should have all fields from the user table in it.
401 * @param $row array A row from the user table
402 * @return \type{User}
404 static function newFromRow( $row ) {
406 $user->loadFromRow( $row );
414 * Get the username corresponding to a given user ID
415 * @param $id \type{\int} %User ID
416 * @return \type{\string} The corresponding username
418 static function whoIs( $id ) {
419 $dbr = wfGetDB( DB_SLAVE
);
420 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
424 * Get the real name of a user given their user ID
426 * @param $id \type{\int} %User ID
427 * @return \type{\string} The corresponding user's real name
429 static function whoIsReal( $id ) {
430 $dbr = wfGetDB( DB_SLAVE
);
431 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
435 * Get database id given a user name
436 * @param $name \type{\string} Username
437 * @return \twotypes{\int,\null} The corresponding user's ID, or null if user is nonexistent
440 static function idFromName( $name ) {
441 $nt = Title
::newFromText( $name );
442 if( is_null( $nt ) ) {
446 $dbr = wfGetDB( DB_SLAVE
);
447 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
449 if ( $s === false ) {
457 * Does the string match an anonymous IPv4 address?
459 * This function exists for username validation, in order to reject
460 * usernames which are similar in form to IP addresses. Strings such
461 * as 300.300.300.300 will return true because it looks like an IP
462 * address, despite not being strictly valid.
464 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
465 * address because the usemod software would "cloak" anonymous IP
466 * addresses like this, if we allowed accounts like this to be created
467 * new users could get the old edits of these anonymous users.
469 * @param $name \type{\string} String to match
470 * @return \type{\bool} True or false
472 static function isIP( $name ) {
473 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
477 * Is the input a valid username?
479 * Checks if the input is a valid username, we don't want an empty string,
480 * an IP address, anything that containins slashes (would mess up subpages),
481 * is longer than the maximum allowed username size or doesn't begin with
484 * @param $name \type{\string} String to match
485 * @return \type{\bool} True or false
487 static function isValidUserName( $name ) {
488 global $wgContLang, $wgMaxNameChars;
491 || User
::isIP( $name )
492 ||
strpos( $name, '/' ) !== false
493 ||
strlen( $name ) > $wgMaxNameChars
494 ||
$name != $wgContLang->ucfirst( $name ) ) {
495 wfDebugLog( 'username', __METHOD__
.
496 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
500 // Ensure that the name can't be misresolved as a different title,
501 // such as with extra namespace keys at the start.
502 $parsed = Title
::newFromText( $name );
503 if( is_null( $parsed )
504 ||
$parsed->getNamespace()
505 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
506 wfDebugLog( 'username', __METHOD__
.
507 ": '$name' invalid due to ambiguous prefixes" );
511 // Check an additional blacklist of troublemaker characters.
512 // Should these be merged into the title char list?
513 $unicodeBlacklist = '/[' .
514 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
515 '\x{00a0}' . # non-breaking space
516 '\x{2000}-\x{200f}' . # various whitespace
517 '\x{2028}-\x{202f}' . # breaks and control chars
518 '\x{3000}' . # ideographic space
519 '\x{e000}-\x{f8ff}' . # private use
521 if( preg_match( $unicodeBlacklist, $name ) ) {
522 wfDebugLog( 'username', __METHOD__
.
523 ": '$name' invalid due to blacklisted characters" );
531 * Usernames which fail to pass this function will be blocked
532 * from user login and new account registrations, but may be used
533 * internally by batch processes.
535 * If an account already exists in this form, login will be blocked
536 * by a failure to pass this function.
538 * @param $name \type{\string} String to match
539 * @return \type{\bool} True or false
541 static function isUsableName( $name ) {
542 global $wgReservedUsernames;
543 // Must be a valid username, obviously ;)
544 if ( !self
::isValidUserName( $name ) ) {
548 static $reservedUsernames = false;
549 if ( !$reservedUsernames ) {
550 $reservedUsernames = $wgReservedUsernames;
551 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
554 // Certain names may be reserved for batch processes.
555 foreach ( $reservedUsernames as $reserved ) {
556 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
557 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
559 if ( $reserved == $name ) {
567 * Usernames which fail to pass this function will be blocked
568 * from new account registrations, but may be used internally
569 * either by batch processes or by user accounts which have
570 * already been created.
572 * Additional character blacklisting may be added here
573 * rather than in isValidUserName() to avoid disrupting
576 * @param $name \type{\string} String to match
577 * @return \type{\bool} True or false
579 static function isCreatableName( $name ) {
581 self
::isUsableName( $name ) &&
583 // Registration-time character blacklisting...
584 strpos( $name, '@' ) === false;
588 * Is the input a valid password for this user?
590 * @param $password \type{\string} Desired password
591 * @return \type{\bool} True or false
593 function isValidPassword( $password ) {
594 global $wgMinimalPasswordLength, $wgContLang;
597 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
599 if( $result === false )
602 // Password needs to be long enough, and can't be the same as the username
603 return strlen( $password ) >= $wgMinimalPasswordLength
604 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
608 * Does a string look like an e-mail address?
610 * There used to be a regular expression here, it got removed because it
611 * rejected valid addresses. Actually just check if there is '@' somewhere
612 * in the given address.
614 * @todo Check for RFC 2822 compilance (bug 959)
616 * @param $addr \type{\string} E-mail address
617 * @return \type{\bool} True or false
619 public static function isValidEmailAddr( $addr ) {
621 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
625 return strpos( $addr, '@' ) !== false;
629 * Given unvalidated user input, return a canonical username, or false if
630 * the username is invalid.
631 * @param $name \type{\string} User input
632 * @param $validate \twotypes{\string,\bool} Type of validation to use:
633 * - false No validation
634 * - 'valid' Valid for batch processes
635 * - 'usable' Valid for batch processes and login
636 * - 'creatable' Valid for batch processes, login and account creation
638 static function getCanonicalName( $name, $validate = 'valid' ) {
639 # Force usernames to capital
641 $name = $wgContLang->ucfirst( $name );
643 # Reject names containing '#'; these will be cleaned up
644 # with title normalisation, but then it's too late to
646 if( strpos( $name, '#' ) !== false )
649 # Clean up name according to title rules
650 $t = ($validate === 'valid') ?
651 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
652 # Check for invalid titles
653 if( is_null( $t ) ) {
657 # Reject various classes of invalid names
658 $name = $t->getText();
660 $name = $wgAuth->getCanonicalName( $t->getText() );
662 switch ( $validate ) {
666 if ( !User
::isValidUserName( $name ) ) {
671 if ( !User
::isUsableName( $name ) ) {
676 if ( !User
::isCreatableName( $name ) ) {
681 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
687 * Count the number of edits of a user
688 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
690 * @param $uid \type{\int} %User ID to check
691 * @return \type{\int} The user's edit count
693 static function edits( $uid ) {
694 wfProfileIn( __METHOD__
);
695 $dbr = wfGetDB( DB_SLAVE
);
696 // check if the user_editcount field has been initialized
697 $field = $dbr->selectField(
698 'user', 'user_editcount',
699 array( 'user_id' => $uid ),
703 if( $field === null ) { // it has not been initialized. do so.
704 $dbw = wfGetDB( DB_MASTER
);
705 $count = $dbr->selectField(
706 'revision', 'count(*)',
707 array( 'rev_user' => $uid ),
712 array( 'user_editcount' => $count ),
713 array( 'user_id' => $uid ),
719 wfProfileOut( __METHOD__
);
724 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
725 * @todo hash random numbers to improve security, like generateToken()
727 * @return \type{\string} New random password
729 static function randomPassword() {
730 global $wgMinimalPasswordLength;
731 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
732 $l = strlen( $pwchars ) - 1;
734 $pwlength = max( 7, $wgMinimalPasswordLength );
735 $digit = mt_rand(0, $pwlength - 1);
737 for ( $i = 0; $i < $pwlength; $i++
) {
738 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
744 * Set cached properties to default.
746 * @note This no longer clears uncached lazy-initialised properties;
747 * the constructor does that instead.
750 function loadDefaults( $name = false ) {
751 wfProfileIn( __METHOD__
);
753 global $wgCookiePrefix;
756 $this->mName
= $name;
757 $this->mRealName
= '';
758 $this->mPassword
= $this->mNewpassword
= '';
759 $this->mNewpassTime
= null;
761 $this->mOptions
= null; # Defer init
763 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
764 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
766 $this->mTouched
= '0'; # Allow any pages to be cached
769 $this->setToken(); # Random
770 $this->mEmailAuthenticated
= null;
771 $this->mEmailToken
= '';
772 $this->mEmailTokenExpires
= null;
773 $this->mRegistration
= wfTimestamp( TS_MW
);
774 $this->mGroups
= array();
776 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
778 wfProfileOut( __METHOD__
);
782 * @deprecated Use wfSetupSession().
784 function SetupSession() {
785 wfDeprecated( __METHOD__
);
790 * Load user data from the session or login cookie. If there are no valid
791 * credentials, initialises the user as an anonymous user.
792 * @return \type{\bool} True if the user is logged in, false otherwise.
794 private function loadFromSession() {
795 global $wgMemc, $wgCookiePrefix;
798 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
799 if ( $result !== null ) {
803 if ( isset( $_SESSION['wsUserID'] ) ) {
804 if ( 0 != $_SESSION['wsUserID'] ) {
805 $sId = $_SESSION['wsUserID'];
807 $this->loadDefaults();
810 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
811 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
812 $_SESSION['wsUserID'] = $sId;
814 $this->loadDefaults();
817 if ( isset( $_SESSION['wsUserName'] ) && isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
818 // Cookie and session username should match
819 if( $_SESSION['wsUserName'] == $_COOKIE["{$wgCookiePrefix}UserName"] ) {
820 $sName = $_SESSION['wsUserName'];
822 $this->loadDefaults();
825 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
826 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
827 $_SESSION['wsUserName'] = $sName;
829 $this->loadDefaults();
833 $passwordCorrect = FALSE;
835 if ( !$this->loadFromId() ) {
836 # Not a valid ID, loadFromId has switched the object to anon for us
840 if ( isset( $_SESSION['wsToken'] ) ) {
841 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
843 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
844 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
847 # No session or persistent login cookie
848 $this->loadDefaults();
852 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
853 $_SESSION['wsToken'] = $this->mToken
;
854 wfDebug( "Logged in from $from\n" );
857 # Invalid credentials
858 wfDebug( "Can't log in from $from, invalid credentials\n" );
859 $this->loadDefaults();
865 * Load user and user_group data from the database.
866 * $this::mId must be set, this is how the user is identified.
868 * @return \type{\bool} True if the user exists, false if the user is anonymous
871 function loadFromDatabase() {
873 $this->mId
= intval( $this->mId
);
875 /** Anonymous user */
877 $this->loadDefaults();
881 $dbr = wfGetDB( DB_MASTER
);
882 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
884 if ( $s !== false ) {
885 # Initialise user table data
886 $this->loadFromRow( $s );
887 $this->mGroups
= null; // deferred
888 $this->getEditCount(); // revalidation for nulls
893 $this->loadDefaults();
899 * Initialize this object from a row from the user table.
901 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
903 function loadFromRow( $row ) {
904 $this->mDataLoaded
= true;
906 if ( isset( $row->user_id
) ) {
907 $this->mId
= $row->user_id
;
909 $this->mName
= $row->user_name
;
910 $this->mRealName
= $row->user_real_name
;
911 $this->mPassword
= $row->user_password
;
912 $this->mNewpassword
= $row->user_newpassword
;
913 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
914 $this->mEmail
= $row->user_email
;
915 $this->decodeOptions( $row->user_options
);
916 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
917 $this->mToken
= $row->user_token
;
918 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
919 $this->mEmailToken
= $row->user_email_token
;
920 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
921 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
922 $this->mEditCount
= $row->user_editcount
;
926 * Load the groups from the database if they aren't already loaded.
929 function loadGroups() {
930 if ( is_null( $this->mGroups
) ) {
931 $dbr = wfGetDB( DB_MASTER
);
932 $res = $dbr->select( 'user_groups',
934 array( 'ug_user' => $this->mId
),
936 $this->mGroups
= array();
937 while( $row = $dbr->fetchObject( $res ) ) {
938 $this->mGroups
[] = $row->ug_group
;
944 * Clear various cached data stored in this object.
945 * @param $reloadFrom \type{\string} Reload user and user_groups table data from a
946 * given source. May be "name", "id", "defaults", "session", or false for
949 function clearInstanceCache( $reloadFrom = false ) {
950 $this->mNewtalk
= -1;
951 $this->mDatePreference
= null;
952 $this->mBlockedby
= -1; # Unset
953 $this->mHash
= false;
955 $this->mRights
= null;
956 $this->mEffectiveGroups
= null;
959 $this->mDataLoaded
= false;
960 $this->mFrom
= $reloadFrom;
965 * Combine the language default options with any site-specific options
966 * and add the default language variants.
968 * @return \type{\arrayof{\string}} Array of options
970 static function getDefaultOptions() {
971 global $wgNamespacesToBeSearchedDefault;
973 * Site defaults will override the global/language defaults
975 global $wgDefaultUserOptions, $wgContLang;
976 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
979 * default language setting
981 $variant = $wgContLang->getPreferredVariant( false );
982 $defOpt['variant'] = $variant;
983 $defOpt['language'] = $variant;
985 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
986 $defOpt['searchNs'.$nsnum] = $val;
992 * Get a given default option value.
994 * @param $opt \type{\string} Name of option to retrieve
995 * @return \type{\string} Default option value
997 public static function getDefaultOption( $opt ) {
998 $defOpts = self
::getDefaultOptions();
999 if( isset( $defOpts[$opt] ) ) {
1000 return $defOpts[$opt];
1007 * Get a list of user toggle names
1008 * @return \type{\arrayof{\string}} Array of user toggle names
1010 static function getToggles() {
1012 $extraToggles = array();
1013 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1014 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1019 * Get blocking information
1021 * @param $bFromSlave \type{\bool} Whether to check the slave database first. To
1022 * improve performance, non-critical checks are done
1023 * against slaves. Check when actually saving should be
1024 * done against master.
1026 function getBlockedStatus( $bFromSlave = true ) {
1027 global $wgEnableSorbs, $wgProxyWhitelist;
1029 if ( -1 != $this->mBlockedby
) {
1030 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1034 wfProfileIn( __METHOD__
);
1035 wfDebug( __METHOD__
.": checking...\n" );
1037 // Initialize data...
1038 // Otherwise something ends up stomping on $this->mBlockedby when
1039 // things get lazy-loaded later, causing false positive block hits
1040 // due to -1 !== 0. Probably session-related... Nothing should be
1041 // overwriting mBlockedby, surely?
1044 $this->mBlockedby
= 0;
1045 $this->mHideName
= 0;
1046 $this->mAllowUsertalk
= 0;
1049 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1050 # Exempt from all types of IP-block
1055 $this->mBlock
= new Block();
1056 $this->mBlock
->fromMaster( !$bFromSlave );
1057 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1058 wfDebug( __METHOD__
.": Found block.\n" );
1059 $this->mBlockedby
= $this->mBlock
->mBy
;
1060 $this->mBlockreason
= $this->mBlock
->mReason
;
1061 $this->mHideName
= $this->mBlock
->mHideName
;
1062 $this->mAllowUsertalk
= $this->mBlock
->mAllowUsertalk
;
1063 if ( $this->isLoggedIn() ) {
1064 $this->spreadBlock();
1067 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1068 // apply to users. Note that the existence of $this->mBlock is not used to
1069 // check for edit blocks, $this->mBlockedby is instead.
1073 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1075 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1076 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1077 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1081 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1082 if ( $this->inSorbsBlacklist( $ip ) ) {
1083 $this->mBlockedby
= wfMsg( 'sorbs' );
1084 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1090 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1092 wfProfileOut( __METHOD__
);
1096 * Whether the given IP is in the SORBS blacklist.
1098 * @param $ip \type{\string} IP to check
1099 * @return \type{\bool} True if blacklisted
1101 function inSorbsBlacklist( $ip ) {
1102 global $wgEnableSorbs, $wgSorbsUrl;
1104 return $wgEnableSorbs &&
1105 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1109 * Whether the given IP is in a given DNS blacklist.
1111 * @param $ip \type{\string} IP to check
1112 * @param $base \type{\string} URL of the DNS blacklist
1113 * @return \type{\bool} True if blacklisted
1115 function inDnsBlacklist( $ip, $base ) {
1116 wfProfileIn( __METHOD__
);
1120 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1121 if( IP
::isIPv4($ip) ) {
1123 $host = "$ip.$base";
1126 $ipList = gethostbynamel( $host );
1129 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1132 wfDebug( "Requested $host, not found in $base.\n" );
1136 wfProfileOut( __METHOD__
);
1141 * Is this user subject to rate limiting?
1143 * @return \type{\bool} True if rate limited
1145 public function isPingLimitable() {
1146 global $wgRateLimitsExcludedGroups;
1147 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1148 // Deprecated, but kept for backwards-compatibility config
1151 return !$this->isAllowed('noratelimit');
1155 * Primitive rate limits: enforce maximum actions per time period
1156 * to put a brake on flooding.
1158 * @note When using a shared cache like memcached, IP-address
1159 * last-hit counters will be shared across wikis.
1161 * @param $action \type{\string} Action to enforce; 'edit' if unspecified
1162 * @return \type{\bool} True if a rate limiter was tripped
1164 function pingLimiter( $action='edit' ) {
1166 # Call the 'PingLimiter' hook
1168 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1172 global $wgRateLimits;
1173 if( !isset( $wgRateLimits[$action] ) ) {
1177 # Some groups shouldn't trigger the ping limiter, ever
1178 if( !$this->isPingLimitable() )
1181 global $wgMemc, $wgRateLimitLog;
1182 wfProfileIn( __METHOD__
);
1184 $limits = $wgRateLimits[$action];
1186 $id = $this->getId();
1190 if( isset( $limits['anon'] ) && $id == 0 ) {
1191 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1194 if( isset( $limits['user'] ) && $id != 0 ) {
1195 $userLimit = $limits['user'];
1197 if( $this->isNewbie() ) {
1198 if( isset( $limits['newbie'] ) && $id != 0 ) {
1199 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1201 if( isset( $limits['ip'] ) ) {
1202 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1205 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1206 $subnet = $matches[1];
1207 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1210 // Check for group-specific permissions
1211 // If more than one group applies, use the group with the highest limit
1212 foreach ( $this->getGroups() as $group ) {
1213 if ( isset( $limits[$group] ) ) {
1214 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1215 $userLimit = $limits[$group];
1219 // Set the user limit key
1220 if ( $userLimit !== false ) {
1221 wfDebug( __METHOD__
.": effective user limit: $userLimit\n" );
1222 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1226 foreach( $keys as $key => $limit ) {
1227 list( $max, $period ) = $limit;
1228 $summary = "(limit $max in {$period}s)";
1229 $count = $wgMemc->get( $key );
1231 if( $count > $max ) {
1232 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1233 if( $wgRateLimitLog ) {
1234 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1238 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1241 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1242 $wgMemc->add( $key, 1, intval( $period ) );
1244 $wgMemc->incr( $key );
1247 wfProfileOut( __METHOD__
);
1252 * Check if user is blocked
1254 * @param $bFromSlave \type{\bool} Whether to check the slave database instead of the master
1255 * @return \type{\bool} True if blocked, false otherwise
1257 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1258 wfDebug( "User::isBlocked: enter\n" );
1259 $this->getBlockedStatus( $bFromSlave );
1260 return $this->mBlockedby
!== 0;
1264 * Check if user is blocked from editing a particular article
1266 * @param $title \type{\string} Title to check
1267 * @param $bFromSlave \type{\bool} Whether to check the slave database instead of the master
1268 * @return \type{\bool} True if blocked, false otherwise
1270 function isBlockedFrom( $title, $bFromSlave = false ) {
1271 global $wgBlockAllowsUTEdit;
1272 wfProfileIn( __METHOD__
);
1273 wfDebug( __METHOD__
.": enter\n" );
1275 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1276 $blocked = $this->isBlocked( $bFromSlave );
1277 $allowUsertalk = ($wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false);
1278 # If a user's name is suppressed, they cannot make edits anywhere
1279 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1280 $title->getNamespace() == NS_USER_TALK
) {
1282 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1284 wfProfileOut( __METHOD__
);
1289 * If user is blocked, return the name of the user who placed the block
1290 * @return \type{\string} name of blocker
1292 function blockedBy() {
1293 $this->getBlockedStatus();
1294 return $this->mBlockedby
;
1298 * If user is blocked, return the specified reason for the block
1299 * @return \type{\string} Blocking reason
1301 function blockedFor() {
1302 $this->getBlockedStatus();
1303 return $this->mBlockreason
;
1307 * Check if user is blocked on all wikis.
1308 * Do not use for actual edit permission checks!
1309 * This is intented for quick UI checks.
1311 * @param $ip \type{\string} IP address, uses current client if none given
1312 * @return \type{\bool} True if blocked, false otherwise
1314 function isBlockedGlobally( $ip = '' ) {
1315 if( $this->mBlockedGlobally
!== null ) {
1316 return $this->mBlockedGlobally
;
1318 // User is already an IP?
1319 if( IP
::isIPAddress( $this->getName() ) ) {
1320 $ip = $this->getName();
1325 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1326 $this->mBlockedGlobally
= (bool)$blocked;
1327 return $this->mBlockedGlobally
;
1331 * Check if user account is locked
1333 * @return \type{\bool} True if locked, false otherwise
1335 function isLocked() {
1336 if( $this->mLocked
!== null ) {
1337 return $this->mLocked
;
1340 $authUser = $wgAuth->getUserInstance( $this );
1341 $this->mLocked
= (bool)$authUser->isLocked();
1342 return $this->mLocked
;
1346 * Check if user account is hidden
1348 * @return \type{\bool} True if hidden, false otherwise
1350 function isHidden() {
1351 if( $this->mHideName
!== null ) {
1352 return $this->mHideName
;
1354 $this->getBlockedStatus();
1355 if( !$this->mHideName
) {
1357 $authUser = $wgAuth->getUserInstance( $this );
1358 $this->mHideName
= (bool)$authUser->isHidden();
1360 return $this->mHideName
;
1364 * Get the user's ID.
1365 * @return \type{\int} The user's ID; 0 if the user is anonymous or nonexistent
1368 if( $this->mId
=== null and $this->mName
!== null
1369 and User
::isIP( $this->mName
) ) {
1370 // Special case, we know the user is anonymous
1372 } elseif( $this->mId
=== null ) {
1373 // Don't load if this was initialized from an ID
1380 * Set the user and reload all fields according to a given ID
1381 * @param $v \type{\int} %User ID to reload
1383 function setId( $v ) {
1385 $this->clearInstanceCache( 'id' );
1389 * Get the user name, or the IP of an anonymous user
1390 * @return \type{\string} User's name or IP address
1392 function getName() {
1393 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1394 # Special case optimisation
1395 return $this->mName
;
1398 if ( $this->mName
=== false ) {
1400 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1402 return $this->mName
;
1407 * Set the user name.
1409 * This does not reload fields from the database according to the given
1410 * name. Rather, it is used to create a temporary "nonexistent user" for
1411 * later addition to the database. It can also be used to set the IP
1412 * address for an anonymous user to something other than the current
1415 * @note User::newFromName() has rougly the same function, when the named user
1417 * @param $str \type{\string} New user name to set
1419 function setName( $str ) {
1421 $this->mName
= $str;
1425 * Get the user's name escaped by underscores.
1426 * @return \type{\string} Username escaped by underscores
1428 function getTitleKey() {
1429 return str_replace( ' ', '_', $this->getName() );
1433 * Check if the user has new messages.
1434 * @return \type{\bool} True if the user has new messages
1436 function getNewtalk() {
1439 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1440 if( $this->mNewtalk
=== -1 ) {
1441 $this->mNewtalk
= false; # reset talk page status
1443 # Check memcached separately for anons, who have no
1444 # entire User object stored in there.
1447 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1448 $newtalk = $wgMemc->get( $key );
1449 if( strval( $newtalk ) !== '' ) {
1450 $this->mNewtalk
= (bool)$newtalk;
1452 // Since we are caching this, make sure it is up to date by getting it
1454 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1455 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1458 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1462 return (bool)$this->mNewtalk
;
1466 * Return the talk page(s) this user has new messages on.
1467 * @return \type{\arrayof{\string}} Array of page URLs
1469 function getNewMessageLinks() {
1471 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1474 if (!$this->getNewtalk())
1476 $up = $this->getUserPage();
1477 $utp = $up->getTalkPage();
1478 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1483 * Internal uncached check for new messages
1486 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1487 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1488 * @param $fromMaster \type{\bool} true to fetch from the master, false for a slave
1489 * @return \type{\bool} True if the user has new messages
1492 function checkNewtalk( $field, $id, $fromMaster = false ) {
1493 if ( $fromMaster ) {
1494 $db = wfGetDB( DB_MASTER
);
1496 $db = wfGetDB( DB_SLAVE
);
1498 $ok = $db->selectField( 'user_newtalk', $field,
1499 array( $field => $id ), __METHOD__
);
1500 return $ok !== false;
1504 * Add or update the new messages flag
1505 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1506 * @param $id \twotypes{string,\int} User's IP address for anonymous users, %User ID otherwise
1507 * @return \type{\bool} True if successful, false otherwise
1510 function updateNewtalk( $field, $id ) {
1511 $dbw = wfGetDB( DB_MASTER
);
1512 $dbw->insert( 'user_newtalk',
1513 array( $field => $id ),
1516 if ( $dbw->affectedRows() ) {
1517 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1520 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1526 * Clear the new messages flag for the given user
1527 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1528 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1529 * @return \type{\bool} True if successful, false otherwise
1532 function deleteNewtalk( $field, $id ) {
1533 $dbw = wfGetDB( DB_MASTER
);
1534 $dbw->delete( 'user_newtalk',
1535 array( $field => $id ),
1537 if ( $dbw->affectedRows() ) {
1538 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1541 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1547 * Update the 'You have new messages!' status.
1548 * @param $val \type{\bool} Whether the user has new messages
1550 function setNewtalk( $val ) {
1551 if( wfReadOnly() ) {
1556 $this->mNewtalk
= $val;
1558 if( $this->isAnon() ) {
1560 $id = $this->getName();
1563 $id = $this->getId();
1568 $changed = $this->updateNewtalk( $field, $id );
1570 $changed = $this->deleteNewtalk( $field, $id );
1573 if( $this->isAnon() ) {
1574 // Anons have a separate memcached space, since
1575 // user records aren't kept for them.
1576 $key = wfMemcKey( 'newtalk', 'ip', $id );
1577 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1580 $this->invalidateCache();
1585 * Generate a current or new-future timestamp to be stored in the
1586 * user_touched field when we update things.
1587 * @return \type{\string} Timestamp in TS_MW format
1589 private static function newTouchedTimestamp() {
1590 global $wgClockSkewFudge;
1591 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1595 * Clear user data from memcached.
1596 * Use after applying fun updates to the database; caller's
1597 * responsibility to update user_touched if appropriate.
1599 * Called implicitly from invalidateCache() and saveSettings().
1601 private function clearSharedCache() {
1605 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1610 * Immediately touch the user data cache for this account.
1611 * Updates user_touched field, and removes account data from memcached
1612 * for reload on the next hit.
1614 function invalidateCache() {
1617 $this->mTouched
= self
::newTouchedTimestamp();
1619 $dbw = wfGetDB( DB_MASTER
);
1620 $dbw->update( 'user',
1621 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1622 array( 'user_id' => $this->mId
),
1625 $this->clearSharedCache();
1630 * Validate the cache for this account.
1631 * @param $timestamp \type{\string} A timestamp in TS_MW format
1633 function validateCache( $timestamp ) {
1635 return ($timestamp >= $this->mTouched
);
1639 * Get the user touched timestamp
1641 function getTouched() {
1643 return $this->mTouched
;
1647 * Set the password and reset the random token.
1648 * Calls through to authentication plugin if necessary;
1649 * will have no effect if the auth plugin refuses to
1650 * pass the change through or if the legal password
1653 * As a special case, setting the password to null
1654 * wipes it, so the account cannot be logged in until
1655 * a new password is set, for instance via e-mail.
1657 * @param $str \type{\string} New password to set
1658 * @throws PasswordError on failure
1660 function setPassword( $str ) {
1663 if( $str !== null ) {
1664 if( !$wgAuth->allowPasswordChange() ) {
1665 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1668 if( !$this->isValidPassword( $str ) ) {
1669 global $wgMinimalPasswordLength;
1670 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1671 $wgMinimalPasswordLength ) );
1675 if( !$wgAuth->setPassword( $this, $str ) ) {
1676 throw new PasswordError( wfMsg( 'externaldberror' ) );
1679 $this->setInternalPassword( $str );
1685 * Set the password and reset the random token unconditionally.
1687 * @param $str \type{\string} New password to set
1689 function setInternalPassword( $str ) {
1693 if( $str === null ) {
1694 // Save an invalid hash...
1695 $this->mPassword
= '';
1697 $this->mPassword
= self
::crypt( $str );
1699 $this->mNewpassword
= '';
1700 $this->mNewpassTime
= null;
1704 * Get the user's current token.
1705 * @return \type{\string} Token
1707 function getToken() {
1709 return $this->mToken
;
1713 * Set the random token (used for persistent authentication)
1714 * Called from loadDefaults() among other places.
1716 * @param $token \type{\string} If specified, set the token to this value
1719 function setToken( $token = false ) {
1720 global $wgSecretKey, $wgProxyKey;
1723 if ( $wgSecretKey ) {
1724 $key = $wgSecretKey;
1725 } elseif ( $wgProxyKey ) {
1730 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1732 $this->mToken
= $token;
1737 * Set the cookie password
1739 * @param $str \type{\string} New cookie password
1742 function setCookiePassword( $str ) {
1744 $this->mCookiePassword
= md5( $str );
1748 * Set the password for a password reminder or new account email
1750 * @param $str \type{\string} New password to set
1751 * @param $throttle \type{\bool} If true, reset the throttle timestamp to the present
1753 function setNewpassword( $str, $throttle = true ) {
1755 $this->mNewpassword
= self
::crypt( $str );
1757 $this->mNewpassTime
= wfTimestampNow();
1762 * Has password reminder email been sent within the last
1763 * $wgPasswordReminderResendTime hours?
1764 * @return \type{\bool} True or false
1766 function isPasswordReminderThrottled() {
1767 global $wgPasswordReminderResendTime;
1769 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1772 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1773 return time() < $expiry;
1777 * Get the user's e-mail address
1778 * @return \type{\string} User's e-mail address
1780 function getEmail() {
1782 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1783 return $this->mEmail
;
1787 * Get the timestamp of the user's e-mail authentication
1788 * @return \type{\string} TS_MW timestamp
1790 function getEmailAuthenticationTimestamp() {
1792 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1793 return $this->mEmailAuthenticated
;
1797 * Set the user's e-mail address
1798 * @param $str \type{\string} New e-mail address
1800 function setEmail( $str ) {
1802 $this->mEmail
= $str;
1803 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1807 * Get the user's real name
1808 * @return \type{\string} User's real name
1810 function getRealName() {
1812 return $this->mRealName
;
1816 * Set the user's real name
1817 * @param $str \type{\string} New real name
1819 function setRealName( $str ) {
1821 $this->mRealName
= $str;
1825 * Get the user's current setting for a given option.
1827 * @param $oname \type{\string} The option to check
1828 * @param $defaultOverride \type{\string} A default value returned if the option does not exist
1829 * @return \type{\string} User's current value for the option
1830 * @see getBoolOption()
1831 * @see getIntOption()
1833 function getOption( $oname, $defaultOverride = '' ) {
1836 if ( is_null( $this->mOptions
) ) {
1837 if($defaultOverride != '') {
1838 return $defaultOverride;
1840 $this->mOptions
= User
::getDefaultOptions();
1843 if ( array_key_exists( $oname, $this->mOptions
) ) {
1844 return trim( $this->mOptions
[$oname] );
1846 return $defaultOverride;
1851 * Get the user's current setting for a given option, as a boolean value.
1853 * @param $oname \type{\string} The option to check
1854 * @return \type{\bool} User's current value for the option
1857 function getBoolOption( $oname ) {
1858 return (bool)$this->getOption( $oname );
1863 * Get the user's current setting for a given option, as a boolean value.
1865 * @param $oname \type{\string} The option to check
1866 * @param $defaultOverride \type{\int} A default value returned if the option does not exist
1867 * @return \type{\int} User's current value for the option
1870 function getIntOption( $oname, $defaultOverride=0 ) {
1871 $val = $this->getOption( $oname );
1873 $val = $defaultOverride;
1875 return intval( $val );
1879 * Set the given option for a user.
1881 * @param $oname \type{\string} The option to set
1882 * @param $val \type{\mixed} New value to set
1884 function setOption( $oname, $val ) {
1886 if ( is_null( $this->mOptions
) ) {
1887 $this->mOptions
= User
::getDefaultOptions();
1889 if ( $oname == 'skin' ) {
1890 # Clear cached skin, so the new one displays immediately in Special:Preferences
1891 unset( $this->mSkin
);
1893 // Filter out any newlines that may have passed through input validation.
1894 // Newlines are used to separate items in the options blob.
1896 $val = str_replace( "\r\n", "\n", $val );
1897 $val = str_replace( "\r", "\n", $val );
1898 $val = str_replace( "\n", " ", $val );
1900 // Explicitly NULL values should refer to defaults
1901 global $wgDefaultUserOptions;
1902 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1903 $val = $wgDefaultUserOptions[$oname];
1905 $this->mOptions
[$oname] = $val;
1909 * Get the user's preferred date format.
1910 * @return \type{\string} User's preferred date format
1912 function getDatePreference() {
1913 // Important migration for old data rows
1914 if ( is_null( $this->mDatePreference
) ) {
1916 $value = $this->getOption( 'date' );
1917 $map = $wgLang->getDatePreferenceMigrationMap();
1918 if ( isset( $map[$value] ) ) {
1919 $value = $map[$value];
1921 $this->mDatePreference
= $value;
1923 return $this->mDatePreference
;
1927 * Get the permissions this user has.
1928 * @return \type{\arrayof{\string}} Array of permission names
1930 function getRights() {
1931 if ( is_null( $this->mRights
) ) {
1932 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1933 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1934 // Force reindexation of rights when a hook has unset one of them
1935 $this->mRights
= array_values( $this->mRights
);
1937 return $this->mRights
;
1941 * Get the list of explicit group memberships this user has.
1942 * The implicit * and user groups are not included.
1943 * @return \type{\arrayof{\string}} Array of internal group names
1945 function getGroups() {
1947 return $this->mGroups
;
1951 * Get the list of implicit group memberships this user has.
1952 * This includes all explicit groups, plus 'user' if logged in,
1953 * '*' for all accounts and autopromoted groups
1955 * @param $recache \type{\bool} Whether to avoid the cache
1956 * @return \type{\arrayof{\string}} Array of internal group names
1958 function getEffectiveGroups( $recache = false ) {
1959 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1960 $this->mEffectiveGroups
= $this->getGroups();
1961 $this->mEffectiveGroups
[] = '*';
1962 if( $this->getId() ) {
1963 $this->mEffectiveGroups
[] = 'user';
1965 $this->mEffectiveGroups
= array_unique( array_merge(
1966 $this->mEffectiveGroups
,
1967 Autopromote
::getAutopromoteGroups( $this )
1970 # Hook for additional groups
1971 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1974 return $this->mEffectiveGroups
;
1978 * Get the user's edit count.
1979 * @return \type{\int} User's edit count
1981 function getEditCount() {
1983 if ( !isset( $this->mEditCount
) ) {
1984 /* Populate the count, if it has not been populated yet */
1985 $this->mEditCount
= User
::edits($this->mId
);
1987 return $this->mEditCount
;
1995 * Add the user to the given group.
1996 * This takes immediate effect.
1997 * @param $group \type{\string} Name of the group to add
1999 function addGroup( $group ) {
2000 $dbw = wfGetDB( DB_MASTER
);
2001 if( $this->getId() ) {
2002 $dbw->insert( 'user_groups',
2004 'ug_user' => $this->getID(),
2005 'ug_group' => $group,
2008 array( 'IGNORE' ) );
2011 $this->loadGroups();
2012 $this->mGroups
[] = $group;
2013 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2015 $this->invalidateCache();
2019 * Remove the user from the given group.
2020 * This takes immediate effect.
2021 * @param $group \type{\string} Name of the group to remove
2023 function removeGroup( $group ) {
2025 $dbw = wfGetDB( DB_MASTER
);
2026 $dbw->delete( 'user_groups',
2028 'ug_user' => $this->getID(),
2029 'ug_group' => $group,
2031 'User::removeGroup' );
2033 $this->loadGroups();
2034 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2035 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2037 $this->invalidateCache();
2042 * Get whether the user is logged in
2043 * @return \type{\bool} True or false
2045 function isLoggedIn() {
2046 return $this->getID() != 0;
2050 * Get whether the user is anonymous
2051 * @return \type{\bool} True or false
2054 return !$this->isLoggedIn();
2058 * Get whether the user is a bot
2059 * @return \type{\bool} True or false
2063 wfDeprecated( __METHOD__
);
2064 return $this->isAllowed( 'bot' );
2068 * Check if user is allowed to access a feature / make an action
2069 * @param $action \type{\string} action to be checked
2070 * @return \type{\bool} True if action is allowed, else false
2072 function isAllowed($action='') {
2073 if ( $action === '' )
2074 // In the spirit of DWIM
2077 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2078 # by misconfiguration: 0 == 'foo'
2079 return in_array( $action, $this->getRights(), true );
2083 * Check whether to enable recent changes patrol features for this user
2084 * @return \type{\bool} True or false
2086 public function useRCPatrol() {
2087 global $wgUseRCPatrol;
2088 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2092 * Check whether to enable new pages patrol features for this user
2093 * @return \type{\bool} True or false
2095 public function useNPPatrol() {
2096 global $wgUseRCPatrol, $wgUseNPPatrol;
2097 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2101 * Get the current skin, loading it if required
2102 * @return \type{Skin} Current skin
2103 * @todo FIXME : need to check the old failback system [AV]
2105 function &getSkin() {
2107 if ( ! isset( $this->mSkin
) ) {
2108 wfProfileIn( __METHOD__
);
2111 $userSkin = $this->getOption( 'skin' );
2112 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2114 $this->mSkin
=& Skin
::newFromKey( $userSkin );
2115 wfProfileOut( __METHOD__
);
2117 return $this->mSkin
;
2121 * Check the watched status of an article.
2122 * @param $title \type{Title} Title of the article to look at
2123 * @return \type{\bool} True if article is watched
2125 function isWatched( $title ) {
2126 $wl = WatchedItem
::fromUserTitle( $this, $title );
2127 return $wl->isWatched();
2132 * @param $title \type{Title} Title of the article to look at
2134 function addWatch( $title ) {
2135 $wl = WatchedItem
::fromUserTitle( $this, $title );
2137 $this->invalidateCache();
2141 * Stop watching an article.
2142 * @param $title \type{Title} Title of the article to look at
2144 function removeWatch( $title ) {
2145 $wl = WatchedItem
::fromUserTitle( $this, $title );
2147 $this->invalidateCache();
2151 * Clear the user's notification timestamp for the given title.
2152 * If e-notif e-mails are on, they will receive notification mails on
2153 * the next change of the page if it's watched etc.
2154 * @param $title \type{Title} Title of the article to look at
2156 function clearNotification( &$title ) {
2157 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2159 # Do nothing if the database is locked to writes
2160 if( wfReadOnly() ) {
2164 if ($title->getNamespace() == NS_USER_TALK
&&
2165 $title->getText() == $this->getName() ) {
2166 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2168 $this->setNewtalk( false );
2171 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2175 if( $this->isAnon() ) {
2176 // Nothing else to do...
2180 // Only update the timestamp if the page is being watched.
2181 // The query to find out if it is watched is cached both in memcached and per-invocation,
2182 // and when it does have to be executed, it can be on a slave
2183 // If this is the user's newtalk page, we always update the timestamp
2184 if ($title->getNamespace() == NS_USER_TALK
&&
2185 $title->getText() == $wgUser->getName())
2188 } elseif ( $this->getId() == $wgUser->getId() ) {
2189 $watched = $title->userIsWatching();
2194 // If the page is watched by the user (or may be watched), update the timestamp on any
2195 // any matching rows
2197 $dbw = wfGetDB( DB_MASTER
);
2198 $dbw->update( 'watchlist',
2200 'wl_notificationtimestamp' => NULL
2201 ), array( /* WHERE */
2202 'wl_title' => $title->getDBkey(),
2203 'wl_namespace' => $title->getNamespace(),
2204 'wl_user' => $this->getID()
2211 * Resets all of the given user's page-change notification timestamps.
2212 * If e-notif e-mails are on, they will receive notification mails on
2213 * the next change of any watched page.
2215 * @param $currentUser \type{\int} %User ID
2217 function clearAllNotifications( $currentUser ) {
2218 global $wgUseEnotif, $wgShowUpdatedMarker;
2219 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2220 $this->setNewtalk( false );
2223 if( $currentUser != 0 ) {
2224 $dbw = wfGetDB( DB_MASTER
);
2225 $dbw->update( 'watchlist',
2227 'wl_notificationtimestamp' => NULL
2228 ), array( /* WHERE */
2229 'wl_user' => $currentUser
2232 # We also need to clear here the "you have new message" notification for the own user_talk page
2233 # This is cleared one page view later in Article::viewUpdates();
2238 * Encode this user's options as a string
2239 * @return \type{\string} Encoded options
2242 function encodeOptions() {
2244 if ( is_null( $this->mOptions
) ) {
2245 $this->mOptions
= User
::getDefaultOptions();
2248 foreach ( $this->mOptions
as $oname => $oval ) {
2249 array_push( $a, $oname.'='.$oval );
2251 $s = implode( "\n", $a );
2256 * Set this user's options from an encoded string
2257 * @param $str \type{\string} Encoded options to import
2260 function decodeOptions( $str ) {
2261 $this->mOptions
= array();
2262 $a = explode( "\n", $str );
2263 foreach ( $a as $s ) {
2265 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2266 $this->mOptions
[$m[1]] = $m[2];
2272 * Set a cookie on the user's client. Wrapper for
2273 * WebResponse::setCookie
2275 protected function setCookie( $name, $value, $exp=0 ) {
2277 $wgRequest->response()->setcookie( $name, $value, $exp );
2281 * Clear a cookie on the user's client
2282 * @param $name \type{\string} Name of the cookie to clear
2284 protected function clearCookie( $name ) {
2285 $this->setCookie( $name, '', time() - 86400 );
2289 * Set the default cookies for this session on the user's client.
2291 function setCookies() {
2293 if ( 0 == $this->mId
) return;
2295 'wsUserID' => $this->mId
,
2296 'wsToken' => $this->mToken
,
2297 'wsUserName' => $this->getName()
2300 'UserID' => $this->mId
,
2301 'UserName' => $this->getName(),
2303 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2304 $cookies['Token'] = $this->mToken
;
2306 $cookies['Token'] = false;
2309 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2310 $_SESSION = $session +
$_SESSION;
2311 foreach ( $cookies as $name => $value ) {
2312 if ( $value === false ) {
2313 $this->clearCookie( $name );
2315 $this->setCookie( $name, $value );
2321 * Log this user out.
2325 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2331 * Clear the user's cookies and session, and reset the instance cache.
2335 function doLogout() {
2336 $this->clearInstanceCache( 'defaults' );
2338 $_SESSION['wsUserID'] = 0;
2340 $this->clearCookie( 'UserID' );
2341 $this->clearCookie( 'Token' );
2343 # Remember when user logged out, to prevent seeing cached pages
2344 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2348 * Save this user's settings into the database.
2349 * @todo Only rarely do all these fields need to be set!
2351 function saveSettings() {
2353 if ( wfReadOnly() ) { return; }
2354 if ( 0 == $this->mId
) { return; }
2356 $this->mTouched
= self
::newTouchedTimestamp();
2358 $dbw = wfGetDB( DB_MASTER
);
2359 $dbw->update( 'user',
2361 'user_name' => $this->mName
,
2362 'user_password' => $this->mPassword
,
2363 'user_newpassword' => $this->mNewpassword
,
2364 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2365 'user_real_name' => $this->mRealName
,
2366 'user_email' => $this->mEmail
,
2367 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2368 'user_options' => $this->encodeOptions(),
2369 'user_touched' => $dbw->timestamp($this->mTouched
),
2370 'user_token' => $this->mToken
,
2371 'user_email_token' => $this->mEmailToken
,
2372 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2373 ), array( /* WHERE */
2374 'user_id' => $this->mId
2377 wfRunHooks( 'UserSaveSettings', array( $this ) );
2378 $this->clearSharedCache();
2382 * If only this user's username is known, and it exists, return the user ID.
2384 function idForName() {
2385 $s = trim( $this->getName() );
2386 if ( $s === '' ) return 0;
2388 $dbr = wfGetDB( DB_SLAVE
);
2389 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2390 if ( $id === false ) {
2397 * Add a user to the database, return the user object
2399 * @param $name \type{\string} Username to add
2400 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2401 * - password The user's password. Password logins will be disabled if this is omitted.
2402 * - newpassword A temporary password mailed to the user
2403 * - email The user's email address
2404 * - email_authenticated The email authentication timestamp
2405 * - real_name The user's real name
2406 * - options An associative array of non-default options
2407 * - token Random authentication token. Do not set.
2408 * - registration Registration timestamp. Do not set.
2410 * @return \type{User} A new User object, or null if the username already exists
2412 static function createNew( $name, $params = array() ) {
2415 if ( isset( $params['options'] ) ) {
2416 $user->mOptions
= $params['options'] +
$user->mOptions
;
2417 unset( $params['options'] );
2419 $dbw = wfGetDB( DB_MASTER
);
2420 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2422 'user_id' => $seqVal,
2423 'user_name' => $name,
2424 'user_password' => $user->mPassword
,
2425 'user_newpassword' => $user->mNewpassword
,
2426 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2427 'user_email' => $user->mEmail
,
2428 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2429 'user_real_name' => $user->mRealName
,
2430 'user_options' => $user->encodeOptions(),
2431 'user_token' => $user->mToken
,
2432 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2433 'user_editcount' => 0,
2435 foreach ( $params as $name => $value ) {
2436 $fields["user_$name"] = $value;
2438 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2439 if ( $dbw->affectedRows() ) {
2440 $newUser = User
::newFromId( $dbw->insertId() );
2448 * Add this existing user object to the database
2450 function addToDatabase() {
2452 $dbw = wfGetDB( DB_MASTER
);
2453 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2454 $dbw->insert( 'user',
2456 'user_id' => $seqVal,
2457 'user_name' => $this->mName
,
2458 'user_password' => $this->mPassword
,
2459 'user_newpassword' => $this->mNewpassword
,
2460 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2461 'user_email' => $this->mEmail
,
2462 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2463 'user_real_name' => $this->mRealName
,
2464 'user_options' => $this->encodeOptions(),
2465 'user_token' => $this->mToken
,
2466 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2467 'user_editcount' => 0,
2470 $this->mId
= $dbw->insertId();
2472 // Clear instance cache other than user table data, which is already accurate
2473 $this->clearInstanceCache();
2477 * If this (non-anonymous) user is blocked, block any IP address
2478 * they've successfully logged in from.
2480 function spreadBlock() {
2481 wfDebug( __METHOD__
."()\n" );
2483 if ( $this->mId
== 0 ) {
2487 $userblock = Block
::newFromDB( '', $this->mId
);
2488 if ( !$userblock ) {
2492 $userblock->doAutoblock( wfGetIp() );
2497 * Generate a string which will be different for any combination of
2498 * user options which would produce different parser output.
2499 * This will be used as part of the hash key for the parser cache,
2500 * so users will the same options can share the same cached data
2503 * Extensions which require it should install 'PageRenderingHash' hook,
2504 * which will give them a chance to modify this key based on their own
2507 * @return \type{\string} Page rendering hash
2509 function getPageRenderingHash() {
2510 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2512 return $this->mHash
;
2515 // stubthreshold is only included below for completeness,
2516 // it will always be 0 when this function is called by parsercache.
2518 $confstr = $this->getOption( 'math' );
2519 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2520 if ( $wgUseDynamicDates ) {
2521 $confstr .= '!' . $this->getDatePreference();
2523 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2524 $confstr .= '!' . $wgLang->getCode();
2525 $confstr .= '!' . $this->getOption( 'thumbsize' );
2526 // add in language specific options, if any
2527 $extra = $wgContLang->getExtraHashOptions();
2530 $confstr .= $wgRenderHashAppend;
2532 // Give a chance for extensions to modify the hash, if they have
2533 // extra options or other effects on the parser cache.
2534 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2536 // Make it a valid memcached key fragment
2537 $confstr = str_replace( ' ', '_', $confstr );
2538 $this->mHash
= $confstr;
2543 * Get whether the user is explicitly blocked from account creation.
2544 * @return \type{\bool} True if blocked
2546 function isBlockedFromCreateAccount() {
2547 $this->getBlockedStatus();
2548 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2552 * Get whether the user is blocked from using Special:Emailuser.
2553 * @return \type{\bool} True if blocked
2555 function isBlockedFromEmailuser() {
2556 $this->getBlockedStatus();
2557 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2561 * Get whether the user is allowed to create an account.
2562 * @return \type{\bool} True if allowed
2564 function isAllowedToCreateAccount() {
2565 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2571 function setLoaded( $loaded ) {
2572 wfDeprecated( __METHOD__
);
2576 * Get this user's personal page title.
2578 * @return \type{Title} User's personal page title
2580 function getUserPage() {
2581 return Title
::makeTitle( NS_USER
, $this->getName() );
2585 * Get this user's talk page title.
2587 * @return \type{Title} User's talk page title
2589 function getTalkPage() {
2590 $title = $this->getUserPage();
2591 return $title->getTalkPage();
2595 * Get the maximum valid user ID.
2596 * @return \type{\int} %User ID
2599 function getMaxID() {
2600 static $res; // cache
2602 if ( isset( $res ) )
2605 $dbr = wfGetDB( DB_SLAVE
);
2606 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2611 * Determine whether the user is a newbie. Newbies are either
2612 * anonymous IPs, or the most recently created accounts.
2613 * @return \type{\bool} True if the user is a newbie
2615 function isNewbie() {
2616 return !$this->isAllowed( 'autoconfirmed' );
2620 * Is the user active? We check to see if they've made at least
2621 * X number of edits in the last Y days.
2623 * @return \type{\bool} True if the user is active, false if not.
2625 public function isActiveEditor() {
2626 global $wgActiveUserEditCount, $wgActiveUserDays;
2627 $dbr = wfGetDB( DB_SLAVE
);
2629 // Stolen without shame from RC
2630 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2631 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
2632 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2634 $res = $dbr->select( 'revision', '1',
2635 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2637 array('LIMIT' => $wgActiveUserEditCount ) );
2639 $count = $dbr->numRows($res);
2640 $dbr->freeResult($res);
2642 return $count == $wgActiveUserEditCount;
2646 * Check to see if the given clear-text password is one of the accepted passwords
2647 * @param $password \type{\string} user password.
2648 * @return \type{\bool} True if the given password is correct, otherwise False.
2650 function checkPassword( $password ) {
2654 // Even though we stop people from creating passwords that
2655 // are shorter than this, doesn't mean people wont be able
2656 // to. Certain authentication plugins do NOT want to save
2657 // domain passwords in a mysql database, so we should
2658 // check this (incase $wgAuth->strict() is false).
2659 if( !$this->isValidPassword( $password ) ) {
2663 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2665 } elseif( $wgAuth->strict() ) {
2666 /* Auth plugin doesn't allow local authentication */
2668 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2669 /* Auth plugin doesn't allow local authentication for this user name */
2672 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2674 } elseif ( function_exists( 'iconv' ) ) {
2675 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2676 # Check for this with iconv
2677 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2678 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2686 * Check if the given clear-text password matches the temporary password
2687 * sent by e-mail for password reset operations.
2688 * @return \type{\bool} True if matches, false otherwise
2690 function checkTemporaryPassword( $plaintext ) {
2691 return self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() );
2695 * Initialize (if necessary) and return a session token value
2696 * which can be used in edit forms to show that the user's
2697 * login credentials aren't being hijacked with a foreign form
2700 * @param $salt \twotypes{\string,\arrayof{\string}} Optional function-specific data for hashing
2701 * @return \type{\string} The new edit token
2703 function editToken( $salt = '' ) {
2704 if ( $this->isAnon() ) {
2705 return EDIT_TOKEN_SUFFIX
;
2707 if( !isset( $_SESSION['wsEditToken'] ) ) {
2708 $token = $this->generateToken();
2709 $_SESSION['wsEditToken'] = $token;
2711 $token = $_SESSION['wsEditToken'];
2713 if( is_array( $salt ) ) {
2714 $salt = implode( '|', $salt );
2716 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2721 * Generate a looking random token for various uses.
2723 * @param $salt \type{\string} Optional salt value
2724 * @return \type{\string} The new random token
2726 function generateToken( $salt = '' ) {
2727 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2728 return md5( $token . $salt );
2732 * Check given value against the token value stored in the session.
2733 * A match should confirm that the form was submitted from the
2734 * user's own login session, not a form submission from a third-party
2737 * @param $val \type{\string} Input value to compare
2738 * @param $salt \type{\string} Optional function-specific data for hashing
2739 * @return \type{\bool} Whether the token matches
2741 function matchEditToken( $val, $salt = '' ) {
2742 $sessionToken = $this->editToken( $salt );
2743 if ( $val != $sessionToken ) {
2744 wfDebug( "User::matchEditToken: broken session data\n" );
2746 return $val == $sessionToken;
2750 * Check given value against the token value stored in the session,
2751 * ignoring the suffix.
2753 * @param $val \type{\string} Input value to compare
2754 * @param $salt \type{\string} Optional function-specific data for hashing
2755 * @return \type{\bool} Whether the token matches
2757 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2758 $sessionToken = $this->editToken( $salt );
2759 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2763 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2764 * mail to the user's given address.
2766 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure.
2768 function sendConfirmationMail() {
2770 $expiration = null; // gets passed-by-ref and defined in next line.
2771 $token = $this->confirmationToken( $expiration );
2772 $url = $this->confirmationTokenUrl( $token );
2773 $invalidateURL = $this->invalidationTokenUrl( $token );
2774 $this->saveSettings();
2776 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2777 wfMsg( 'confirmemail_body',
2781 $wgLang->timeanddate( $expiration, false ),
2786 * Send an e-mail to this user's account. Does not check for
2787 * confirmed status or validity.
2789 * @param $subject \type{\string} Message subject
2790 * @param $body \type{\string} Message body
2791 * @param $from \type{\string} Optional From address; if unspecified, default $wgPasswordSender will be used
2792 * @param $replyto \type{\string} Reply-to address
2793 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure
2795 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2796 if( is_null( $from ) ) {
2797 global $wgPasswordSender;
2798 $from = $wgPasswordSender;
2801 $to = new MailAddress( $this );
2802 $sender = new MailAddress( $from );
2803 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2807 * Generate, store, and return a new e-mail confirmation code.
2808 * A hash (unsalted, since it's used as a key) is stored.
2810 * @note Call saveSettings() after calling this function to commit
2811 * this change to the database.
2813 * @param[out] &$expiration \type{\mixed} Accepts the expiration time
2814 * @return \type{\string} New token
2817 function confirmationToken( &$expiration ) {
2819 $expires = $now +
7 * 24 * 60 * 60;
2820 $expiration = wfTimestamp( TS_MW
, $expires );
2821 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2822 $hash = md5( $token );
2824 $this->mEmailToken
= $hash;
2825 $this->mEmailTokenExpires
= $expiration;
2830 * Return a URL the user can use to confirm their email address.
2831 * @param $token \type{\string} Accepts the email confirmation token
2832 * @return \type{\string} New token URL
2835 function confirmationTokenUrl( $token ) {
2836 return $this->getTokenUrl( 'ConfirmEmail', $token );
2839 * Return a URL the user can use to invalidate their email address.
2841 * @param $token \type{\string} Accepts the email confirmation token
2842 * @return \type{\string} New token URL
2845 function invalidationTokenUrl( $token ) {
2846 return $this->getTokenUrl( 'Invalidateemail', $token );
2850 * Internal function to format the e-mail validation/invalidation URLs.
2851 * This uses $wgArticlePath directly as a quickie hack to use the
2852 * hardcoded English names of the Special: pages, for ASCII safety.
2854 * @note Since these URLs get dropped directly into emails, using the
2855 * short English names avoids insanely long URL-encoded links, which
2856 * also sometimes can get corrupted in some browsers/mailers
2857 * (bug 6957 with Gmail and Internet Explorer).
2859 * @param $page \type{\string} Special page
2860 * @param $token \type{\string} Token
2861 * @return \type{\string} Formatted URL
2863 protected function getTokenUrl( $page, $token ) {
2864 global $wgArticlePath;
2868 "Special:$page/$token",
2873 * Mark the e-mail address confirmed.
2875 * @note Call saveSettings() after calling this function to commit the change.
2877 function confirmEmail() {
2878 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2883 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2884 * address if it was already confirmed.
2886 * @note Call saveSettings() after calling this function to commit the change.
2888 function invalidateEmail() {
2890 $this->mEmailToken
= null;
2891 $this->mEmailTokenExpires
= null;
2892 $this->setEmailAuthenticationTimestamp( null );
2897 * Set the e-mail authentication timestamp.
2898 * @param $timestamp \type{\string} TS_MW timestamp
2900 function setEmailAuthenticationTimestamp( $timestamp ) {
2902 $this->mEmailAuthenticated
= $timestamp;
2903 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2907 * Is this user allowed to send e-mails within limits of current
2908 * site configuration?
2909 * @return \type{\bool} True if allowed
2911 function canSendEmail() {
2912 $canSend = $this->isEmailConfirmed();
2913 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2918 * Is this user allowed to receive e-mails within limits of current
2919 * site configuration?
2920 * @return \type{\bool} True if allowed
2922 function canReceiveEmail() {
2923 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2927 * Is this user's e-mail address valid-looking and confirmed within
2928 * limits of the current site configuration?
2930 * @note If $wgEmailAuthentication is on, this may require the user to have
2931 * confirmed their address by returning a code or using a password
2932 * sent to the address from the wiki.
2934 * @return \type{\bool} True if confirmed
2936 function isEmailConfirmed() {
2937 global $wgEmailAuthentication;
2940 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2941 if( $this->isAnon() )
2943 if( !self
::isValidEmailAddr( $this->mEmail
) )
2945 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2954 * Check whether there is an outstanding request for e-mail confirmation.
2955 * @return \type{\bool} True if pending
2957 function isEmailConfirmationPending() {
2958 global $wgEmailAuthentication;
2959 return $wgEmailAuthentication &&
2960 !$this->isEmailConfirmed() &&
2961 $this->mEmailToken
&&
2962 $this->mEmailTokenExpires
> wfTimestamp();
2966 * Get the timestamp of account creation.
2968 * @return \twotypes{\string,\bool} string Timestamp of account creation, or false for
2969 * non-existent/anonymous user accounts.
2971 public function getRegistration() {
2972 return $this->mId
> 0
2973 ?
$this->mRegistration
2978 * Get the permissions associated with a given list of groups
2980 * @param $groups \type{\arrayof{\string}} List of internal group names
2981 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
2983 static function getGroupPermissions( $groups ) {
2984 global $wgGroupPermissions;
2986 foreach( $groups as $group ) {
2987 if( isset( $wgGroupPermissions[$group] ) ) {
2988 $rights = array_merge( $rights,
2989 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2996 * Get all the groups who have a given permission
2998 * @param $role \type{\string} Role to check
2999 * @return \type{\arrayof{\string}} List of internal group names with the given permission
3001 static function getGroupsWithPermission( $role ) {
3002 global $wgGroupPermissions;
3003 $allowedGroups = array();
3004 foreach ( $wgGroupPermissions as $group => $rights ) {
3005 if ( isset( $rights[$role] ) && $rights[$role] ) {
3006 $allowedGroups[] = $group;
3009 return $allowedGroups;
3013 * Get the localized descriptive name for a group, if it exists
3015 * @param $group \type{\string} Internal group name
3016 * @return \type{\string} Localized descriptive group name
3018 static function getGroupName( $group ) {
3019 global $wgMessageCache;
3020 $wgMessageCache->loadAllMessages();
3021 $key = "group-$group";
3022 $name = wfMsg( $key );
3023 return $name == '' ||
wfEmptyMsg( $key, $name )
3029 * Get the localized descriptive name for a member of a group, if it exists
3031 * @param $group \type{\string} Internal group name
3032 * @return \type{\string} Localized name for group member
3034 static function getGroupMember( $group ) {
3035 global $wgMessageCache;
3036 $wgMessageCache->loadAllMessages();
3037 $key = "group-$group-member";
3038 $name = wfMsg( $key );
3039 return $name == '' ||
wfEmptyMsg( $key, $name )
3045 * Return the set of defined explicit groups.
3046 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3047 * are not included, as they are defined automatically, not in the database.
3048 * @return \type{\arrayof{\string}} Array of internal group names
3050 static function getAllGroups() {
3051 global $wgGroupPermissions;
3053 array_keys( $wgGroupPermissions ),
3054 self
::getImplicitGroups()
3059 * Get a list of all available permissions.
3060 * @return \type{\arrayof{\string}} Array of permission names
3062 static function getAllRights() {
3063 if ( self
::$mAllRights === false ) {
3064 global $wgAvailableRights;
3065 if ( count( $wgAvailableRights ) ) {
3066 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3068 self
::$mAllRights = self
::$mCoreRights;
3070 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3072 return self
::$mAllRights;
3076 * Get a list of implicit groups
3077 * @return \type{\arrayof{\string}} Array of internal group names
3079 public static function getImplicitGroups() {
3080 global $wgImplicitGroups;
3081 $groups = $wgImplicitGroups;
3082 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3087 * Get the title of a page describing a particular group
3089 * @param $group \type{\string} Internal group name
3090 * @return \twotypes{Title,\bool} Title of the page if it exists, false otherwise
3092 static function getGroupPage( $group ) {
3093 global $wgMessageCache;
3094 $wgMessageCache->loadAllMessages();
3095 $page = wfMsgForContent( 'grouppage-' . $group );
3096 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3097 $title = Title
::newFromText( $page );
3098 if( is_object( $title ) )
3105 * Create a link to the group in HTML, if available;
3106 * else return the group name.
3108 * @param $group \type{\string} Internal name of the group
3109 * @param $text \type{\string} The text of the link
3110 * @return \type{\string} HTML link to the group
3112 static function makeGroupLinkHTML( $group, $text = '' ) {
3114 $text = self
::getGroupName( $group );
3116 $title = self
::getGroupPage( $group );
3119 $sk = $wgUser->getSkin();
3120 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3127 * Create a link to the group in Wikitext, if available;
3128 * else return the group name.
3130 * @param $group \type{\string} Internal name of the group
3131 * @param $text \type{\string} The text of the link
3132 * @return \type{\string} Wikilink to the group
3134 static function makeGroupLinkWiki( $group, $text = '' ) {
3136 $text = self
::getGroupName( $group );
3138 $title = self
::getGroupPage( $group );
3140 $page = $title->getPrefixedText();
3141 return "[[$page|$text]]";
3148 * Increment the user's edit-count field.
3149 * Will have no effect for anonymous users.
3151 function incEditCount() {
3152 if( !$this->isAnon() ) {
3153 $dbw = wfGetDB( DB_MASTER
);
3154 $dbw->update( 'user',
3155 array( 'user_editcount=user_editcount+1' ),
3156 array( 'user_id' => $this->getId() ),
3159 // Lazy initialization check...
3160 if( $dbw->affectedRows() == 0 ) {
3161 // Pull from a slave to be less cruel to servers
3162 // Accuracy isn't the point anyway here
3163 $dbr = wfGetDB( DB_SLAVE
);
3164 $count = $dbr->selectField( 'revision',
3166 array( 'rev_user' => $this->getId() ),
3169 // Now here's a goddamn hack...
3170 if( $dbr !== $dbw ) {
3171 // If we actually have a slave server, the count is
3172 // at least one behind because the current transaction
3173 // has not been committed and replicated.
3176 // But if DB_SLAVE is selecting the master, then the
3177 // count we just read includes the revision that was
3178 // just added in the working transaction.
3181 $dbw->update( 'user',
3182 array( 'user_editcount' => $count ),
3183 array( 'user_id' => $this->getId() ),
3187 // edit count in user cache too
3188 $this->invalidateCache();
3192 * Get the description of a given right
3194 * @param $right \type{\string} Right to query
3195 * @return \type{\string} Localized description of the right
3197 static function getRightDescription( $right ) {
3198 global $wgMessageCache;
3199 $wgMessageCache->loadAllMessages();
3200 $key = "right-$right";
3201 $name = wfMsg( $key );
3202 return $name == '' ||
wfEmptyMsg( $key, $name )
3208 * Make an old-style password hash
3210 * @param $password \type{\string} Plain-text password
3211 * @param $userId \type{\string} %User ID
3212 * @return \type{\string} Password hash
3214 static function oldCrypt( $password, $userId ) {
3215 global $wgPasswordSalt;
3216 if ( $wgPasswordSalt ) {
3217 return md5( $userId . '-' . md5( $password ) );
3219 return md5( $password );
3224 * Make a new-style password hash
3226 * @param $password \type{\string} Plain-text password
3227 * @param $salt \type{\string} Optional salt, may be random or the user ID.
3228 * If unspecified or false, will generate one automatically
3229 * @return \type{\string} Password hash
3231 static function crypt( $password, $salt = false ) {
3232 global $wgPasswordSalt;
3234 if($wgPasswordSalt) {
3235 if ( $salt === false ) {
3236 $salt = substr( wfGenerateToken(), 0, 8 );
3238 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3240 return ':A:' . md5( $password);
3245 * Compare a password hash with a plain-text password. Requires the user
3246 * ID if there's a chance that the hash is an old-style hash.
3248 * @param $hash \type{\string} Password hash
3249 * @param $password \type{\string} Plain-text password to compare
3250 * @param $userId \type{\string} %User ID for old-style password salt
3251 * @return \type{\bool} True if matches, false otherwise
3253 static function comparePasswords( $hash, $password, $userId = false ) {
3255 $type = substr( $hash, 0, 3 );
3256 if ( $type == ':A:' ) {
3258 return md5( $password ) === substr( $hash, 3 );
3259 } elseif ( $type == ':B:' ) {
3261 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3262 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3265 return self
::oldCrypt( $password, $userId ) === $hash;
3270 * Add a newuser log entry for this user
3271 * @param bool $byEmail, account made by email?
3273 public function addNewUserLogEntry( $byEmail = false ) {
3274 global $wgUser, $wgContLang, $wgNewUserLog;
3275 if( empty($wgNewUserLog) ) {
3276 return true; // disabled
3278 $talk = $wgContLang->getFormattedNsText( NS_TALK
);
3279 if( $this->getName() == $wgUser->getName() ) {
3283 $action = 'create2';
3284 $message = $byEmail ?
wfMsgForContent( 'newuserlog-byemail' ) : '';
3286 $log = new LogPage( 'newusers' );
3287 $log->addEntry( $action, $this->getUserPage(), $message, array( $this->getId() ) );
3292 * Add an autocreate newuser log entry for this user
3293 * Used by things like CentralAuth and perhaps other authplugins.
3295 public function addNewUserLogEntryAutoCreate() {
3296 global $wgNewUserLog;
3297 if( empty($wgNewUserLog) ) {
3298 return true; // disabled
3300 $log = new LogPage( 'newusers', false );
3301 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );