c43507177699de2a05aca038ee5e896dcf0d7407
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', 7 );
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 $allowUsertalk = ($wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false);
1277 # If a user's name is suppressed, they cannot make edits anywhere
1278 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1279 $title->getNamespace() == NS_USER_TALK
) {
1281 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1283 wfProfileOut( __METHOD__
);
1288 * If user is blocked, return the name of the user who placed the block
1289 * @return \type{\string} name of blocker
1291 function blockedBy() {
1292 $this->getBlockedStatus();
1293 return $this->mBlockedby
;
1297 * If user is blocked, return the specified reason for the block
1298 * @return \type{\string} Blocking reason
1300 function blockedFor() {
1301 $this->getBlockedStatus();
1302 return $this->mBlockreason
;
1306 * Get the user's ID.
1307 * @return \type{\int} The user's ID; 0 if the user is anonymous or nonexistent
1310 if( $this->mId
=== null and $this->mName
!== null
1311 and User
::isIP( $this->mName
) ) {
1312 // Special case, we know the user is anonymous
1314 } elseif( $this->mId
=== null ) {
1315 // Don't load if this was initialized from an ID
1322 * Set the user and reload all fields according to a given ID
1323 * @param $v \type{\int} %User ID to reload
1325 function setId( $v ) {
1327 $this->clearInstanceCache( 'id' );
1331 * Get the user name, or the IP of an anonymous user
1332 * @return \type{\string} User's name or IP address
1334 function getName() {
1335 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1336 # Special case optimisation
1337 return $this->mName
;
1340 if ( $this->mName
=== false ) {
1342 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1344 return $this->mName
;
1349 * Set the user name.
1351 * This does not reload fields from the database according to the given
1352 * name. Rather, it is used to create a temporary "nonexistent user" for
1353 * later addition to the database. It can also be used to set the IP
1354 * address for an anonymous user to something other than the current
1357 * @note User::newFromName() has rougly the same function, when the named user
1359 * @param $str \type{\string} New user name to set
1361 function setName( $str ) {
1363 $this->mName
= $str;
1367 * Get the user's name escaped by underscores.
1368 * @return \type{\string} Username escaped by underscores
1370 function getTitleKey() {
1371 return str_replace( ' ', '_', $this->getName() );
1375 * Check if the user has new messages.
1376 * @return \type{\bool} True if the user has new messages
1378 function getNewtalk() {
1381 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1382 if( $this->mNewtalk
=== -1 ) {
1383 $this->mNewtalk
= false; # reset talk page status
1385 # Check memcached separately for anons, who have no
1386 # entire User object stored in there.
1389 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1390 $newtalk = $wgMemc->get( $key );
1391 if( strval( $newtalk ) !== '' ) {
1392 $this->mNewtalk
= (bool)$newtalk;
1394 // Since we are caching this, make sure it is up to date by getting it
1396 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1397 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1400 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1404 return (bool)$this->mNewtalk
;
1408 * Return the talk page(s) this user has new messages on.
1409 * @return \type{\arrayof{\string}} Array of page URLs
1411 function getNewMessageLinks() {
1413 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1416 if (!$this->getNewtalk())
1418 $up = $this->getUserPage();
1419 $utp = $up->getTalkPage();
1420 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1425 * Internal uncached check for new messages
1428 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1429 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1430 * @param $fromMaster \type{\bool} true to fetch from the master, false for a slave
1431 * @return \type{\bool} True if the user has new messages
1434 function checkNewtalk( $field, $id, $fromMaster = false ) {
1435 if ( $fromMaster ) {
1436 $db = wfGetDB( DB_MASTER
);
1438 $db = wfGetDB( DB_SLAVE
);
1440 $ok = $db->selectField( 'user_newtalk', $field,
1441 array( $field => $id ), __METHOD__
);
1442 return $ok !== false;
1446 * Add or update the new messages flag
1447 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1448 * @param $id \twotypes{string,\int} User's IP address for anonymous users, %User ID otherwise
1449 * @return \type{\bool} True if successful, false otherwise
1452 function updateNewtalk( $field, $id ) {
1453 $dbw = wfGetDB( DB_MASTER
);
1454 $dbw->insert( 'user_newtalk',
1455 array( $field => $id ),
1458 if ( $dbw->affectedRows() ) {
1459 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1462 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1468 * Clear the new messages flag for the given user
1469 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1470 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1471 * @return \type{\bool} True if successful, false otherwise
1474 function deleteNewtalk( $field, $id ) {
1475 $dbw = wfGetDB( DB_MASTER
);
1476 $dbw->delete( 'user_newtalk',
1477 array( $field => $id ),
1479 if ( $dbw->affectedRows() ) {
1480 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1483 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1489 * Update the 'You have new messages!' status.
1490 * @param $val \type{\bool} Whether the user has new messages
1492 function setNewtalk( $val ) {
1493 if( wfReadOnly() ) {
1498 $this->mNewtalk
= $val;
1500 if( $this->isAnon() ) {
1502 $id = $this->getName();
1505 $id = $this->getId();
1510 $changed = $this->updateNewtalk( $field, $id );
1512 $changed = $this->deleteNewtalk( $field, $id );
1515 if( $this->isAnon() ) {
1516 // Anons have a separate memcached space, since
1517 // user records aren't kept for them.
1518 $key = wfMemcKey( 'newtalk', 'ip', $id );
1519 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1522 $this->invalidateCache();
1527 * Generate a current or new-future timestamp to be stored in the
1528 * user_touched field when we update things.
1529 * @return \type{\string} Timestamp in TS_MW format
1531 private static function newTouchedTimestamp() {
1532 global $wgClockSkewFudge;
1533 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1537 * Clear user data from memcached.
1538 * Use after applying fun updates to the database; caller's
1539 * responsibility to update user_touched if appropriate.
1541 * Called implicitly from invalidateCache() and saveSettings().
1543 private function clearSharedCache() {
1546 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1551 * Immediately touch the user data cache for this account.
1552 * Updates user_touched field, and removes account data from memcached
1553 * for reload on the next hit.
1555 function invalidateCache() {
1558 $this->mTouched
= self
::newTouchedTimestamp();
1560 $dbw = wfGetDB( DB_MASTER
);
1561 $dbw->update( 'user',
1562 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1563 array( 'user_id' => $this->mId
),
1566 $this->clearSharedCache();
1571 * Validate the cache for this account.
1572 * @param $timestamp \type{\string} A timestamp in TS_MW format
1574 function validateCache( $timestamp ) {
1576 return ($timestamp >= $this->mTouched
);
1580 * Get the user touched timestamp
1582 function getTouched() {
1584 return $this->mTouched
;
1588 * Set the password and reset the random token.
1589 * Calls through to authentication plugin if necessary;
1590 * will have no effect if the auth plugin refuses to
1591 * pass the change through or if the legal password
1594 * As a special case, setting the password to null
1595 * wipes it, so the account cannot be logged in until
1596 * a new password is set, for instance via e-mail.
1598 * @param $str \type{\string} New password to set
1599 * @throws PasswordError on failure
1601 function setPassword( $str ) {
1604 if( $str !== null ) {
1605 if( !$wgAuth->allowPasswordChange() ) {
1606 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1609 if( !$this->isValidPassword( $str ) ) {
1610 global $wgMinimalPasswordLength;
1611 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1612 $wgMinimalPasswordLength ) );
1616 if( !$wgAuth->setPassword( $this, $str ) ) {
1617 throw new PasswordError( wfMsg( 'externaldberror' ) );
1620 $this->setInternalPassword( $str );
1626 * Set the password and reset the random token unconditionally.
1628 * @param $str \type{\string} New password to set
1630 function setInternalPassword( $str ) {
1634 if( $str === null ) {
1635 // Save an invalid hash...
1636 $this->mPassword
= '';
1638 $this->mPassword
= self
::crypt( $str );
1640 $this->mNewpassword
= '';
1641 $this->mNewpassTime
= null;
1645 * Get the user's current token.
1646 * @return \type{\string} Token
1648 function getToken() {
1650 return $this->mToken
;
1654 * Set the random token (used for persistent authentication)
1655 * Called from loadDefaults() among other places.
1657 * @param $token \type{\string} If specified, set the token to this value
1660 function setToken( $token = false ) {
1661 global $wgSecretKey, $wgProxyKey;
1664 if ( $wgSecretKey ) {
1665 $key = $wgSecretKey;
1666 } elseif ( $wgProxyKey ) {
1671 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1673 $this->mToken
= $token;
1678 * Set the cookie password
1680 * @param $str \type{\string} New cookie password
1683 function setCookiePassword( $str ) {
1685 $this->mCookiePassword
= md5( $str );
1689 * Set the password for a password reminder or new account email
1691 * @param $str \type{\string} New password to set
1692 * @param $throttle \type{\bool} If true, reset the throttle timestamp to the present
1694 function setNewpassword( $str, $throttle = true ) {
1696 $this->mNewpassword
= self
::crypt( $str );
1698 $this->mNewpassTime
= wfTimestampNow();
1703 * Has password reminder email been sent within the last
1704 * $wgPasswordReminderResendTime hours?
1705 * @return \type{\bool} True or false
1707 function isPasswordReminderThrottled() {
1708 global $wgPasswordReminderResendTime;
1710 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1713 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1714 return time() < $expiry;
1718 * Get the user's e-mail address
1719 * @return \type{\string} User's e-mail address
1721 function getEmail() {
1723 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1724 return $this->mEmail
;
1728 * Get the timestamp of the user's e-mail authentication
1729 * @return \type{\string} TS_MW timestamp
1731 function getEmailAuthenticationTimestamp() {
1733 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1734 return $this->mEmailAuthenticated
;
1738 * Set the user's e-mail address
1739 * @param $str \type{\string} New e-mail address
1741 function setEmail( $str ) {
1743 $this->mEmail
= $str;
1744 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1748 * Get the user's real name
1749 * @return \type{\string} User's real name
1751 function getRealName() {
1753 return $this->mRealName
;
1757 * Set the user's real name
1758 * @param $str \type{\string} New real name
1760 function setRealName( $str ) {
1762 $this->mRealName
= $str;
1766 * Get the user's current setting for a given option.
1768 * @param $oname \type{\string} The option to check
1769 * @param $defaultOverride \type{\string} A default value returned if the option does not exist
1770 * @return \type{\string} User's current value for the option
1771 * @see getBoolOption()
1772 * @see getIntOption()
1774 function getOption( $oname, $defaultOverride = '' ) {
1777 if ( is_null( $this->mOptions
) ) {
1778 if($defaultOverride != '') {
1779 return $defaultOverride;
1781 $this->mOptions
= User
::getDefaultOptions();
1784 if ( array_key_exists( $oname, $this->mOptions
) ) {
1785 return trim( $this->mOptions
[$oname] );
1787 return $defaultOverride;
1792 * Get the user's current setting for a given option, as a boolean value.
1794 * @param $oname \type{\string} The option to check
1795 * @return \type{\bool} User's current value for the option
1798 function getBoolOption( $oname ) {
1799 return (bool)$this->getOption( $oname );
1804 * Get the user's current setting for a given option, as a boolean value.
1806 * @param $oname \type{\string} The option to check
1807 * @param $defaultOverride \type{\int} A default value returned if the option does not exist
1808 * @return \type{\int} User's current value for the option
1811 function getIntOption( $oname, $defaultOverride=0 ) {
1812 $val = $this->getOption( $oname );
1814 $val = $defaultOverride;
1816 return intval( $val );
1820 * Set the given option for a user.
1822 * @param $oname \type{\string} The option to set
1823 * @param $val \type{\mixed} New value to set
1825 function setOption( $oname, $val ) {
1827 if ( is_null( $this->mOptions
) ) {
1828 $this->mOptions
= User
::getDefaultOptions();
1830 if ( $oname == 'skin' ) {
1831 # Clear cached skin, so the new one displays immediately in Special:Preferences
1832 unset( $this->mSkin
);
1834 // Filter out any newlines that may have passed through input validation.
1835 // Newlines are used to separate items in the options blob.
1837 $val = str_replace( "\r\n", "\n", $val );
1838 $val = str_replace( "\r", "\n", $val );
1839 $val = str_replace( "\n", " ", $val );
1841 // Explicitly NULL values should refer to defaults
1842 global $wgDefaultUserOptions;
1843 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1844 $val = $wgDefaultUserOptions[$oname];
1846 $this->mOptions
[$oname] = $val;
1850 * Get the user's preferred date format.
1851 * @return \type{\string} User's preferred date format
1853 function getDatePreference() {
1854 // Important migration for old data rows
1855 if ( is_null( $this->mDatePreference
) ) {
1857 $value = $this->getOption( 'date' );
1858 $map = $wgLang->getDatePreferenceMigrationMap();
1859 if ( isset( $map[$value] ) ) {
1860 $value = $map[$value];
1862 $this->mDatePreference
= $value;
1864 return $this->mDatePreference
;
1868 * Get the permissions this user has.
1869 * @return \type{\arrayof{\string}} Array of permission names
1871 function getRights() {
1872 if ( is_null( $this->mRights
) ) {
1873 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1874 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1875 // Force reindexation of rights when a hook has unset one of them
1876 $this->mRights
= array_values( $this->mRights
);
1878 return $this->mRights
;
1882 * Get the list of explicit group memberships this user has.
1883 * The implicit * and user groups are not included.
1884 * @return \type{\arrayof{\string}} Array of internal group names
1886 function getGroups() {
1888 return $this->mGroups
;
1892 * Get the list of implicit group memberships this user has.
1893 * This includes all explicit groups, plus 'user' if logged in,
1894 * '*' for all accounts and autopromoted groups
1896 * @param $recache \type{\bool} Whether to avoid the cache
1897 * @return \type{\arrayof{\string}} Array of internal group names
1899 function getEffectiveGroups( $recache = false ) {
1900 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1901 $this->mEffectiveGroups
= $this->getGroups();
1902 $this->mEffectiveGroups
[] = '*';
1903 if( $this->getId() ) {
1904 $this->mEffectiveGroups
[] = 'user';
1906 $this->mEffectiveGroups
= array_unique( array_merge(
1907 $this->mEffectiveGroups
,
1908 Autopromote
::getAutopromoteGroups( $this )
1911 # Hook for additional groups
1912 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1915 return $this->mEffectiveGroups
;
1919 * Get the user's edit count.
1920 * @return \type{\int} User's edit count
1922 function getEditCount() {
1924 if ( !isset( $this->mEditCount
) ) {
1925 /* Populate the count, if it has not been populated yet */
1926 $this->mEditCount
= User
::edits($this->mId
);
1928 return $this->mEditCount
;
1936 * Add the user to the given group.
1937 * This takes immediate effect.
1938 * @param $group \type{\string} Name of the group to add
1940 function addGroup( $group ) {
1941 $dbw = wfGetDB( DB_MASTER
);
1942 if( $this->getId() ) {
1943 $dbw->insert( 'user_groups',
1945 'ug_user' => $this->getID(),
1946 'ug_group' => $group,
1949 array( 'IGNORE' ) );
1952 $this->loadGroups();
1953 $this->mGroups
[] = $group;
1954 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1956 $this->invalidateCache();
1960 * Remove the user from the given group.
1961 * This takes immediate effect.
1962 * @param $group \type{\string} Name of the group to remove
1964 function removeGroup( $group ) {
1966 $dbw = wfGetDB( DB_MASTER
);
1967 $dbw->delete( 'user_groups',
1969 'ug_user' => $this->getID(),
1970 'ug_group' => $group,
1972 'User::removeGroup' );
1974 $this->loadGroups();
1975 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1976 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1978 $this->invalidateCache();
1983 * Get whether the user is logged in
1984 * @return \type{\bool} True or false
1986 function isLoggedIn() {
1987 return $this->getID() != 0;
1991 * Get whether the user is anonymous
1992 * @return \type{\bool} True or false
1995 return !$this->isLoggedIn();
1999 * Get whether the user is a bot
2000 * @return \type{\bool} True or false
2004 wfDeprecated( __METHOD__
);
2005 return $this->isAllowed( 'bot' );
2009 * Check if user is allowed to access a feature / make an action
2010 * @param $action \type{\string} action to be checked
2011 * @return \type{\bool} True if action is allowed, else false
2013 function isAllowed($action='') {
2014 if ( $action === '' )
2015 // In the spirit of DWIM
2018 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2019 # by misconfiguration: 0 == 'foo'
2020 return in_array( $action, $this->getRights(), true );
2024 * Check whether to enable recent changes patrol features for this user
2025 * @return \type{\bool} True or false
2027 public function useRCPatrol() {
2028 global $wgUseRCPatrol;
2029 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2033 * Check whether to enable new pages patrol features for this user
2034 * @return \type{\bool} True or false
2036 public function useNPPatrol() {
2037 global $wgUseRCPatrol, $wgUseNPPatrol;
2038 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2042 * Get the current skin, loading it if required
2043 * @return \type{Skin} Current skin
2044 * @todo FIXME : need to check the old failback system [AV]
2046 function &getSkin() {
2048 if ( ! isset( $this->mSkin
) ) {
2049 wfProfileIn( __METHOD__
);
2052 $userSkin = $this->getOption( 'skin' );
2053 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2055 $this->mSkin
=& Skin
::newFromKey( $userSkin );
2056 wfProfileOut( __METHOD__
);
2058 return $this->mSkin
;
2062 * Check the watched status of an article.
2063 * @param $title \type{Title} Title of the article to look at
2064 * @return \type{\bool} True if article is watched
2066 function isWatched( $title ) {
2067 $wl = WatchedItem
::fromUserTitle( $this, $title );
2068 return $wl->isWatched();
2073 * @param $title \type{Title} Title of the article to look at
2075 function addWatch( $title ) {
2076 $wl = WatchedItem
::fromUserTitle( $this, $title );
2078 $this->invalidateCache();
2082 * Stop watching an article.
2083 * @param $title \type{Title} Title of the article to look at
2085 function removeWatch( $title ) {
2086 $wl = WatchedItem
::fromUserTitle( $this, $title );
2088 $this->invalidateCache();
2092 * Clear the user's notification timestamp for the given title.
2093 * If e-notif e-mails are on, they will receive notification mails on
2094 * the next change of the page if it's watched etc.
2095 * @param $title \type{Title} Title of the article to look at
2097 function clearNotification( &$title ) {
2098 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2100 # Do nothing if the database is locked to writes
2101 if( wfReadOnly() ) {
2105 if ($title->getNamespace() == NS_USER_TALK
&&
2106 $title->getText() == $this->getName() ) {
2107 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2109 $this->setNewtalk( false );
2112 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2116 if( $this->isAnon() ) {
2117 // Nothing else to do...
2121 // Only update the timestamp if the page is being watched.
2122 // The query to find out if it is watched is cached both in memcached and per-invocation,
2123 // and when it does have to be executed, it can be on a slave
2124 // If this is the user's newtalk page, we always update the timestamp
2125 if ($title->getNamespace() == NS_USER_TALK
&&
2126 $title->getText() == $wgUser->getName())
2129 } elseif ( $this->getId() == $wgUser->getId() ) {
2130 $watched = $title->userIsWatching();
2135 // If the page is watched by the user (or may be watched), update the timestamp on any
2136 // any matching rows
2138 $dbw = wfGetDB( DB_MASTER
);
2139 $dbw->update( 'watchlist',
2141 'wl_notificationtimestamp' => NULL
2142 ), array( /* WHERE */
2143 'wl_title' => $title->getDBkey(),
2144 'wl_namespace' => $title->getNamespace(),
2145 'wl_user' => $this->getID()
2152 * Resets all of the given user's page-change notification timestamps.
2153 * If e-notif e-mails are on, they will receive notification mails on
2154 * the next change of any watched page.
2156 * @param $currentUser \type{\int} %User ID
2158 function clearAllNotifications( $currentUser ) {
2159 global $wgUseEnotif, $wgShowUpdatedMarker;
2160 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2161 $this->setNewtalk( false );
2164 if( $currentUser != 0 ) {
2165 $dbw = wfGetDB( DB_MASTER
);
2166 $dbw->update( 'watchlist',
2168 'wl_notificationtimestamp' => NULL
2169 ), array( /* WHERE */
2170 'wl_user' => $currentUser
2173 # We also need to clear here the "you have new message" notification for the own user_talk page
2174 # This is cleared one page view later in Article::viewUpdates();
2179 * Encode this user's options as a string
2180 * @return \type{\string} Encoded options
2183 function encodeOptions() {
2185 if ( is_null( $this->mOptions
) ) {
2186 $this->mOptions
= User
::getDefaultOptions();
2189 foreach ( $this->mOptions
as $oname => $oval ) {
2190 array_push( $a, $oname.'='.$oval );
2192 $s = implode( "\n", $a );
2197 * Set this user's options from an encoded string
2198 * @param $str \type{\string} Encoded options to import
2201 function decodeOptions( $str ) {
2202 $this->mOptions
= array();
2203 $a = explode( "\n", $str );
2204 foreach ( $a as $s ) {
2206 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2207 $this->mOptions
[$m[1]] = $m[2];
2213 * Set a cookie on the user's client. Wrapper for
2214 * WebResponse::setCookie
2216 protected function setCookie( $name, $value, $exp=0 ) {
2218 $wgRequest->response()->setcookie( $name, $value, $exp );
2222 * Clear a cookie on the user's client
2223 * @param $name \type{\string} Name of the cookie to clear
2225 protected function clearCookie( $name ) {
2226 $this->setCookie( $name, '', time() - 86400 );
2230 * Set the default cookies for this session on the user's client.
2232 function setCookies() {
2234 if ( 0 == $this->mId
) return;
2236 'wsUserID' => $this->mId
,
2237 'wsToken' => $this->mToken
,
2238 'wsUserName' => $this->getName()
2241 'UserID' => $this->mId
,
2242 'UserName' => $this->getName(),
2244 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2245 $cookies['Token'] = $this->mToken
;
2247 $cookies['Token'] = false;
2250 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2251 $_SESSION = $session +
$_SESSION;
2252 foreach ( $cookies as $name => $value ) {
2253 if ( $value === false ) {
2254 $this->clearCookie( $name );
2256 $this->setCookie( $name, $value );
2262 * Log this user out.
2266 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2272 * Clear the user's cookies and session, and reset the instance cache.
2276 function doLogout() {
2277 $this->clearInstanceCache( 'defaults' );
2279 $_SESSION['wsUserID'] = 0;
2281 $this->clearCookie( 'UserID' );
2282 $this->clearCookie( 'Token' );
2284 # Remember when user logged out, to prevent seeing cached pages
2285 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2289 * Save this user's settings into the database.
2290 * @todo Only rarely do all these fields need to be set!
2292 function saveSettings() {
2294 if ( wfReadOnly() ) { return; }
2295 if ( 0 == $this->mId
) { return; }
2297 $this->mTouched
= self
::newTouchedTimestamp();
2299 $dbw = wfGetDB( DB_MASTER
);
2300 $dbw->update( 'user',
2302 'user_name' => $this->mName
,
2303 'user_password' => $this->mPassword
,
2304 'user_newpassword' => $this->mNewpassword
,
2305 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2306 'user_real_name' => $this->mRealName
,
2307 'user_email' => $this->mEmail
,
2308 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2309 'user_options' => $this->encodeOptions(),
2310 'user_touched' => $dbw->timestamp($this->mTouched
),
2311 'user_token' => $this->mToken
,
2312 'user_email_token' => $this->mEmailToken
,
2313 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2314 ), array( /* WHERE */
2315 'user_id' => $this->mId
2318 wfRunHooks( 'UserSaveSettings', array( $this ) );
2319 $this->clearSharedCache();
2323 * If only this user's username is known, and it exists, return the user ID.
2325 function idForName() {
2326 $s = trim( $this->getName() );
2327 if ( $s === '' ) return 0;
2329 $dbr = wfGetDB( DB_SLAVE
);
2330 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2331 if ( $id === false ) {
2338 * Add a user to the database, return the user object
2340 * @param $name \type{\string} Username to add
2341 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2342 * - password The user's password. Password logins will be disabled if this is omitted.
2343 * - newpassword A temporary password mailed to the user
2344 * - email The user's email address
2345 * - email_authenticated The email authentication timestamp
2346 * - real_name The user's real name
2347 * - options An associative array of non-default options
2348 * - token Random authentication token. Do not set.
2349 * - registration Registration timestamp. Do not set.
2351 * @return \type{User} A new User object, or null if the username already exists
2353 static function createNew( $name, $params = array() ) {
2356 if ( isset( $params['options'] ) ) {
2357 $user->mOptions
= $params['options'] +
$user->mOptions
;
2358 unset( $params['options'] );
2360 $dbw = wfGetDB( DB_MASTER
);
2361 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2363 'user_id' => $seqVal,
2364 'user_name' => $name,
2365 'user_password' => $user->mPassword
,
2366 'user_newpassword' => $user->mNewpassword
,
2367 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2368 'user_email' => $user->mEmail
,
2369 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2370 'user_real_name' => $user->mRealName
,
2371 'user_options' => $user->encodeOptions(),
2372 'user_token' => $user->mToken
,
2373 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2374 'user_editcount' => 0,
2376 foreach ( $params as $name => $value ) {
2377 $fields["user_$name"] = $value;
2379 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2380 if ( $dbw->affectedRows() ) {
2381 $newUser = User
::newFromId( $dbw->insertId() );
2389 * Add this existing user object to the database
2391 function addToDatabase() {
2393 $dbw = wfGetDB( DB_MASTER
);
2394 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2395 $dbw->insert( 'user',
2397 'user_id' => $seqVal,
2398 'user_name' => $this->mName
,
2399 'user_password' => $this->mPassword
,
2400 'user_newpassword' => $this->mNewpassword
,
2401 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2402 'user_email' => $this->mEmail
,
2403 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2404 'user_real_name' => $this->mRealName
,
2405 'user_options' => $this->encodeOptions(),
2406 'user_token' => $this->mToken
,
2407 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2408 'user_editcount' => 0,
2411 $this->mId
= $dbw->insertId();
2413 // Clear instance cache other than user table data, which is already accurate
2414 $this->clearInstanceCache();
2418 * If this (non-anonymous) user is blocked, block any IP address
2419 * they've successfully logged in from.
2421 function spreadBlock() {
2422 wfDebug( __METHOD__
."()\n" );
2424 if ( $this->mId
== 0 ) {
2428 $userblock = Block
::newFromDB( '', $this->mId
);
2429 if ( !$userblock ) {
2433 $userblock->doAutoblock( wfGetIp() );
2438 * Generate a string which will be different for any combination of
2439 * user options which would produce different parser output.
2440 * This will be used as part of the hash key for the parser cache,
2441 * so users will the same options can share the same cached data
2444 * Extensions which require it should install 'PageRenderingHash' hook,
2445 * which will give them a chance to modify this key based on their own
2448 * @return \type{\string} Page rendering hash
2450 function getPageRenderingHash() {
2451 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2453 return $this->mHash
;
2456 // stubthreshold is only included below for completeness,
2457 // it will always be 0 when this function is called by parsercache.
2459 $confstr = $this->getOption( 'math' );
2460 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2461 if ( $wgUseDynamicDates ) {
2462 $confstr .= '!' . $this->getDatePreference();
2464 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2465 $confstr .= '!' . $wgLang->getCode();
2466 $confstr .= '!' . $this->getOption( 'thumbsize' );
2467 // add in language specific options, if any
2468 $extra = $wgContLang->getExtraHashOptions();
2471 $confstr .= $wgRenderHashAppend;
2473 // Give a chance for extensions to modify the hash, if they have
2474 // extra options or other effects on the parser cache.
2475 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2477 // Make it a valid memcached key fragment
2478 $confstr = str_replace( ' ', '_', $confstr );
2479 $this->mHash
= $confstr;
2484 * Get whether the user is explicitly blocked from account creation.
2485 * @return \type{\bool} True if blocked
2487 function isBlockedFromCreateAccount() {
2488 $this->getBlockedStatus();
2489 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2493 * Get whether the user is blocked from using Special:Emailuser.
2494 * @return \type{\bool} True if blocked
2496 function isBlockedFromEmailuser() {
2497 $this->getBlockedStatus();
2498 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2502 * Get whether the user is allowed to create an account.
2503 * @return \type{\bool} True if allowed
2505 function isAllowedToCreateAccount() {
2506 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2512 function setLoaded( $loaded ) {
2513 wfDeprecated( __METHOD__
);
2517 * Get this user's personal page title.
2519 * @return \type{Title} User's personal page title
2521 function getUserPage() {
2522 return Title
::makeTitle( NS_USER
, $this->getName() );
2526 * Get this user's talk page title.
2528 * @return \type{Title} User's talk page title
2530 function getTalkPage() {
2531 $title = $this->getUserPage();
2532 return $title->getTalkPage();
2536 * Get the maximum valid user ID.
2537 * @return \type{\int} %User ID
2540 function getMaxID() {
2541 static $res; // cache
2543 if ( isset( $res ) )
2546 $dbr = wfGetDB( DB_SLAVE
);
2547 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2552 * Determine whether the user is a newbie. Newbies are either
2553 * anonymous IPs, or the most recently created accounts.
2554 * @return \type{\bool} True if the user is a newbie
2556 function isNewbie() {
2557 return !$this->isAllowed( 'autoconfirmed' );
2561 * Is the user active? We check to see if they've made at least
2562 * X number of edits in the last Y days.
2564 * @return \type{\bool} True if the user is active, false if not.
2566 public function isActiveEditor() {
2567 global $wgActiveUserEditCount, $wgActiveUserDays;
2568 $dbr = wfGetDB( DB_SLAVE
);
2570 // Stolen without shame from RC
2571 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2572 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
2573 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2575 $res = $dbr->select( 'revision', '1',
2576 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2578 array('LIMIT' => $wgActiveUserEditCount ) );
2580 $count = $dbr->numRows($res);
2581 $dbr->freeResult($res);
2583 return $count == $wgActiveUserEditCount;
2587 * Check to see if the given clear-text password is one of the accepted passwords
2588 * @param $password \type{\string} user password.
2589 * @return \type{\bool} True if the given password is correct, otherwise False.
2591 function checkPassword( $password ) {
2595 // Even though we stop people from creating passwords that
2596 // are shorter than this, doesn't mean people wont be able
2597 // to. Certain authentication plugins do NOT want to save
2598 // domain passwords in a mysql database, so we should
2599 // check this (incase $wgAuth->strict() is false).
2600 if( !$this->isValidPassword( $password ) ) {
2604 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2606 } elseif( $wgAuth->strict() ) {
2607 /* Auth plugin doesn't allow local authentication */
2609 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2610 /* Auth plugin doesn't allow local authentication for this user name */
2613 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2615 } elseif ( function_exists( 'iconv' ) ) {
2616 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2617 # Check for this with iconv
2618 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2619 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2627 * Check if the given clear-text password matches the temporary password
2628 * sent by e-mail for password reset operations.
2629 * @return \type{\bool} True if matches, false otherwise
2631 function checkTemporaryPassword( $plaintext ) {
2632 return self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() );
2636 * Initialize (if necessary) and return a session token value
2637 * which can be used in edit forms to show that the user's
2638 * login credentials aren't being hijacked with a foreign form
2641 * @param $salt \twotypes{\string,\arrayof{\string}} Optional function-specific data for hashing
2642 * @return \type{\string} The new edit token
2644 function editToken( $salt = '' ) {
2645 if ( $this->isAnon() ) {
2646 return EDIT_TOKEN_SUFFIX
;
2648 if( !isset( $_SESSION['wsEditToken'] ) ) {
2649 $token = $this->generateToken();
2650 $_SESSION['wsEditToken'] = $token;
2652 $token = $_SESSION['wsEditToken'];
2654 if( is_array( $salt ) ) {
2655 $salt = implode( '|', $salt );
2657 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2662 * Generate a looking random token for various uses.
2664 * @param $salt \type{\string} Optional salt value
2665 * @return \type{\string} The new random token
2667 function generateToken( $salt = '' ) {
2668 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2669 return md5( $token . $salt );
2673 * Check given value against the token value stored in the session.
2674 * A match should confirm that the form was submitted from the
2675 * user's own login session, not a form submission from a third-party
2678 * @param $val \type{\string} Input value to compare
2679 * @param $salt \type{\string} Optional function-specific data for hashing
2680 * @return \type{\bool} Whether the token matches
2682 function matchEditToken( $val, $salt = '' ) {
2683 $sessionToken = $this->editToken( $salt );
2684 if ( $val != $sessionToken ) {
2685 wfDebug( "User::matchEditToken: broken session data\n" );
2687 return $val == $sessionToken;
2691 * Check given value against the token value stored in the session,
2692 * ignoring the suffix.
2694 * @param $val \type{\string} Input value to compare
2695 * @param $salt \type{\string} Optional function-specific data for hashing
2696 * @return \type{\bool} Whether the token matches
2698 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2699 $sessionToken = $this->editToken( $salt );
2700 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2704 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2705 * mail to the user's given address.
2707 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure.
2709 function sendConfirmationMail() {
2711 $expiration = null; // gets passed-by-ref and defined in next line.
2712 $token = $this->confirmationToken( $expiration );
2713 $url = $this->confirmationTokenUrl( $token );
2714 $invalidateURL = $this->invalidationTokenUrl( $token );
2715 $this->saveSettings();
2717 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2718 wfMsg( 'confirmemail_body',
2722 $wgLang->timeanddate( $expiration, false ),
2727 * Send an e-mail to this user's account. Does not check for
2728 * confirmed status or validity.
2730 * @param $subject \type{\string} Message subject
2731 * @param $body \type{\string} Message body
2732 * @param $from \type{\string} Optional From address; if unspecified, default $wgPasswordSender will be used
2733 * @param $replyto \type{\string} Reply-to address
2734 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure
2736 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2737 if( is_null( $from ) ) {
2738 global $wgPasswordSender;
2739 $from = $wgPasswordSender;
2742 $to = new MailAddress( $this );
2743 $sender = new MailAddress( $from );
2744 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2748 * Generate, store, and return a new e-mail confirmation code.
2749 * A hash (unsalted, since it's used as a key) is stored.
2751 * @note Call saveSettings() after calling this function to commit
2752 * this change to the database.
2754 * @param[out] &$expiration \type{\mixed} Accepts the expiration time
2755 * @return \type{\string} New token
2758 function confirmationToken( &$expiration ) {
2760 $expires = $now +
7 * 24 * 60 * 60;
2761 $expiration = wfTimestamp( TS_MW
, $expires );
2762 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2763 $hash = md5( $token );
2765 $this->mEmailToken
= $hash;
2766 $this->mEmailTokenExpires
= $expiration;
2771 * Return a URL the user can use to confirm their email address.
2772 * @param $token \type{\string} Accepts the email confirmation token
2773 * @return \type{\string} New token URL
2776 function confirmationTokenUrl( $token ) {
2777 return $this->getTokenUrl( 'ConfirmEmail', $token );
2780 * Return a URL the user can use to invalidate their email address.
2782 * @param $token \type{\string} Accepts the email confirmation token
2783 * @return \type{\string} New token URL
2786 function invalidationTokenUrl( $token ) {
2787 return $this->getTokenUrl( 'Invalidateemail', $token );
2791 * Internal function to format the e-mail validation/invalidation URLs.
2792 * This uses $wgArticlePath directly as a quickie hack to use the
2793 * hardcoded English names of the Special: pages, for ASCII safety.
2795 * @note Since these URLs get dropped directly into emails, using the
2796 * short English names avoids insanely long URL-encoded links, which
2797 * also sometimes can get corrupted in some browsers/mailers
2798 * (bug 6957 with Gmail and Internet Explorer).
2800 * @param $page \type{\string} Special page
2801 * @param $token \type{\string} Token
2802 * @return \type{\string} Formatted URL
2804 protected function getTokenUrl( $page, $token ) {
2805 global $wgArticlePath;
2809 "Special:$page/$token",
2814 * Mark the e-mail address confirmed.
2816 * @note Call saveSettings() after calling this function to commit the change.
2818 function confirmEmail() {
2819 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2824 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2825 * address if it was already confirmed.
2827 * @note Call saveSettings() after calling this function to commit the change.
2829 function invalidateEmail() {
2831 $this->mEmailToken
= null;
2832 $this->mEmailTokenExpires
= null;
2833 $this->setEmailAuthenticationTimestamp( null );
2838 * Set the e-mail authentication timestamp.
2839 * @param $timestamp \type{\string} TS_MW timestamp
2841 function setEmailAuthenticationTimestamp( $timestamp ) {
2843 $this->mEmailAuthenticated
= $timestamp;
2844 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2848 * Is this user allowed to send e-mails within limits of current
2849 * site configuration?
2850 * @return \type{\bool} True if allowed
2852 function canSendEmail() {
2853 $canSend = $this->isEmailConfirmed();
2854 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2859 * Is this user allowed to receive e-mails within limits of current
2860 * site configuration?
2861 * @return \type{\bool} True if allowed
2863 function canReceiveEmail() {
2864 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2868 * Is this user's e-mail address valid-looking and confirmed within
2869 * limits of the current site configuration?
2871 * @note If $wgEmailAuthentication is on, this may require the user to have
2872 * confirmed their address by returning a code or using a password
2873 * sent to the address from the wiki.
2875 * @return \type{\bool} True if confirmed
2877 function isEmailConfirmed() {
2878 global $wgEmailAuthentication;
2881 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2882 if( $this->isAnon() )
2884 if( !self
::isValidEmailAddr( $this->mEmail
) )
2886 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2895 * Check whether there is an outstanding request for e-mail confirmation.
2896 * @return \type{\bool} True if pending
2898 function isEmailConfirmationPending() {
2899 global $wgEmailAuthentication;
2900 return $wgEmailAuthentication &&
2901 !$this->isEmailConfirmed() &&
2902 $this->mEmailToken
&&
2903 $this->mEmailTokenExpires
> wfTimestamp();
2907 * Get the timestamp of account creation.
2909 * @return \twotypes{\string,\bool} string Timestamp of account creation, or false for
2910 * non-existent/anonymous user accounts.
2912 public function getRegistration() {
2913 return $this->mId
> 0
2914 ?
$this->mRegistration
2919 * Get the permissions associated with a given list of groups
2921 * @param $groups \type{\arrayof{\string}} List of internal group names
2922 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
2924 static function getGroupPermissions( $groups ) {
2925 global $wgGroupPermissions;
2927 foreach( $groups as $group ) {
2928 if( isset( $wgGroupPermissions[$group] ) ) {
2929 $rights = array_merge( $rights,
2930 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2937 * Get all the groups who have a given permission
2939 * @param $role \type{\string} Role to check
2940 * @return \type{\arrayof{\string}} List of internal group names with the given permission
2942 static function getGroupsWithPermission( $role ) {
2943 global $wgGroupPermissions;
2944 $allowedGroups = array();
2945 foreach ( $wgGroupPermissions as $group => $rights ) {
2946 if ( isset( $rights[$role] ) && $rights[$role] ) {
2947 $allowedGroups[] = $group;
2950 return $allowedGroups;
2954 * Get the localized descriptive name for a group, if it exists
2956 * @param $group \type{\string} Internal group name
2957 * @return \type{\string} Localized descriptive group name
2959 static function getGroupName( $group ) {
2960 global $wgMessageCache;
2961 $wgMessageCache->loadAllMessages();
2962 $key = "group-$group";
2963 $name = wfMsg( $key );
2964 return $name == '' ||
wfEmptyMsg( $key, $name )
2970 * Get the localized descriptive name for a member of a group, if it exists
2972 * @param $group \type{\string} Internal group name
2973 * @return \type{\string} Localized name for group member
2975 static function getGroupMember( $group ) {
2976 global $wgMessageCache;
2977 $wgMessageCache->loadAllMessages();
2978 $key = "group-$group-member";
2979 $name = wfMsg( $key );
2980 return $name == '' ||
wfEmptyMsg( $key, $name )
2986 * Return the set of defined explicit groups.
2987 * The implicit groups (by default *, 'user' and 'autoconfirmed')
2988 * are not included, as they are defined automatically, not in the database.
2989 * @return \type{\arrayof{\string}} Array of internal group names
2991 static function getAllGroups() {
2992 global $wgGroupPermissions;
2994 array_keys( $wgGroupPermissions ),
2995 self
::getImplicitGroups()
3000 * Get a list of all available permissions.
3001 * @return \type{\arrayof{\string}} Array of permission names
3003 static function getAllRights() {
3004 if ( self
::$mAllRights === false ) {
3005 global $wgAvailableRights;
3006 if ( count( $wgAvailableRights ) ) {
3007 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3009 self
::$mAllRights = self
::$mCoreRights;
3011 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3013 return self
::$mAllRights;
3017 * Get a list of implicit groups
3018 * @return \type{\arrayof{\string}} Array of internal group names
3020 public static function getImplicitGroups() {
3021 global $wgImplicitGroups;
3022 $groups = $wgImplicitGroups;
3023 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3028 * Get the title of a page describing a particular group
3030 * @param $group \type{\string} Internal group name
3031 * @return \twotypes{Title,\bool} Title of the page if it exists, false otherwise
3033 static function getGroupPage( $group ) {
3034 global $wgMessageCache;
3035 $wgMessageCache->loadAllMessages();
3036 $page = wfMsgForContent( 'grouppage-' . $group );
3037 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3038 $title = Title
::newFromText( $page );
3039 if( is_object( $title ) )
3046 * Create a link to the group in HTML, if available;
3047 * else return the group name.
3049 * @param $group \type{\string} Internal name of the group
3050 * @param $text \type{\string} The text of the link
3051 * @return \type{\string} HTML link to the group
3053 static function makeGroupLinkHTML( $group, $text = '' ) {
3055 $text = self
::getGroupName( $group );
3057 $title = self
::getGroupPage( $group );
3060 $sk = $wgUser->getSkin();
3061 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3068 * Create a link to the group in Wikitext, if available;
3069 * else return the group name.
3071 * @param $group \type{\string} Internal name of the group
3072 * @param $text \type{\string} The text of the link
3073 * @return \type{\string} Wikilink to the group
3075 static function makeGroupLinkWiki( $group, $text = '' ) {
3077 $text = self
::getGroupName( $group );
3079 $title = self
::getGroupPage( $group );
3081 $page = $title->getPrefixedText();
3082 return "[[$page|$text]]";
3089 * Increment the user's edit-count field.
3090 * Will have no effect for anonymous users.
3092 function incEditCount() {
3093 if( !$this->isAnon() ) {
3094 $dbw = wfGetDB( DB_MASTER
);
3095 $dbw->update( 'user',
3096 array( 'user_editcount=user_editcount+1' ),
3097 array( 'user_id' => $this->getId() ),
3100 // Lazy initialization check...
3101 if( $dbw->affectedRows() == 0 ) {
3102 // Pull from a slave to be less cruel to servers
3103 // Accuracy isn't the point anyway here
3104 $dbr = wfGetDB( DB_SLAVE
);
3105 $count = $dbr->selectField( 'revision',
3107 array( 'rev_user' => $this->getId() ),
3110 // Now here's a goddamn hack...
3111 if( $dbr !== $dbw ) {
3112 // If we actually have a slave server, the count is
3113 // at least one behind because the current transaction
3114 // has not been committed and replicated.
3117 // But if DB_SLAVE is selecting the master, then the
3118 // count we just read includes the revision that was
3119 // just added in the working transaction.
3122 $dbw->update( 'user',
3123 array( 'user_editcount' => $count ),
3124 array( 'user_id' => $this->getId() ),
3128 // edit count in user cache too
3129 $this->invalidateCache();
3133 * Get the description of a given right
3135 * @param $right \type{\string} Right to query
3136 * @return \type{\string} Localized description of the right
3138 static function getRightDescription( $right ) {
3139 global $wgMessageCache;
3140 $wgMessageCache->loadAllMessages();
3141 $key = "right-$right";
3142 $name = wfMsg( $key );
3143 return $name == '' ||
wfEmptyMsg( $key, $name )
3149 * Make an old-style password hash
3151 * @param $password \type{\string} Plain-text password
3152 * @param $userId \type{\string} %User ID
3153 * @return \type{\string} Password hash
3155 static function oldCrypt( $password, $userId ) {
3156 global $wgPasswordSalt;
3157 if ( $wgPasswordSalt ) {
3158 return md5( $userId . '-' . md5( $password ) );
3160 return md5( $password );
3165 * Make a new-style password hash
3167 * @param $password \type{\string} Plain-text password
3168 * @param $salt \type{\string} Optional salt, may be random or the user ID.
3169 * If unspecified or false, will generate one automatically
3170 * @return \type{\string} Password hash
3172 static function crypt( $password, $salt = false ) {
3173 global $wgPasswordSalt;
3175 if($wgPasswordSalt) {
3176 if ( $salt === false ) {
3177 $salt = substr( wfGenerateToken(), 0, 8 );
3179 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3181 return ':A:' . md5( $password);
3186 * Compare a password hash with a plain-text password. Requires the user
3187 * ID if there's a chance that the hash is an old-style hash.
3189 * @param $hash \type{\string} Password hash
3190 * @param $password \type{\string} Plain-text password to compare
3191 * @param $userId \type{\string} %User ID for old-style password salt
3192 * @return \type{\bool} True if matches, false otherwise
3194 static function comparePasswords( $hash, $password, $userId = false ) {
3196 $type = substr( $hash, 0, 3 );
3197 if ( $type == ':A:' ) {
3199 return md5( $password ) === substr( $hash, 3 );
3200 } elseif ( $type == ':B:' ) {
3202 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3203 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3206 return self
::oldCrypt( $password, $userId ) === $hash;
3211 * Add a newuser log entry for this user
3212 * @param bool $byEmail, account made by email?
3214 public function addNewUserLogEntry( $byEmail = false ) {
3215 global $wgUser, $wgContLang, $wgNewUserLog;
3216 if( empty($wgNewUserLog) ) {
3217 return true; // disabled
3219 $talk = $wgContLang->getFormattedNsText( NS_TALK
);
3220 if( $this->getName() == $wgUser->getName() ) {
3224 $action = 'create2';
3225 $message = $byEmail ?
wfMsgForContent( 'newuserlog-byemail' ) : '';
3227 $log = new LogPage( 'newusers' );
3228 $log->addEntry( $action, $this->getUserPage(), $message, array( $this->getId() ) );
3233 * Add an autocreate newuser log entry for this user
3234 * Used by things like CentralAuth and perhaps other authplugins.
3236 public function addNewUserLogEntryAutoCreate() {
3237 global $wgNewUserLog;
3238 if( empty($wgNewUserLog) ) {
3239 return true; // disabled
3241 $log = new LogPage( 'newusers', false );
3242 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3246 // Restrictions-related block
3248 public function loadRestrictions() {
3249 if( is_null( $this->mRestrictions
) )
3250 $this->mRestrictions
= UserRestriction
::fetchForUser( $this->isLoggedIn() ?
3251 intval( $this->getId() ) : $this->getName() );
3254 public function getRestrictions() {
3255 $this->loadRestrictions();
3257 // Check for expired restrictions. Recache if found expired ones
3258 static $checked = false;
3261 $old = $this->mRestrictions
;
3262 $this->mRestrictions
= array();
3263 foreach( $old as $restriction ) {
3264 if( $restriction->deleteIfExpired() )
3267 $this->mRestrictions
[] = $restriction;
3270 $this->saveToCache();
3274 return $this->mRestrictions
;
3277 public function getRestrictionForPage( Title
$page ) {
3278 foreach( $this->getRestrictions() as $r ) {
3279 if( $r->isPage() && $page->equals( $r->getPage() ) )
3285 public function getRestrictionForNamespace( $nsid ) {
3286 foreach( $this->getRestrictions() as $r ) {
3287 if( $r->isNamespace() && $r->getNamespace() == $nsid )