3 * Implements the User class for the %MediaWiki software.
8 * \type{\int} Number of characters in user_token field.
11 define( 'USER_TOKEN_LENGTH', 32 );
14 * \type{\int} Serialized record version.
17 define( 'MW_USER_VERSION', 6 );
20 * \type{\string} Some punctuation to prevent editing from broken text-mangling proxies.
23 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
26 * Thrown by User::setPassword() on error.
29 class PasswordError
extends MWException
{
34 * The User object encapsulates all of the user-specific settings (user_id,
35 * name, rights, password, email address, options, last login time). Client
36 * classes use the getXXX() functions to access these fields. These functions
37 * do all the work of determining whether the user is logged in,
38 * whether the requested option can be satisfied from cookies or
39 * whether a database query is needed. Most of the settings needed
40 * for rendering normal pages are set in the cookie to minimize use
46 * \type{\arrayof{\string}} A list of default user toggles, i.e., boolean user
47 * preferences that are displayed by Special:Preferences as checkboxes.
48 * This list can be extended via the UserToggles hook or by
49 * $wgContLang::getExtraUserToggles().
52 public static $mToggles = array(
62 'editsectiononrightclick',
74 'enotifwatchlistpages',
75 'enotifusertalkpages',
78 'shownumberswatching',
97 * \type{\arrayof{\string}} List of member variables which are saved to the
98 * shared cache (memcached). Any operation which changes the
99 * corresponding database fields must call a cache-clearing function.
102 static $mCacheVars = array(
114 'mEmailAuthenticated',
116 'mEmailTokenExpires',
124 * \type{\arrayof{\string}} Core rights.
125 * Each of these should have a corresponding message of the form
129 static $mCoreRights = array(
171 * \type{\string} Cached results of getAllRights()
173 static $mAllRights = false;
175 /** @name Cache variables */
177 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
178 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
179 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
183 * \type{\bool} Whether the cache variables have been loaded.
188 * \type{\string} Initialization data source if mDataLoaded==false. May be one of:
189 * - 'defaults' anonymous user initialised from class defaults
190 * - 'name' initialise from mName
191 * - 'id' initialise from mId
192 * - 'session' log in from cookies or session if possible
194 * Use the User::newFrom*() family of functions to set this.
198 /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
200 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
201 $mBlockreason, $mBlock, $mEffectiveGroups;
205 * Lightweight constructor for an anonymous user.
206 * Use the User::newFrom* factory functions for other kinds of users.
210 * @see newFromConfirmationCode()
211 * @see newFromSession()
215 $this->clearInstanceCache( 'defaults' );
219 * Load the user table data for this object from the source given by mFrom.
222 if ( $this->mDataLoaded
) {
225 wfProfileIn( __METHOD__
);
227 # Set it now to avoid infinite recursion in accessors
228 $this->mDataLoaded
= true;
230 switch ( $this->mFrom
) {
232 $this->loadDefaults();
235 $this->mId
= self
::idFromName( $this->mName
);
237 # Nonexistent user placeholder object
238 $this->loadDefaults( $this->mName
);
247 $this->loadFromSession();
250 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
252 wfProfileOut( __METHOD__
);
256 * Load user table data, given mId has already been set.
257 * @return \type{\bool} false if the ID does not exist, true otherwise
260 function loadFromId() {
262 if ( $this->mId
== 0 ) {
263 $this->loadDefaults();
268 $key = wfMemcKey( 'user', 'id', $this->mId
);
269 $data = $wgMemc->get( $key );
270 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
271 # Object is expired, load from DB
276 wfDebug( "Cache miss for user {$this->mId}\n" );
278 if ( !$this->loadFromDatabase() ) {
279 # Can't load from ID, user is anonymous
282 $this->saveToCache();
284 wfDebug( "Got user {$this->mId} from cache\n" );
286 foreach ( self
::$mCacheVars as $name ) {
287 $this->$name = $data[$name];
294 * Save user data to the shared cache
296 function saveToCache() {
299 if ( $this->isAnon() ) {
300 // Anonymous users are uncached
304 foreach ( self
::$mCacheVars as $name ) {
305 $data[$name] = $this->$name;
307 $data['mVersion'] = MW_USER_VERSION
;
308 $key = wfMemcKey( 'user', 'id', $this->mId
);
310 $wgMemc->set( $key, $data );
314 /** @name newFrom*() static factory methods */
318 * Static factory method for creation from username.
320 * This is slightly less efficient than newFromId(), so use newFromId() if
321 * you have both an ID and a name handy.
323 * @param $name \type{\string} Username, validated by Title::newFromText()
324 * @param $validate \type{\mixed} Validate username. Takes the same parameters as
325 * User::getCanonicalName(), except that true is accepted as an alias
326 * for 'valid', for BC.
328 * @return \type{User} The User object, or null if the username is invalid. If the
329 * username is not present in the database, the result will be a user object
330 * with a name, zero user ID and default settings.
332 static function newFromName( $name, $validate = 'valid' ) {
333 if ( $validate === true ) {
336 $name = self
::getCanonicalName( $name, $validate );
337 if ( $name === false ) {
340 # Create unloaded user object
349 * Static factory method for creation from a given user ID.
351 * @param $id \type{\int} Valid user ID
352 * @return \type{User} The corresponding User object
354 static function newFromId( $id ) {
362 * Factory method to fetch whichever user has a given email confirmation code.
363 * This code is generated when an account is created or its e-mail address
366 * If the code is invalid or has expired, returns NULL.
368 * @param $code \type{\string} Confirmation code
369 * @return \type{User}
371 static function newFromConfirmationCode( $code ) {
372 $dbr = wfGetDB( DB_SLAVE
);
373 $id = $dbr->selectField( 'user', 'user_id', array(
374 'user_email_token' => md5( $code ),
375 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
377 if( $id !== false ) {
378 return User
::newFromId( $id );
385 * Create a new user object using data from session or cookies. If the
386 * login credentials are invalid, the result is an anonymous user.
388 * @return \type{User}
390 static function newFromSession() {
392 $user->mFrom
= 'session';
397 * Create a new user object from a user row.
398 * The row should have all fields from the user table in it.
399 * @param $row array A row from the user table
400 * @return \type{User}
402 static function newFromRow( $row ) {
404 $user->loadFromRow( $row );
412 * Get the username corresponding to a given user ID
413 * @param $id \type{\int} %User ID
414 * @return \type{\string} The corresponding username
416 static function whoIs( $id ) {
417 $dbr = wfGetDB( DB_SLAVE
);
418 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
422 * Get the real name of a user given their user ID
424 * @param $id \type{\int} %User ID
425 * @return \type{\string} The corresponding user's real name
427 static function whoIsReal( $id ) {
428 $dbr = wfGetDB( DB_SLAVE
);
429 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
433 * Get database id given a user name
434 * @param $name \type{\string} Username
435 * @return \twotypes{\int,\null} The corresponding user's ID, or null if user is nonexistent
438 static function idFromName( $name ) {
439 $nt = Title
::newFromText( $name );
440 if( is_null( $nt ) ) {
444 $dbr = wfGetDB( DB_SLAVE
);
445 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
447 if ( $s === false ) {
455 * Does the string match an anonymous IPv4 address?
457 * This function exists for username validation, in order to reject
458 * usernames which are similar in form to IP addresses. Strings such
459 * as 300.300.300.300 will return true because it looks like an IP
460 * address, despite not being strictly valid.
462 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
463 * address because the usemod software would "cloak" anonymous IP
464 * addresses like this, if we allowed accounts like this to be created
465 * new users could get the old edits of these anonymous users.
467 * @param $name \type{\string} String to match
468 * @return \type{\bool} True or false
470 static function isIP( $name ) {
471 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
475 * Is the input a valid username?
477 * Checks if the input is a valid username, we don't want an empty string,
478 * an IP address, anything that containins slashes (would mess up subpages),
479 * is longer than the maximum allowed username size or doesn't begin with
482 * @param $name \type{\string} String to match
483 * @return \type{\bool} True or false
485 static function isValidUserName( $name ) {
486 global $wgContLang, $wgMaxNameChars;
489 || User
::isIP( $name )
490 ||
strpos( $name, '/' ) !== false
491 ||
strlen( $name ) > $wgMaxNameChars
492 ||
$name != $wgContLang->ucfirst( $name ) ) {
493 wfDebugLog( 'username', __METHOD__
.
494 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
498 // Ensure that the name can't be misresolved as a different title,
499 // such as with extra namespace keys at the start.
500 $parsed = Title
::newFromText( $name );
501 if( is_null( $parsed )
502 ||
$parsed->getNamespace()
503 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
504 wfDebugLog( 'username', __METHOD__
.
505 ": '$name' invalid due to ambiguous prefixes" );
509 // Check an additional blacklist of troublemaker characters.
510 // Should these be merged into the title char list?
511 $unicodeBlacklist = '/[' .
512 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
513 '\x{00a0}' . # non-breaking space
514 '\x{2000}-\x{200f}' . # various whitespace
515 '\x{2028}-\x{202f}' . # breaks and control chars
516 '\x{3000}' . # ideographic space
517 '\x{e000}-\x{f8ff}' . # private use
519 if( preg_match( $unicodeBlacklist, $name ) ) {
520 wfDebugLog( 'username', __METHOD__
.
521 ": '$name' invalid due to blacklisted characters" );
529 * Usernames which fail to pass this function will be blocked
530 * from user login and new account registrations, but may be used
531 * internally by batch processes.
533 * If an account already exists in this form, login will be blocked
534 * by a failure to pass this function.
536 * @param $name \type{\string} String to match
537 * @return \type{\bool} True or false
539 static function isUsableName( $name ) {
540 global $wgReservedUsernames;
541 // Must be a valid username, obviously ;)
542 if ( !self
::isValidUserName( $name ) ) {
546 static $reservedUsernames = false;
547 if ( !$reservedUsernames ) {
548 $reservedUsernames = $wgReservedUsernames;
549 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
552 // Certain names may be reserved for batch processes.
553 foreach ( $reservedUsernames as $reserved ) {
554 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
555 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
557 if ( $reserved == $name ) {
565 * Usernames which fail to pass this function will be blocked
566 * from new account registrations, but may be used internally
567 * either by batch processes or by user accounts which have
568 * already been created.
570 * Additional character blacklisting may be added here
571 * rather than in isValidUserName() to avoid disrupting
574 * @param $name \type{\string} String to match
575 * @return \type{\bool} True or false
577 static function isCreatableName( $name ) {
579 self
::isUsableName( $name ) &&
581 // Registration-time character blacklisting...
582 strpos( $name, '@' ) === false;
586 * Is the input a valid password for this user?
588 * @param $password \type{\string} Desired password
589 * @return \type{\bool} True or false
591 function isValidPassword( $password ) {
592 global $wgMinimalPasswordLength, $wgContLang;
595 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
597 if( $result === false )
600 // Password needs to be long enough, and can't be the same as the username
601 return strlen( $password ) >= $wgMinimalPasswordLength
602 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
606 * Does a string look like an e-mail address?
608 * There used to be a regular expression here, it got removed because it
609 * rejected valid addresses. Actually just check if there is '@' somewhere
610 * in the given address.
612 * @todo Check for RFC 2822 compilance (bug 959)
614 * @param $addr \type{\string} E-mail address
615 * @return \type{\bool} True or false
617 public static function isValidEmailAddr( $addr ) {
619 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
623 return strpos( $addr, '@' ) !== false;
627 * Given unvalidated user input, return a canonical username, or false if
628 * the username is invalid.
629 * @param $name \type{\string} User input
630 * @param $validate \twotypes{\string,\bool} Type of validation to use:
631 * - false No validation
632 * - 'valid' Valid for batch processes
633 * - 'usable' Valid for batch processes and login
634 * - 'creatable' Valid for batch processes, login and account creation
636 static function getCanonicalName( $name, $validate = 'valid' ) {
637 # Force usernames to capital
639 $name = $wgContLang->ucfirst( $name );
641 # Reject names containing '#'; these will be cleaned up
642 # with title normalisation, but then it's too late to
644 if( strpos( $name, '#' ) !== false )
647 # Clean up name according to title rules
648 $t = Title
::newFromText( $name );
649 if( is_null( $t ) ) {
653 # Reject various classes of invalid names
654 $name = $t->getText();
656 $name = $wgAuth->getCanonicalName( $t->getText() );
658 switch ( $validate ) {
662 if ( !User
::isValidUserName( $name ) ) {
667 if ( !User
::isUsableName( $name ) ) {
672 if ( !User
::isCreatableName( $name ) ) {
677 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
683 * Count the number of edits of a user
684 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
686 * @param $uid \type{\int} %User ID to check
687 * @return \type{\int} The user's edit count
689 static function edits( $uid ) {
690 wfProfileIn( __METHOD__
);
691 $dbr = wfGetDB( DB_SLAVE
);
692 // check if the user_editcount field has been initialized
693 $field = $dbr->selectField(
694 'user', 'user_editcount',
695 array( 'user_id' => $uid ),
699 if( $field === null ) { // it has not been initialized. do so.
700 $dbw = wfGetDB( DB_MASTER
);
701 $count = $dbr->selectField(
702 'revision', 'count(*)',
703 array( 'rev_user' => $uid ),
708 array( 'user_editcount' => $count ),
709 array( 'user_id' => $uid ),
715 wfProfileOut( __METHOD__
);
720 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
721 * @todo hash random numbers to improve security, like generateToken()
723 * @return \type{\string} New random password
725 static function randomPassword() {
726 global $wgMinimalPasswordLength;
727 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
728 $l = strlen( $pwchars ) - 1;
730 $pwlength = max( 7, $wgMinimalPasswordLength );
731 $digit = mt_rand(0, $pwlength - 1);
733 for ( $i = 0; $i < $pwlength; $i++
) {
734 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
740 * Set cached properties to default.
742 * @note This no longer clears uncached lazy-initialised properties;
743 * the constructor does that instead.
746 function loadDefaults( $name = false ) {
747 wfProfileIn( __METHOD__
);
749 global $wgCookiePrefix;
752 $this->mName
= $name;
753 $this->mRealName
= '';
754 $this->mPassword
= $this->mNewpassword
= '';
755 $this->mNewpassTime
= null;
757 $this->mOptions
= null; # Defer init
759 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
760 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
762 $this->mTouched
= '0'; # Allow any pages to be cached
765 $this->setToken(); # Random
766 $this->mEmailAuthenticated
= null;
767 $this->mEmailToken
= '';
768 $this->mEmailTokenExpires
= null;
769 $this->mRegistration
= wfTimestamp( TS_MW
);
770 $this->mGroups
= array();
772 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
774 wfProfileOut( __METHOD__
);
778 * @deprecated Use wfSetupSession().
780 function SetupSession() {
781 wfDeprecated( __METHOD__
);
786 * Load user data from the session or login cookie. If there are no valid
787 * credentials, initialises the user as an anonymous user.
788 * @return \type{\bool} True if the user is logged in, false otherwise.
790 private function loadFromSession() {
791 global $wgMemc, $wgCookiePrefix;
794 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
795 if ( $result !== null ) {
799 if ( isset( $_SESSION['wsUserID'] ) ) {
800 if ( 0 != $_SESSION['wsUserID'] ) {
801 $sId = $_SESSION['wsUserID'];
803 $this->loadDefaults();
806 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
807 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
808 $_SESSION['wsUserID'] = $sId;
810 $this->loadDefaults();
813 if ( isset( $_SESSION['wsUserName'] ) ) {
814 $sName = $_SESSION['wsUserName'];
815 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
816 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
817 $_SESSION['wsUserName'] = $sName;
819 $this->loadDefaults();
823 $passwordCorrect = FALSE;
825 if ( !$this->loadFromId() ) {
826 # Not a valid ID, loadFromId has switched the object to anon for us
830 if ( isset( $_SESSION['wsToken'] ) ) {
831 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
833 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
834 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
837 # No session or persistent login cookie
838 $this->loadDefaults();
842 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
843 $_SESSION['wsToken'] = $this->mToken
;
844 wfDebug( "Logged in from $from\n" );
847 # Invalid credentials
848 wfDebug( "Can't log in from $from, invalid credentials\n" );
849 $this->loadDefaults();
855 * Load user and user_group data from the database.
856 * $this::mId must be set, this is how the user is identified.
858 * @return \type{\bool} True if the user exists, false if the user is anonymous
861 function loadFromDatabase() {
863 $this->mId
= intval( $this->mId
);
865 /** Anonymous user */
867 $this->loadDefaults();
871 $dbr = wfGetDB( DB_MASTER
);
872 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
874 if ( $s !== false ) {
875 # Initialise user table data
876 $this->loadFromRow( $s );
877 $this->mGroups
= null; // deferred
878 $this->getEditCount(); // revalidation for nulls
883 $this->loadDefaults();
889 * Initialize this object from a row from the user table.
891 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
893 function loadFromRow( $row ) {
894 $this->mDataLoaded
= true;
896 if ( isset( $row->user_id
) ) {
897 $this->mId
= $row->user_id
;
899 $this->mName
= $row->user_name
;
900 $this->mRealName
= $row->user_real_name
;
901 $this->mPassword
= $row->user_password
;
902 $this->mNewpassword
= $row->user_newpassword
;
903 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
904 $this->mEmail
= $row->user_email
;
905 $this->decodeOptions( $row->user_options
);
906 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
907 $this->mToken
= $row->user_token
;
908 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
909 $this->mEmailToken
= $row->user_email_token
;
910 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
911 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
912 $this->mEditCount
= $row->user_editcount
;
916 * Load the groups from the database if they aren't already loaded.
919 function loadGroups() {
920 if ( is_null( $this->mGroups
) ) {
921 $dbr = wfGetDB( DB_MASTER
);
922 $res = $dbr->select( 'user_groups',
924 array( 'ug_user' => $this->mId
),
926 $this->mGroups
= array();
927 while( $row = $dbr->fetchObject( $res ) ) {
928 $this->mGroups
[] = $row->ug_group
;
934 * Clear various cached data stored in this object.
935 * @param $reloadFrom \type{\string} Reload user and user_groups table data from a
936 * given source. May be "name", "id", "defaults", "session", or false for
939 function clearInstanceCache( $reloadFrom = false ) {
940 $this->mNewtalk
= -1;
941 $this->mDatePreference
= null;
942 $this->mBlockedby
= -1; # Unset
943 $this->mHash
= false;
945 $this->mRights
= null;
946 $this->mEffectiveGroups
= null;
949 $this->mDataLoaded
= false;
950 $this->mFrom
= $reloadFrom;
955 * Combine the language default options with any site-specific options
956 * and add the default language variants.
958 * @return \type{\arrayof{\string}} Array of options
960 static function getDefaultOptions() {
961 global $wgNamespacesToBeSearchedDefault;
963 * Site defaults will override the global/language defaults
965 global $wgDefaultUserOptions, $wgContLang;
966 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
969 * default language setting
971 $variant = $wgContLang->getPreferredVariant( false );
972 $defOpt['variant'] = $variant;
973 $defOpt['language'] = $variant;
975 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
976 $defOpt['searchNs'.$nsnum] = $val;
982 * Get a given default option value.
984 * @param $opt \type{\string} Name of option to retrieve
985 * @return \type{\string} Default option value
987 public static function getDefaultOption( $opt ) {
988 $defOpts = self
::getDefaultOptions();
989 if( isset( $defOpts[$opt] ) ) {
990 return $defOpts[$opt];
997 * Get a list of user toggle names
998 * @return \type{\arrayof{\string}} Array of user toggle names
1000 static function getToggles() {
1002 $extraToggles = array();
1003 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1004 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1009 * Get blocking information
1011 * @param $bFromSlave \type{\bool} Whether to check the slave database first. To
1012 * improve performance, non-critical checks are done
1013 * against slaves. Check when actually saving should be
1014 * done against master.
1016 function getBlockedStatus( $bFromSlave = true ) {
1017 global $wgEnableSorbs, $wgProxyWhitelist;
1019 if ( -1 != $this->mBlockedby
) {
1020 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1024 wfProfileIn( __METHOD__
);
1025 wfDebug( __METHOD__
.": checking...\n" );
1027 // Initialize data...
1028 // Otherwise something ends up stomping on $this->mBlockedby when
1029 // things get lazy-loaded later, causing false positive block hits
1030 // due to -1 !== 0. Probably session-related... Nothing should be
1031 // overwriting mBlockedby, surely?
1034 $this->mBlockedby
= 0;
1035 $this->mHideName
= 0;
1038 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1039 # Exempt from all types of IP-block
1044 $this->mBlock
= new Block();
1045 $this->mBlock
->fromMaster( !$bFromSlave );
1046 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1047 wfDebug( __METHOD__
.": Found block.\n" );
1048 $this->mBlockedby
= $this->mBlock
->mBy
;
1049 $this->mBlockreason
= $this->mBlock
->mReason
;
1050 $this->mHideName
= $this->mBlock
->mHideName
;
1051 if ( $this->isLoggedIn() ) {
1052 $this->spreadBlock();
1055 $this->mBlock
= null;
1056 wfDebug( __METHOD__
.": No block.\n" );
1060 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1062 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1063 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1064 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1068 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1069 if ( $this->inSorbsBlacklist( $ip ) ) {
1070 $this->mBlockedby
= wfMsg( 'sorbs' );
1071 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1077 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1079 wfProfileOut( __METHOD__
);
1083 * Whether the given IP is in the SORBS blacklist.
1085 * @param $ip \type{\string} IP to check
1086 * @return \type{\bool} True if blacklisted
1088 function inSorbsBlacklist( $ip ) {
1089 global $wgEnableSorbs, $wgSorbsUrl;
1091 return $wgEnableSorbs &&
1092 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1096 * Whether the given IP is in a given DNS blacklist.
1098 * @param $ip \type{\string} IP to check
1099 * @param $base \type{\string} URL of the DNS blacklist
1100 * @return \type{\bool} True if blacklisted
1102 function inDnsBlacklist( $ip, $base ) {
1103 wfProfileIn( __METHOD__
);
1109 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
1111 for ( $i=4; $i>=1; $i-- ) {
1112 $host .= $m[$i] . '.';
1117 $ipList = gethostbynamel( $host );
1120 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1123 wfDebug( "Requested $host, not found in $base.\n" );
1127 wfProfileOut( __METHOD__
);
1132 * Is this user subject to rate limiting?
1134 * @return \type{\bool} True if rate limited
1136 public function isPingLimitable() {
1137 global $wgRateLimitsExcludedGroups;
1138 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1139 // Deprecated, but kept for backwards-compatibility config
1142 return !$this->isAllowed('noratelimit');
1146 * Primitive rate limits: enforce maximum actions per time period
1147 * to put a brake on flooding.
1149 * @note When using a shared cache like memcached, IP-address
1150 * last-hit counters will be shared across wikis.
1152 * @param $action \type{\string} Action to enforce; 'edit' if unspecified
1153 * @return \type{\bool} True if a rate limiter was tripped
1155 function pingLimiter( $action='edit' ) {
1157 # Call the 'PingLimiter' hook
1159 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1163 global $wgRateLimits;
1164 if( !isset( $wgRateLimits[$action] ) ) {
1168 # Some groups shouldn't trigger the ping limiter, ever
1169 if( !$this->isPingLimitable() )
1172 global $wgMemc, $wgRateLimitLog;
1173 wfProfileIn( __METHOD__
);
1175 $limits = $wgRateLimits[$action];
1177 $id = $this->getId();
1181 if( isset( $limits['anon'] ) && $id == 0 ) {
1182 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1185 if( isset( $limits['user'] ) && $id != 0 ) {
1186 $userLimit = $limits['user'];
1188 if( $this->isNewbie() ) {
1189 if( isset( $limits['newbie'] ) && $id != 0 ) {
1190 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1192 if( isset( $limits['ip'] ) ) {
1193 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1196 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1197 $subnet = $matches[1];
1198 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1201 // Check for group-specific permissions
1202 // If more than one group applies, use the group with the highest limit
1203 foreach ( $this->getGroups() as $group ) {
1204 if ( isset( $limits[$group] ) ) {
1205 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1206 $userLimit = $limits[$group];
1210 // Set the user limit key
1211 if ( $userLimit !== false ) {
1212 wfDebug( __METHOD__
.": effective user limit: $userLimit\n" );
1213 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1217 foreach( $keys as $key => $limit ) {
1218 list( $max, $period ) = $limit;
1219 $summary = "(limit $max in {$period}s)";
1220 $count = $wgMemc->get( $key );
1222 if( $count > $max ) {
1223 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1224 if( $wgRateLimitLog ) {
1225 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1229 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1232 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1233 $wgMemc->add( $key, 1, intval( $period ) );
1235 $wgMemc->incr( $key );
1238 wfProfileOut( __METHOD__
);
1243 * Check if user is blocked
1245 * @param $bFromSlave \type{\bool} Whether to check the slave database instead of the master
1246 * @return \type{\bool} True if blocked, false otherwise
1248 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1249 wfDebug( "User::isBlocked: enter\n" );
1250 $this->getBlockedStatus( $bFromSlave );
1251 return $this->mBlockedby
!== 0;
1255 * Check if user is blocked from editing a particular article
1257 * @param $title \type{\string} Title to check
1258 * @param $bFromSlave \type{\bool} Whether to check the slave database instead of the master
1259 * @return \type{\bool} True if blocked, false otherwise
1261 function isBlockedFrom( $title, $bFromSlave = false ) {
1262 global $wgBlockAllowsUTEdit;
1263 wfProfileIn( __METHOD__
);
1264 wfDebug( __METHOD__
.": enter\n" );
1266 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1267 $blocked = $this->isBlocked( $bFromSlave );
1268 # If a user's name is suppressed, they cannot make edits anywhere
1269 if ( !$this->mHideName
&& $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1270 $title->getNamespace() == NS_USER_TALK
) {
1272 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1274 wfProfileOut( __METHOD__
);
1279 * If user is blocked, return the name of the user who placed the block
1280 * @return \type{\string} name of blocker
1282 function blockedBy() {
1283 $this->getBlockedStatus();
1284 return $this->mBlockedby
;
1288 * If user is blocked, return the specified reason for the block
1289 * @return \type{\string} Blocking reason
1291 function blockedFor() {
1292 $this->getBlockedStatus();
1293 return $this->mBlockreason
;
1297 * Get the user's ID.
1298 * @return \type{\int} The user's ID; 0 if the user is anonymous or nonexistent
1301 if( $this->mId
=== null and $this->mName
!== null
1302 and User
::isIP( $this->mName
) ) {
1303 // Special case, we know the user is anonymous
1305 } elseif( $this->mId
=== null ) {
1306 // Don't load if this was initialized from an ID
1313 * Set the user and reload all fields according to a given ID
1314 * @param $v \type{\int} %User ID to reload
1316 function setId( $v ) {
1318 $this->clearInstanceCache( 'id' );
1322 * Get the user name, or the IP of an anonymous user
1323 * @return \type{\string} User's name or IP address
1325 function getName() {
1326 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1327 # Special case optimisation
1328 return $this->mName
;
1331 if ( $this->mName
=== false ) {
1333 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1335 return $this->mName
;
1340 * Set the user name.
1342 * This does not reload fields from the database according to the given
1343 * name. Rather, it is used to create a temporary "nonexistent user" for
1344 * later addition to the database. It can also be used to set the IP
1345 * address for an anonymous user to something other than the current
1348 * @note User::newFromName() has rougly the same function, when the named user
1350 * @param $str \type{\string} New user name to set
1352 function setName( $str ) {
1354 $this->mName
= $str;
1358 * Get the user's name escaped by underscores.
1359 * @return \type{\string} Username escaped by underscores
1361 function getTitleKey() {
1362 return str_replace( ' ', '_', $this->getName() );
1366 * Check if the user has new messages.
1367 * @return \type{\bool} True if the user has new messages
1369 function getNewtalk() {
1372 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1373 if( $this->mNewtalk
=== -1 ) {
1374 $this->mNewtalk
= false; # reset talk page status
1376 # Check memcached separately for anons, who have no
1377 # entire User object stored in there.
1380 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1381 $newtalk = $wgMemc->get( $key );
1382 if( strval( $newtalk ) !== '' ) {
1383 $this->mNewtalk
= (bool)$newtalk;
1385 // Since we are caching this, make sure it is up to date by getting it
1387 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1388 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1391 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1395 return (bool)$this->mNewtalk
;
1399 * Return the talk page(s) this user has new messages on.
1400 * @return \type{\arrayof{\string}} Array of page URLs
1402 function getNewMessageLinks() {
1404 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1407 if (!$this->getNewtalk())
1409 $up = $this->getUserPage();
1410 $utp = $up->getTalkPage();
1411 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1416 * Internal uncached check for new messages
1419 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1420 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1421 * @param $fromMaster \type{\bool} true to fetch from the master, false for a slave
1422 * @return \type{\bool} True if the user has new messages
1425 function checkNewtalk( $field, $id, $fromMaster = false ) {
1426 if ( $fromMaster ) {
1427 $db = wfGetDB( DB_MASTER
);
1429 $db = wfGetDB( DB_SLAVE
);
1431 $ok = $db->selectField( 'user_newtalk', $field,
1432 array( $field => $id ), __METHOD__
);
1433 return $ok !== false;
1437 * Add or update the new messages flag
1438 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1439 * @param $id \twotypes{string,\int} User's IP address for anonymous users, %User ID otherwise
1440 * @return \type{\bool} True if successful, false otherwise
1443 function updateNewtalk( $field, $id ) {
1444 $dbw = wfGetDB( DB_MASTER
);
1445 $dbw->insert( 'user_newtalk',
1446 array( $field => $id ),
1449 if ( $dbw->affectedRows() ) {
1450 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1453 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1459 * Clear the new messages flag for the given user
1460 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1461 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1462 * @return \type{\bool} True if successful, false otherwise
1465 function deleteNewtalk( $field, $id ) {
1466 $dbw = wfGetDB( DB_MASTER
);
1467 $dbw->delete( 'user_newtalk',
1468 array( $field => $id ),
1470 if ( $dbw->affectedRows() ) {
1471 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1474 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1480 * Update the 'You have new messages!' status.
1481 * @param $val \type{\bool} Whether the user has new messages
1483 function setNewtalk( $val ) {
1484 if( wfReadOnly() ) {
1489 $this->mNewtalk
= $val;
1491 if( $this->isAnon() ) {
1493 $id = $this->getName();
1496 $id = $this->getId();
1501 $changed = $this->updateNewtalk( $field, $id );
1503 $changed = $this->deleteNewtalk( $field, $id );
1506 if( $this->isAnon() ) {
1507 // Anons have a separate memcached space, since
1508 // user records aren't kept for them.
1509 $key = wfMemcKey( 'newtalk', 'ip', $id );
1510 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1513 $this->invalidateCache();
1518 * Generate a current or new-future timestamp to be stored in the
1519 * user_touched field when we update things.
1520 * @return \type{\string} Timestamp in TS_MW format
1522 private static function newTouchedTimestamp() {
1523 global $wgClockSkewFudge;
1524 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1528 * Clear user data from memcached.
1529 * Use after applying fun updates to the database; caller's
1530 * responsibility to update user_touched if appropriate.
1532 * Called implicitly from invalidateCache() and saveSettings().
1534 private function clearSharedCache() {
1537 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1542 * Immediately touch the user data cache for this account.
1543 * Updates user_touched field, and removes account data from memcached
1544 * for reload on the next hit.
1546 function invalidateCache() {
1549 $this->mTouched
= self
::newTouchedTimestamp();
1551 $dbw = wfGetDB( DB_MASTER
);
1552 $dbw->update( 'user',
1553 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1554 array( 'user_id' => $this->mId
),
1557 $this->clearSharedCache();
1562 * Validate the cache for this account.
1563 * @param $timestamp \type{\string} A timestamp in TS_MW format
1565 function validateCache( $timestamp ) {
1567 return ($timestamp >= $this->mTouched
);
1571 * Set the password and reset the random token.
1572 * Calls through to authentication plugin if necessary;
1573 * will have no effect if the auth plugin refuses to
1574 * pass the change through or if the legal password
1577 * As a special case, setting the password to null
1578 * wipes it, so the account cannot be logged in until
1579 * a new password is set, for instance via e-mail.
1581 * @param $str \type{\string} New password to set
1582 * @throws PasswordError on failure
1584 function setPassword( $str ) {
1587 if( $str !== null ) {
1588 if( !$wgAuth->allowPasswordChange() ) {
1589 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1592 if( !$this->isValidPassword( $str ) ) {
1593 global $wgMinimalPasswordLength;
1594 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1595 $wgMinimalPasswordLength ) );
1599 if( !$wgAuth->setPassword( $this, $str ) ) {
1600 throw new PasswordError( wfMsg( 'externaldberror' ) );
1603 $this->setInternalPassword( $str );
1609 * Set the password and reset the random token unconditionally.
1611 * @param $str \type{\string} New password to set
1613 function setInternalPassword( $str ) {
1617 if( $str === null ) {
1618 // Save an invalid hash...
1619 $this->mPassword
= '';
1621 $this->mPassword
= self
::crypt( $str );
1623 $this->mNewpassword
= '';
1624 $this->mNewpassTime
= null;
1628 * Get the user's current token.
1629 * @return \type{\string} Token
1631 function getToken() {
1633 return $this->mToken
;
1637 * Set the random token (used for persistent authentication)
1638 * Called from loadDefaults() among other places.
1640 * @param $token \type{\string} If specified, set the token to this value
1643 function setToken( $token = false ) {
1644 global $wgSecretKey, $wgProxyKey;
1647 if ( $wgSecretKey ) {
1648 $key = $wgSecretKey;
1649 } elseif ( $wgProxyKey ) {
1654 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1656 $this->mToken
= $token;
1661 * Set the cookie password
1663 * @param $str \type{\string} New cookie password
1666 function setCookiePassword( $str ) {
1668 $this->mCookiePassword
= md5( $str );
1672 * Set the password for a password reminder or new account email
1674 * @param $str \type{\string} New password to set
1675 * @param $throttle \type{\bool} If true, reset the throttle timestamp to the present
1677 function setNewpassword( $str, $throttle = true ) {
1679 $this->mNewpassword
= self
::crypt( $str );
1681 $this->mNewpassTime
= wfTimestampNow();
1686 * Has password reminder email been sent within the last
1687 * $wgPasswordReminderResendTime hours?
1688 * @return \type{\bool} True or false
1690 function isPasswordReminderThrottled() {
1691 global $wgPasswordReminderResendTime;
1693 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1696 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1697 return time() < $expiry;
1701 * Get the user's e-mail address
1702 * @return \type{\string} User's e-mail address
1704 function getEmail() {
1706 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1707 return $this->mEmail
;
1711 * Get the timestamp of the user's e-mail authentication
1712 * @return \type{\string} TS_MW timestamp
1714 function getEmailAuthenticationTimestamp() {
1716 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1717 return $this->mEmailAuthenticated
;
1721 * Set the user's e-mail address
1722 * @param $str \type{\string} New e-mail address
1724 function setEmail( $str ) {
1726 $this->mEmail
= $str;
1727 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1731 * Get the user's real name
1732 * @return \type{\string} User's real name
1734 function getRealName() {
1736 return $this->mRealName
;
1740 * Set the user's real name
1741 * @param $str \type{\string} New real name
1743 function setRealName( $str ) {
1745 $this->mRealName
= $str;
1749 * Get the user's current setting for a given option.
1751 * @param $oname \type{\string} The option to check
1752 * @param $defaultOverride \type{\string} A default value returned if the option does not exist
1753 * @return \type{\string} User's current value for the option
1754 * @see getBoolOption()
1755 * @see getIntOption()
1757 function getOption( $oname, $defaultOverride = '' ) {
1760 if ( is_null( $this->mOptions
) ) {
1761 if($defaultOverride != '') {
1762 return $defaultOverride;
1764 $this->mOptions
= User
::getDefaultOptions();
1767 if ( array_key_exists( $oname, $this->mOptions
) ) {
1768 return trim( $this->mOptions
[$oname] );
1770 return $defaultOverride;
1775 * Get the user's current setting for a given option, as a boolean value.
1777 * @param $oname \type{\string} The option to check
1778 * @return \type{\bool} User's current value for the option
1781 function getBoolOption( $oname ) {
1782 return (bool)$this->getOption( $oname );
1787 * Get the user's current setting for a given option, as a boolean value.
1789 * @param $oname \type{\string} The option to check
1790 * @param $defaultOverride \type{\int} A default value returned if the option does not exist
1791 * @return \type{\int} User's current value for the option
1794 function getIntOption( $oname, $defaultOverride=0 ) {
1795 $val = $this->getOption( $oname );
1797 $val = $defaultOverride;
1799 return intval( $val );
1803 * Set the given option for a user.
1805 * @param $oname \type{\string} The option to set
1806 * @param $val \type{\mixed} New value to set
1808 function setOption( $oname, $val ) {
1810 if ( is_null( $this->mOptions
) ) {
1811 $this->mOptions
= User
::getDefaultOptions();
1813 if ( $oname == 'skin' ) {
1814 # Clear cached skin, so the new one displays immediately in Special:Preferences
1815 unset( $this->mSkin
);
1817 // Filter out any newlines that may have passed through input validation.
1818 // Newlines are used to separate items in the options blob.
1820 $val = str_replace( "\r\n", "\n", $val );
1821 $val = str_replace( "\r", "\n", $val );
1822 $val = str_replace( "\n", " ", $val );
1824 // Explicitly NULL values should refer to defaults
1825 global $wgDefaultUserOptions;
1826 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1827 $val = $wgDefaultUserOptions[$oname];
1829 $this->mOptions
[$oname] = $val;
1833 * Get the user's preferred date format.
1834 * @return \type{\string} User's preferred date format
1836 function getDatePreference() {
1837 // Important migration for old data rows
1838 if ( is_null( $this->mDatePreference
) ) {
1840 $value = $this->getOption( 'date' );
1841 $map = $wgLang->getDatePreferenceMigrationMap();
1842 if ( isset( $map[$value] ) ) {
1843 $value = $map[$value];
1845 $this->mDatePreference
= $value;
1847 return $this->mDatePreference
;
1851 * Get the permissions this user has.
1852 * @return \type{\arrayof{\string}} Array of permission names
1854 function getRights() {
1855 if ( is_null( $this->mRights
) ) {
1856 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1857 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1858 // Force reindexation of rights when a hook has unset one of them
1859 $this->mRights
= array_values( $this->mRights
);
1861 return $this->mRights
;
1865 * Get the list of explicit group memberships this user has.
1866 * The implicit * and user groups are not included.
1867 * @return \type{\arrayof{\string}} Array of internal group names
1869 function getGroups() {
1871 return $this->mGroups
;
1875 * Get the list of implicit group memberships this user has.
1876 * This includes all explicit groups, plus 'user' if logged in,
1877 * '*' for all accounts and autopromoted groups
1879 * @param $recache \type{\bool} Whether to avoid the cache
1880 * @return \type{\arrayof{\string}} Array of internal group names
1882 function getEffectiveGroups( $recache = false ) {
1883 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1884 $this->mEffectiveGroups
= $this->getGroups();
1885 $this->mEffectiveGroups
[] = '*';
1886 if( $this->getId() ) {
1887 $this->mEffectiveGroups
[] = 'user';
1889 $this->mEffectiveGroups
= array_unique( array_merge(
1890 $this->mEffectiveGroups
,
1891 Autopromote
::getAutopromoteGroups( $this )
1894 # Hook for additional groups
1895 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1898 return $this->mEffectiveGroups
;
1902 * Get the user's edit count.
1903 * @return \type{\int} User's edit count
1905 function getEditCount() {
1907 if ( !isset( $this->mEditCount
) ) {
1908 /* Populate the count, if it has not been populated yet */
1909 $this->mEditCount
= User
::edits($this->mId
);
1911 return $this->mEditCount
;
1919 * Add the user to the given group.
1920 * This takes immediate effect.
1921 * @param $group \type{\string} Name of the group to add
1923 function addGroup( $group ) {
1924 $dbw = wfGetDB( DB_MASTER
);
1925 if( $this->getId() ) {
1926 $dbw->insert( 'user_groups',
1928 'ug_user' => $this->getID(),
1929 'ug_group' => $group,
1932 array( 'IGNORE' ) );
1935 $this->loadGroups();
1936 $this->mGroups
[] = $group;
1937 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1939 $this->invalidateCache();
1943 * Remove the user from the given group.
1944 * This takes immediate effect.
1945 * @param $group \type{\string} Name of the group to remove
1947 function removeGroup( $group ) {
1949 $dbw = wfGetDB( DB_MASTER
);
1950 $dbw->delete( 'user_groups',
1952 'ug_user' => $this->getID(),
1953 'ug_group' => $group,
1955 'User::removeGroup' );
1957 $this->loadGroups();
1958 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1959 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1961 $this->invalidateCache();
1966 * Get whether the user is logged in
1967 * @return \type{\bool} True or false
1969 function isLoggedIn() {
1970 return $this->getID() != 0;
1974 * Get whether the user is anonymous
1975 * @return \type{\bool} True or false
1978 return !$this->isLoggedIn();
1982 * Get whether the user is a bot
1983 * @return \type{\bool} True or false
1987 wfDeprecated( __METHOD__
);
1988 return $this->isAllowed( 'bot' );
1992 * Check if user is allowed to access a feature / make an action
1993 * @param $action \type{\string} action to be checked
1994 * @return \type{\bool} True if action is allowed, else false
1996 function isAllowed($action='') {
1997 if ( $action === '' )
1998 // In the spirit of DWIM
2001 return in_array( $action, $this->getRights() );
2005 * Check whether to enable recent changes patrol features for this user
2006 * @return \type{\bool} True or false
2008 public function useRCPatrol() {
2009 global $wgUseRCPatrol;
2010 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2014 * Check whether to enable new pages patrol features for this user
2015 * @return \type{\bool} True or false
2017 public function useNPPatrol() {
2018 global $wgUseRCPatrol, $wgUseNPPatrol;
2019 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2023 * Get the current skin, loading it if required
2024 * @return \type{Skin} Current skin
2025 * @todo FIXME : need to check the old failback system [AV]
2027 function &getSkin() {
2029 if ( ! isset( $this->mSkin
) ) {
2030 wfProfileIn( __METHOD__
);
2033 $userSkin = $this->getOption( 'skin' );
2034 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2036 $this->mSkin
=& Skin
::newFromKey( $userSkin );
2037 wfProfileOut( __METHOD__
);
2039 return $this->mSkin
;
2043 * Check the watched status of an article.
2044 * @param $title \type{Title} Title of the article to look at
2045 * @return \type{\bool} True if article is watched
2047 function isWatched( $title ) {
2048 $wl = WatchedItem
::fromUserTitle( $this, $title );
2049 return $wl->isWatched();
2054 * @param $title \type{Title} Title of the article to look at
2056 function addWatch( $title ) {
2057 $wl = WatchedItem
::fromUserTitle( $this, $title );
2059 $this->invalidateCache();
2063 * Stop watching an article.
2064 * @param $title \type{Title} Title of the article to look at
2066 function removeWatch( $title ) {
2067 $wl = WatchedItem
::fromUserTitle( $this, $title );
2069 $this->invalidateCache();
2073 * Clear the user's notification timestamp for the given title.
2074 * If e-notif e-mails are on, they will receive notification mails on
2075 * the next change of the page if it's watched etc.
2076 * @param $title \type{Title} Title of the article to look at
2078 function clearNotification( &$title ) {
2079 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2081 # Do nothing if the database is locked to writes
2082 if( wfReadOnly() ) {
2086 if ($title->getNamespace() == NS_USER_TALK
&&
2087 $title->getText() == $this->getName() ) {
2088 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2090 $this->setNewtalk( false );
2093 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2097 if( $this->isAnon() ) {
2098 // Nothing else to do...
2102 // Only update the timestamp if the page is being watched.
2103 // The query to find out if it is watched is cached both in memcached and per-invocation,
2104 // and when it does have to be executed, it can be on a slave
2105 // If this is the user's newtalk page, we always update the timestamp
2106 if ($title->getNamespace() == NS_USER_TALK
&&
2107 $title->getText() == $wgUser->getName())
2110 } elseif ( $this->getId() == $wgUser->getId() ) {
2111 $watched = $title->userIsWatching();
2116 // If the page is watched by the user (or may be watched), update the timestamp on any
2117 // any matching rows
2119 $dbw = wfGetDB( DB_MASTER
);
2120 $dbw->update( 'watchlist',
2122 'wl_notificationtimestamp' => NULL
2123 ), array( /* WHERE */
2124 'wl_title' => $title->getDBkey(),
2125 'wl_namespace' => $title->getNamespace(),
2126 'wl_user' => $this->getID()
2133 * Resets all of the given user's page-change notification timestamps.
2134 * If e-notif e-mails are on, they will receive notification mails on
2135 * the next change of any watched page.
2137 * @param $currentUser \type{\int} %User ID
2139 function clearAllNotifications( $currentUser ) {
2140 global $wgUseEnotif, $wgShowUpdatedMarker;
2141 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2142 $this->setNewtalk( false );
2145 if( $currentUser != 0 ) {
2146 $dbw = wfGetDB( DB_MASTER
);
2147 $dbw->update( 'watchlist',
2149 'wl_notificationtimestamp' => NULL
2150 ), array( /* WHERE */
2151 'wl_user' => $currentUser
2154 # We also need to clear here the "you have new message" notification for the own user_talk page
2155 # This is cleared one page view later in Article::viewUpdates();
2160 * Encode this user's options as a string
2161 * @return \type{\string} Encoded options
2164 function encodeOptions() {
2166 if ( is_null( $this->mOptions
) ) {
2167 $this->mOptions
= User
::getDefaultOptions();
2170 foreach ( $this->mOptions
as $oname => $oval ) {
2171 array_push( $a, $oname.'='.$oval );
2173 $s = implode( "\n", $a );
2178 * Set this user's options from an encoded string
2179 * @param $str \type{\string} Encoded options to import
2182 function decodeOptions( $str ) {
2183 $this->mOptions
= array();
2184 $a = explode( "\n", $str );
2185 foreach ( $a as $s ) {
2187 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2188 $this->mOptions
[$m[1]] = $m[2];
2194 * Set a cookie on the user's client. Wrapper for
2195 * WebResponse::setCookie
2197 protected function setCookie( $name, $value, $exp=0 ) {
2199 $wgRequest->response()->setcookie( $name, $value, $exp );
2203 * Clear a cookie on the user's client
2204 * @param $name \type{\string} Name of the cookie to clear
2206 protected function clearCookie( $name ) {
2207 $this->setCookie( $name, '', time() - 86400 );
2211 * Set the default cookies for this session on the user's client.
2213 function setCookies() {
2215 if ( 0 == $this->mId
) return;
2217 'wsUserID' => $this->mId
,
2218 'wsToken' => $this->mToken
,
2219 'wsUserName' => $this->getName()
2222 'UserID' => $this->mId
,
2223 'UserName' => $this->getName(),
2225 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2226 $cookies['Token'] = $this->mToken
;
2228 $cookies['Token'] = false;
2231 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2232 $_SESSION = $session +
$_SESSION;
2233 foreach ( $cookies as $name => $value ) {
2234 if ( $value === false ) {
2235 $this->clearCookie( $name );
2237 $this->setCookie( $name, $value );
2243 * Log this user out.
2247 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2253 * Clear the user's cookies and session, and reset the instance cache.
2257 function doLogout() {
2258 $this->clearInstanceCache( 'defaults' );
2260 $_SESSION['wsUserID'] = 0;
2262 $this->clearCookie( 'UserID' );
2263 $this->clearCookie( 'Token' );
2265 # Remember when user logged out, to prevent seeing cached pages
2266 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2270 * Save this user's settings into the database.
2271 * @todo Only rarely do all these fields need to be set!
2273 function saveSettings() {
2275 if ( wfReadOnly() ) { return; }
2276 if ( 0 == $this->mId
) { return; }
2278 $this->mTouched
= self
::newTouchedTimestamp();
2280 $dbw = wfGetDB( DB_MASTER
);
2281 $dbw->update( 'user',
2283 'user_name' => $this->mName
,
2284 'user_password' => $this->mPassword
,
2285 'user_newpassword' => $this->mNewpassword
,
2286 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2287 'user_real_name' => $this->mRealName
,
2288 'user_email' => $this->mEmail
,
2289 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2290 'user_options' => $this->encodeOptions(),
2291 'user_touched' => $dbw->timestamp($this->mTouched
),
2292 'user_token' => $this->mToken
,
2293 'user_email_token' => $this->mEmailToken
,
2294 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2295 ), array( /* WHERE */
2296 'user_id' => $this->mId
2299 wfRunHooks( 'UserSaveSettings', array( $this ) );
2300 $this->clearSharedCache();
2304 * If only this user's username is known, and it exists, return the user ID.
2306 function idForName() {
2307 $s = trim( $this->getName() );
2308 if ( $s === '' ) return 0;
2310 $dbr = wfGetDB( DB_SLAVE
);
2311 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2312 if ( $id === false ) {
2319 * Add a user to the database, return the user object
2321 * @param $name \type{\string} Username to add
2322 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2323 * - password The user's password. Password logins will be disabled if this is omitted.
2324 * - newpassword A temporary password mailed to the user
2325 * - email The user's email address
2326 * - email_authenticated The email authentication timestamp
2327 * - real_name The user's real name
2328 * - options An associative array of non-default options
2329 * - token Random authentication token. Do not set.
2330 * - registration Registration timestamp. Do not set.
2332 * @return \type{User} A new User object, or null if the username already exists
2334 static function createNew( $name, $params = array() ) {
2337 if ( isset( $params['options'] ) ) {
2338 $user->mOptions
= $params['options'] +
$user->mOptions
;
2339 unset( $params['options'] );
2341 $dbw = wfGetDB( DB_MASTER
);
2342 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2344 'user_id' => $seqVal,
2345 'user_name' => $name,
2346 'user_password' => $user->mPassword
,
2347 'user_newpassword' => $user->mNewpassword
,
2348 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2349 'user_email' => $user->mEmail
,
2350 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2351 'user_real_name' => $user->mRealName
,
2352 'user_options' => $user->encodeOptions(),
2353 'user_token' => $user->mToken
,
2354 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2355 'user_editcount' => 0,
2357 foreach ( $params as $name => $value ) {
2358 $fields["user_$name"] = $value;
2360 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2361 if ( $dbw->affectedRows() ) {
2362 $newUser = User
::newFromId( $dbw->insertId() );
2370 * Add this existing user object to the database
2372 function addToDatabase() {
2374 $dbw = wfGetDB( DB_MASTER
);
2375 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2376 $dbw->insert( 'user',
2378 'user_id' => $seqVal,
2379 'user_name' => $this->mName
,
2380 'user_password' => $this->mPassword
,
2381 'user_newpassword' => $this->mNewpassword
,
2382 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2383 'user_email' => $this->mEmail
,
2384 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2385 'user_real_name' => $this->mRealName
,
2386 'user_options' => $this->encodeOptions(),
2387 'user_token' => $this->mToken
,
2388 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2389 'user_editcount' => 0,
2392 $this->mId
= $dbw->insertId();
2394 // Clear instance cache other than user table data, which is already accurate
2395 $this->clearInstanceCache();
2399 * If this (non-anonymous) user is blocked, block any IP address
2400 * they've successfully logged in from.
2402 function spreadBlock() {
2403 wfDebug( __METHOD__
."()\n" );
2405 if ( $this->mId
== 0 ) {
2409 $userblock = Block
::newFromDB( '', $this->mId
);
2410 if ( !$userblock ) {
2414 $userblock->doAutoblock( wfGetIp() );
2419 * Generate a string which will be different for any combination of
2420 * user options which would produce different parser output.
2421 * This will be used as part of the hash key for the parser cache,
2422 * so users will the same options can share the same cached data
2425 * Extensions which require it should install 'PageRenderingHash' hook,
2426 * which will give them a chance to modify this key based on their own
2429 * @return \type{\string} Page rendering hash
2431 function getPageRenderingHash() {
2432 global $wgContLang, $wgUseDynamicDates, $wgLang;
2434 return $this->mHash
;
2437 // stubthreshold is only included below for completeness,
2438 // it will always be 0 when this function is called by parsercache.
2440 $confstr = $this->getOption( 'math' );
2441 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2442 if ( $wgUseDynamicDates ) {
2443 $confstr .= '!' . $this->getDatePreference();
2445 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2446 $confstr .= '!' . $wgLang->getCode();
2447 $confstr .= '!' . $this->getOption( 'thumbsize' );
2448 // add in language specific options, if any
2449 $extra = $wgContLang->getExtraHashOptions();
2452 // Give a chance for extensions to modify the hash, if they have
2453 // extra options or other effects on the parser cache.
2454 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2456 // Make it a valid memcached key fragment
2457 $confstr = str_replace( ' ', '_', $confstr );
2458 $this->mHash
= $confstr;
2463 * Get whether the user is explicitly blocked from account creation.
2464 * @return \type{\bool} True if blocked
2466 function isBlockedFromCreateAccount() {
2467 $this->getBlockedStatus();
2468 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2472 * Get whether the user is blocked from using Special:Emailuser.
2473 * @return \type{\bool} True if blocked
2475 function isBlockedFromEmailuser() {
2476 $this->getBlockedStatus();
2477 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2481 * Get whether the user is allowed to create an account.
2482 * @return \type{\bool} True if allowed
2484 function isAllowedToCreateAccount() {
2485 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2491 function setLoaded( $loaded ) {
2492 wfDeprecated( __METHOD__
);
2496 * Get this user's personal page title.
2498 * @return \type{Title} User's personal page title
2500 function getUserPage() {
2501 return Title
::makeTitle( NS_USER
, $this->getName() );
2505 * Get this user's talk page title.
2507 * @return \type{Title} User's talk page title
2509 function getTalkPage() {
2510 $title = $this->getUserPage();
2511 return $title->getTalkPage();
2515 * Get the maximum valid user ID.
2516 * @return \type{\int} %User ID
2519 function getMaxID() {
2520 static $res; // cache
2522 if ( isset( $res ) )
2525 $dbr = wfGetDB( DB_SLAVE
);
2526 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2531 * Determine whether the user is a newbie. Newbies are either
2532 * anonymous IPs, or the most recently created accounts.
2533 * @return \type{\bool} True if the user is a newbie
2535 function isNewbie() {
2536 return !$this->isAllowed( 'autoconfirmed' );
2540 * Is the user active? We check to see if they've made at least
2541 * X number of edits in the last Y days.
2543 * @return \type{\bool} True if the user is active, false if not.
2545 public function isActiveEditor() {
2546 global $wgActiveUserEditCount, $wgActiveUserDays;
2547 $dbr = wfGetDB( DB_SLAVE
);
2549 // Stolen without shame from RC
2550 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2551 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
2552 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2554 $res = $dbr->select( 'revision', '1',
2555 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2557 array('LIMIT' => $wgActiveUserEditCount ) );
2559 $count = $dbr->numRows($res);
2560 $dbr->freeResult($res);
2562 return $count == $wgActiveUserEditCount;
2566 * Check to see if the given clear-text password is one of the accepted passwords
2567 * @param $password \type{\string} user password.
2568 * @return \type{\bool} True if the given password is correct, otherwise False.
2570 function checkPassword( $password ) {
2574 // Even though we stop people from creating passwords that
2575 // are shorter than this, doesn't mean people wont be able
2576 // to. Certain authentication plugins do NOT want to save
2577 // domain passwords in a mysql database, so we should
2578 // check this (incase $wgAuth->strict() is false).
2579 if( !$this->isValidPassword( $password ) ) {
2583 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2585 } elseif( $wgAuth->strict() ) {
2586 /* Auth plugin doesn't allow local authentication */
2588 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2589 /* Auth plugin doesn't allow local authentication for this user name */
2592 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2594 } elseif ( function_exists( 'iconv' ) ) {
2595 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2596 # Check for this with iconv
2597 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2598 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2606 * Check if the given clear-text password matches the temporary password
2607 * sent by e-mail for password reset operations.
2608 * @return \type{\bool} True if matches, false otherwise
2610 function checkTemporaryPassword( $plaintext ) {
2611 return self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() );
2615 * Initialize (if necessary) and return a session token value
2616 * which can be used in edit forms to show that the user's
2617 * login credentials aren't being hijacked with a foreign form
2620 * @param $salt \twotypes{\string,\arrayof{\string}} Optional function-specific data for hashing
2621 * @return \type{\string} The new edit token
2623 function editToken( $salt = '' ) {
2624 if ( $this->isAnon() ) {
2625 return EDIT_TOKEN_SUFFIX
;
2627 if( !isset( $_SESSION['wsEditToken'] ) ) {
2628 $token = $this->generateToken();
2629 $_SESSION['wsEditToken'] = $token;
2631 $token = $_SESSION['wsEditToken'];
2633 if( is_array( $salt ) ) {
2634 $salt = implode( '|', $salt );
2636 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2641 * Generate a looking random token for various uses.
2643 * @param $salt \type{\string} Optional salt value
2644 * @return \type{\string} The new random token
2646 function generateToken( $salt = '' ) {
2647 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2648 return md5( $token . $salt );
2652 * Check given value against the token value stored in the session.
2653 * A match should confirm that the form was submitted from the
2654 * user's own login session, not a form submission from a third-party
2657 * @param $val \type{\string} Input value to compare
2658 * @param $salt \type{\string} Optional function-specific data for hashing
2659 * @return \type{\bool} Whether the token matches
2661 function matchEditToken( $val, $salt = '' ) {
2662 $sessionToken = $this->editToken( $salt );
2663 if ( $val != $sessionToken ) {
2664 wfDebug( "User::matchEditToken: broken session data\n" );
2666 return $val == $sessionToken;
2670 * Check given value against the token value stored in the session,
2671 * ignoring the suffix.
2673 * @param $val \type{\string} Input value to compare
2674 * @param $salt \type{\string} Optional function-specific data for hashing
2675 * @return \type{\bool} Whether the token matches
2677 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2678 $sessionToken = $this->editToken( $salt );
2679 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2683 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2684 * mail to the user's given address.
2686 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure.
2688 function sendConfirmationMail() {
2690 $expiration = null; // gets passed-by-ref and defined in next line.
2691 $token = $this->confirmationToken( $expiration );
2692 $url = $this->confirmationTokenUrl( $token );
2693 $invalidateURL = $this->invalidationTokenUrl( $token );
2694 $this->saveSettings();
2696 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2697 wfMsg( 'confirmemail_body',
2701 $wgLang->timeanddate( $expiration, false ),
2706 * Send an e-mail to this user's account. Does not check for
2707 * confirmed status or validity.
2709 * @param $subject \type{\string} Message subject
2710 * @param $body \type{\string} Message body
2711 * @param $from \type{\string} Optional From address; if unspecified, default $wgPasswordSender will be used
2712 * @param $replyto \type{\string} Reply-to address
2713 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure
2715 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2716 if( is_null( $from ) ) {
2717 global $wgPasswordSender;
2718 $from = $wgPasswordSender;
2721 $to = new MailAddress( $this );
2722 $sender = new MailAddress( $from );
2723 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2727 * Generate, store, and return a new e-mail confirmation code.
2728 * A hash (unsalted, since it's used as a key) is stored.
2730 * @note Call saveSettings() after calling this function to commit
2731 * this change to the database.
2733 * @param[out] &$expiration \type{\mixed} Accepts the expiration time
2734 * @return \type{\string} New token
2737 function confirmationToken( &$expiration ) {
2739 $expires = $now +
7 * 24 * 60 * 60;
2740 $expiration = wfTimestamp( TS_MW
, $expires );
2741 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2742 $hash = md5( $token );
2744 $this->mEmailToken
= $hash;
2745 $this->mEmailTokenExpires
= $expiration;
2750 * Return a URL the user can use to confirm their email address.
2751 * @param $token \type{\string} Accepts the email confirmation token
2752 * @return \type{\string} New token URL
2755 function confirmationTokenUrl( $token ) {
2756 return $this->getTokenUrl( 'ConfirmEmail', $token );
2759 * Return a URL the user can use to invalidate their email address.
2761 * @param $token \type{\string} Accepts the email confirmation token
2762 * @return \type{\string} New token URL
2765 function invalidationTokenUrl( $token ) {
2766 return $this->getTokenUrl( 'Invalidateemail', $token );
2770 * Internal function to format the e-mail validation/invalidation URLs.
2771 * This uses $wgArticlePath directly as a quickie hack to use the
2772 * hardcoded English names of the Special: pages, for ASCII safety.
2774 * @note Since these URLs get dropped directly into emails, using the
2775 * short English names avoids insanely long URL-encoded links, which
2776 * also sometimes can get corrupted in some browsers/mailers
2777 * (bug 6957 with Gmail and Internet Explorer).
2779 * @param $page \type{\string} Special page
2780 * @param $token \type{\string} Token
2781 * @return \type{\string} Formatted URL
2783 protected function getTokenUrl( $page, $token ) {
2784 global $wgArticlePath;
2788 "Special:$page/$token",
2793 * Mark the e-mail address confirmed.
2795 * @note Call saveSettings() after calling this function to commit the change.
2797 function confirmEmail() {
2798 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2803 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2804 * address if it was already confirmed.
2806 * @note Call saveSettings() after calling this function to commit the change.
2808 function invalidateEmail() {
2810 $this->mEmailToken
= null;
2811 $this->mEmailTokenExpires
= null;
2812 $this->setEmailAuthenticationTimestamp( null );
2817 * Set the e-mail authentication timestamp.
2818 * @param $timestamp \type{\string} TS_MW timestamp
2820 function setEmailAuthenticationTimestamp( $timestamp ) {
2822 $this->mEmailAuthenticated
= $timestamp;
2823 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2827 * Is this user allowed to send e-mails within limits of current
2828 * site configuration?
2829 * @return \type{\bool} True if allowed
2831 function canSendEmail() {
2832 $canSend = $this->isEmailConfirmed();
2833 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2838 * Is this user allowed to receive e-mails within limits of current
2839 * site configuration?
2840 * @return \type{\bool} True if allowed
2842 function canReceiveEmail() {
2843 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2847 * Is this user's e-mail address valid-looking and confirmed within
2848 * limits of the current site configuration?
2850 * @note If $wgEmailAuthentication is on, this may require the user to have
2851 * confirmed their address by returning a code or using a password
2852 * sent to the address from the wiki.
2854 * @return \type{\bool} True if confirmed
2856 function isEmailConfirmed() {
2857 global $wgEmailAuthentication;
2860 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2861 if( $this->isAnon() )
2863 if( !self
::isValidEmailAddr( $this->mEmail
) )
2865 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2874 * Check whether there is an outstanding request for e-mail confirmation.
2875 * @return \type{\bool} True if pending
2877 function isEmailConfirmationPending() {
2878 global $wgEmailAuthentication;
2879 return $wgEmailAuthentication &&
2880 !$this->isEmailConfirmed() &&
2881 $this->mEmailToken
&&
2882 $this->mEmailTokenExpires
> wfTimestamp();
2886 * Get the timestamp of account creation.
2888 * @return \twotypes{\string,\bool} string Timestamp of account creation, or false for
2889 * non-existent/anonymous user accounts.
2891 public function getRegistration() {
2892 return $this->mId
> 0
2893 ?
$this->mRegistration
2898 * Get the permissions associated with a given list of groups
2900 * @param $groups \type{\arrayof{\string}} List of internal group names
2901 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
2903 static function getGroupPermissions( $groups ) {
2904 global $wgGroupPermissions;
2906 foreach( $groups as $group ) {
2907 if( isset( $wgGroupPermissions[$group] ) ) {
2908 $rights = array_merge( $rights,
2909 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2916 * Get all the groups who have a given permission
2918 * @param $role \type{\string} Role to check
2919 * @return \type{\arrayof{\string}} List of internal group names with the given permission
2921 static function getGroupsWithPermission( $role ) {
2922 global $wgGroupPermissions;
2923 $allowedGroups = array();
2924 foreach ( $wgGroupPermissions as $group => $rights ) {
2925 if ( isset( $rights[$role] ) && $rights[$role] ) {
2926 $allowedGroups[] = $group;
2929 return $allowedGroups;
2933 * Get the localized descriptive name for a group, if it exists
2935 * @param $group \type{\string} Internal group name
2936 * @return \type{\string} Localized descriptive group name
2938 static function getGroupName( $group ) {
2939 global $wgMessageCache;
2940 $wgMessageCache->loadAllMessages();
2941 $key = "group-$group";
2942 $name = wfMsg( $key );
2943 return $name == '' ||
wfEmptyMsg( $key, $name )
2949 * Get the localized descriptive name for a member of a group, if it exists
2951 * @param $group \type{\string} Internal group name
2952 * @return \type{\string} Localized name for group member
2954 static function getGroupMember( $group ) {
2955 global $wgMessageCache;
2956 $wgMessageCache->loadAllMessages();
2957 $key = "group-$group-member";
2958 $name = wfMsg( $key );
2959 return $name == '' ||
wfEmptyMsg( $key, $name )
2965 * Return the set of defined explicit groups.
2966 * The implicit groups (by default *, 'user' and 'autoconfirmed')
2967 * are not included, as they are defined automatically, not in the database.
2968 * @return \type{\arrayof{\string}} Array of internal group names
2970 static function getAllGroups() {
2971 global $wgGroupPermissions;
2973 array_keys( $wgGroupPermissions ),
2974 self
::getImplicitGroups()
2979 * Get a list of all available permissions.
2980 * @return \type{\arrayof{\string}} Array of permission names
2982 static function getAllRights() {
2983 if ( self
::$mAllRights === false ) {
2984 global $wgAvailableRights;
2985 if ( count( $wgAvailableRights ) ) {
2986 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
2988 self
::$mAllRights = self
::$mCoreRights;
2990 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
2992 return self
::$mAllRights;
2996 * Get a list of implicit groups
2997 * @return \type{\arrayof{\string}} Array of internal group names
2999 public static function getImplicitGroups() {
3000 global $wgImplicitGroups;
3001 $groups = $wgImplicitGroups;
3002 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3007 * Get the title of a page describing a particular group
3009 * @param $group \type{\string} Internal group name
3010 * @return \twotypes{Title,\bool} Title of the page if it exists, false otherwise
3012 static function getGroupPage( $group ) {
3013 global $wgMessageCache;
3014 $wgMessageCache->loadAllMessages();
3015 $page = wfMsgForContent( 'grouppage-' . $group );
3016 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3017 $title = Title
::newFromText( $page );
3018 if( is_object( $title ) )
3025 * Create a link to the group in HTML, if available;
3026 * else return the group name.
3028 * @param $group \type{\string} Internal name of the group
3029 * @param $text \type{\string} The text of the link
3030 * @return \type{\string} HTML link to the group
3032 static function makeGroupLinkHTML( $group, $text = '' ) {
3034 $text = self
::getGroupName( $group );
3036 $title = self
::getGroupPage( $group );
3039 $sk = $wgUser->getSkin();
3040 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3047 * Create a link to the group in Wikitext, if available;
3048 * else return the group name.
3050 * @param $group \type{\string} Internal name of the group
3051 * @param $text \type{\string} The text of the link
3052 * @return \type{\string} Wikilink to the group
3054 static function makeGroupLinkWiki( $group, $text = '' ) {
3056 $text = self
::getGroupName( $group );
3058 $title = self
::getGroupPage( $group );
3060 $page = $title->getPrefixedText();
3061 return "[[$page|$text]]";
3068 * Increment the user's edit-count field.
3069 * Will have no effect for anonymous users.
3071 function incEditCount() {
3072 if( !$this->isAnon() ) {
3073 $dbw = wfGetDB( DB_MASTER
);
3074 $dbw->update( 'user',
3075 array( 'user_editcount=user_editcount+1' ),
3076 array( 'user_id' => $this->getId() ),
3079 // Lazy initialization check...
3080 if( $dbw->affectedRows() == 0 ) {
3081 // Pull from a slave to be less cruel to servers
3082 // Accuracy isn't the point anyway here
3083 $dbr = wfGetDB( DB_SLAVE
);
3084 $count = $dbr->selectField( 'revision',
3086 array( 'rev_user' => $this->getId() ),
3089 // Now here's a goddamn hack...
3090 if( $dbr !== $dbw ) {
3091 // If we actually have a slave server, the count is
3092 // at least one behind because the current transaction
3093 // has not been committed and replicated.
3096 // But if DB_SLAVE is selecting the master, then the
3097 // count we just read includes the revision that was
3098 // just added in the working transaction.
3101 $dbw->update( 'user',
3102 array( 'user_editcount' => $count ),
3103 array( 'user_id' => $this->getId() ),
3107 // edit count in user cache too
3108 $this->invalidateCache();
3112 * Get the description of a given right
3114 * @param $right \type{\string} Right to query
3115 * @return \type{\string} Localized description of the right
3117 static function getRightDescription( $right ) {
3118 global $wgMessageCache;
3119 $wgMessageCache->loadAllMessages();
3120 $key = "right-$right";
3121 $name = wfMsg( $key );
3122 return $name == '' ||
wfEmptyMsg( $key, $name )
3128 * Make an old-style password hash
3130 * @param $password \type{\string} Plain-text password
3131 * @param $userId \type{\string} %User ID
3132 * @return \type{\string} Password hash
3134 static function oldCrypt( $password, $userId ) {
3135 global $wgPasswordSalt;
3136 if ( $wgPasswordSalt ) {
3137 return md5( $userId . '-' . md5( $password ) );
3139 return md5( $password );
3144 * Make a new-style password hash
3146 * @param $password \type{\string} Plain-text password
3147 * @param $salt \type{\string} Optional salt, may be random or the user ID.
3148 * If unspecified or false, will generate one automatically
3149 * @return \type{\string} Password hash
3151 static function crypt( $password, $salt = false ) {
3152 global $wgPasswordSalt;
3154 if($wgPasswordSalt) {
3155 if ( $salt === false ) {
3156 $salt = substr( wfGenerateToken(), 0, 8 );
3158 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3160 return ':A:' . md5( $password);
3165 * Compare a password hash with a plain-text password. Requires the user
3166 * ID if there's a chance that the hash is an old-style hash.
3168 * @param $hash \type{\string} Password hash
3169 * @param $password \type{\string} Plain-text password to compare
3170 * @param $userId \type{\string} %User ID for old-style password salt
3171 * @return \type{\bool} True if matches, false otherwise
3173 static function comparePasswords( $hash, $password, $userId = false ) {
3175 $type = substr( $hash, 0, 3 );
3176 if ( $type == ':A:' ) {
3178 return md5( $password ) === substr( $hash, 3 );
3179 } elseif ( $type == ':B:' ) {
3181 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3182 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3185 return self
::oldCrypt( $password, $userId ) === $hash;