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',
121 // user_restrictions table
126 * \type{\arrayof{\string}} Core rights.
127 * Each of these should have a corresponding message of the form
131 static $mCoreRights = array(
175 * \type{\string} Cached results of getAllRights()
177 static $mAllRights = false;
179 /** @name Cache variables */
181 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
182 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
183 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups,
188 * \type{\bool} Whether the cache variables have been loaded.
193 * \type{\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;
210 * Lightweight constructor for an anonymous user.
211 * Use the User::newFrom* factory functions for other kinds of users.
215 * @see newFromConfirmationCode()
216 * @see newFromSession()
220 $this->clearInstanceCache( 'defaults' );
224 * Load the user table data for this object from the source given by mFrom.
227 if ( $this->mDataLoaded
) {
230 wfProfileIn( __METHOD__
);
232 # Set it now to avoid infinite recursion in accessors
233 $this->mDataLoaded
= true;
235 switch ( $this->mFrom
) {
237 $this->loadDefaults();
240 $this->mId
= self
::idFromName( $this->mName
);
242 # Nonexistent user placeholder object
243 $this->loadDefaults( $this->mName
);
252 $this->loadFromSession();
255 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
257 wfProfileOut( __METHOD__
);
261 * Load user table data, given mId has already been set.
262 * @return \type{\bool} false if the ID does not exist, true otherwise
265 function loadFromId() {
267 if ( $this->mId
== 0 ) {
268 $this->loadDefaults();
273 $key = wfMemcKey( 'user', 'id', $this->mId
);
274 $data = $wgMemc->get( $key );
275 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
276 # Object is expired, load from DB
281 wfDebug( "Cache miss for user {$this->mId}\n" );
283 if ( !$this->loadFromDatabase() ) {
284 # Can't load from ID, user is anonymous
287 $this->saveToCache();
289 wfDebug( "Got user {$this->mId} from cache\n" );
291 foreach ( self
::$mCacheVars as $name ) {
292 $this->$name = $data[$name];
299 * Save user data to the shared cache
301 function saveToCache() {
304 $this->loadRestrictions();
305 if ( $this->isAnon() ) {
306 // Anonymous users are uncached
310 foreach ( self
::$mCacheVars as $name ) {
311 $data[$name] = $this->$name;
313 $data['mVersion'] = MW_USER_VERSION
;
314 $key = wfMemcKey( 'user', 'id', $this->mId
);
316 $wgMemc->set( $key, $data );
320 /** @name newFrom*() static factory methods */
324 * Static factory method for creation from username.
326 * This is slightly less efficient than newFromId(), so use newFromId() if
327 * you have both an ID and a name handy.
329 * @param $name \type{\string} Username, validated by Title::newFromText()
330 * @param $validate \type{\mixed} Validate username. Takes the same parameters as
331 * User::getCanonicalName(), except that true is accepted as an alias
332 * for 'valid', for BC.
334 * @return \type{User} The User object, or null if the username is invalid. If the
335 * username is not present in the database, the result will be a user object
336 * with a name, zero user ID and default settings.
338 static function newFromName( $name, $validate = 'valid' ) {
339 if ( $validate === true ) {
342 $name = self
::getCanonicalName( $name, $validate );
343 if ( $name === false ) {
346 # Create unloaded user object
355 * Static factory method for creation from a given user ID.
357 * @param $id \type{\int} Valid user ID
358 * @return \type{User} The corresponding User object
360 static function newFromId( $id ) {
368 * Factory method to fetch whichever user has a given email confirmation code.
369 * This code is generated when an account is created or its e-mail address
372 * If the code is invalid or has expired, returns NULL.
374 * @param $code \type{\string} Confirmation code
375 * @return \type{User}
377 static function newFromConfirmationCode( $code ) {
378 $dbr = wfGetDB( DB_SLAVE
);
379 $id = $dbr->selectField( 'user', 'user_id', array(
380 'user_email_token' => md5( $code ),
381 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
383 if( $id !== false ) {
384 return User
::newFromId( $id );
391 * Create a new user object using data from session or cookies. If the
392 * login credentials are invalid, the result is an anonymous user.
394 * @return \type{User}
396 static function newFromSession() {
398 $user->mFrom
= 'session';
403 * Create a new user object from a user row.
404 * The row should have all fields from the user table in it.
405 * @param $row array A row from the user table
406 * @return \type{User}
408 static function newFromRow( $row ) {
410 $user->loadFromRow( $row );
418 * Get the username corresponding to a given user ID
419 * @param $id \type{\int} %User ID
420 * @return \type{\string} The corresponding username
422 static function whoIs( $id ) {
423 $dbr = wfGetDB( DB_SLAVE
);
424 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
428 * Get the real name of a user given their user ID
430 * @param $id \type{\int} %User ID
431 * @return \type{\string} The corresponding user's real name
433 static function whoIsReal( $id ) {
434 $dbr = wfGetDB( DB_SLAVE
);
435 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
439 * Get database id given a user name
440 * @param $name \type{\string} Username
441 * @return \twotypes{\int,\null} The corresponding user's ID, or null if user is nonexistent
444 static function idFromName( $name ) {
445 $nt = Title
::newFromText( $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 \type{\string} String to match
474 * @return \type{\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 \type{\string} String to match
489 * @return \type{\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 \type{\string} String to match
543 * @return \type{\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 \type{\string} String to match
581 * @return \type{\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 \type{\string} Desired password
595 * @return \type{\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 \type{\string} E-mail address
621 * @return \type{\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 \type{\string} User input
636 * @param $validate \twotypes{\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 \type{\int} %User ID to check
695 * @return \type{\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 \type{\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 \type{\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( $_SESSION['wsUserID'] ) ) {
808 if ( 0 != $_SESSION['wsUserID'] ) {
809 $sId = $_SESSION['wsUserID'];
811 $this->loadDefaults();
814 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
815 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
816 $_SESSION['wsUserID'] = $sId;
818 $this->loadDefaults();
821 if ( isset( $_SESSION['wsUserName'] ) ) {
822 $sName = $_SESSION['wsUserName'];
823 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
824 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
825 $_SESSION['wsUserName'] = $sName;
827 $this->loadDefaults();
831 $passwordCorrect = FALSE;
833 if ( !$this->loadFromId() ) {
834 # Not a valid ID, loadFromId has switched the object to anon for us
838 if ( isset( $_SESSION['wsToken'] ) ) {
839 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
841 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
842 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
845 # No session or persistent login cookie
846 $this->loadDefaults();
850 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
851 $_SESSION['wsToken'] = $this->mToken
;
852 wfDebug( "Logged in from $from\n" );
855 # Invalid credentials
856 wfDebug( "Can't log in from $from, invalid credentials\n" );
857 $this->loadDefaults();
863 * Load user and user_group data from the database.
864 * $this::mId must be set, this is how the user is identified.
866 * @return \type{\bool} True if the user exists, false if the user is anonymous
869 function loadFromDatabase() {
871 $this->mId
= intval( $this->mId
);
873 /** Anonymous user */
875 $this->loadDefaults();
879 $dbr = wfGetDB( DB_MASTER
);
880 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
882 if ( $s !== false ) {
883 # Initialise user table data
884 $this->loadFromRow( $s );
885 $this->mGroups
= null; // deferred
886 $this->mRestrictions
= null;
887 $this->getEditCount(); // revalidation for nulls
892 $this->loadDefaults();
898 * Initialize this object from a row from the user table.
900 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
902 function loadFromRow( $row ) {
903 $this->mDataLoaded
= true;
905 if ( isset( $row->user_id
) ) {
906 $this->mId
= $row->user_id
;
908 $this->mName
= $row->user_name
;
909 $this->mRealName
= $row->user_real_name
;
910 $this->mPassword
= $row->user_password
;
911 $this->mNewpassword
= $row->user_newpassword
;
912 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
913 $this->mEmail
= $row->user_email
;
914 $this->decodeOptions( $row->user_options
);
915 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
916 $this->mToken
= $row->user_token
;
917 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
918 $this->mEmailToken
= $row->user_email_token
;
919 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
920 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
921 $this->mEditCount
= $row->user_editcount
;
925 * Load the groups from the database if they aren't already loaded.
928 function loadGroups() {
929 if ( is_null( $this->mGroups
) ) {
930 $dbr = wfGetDB( DB_MASTER
);
931 $res = $dbr->select( 'user_groups',
933 array( 'ug_user' => $this->mId
),
935 $this->mGroups
= array();
936 while( $row = $dbr->fetchObject( $res ) ) {
937 $this->mGroups
[] = $row->ug_group
;
943 * Clear various cached data stored in this object.
944 * @param $reloadFrom \type{\string} Reload user and user_groups table data from a
945 * given source. May be "name", "id", "defaults", "session", or false for
948 function clearInstanceCache( $reloadFrom = false ) {
949 $this->mNewtalk
= -1;
950 $this->mDatePreference
= null;
951 $this->mBlockedby
= -1; # Unset
952 $this->mHash
= false;
954 $this->mRights
= null;
955 $this->mEffectiveGroups
= null;
958 $this->mDataLoaded
= false;
959 $this->mFrom
= $reloadFrom;
964 * Combine the language default options with any site-specific options
965 * and add the default language variants.
967 * @return \type{\arrayof{\string}} Array of options
969 static function getDefaultOptions() {
970 global $wgNamespacesToBeSearchedDefault;
972 * Site defaults will override the global/language defaults
974 global $wgDefaultUserOptions, $wgContLang;
975 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
978 * default language setting
980 $variant = $wgContLang->getPreferredVariant( false );
981 $defOpt['variant'] = $variant;
982 $defOpt['language'] = $variant;
984 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
985 $defOpt['searchNs'.$nsnum] = $val;
991 * Get a given default option value.
993 * @param $opt \type{\string} Name of option to retrieve
994 * @return \type{\string} Default option value
996 public static function getDefaultOption( $opt ) {
997 $defOpts = self
::getDefaultOptions();
998 if( isset( $defOpts[$opt] ) ) {
999 return $defOpts[$opt];
1006 * Get a list of user toggle names
1007 * @return \type{\arrayof{\string}} Array of user toggle names
1009 static function getToggles() {
1011 $extraToggles = array();
1012 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1013 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1018 * Get blocking information
1020 * @param $bFromSlave \type{\bool} Whether to check the slave database first. To
1021 * improve performance, non-critical checks are done
1022 * against slaves. Check when actually saving should be
1023 * done against master.
1025 function getBlockedStatus( $bFromSlave = true ) {
1026 global $wgEnableSorbs, $wgProxyWhitelist;
1028 if ( -1 != $this->mBlockedby
) {
1029 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1033 wfProfileIn( __METHOD__
);
1034 wfDebug( __METHOD__
.": checking...\n" );
1036 // Initialize data...
1037 // Otherwise something ends up stomping on $this->mBlockedby when
1038 // things get lazy-loaded later, causing false positive block hits
1039 // due to -1 !== 0. Probably session-related... Nothing should be
1040 // overwriting mBlockedby, surely?
1043 $this->mBlockedby
= 0;
1044 $this->mHideName
= 0;
1045 $this->mAllowUsertalk
= 0;
1048 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1049 # Exempt from all types of IP-block
1054 $this->mBlock
= new Block();
1055 $this->mBlock
->fromMaster( !$bFromSlave );
1056 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1057 wfDebug( __METHOD__
.": Found block.\n" );
1058 $this->mBlockedby
= $this->mBlock
->mBy
;
1059 $this->mBlockreason
= $this->mBlock
->mReason
;
1060 $this->mHideName
= $this->mBlock
->mHideName
;
1061 $this->mAllowUsertalk
= $this->mBlock
->mAllowUsertalk
;
1062 if ( $this->isLoggedIn() ) {
1063 $this->spreadBlock();
1066 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1067 // apply to users. Note that the existence of $this->mBlock is not used to
1068 // check for edit blocks, $this->mBlockedby is instead.
1072 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1074 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1075 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1076 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1080 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1081 if ( $this->inSorbsBlacklist( $ip ) ) {
1082 $this->mBlockedby
= wfMsg( 'sorbs' );
1083 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1089 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1091 wfProfileOut( __METHOD__
);
1095 * Whether the given IP is in the SORBS blacklist.
1097 * @param $ip \type{\string} IP to check
1098 * @return \type{\bool} True if blacklisted
1100 function inSorbsBlacklist( $ip ) {
1101 global $wgEnableSorbs, $wgSorbsUrl;
1103 return $wgEnableSorbs &&
1104 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1108 * Whether the given IP is in a given DNS blacklist.
1110 * @param $ip \type{\string} IP to check
1111 * @param $base \type{\string} URL of the DNS blacklist
1112 * @return \type{\bool} True if blacklisted
1114 function inDnsBlacklist( $ip, $base ) {
1115 wfProfileIn( __METHOD__
);
1119 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1120 if( IP
::isIPv4($ip) ) {
1122 $host = "$ip.$base";
1125 $ipList = gethostbynamel( $host );
1128 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1131 wfDebug( "Requested $host, not found in $base.\n" );
1135 wfProfileOut( __METHOD__
);
1140 * Is this user subject to rate limiting?
1142 * @return \type{\bool} True if rate limited
1144 public function isPingLimitable() {
1145 global $wgRateLimitsExcludedGroups;
1146 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1147 // Deprecated, but kept for backwards-compatibility config
1150 return !$this->isAllowed('noratelimit');
1154 * Primitive rate limits: enforce maximum actions per time period
1155 * to put a brake on flooding.
1157 * @note When using a shared cache like memcached, IP-address
1158 * last-hit counters will be shared across wikis.
1160 * @param $action \type{\string} Action to enforce; 'edit' if unspecified
1161 * @return \type{\bool} True if a rate limiter was tripped
1163 function pingLimiter( $action='edit' ) {
1165 # Call the 'PingLimiter' hook
1167 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1171 global $wgRateLimits;
1172 if( !isset( $wgRateLimits[$action] ) ) {
1176 # Some groups shouldn't trigger the ping limiter, ever
1177 if( !$this->isPingLimitable() )
1180 global $wgMemc, $wgRateLimitLog;
1181 wfProfileIn( __METHOD__
);
1183 $limits = $wgRateLimits[$action];
1185 $id = $this->getId();
1189 if( isset( $limits['anon'] ) && $id == 0 ) {
1190 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1193 if( isset( $limits['user'] ) && $id != 0 ) {
1194 $userLimit = $limits['user'];
1196 if( $this->isNewbie() ) {
1197 if( isset( $limits['newbie'] ) && $id != 0 ) {
1198 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1200 if( isset( $limits['ip'] ) ) {
1201 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1204 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1205 $subnet = $matches[1];
1206 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1209 // Check for group-specific permissions
1210 // If more than one group applies, use the group with the highest limit
1211 foreach ( $this->getGroups() as $group ) {
1212 if ( isset( $limits[$group] ) ) {
1213 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1214 $userLimit = $limits[$group];
1218 // Set the user limit key
1219 if ( $userLimit !== false ) {
1220 wfDebug( __METHOD__
.": effective user limit: $userLimit\n" );
1221 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1225 foreach( $keys as $key => $limit ) {
1226 list( $max, $period ) = $limit;
1227 $summary = "(limit $max in {$period}s)";
1228 $count = $wgMemc->get( $key );
1230 if( $count > $max ) {
1231 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1232 if( $wgRateLimitLog ) {
1233 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1237 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1240 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1241 $wgMemc->add( $key, 1, intval( $period ) );
1243 $wgMemc->incr( $key );
1246 wfProfileOut( __METHOD__
);
1251 * Check if user is blocked
1253 * @param $bFromSlave \type{\bool} Whether to check the slave database instead of the master
1254 * @return \type{\bool} True if blocked, false otherwise
1256 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1257 wfDebug( "User::isBlocked: enter\n" );
1258 $this->getBlockedStatus( $bFromSlave );
1259 return $this->mBlockedby
!== 0;
1263 * Check if user is blocked from editing a particular article
1265 * @param $title \type{\string} Title to check
1266 * @param $bFromSlave \type{\bool} Whether to check the slave database instead of the master
1267 * @return \type{\bool} True if blocked, false otherwise
1269 function isBlockedFrom( $title, $bFromSlave = false ) {
1270 global $wgBlockAllowsUTEdit;
1271 wfProfileIn( __METHOD__
);
1272 wfDebug( __METHOD__
.": enter\n" );
1274 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1275 $blocked = $this->isBlocked( $bFromSlave );
1276 # If a user's name is suppressed, they cannot make edits anywhere
1277 if ( !$this->mHideName
&& $this->mAllowUsertalk
&& $title->getText() === $this->getName() &&
1278 $title->getNamespace() == NS_USER_TALK
) {
1280 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1282 wfProfileOut( __METHOD__
);
1287 * If user is blocked, return the name of the user who placed the block
1288 * @return \type{\string} name of blocker
1290 function blockedBy() {
1291 $this->getBlockedStatus();
1292 return $this->mBlockedby
;
1296 * If user is blocked, return the specified reason for the block
1297 * @return \type{\string} Blocking reason
1299 function blockedFor() {
1300 $this->getBlockedStatus();
1301 return $this->mBlockreason
;
1305 * Get the user's ID.
1306 * @return \type{\int} The user's ID; 0 if the user is anonymous or nonexistent
1309 if( $this->mId
=== null and $this->mName
!== null
1310 and User
::isIP( $this->mName
) ) {
1311 // Special case, we know the user is anonymous
1313 } elseif( $this->mId
=== null ) {
1314 // Don't load if this was initialized from an ID
1321 * Set the user and reload all fields according to a given ID
1322 * @param $v \type{\int} %User ID to reload
1324 function setId( $v ) {
1326 $this->clearInstanceCache( 'id' );
1330 * Get the user name, or the IP of an anonymous user
1331 * @return \type{\string} User's name or IP address
1333 function getName() {
1334 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1335 # Special case optimisation
1336 return $this->mName
;
1339 if ( $this->mName
=== false ) {
1341 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1343 return $this->mName
;
1348 * Set the user name.
1350 * This does not reload fields from the database according to the given
1351 * name. Rather, it is used to create a temporary "nonexistent user" for
1352 * later addition to the database. It can also be used to set the IP
1353 * address for an anonymous user to something other than the current
1356 * @note User::newFromName() has rougly the same function, when the named user
1358 * @param $str \type{\string} New user name to set
1360 function setName( $str ) {
1362 $this->mName
= $str;
1366 * Get the user's name escaped by underscores.
1367 * @return \type{\string} Username escaped by underscores
1369 function getTitleKey() {
1370 return str_replace( ' ', '_', $this->getName() );
1374 * Check if the user has new messages.
1375 * @return \type{\bool} True if the user has new messages
1377 function getNewtalk() {
1380 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1381 if( $this->mNewtalk
=== -1 ) {
1382 $this->mNewtalk
= false; # reset talk page status
1384 # Check memcached separately for anons, who have no
1385 # entire User object stored in there.
1388 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1389 $newtalk = $wgMemc->get( $key );
1390 if( strval( $newtalk ) !== '' ) {
1391 $this->mNewtalk
= (bool)$newtalk;
1393 // Since we are caching this, make sure it is up to date by getting it
1395 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1396 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1399 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1403 return (bool)$this->mNewtalk
;
1407 * Return the talk page(s) this user has new messages on.
1408 * @return \type{\arrayof{\string}} Array of page URLs
1410 function getNewMessageLinks() {
1412 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1415 if (!$this->getNewtalk())
1417 $up = $this->getUserPage();
1418 $utp = $up->getTalkPage();
1419 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1424 * Internal uncached check for new messages
1427 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1428 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1429 * @param $fromMaster \type{\bool} true to fetch from the master, false for a slave
1430 * @return \type{\bool} True if the user has new messages
1433 function checkNewtalk( $field, $id, $fromMaster = false ) {
1434 if ( $fromMaster ) {
1435 $db = wfGetDB( DB_MASTER
);
1437 $db = wfGetDB( DB_SLAVE
);
1439 $ok = $db->selectField( 'user_newtalk', $field,
1440 array( $field => $id ), __METHOD__
);
1441 return $ok !== false;
1445 * Add or update the new messages flag
1446 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1447 * @param $id \twotypes{string,\int} User's IP address for anonymous users, %User ID otherwise
1448 * @return \type{\bool} True if successful, false otherwise
1451 function updateNewtalk( $field, $id ) {
1452 $dbw = wfGetDB( DB_MASTER
);
1453 $dbw->insert( 'user_newtalk',
1454 array( $field => $id ),
1457 if ( $dbw->affectedRows() ) {
1458 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1461 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1467 * Clear the new messages flag for the given user
1468 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1469 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1470 * @return \type{\bool} True if successful, false otherwise
1473 function deleteNewtalk( $field, $id ) {
1474 $dbw = wfGetDB( DB_MASTER
);
1475 $dbw->delete( 'user_newtalk',
1476 array( $field => $id ),
1478 if ( $dbw->affectedRows() ) {
1479 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1482 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1488 * Update the 'You have new messages!' status.
1489 * @param $val \type{\bool} Whether the user has new messages
1491 function setNewtalk( $val ) {
1492 if( wfReadOnly() ) {
1497 $this->mNewtalk
= $val;
1499 if( $this->isAnon() ) {
1501 $id = $this->getName();
1504 $id = $this->getId();
1509 $changed = $this->updateNewtalk( $field, $id );
1511 $changed = $this->deleteNewtalk( $field, $id );
1514 if( $this->isAnon() ) {
1515 // Anons have a separate memcached space, since
1516 // user records aren't kept for them.
1517 $key = wfMemcKey( 'newtalk', 'ip', $id );
1518 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1521 $this->invalidateCache();
1526 * Generate a current or new-future timestamp to be stored in the
1527 * user_touched field when we update things.
1528 * @return \type{\string} Timestamp in TS_MW format
1530 private static function newTouchedTimestamp() {
1531 global $wgClockSkewFudge;
1532 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1536 * Clear user data from memcached.
1537 * Use after applying fun updates to the database; caller's
1538 * responsibility to update user_touched if appropriate.
1540 * Called implicitly from invalidateCache() and saveSettings().
1542 private function clearSharedCache() {
1545 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1550 * Immediately touch the user data cache for this account.
1551 * Updates user_touched field, and removes account data from memcached
1552 * for reload on the next hit.
1554 function invalidateCache() {
1557 $this->mTouched
= self
::newTouchedTimestamp();
1559 $dbw = wfGetDB( DB_MASTER
);
1560 $dbw->update( 'user',
1561 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1562 array( 'user_id' => $this->mId
),
1565 $this->clearSharedCache();
1570 * Validate the cache for this account.
1571 * @param $timestamp \type{\string} A timestamp in TS_MW format
1573 function validateCache( $timestamp ) {
1575 return ($timestamp >= $this->mTouched
);
1579 * Get the user touched timestamp
1581 function getTouched() {
1583 return $this->mTouched
;
1587 * Set the password and reset the random token.
1588 * Calls through to authentication plugin if necessary;
1589 * will have no effect if the auth plugin refuses to
1590 * pass the change through or if the legal password
1593 * As a special case, setting the password to null
1594 * wipes it, so the account cannot be logged in until
1595 * a new password is set, for instance via e-mail.
1597 * @param $str \type{\string} New password to set
1598 * @throws PasswordError on failure
1600 function setPassword( $str ) {
1603 if( $str !== null ) {
1604 if( !$wgAuth->allowPasswordChange() ) {
1605 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1608 if( !$this->isValidPassword( $str ) ) {
1609 global $wgMinimalPasswordLength;
1610 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1611 $wgMinimalPasswordLength ) );
1615 if( !$wgAuth->setPassword( $this, $str ) ) {
1616 throw new PasswordError( wfMsg( 'externaldberror' ) );
1619 $this->setInternalPassword( $str );
1625 * Set the password and reset the random token unconditionally.
1627 * @param $str \type{\string} New password to set
1629 function setInternalPassword( $str ) {
1633 if( $str === null ) {
1634 // Save an invalid hash...
1635 $this->mPassword
= '';
1637 $this->mPassword
= self
::crypt( $str );
1639 $this->mNewpassword
= '';
1640 $this->mNewpassTime
= null;
1644 * Get the user's current token.
1645 * @return \type{\string} Token
1647 function getToken() {
1649 return $this->mToken
;
1653 * Set the random token (used for persistent authentication)
1654 * Called from loadDefaults() among other places.
1656 * @param $token \type{\string} If specified, set the token to this value
1659 function setToken( $token = false ) {
1660 global $wgSecretKey, $wgProxyKey;
1663 if ( $wgSecretKey ) {
1664 $key = $wgSecretKey;
1665 } elseif ( $wgProxyKey ) {
1670 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1672 $this->mToken
= $token;
1677 * Set the cookie password
1679 * @param $str \type{\string} New cookie password
1682 function setCookiePassword( $str ) {
1684 $this->mCookiePassword
= md5( $str );
1688 * Set the password for a password reminder or new account email
1690 * @param $str \type{\string} New password to set
1691 * @param $throttle \type{\bool} If true, reset the throttle timestamp to the present
1693 function setNewpassword( $str, $throttle = true ) {
1695 $this->mNewpassword
= self
::crypt( $str );
1697 $this->mNewpassTime
= wfTimestampNow();
1702 * Has password reminder email been sent within the last
1703 * $wgPasswordReminderResendTime hours?
1704 * @return \type{\bool} True or false
1706 function isPasswordReminderThrottled() {
1707 global $wgPasswordReminderResendTime;
1709 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1712 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1713 return time() < $expiry;
1717 * Get the user's e-mail address
1718 * @return \type{\string} User's e-mail address
1720 function getEmail() {
1722 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1723 return $this->mEmail
;
1727 * Get the timestamp of the user's e-mail authentication
1728 * @return \type{\string} TS_MW timestamp
1730 function getEmailAuthenticationTimestamp() {
1732 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1733 return $this->mEmailAuthenticated
;
1737 * Set the user's e-mail address
1738 * @param $str \type{\string} New e-mail address
1740 function setEmail( $str ) {
1742 $this->mEmail
= $str;
1743 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1747 * Get the user's real name
1748 * @return \type{\string} User's real name
1750 function getRealName() {
1752 return $this->mRealName
;
1756 * Set the user's real name
1757 * @param $str \type{\string} New real name
1759 function setRealName( $str ) {
1761 $this->mRealName
= $str;
1765 * Get the user's current setting for a given option.
1767 * @param $oname \type{\string} The option to check
1768 * @param $defaultOverride \type{\string} A default value returned if the option does not exist
1769 * @return \type{\string} User's current value for the option
1770 * @see getBoolOption()
1771 * @see getIntOption()
1773 function getOption( $oname, $defaultOverride = '' ) {
1776 if ( is_null( $this->mOptions
) ) {
1777 if($defaultOverride != '') {
1778 return $defaultOverride;
1780 $this->mOptions
= User
::getDefaultOptions();
1783 if ( array_key_exists( $oname, $this->mOptions
) ) {
1784 return trim( $this->mOptions
[$oname] );
1786 return $defaultOverride;
1791 * Get the user's current setting for a given option, as a boolean value.
1793 * @param $oname \type{\string} The option to check
1794 * @return \type{\bool} User's current value for the option
1797 function getBoolOption( $oname ) {
1798 return (bool)$this->getOption( $oname );
1803 * Get the user's current setting for a given option, as a boolean value.
1805 * @param $oname \type{\string} The option to check
1806 * @param $defaultOverride \type{\int} A default value returned if the option does not exist
1807 * @return \type{\int} User's current value for the option
1810 function getIntOption( $oname, $defaultOverride=0 ) {
1811 $val = $this->getOption( $oname );
1813 $val = $defaultOverride;
1815 return intval( $val );
1819 * Set the given option for a user.
1821 * @param $oname \type{\string} The option to set
1822 * @param $val \type{\mixed} New value to set
1824 function setOption( $oname, $val ) {
1826 if ( is_null( $this->mOptions
) ) {
1827 $this->mOptions
= User
::getDefaultOptions();
1829 if ( $oname == 'skin' ) {
1830 # Clear cached skin, so the new one displays immediately in Special:Preferences
1831 unset( $this->mSkin
);
1833 // Filter out any newlines that may have passed through input validation.
1834 // Newlines are used to separate items in the options blob.
1836 $val = str_replace( "\r\n", "\n", $val );
1837 $val = str_replace( "\r", "\n", $val );
1838 $val = str_replace( "\n", " ", $val );
1840 // Explicitly NULL values should refer to defaults
1841 global $wgDefaultUserOptions;
1842 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1843 $val = $wgDefaultUserOptions[$oname];
1845 $this->mOptions
[$oname] = $val;
1849 * Get the user's preferred date format.
1850 * @return \type{\string} User's preferred date format
1852 function getDatePreference() {
1853 // Important migration for old data rows
1854 if ( is_null( $this->mDatePreference
) ) {
1856 $value = $this->getOption( 'date' );
1857 $map = $wgLang->getDatePreferenceMigrationMap();
1858 if ( isset( $map[$value] ) ) {
1859 $value = $map[$value];
1861 $this->mDatePreference
= $value;
1863 return $this->mDatePreference
;
1867 * Get the permissions this user has.
1868 * @return \type{\arrayof{\string}} Array of permission names
1870 function getRights() {
1871 if ( is_null( $this->mRights
) ) {
1872 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1873 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1874 // Force reindexation of rights when a hook has unset one of them
1875 $this->mRights
= array_values( $this->mRights
);
1877 return $this->mRights
;
1881 * Get the list of explicit group memberships this user has.
1882 * The implicit * and user groups are not included.
1883 * @return \type{\arrayof{\string}} Array of internal group names
1885 function getGroups() {
1887 return $this->mGroups
;
1891 * Get the list of implicit group memberships this user has.
1892 * This includes all explicit groups, plus 'user' if logged in,
1893 * '*' for all accounts and autopromoted groups
1895 * @param $recache \type{\bool} Whether to avoid the cache
1896 * @return \type{\arrayof{\string}} Array of internal group names
1898 function getEffectiveGroups( $recache = false ) {
1899 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1900 $this->mEffectiveGroups
= $this->getGroups();
1901 $this->mEffectiveGroups
[] = '*';
1902 if( $this->getId() ) {
1903 $this->mEffectiveGroups
[] = 'user';
1905 $this->mEffectiveGroups
= array_unique( array_merge(
1906 $this->mEffectiveGroups
,
1907 Autopromote
::getAutopromoteGroups( $this )
1910 # Hook for additional groups
1911 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1914 return $this->mEffectiveGroups
;
1918 * Get the user's edit count.
1919 * @return \type{\int} User's edit count
1921 function getEditCount() {
1923 if ( !isset( $this->mEditCount
) ) {
1924 /* Populate the count, if it has not been populated yet */
1925 $this->mEditCount
= User
::edits($this->mId
);
1927 return $this->mEditCount
;
1935 * Add the user to the given group.
1936 * This takes immediate effect.
1937 * @param $group \type{\string} Name of the group to add
1939 function addGroup( $group ) {
1940 $dbw = wfGetDB( DB_MASTER
);
1941 if( $this->getId() ) {
1942 $dbw->insert( 'user_groups',
1944 'ug_user' => $this->getID(),
1945 'ug_group' => $group,
1948 array( 'IGNORE' ) );
1951 $this->loadGroups();
1952 $this->mGroups
[] = $group;
1953 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1955 $this->invalidateCache();
1959 * Remove the user from the given group.
1960 * This takes immediate effect.
1961 * @param $group \type{\string} Name of the group to remove
1963 function removeGroup( $group ) {
1965 $dbw = wfGetDB( DB_MASTER
);
1966 $dbw->delete( 'user_groups',
1968 'ug_user' => $this->getID(),
1969 'ug_group' => $group,
1971 'User::removeGroup' );
1973 $this->loadGroups();
1974 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1975 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1977 $this->invalidateCache();
1982 * Get whether the user is logged in
1983 * @return \type{\bool} True or false
1985 function isLoggedIn() {
1986 return $this->getID() != 0;
1990 * Get whether the user is anonymous
1991 * @return \type{\bool} True or false
1994 return !$this->isLoggedIn();
1998 * Get whether the user is a bot
1999 * @return \type{\bool} True or false
2003 wfDeprecated( __METHOD__
);
2004 return $this->isAllowed( 'bot' );
2008 * Check if user is allowed to access a feature / make an action
2009 * @param $action \type{\string} action to be checked
2010 * @return \type{\bool} True if action is allowed, else false
2012 function isAllowed($action='') {
2013 if ( $action === '' )
2014 // In the spirit of DWIM
2017 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2018 # by misconfiguration: 0 == 'foo'
2019 return in_array( $action, $this->getRights(), true );
2023 * Check whether to enable recent changes patrol features for this user
2024 * @return \type{\bool} True or false
2026 public function useRCPatrol() {
2027 global $wgUseRCPatrol;
2028 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2032 * Check whether to enable new pages patrol features for this user
2033 * @return \type{\bool} True or false
2035 public function useNPPatrol() {
2036 global $wgUseRCPatrol, $wgUseNPPatrol;
2037 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2041 * Get the current skin, loading it if required
2042 * @return \type{Skin} Current skin
2043 * @todo FIXME : need to check the old failback system [AV]
2045 function &getSkin() {
2047 if ( ! isset( $this->mSkin
) ) {
2048 wfProfileIn( __METHOD__
);
2051 $userSkin = $this->getOption( 'skin' );
2052 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2054 $this->mSkin
=& Skin
::newFromKey( $userSkin );
2055 wfProfileOut( __METHOD__
);
2057 return $this->mSkin
;
2061 * Check the watched status of an article.
2062 * @param $title \type{Title} Title of the article to look at
2063 * @return \type{\bool} True if article is watched
2065 function isWatched( $title ) {
2066 $wl = WatchedItem
::fromUserTitle( $this, $title );
2067 return $wl->isWatched();
2072 * @param $title \type{Title} Title of the article to look at
2074 function addWatch( $title ) {
2075 $wl = WatchedItem
::fromUserTitle( $this, $title );
2077 $this->invalidateCache();
2081 * Stop watching an article.
2082 * @param $title \type{Title} Title of the article to look at
2084 function removeWatch( $title ) {
2085 $wl = WatchedItem
::fromUserTitle( $this, $title );
2087 $this->invalidateCache();
2091 * Clear the user's notification timestamp for the given title.
2092 * If e-notif e-mails are on, they will receive notification mails on
2093 * the next change of the page if it's watched etc.
2094 * @param $title \type{Title} Title of the article to look at
2096 function clearNotification( &$title ) {
2097 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2099 # Do nothing if the database is locked to writes
2100 if( wfReadOnly() ) {
2104 if ($title->getNamespace() == NS_USER_TALK
&&
2105 $title->getText() == $this->getName() ) {
2106 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2108 $this->setNewtalk( false );
2111 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2115 if( $this->isAnon() ) {
2116 // Nothing else to do...
2120 // Only update the timestamp if the page is being watched.
2121 // The query to find out if it is watched is cached both in memcached and per-invocation,
2122 // and when it does have to be executed, it can be on a slave
2123 // If this is the user's newtalk page, we always update the timestamp
2124 if ($title->getNamespace() == NS_USER_TALK
&&
2125 $title->getText() == $wgUser->getName())
2128 } elseif ( $this->getId() == $wgUser->getId() ) {
2129 $watched = $title->userIsWatching();
2134 // If the page is watched by the user (or may be watched), update the timestamp on any
2135 // any matching rows
2137 $dbw = wfGetDB( DB_MASTER
);
2138 $dbw->update( 'watchlist',
2140 'wl_notificationtimestamp' => NULL
2141 ), array( /* WHERE */
2142 'wl_title' => $title->getDBkey(),
2143 'wl_namespace' => $title->getNamespace(),
2144 'wl_user' => $this->getID()
2151 * Resets all of the given user's page-change notification timestamps.
2152 * If e-notif e-mails are on, they will receive notification mails on
2153 * the next change of any watched page.
2155 * @param $currentUser \type{\int} %User ID
2157 function clearAllNotifications( $currentUser ) {
2158 global $wgUseEnotif, $wgShowUpdatedMarker;
2159 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2160 $this->setNewtalk( false );
2163 if( $currentUser != 0 ) {
2164 $dbw = wfGetDB( DB_MASTER
);
2165 $dbw->update( 'watchlist',
2167 'wl_notificationtimestamp' => NULL
2168 ), array( /* WHERE */
2169 'wl_user' => $currentUser
2172 # We also need to clear here the "you have new message" notification for the own user_talk page
2173 # This is cleared one page view later in Article::viewUpdates();
2178 * Encode this user's options as a string
2179 * @return \type{\string} Encoded options
2182 function encodeOptions() {
2184 if ( is_null( $this->mOptions
) ) {
2185 $this->mOptions
= User
::getDefaultOptions();
2188 foreach ( $this->mOptions
as $oname => $oval ) {
2189 array_push( $a, $oname.'='.$oval );
2191 $s = implode( "\n", $a );
2196 * Set this user's options from an encoded string
2197 * @param $str \type{\string} Encoded options to import
2200 function decodeOptions( $str ) {
2201 $this->mOptions
= array();
2202 $a = explode( "\n", $str );
2203 foreach ( $a as $s ) {
2205 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2206 $this->mOptions
[$m[1]] = $m[2];
2212 * Set a cookie on the user's client. Wrapper for
2213 * WebResponse::setCookie
2215 protected function setCookie( $name, $value, $exp=0 ) {
2217 $wgRequest->response()->setcookie( $name, $value, $exp );
2221 * Clear a cookie on the user's client
2222 * @param $name \type{\string} Name of the cookie to clear
2224 protected function clearCookie( $name ) {
2225 $this->setCookie( $name, '', time() - 86400 );
2229 * Set the default cookies for this session on the user's client.
2231 function setCookies() {
2233 if ( 0 == $this->mId
) return;
2235 'wsUserID' => $this->mId
,
2236 'wsToken' => $this->mToken
,
2237 'wsUserName' => $this->getName()
2240 'UserID' => $this->mId
,
2241 'UserName' => $this->getName(),
2243 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2244 $cookies['Token'] = $this->mToken
;
2246 $cookies['Token'] = false;
2249 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2250 $_SESSION = $session +
$_SESSION;
2251 foreach ( $cookies as $name => $value ) {
2252 if ( $value === false ) {
2253 $this->clearCookie( $name );
2255 $this->setCookie( $name, $value );
2261 * Log this user out.
2265 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2271 * Clear the user's cookies and session, and reset the instance cache.
2275 function doLogout() {
2276 $this->clearInstanceCache( 'defaults' );
2278 $_SESSION['wsUserID'] = 0;
2280 $this->clearCookie( 'UserID' );
2281 $this->clearCookie( 'Token' );
2283 # Remember when user logged out, to prevent seeing cached pages
2284 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2288 * Save this user's settings into the database.
2289 * @todo Only rarely do all these fields need to be set!
2291 function saveSettings() {
2293 if ( wfReadOnly() ) { return; }
2294 if ( 0 == $this->mId
) { return; }
2296 $this->mTouched
= self
::newTouchedTimestamp();
2298 $dbw = wfGetDB( DB_MASTER
);
2299 $dbw->update( 'user',
2301 'user_name' => $this->mName
,
2302 'user_password' => $this->mPassword
,
2303 'user_newpassword' => $this->mNewpassword
,
2304 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2305 'user_real_name' => $this->mRealName
,
2306 'user_email' => $this->mEmail
,
2307 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2308 'user_options' => $this->encodeOptions(),
2309 'user_touched' => $dbw->timestamp($this->mTouched
),
2310 'user_token' => $this->mToken
,
2311 'user_email_token' => $this->mEmailToken
,
2312 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2313 ), array( /* WHERE */
2314 'user_id' => $this->mId
2317 wfRunHooks( 'UserSaveSettings', array( $this ) );
2318 $this->clearSharedCache();
2322 * If only this user's username is known, and it exists, return the user ID.
2324 function idForName() {
2325 $s = trim( $this->getName() );
2326 if ( $s === '' ) return 0;
2328 $dbr = wfGetDB( DB_SLAVE
);
2329 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2330 if ( $id === false ) {
2337 * Add a user to the database, return the user object
2339 * @param $name \type{\string} Username to add
2340 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2341 * - password The user's password. Password logins will be disabled if this is omitted.
2342 * - newpassword A temporary password mailed to the user
2343 * - email The user's email address
2344 * - email_authenticated The email authentication timestamp
2345 * - real_name The user's real name
2346 * - options An associative array of non-default options
2347 * - token Random authentication token. Do not set.
2348 * - registration Registration timestamp. Do not set.
2350 * @return \type{User} A new User object, or null if the username already exists
2352 static function createNew( $name, $params = array() ) {
2355 if ( isset( $params['options'] ) ) {
2356 $user->mOptions
= $params['options'] +
$user->mOptions
;
2357 unset( $params['options'] );
2359 $dbw = wfGetDB( DB_MASTER
);
2360 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2362 'user_id' => $seqVal,
2363 'user_name' => $name,
2364 'user_password' => $user->mPassword
,
2365 'user_newpassword' => $user->mNewpassword
,
2366 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2367 'user_email' => $user->mEmail
,
2368 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2369 'user_real_name' => $user->mRealName
,
2370 'user_options' => $user->encodeOptions(),
2371 'user_token' => $user->mToken
,
2372 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2373 'user_editcount' => 0,
2375 foreach ( $params as $name => $value ) {
2376 $fields["user_$name"] = $value;
2378 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2379 if ( $dbw->affectedRows() ) {
2380 $newUser = User
::newFromId( $dbw->insertId() );
2388 * Add this existing user object to the database
2390 function addToDatabase() {
2392 $dbw = wfGetDB( DB_MASTER
);
2393 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2394 $dbw->insert( 'user',
2396 'user_id' => $seqVal,
2397 'user_name' => $this->mName
,
2398 'user_password' => $this->mPassword
,
2399 'user_newpassword' => $this->mNewpassword
,
2400 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2401 'user_email' => $this->mEmail
,
2402 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2403 'user_real_name' => $this->mRealName
,
2404 'user_options' => $this->encodeOptions(),
2405 'user_token' => $this->mToken
,
2406 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2407 'user_editcount' => 0,
2410 $this->mId
= $dbw->insertId();
2412 // Clear instance cache other than user table data, which is already accurate
2413 $this->clearInstanceCache();
2417 * If this (non-anonymous) user is blocked, block any IP address
2418 * they've successfully logged in from.
2420 function spreadBlock() {
2421 wfDebug( __METHOD__
."()\n" );
2423 if ( $this->mId
== 0 ) {
2427 $userblock = Block
::newFromDB( '', $this->mId
);
2428 if ( !$userblock ) {
2432 $userblock->doAutoblock( wfGetIp() );
2437 * Generate a string which will be different for any combination of
2438 * user options which would produce different parser output.
2439 * This will be used as part of the hash key for the parser cache,
2440 * so users will the same options can share the same cached data
2443 * Extensions which require it should install 'PageRenderingHash' hook,
2444 * which will give them a chance to modify this key based on their own
2447 * @return \type{\string} Page rendering hash
2449 function getPageRenderingHash() {
2450 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2452 return $this->mHash
;
2455 // stubthreshold is only included below for completeness,
2456 // it will always be 0 when this function is called by parsercache.
2458 $confstr = $this->getOption( 'math' );
2459 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2460 if ( $wgUseDynamicDates ) {
2461 $confstr .= '!' . $this->getDatePreference();
2463 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2464 $confstr .= '!' . $wgLang->getCode();
2465 $confstr .= '!' . $this->getOption( 'thumbsize' );
2466 // add in language specific options, if any
2467 $extra = $wgContLang->getExtraHashOptions();
2470 $confstr .= $wgRenderHashAppend;
2472 // Give a chance for extensions to modify the hash, if they have
2473 // extra options or other effects on the parser cache.
2474 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2476 // Make it a valid memcached key fragment
2477 $confstr = str_replace( ' ', '_', $confstr );
2478 $this->mHash
= $confstr;
2483 * Get whether the user is explicitly blocked from account creation.
2484 * @return \type{\bool} True if blocked
2486 function isBlockedFromCreateAccount() {
2487 $this->getBlockedStatus();
2488 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2492 * Get whether the user is blocked from using Special:Emailuser.
2493 * @return \type{\bool} True if blocked
2495 function isBlockedFromEmailuser() {
2496 $this->getBlockedStatus();
2497 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2501 * Get whether the user is allowed to create an account.
2502 * @return \type{\bool} True if allowed
2504 function isAllowedToCreateAccount() {
2505 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2511 function setLoaded( $loaded ) {
2512 wfDeprecated( __METHOD__
);
2516 * Get this user's personal page title.
2518 * @return \type{Title} User's personal page title
2520 function getUserPage() {
2521 return Title
::makeTitle( NS_USER
, $this->getName() );
2525 * Get this user's talk page title.
2527 * @return \type{Title} User's talk page title
2529 function getTalkPage() {
2530 $title = $this->getUserPage();
2531 return $title->getTalkPage();
2535 * Get the maximum valid user ID.
2536 * @return \type{\int} %User ID
2539 function getMaxID() {
2540 static $res; // cache
2542 if ( isset( $res ) )
2545 $dbr = wfGetDB( DB_SLAVE
);
2546 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2551 * Determine whether the user is a newbie. Newbies are either
2552 * anonymous IPs, or the most recently created accounts.
2553 * @return \type{\bool} True if the user is a newbie
2555 function isNewbie() {
2556 return !$this->isAllowed( 'autoconfirmed' );
2560 * Is the user active? We check to see if they've made at least
2561 * X number of edits in the last Y days.
2563 * @return \type{\bool} True if the user is active, false if not.
2565 public function isActiveEditor() {
2566 global $wgActiveUserEditCount, $wgActiveUserDays;
2567 $dbr = wfGetDB( DB_SLAVE
);
2569 // Stolen without shame from RC
2570 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2571 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
2572 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2574 $res = $dbr->select( 'revision', '1',
2575 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2577 array('LIMIT' => $wgActiveUserEditCount ) );
2579 $count = $dbr->numRows($res);
2580 $dbr->freeResult($res);
2582 return $count == $wgActiveUserEditCount;
2586 * Check to see if the given clear-text password is one of the accepted passwords
2587 * @param $password \type{\string} user password.
2588 * @return \type{\bool} True if the given password is correct, otherwise False.
2590 function checkPassword( $password ) {
2594 // Even though we stop people from creating passwords that
2595 // are shorter than this, doesn't mean people wont be able
2596 // to. Certain authentication plugins do NOT want to save
2597 // domain passwords in a mysql database, so we should
2598 // check this (incase $wgAuth->strict() is false).
2599 if( !$this->isValidPassword( $password ) ) {
2603 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2605 } elseif( $wgAuth->strict() ) {
2606 /* Auth plugin doesn't allow local authentication */
2608 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2609 /* Auth plugin doesn't allow local authentication for this user name */
2612 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2614 } elseif ( function_exists( 'iconv' ) ) {
2615 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2616 # Check for this with iconv
2617 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2618 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2626 * Check if the given clear-text password matches the temporary password
2627 * sent by e-mail for password reset operations.
2628 * @return \type{\bool} True if matches, false otherwise
2630 function checkTemporaryPassword( $plaintext ) {
2631 return self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() );
2635 * Initialize (if necessary) and return a session token value
2636 * which can be used in edit forms to show that the user's
2637 * login credentials aren't being hijacked with a foreign form
2640 * @param $salt \twotypes{\string,\arrayof{\string}} Optional function-specific data for hashing
2641 * @return \type{\string} The new edit token
2643 function editToken( $salt = '' ) {
2644 if ( $this->isAnon() ) {
2645 return EDIT_TOKEN_SUFFIX
;
2647 if( !isset( $_SESSION['wsEditToken'] ) ) {
2648 $token = $this->generateToken();
2649 $_SESSION['wsEditToken'] = $token;
2651 $token = $_SESSION['wsEditToken'];
2653 if( is_array( $salt ) ) {
2654 $salt = implode( '|', $salt );
2656 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2661 * Generate a looking random token for various uses.
2663 * @param $salt \type{\string} Optional salt value
2664 * @return \type{\string} The new random token
2666 function generateToken( $salt = '' ) {
2667 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2668 return md5( $token . $salt );
2672 * Check given value against the token value stored in the session.
2673 * A match should confirm that the form was submitted from the
2674 * user's own login session, not a form submission from a third-party
2677 * @param $val \type{\string} Input value to compare
2678 * @param $salt \type{\string} Optional function-specific data for hashing
2679 * @return \type{\bool} Whether the token matches
2681 function matchEditToken( $val, $salt = '' ) {
2682 $sessionToken = $this->editToken( $salt );
2683 if ( $val != $sessionToken ) {
2684 wfDebug( "User::matchEditToken: broken session data\n" );
2686 return $val == $sessionToken;
2690 * Check given value against the token value stored in the session,
2691 * ignoring the suffix.
2693 * @param $val \type{\string} Input value to compare
2694 * @param $salt \type{\string} Optional function-specific data for hashing
2695 * @return \type{\bool} Whether the token matches
2697 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2698 $sessionToken = $this->editToken( $salt );
2699 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2703 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2704 * mail to the user's given address.
2706 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure.
2708 function sendConfirmationMail() {
2710 $expiration = null; // gets passed-by-ref and defined in next line.
2711 $token = $this->confirmationToken( $expiration );
2712 $url = $this->confirmationTokenUrl( $token );
2713 $invalidateURL = $this->invalidationTokenUrl( $token );
2714 $this->saveSettings();
2716 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2717 wfMsg( 'confirmemail_body',
2721 $wgLang->timeanddate( $expiration, false ),
2726 * Send an e-mail to this user's account. Does not check for
2727 * confirmed status or validity.
2729 * @param $subject \type{\string} Message subject
2730 * @param $body \type{\string} Message body
2731 * @param $from \type{\string} Optional From address; if unspecified, default $wgPasswordSender will be used
2732 * @param $replyto \type{\string} Reply-to address
2733 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure
2735 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2736 if( is_null( $from ) ) {
2737 global $wgPasswordSender;
2738 $from = $wgPasswordSender;
2741 $to = new MailAddress( $this );
2742 $sender = new MailAddress( $from );
2743 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2747 * Generate, store, and return a new e-mail confirmation code.
2748 * A hash (unsalted, since it's used as a key) is stored.
2750 * @note Call saveSettings() after calling this function to commit
2751 * this change to the database.
2753 * @param[out] &$expiration \type{\mixed} Accepts the expiration time
2754 * @return \type{\string} New token
2757 function confirmationToken( &$expiration ) {
2759 $expires = $now +
7 * 24 * 60 * 60;
2760 $expiration = wfTimestamp( TS_MW
, $expires );
2761 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2762 $hash = md5( $token );
2764 $this->mEmailToken
= $hash;
2765 $this->mEmailTokenExpires
= $expiration;
2770 * Return a URL the user can use to confirm their email address.
2771 * @param $token \type{\string} Accepts the email confirmation token
2772 * @return \type{\string} New token URL
2775 function confirmationTokenUrl( $token ) {
2776 return $this->getTokenUrl( 'ConfirmEmail', $token );
2779 * Return a URL the user can use to invalidate their email address.
2781 * @param $token \type{\string} Accepts the email confirmation token
2782 * @return \type{\string} New token URL
2785 function invalidationTokenUrl( $token ) {
2786 return $this->getTokenUrl( 'Invalidateemail', $token );
2790 * Internal function to format the e-mail validation/invalidation URLs.
2791 * This uses $wgArticlePath directly as a quickie hack to use the
2792 * hardcoded English names of the Special: pages, for ASCII safety.
2794 * @note Since these URLs get dropped directly into emails, using the
2795 * short English names avoids insanely long URL-encoded links, which
2796 * also sometimes can get corrupted in some browsers/mailers
2797 * (bug 6957 with Gmail and Internet Explorer).
2799 * @param $page \type{\string} Special page
2800 * @param $token \type{\string} Token
2801 * @return \type{\string} Formatted URL
2803 protected function getTokenUrl( $page, $token ) {
2804 global $wgArticlePath;
2808 "Special:$page/$token",
2813 * Mark the e-mail address confirmed.
2815 * @note Call saveSettings() after calling this function to commit the change.
2817 function confirmEmail() {
2818 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2823 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2824 * address if it was already confirmed.
2826 * @note Call saveSettings() after calling this function to commit the change.
2828 function invalidateEmail() {
2830 $this->mEmailToken
= null;
2831 $this->mEmailTokenExpires
= null;
2832 $this->setEmailAuthenticationTimestamp( null );
2837 * Set the e-mail authentication timestamp.
2838 * @param $timestamp \type{\string} TS_MW timestamp
2840 function setEmailAuthenticationTimestamp( $timestamp ) {
2842 $this->mEmailAuthenticated
= $timestamp;
2843 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2847 * Is this user allowed to send e-mails within limits of current
2848 * site configuration?
2849 * @return \type{\bool} True if allowed
2851 function canSendEmail() {
2852 $canSend = $this->isEmailConfirmed();
2853 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2858 * Is this user allowed to receive e-mails within limits of current
2859 * site configuration?
2860 * @return \type{\bool} True if allowed
2862 function canReceiveEmail() {
2863 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2867 * Is this user's e-mail address valid-looking and confirmed within
2868 * limits of the current site configuration?
2870 * @note If $wgEmailAuthentication is on, this may require the user to have
2871 * confirmed their address by returning a code or using a password
2872 * sent to the address from the wiki.
2874 * @return \type{\bool} True if confirmed
2876 function isEmailConfirmed() {
2877 global $wgEmailAuthentication;
2880 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2881 if( $this->isAnon() )
2883 if( !self
::isValidEmailAddr( $this->mEmail
) )
2885 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2894 * Check whether there is an outstanding request for e-mail confirmation.
2895 * @return \type{\bool} True if pending
2897 function isEmailConfirmationPending() {
2898 global $wgEmailAuthentication;
2899 return $wgEmailAuthentication &&
2900 !$this->isEmailConfirmed() &&
2901 $this->mEmailToken
&&
2902 $this->mEmailTokenExpires
> wfTimestamp();
2906 * Get the timestamp of account creation.
2908 * @return \twotypes{\string,\bool} string Timestamp of account creation, or false for
2909 * non-existent/anonymous user accounts.
2911 public function getRegistration() {
2912 return $this->mId
> 0
2913 ?
$this->mRegistration
2918 * Get the permissions associated with a given list of groups
2920 * @param $groups \type{\arrayof{\string}} List of internal group names
2921 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
2923 static function getGroupPermissions( $groups ) {
2924 global $wgGroupPermissions;
2926 foreach( $groups as $group ) {
2927 if( isset( $wgGroupPermissions[$group] ) ) {
2928 $rights = array_merge( $rights,
2929 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2936 * Get all the groups who have a given permission
2938 * @param $role \type{\string} Role to check
2939 * @return \type{\arrayof{\string}} List of internal group names with the given permission
2941 static function getGroupsWithPermission( $role ) {
2942 global $wgGroupPermissions;
2943 $allowedGroups = array();
2944 foreach ( $wgGroupPermissions as $group => $rights ) {
2945 if ( isset( $rights[$role] ) && $rights[$role] ) {
2946 $allowedGroups[] = $group;
2949 return $allowedGroups;
2953 * Get the localized descriptive name for a group, if it exists
2955 * @param $group \type{\string} Internal group name
2956 * @return \type{\string} Localized descriptive group name
2958 static function getGroupName( $group ) {
2959 global $wgMessageCache;
2960 $wgMessageCache->loadAllMessages();
2961 $key = "group-$group";
2962 $name = wfMsg( $key );
2963 return $name == '' ||
wfEmptyMsg( $key, $name )
2969 * Get the localized descriptive name for a member of a group, if it exists
2971 * @param $group \type{\string} Internal group name
2972 * @return \type{\string} Localized name for group member
2974 static function getGroupMember( $group ) {
2975 global $wgMessageCache;
2976 $wgMessageCache->loadAllMessages();
2977 $key = "group-$group-member";
2978 $name = wfMsg( $key );
2979 return $name == '' ||
wfEmptyMsg( $key, $name )
2985 * Return the set of defined explicit groups.
2986 * The implicit groups (by default *, 'user' and 'autoconfirmed')
2987 * are not included, as they are defined automatically, not in the database.
2988 * @return \type{\arrayof{\string}} Array of internal group names
2990 static function getAllGroups() {
2991 global $wgGroupPermissions;
2993 array_keys( $wgGroupPermissions ),
2994 self
::getImplicitGroups()
2999 * Get a list of all available permissions.
3000 * @return \type{\arrayof{\string}} Array of permission names
3002 static function getAllRights() {
3003 if ( self
::$mAllRights === false ) {
3004 global $wgAvailableRights;
3005 if ( count( $wgAvailableRights ) ) {
3006 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3008 self
::$mAllRights = self
::$mCoreRights;
3010 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3012 return self
::$mAllRights;
3016 * Get a list of implicit groups
3017 * @return \type{\arrayof{\string}} Array of internal group names
3019 public static function getImplicitGroups() {
3020 global $wgImplicitGroups;
3021 $groups = $wgImplicitGroups;
3022 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3027 * Get the title of a page describing a particular group
3029 * @param $group \type{\string} Internal group name
3030 * @return \twotypes{Title,\bool} Title of the page if it exists, false otherwise
3032 static function getGroupPage( $group ) {
3033 global $wgMessageCache;
3034 $wgMessageCache->loadAllMessages();
3035 $page = wfMsgForContent( 'grouppage-' . $group );
3036 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3037 $title = Title
::newFromText( $page );
3038 if( is_object( $title ) )
3045 * Create a link to the group in HTML, if available;
3046 * else return the group name.
3048 * @param $group \type{\string} Internal name of the group
3049 * @param $text \type{\string} The text of the link
3050 * @return \type{\string} HTML link to the group
3052 static function makeGroupLinkHTML( $group, $text = '' ) {
3054 $text = self
::getGroupName( $group );
3056 $title = self
::getGroupPage( $group );
3059 $sk = $wgUser->getSkin();
3060 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3067 * Create a link to the group in Wikitext, if available;
3068 * else return the group name.
3070 * @param $group \type{\string} Internal name of the group
3071 * @param $text \type{\string} The text of the link
3072 * @return \type{\string} Wikilink to the group
3074 static function makeGroupLinkWiki( $group, $text = '' ) {
3076 $text = self
::getGroupName( $group );
3078 $title = self
::getGroupPage( $group );
3080 $page = $title->getPrefixedText();
3081 return "[[$page|$text]]";
3088 * Increment the user's edit-count field.
3089 * Will have no effect for anonymous users.
3091 function incEditCount() {
3092 if( !$this->isAnon() ) {
3093 $dbw = wfGetDB( DB_MASTER
);
3094 $dbw->update( 'user',
3095 array( 'user_editcount=user_editcount+1' ),
3096 array( 'user_id' => $this->getId() ),
3099 // Lazy initialization check...
3100 if( $dbw->affectedRows() == 0 ) {
3101 // Pull from a slave to be less cruel to servers
3102 // Accuracy isn't the point anyway here
3103 $dbr = wfGetDB( DB_SLAVE
);
3104 $count = $dbr->selectField( 'revision',
3106 array( 'rev_user' => $this->getId() ),
3109 // Now here's a goddamn hack...
3110 if( $dbr !== $dbw ) {
3111 // If we actually have a slave server, the count is
3112 // at least one behind because the current transaction
3113 // has not been committed and replicated.
3116 // But if DB_SLAVE is selecting the master, then the
3117 // count we just read includes the revision that was
3118 // just added in the working transaction.
3121 $dbw->update( 'user',
3122 array( 'user_editcount' => $count ),
3123 array( 'user_id' => $this->getId() ),
3127 // edit count in user cache too
3128 $this->invalidateCache();
3132 * Get the description of a given right
3134 * @param $right \type{\string} Right to query
3135 * @return \type{\string} Localized description of the right
3137 static function getRightDescription( $right ) {
3138 global $wgMessageCache;
3139 $wgMessageCache->loadAllMessages();
3140 $key = "right-$right";
3141 $name = wfMsg( $key );
3142 return $name == '' ||
wfEmptyMsg( $key, $name )
3148 * Make an old-style password hash
3150 * @param $password \type{\string} Plain-text password
3151 * @param $userId \type{\string} %User ID
3152 * @return \type{\string} Password hash
3154 static function oldCrypt( $password, $userId ) {
3155 global $wgPasswordSalt;
3156 if ( $wgPasswordSalt ) {
3157 return md5( $userId . '-' . md5( $password ) );
3159 return md5( $password );
3164 * Make a new-style password hash
3166 * @param $password \type{\string} Plain-text password
3167 * @param $salt \type{\string} Optional salt, may be random or the user ID.
3168 * If unspecified or false, will generate one automatically
3169 * @return \type{\string} Password hash
3171 static function crypt( $password, $salt = false ) {
3172 global $wgPasswordSalt;
3174 if($wgPasswordSalt) {
3175 if ( $salt === false ) {
3176 $salt = substr( wfGenerateToken(), 0, 8 );
3178 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3180 return ':A:' . md5( $password);
3185 * Compare a password hash with a plain-text password. Requires the user
3186 * ID if there's a chance that the hash is an old-style hash.
3188 * @param $hash \type{\string} Password hash
3189 * @param $password \type{\string} Plain-text password to compare
3190 * @param $userId \type{\string} %User ID for old-style password salt
3191 * @return \type{\bool} True if matches, false otherwise
3193 static function comparePasswords( $hash, $password, $userId = false ) {
3195 $type = substr( $hash, 0, 3 );
3196 if ( $type == ':A:' ) {
3198 return md5( $password ) === substr( $hash, 3 );
3199 } elseif ( $type == ':B:' ) {
3201 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3202 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3205 return self
::oldCrypt( $password, $userId ) === $hash;
3210 * Add a newuser log entry for this user
3211 * @param bool $byEmail, account made by email?
3213 public function addNewUserLogEntry( $byEmail = false ) {
3214 global $wgUser, $wgContLang, $wgNewUserLog;
3215 if( empty($wgNewUserLog) ) {
3216 return true; // disabled
3218 $talk = $wgContLang->getFormattedNsText( NS_TALK
);
3219 if( $this->getName() == $wgUser->getName() ) {
3223 $action = 'create2';
3224 $message = $byEmail ?
wfMsgForContent( 'newuserlog-byemail' ) : '';
3226 $log = new LogPage( 'newusers' );
3227 $log->addEntry( $action, $this->getUserPage(), $message, array( $this->getId() ) );
3232 * Add an autocreate newuser log entry for this user
3233 * Used by things like CentralAuth and perhaps other authplugins.
3235 public function addNewUserLogEntryAutoCreate() {
3236 global $wgNewUserLog;
3237 if( empty($wgNewUserLog) ) {
3238 return true; // disabled
3240 $log = new LogPage( 'newusers', false );
3241 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3245 // Restrictions-related block
3247 public function loadRestrictions() {
3248 if( !$this->mRestrictions
)
3249 $this->mRestrictions
= UserRestriction
::fetchForUser( $this->isLoggedIn() ?
3250 intval( $this->getId() ) : $this->getName() );
3253 public function getRestrictions() {
3254 $this->loadRestrictions();
3256 // Check for expired restrictions. Recache if found expired ones
3257 static $checked = false;
3260 $old = $this->mRestrictions
;
3261 $this->mRestrictions
= array();
3262 foreach( $old as $restriction ) {
3263 if( $restriction->deleteIfExpired() )
3266 $this->mRestrictions
[] = $restriction;
3269 $this->saveToCache();
3273 return $this->mRestrictions
;
3276 public function getRestrictionForPage( Title
$page ) {
3277 foreach( $this->getRestrictions() as $r ) {
3278 if( $r->isPage() && $page->equals( $r->getPage() ) )
3284 public function getRestrictionForNamespace( $nsid ) {
3285 foreach( $this->getRestrictions() as $r ) {
3286 if( $r->isNamespace() && $r->getNamespace() == $nsid )