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 * \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',
94 * \arrayof{\string} List of member variables which are saved to the
95 * shared cache (memcached). Any operation which changes the
96 * corresponding database fields must call a cache-clearing function.
99 static $mCacheVars = array(
111 'mEmailAuthenticated',
113 'mEmailTokenExpires',
121 * \arrayof{\string} Core rights.
122 * Each of these should have a corresponding message of the form
126 static $mCoreRights = array(
168 * \type{\string} Cached results of getAllRights()
170 static $mAllRights = false;
172 /** @name Cache variables */
174 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
175 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
176 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
180 * \type{\bool} Whether the cache variables have been loaded.
185 * \type{\string} Initialization data source if mDataLoaded==false. May be one of:
186 * - 'defaults' anonymous user initialised from class defaults
187 * - 'name' initialise from mName
188 * - 'id' initialise from mId
189 * - 'session' log in from cookies or session if possible
191 * Use the User::newFrom*() family of functions to set this.
195 /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
197 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
198 $mBlockreason, $mBlock, $mEffectiveGroups;
202 * Lightweight constructor for an anonymous user.
203 * Use the User::newFrom* factory functions for other kinds of users.
207 * @see newFromConfirmationCode()
208 * @see newFromSession()
212 $this->clearInstanceCache( 'defaults' );
216 * Load the user table data for this object from the source given by mFrom.
219 if ( $this->mDataLoaded
) {
222 wfProfileIn( __METHOD__
);
224 # Set it now to avoid infinite recursion in accessors
225 $this->mDataLoaded
= true;
227 switch ( $this->mFrom
) {
229 $this->loadDefaults();
232 $this->mId
= self
::idFromName( $this->mName
);
234 # Nonexistent user placeholder object
235 $this->loadDefaults( $this->mName
);
244 $this->loadFromSession();
247 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
249 wfProfileOut( __METHOD__
);
253 * Load user table data, given mId has already been set.
254 * @return \type{\bool} false if the ID does not exist, true otherwise
257 function loadFromId() {
259 if ( $this->mId
== 0 ) {
260 $this->loadDefaults();
265 $key = wfMemcKey( 'user', 'id', $this->mId
);
266 $data = $wgMemc->get( $key );
267 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
268 # Object is expired, load from DB
273 wfDebug( "Cache miss for user {$this->mId}\n" );
275 if ( !$this->loadFromDatabase() ) {
276 # Can't load from ID, user is anonymous
279 $this->saveToCache();
281 wfDebug( "Got user {$this->mId} from cache\n" );
283 foreach ( self
::$mCacheVars as $name ) {
284 $this->$name = $data[$name];
291 * Save user data to the shared cache
293 function saveToCache() {
296 if ( $this->isAnon() ) {
297 // Anonymous users are uncached
301 foreach ( self
::$mCacheVars as $name ) {
302 $data[$name] = $this->$name;
304 $data['mVersion'] = MW_USER_VERSION
;
305 $key = wfMemcKey( 'user', 'id', $this->mId
);
307 $wgMemc->set( $key, $data );
311 /** @name newFrom*() static factory methods */
315 * Static factory method for creation from username.
317 * This is slightly less efficient than newFromId(), so use newFromId() if
318 * you have both an ID and a name handy.
320 * @param $name \type{\string} Username, validated by Title::newFromText()
321 * @param $validate \type{\mixed} Validate username. Takes the same parameters as
322 * User::getCanonicalName(), except that true is accepted as an alias
323 * for 'valid', for BC.
325 * @return \type{User} The User object, or null if the username is invalid. If the
326 * username is not present in the database, the result will be a user object
327 * with a name, zero user ID and default settings.
329 static function newFromName( $name, $validate = 'valid' ) {
330 if ( $validate === true ) {
333 $name = self
::getCanonicalName( $name, $validate );
334 if ( $name === false ) {
337 # Create unloaded user object
346 * Static factory method for creation from a given user ID.
348 * @param $id \type{\int} Valid user ID
349 * @return \type{User} The corresponding User object
351 static function newFromId( $id ) {
359 * Factory method to fetch whichever user has a given email confirmation code.
360 * This code is generated when an account is created or its e-mail address
363 * If the code is invalid or has expired, returns NULL.
365 * @param $code \type{\string} Confirmation code
366 * @return \type{User}
368 static function newFromConfirmationCode( $code ) {
369 $dbr = wfGetDB( DB_SLAVE
);
370 $id = $dbr->selectField( 'user', 'user_id', array(
371 'user_email_token' => md5( $code ),
372 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
374 if( $id !== false ) {
375 return User
::newFromId( $id );
382 * Create a new user object using data from session or cookies. If the
383 * login credentials are invalid, the result is an anonymous user.
385 * @return \type{User}
387 static function newFromSession() {
389 $user->mFrom
= 'session';
394 * Create a new user object from a user row.
395 * The row should have all fields from the user table in it.
396 * @param $row array A row from the user table
397 * @return \type{User}
399 static function newFromRow( $row ) {
401 $user->loadFromRow( $row );
409 * Get the username corresponding to a given user ID
410 * @param $id \type{\int} %User ID
411 * @return \type{\string} The corresponding username
413 static function whoIs( $id ) {
414 $dbr = wfGetDB( DB_SLAVE
);
415 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
419 * Get the real name of a user given their user ID
421 * @param $id \type{\int} %User ID
422 * @return \type{\string} The corresponding user's real name
424 static function whoIsReal( $id ) {
425 $dbr = wfGetDB( DB_SLAVE
);
426 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
430 * Get database id given a user name
431 * @param $name \type{\string} Username
432 * @return \twotypes{\int,\null} The corresponding user's ID, or null if user is nonexistent
435 static function idFromName( $name ) {
436 $nt = Title
::newFromText( $name );
437 if( is_null( $nt ) ) {
441 $dbr = wfGetDB( DB_SLAVE
);
442 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
444 if ( $s === false ) {
452 * Does the string match an anonymous IPv4 address?
454 * This function exists for username validation, in order to reject
455 * usernames which are similar in form to IP addresses. Strings such
456 * as 300.300.300.300 will return true because it looks like an IP
457 * address, despite not being strictly valid.
459 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
460 * address because the usemod software would "cloak" anonymous IP
461 * addresses like this, if we allowed accounts like this to be created
462 * new users could get the old edits of these anonymous users.
465 * @param $name \type{\string} String to match
466 * @return \type{\bool} True or false
468 * @param $name \type{\string}
469 * @return \type{\bool}
472 static function isIP( $name ) {
473 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
477 * Is the input a valid username?
479 * Checks if the input is a valid username, we don't want an empty string,
480 * an IP address, anything that containins slashes (would mess up subpages),
481 * is longer than the maximum allowed username size or doesn't begin with
485 * @param $name \type{\string} String to match
486 * @return \type{\bool} True or false
488 * @param $name \type{\string}
489 * @return \type{\bool}
492 static function isValidUserName( $name ) {
493 global $wgContLang, $wgMaxNameChars;
496 || User
::isIP( $name )
497 ||
strpos( $name, '/' ) !== false
498 ||
strlen( $name ) > $wgMaxNameChars
499 ||
$name != $wgContLang->ucfirst( $name ) ) {
500 wfDebugLog( 'username', __METHOD__
.
501 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
505 // Ensure that the name can't be misresolved as a different title,
506 // such as with extra namespace keys at the start.
507 $parsed = Title
::newFromText( $name );
508 if( is_null( $parsed )
509 ||
$parsed->getNamespace()
510 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
511 wfDebugLog( 'username', __METHOD__
.
512 ": '$name' invalid due to ambiguous prefixes" );
516 // Check an additional blacklist of troublemaker characters.
517 // Should these be merged into the title char list?
518 $unicodeBlacklist = '/[' .
519 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
520 '\x{00a0}' . # non-breaking space
521 '\x{2000}-\x{200f}' . # various whitespace
522 '\x{2028}-\x{202f}' . # breaks and control chars
523 '\x{3000}' . # ideographic space
524 '\x{e000}-\x{f8ff}' . # private use
526 if( preg_match( $unicodeBlacklist, $name ) ) {
527 wfDebugLog( 'username', __METHOD__
.
528 ": '$name' invalid due to blacklisted characters" );
536 * Usernames which fail to pass this function will be blocked
537 * from user login and new account registrations, but may be used
538 * internally by batch processes.
540 * If an account already exists in this form, login will be blocked
541 * by a failure to pass this function.
544 * @param $name \type{\string} String to match
545 * @return \type{\bool} True or false
547 * @param $name \type{\string}
548 * @return \type{\bool}
551 static function isUsableName( $name ) {
552 global $wgReservedUsernames;
553 // Must be a valid username, obviously ;)
554 if ( !self
::isValidUserName( $name ) ) {
558 // Certain names may be reserved for batch processes.
559 foreach ( $wgReservedUsernames 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
581 * @param $name \type{\string} String to match
582 * @return \type{\bool} True or false
584 * @param $name \type{\string}
585 * @return \type{\bool}
588 static function isCreatableName( $name ) {
590 self
::isUsableName( $name ) &&
592 // Registration-time character blacklisting...
593 strpos( $name, '@' ) === false;
597 * Is the input a valid password for this user?
600 * @param $password \type{\string} Desired password
601 * @return \type{\bool} True or false
603 * @param $password \type{\string} Desired password
604 * @return \type{\bool}
607 function isValidPassword( $password ) {
608 global $wgMinimalPasswordLength, $wgContLang;
611 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
613 if( $result === false )
616 // Password needs to be long enough, and can't be the same as the username
617 return strlen( $password ) >= $wgMinimalPasswordLength
618 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
622 * Does a string look like an e-mail address?
624 * There used to be a regular expression here, it got removed because it
625 * rejected valid addresses. Actually just check if there is '@' somewhere
626 * in the given address.
628 * @todo Check for RFC 2822 compilance (bug 959)
631 * @param $addr \type{\string} E-mail address
632 * @return \type{\bool} True or false
634 * @param $addr \type{\string} E-mail address
635 * @return \type{\bool}
638 public static function isValidEmailAddr( $addr ) {
640 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
644 return strpos( $addr, '@' ) !== false;
648 * Given unvalidated user input, return a canonical username, or false if
649 * the username is invalid.
650 * @param $name \type{\string} User input
651 * @param $validate \twotypes{\string,\bool} Type of validation to use:
652 * - false No validation
653 * - 'valid' Valid for batch processes
654 * - 'usable' Valid for batch processes and login
655 * - 'creatable' Valid for batch processes, login and account creation
657 static function getCanonicalName( $name, $validate = 'valid' ) {
658 # Force usernames to capital
660 $name = $wgContLang->ucfirst( $name );
662 # Reject names containing '#'; these will be cleaned up
663 # with title normalisation, but then it's too late to
665 if( strpos( $name, '#' ) !== false )
668 # Clean up name according to title rules
669 $t = Title
::newFromText( $name );
670 if( is_null( $t ) ) {
674 # Reject various classes of invalid names
675 $name = $t->getText();
677 $name = $wgAuth->getCanonicalName( $t->getText() );
679 switch ( $validate ) {
683 if ( !User
::isValidUserName( $name ) ) {
688 if ( !User
::isUsableName( $name ) ) {
693 if ( !User
::isCreatableName( $name ) ) {
698 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
704 * Count the number of edits of a user
705 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
707 * @param $uid \type{\int} %User ID to check
708 * @return \type{\int} The user's edit count
710 static function edits( $uid ) {
711 wfProfileIn( __METHOD__
);
712 $dbr = wfGetDB( DB_SLAVE
);
713 // check if the user_editcount field has been initialized
714 $field = $dbr->selectField(
715 'user', 'user_editcount',
716 array( 'user_id' => $uid ),
720 if( $field === null ) { // it has not been initialized. do so.
721 $dbw = wfGetDB( DB_MASTER
);
722 $count = $dbr->selectField(
723 'revision', 'count(*)',
724 array( 'rev_user' => $uid ),
729 array( 'user_editcount' => $count ),
730 array( 'user_id' => $uid ),
736 wfProfileOut( __METHOD__
);
741 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
742 * @todo hash random numbers to improve security, like generateToken()
745 * @return \type{\string} New random password
747 * @return \type{\string}
750 static function randomPassword() {
751 global $wgMinimalPasswordLength;
752 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
753 $l = strlen( $pwchars ) - 1;
755 $pwlength = max( 7, $wgMinimalPasswordLength );
756 $digit = mt_rand(0, $pwlength - 1);
758 for ( $i = 0; $i < $pwlength; $i++
) {
759 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
765 * Set cached properties to default.
767 * @note This no longer clears uncached lazy-initialised properties;
768 * the constructor does that instead.
771 function loadDefaults( $name = false ) {
772 wfProfileIn( __METHOD__
);
774 global $wgCookiePrefix;
777 $this->mName
= $name;
778 $this->mRealName
= '';
779 $this->mPassword
= $this->mNewpassword
= '';
780 $this->mNewpassTime
= null;
782 $this->mOptions
= null; # Defer init
784 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
785 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
787 $this->mTouched
= '0'; # Allow any pages to be cached
790 $this->setToken(); # Random
791 $this->mEmailAuthenticated
= null;
792 $this->mEmailToken
= '';
793 $this->mEmailTokenExpires
= null;
794 $this->mRegistration
= wfTimestamp( TS_MW
);
795 $this->mGroups
= array();
797 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
799 wfProfileOut( __METHOD__
);
803 * @deprecated Use wfSetupSession().
805 function SetupSession() {
806 wfDeprecated( __METHOD__
);
811 * Load user data from the session or login cookie. If there are no valid
812 * credentials, initialises the user as an anonymous user.
813 * @return \type{\bool} True if the user is logged in, false otherwise.
815 private function loadFromSession() {
816 global $wgMemc, $wgCookiePrefix;
819 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
820 if ( $result !== null ) {
824 if ( isset( $_SESSION['wsUserID'] ) ) {
825 if ( 0 != $_SESSION['wsUserID'] ) {
826 $sId = $_SESSION['wsUserID'];
828 $this->loadDefaults();
831 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
832 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
833 $_SESSION['wsUserID'] = $sId;
835 $this->loadDefaults();
838 if ( isset( $_SESSION['wsUserName'] ) ) {
839 $sName = $_SESSION['wsUserName'];
840 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
841 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
842 $_SESSION['wsUserName'] = $sName;
844 $this->loadDefaults();
848 $passwordCorrect = FALSE;
850 if ( !$this->loadFromId() ) {
851 # Not a valid ID, loadFromId has switched the object to anon for us
855 if ( isset( $_SESSION['wsToken'] ) ) {
856 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
858 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
859 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
862 # No session or persistent login cookie
863 $this->loadDefaults();
867 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
868 $_SESSION['wsToken'] = $this->mToken
;
869 wfDebug( "Logged in from $from\n" );
872 # Invalid credentials
873 wfDebug( "Can't log in from $from, invalid credentials\n" );
874 $this->loadDefaults();
880 * Load user and user_group data from the database.
881 * $this::mId must be set, this is how the user is identified.
883 * @return \type{\bool} True if the user exists, false if the user is anonymous
886 function loadFromDatabase() {
888 $this->mId
= intval( $this->mId
);
890 /** Anonymous user */
892 $this->loadDefaults();
896 $dbr = wfGetDB( DB_MASTER
);
897 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
899 if ( $s !== false ) {
900 # Initialise user table data
901 $this->loadFromRow( $s );
902 $this->mGroups
= null; // deferred
903 $this->getEditCount(); // revalidation for nulls
908 $this->loadDefaults();
914 * Initialize this object from a row from the user table.
916 * @param $row \arrayof{\mixed} Row from the user table to load.
918 function loadFromRow( $row ) {
919 $this->mDataLoaded
= true;
921 if ( isset( $row->user_id
) ) {
922 $this->mId
= $row->user_id
;
924 $this->mName
= $row->user_name
;
925 $this->mRealName
= $row->user_real_name
;
926 $this->mPassword
= $row->user_password
;
927 $this->mNewpassword
= $row->user_newpassword
;
928 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
929 $this->mEmail
= $row->user_email
;
930 $this->decodeOptions( $row->user_options
);
931 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
932 $this->mToken
= $row->user_token
;
933 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
934 $this->mEmailToken
= $row->user_email_token
;
935 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
936 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
937 $this->mEditCount
= $row->user_editcount
;
941 * Load the groups from the database if they aren't already loaded.
944 function loadGroups() {
945 if ( is_null( $this->mGroups
) ) {
946 $dbr = wfGetDB( DB_MASTER
);
947 $res = $dbr->select( 'user_groups',
949 array( 'ug_user' => $this->mId
),
951 $this->mGroups
= array();
952 while( $row = $dbr->fetchObject( $res ) ) {
953 $this->mGroups
[] = $row->ug_group
;
959 * Clear various cached data stored in this object.
960 * @param $reloadFrom \type{\string} Reload user and user_groups table data from a
961 * given source. May be "name", "id", "defaults", "session", or false for
964 function clearInstanceCache( $reloadFrom = false ) {
965 $this->mNewtalk
= -1;
966 $this->mDatePreference
= null;
967 $this->mBlockedby
= -1; # Unset
968 $this->mHash
= false;
970 $this->mRights
= null;
971 $this->mEffectiveGroups
= null;
974 $this->mDataLoaded
= false;
975 $this->mFrom
= $reloadFrom;
980 * Combine the language default options with any site-specific options
981 * and add the default language variants.
983 * @return \arrayof{\string} Array of options
985 static function getDefaultOptions() {
986 global $wgNamespacesToBeSearchedDefault;
988 * Site defaults will override the global/language defaults
990 global $wgDefaultUserOptions, $wgContLang;
991 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
994 * default language setting
996 $variant = $wgContLang->getPreferredVariant( false );
997 $defOpt['variant'] = $variant;
998 $defOpt['language'] = $variant;
1000 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1001 $defOpt['searchNs'.$nsnum] = $val;
1007 * Get a given default option value.
1010 * @param $opt \type{\string} Name of option to retrieve
1011 * @return \type{\string} Default option value
1013 * @param $opt \type{\string} Name of option to retrieve
1014 * @return \type{\string}
1017 public static function getDefaultOption( $opt ) {
1018 $defOpts = self
::getDefaultOptions();
1019 if( isset( $defOpts[$opt] ) ) {
1020 return $defOpts[$opt];
1027 * Get a list of user toggle names
1028 * @return \arrayof{\string} Array of user toggle names
1030 static function getToggles() {
1032 $extraToggles = array();
1033 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1034 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1039 * Get blocking information
1041 * @param $bFromSlave \type{\bool} Whether to check the slave database first. To
1042 * improve performance, non-critical checks are done
1043 * against slaves. Check when actually saving should be
1044 * done against master.
1046 function getBlockedStatus( $bFromSlave = true ) {
1047 global $wgEnableSorbs, $wgProxyWhitelist;
1049 if ( -1 != $this->mBlockedby
) {
1050 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1054 wfProfileIn( __METHOD__
);
1055 wfDebug( __METHOD__
.": checking...\n" );
1057 // Initialize data...
1058 // Otherwise something ends up stomping on $this->mBlockedby when
1059 // things get lazy-loaded later, causing false positive block hits
1060 // due to -1 !== 0. Probably session-related... Nothing should be
1061 // overwriting mBlockedby, surely?
1064 $this->mBlockedby
= 0;
1065 $this->mHideName
= 0;
1068 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1069 # Exempt from all types of IP-block
1074 $this->mBlock
= new Block();
1075 $this->mBlock
->fromMaster( !$bFromSlave );
1076 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1077 wfDebug( __METHOD__
.": Found block.\n" );
1078 $this->mBlockedby
= $this->mBlock
->mBy
;
1079 $this->mBlockreason
= $this->mBlock
->mReason
;
1080 $this->mHideName
= $this->mBlock
->mHideName
;
1081 if ( $this->isLoggedIn() ) {
1082 $this->spreadBlock();
1085 $this->mBlock
= null;
1086 wfDebug( __METHOD__
.": No block.\n" );
1090 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1092 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1093 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1094 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1098 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1099 if ( $this->inSorbsBlacklist( $ip ) ) {
1100 $this->mBlockedby
= wfMsg( 'sorbs' );
1101 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1107 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1109 wfProfileOut( __METHOD__
);
1113 * Whether the given IP is in the SORBS blacklist.
1116 * @param $ip \type{\string} IP to check
1117 * @return \type{\bool} True if blacklisted
1119 * @param $ip \type{\string} IP to check
1120 * @return \type{\bool}
1123 function inSorbsBlacklist( $ip ) {
1124 global $wgEnableSorbs, $wgSorbsUrl;
1126 return $wgEnableSorbs &&
1127 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1131 * Whether the given IP is in a given DNS blacklist.
1134 * @param $ip \type{\string} IP to check
1135 * @param $base \type{\string} URL of the DNS blacklist
1136 * @return \type{\bool} True if blacklisted
1138 * @param $ip \type{\string} IP to check
1139 * @param $base \type{\string} URL of the DNS blacklist
1140 * @return \type{\bool}
1143 function inDnsBlacklist( $ip, $base ) {
1144 wfProfileIn( __METHOD__
);
1150 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
1152 for ( $i=4; $i>=1; $i-- ) {
1153 $host .= $m[$i] . '.';
1158 $ipList = gethostbynamel( $host );
1161 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1164 wfDebug( "Requested $host, not found in $base.\n" );
1168 wfProfileOut( __METHOD__
);
1173 * Is this user subject to rate limiting?
1176 * @return \type{\bool} True if rate limited
1178 * @return \type{\bool}
1181 public function isPingLimitable() {
1182 global $wgRateLimitsExcludedGroups;
1183 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1184 // Deprecated, but kept for backwards-compatibility config
1187 return !$this->isAllowed('noratelimit');
1191 * Primitive rate limits: enforce maximum actions per time period
1192 * to put a brake on flooding.
1194 * @note When using a shared cache like memcached, IP-address
1195 * last-hit counters will be shared across wikis.
1197 * @param $action \type{\string} Action to enforce; 'edit' if unspecified
1198 * @return \type{\bool} True if a rate limiter was tripped
1200 function pingLimiter( $action='edit' ) {
1202 # Call the 'PingLimiter' hook
1204 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1208 global $wgRateLimits;
1209 if( !isset( $wgRateLimits[$action] ) ) {
1213 # Some groups shouldn't trigger the ping limiter, ever
1214 if( !$this->isPingLimitable() )
1217 global $wgMemc, $wgRateLimitLog;
1218 wfProfileIn( __METHOD__
);
1220 $limits = $wgRateLimits[$action];
1222 $id = $this->getId();
1226 if( isset( $limits['anon'] ) && $id == 0 ) {
1227 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1230 if( isset( $limits['user'] ) && $id != 0 ) {
1231 $userLimit = $limits['user'];
1233 if( $this->isNewbie() ) {
1234 if( isset( $limits['newbie'] ) && $id != 0 ) {
1235 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1237 if( isset( $limits['ip'] ) ) {
1238 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1241 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1242 $subnet = $matches[1];
1243 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1246 // Check for group-specific permissions
1247 // If more than one group applies, use the group with the highest limit
1248 foreach ( $this->getGroups() as $group ) {
1249 if ( isset( $limits[$group] ) ) {
1250 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1251 $userLimit = $limits[$group];
1255 // Set the user limit key
1256 if ( $userLimit !== false ) {
1257 wfDebug( __METHOD__
.": effective user limit: $userLimit\n" );
1258 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1262 foreach( $keys as $key => $limit ) {
1263 list( $max, $period ) = $limit;
1264 $summary = "(limit $max in {$period}s)";
1265 $count = $wgMemc->get( $key );
1267 if( $count > $max ) {
1268 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1269 if( $wgRateLimitLog ) {
1270 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1274 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1277 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1278 $wgMemc->add( $key, 1, intval( $period ) );
1280 $wgMemc->incr( $key );
1283 wfProfileOut( __METHOD__
);
1288 * Check if user is blocked
1290 * @param $bFromSlave \type{\bool} Whether to check the slave database instead of the master
1291 * @return \type{\bool} True if blocked, false otherwise
1293 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1294 wfDebug( "User::isBlocked: enter\n" );
1295 $this->getBlockedStatus( $bFromSlave );
1296 return $this->mBlockedby
!== 0;
1300 * Check if user is blocked from editing a particular article
1302 * @param $title \type{\string} Title to check
1303 * @param $bFromSlave \type{\bool} Whether to check the slave database instead of the master
1304 * @return \type{\bool} True if blocked, false otherwise
1306 function isBlockedFrom( $title, $bFromSlave = false ) {
1307 global $wgBlockAllowsUTEdit;
1308 wfProfileIn( __METHOD__
);
1309 wfDebug( __METHOD__
.": enter\n" );
1311 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1312 $blocked = $this->isBlocked( $bFromSlave );
1313 # If a user's name is suppressed, they cannot make edits anywhere
1314 if ( !$this->mHideName
&& $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1315 $title->getNamespace() == NS_USER_TALK
) {
1317 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1319 wfProfileOut( __METHOD__
);
1324 * If user is blocked, return the name of the user who placed the block
1325 * @return \type{\string} name of blocker
1327 function blockedBy() {
1328 $this->getBlockedStatus();
1329 return $this->mBlockedby
;
1333 * If user is blocked, return the specified reason for the block
1334 * @return \type{\string} Blocking reason
1336 function blockedFor() {
1337 $this->getBlockedStatus();
1338 return $this->mBlockreason
;
1342 * Get the user's ID.
1343 * @return \type{\int} The user's ID; 0 if the user is anonymous or nonexistent
1346 if( $this->mId
=== null and $this->mName
!== null
1347 and User
::isIP( $this->mName
) ) {
1348 // Special case, we know the user is anonymous
1350 } elseif( $this->mId
=== null ) {
1351 // Don't load if this was initialized from an ID
1358 * Set the user and reload all fields according to a given ID
1359 * @param $v \type{\int} %User ID to reload
1361 function setId( $v ) {
1363 $this->clearInstanceCache( 'id' );
1367 * Get the user name, or the IP of an anonymous user
1369 * @return \type{\string} User's name or IP address
1371 * @return \type{\string}
1374 function getName() {
1375 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1376 # Special case optimisation
1377 return $this->mName
;
1380 if ( $this->mName
=== false ) {
1382 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1384 return $this->mName
;
1389 * Set the user name.
1391 * This does not reload fields from the database according to the given
1392 * name. Rather, it is used to create a temporary "nonexistent user" for
1393 * later addition to the database. It can also be used to set the IP
1394 * address for an anonymous user to something other than the current
1397 * @note User::newFromName() has rougly the same function, when the named user
1399 * @param $str \type{\string} New user name to set
1401 function setName( $str ) {
1403 $this->mName
= $str;
1407 * Get the user's name escaped by underscores.
1409 * @return \type{\string} Username escaped by underscores
1411 * @return \type{\string}
1414 function getTitleKey() {
1415 return str_replace( ' ', '_', $this->getName() );
1419 * Check if the user has new messages.
1420 * @return \type{\bool} True if the user has new messages
1422 function getNewtalk() {
1425 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1426 if( $this->mNewtalk
=== -1 ) {
1427 $this->mNewtalk
= false; # reset talk page status
1429 # Check memcached separately for anons, who have no
1430 # entire User object stored in there.
1433 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1434 $newtalk = $wgMemc->get( $key );
1435 if( strval( $newtalk ) !== '' ) {
1436 $this->mNewtalk
= (bool)$newtalk;
1438 // Since we are caching this, make sure it is up to date by getting it
1440 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1441 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1444 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1448 return (bool)$this->mNewtalk
;
1452 * Return the talk page(s) this user has new messages on.
1453 * @return \arrayof{\string} Array of page URLs
1455 function getNewMessageLinks() {
1457 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1460 if (!$this->getNewtalk())
1462 $up = $this->getUserPage();
1463 $utp = $up->getTalkPage();
1464 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1469 * Internal uncached check for new messages
1472 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1473 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1474 * @param $fromMaster \type{\bool} true to fetch from the master, false for a slave
1475 * @return \type{\bool} True if the user has new messages
1478 function checkNewtalk( $field, $id, $fromMaster = false ) {
1479 if ( $fromMaster ) {
1480 $db = wfGetDB( DB_MASTER
);
1482 $db = wfGetDB( DB_SLAVE
);
1484 $ok = $db->selectField( 'user_newtalk', $field,
1485 array( $field => $id ), __METHOD__
);
1486 return $ok !== false;
1490 * Add or update the new messages flag
1491 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1492 * @param $id \twotypes{string,\int} User's IP address for anonymous users, %User ID otherwise
1493 * @return \type{\bool} True if successful, false otherwise
1496 function updateNewtalk( $field, $id ) {
1497 $dbw = wfGetDB( DB_MASTER
);
1498 $dbw->insert( 'user_newtalk',
1499 array( $field => $id ),
1502 if ( $dbw->affectedRows() ) {
1503 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1506 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1512 * Clear the new messages flag for the given user
1513 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1514 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1515 * @return \type{\bool} True if successful, false otherwise
1518 function deleteNewtalk( $field, $id ) {
1519 $dbw = wfGetDB( DB_MASTER
);
1520 $dbw->delete( 'user_newtalk',
1521 array( $field => $id ),
1523 if ( $dbw->affectedRows() ) {
1524 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1527 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1533 * Update the 'You have new messages!' status.
1534 * @param $val \type{\bool} Whether the user has new messages
1536 function setNewtalk( $val ) {
1537 if( wfReadOnly() ) {
1542 $this->mNewtalk
= $val;
1544 if( $this->isAnon() ) {
1546 $id = $this->getName();
1549 $id = $this->getId();
1554 $changed = $this->updateNewtalk( $field, $id );
1556 $changed = $this->deleteNewtalk( $field, $id );
1559 if( $this->isAnon() ) {
1560 // Anons have a separate memcached space, since
1561 // user records aren't kept for them.
1562 $key = wfMemcKey( 'newtalk', 'ip', $id );
1563 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1566 $this->invalidateCache();
1571 * Generate a current or new-future timestamp to be stored in the
1572 * user_touched field when we update things.
1573 * @return \type{\string} Timestamp in TS_MW format
1575 private static function newTouchedTimestamp() {
1576 global $wgClockSkewFudge;
1577 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1581 * Clear user data from memcached.
1582 * Use after applying fun updates to the database; caller's
1583 * responsibility to update user_touched if appropriate.
1585 * Called implicitly from invalidateCache() and saveSettings().
1587 private function clearSharedCache() {
1590 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1595 * Immediately touch the user data cache for this account.
1596 * Updates user_touched field, and removes account data from memcached
1597 * for reload on the next hit.
1599 function invalidateCache() {
1602 $this->mTouched
= self
::newTouchedTimestamp();
1604 $dbw = wfGetDB( DB_MASTER
);
1605 $dbw->update( 'user',
1606 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1607 array( 'user_id' => $this->mId
),
1610 $this->clearSharedCache();
1615 * Validate the cache for this account.
1616 * @param $timestamp \type{\string} A timestamp in TS_MW format
1618 function validateCache( $timestamp ) {
1620 return ($timestamp >= $this->mTouched
);
1624 * Set the password and reset the random token.
1625 * Calls through to authentication plugin if necessary;
1626 * will have no effect if the auth plugin refuses to
1627 * pass the change through or if the legal password
1630 * As a special case, setting the password to null
1631 * wipes it, so the account cannot be logged in until
1632 * a new password is set, for instance via e-mail.
1634 * @param $str \type{\string} New password to set
1635 * @throws PasswordError on failure
1637 function setPassword( $str ) {
1640 if( $str !== null ) {
1641 if( !$wgAuth->allowPasswordChange() ) {
1642 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1645 if( !$this->isValidPassword( $str ) ) {
1646 global $wgMinimalPasswordLength;
1647 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1648 $wgMinimalPasswordLength ) );
1652 if( !$wgAuth->setPassword( $this, $str ) ) {
1653 throw new PasswordError( wfMsg( 'externaldberror' ) );
1656 $this->setInternalPassword( $str );
1662 * Set the password and reset the random token unconditionally.
1664 * @param $str \type{\string} New password to set
1666 function setInternalPassword( $str ) {
1670 if( $str === null ) {
1671 // Save an invalid hash...
1672 $this->mPassword
= '';
1674 $this->mPassword
= self
::crypt( $str );
1676 $this->mNewpassword
= '';
1677 $this->mNewpassTime
= null;
1681 * Get the user's current token.
1683 * @return \type{\string} Token
1685 * @return \type{\string}
1688 function getToken() {
1690 return $this->mToken
;
1694 * Set the random token (used for persistent authentication)
1695 * Called from loadDefaults() among other places.
1697 * @param $token \type{\string} If specified, set the token to this value
1700 function setToken( $token = false ) {
1701 global $wgSecretKey, $wgProxyKey;
1704 if ( $wgSecretKey ) {
1705 $key = $wgSecretKey;
1706 } elseif ( $wgProxyKey ) {
1711 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1713 $this->mToken
= $token;
1718 * Set the cookie password
1720 * @param $str \type{\string} New cookie password
1723 function setCookiePassword( $str ) {
1725 $this->mCookiePassword
= md5( $str );
1729 * Set the password for a password reminder or new account email
1731 * @param $str \type{\string} New password to set
1732 * @param $throttle \type{\bool} If true, reset the throttle timestamp to the present
1734 function setNewpassword( $str, $throttle = true ) {
1736 $this->mNewpassword
= self
::crypt( $str );
1738 $this->mNewpassTime
= wfTimestampNow();
1743 * Has password reminder email been sent within the last
1744 * $wgPasswordReminderResendTime hours?
1746 * @return \type{\bool} True or false
1748 * @return \type{\bool}
1751 function isPasswordReminderThrottled() {
1752 global $wgPasswordReminderResendTime;
1754 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1757 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1758 return time() < $expiry;
1762 * Get the user's e-mail address
1764 * @return \type{\string} User's -mail address
1766 * @return \type{\string}
1769 function getEmail() {
1771 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1772 return $this->mEmail
;
1776 * Get the timestamp of the user's e-mail authentication
1777 * @return \type{\string} TS_MW timestamp
1779 function getEmailAuthenticationTimestamp() {
1781 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1782 return $this->mEmailAuthenticated
;
1786 * Set the user's e-mail address
1787 * @param $str \type{\string} New e-mail address
1789 function setEmail( $str ) {
1791 $this->mEmail
= $str;
1792 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1796 * Get the user's real name
1798 * @return \type{\string} User's real name
1800 * @return \type{\string}
1803 function getRealName() {
1805 return $this->mRealName
;
1809 * Set the user's real name
1810 * @param $str \type{\string} New real name
1812 function setRealName( $str ) {
1814 $this->mRealName
= $str;
1818 * Get the user's current setting for a given option.
1820 * @param $oname \type{\string} The option to check
1821 * @param $defaultOverride \type{\string} A default value returned if the option does not exist
1822 * @return \type{\string} User's current value for the option
1823 * @see getBoolOption()
1824 * @see getIntOption()
1826 function getOption( $oname, $defaultOverride = '' ) {
1829 if ( is_null( $this->mOptions
) ) {
1830 if($defaultOverride != '') {
1831 return $defaultOverride;
1833 $this->mOptions
= User
::getDefaultOptions();
1836 if ( array_key_exists( $oname, $this->mOptions
) ) {
1837 return trim( $this->mOptions
[$oname] );
1839 return $defaultOverride;
1844 * Get the user's current setting for a given option, as a boolean value.
1846 * @param $oname \type{\string} The option to check
1847 * @return \type{\bool} User's current value for the option
1850 function getBoolOption( $oname ) {
1851 return (bool)$this->getOption( $oname );
1856 * Get the user's current setting for a given option, as a boolean value.
1858 * @param $oname \type{\string} The option to check
1859 * @param $defaultOverride \type{\int} A default value returned if the option does not exist
1860 * @return \type{\int} User's current value for the option
1863 function getIntOption( $oname, $defaultOverride=0 ) {
1864 $val = $this->getOption( $oname );
1866 $val = $defaultOverride;
1868 return intval( $val );
1872 * Set the given option for a user.
1874 * @param $oname \type{\string} The option to set
1875 * @param $val \type{\mixed} New value to set
1877 function setOption( $oname, $val ) {
1879 if ( is_null( $this->mOptions
) ) {
1880 $this->mOptions
= User
::getDefaultOptions();
1882 if ( $oname == 'skin' ) {
1883 # Clear cached skin, so the new one displays immediately in Special:Preferences
1884 unset( $this->mSkin
);
1886 // Filter out any newlines that may have passed through input validation.
1887 // Newlines are used to separate items in the options blob.
1889 $val = str_replace( "\r\n", "\n", $val );
1890 $val = str_replace( "\r", "\n", $val );
1891 $val = str_replace( "\n", " ", $val );
1893 // Explicitly NULL values should refer to defaults
1894 global $wgDefaultUserOptions;
1895 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1896 $val = $wgDefaultUserOptions[$oname];
1898 $this->mOptions
[$oname] = $val;
1902 * Get the user's preferred date format.
1904 * @return \type{\string} User's preferred date format
1906 * @return \type{\string}
1909 function getDatePreference() {
1910 // Important migration for old data rows
1911 if ( is_null( $this->mDatePreference
) ) {
1913 $value = $this->getOption( 'date' );
1914 $map = $wgLang->getDatePreferenceMigrationMap();
1915 if ( isset( $map[$value] ) ) {
1916 $value = $map[$value];
1918 $this->mDatePreference
= $value;
1920 return $this->mDatePreference
;
1924 * Get the permissions this user has.
1925 * @return \arrayof{\string} Array of permission names
1927 function getRights() {
1928 if ( is_null( $this->mRights
) ) {
1929 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1930 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1931 // Force reindexation of rights when a hook has unset one of them
1932 $this->mRights
= array_values( $this->mRights
);
1934 return $this->mRights
;
1938 * Get the list of explicit group memberships this user has.
1939 * The implicit * and user groups are not included.
1940 * @return \arrayof{\string} Array of internal group names
1942 function getGroups() {
1944 return $this->mGroups
;
1948 * Get the list of implicit group memberships this user has.
1949 * This includes all explicit groups, plus 'user' if logged in,
1950 * '*' for all accounts and autopromoted groups
1952 * @param $recache \type{\bool} Whether to avoid the cache
1953 * @return \arrayof{\string} Array of internal group names
1955 * @param $recache \type{\bool} Whether to avoid the cache
1956 * @return \arrayof{\string}
1959 function getEffectiveGroups( $recache = false ) {
1960 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1961 $this->mEffectiveGroups
= $this->getGroups();
1962 $this->mEffectiveGroups
[] = '*';
1963 if( $this->getId() ) {
1964 $this->mEffectiveGroups
[] = 'user';
1966 $this->mEffectiveGroups
= array_unique( array_merge(
1967 $this->mEffectiveGroups
,
1968 Autopromote
::getAutopromoteGroups( $this )
1971 # Hook for additional groups
1972 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1975 return $this->mEffectiveGroups
;
1979 * Get the user's edit count.
1981 * @return \type{\int} User's edit count
1983 * @return \type{\int}
1986 function getEditCount() {
1988 if ( !isset( $this->mEditCount
) ) {
1989 /* Populate the count, if it has not been populated yet */
1990 $this->mEditCount
= User
::edits($this->mId
);
1992 return $this->mEditCount
;
2000 * Add the user to the given group.
2001 * This takes immediate effect.
2002 * @param $group \type{\string} Name of the group to add
2004 function addGroup( $group ) {
2005 $dbw = wfGetDB( DB_MASTER
);
2006 if( $this->getId() ) {
2007 $dbw->insert( 'user_groups',
2009 'ug_user' => $this->getID(),
2010 'ug_group' => $group,
2013 array( 'IGNORE' ) );
2016 $this->loadGroups();
2017 $this->mGroups
[] = $group;
2018 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2020 $this->invalidateCache();
2024 * Remove the user from the given group.
2025 * This takes immediate effect.
2026 * @param $group \type{\string} Name of the group to remove
2028 function removeGroup( $group ) {
2030 $dbw = wfGetDB( DB_MASTER
);
2031 $dbw->delete( 'user_groups',
2033 'ug_user' => $this->getID(),
2034 'ug_group' => $group,
2036 'User::removeGroup' );
2038 $this->loadGroups();
2039 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2040 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2042 $this->invalidateCache();
2047 * Get whether the user is logged in
2049 * @return \type{\bool} True or false
2051 * @return \type{\bool}
2054 function isLoggedIn() {
2055 return $this->getID() != 0;
2059 * Get whether the user is anonymous
2061 * @return \type{\bool} True or false
2063 * @return \type{\bool}
2067 return !$this->isLoggedIn();
2071 * Get whether the user is a bot
2073 * @return \type{\bool} True or false
2075 * @return \type{\bool}
2080 wfDeprecated( __METHOD__
);
2081 return $this->isAllowed( 'bot' );
2085 * Check if user is allowed to access a feature / make an action
2086 * @param $action \type{\string} action to be checked
2087 * @return \type{\bool} True if action is allowed, else false
2089 function isAllowed($action='') {
2090 if ( $action === '' )
2091 // In the spirit of DWIM
2094 return in_array( $action, $this->getRights() );
2098 * Check whether to enable recent changes patrol features for this user
2100 * @return \type{\bool} True or false
2102 * @return \type{\bool}
2105 public function useRCPatrol() {
2106 global $wgUseRCPatrol;
2107 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2111 * Check whether to enable new pages patrol features for this user
2113 * @return \type{\bool} True or false
2115 * @return \type{\bool}
2118 public function useNPPatrol() {
2119 global $wgUseRCPatrol, $wgUseNPPatrol;
2120 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2124 * Get the current skin, loading it if required
2125 * @return \type{Skin} Current skin
2126 * @todo FIXME : need to check the old failback system [AV]
2128 function &getSkin() {
2130 if ( ! isset( $this->mSkin
) ) {
2131 wfProfileIn( __METHOD__
);
2134 $userSkin = $this->getOption( 'skin' );
2135 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2137 $this->mSkin
=& Skin
::newFromKey( $userSkin );
2138 wfProfileOut( __METHOD__
);
2140 return $this->mSkin
;
2144 * Check the watched status of an article.
2145 * @param $title \type{Title} Title of the article to look at
2146 * @return \type{\bool} True if article is watched
2148 function isWatched( $title ) {
2149 $wl = WatchedItem
::fromUserTitle( $this, $title );
2150 return $wl->isWatched();
2155 * @param $title \type{Title} Title of the article to look at
2157 function addWatch( $title ) {
2158 $wl = WatchedItem
::fromUserTitle( $this, $title );
2160 $this->invalidateCache();
2164 * Stop watching an article.
2165 * @param $title \type{Title} Title of the article to look at
2167 function removeWatch( $title ) {
2168 $wl = WatchedItem
::fromUserTitle( $this, $title );
2170 $this->invalidateCache();
2174 * Clear the user's notification timestamp for the given title.
2175 * If e-notif e-mails are on, they will receive notification mails on
2176 * the next change of the page if it's watched etc.
2177 * @param $title \type{Title} Title of the article to look at
2179 function clearNotification( &$title ) {
2180 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2182 # Do nothing if the database is locked to writes
2183 if( wfReadOnly() ) {
2187 if ($title->getNamespace() == NS_USER_TALK
&&
2188 $title->getText() == $this->getName() ) {
2189 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2191 $this->setNewtalk( false );
2194 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2198 if( $this->isAnon() ) {
2199 // Nothing else to do...
2203 // Only update the timestamp if the page is being watched.
2204 // The query to find out if it is watched is cached both in memcached and per-invocation,
2205 // and when it does have to be executed, it can be on a slave
2206 // If this is the user's newtalk page, we always update the timestamp
2207 if ($title->getNamespace() == NS_USER_TALK
&&
2208 $title->getText() == $wgUser->getName())
2211 } elseif ( $this->getId() == $wgUser->getId() ) {
2212 $watched = $title->userIsWatching();
2217 // If the page is watched by the user (or may be watched), update the timestamp on any
2218 // any matching rows
2220 $dbw = wfGetDB( DB_MASTER
);
2221 $dbw->update( 'watchlist',
2223 'wl_notificationtimestamp' => NULL
2224 ), array( /* WHERE */
2225 'wl_title' => $title->getDBkey(),
2226 'wl_namespace' => $title->getNamespace(),
2227 'wl_user' => $this->getID()
2234 * Resets all of the given user's page-change notification timestamps.
2235 * If e-notif e-mails are on, they will receive notification mails on
2236 * the next change of any watched page.
2238 * @param $currentUser \type{\int} %User ID
2240 function clearAllNotifications( $currentUser ) {
2241 global $wgUseEnotif, $wgShowUpdatedMarker;
2242 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2243 $this->setNewtalk( false );
2246 if( $currentUser != 0 ) {
2247 $dbw = wfGetDB( DB_MASTER
);
2248 $dbw->update( 'watchlist',
2250 'wl_notificationtimestamp' => NULL
2251 ), array( /* WHERE */
2252 'wl_user' => $currentUser
2255 # We also need to clear here the "you have new message" notification for the own user_talk page
2256 # This is cleared one page view later in Article::viewUpdates();
2261 * Encode this user's options as a string
2262 * @return \type{\string} Encoded options
2265 function encodeOptions() {
2267 if ( is_null( $this->mOptions
) ) {
2268 $this->mOptions
= User
::getDefaultOptions();
2271 foreach ( $this->mOptions
as $oname => $oval ) {
2272 array_push( $a, $oname.'='.$oval );
2274 $s = implode( "\n", $a );
2279 * Set this user's options from an encoded string
2280 * @param $str \type{\string} Encoded options to import
2283 function decodeOptions( $str ) {
2284 $this->mOptions
= array();
2285 $a = explode( "\n", $str );
2286 foreach ( $a as $s ) {
2288 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2289 $this->mOptions
[$m[1]] = $m[2];
2295 * Set a cookie on the user's client
2296 * @param $name \type{\string} Name of the cookie to set
2297 * @param $name \type{\string} Value to set
2298 * @param $name \type{\int} Expiration time, as a UNIX time value;
2299 * if 0 or not specified, use the default $wgCookieExpiration
2301 protected function setCookie( $name, $value, $exp=0 ) {
2302 global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly;
2304 $exp = time() +
$wgCookieExpiration;
2306 $httpOnlySafe = wfHttpOnlySafe();
2307 wfDebugLog( 'cookie',
2308 'setcookie: "' . implode( '", "',
2310 $wgCookiePrefix . $name,
2316 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2317 if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) {
2318 setcookie( $wgCookiePrefix . $name,
2324 $wgCookieHttpOnly );
2326 // setcookie() fails on PHP 5.1 if you give it future-compat paramters.
2328 setcookie( $wgCookiePrefix . $name,
2338 * Clear a cookie on the user's client
2339 * @param $name \type{\string} Name of the cookie to clear
2341 protected function clearCookie( $name ) {
2342 $this->setCookie( $name, '', time() - 86400 );
2346 * Set the default cookies for this session on the user's client.
2348 function setCookies() {
2350 if ( 0 == $this->mId
) return;
2352 'wsUserID' => $this->mId
,
2353 'wsToken' => $this->mToken
,
2354 'wsUserName' => $this->getName()
2357 'UserID' => $this->mId
,
2358 'UserName' => $this->getName(),
2360 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2361 $cookies['Token'] = $this->mToken
;
2363 $cookies['Token'] = false;
2366 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2367 $_SESSION = $session +
$_SESSION;
2368 foreach ( $cookies as $name => $value ) {
2369 if ( $value === false ) {
2370 $this->clearCookie( $name );
2372 $this->setCookie( $name, $value );
2378 * Log this user out.
2382 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2388 * Clear the user's cookies and session, and reset the instance cache.
2392 function doLogout() {
2393 $this->clearInstanceCache( 'defaults' );
2395 $_SESSION['wsUserID'] = 0;
2397 $this->clearCookie( 'UserID' );
2398 $this->clearCookie( 'Token' );
2400 # Remember when user logged out, to prevent seeing cached pages
2401 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2405 * Save this user's settings into the database.
2406 * @todo Only rarely do all these fields need to be set!
2408 function saveSettings() {
2410 if ( wfReadOnly() ) { return; }
2411 if ( 0 == $this->mId
) { return; }
2413 $this->mTouched
= self
::newTouchedTimestamp();
2415 $dbw = wfGetDB( DB_MASTER
);
2416 $dbw->update( 'user',
2418 'user_name' => $this->mName
,
2419 'user_password' => $this->mPassword
,
2420 'user_newpassword' => $this->mNewpassword
,
2421 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2422 'user_real_name' => $this->mRealName
,
2423 'user_email' => $this->mEmail
,
2424 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2425 'user_options' => $this->encodeOptions(),
2426 'user_touched' => $dbw->timestamp($this->mTouched
),
2427 'user_token' => $this->mToken
,
2428 'user_email_token' => $this->mEmailToken
,
2429 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2430 ), array( /* WHERE */
2431 'user_id' => $this->mId
2434 wfRunHooks( 'UserSaveSettings', array( $this ) );
2435 $this->clearSharedCache();
2439 * If only this user's username is known, and it exists, return the user ID.
2441 function idForName() {
2442 $s = trim( $this->getName() );
2443 if ( $s === '' ) return 0;
2445 $dbr = wfGetDB( DB_SLAVE
);
2446 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2447 if ( $id === false ) {
2454 * Add a user to the database, return the user object
2456 * @param $name \type{\string} Username to add
2457 * @param $params \arrayof{\string} Non-default parameters to save to the database:
2458 * - password The user's password. Password logins will be disabled if this is omitted.
2459 * - newpassword A temporary password mailed to the user
2460 * - email The user's email address
2461 * - email_authenticated The email authentication timestamp
2462 * - real_name The user's real name
2463 * - options An associative array of non-default options
2464 * - token Random authentication token. Do not set.
2465 * - registration Registration timestamp. Do not set.
2467 * @return \type{User} A new User object, or null if the username already exists
2469 static function createNew( $name, $params = array() ) {
2472 if ( isset( $params['options'] ) ) {
2473 $user->mOptions
= $params['options'] +
$user->mOptions
;
2474 unset( $params['options'] );
2476 $dbw = wfGetDB( DB_MASTER
);
2477 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2479 'user_id' => $seqVal,
2480 'user_name' => $name,
2481 'user_password' => $user->mPassword
,
2482 'user_newpassword' => $user->mNewpassword
,
2483 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2484 'user_email' => $user->mEmail
,
2485 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2486 'user_real_name' => $user->mRealName
,
2487 'user_options' => $user->encodeOptions(),
2488 'user_token' => $user->mToken
,
2489 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2490 'user_editcount' => 0,
2492 foreach ( $params as $name => $value ) {
2493 $fields["user_$name"] = $value;
2495 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2496 if ( $dbw->affectedRows() ) {
2497 $newUser = User
::newFromId( $dbw->insertId() );
2505 * Add this existing user object to the database
2507 function addToDatabase() {
2509 $dbw = wfGetDB( DB_MASTER
);
2510 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2511 $dbw->insert( 'user',
2513 'user_id' => $seqVal,
2514 'user_name' => $this->mName
,
2515 'user_password' => $this->mPassword
,
2516 'user_newpassword' => $this->mNewpassword
,
2517 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2518 'user_email' => $this->mEmail
,
2519 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2520 'user_real_name' => $this->mRealName
,
2521 'user_options' => $this->encodeOptions(),
2522 'user_token' => $this->mToken
,
2523 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2524 'user_editcount' => 0,
2527 $this->mId
= $dbw->insertId();
2529 // Clear instance cache other than user table data, which is already accurate
2530 $this->clearInstanceCache();
2534 * If this (non-anonymous) user is blocked, block any IP address
2535 * they've successfully logged in from.
2537 function spreadBlock() {
2538 wfDebug( __METHOD__
."()\n" );
2540 if ( $this->mId
== 0 ) {
2544 $userblock = Block
::newFromDB( '', $this->mId
);
2545 if ( !$userblock ) {
2549 $userblock->doAutoblock( wfGetIp() );
2554 * Generate a string which will be different for any combination of
2555 * user options which would produce different parser output.
2556 * This will be used as part of the hash key for the parser cache,
2557 * so users will the same options can share the same cached data
2560 * Extensions which require it should install 'PageRenderingHash' hook,
2561 * which will give them a chance to modify this key based on their own
2565 * @return \type{\string} Page rendering hash
2567 * @return \type{\string}
2570 function getPageRenderingHash() {
2571 global $wgContLang, $wgUseDynamicDates, $wgLang;
2573 return $this->mHash
;
2576 // stubthreshold is only included below for completeness,
2577 // it will always be 0 when this function is called by parsercache.
2579 $confstr = $this->getOption( 'math' );
2580 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2581 if ( $wgUseDynamicDates ) {
2582 $confstr .= '!' . $this->getDatePreference();
2584 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2585 $confstr .= '!' . $wgLang->getCode();
2586 $confstr .= '!' . $this->getOption( 'thumbsize' );
2587 // add in language specific options, if any
2588 $extra = $wgContLang->getExtraHashOptions();
2591 // Give a chance for extensions to modify the hash, if they have
2592 // extra options or other effects on the parser cache.
2593 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2595 // Make it a valid memcached key fragment
2596 $confstr = str_replace( ' ', '_', $confstr );
2597 $this->mHash
= $confstr;
2602 * Get whether the user is explicitly blocked from account creation.
2604 * @return \type{\bool} True if blocked
2606 * @return \type{\bool}
2609 function isBlockedFromCreateAccount() {
2610 $this->getBlockedStatus();
2611 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2615 * Get whether the user is blocked from using Special:Emailuser.
2617 * @return \type{\bool} True if blocked
2619 * @return \type{\bool}
2622 function isBlockedFromEmailuser() {
2623 $this->getBlockedStatus();
2624 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2628 * Get whether the user is allowed to create an account.
2630 * @return \type{\bool} True if allowed
2632 * @return \type{\bool}
2635 function isAllowedToCreateAccount() {
2636 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2642 function setLoaded( $loaded ) {
2643 wfDeprecated( __METHOD__
);
2647 * Get this user's personal page title.
2649 * @return \type{Title} User's personal page title
2651 function getUserPage() {
2652 return Title
::makeTitle( NS_USER
, $this->getName() );
2656 * Get this user's talk page title.
2658 * @return \type{Title} User's talk page title
2660 function getTalkPage() {
2661 $title = $this->getUserPage();
2662 return $title->getTalkPage();
2666 * Get the maximum valid user ID.
2668 * @return \type{\int} %User ID
2670 * @return \type{\int}
2674 function getMaxID() {
2675 static $res; // cache
2677 if ( isset( $res ) )
2680 $dbr = wfGetDB( DB_SLAVE
);
2681 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2686 * Determine whether the user is a newbie. Newbies are either
2687 * anonymous IPs, or the most recently created accounts.
2688 * @return \type{\bool} True if the user is a newbie
2690 function isNewbie() {
2691 return !$this->isAllowed( 'autoconfirmed' );
2695 * Is the user active? We check to see if they've made at least
2696 * X number of edits in the last Y days.
2698 * @return \type{\bool} True if the user is active, false if not.
2700 public function isActiveEditor() {
2701 global $wgActiveUserEditCount, $wgActiveUserDays;
2702 $dbr = wfGetDB( DB_SLAVE
);
2704 // Stolen without shame from RC
2705 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2706 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
2707 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2709 $res = $dbr->select( 'revision', '1',
2710 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2712 array('LIMIT' => $wgActiveUserEditCount ) );
2714 $count = $dbr->numRows($res);
2715 $dbr->freeResult($res);
2717 return $count == $wgActiveUserEditCount;
2721 * Check to see if the given clear-text password is one of the accepted passwords
2722 * @param $password \type{\string} user password.
2723 * @return \type{\bool} True if the given password is correct, otherwise False.
2725 function checkPassword( $password ) {
2729 // Even though we stop people from creating passwords that
2730 // are shorter than this, doesn't mean people wont be able
2731 // to. Certain authentication plugins do NOT want to save
2732 // domain passwords in a mysql database, so we should
2733 // check this (incase $wgAuth->strict() is false).
2734 if( !$this->isValidPassword( $password ) ) {
2738 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2740 } elseif( $wgAuth->strict() ) {
2741 /* Auth plugin doesn't allow local authentication */
2743 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2744 /* Auth plugin doesn't allow local authentication for this user name */
2747 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2749 } elseif ( function_exists( 'iconv' ) ) {
2750 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2751 # Check for this with iconv
2752 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2753 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2761 * Check if the given clear-text password matches the temporary password
2762 * sent by e-mail for password reset operations.
2764 * @return \type{\bool} True if matches, false otherwise
2766 * @return \type{\bool}
2769 function checkTemporaryPassword( $plaintext ) {
2770 return self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() );
2774 * Initialize (if necessary) and return a session token value
2775 * which can be used in edit forms to show that the user's
2776 * login credentials aren't being hijacked with a foreign form
2779 * @param $salt \twotypes{\string,\arrayof{\string}} Optional function-specific data for hashing
2780 * @return \type{\string} The new edit token
2782 function editToken( $salt = '' ) {
2783 if ( $this->isAnon() ) {
2784 return EDIT_TOKEN_SUFFIX
;
2786 if( !isset( $_SESSION['wsEditToken'] ) ) {
2787 $token = $this->generateToken();
2788 $_SESSION['wsEditToken'] = $token;
2790 $token = $_SESSION['wsEditToken'];
2792 if( is_array( $salt ) ) {
2793 $salt = implode( '|', $salt );
2795 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2800 * Generate a looking random token for various uses.
2802 * @param $salt \type{\string} Optional salt value
2803 * @return \type{\string} The new random token
2805 function generateToken( $salt = '' ) {
2806 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2807 return md5( $token . $salt );
2811 * Check given value against the token value stored in the session.
2812 * A match should confirm that the form was submitted from the
2813 * user's own login session, not a form submission from a third-party
2816 * @param $val \type{\string} Input value to compare
2817 * @param $salt \type{\string} Optional function-specific data for hashing
2818 * @return \type{\bool} Whether the token matches
2820 function matchEditToken( $val, $salt = '' ) {
2821 $sessionToken = $this->editToken( $salt );
2822 if ( $val != $sessionToken ) {
2823 wfDebug( "User::matchEditToken: broken session data\n" );
2825 return $val == $sessionToken;
2829 * Check given value against the token value stored in the session,
2830 * ignoring the suffix.
2832 * @param $val \type{\string} Input value to compare
2833 * @param $salt \type{\string} Optional function-specific data for hashing
2834 * @return \type{\bool} Whether the token matches
2836 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2837 $sessionToken = $this->editToken( $salt );
2838 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2842 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2843 * mail to the user's given address.
2845 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure.
2847 function sendConfirmationMail() {
2849 $expiration = null; // gets passed-by-ref and defined in next line.
2850 $token = $this->confirmationToken( $expiration );
2851 $url = $this->confirmationTokenUrl( $token );
2852 $invalidateURL = $this->invalidationTokenUrl( $token );
2853 $this->saveSettings();
2855 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2856 wfMsg( 'confirmemail_body',
2860 $wgLang->timeanddate( $expiration, false ),
2865 * Send an e-mail to this user's account. Does not check for
2866 * confirmed status or validity.
2869 * @param $subject \type{\string} Message subject
2870 * @param $body \type{\string} Message body
2871 * @param $from \type{\string} Optional From address; if unspecified, default $wgPasswordSender will be used
2872 * @param $replyto \type{\string} Reply-to address
2873 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure
2875 * @param $subject \type{\string} Message subject
2876 * @param $body \type{\string} Message body
2877 * @param $from \type{\string} Optional From address; if unspecified, default $wgPasswordSender will be used
2878 * @param $replyto \type{\string}
2879 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure
2882 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2883 if( is_null( $from ) ) {
2884 global $wgPasswordSender;
2885 $from = $wgPasswordSender;
2888 $to = new MailAddress( $this );
2889 $sender = new MailAddress( $from );
2890 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2894 * Generate, store, and return a new e-mail confirmation code.
2895 * A hash (unsalted, since it's used as a key) is stored.
2897 * @note Call saveSettings() after calling this function to commit
2898 * this change to the database.
2901 * @param[out] &$expiration \type{\mixed} Accepts the expiration time
2902 * @return \type{\string} New token
2904 * @param[out] &$expiration \type{\mixed} Accepts the expiration time
2905 * @return \type{\string}
2909 function confirmationToken( &$expiration ) {
2911 $expires = $now +
7 * 24 * 60 * 60;
2912 $expiration = wfTimestamp( TS_MW
, $expires );
2913 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2914 $hash = md5( $token );
2916 $this->mEmailToken
= $hash;
2917 $this->mEmailTokenExpires
= $expiration;
2922 * Return a URL the user can use to confirm their email address.
2924 * @param $token \type{\string} Accepts the email confirmation token
2925 * @return \type{\string} New token URL
2927 * @param $token \type{\string} Accepts the email confirmation token
2928 * @return \type{\string}
2932 function confirmationTokenUrl( $token ) {
2933 return $this->getTokenUrl( 'ConfirmEmail', $token );
2936 * Return a URL the user can use to invalidate their email address.
2938 * @param $token \type{\string} Accepts the email confirmation token
2939 * @return \type{\string} New token URL
2941 * @param $token \type{\string} Accepts the email confirmation token
2942 * @return \type{\string}
2946 function invalidationTokenUrl( $token ) {
2947 return $this->getTokenUrl( 'Invalidateemail', $token );
2951 * Internal function to format the e-mail validation/invalidation URLs.
2952 * This uses $wgArticlePath directly as a quickie hack to use the
2953 * hardcoded English names of the Special: pages, for ASCII safety.
2955 * @note Since these URLs get dropped directly into emails, using the
2956 * short English names avoids insanely long URL-encoded links, which
2957 * also sometimes can get corrupted in some browsers/mailers
2958 * (bug 6957 with Gmail and Internet Explorer).
2960 * @param $page \type{\string} Special page
2961 * @param $token \type{\string} Token
2962 * @return \type{\string} Formatted URL
2964 protected function getTokenUrl( $page, $token ) {
2965 global $wgArticlePath;
2969 "Special:$page/$token",
2974 * Mark the e-mail address confirmed.
2976 * @note Call saveSettings() after calling this function to commit the change.
2978 function confirmEmail() {
2979 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2984 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2985 * address if it was already confirmed.
2987 * @note Call saveSettings() after calling this function to commit the change.
2989 function invalidateEmail() {
2991 $this->mEmailToken
= null;
2992 $this->mEmailTokenExpires
= null;
2993 $this->setEmailAuthenticationTimestamp( null );
2998 * Set the e-mail authentication timestamp.
2999 * @param $timestamp \type{\string} TS_MW timestamp
3001 function setEmailAuthenticationTimestamp( $timestamp ) {
3003 $this->mEmailAuthenticated
= $timestamp;
3004 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3008 * Is this user allowed to send e-mails within limits of current
3009 * site configuration?
3011 * @return \type{\bool} True if allowed
3013 * @return \type{\bool}
3016 function canSendEmail() {
3017 $canSend = $this->isEmailConfirmed();
3018 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3023 * Is this user allowed to receive e-mails within limits of current
3024 * site configuration?
3026 * @return \type{\bool} True if allowed
3028 * @return \type{\bool}
3031 function canReceiveEmail() {
3032 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3036 * Is this user's e-mail address valid-looking and confirmed within
3037 * limits of the current site configuration?
3039 * @note If $wgEmailAuthentication is on, this may require the user to have
3040 * confirmed their address by returning a code or using a password
3041 * sent to the address from the wiki.
3044 * @return \type{\bool} True if conffirmed
3046 * @return \type{\bool}
3049 function isEmailConfirmed() {
3050 global $wgEmailAuthentication;
3053 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3054 if( $this->isAnon() )
3056 if( !self
::isValidEmailAddr( $this->mEmail
) )
3058 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3067 * Check whether there is an outstanding request for e-mail confirmation.
3069 * @return \type{\bool} True if pending
3071 * @return \type{\bool}
3074 function isEmailConfirmationPending() {
3075 global $wgEmailAuthentication;
3076 return $wgEmailAuthentication &&
3077 !$this->isEmailConfirmed() &&
3078 $this->mEmailToken
&&
3079 $this->mEmailTokenExpires
> wfTimestamp();
3083 * Get the timestamp of account creation.
3085 * @return \twotypes{\string,\bool} string Timestamp of account creation, or false for
3086 * non-existent/anonymous user accounts.
3088 public function getRegistration() {
3089 return $this->mId
> 0
3090 ?
$this->mRegistration
3095 * Get the permissions associated with a given list of groups
3097 * @param $groups \arrayof{\string} List of internal group names
3098 * @return \arrayof{\string} List of permission key names for given groups combined
3100 static function getGroupPermissions( $groups ) {
3101 global $wgGroupPermissions;
3103 foreach( $groups as $group ) {
3104 if( isset( $wgGroupPermissions[$group] ) ) {
3105 $rights = array_merge( $rights,
3106 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3113 * Get all the groups who have a given permission
3115 * @param $role \type{\string} Role to check
3116 * @return \arrayof{\string} List of internal group names with the given permission
3118 static function getGroupsWithPermission( $role ) {
3119 global $wgGroupPermissions;
3120 $allowedGroups = array();
3121 foreach ( $wgGroupPermissions as $group => $rights ) {
3122 if ( isset( $rights[$role] ) && $rights[$role] ) {
3123 $allowedGroups[] = $group;
3126 return $allowedGroups;
3130 * Get the localized descriptive name for a group, if it exists
3133 * @param $group \type{\string} Internal group name
3134 * @return \type{\string} Localized descriptive group name
3136 * @param $group \type{\string} Internal group name
3137 * @return \type{\string}
3140 static function getGroupName( $group ) {
3141 global $wgMessageCache;
3142 $wgMessageCache->loadAllMessages();
3143 $key = "group-$group";
3144 $name = wfMsg( $key );
3145 return $name == '' ||
wfEmptyMsg( $key, $name )
3151 * Get the localized descriptive name for a member of a group, if it exists
3154 * @param $group \type{\string} Internal group name
3155 * @return \type{\string} Localized name for group member
3157 * @param $group \type{\string} Internal group name
3158 * @return \type{\string}
3161 static function getGroupMember( $group ) {
3162 global $wgMessageCache;
3163 $wgMessageCache->loadAllMessages();
3164 $key = "group-$group-member";
3165 $name = wfMsg( $key );
3166 return $name == '' ||
wfEmptyMsg( $key, $name )
3172 * Return the set of defined explicit groups.
3173 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3174 * are not included, as they are defined automatically, not in the database.
3175 * @return \arrayof{\string} Array of internal group names
3177 static function getAllGroups() {
3178 global $wgGroupPermissions;
3180 array_keys( $wgGroupPermissions ),
3181 self
::getImplicitGroups()
3186 * Get a list of all available permissions.
3187 * @return \arrayof{\string} Array of permission names
3189 static function getAllRights() {
3190 if ( self
::$mAllRights === false ) {
3191 global $wgAvailableRights;
3192 if ( count( $wgAvailableRights ) ) {
3193 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3195 self
::$mAllRights = self
::$mCoreRights;
3197 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3199 return self
::$mAllRights;
3203 * Get a list of implicit groups
3204 * @return \arrayof{\string} Array of internal group names
3206 public static function getImplicitGroups() {
3207 global $wgImplicitGroups;
3208 $groups = $wgImplicitGroups;
3209 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3214 * Get the title of a page describing a particular group
3216 * @param $group \type{\string} Internal group name
3217 * @return \twotypes{Title,\bool} Title of the page if it exists, false otherwise
3219 static function getGroupPage( $group ) {
3220 global $wgMessageCache;
3221 $wgMessageCache->loadAllMessages();
3222 $page = wfMsgForContent( 'grouppage-' . $group );
3223 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3224 $title = Title
::newFromText( $page );
3225 if( is_object( $title ) )
3232 * Create a link to the group in HTML, if available;
3233 * else return the group name.
3235 * @param $group \type{\string} Internal name of the group
3236 * @param $text \type{\string} The text of the link
3237 * @return \type{\string} HTML link to the group
3239 static function makeGroupLinkHTML( $group, $text = '' ) {
3241 $text = self
::getGroupName( $group );
3243 $title = self
::getGroupPage( $group );
3246 $sk = $wgUser->getSkin();
3247 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3254 * Create a link to the group in Wikitext, if available;
3255 * else return the group name.
3257 * @param $group \type{\string} Internal name of the group
3258 * @param $text \type{\string} The text of the link
3259 * @return \type{\string} Wikilink to the group
3261 static function makeGroupLinkWiki( $group, $text = '' ) {
3263 $text = self
::getGroupName( $group );
3265 $title = self
::getGroupPage( $group );
3267 $page = $title->getPrefixedText();
3268 return "[[$page|$text]]";
3275 * Increment the user's edit-count field.
3276 * Will have no effect for anonymous users.
3278 function incEditCount() {
3279 if( !$this->isAnon() ) {
3280 $dbw = wfGetDB( DB_MASTER
);
3281 $dbw->update( 'user',
3282 array( 'user_editcount=user_editcount+1' ),
3283 array( 'user_id' => $this->getId() ),
3286 // Lazy initialization check...
3287 if( $dbw->affectedRows() == 0 ) {
3288 // Pull from a slave to be less cruel to servers
3289 // Accuracy isn't the point anyway here
3290 $dbr = wfGetDB( DB_SLAVE
);
3291 $count = $dbr->selectField( 'revision',
3293 array( 'rev_user' => $this->getId() ),
3296 // Now here's a goddamn hack...
3297 if( $dbr !== $dbw ) {
3298 // If we actually have a slave server, the count is
3299 // at least one behind because the current transaction
3300 // has not been committed and replicated.
3303 // But if DB_SLAVE is selecting the master, then the
3304 // count we just read includes the revision that was
3305 // just added in the working transaction.
3308 $dbw->update( 'user',
3309 array( 'user_editcount' => $count ),
3310 array( 'user_id' => $this->getId() ),
3314 // edit count in user cache too
3315 $this->invalidateCache();
3319 * Get the description of a given right
3322 * @param $right \type{\string} Right to query
3323 * @return \type{\string} Localized description of the right
3325 * @param $right \type{\string} Right to query
3326 * @return \type{\string}
3329 static function getRightDescription( $right ) {
3330 global $wgMessageCache;
3331 $wgMessageCache->loadAllMessages();
3332 $key = "right-$right";
3333 $name = wfMsg( $key );
3334 return $name == '' ||
wfEmptyMsg( $key, $name )
3340 * Make an old-style password hash
3342 * @param $password \type{\string} Plain-text password
3343 * @param $userId \type{\string} %User ID
3344 * @return \type{\string} Password hash
3346 static function oldCrypt( $password, $userId ) {
3347 global $wgPasswordSalt;
3348 if ( $wgPasswordSalt ) {
3349 return md5( $userId . '-' . md5( $password ) );
3351 return md5( $password );
3356 * Make a new-style password hash
3358 * @param $password \type{\string} Plain-text password
3359 * @param $salt \type{\string} Optional salt, may be random or the user ID.
3360 * If unspecified or false, will generate one automatically
3361 * @return \type{\string} Password hash
3363 static function crypt( $password, $salt = false ) {
3364 global $wgPasswordSalt;
3366 if($wgPasswordSalt) {
3367 if ( $salt === false ) {
3368 $salt = substr( wfGenerateToken(), 0, 8 );
3370 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3372 return ':A:' . md5( $password);
3377 * Compare a password hash with a plain-text password. Requires the user
3378 * ID if there's a chance that the hash is an old-style hash.
3381 * @param $hash \type{\string} Password hash
3382 * @param $password \type{\string} Plain-text password to compare
3383 * @param $userId \type{\string} %User ID for old-style password salt
3384 * @return \type{\bool} True if matches, false otherwise
3386 * @param $hash \type{\string} Password hash
3387 * @param $password \type{\string} Plain-text password to compare
3388 * @param $userId \type{\string} %User ID for old-style password salt
3389 * @return \type{\bool}
3392 static function comparePasswords( $hash, $password, $userId = false ) {
3394 $type = substr( $hash, 0, 3 );
3395 if ( $type == ':A:' ) {
3397 return md5( $password ) === substr( $hash, 3 );
3398 } elseif ( $type == ':B:' ) {
3400 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3401 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3404 return self
::oldCrypt( $password, $userId ) === $hash;