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.
464 * @param $name \type{\string} String to match
465 * @return \type{\bool} True or false
467 static function isIP( $name ) {
468 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
472 * Is the input a valid username?
474 * Checks if the input is a valid username, we don't want an empty string,
475 * an IP address, anything that containins slashes (would mess up subpages),
476 * is longer than the maximum allowed username size or doesn't begin with
479 * @param $name \type{\string} String to match
480 * @return \type{\bool} True or false
482 static function isValidUserName( $name ) {
483 global $wgContLang, $wgMaxNameChars;
486 || User
::isIP( $name )
487 ||
strpos( $name, '/' ) !== false
488 ||
strlen( $name ) > $wgMaxNameChars
489 ||
$name != $wgContLang->ucfirst( $name ) ) {
490 wfDebugLog( 'username', __METHOD__
.
491 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
495 // Ensure that the name can't be misresolved as a different title,
496 // such as with extra namespace keys at the start.
497 $parsed = Title
::newFromText( $name );
498 if( is_null( $parsed )
499 ||
$parsed->getNamespace()
500 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
501 wfDebugLog( 'username', __METHOD__
.
502 ": '$name' invalid due to ambiguous prefixes" );
506 // Check an additional blacklist of troublemaker characters.
507 // Should these be merged into the title char list?
508 $unicodeBlacklist = '/[' .
509 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
510 '\x{00a0}' . # non-breaking space
511 '\x{2000}-\x{200f}' . # various whitespace
512 '\x{2028}-\x{202f}' . # breaks and control chars
513 '\x{3000}' . # ideographic space
514 '\x{e000}-\x{f8ff}' . # private use
516 if( preg_match( $unicodeBlacklist, $name ) ) {
517 wfDebugLog( 'username', __METHOD__
.
518 ": '$name' invalid due to blacklisted characters" );
526 * Usernames which fail to pass this function will be blocked
527 * from user login and new account registrations, but may be used
528 * internally by batch processes.
530 * If an account already exists in this form, login will be blocked
531 * by a failure to pass this function.
533 * @param $name \type{\string} String to match
534 * @return \type{\bool} True or false
536 static function isUsableName( $name ) {
537 global $wgReservedUsernames;
538 // Must be a valid username, obviously ;)
539 if ( !self
::isValidUserName( $name ) ) {
543 static $reservedUsernames = false;
544 if ( !$reservedUsernames ) {
545 $reservedUsernames = $wgReservedUsernames;
546 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
549 // Certain names may be reserved for batch processes.
550 foreach ( $reservedUsernames as $reserved ) {
551 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
552 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
554 if ( $reserved == $name ) {
562 * Usernames which fail to pass this function will be blocked
563 * from new account registrations, but may be used internally
564 * either by batch processes or by user accounts which have
565 * already been created.
567 * Additional character blacklisting may be added here
568 * rather than in isValidUserName() to avoid disrupting
571 * @param $name \type{\string} String to match
572 * @return \type{\bool} True or false
574 static function isCreatableName( $name ) {
576 self
::isUsableName( $name ) &&
578 // Registration-time character blacklisting...
579 strpos( $name, '@' ) === false;
583 * Is the input a valid password for this user?
585 * @param $password \type{\string} Desired password
586 * @return \type{\bool} True or false
588 function isValidPassword( $password ) {
589 global $wgMinimalPasswordLength, $wgContLang;
592 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
594 if( $result === false )
597 // Password needs to be long enough, and can't be the same as the username
598 return strlen( $password ) >= $wgMinimalPasswordLength
599 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
603 * Does a string look like an e-mail address?
605 * There used to be a regular expression here, it got removed because it
606 * rejected valid addresses. Actually just check if there is '@' somewhere
607 * in the given address.
609 * @todo Check for RFC 2822 compilance (bug 959)
611 * @param $addr \type{\string} E-mail address
612 * @return \type{\bool} True or false
614 public static function isValidEmailAddr( $addr ) {
616 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
620 return strpos( $addr, '@' ) !== false;
624 * Given unvalidated user input, return a canonical username, or false if
625 * the username is invalid.
626 * @param $name \type{\string} User input
627 * @param $validate \twotypes{\string,\bool} Type of validation to use:
628 * - false No validation
629 * - 'valid' Valid for batch processes
630 * - 'usable' Valid for batch processes and login
631 * - 'creatable' Valid for batch processes, login and account creation
633 static function getCanonicalName( $name, $validate = 'valid' ) {
634 # Force usernames to capital
636 $name = $wgContLang->ucfirst( $name );
638 # Reject names containing '#'; these will be cleaned up
639 # with title normalisation, but then it's too late to
641 if( strpos( $name, '#' ) !== false )
644 # Clean up name according to title rules
645 $t = Title
::newFromText( $name );
646 if( is_null( $t ) ) {
650 # Reject various classes of invalid names
651 $name = $t->getText();
653 $name = $wgAuth->getCanonicalName( $t->getText() );
655 switch ( $validate ) {
659 if ( !User
::isValidUserName( $name ) ) {
664 if ( !User
::isUsableName( $name ) ) {
669 if ( !User
::isCreatableName( $name ) ) {
674 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
680 * Count the number of edits of a user
681 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
683 * @param $uid \type{\int} %User ID to check
684 * @return \type{\int} The user's edit count
686 static function edits( $uid ) {
687 wfProfileIn( __METHOD__
);
688 $dbr = wfGetDB( DB_SLAVE
);
689 // check if the user_editcount field has been initialized
690 $field = $dbr->selectField(
691 'user', 'user_editcount',
692 array( 'user_id' => $uid ),
696 if( $field === null ) { // it has not been initialized. do so.
697 $dbw = wfGetDB( DB_MASTER
);
698 $count = $dbr->selectField(
699 'revision', 'count(*)',
700 array( 'rev_user' => $uid ),
705 array( 'user_editcount' => $count ),
706 array( 'user_id' => $uid ),
712 wfProfileOut( __METHOD__
);
717 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
718 * @todo hash random numbers to improve security, like generateToken()
720 * @return \type{\string} New random password
722 static function randomPassword() {
723 global $wgMinimalPasswordLength;
724 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
725 $l = strlen( $pwchars ) - 1;
727 $pwlength = max( 7, $wgMinimalPasswordLength );
728 $digit = mt_rand(0, $pwlength - 1);
730 for ( $i = 0; $i < $pwlength; $i++
) {
731 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
737 * Set cached properties to default.
739 * @note This no longer clears uncached lazy-initialised properties;
740 * the constructor does that instead.
743 function loadDefaults( $name = false ) {
744 wfProfileIn( __METHOD__
);
746 global $wgCookiePrefix;
749 $this->mName
= $name;
750 $this->mRealName
= '';
751 $this->mPassword
= $this->mNewpassword
= '';
752 $this->mNewpassTime
= null;
754 $this->mOptions
= null; # Defer init
756 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
757 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
759 $this->mTouched
= '0'; # Allow any pages to be cached
762 $this->setToken(); # Random
763 $this->mEmailAuthenticated
= null;
764 $this->mEmailToken
= '';
765 $this->mEmailTokenExpires
= null;
766 $this->mRegistration
= wfTimestamp( TS_MW
);
767 $this->mGroups
= array();
769 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
771 wfProfileOut( __METHOD__
);
775 * @deprecated Use wfSetupSession().
777 function SetupSession() {
778 wfDeprecated( __METHOD__
);
783 * Load user data from the session or login cookie. If there are no valid
784 * credentials, initialises the user as an anonymous user.
785 * @return \type{\bool} True if the user is logged in, false otherwise.
787 private function loadFromSession() {
788 global $wgMemc, $wgCookiePrefix;
791 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
792 if ( $result !== null ) {
796 if ( isset( $_SESSION['wsUserID'] ) ) {
797 if ( 0 != $_SESSION['wsUserID'] ) {
798 $sId = $_SESSION['wsUserID'];
800 $this->loadDefaults();
803 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
804 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
805 $_SESSION['wsUserID'] = $sId;
807 $this->loadDefaults();
810 if ( isset( $_SESSION['wsUserName'] ) ) {
811 $sName = $_SESSION['wsUserName'];
812 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
813 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
814 $_SESSION['wsUserName'] = $sName;
816 $this->loadDefaults();
820 $passwordCorrect = FALSE;
822 if ( !$this->loadFromId() ) {
823 # Not a valid ID, loadFromId has switched the object to anon for us
827 if ( isset( $_SESSION['wsToken'] ) ) {
828 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
830 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
831 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
834 # No session or persistent login cookie
835 $this->loadDefaults();
839 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
840 $_SESSION['wsToken'] = $this->mToken
;
841 wfDebug( "Logged in from $from\n" );
844 # Invalid credentials
845 wfDebug( "Can't log in from $from, invalid credentials\n" );
846 $this->loadDefaults();
852 * Load user and user_group data from the database.
853 * $this::mId must be set, this is how the user is identified.
855 * @return \type{\bool} True if the user exists, false if the user is anonymous
858 function loadFromDatabase() {
860 $this->mId
= intval( $this->mId
);
862 /** Anonymous user */
864 $this->loadDefaults();
868 $dbr = wfGetDB( DB_MASTER
);
869 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
871 if ( $s !== false ) {
872 # Initialise user table data
873 $this->loadFromRow( $s );
874 $this->mGroups
= null; // deferred
875 $this->getEditCount(); // revalidation for nulls
880 $this->loadDefaults();
886 * Initialize this object from a row from the user table.
888 * @param $row \arrayof{\mixed} Row from the user table to load.
890 function loadFromRow( $row ) {
891 $this->mDataLoaded
= true;
893 if ( isset( $row->user_id
) ) {
894 $this->mId
= $row->user_id
;
896 $this->mName
= $row->user_name
;
897 $this->mRealName
= $row->user_real_name
;
898 $this->mPassword
= $row->user_password
;
899 $this->mNewpassword
= $row->user_newpassword
;
900 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
901 $this->mEmail
= $row->user_email
;
902 $this->decodeOptions( $row->user_options
);
903 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
904 $this->mToken
= $row->user_token
;
905 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
906 $this->mEmailToken
= $row->user_email_token
;
907 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
908 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
909 $this->mEditCount
= $row->user_editcount
;
913 * Load the groups from the database if they aren't already loaded.
916 function loadGroups() {
917 if ( is_null( $this->mGroups
) ) {
918 $dbr = wfGetDB( DB_MASTER
);
919 $res = $dbr->select( 'user_groups',
921 array( 'ug_user' => $this->mId
),
923 $this->mGroups
= array();
924 while( $row = $dbr->fetchObject( $res ) ) {
925 $this->mGroups
[] = $row->ug_group
;
931 * Clear various cached data stored in this object.
932 * @param $reloadFrom \type{\string} Reload user and user_groups table data from a
933 * given source. May be "name", "id", "defaults", "session", or false for
936 function clearInstanceCache( $reloadFrom = false ) {
937 $this->mNewtalk
= -1;
938 $this->mDatePreference
= null;
939 $this->mBlockedby
= -1; # Unset
940 $this->mHash
= false;
942 $this->mRights
= null;
943 $this->mEffectiveGroups
= null;
946 $this->mDataLoaded
= false;
947 $this->mFrom
= $reloadFrom;
952 * Combine the language default options with any site-specific options
953 * and add the default language variants.
955 * @return \arrayof{\string} Array of options
957 static function getDefaultOptions() {
958 global $wgNamespacesToBeSearchedDefault;
960 * Site defaults will override the global/language defaults
962 global $wgDefaultUserOptions, $wgContLang;
963 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
966 * default language setting
968 $variant = $wgContLang->getPreferredVariant( false );
969 $defOpt['variant'] = $variant;
970 $defOpt['language'] = $variant;
972 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
973 $defOpt['searchNs'.$nsnum] = $val;
979 * Get a given default option value.
981 * @param $opt \type{\string} Name of option to retrieve
982 * @return \type{\string} Default option value
984 public static function getDefaultOption( $opt ) {
985 $defOpts = self
::getDefaultOptions();
986 if( isset( $defOpts[$opt] ) ) {
987 return $defOpts[$opt];
994 * Get a list of user toggle names
995 * @return \arrayof{\string} Array of user toggle names
997 static function getToggles() {
999 $extraToggles = array();
1000 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1001 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1006 * Get blocking information
1008 * @param $bFromSlave \type{\bool} Whether to check the slave database first. To
1009 * improve performance, non-critical checks are done
1010 * against slaves. Check when actually saving should be
1011 * done against master.
1013 function getBlockedStatus( $bFromSlave = true ) {
1014 global $wgEnableSorbs, $wgProxyWhitelist;
1016 if ( -1 != $this->mBlockedby
) {
1017 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1021 wfProfileIn( __METHOD__
);
1022 wfDebug( __METHOD__
.": checking...\n" );
1024 // Initialize data...
1025 // Otherwise something ends up stomping on $this->mBlockedby when
1026 // things get lazy-loaded later, causing false positive block hits
1027 // due to -1 !== 0. Probably session-related... Nothing should be
1028 // overwriting mBlockedby, surely?
1031 $this->mBlockedby
= 0;
1032 $this->mHideName
= 0;
1035 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1036 # Exempt from all types of IP-block
1041 $this->mBlock
= new Block();
1042 $this->mBlock
->fromMaster( !$bFromSlave );
1043 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1044 wfDebug( __METHOD__
.": Found block.\n" );
1045 $this->mBlockedby
= $this->mBlock
->mBy
;
1046 $this->mBlockreason
= $this->mBlock
->mReason
;
1047 $this->mHideName
= $this->mBlock
->mHideName
;
1048 if ( $this->isLoggedIn() ) {
1049 $this->spreadBlock();
1052 $this->mBlock
= null;
1053 wfDebug( __METHOD__
.": No block.\n" );
1057 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1059 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1060 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1061 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1065 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1066 if ( $this->inSorbsBlacklist( $ip ) ) {
1067 $this->mBlockedby
= wfMsg( 'sorbs' );
1068 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1074 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1076 wfProfileOut( __METHOD__
);
1080 * Whether the given IP is in the SORBS blacklist.
1082 * @param $ip \type{\string} IP to check
1083 * @return \type{\bool} True if blacklisted
1085 function inSorbsBlacklist( $ip ) {
1086 global $wgEnableSorbs, $wgSorbsUrl;
1088 return $wgEnableSorbs &&
1089 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1093 * Whether the given IP is in a given DNS blacklist.
1095 * @param $ip \type{\string} IP to check
1096 * @param $base \type{\string} URL of the DNS blacklist
1097 * @return \type{\bool} True if blacklisted
1099 function inDnsBlacklist( $ip, $base ) {
1100 wfProfileIn( __METHOD__
);
1106 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
1108 for ( $i=4; $i>=1; $i-- ) {
1109 $host .= $m[$i] . '.';
1114 $ipList = gethostbynamel( $host );
1117 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1120 wfDebug( "Requested $host, not found in $base.\n" );
1124 wfProfileOut( __METHOD__
);
1129 * Is this user subject to rate limiting?
1131 * @return \type{\bool} True if rate limited
1133 public function isPingLimitable() {
1134 global $wgRateLimitsExcludedGroups;
1135 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1136 // Deprecated, but kept for backwards-compatibility config
1139 return !$this->isAllowed('noratelimit');
1143 * Primitive rate limits: enforce maximum actions per time period
1144 * to put a brake on flooding.
1146 * @note When using a shared cache like memcached, IP-address
1147 * last-hit counters will be shared across wikis.
1149 * @param $action \type{\string} Action to enforce; 'edit' if unspecified
1150 * @return \type{\bool} True if a rate limiter was tripped
1152 function pingLimiter( $action='edit' ) {
1154 # Call the 'PingLimiter' hook
1156 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1160 global $wgRateLimits;
1161 if( !isset( $wgRateLimits[$action] ) ) {
1165 # Some groups shouldn't trigger the ping limiter, ever
1166 if( !$this->isPingLimitable() )
1169 global $wgMemc, $wgRateLimitLog;
1170 wfProfileIn( __METHOD__
);
1172 $limits = $wgRateLimits[$action];
1174 $id = $this->getId();
1178 if( isset( $limits['anon'] ) && $id == 0 ) {
1179 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1182 if( isset( $limits['user'] ) && $id != 0 ) {
1183 $userLimit = $limits['user'];
1185 if( $this->isNewbie() ) {
1186 if( isset( $limits['newbie'] ) && $id != 0 ) {
1187 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1189 if( isset( $limits['ip'] ) ) {
1190 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1193 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1194 $subnet = $matches[1];
1195 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1198 // Check for group-specific permissions
1199 // If more than one group applies, use the group with the highest limit
1200 foreach ( $this->getGroups() as $group ) {
1201 if ( isset( $limits[$group] ) ) {
1202 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1203 $userLimit = $limits[$group];
1207 // Set the user limit key
1208 if ( $userLimit !== false ) {
1209 wfDebug( __METHOD__
.": effective user limit: $userLimit\n" );
1210 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1214 foreach( $keys as $key => $limit ) {
1215 list( $max, $period ) = $limit;
1216 $summary = "(limit $max in {$period}s)";
1217 $count = $wgMemc->get( $key );
1219 if( $count > $max ) {
1220 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1221 if( $wgRateLimitLog ) {
1222 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1226 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1229 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1230 $wgMemc->add( $key, 1, intval( $period ) );
1232 $wgMemc->incr( $key );
1235 wfProfileOut( __METHOD__
);
1240 * Check if user is blocked
1242 * @param $bFromSlave \type{\bool} Whether to check the slave database instead of the master
1243 * @return \type{\bool} True if blocked, false otherwise
1245 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1246 wfDebug( "User::isBlocked: enter\n" );
1247 $this->getBlockedStatus( $bFromSlave );
1248 return $this->mBlockedby
!== 0;
1252 * Check if user is blocked from editing a particular article
1254 * @param $title \type{\string} Title to check
1255 * @param $bFromSlave \type{\bool} Whether to check the slave database instead of the master
1256 * @return \type{\bool} True if blocked, false otherwise
1258 function isBlockedFrom( $title, $bFromSlave = false ) {
1259 global $wgBlockAllowsUTEdit;
1260 wfProfileIn( __METHOD__
);
1261 wfDebug( __METHOD__
.": enter\n" );
1263 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1264 $blocked = $this->isBlocked( $bFromSlave );
1265 # If a user's name is suppressed, they cannot make edits anywhere
1266 if ( !$this->mHideName
&& $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1267 $title->getNamespace() == NS_USER_TALK
) {
1269 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1271 wfProfileOut( __METHOD__
);
1276 * If user is blocked, return the name of the user who placed the block
1277 * @return \type{\string} name of blocker
1279 function blockedBy() {
1280 $this->getBlockedStatus();
1281 return $this->mBlockedby
;
1285 * If user is blocked, return the specified reason for the block
1286 * @return \type{\string} Blocking reason
1288 function blockedFor() {
1289 $this->getBlockedStatus();
1290 return $this->mBlockreason
;
1294 * Get the user's ID.
1295 * @return \type{\int} The user's ID; 0 if the user is anonymous or nonexistent
1298 if( $this->mId
=== null and $this->mName
!== null
1299 and User
::isIP( $this->mName
) ) {
1300 // Special case, we know the user is anonymous
1302 } elseif( $this->mId
=== null ) {
1303 // Don't load if this was initialized from an ID
1310 * Set the user and reload all fields according to a given ID
1311 * @param $v \type{\int} %User ID to reload
1313 function setId( $v ) {
1315 $this->clearInstanceCache( 'id' );
1319 * Get the user name, or the IP of an anonymous user
1320 * @return \type{\string} User's name or IP address
1322 function getName() {
1323 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1324 # Special case optimisation
1325 return $this->mName
;
1328 if ( $this->mName
=== false ) {
1330 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1332 return $this->mName
;
1337 * Set the user name.
1339 * This does not reload fields from the database according to the given
1340 * name. Rather, it is used to create a temporary "nonexistent user" for
1341 * later addition to the database. It can also be used to set the IP
1342 * address for an anonymous user to something other than the current
1345 * @note User::newFromName() has rougly the same function, when the named user
1347 * @param $str \type{\string} New user name to set
1349 function setName( $str ) {
1351 $this->mName
= $str;
1355 * Get the user's name escaped by underscores.
1356 * @return \type{\string} Username escaped by underscores
1358 function getTitleKey() {
1359 return str_replace( ' ', '_', $this->getName() );
1363 * Check if the user has new messages.
1364 * @return \type{\bool} True if the user has new messages
1366 function getNewtalk() {
1369 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1370 if( $this->mNewtalk
=== -1 ) {
1371 $this->mNewtalk
= false; # reset talk page status
1373 # Check memcached separately for anons, who have no
1374 # entire User object stored in there.
1377 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1378 $newtalk = $wgMemc->get( $key );
1379 if( strval( $newtalk ) !== '' ) {
1380 $this->mNewtalk
= (bool)$newtalk;
1382 // Since we are caching this, make sure it is up to date by getting it
1384 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1385 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1388 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1392 return (bool)$this->mNewtalk
;
1396 * Return the talk page(s) this user has new messages on.
1397 * @return \arrayof{\string} Array of page URLs
1399 function getNewMessageLinks() {
1401 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1404 if (!$this->getNewtalk())
1406 $up = $this->getUserPage();
1407 $utp = $up->getTalkPage();
1408 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1413 * Internal uncached check for new messages
1416 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1417 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1418 * @param $fromMaster \type{\bool} true to fetch from the master, false for a slave
1419 * @return \type{\bool} True if the user has new messages
1422 function checkNewtalk( $field, $id, $fromMaster = false ) {
1423 if ( $fromMaster ) {
1424 $db = wfGetDB( DB_MASTER
);
1426 $db = wfGetDB( DB_SLAVE
);
1428 $ok = $db->selectField( 'user_newtalk', $field,
1429 array( $field => $id ), __METHOD__
);
1430 return $ok !== false;
1434 * Add or update the new messages flag
1435 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1436 * @param $id \twotypes{string,\int} User's IP address for anonymous users, %User ID otherwise
1437 * @return \type{\bool} True if successful, false otherwise
1440 function updateNewtalk( $field, $id ) {
1441 $dbw = wfGetDB( DB_MASTER
);
1442 $dbw->insert( 'user_newtalk',
1443 array( $field => $id ),
1446 if ( $dbw->affectedRows() ) {
1447 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1450 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1456 * Clear the new messages flag for the given user
1457 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1458 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1459 * @return \type{\bool} True if successful, false otherwise
1462 function deleteNewtalk( $field, $id ) {
1463 $dbw = wfGetDB( DB_MASTER
);
1464 $dbw->delete( 'user_newtalk',
1465 array( $field => $id ),
1467 if ( $dbw->affectedRows() ) {
1468 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1471 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1477 * Update the 'You have new messages!' status.
1478 * @param $val \type{\bool} Whether the user has new messages
1480 function setNewtalk( $val ) {
1481 if( wfReadOnly() ) {
1486 $this->mNewtalk
= $val;
1488 if( $this->isAnon() ) {
1490 $id = $this->getName();
1493 $id = $this->getId();
1498 $changed = $this->updateNewtalk( $field, $id );
1500 $changed = $this->deleteNewtalk( $field, $id );
1503 if( $this->isAnon() ) {
1504 // Anons have a separate memcached space, since
1505 // user records aren't kept for them.
1506 $key = wfMemcKey( 'newtalk', 'ip', $id );
1507 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1510 $this->invalidateCache();
1515 * Generate a current or new-future timestamp to be stored in the
1516 * user_touched field when we update things.
1517 * @return \type{\string} Timestamp in TS_MW format
1519 private static function newTouchedTimestamp() {
1520 global $wgClockSkewFudge;
1521 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1525 * Clear user data from memcached.
1526 * Use after applying fun updates to the database; caller's
1527 * responsibility to update user_touched if appropriate.
1529 * Called implicitly from invalidateCache() and saveSettings().
1531 private function clearSharedCache() {
1534 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1539 * Immediately touch the user data cache for this account.
1540 * Updates user_touched field, and removes account data from memcached
1541 * for reload on the next hit.
1543 function invalidateCache() {
1546 $this->mTouched
= self
::newTouchedTimestamp();
1548 $dbw = wfGetDB( DB_MASTER
);
1549 $dbw->update( 'user',
1550 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1551 array( 'user_id' => $this->mId
),
1554 $this->clearSharedCache();
1559 * Validate the cache for this account.
1560 * @param $timestamp \type{\string} A timestamp in TS_MW format
1562 function validateCache( $timestamp ) {
1564 return ($timestamp >= $this->mTouched
);
1568 * Set the password and reset the random token.
1569 * Calls through to authentication plugin if necessary;
1570 * will have no effect if the auth plugin refuses to
1571 * pass the change through or if the legal password
1574 * As a special case, setting the password to null
1575 * wipes it, so the account cannot be logged in until
1576 * a new password is set, for instance via e-mail.
1578 * @param $str \type{\string} New password to set
1579 * @throws PasswordError on failure
1581 function setPassword( $str ) {
1584 if( $str !== null ) {
1585 if( !$wgAuth->allowPasswordChange() ) {
1586 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1589 if( !$this->isValidPassword( $str ) ) {
1590 global $wgMinimalPasswordLength;
1591 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1592 $wgMinimalPasswordLength ) );
1596 if( !$wgAuth->setPassword( $this, $str ) ) {
1597 throw new PasswordError( wfMsg( 'externaldberror' ) );
1600 $this->setInternalPassword( $str );
1606 * Set the password and reset the random token unconditionally.
1608 * @param $str \type{\string} New password to set
1610 function setInternalPassword( $str ) {
1614 if( $str === null ) {
1615 // Save an invalid hash...
1616 $this->mPassword
= '';
1618 $this->mPassword
= self
::crypt( $str );
1620 $this->mNewpassword
= '';
1621 $this->mNewpassTime
= null;
1625 * Get the user's current token.
1626 * @return \type{\string} Token
1628 function getToken() {
1630 return $this->mToken
;
1634 * Set the random token (used for persistent authentication)
1635 * Called from loadDefaults() among other places.
1637 * @param $token \type{\string} If specified, set the token to this value
1640 function setToken( $token = false ) {
1641 global $wgSecretKey, $wgProxyKey;
1644 if ( $wgSecretKey ) {
1645 $key = $wgSecretKey;
1646 } elseif ( $wgProxyKey ) {
1651 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1653 $this->mToken
= $token;
1658 * Set the cookie password
1660 * @param $str \type{\string} New cookie password
1663 function setCookiePassword( $str ) {
1665 $this->mCookiePassword
= md5( $str );
1669 * Set the password for a password reminder or new account email
1671 * @param $str \type{\string} New password to set
1672 * @param $throttle \type{\bool} If true, reset the throttle timestamp to the present
1674 function setNewpassword( $str, $throttle = true ) {
1676 $this->mNewpassword
= self
::crypt( $str );
1678 $this->mNewpassTime
= wfTimestampNow();
1683 * Has password reminder email been sent within the last
1684 * $wgPasswordReminderResendTime hours?
1685 * @return \type{\bool} True or false
1687 function isPasswordReminderThrottled() {
1688 global $wgPasswordReminderResendTime;
1690 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1693 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1694 return time() < $expiry;
1698 * Get the user's e-mail address
1699 * @return \type{\string} User's e-mail address
1701 function getEmail() {
1703 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1704 return $this->mEmail
;
1708 * Get the timestamp of the user's e-mail authentication
1709 * @return \type{\string} TS_MW timestamp
1711 function getEmailAuthenticationTimestamp() {
1713 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1714 return $this->mEmailAuthenticated
;
1718 * Set the user's e-mail address
1719 * @param $str \type{\string} New e-mail address
1721 function setEmail( $str ) {
1723 $this->mEmail
= $str;
1724 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1728 * Get the user's real name
1729 * @return \type{\string} User's real name
1731 function getRealName() {
1733 return $this->mRealName
;
1737 * Set the user's real name
1738 * @param $str \type{\string} New real name
1740 function setRealName( $str ) {
1742 $this->mRealName
= $str;
1746 * Get the user's current setting for a given option.
1748 * @param $oname \type{\string} The option to check
1749 * @param $defaultOverride \type{\string} A default value returned if the option does not exist
1750 * @return \type{\string} User's current value for the option
1751 * @see getBoolOption()
1752 * @see getIntOption()
1754 function getOption( $oname, $defaultOverride = '' ) {
1757 if ( is_null( $this->mOptions
) ) {
1758 if($defaultOverride != '') {
1759 return $defaultOverride;
1761 $this->mOptions
= User
::getDefaultOptions();
1764 if ( array_key_exists( $oname, $this->mOptions
) ) {
1765 return trim( $this->mOptions
[$oname] );
1767 return $defaultOverride;
1772 * Get the user's current setting for a given option, as a boolean value.
1774 * @param $oname \type{\string} The option to check
1775 * @return \type{\bool} User's current value for the option
1778 function getBoolOption( $oname ) {
1779 return (bool)$this->getOption( $oname );
1784 * Get the user's current setting for a given option, as a boolean value.
1786 * @param $oname \type{\string} The option to check
1787 * @param $defaultOverride \type{\int} A default value returned if the option does not exist
1788 * @return \type{\int} User's current value for the option
1791 function getIntOption( $oname, $defaultOverride=0 ) {
1792 $val = $this->getOption( $oname );
1794 $val = $defaultOverride;
1796 return intval( $val );
1800 * Set the given option for a user.
1802 * @param $oname \type{\string} The option to set
1803 * @param $val \type{\mixed} New value to set
1805 function setOption( $oname, $val ) {
1807 if ( is_null( $this->mOptions
) ) {
1808 $this->mOptions
= User
::getDefaultOptions();
1810 if ( $oname == 'skin' ) {
1811 # Clear cached skin, so the new one displays immediately in Special:Preferences
1812 unset( $this->mSkin
);
1814 // Filter out any newlines that may have passed through input validation.
1815 // Newlines are used to separate items in the options blob.
1817 $val = str_replace( "\r\n", "\n", $val );
1818 $val = str_replace( "\r", "\n", $val );
1819 $val = str_replace( "\n", " ", $val );
1821 // Explicitly NULL values should refer to defaults
1822 global $wgDefaultUserOptions;
1823 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1824 $val = $wgDefaultUserOptions[$oname];
1826 $this->mOptions
[$oname] = $val;
1830 * Get the user's preferred date format.
1831 * @return \type{\string} User's preferred date format
1833 function getDatePreference() {
1834 // Important migration for old data rows
1835 if ( is_null( $this->mDatePreference
) ) {
1837 $value = $this->getOption( 'date' );
1838 $map = $wgLang->getDatePreferenceMigrationMap();
1839 if ( isset( $map[$value] ) ) {
1840 $value = $map[$value];
1842 $this->mDatePreference
= $value;
1844 return $this->mDatePreference
;
1848 * Get the permissions this user has.
1849 * @return \arrayof{\string} Array of permission names
1851 function getRights() {
1852 if ( is_null( $this->mRights
) ) {
1853 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1854 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1855 // Force reindexation of rights when a hook has unset one of them
1856 $this->mRights
= array_values( $this->mRights
);
1858 return $this->mRights
;
1862 * Get the list of explicit group memberships this user has.
1863 * The implicit * and user groups are not included.
1864 * @return \arrayof{\string} Array of internal group names
1866 function getGroups() {
1868 return $this->mGroups
;
1872 * Get the list of implicit group memberships this user has.
1873 * This includes all explicit groups, plus 'user' if logged in,
1874 * '*' for all accounts and autopromoted groups
1876 * @param $recache \type{\bool} Whether to avoid the cache
1877 * @return \arrayof{\string} Array of internal group names
1879 function getEffectiveGroups( $recache = false ) {
1880 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1881 $this->mEffectiveGroups
= $this->getGroups();
1882 $this->mEffectiveGroups
[] = '*';
1883 if( $this->getId() ) {
1884 $this->mEffectiveGroups
[] = 'user';
1886 $this->mEffectiveGroups
= array_unique( array_merge(
1887 $this->mEffectiveGroups
,
1888 Autopromote
::getAutopromoteGroups( $this )
1891 # Hook for additional groups
1892 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1895 return $this->mEffectiveGroups
;
1899 * Get the user's edit count.
1900 * @return \type{\int} User's edit count
1902 function getEditCount() {
1904 if ( !isset( $this->mEditCount
) ) {
1905 /* Populate the count, if it has not been populated yet */
1906 $this->mEditCount
= User
::edits($this->mId
);
1908 return $this->mEditCount
;
1916 * Add the user to the given group.
1917 * This takes immediate effect.
1918 * @param $group \type{\string} Name of the group to add
1920 function addGroup( $group ) {
1921 $dbw = wfGetDB( DB_MASTER
);
1922 if( $this->getId() ) {
1923 $dbw->insert( 'user_groups',
1925 'ug_user' => $this->getID(),
1926 'ug_group' => $group,
1929 array( 'IGNORE' ) );
1932 $this->loadGroups();
1933 $this->mGroups
[] = $group;
1934 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1936 $this->invalidateCache();
1940 * Remove the user from the given group.
1941 * This takes immediate effect.
1942 * @param $group \type{\string} Name of the group to remove
1944 function removeGroup( $group ) {
1946 $dbw = wfGetDB( DB_MASTER
);
1947 $dbw->delete( 'user_groups',
1949 'ug_user' => $this->getID(),
1950 'ug_group' => $group,
1952 'User::removeGroup' );
1954 $this->loadGroups();
1955 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1956 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1958 $this->invalidateCache();
1963 * Get whether the user is logged in
1964 * @return \type{\bool} True or false
1966 function isLoggedIn() {
1967 return $this->getID() != 0;
1971 * Get whether the user is anonymous
1972 * @return \type{\bool} True or false
1975 return !$this->isLoggedIn();
1979 * Get whether the user is a bot
1980 * @return \type{\bool} True or false
1984 wfDeprecated( __METHOD__
);
1985 return $this->isAllowed( 'bot' );
1989 * Check if user is allowed to access a feature / make an action
1990 * @param $action \type{\string} action to be checked
1991 * @return \type{\bool} True if action is allowed, else false
1993 function isAllowed($action='') {
1994 if ( $action === '' )
1995 // In the spirit of DWIM
1998 return in_array( $action, $this->getRights() );
2002 * Check whether to enable recent changes patrol features for this user
2003 * @return \type{\bool} True or false
2005 public function useRCPatrol() {
2006 global $wgUseRCPatrol;
2007 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2011 * Check whether to enable new pages patrol features for this user
2012 * @return \type{\bool} True or false
2014 public function useNPPatrol() {
2015 global $wgUseRCPatrol, $wgUseNPPatrol;
2016 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2020 * Get the current skin, loading it if required
2021 * @return \type{Skin} Current skin
2022 * @todo FIXME : need to check the old failback system [AV]
2024 function &getSkin() {
2026 if ( ! isset( $this->mSkin
) ) {
2027 wfProfileIn( __METHOD__
);
2030 $userSkin = $this->getOption( 'skin' );
2031 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2033 $this->mSkin
=& Skin
::newFromKey( $userSkin );
2034 wfProfileOut( __METHOD__
);
2036 return $this->mSkin
;
2040 * Check the watched status of an article.
2041 * @param $title \type{Title} Title of the article to look at
2042 * @return \type{\bool} True if article is watched
2044 function isWatched( $title ) {
2045 $wl = WatchedItem
::fromUserTitle( $this, $title );
2046 return $wl->isWatched();
2051 * @param $title \type{Title} Title of the article to look at
2053 function addWatch( $title ) {
2054 $wl = WatchedItem
::fromUserTitle( $this, $title );
2056 $this->invalidateCache();
2060 * Stop watching an article.
2061 * @param $title \type{Title} Title of the article to look at
2063 function removeWatch( $title ) {
2064 $wl = WatchedItem
::fromUserTitle( $this, $title );
2066 $this->invalidateCache();
2070 * Clear the user's notification timestamp for the given title.
2071 * If e-notif e-mails are on, they will receive notification mails on
2072 * the next change of the page if it's watched etc.
2073 * @param $title \type{Title} Title of the article to look at
2075 function clearNotification( &$title ) {
2076 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2078 # Do nothing if the database is locked to writes
2079 if( wfReadOnly() ) {
2083 if ($title->getNamespace() == NS_USER_TALK
&&
2084 $title->getText() == $this->getName() ) {
2085 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2087 $this->setNewtalk( false );
2090 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2094 if( $this->isAnon() ) {
2095 // Nothing else to do...
2099 // Only update the timestamp if the page is being watched.
2100 // The query to find out if it is watched is cached both in memcached and per-invocation,
2101 // and when it does have to be executed, it can be on a slave
2102 // If this is the user's newtalk page, we always update the timestamp
2103 if ($title->getNamespace() == NS_USER_TALK
&&
2104 $title->getText() == $wgUser->getName())
2107 } elseif ( $this->getId() == $wgUser->getId() ) {
2108 $watched = $title->userIsWatching();
2113 // If the page is watched by the user (or may be watched), update the timestamp on any
2114 // any matching rows
2116 $dbw = wfGetDB( DB_MASTER
);
2117 $dbw->update( 'watchlist',
2119 'wl_notificationtimestamp' => NULL
2120 ), array( /* WHERE */
2121 'wl_title' => $title->getDBkey(),
2122 'wl_namespace' => $title->getNamespace(),
2123 'wl_user' => $this->getID()
2130 * Resets all of the given user's page-change notification timestamps.
2131 * If e-notif e-mails are on, they will receive notification mails on
2132 * the next change of any watched page.
2134 * @param $currentUser \type{\int} %User ID
2136 function clearAllNotifications( $currentUser ) {
2137 global $wgUseEnotif, $wgShowUpdatedMarker;
2138 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2139 $this->setNewtalk( false );
2142 if( $currentUser != 0 ) {
2143 $dbw = wfGetDB( DB_MASTER
);
2144 $dbw->update( 'watchlist',
2146 'wl_notificationtimestamp' => NULL
2147 ), array( /* WHERE */
2148 'wl_user' => $currentUser
2151 # We also need to clear here the "you have new message" notification for the own user_talk page
2152 # This is cleared one page view later in Article::viewUpdates();
2157 * Encode this user's options as a string
2158 * @return \type{\string} Encoded options
2161 function encodeOptions() {
2163 if ( is_null( $this->mOptions
) ) {
2164 $this->mOptions
= User
::getDefaultOptions();
2167 foreach ( $this->mOptions
as $oname => $oval ) {
2168 array_push( $a, $oname.'='.$oval );
2170 $s = implode( "\n", $a );
2175 * Set this user's options from an encoded string
2176 * @param $str \type{\string} Encoded options to import
2179 function decodeOptions( $str ) {
2180 $this->mOptions
= array();
2181 $a = explode( "\n", $str );
2182 foreach ( $a as $s ) {
2184 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2185 $this->mOptions
[$m[1]] = $m[2];
2191 * Set a cookie on the user's client
2192 * @param $name \type{\string} Name of the cookie to set
2193 * @param $name \type{\string} Value to set
2194 * @param $name \type{\int} Expiration time, as a UNIX time value;
2195 * if 0 or not specified, use the default $wgCookieExpiration
2197 protected function setCookie( $name, $value, $exp=0 ) {
2198 global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly;
2200 $exp = time() +
$wgCookieExpiration;
2202 $httpOnlySafe = wfHttpOnlySafe();
2203 wfDebugLog( 'cookie',
2204 'setcookie: "' . implode( '", "',
2206 $wgCookiePrefix . $name,
2212 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2213 if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) {
2214 setcookie( $wgCookiePrefix . $name,
2220 $wgCookieHttpOnly );
2222 // setcookie() fails on PHP 5.1 if you give it future-compat paramters.
2224 setcookie( $wgCookiePrefix . $name,
2234 * Clear a cookie on the user's client
2235 * @param $name \type{\string} Name of the cookie to clear
2237 protected function clearCookie( $name ) {
2238 $this->setCookie( $name, '', time() - 86400 );
2242 * Set the default cookies for this session on the user's client.
2244 function setCookies() {
2246 if ( 0 == $this->mId
) return;
2248 'wsUserID' => $this->mId
,
2249 'wsToken' => $this->mToken
,
2250 'wsUserName' => $this->getName()
2253 'UserID' => $this->mId
,
2254 'UserName' => $this->getName(),
2256 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2257 $cookies['Token'] = $this->mToken
;
2259 $cookies['Token'] = false;
2262 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2263 $_SESSION = $session +
$_SESSION;
2264 foreach ( $cookies as $name => $value ) {
2265 if ( $value === false ) {
2266 $this->clearCookie( $name );
2268 $this->setCookie( $name, $value );
2274 * Log this user out.
2278 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2284 * Clear the user's cookies and session, and reset the instance cache.
2288 function doLogout() {
2289 $this->clearInstanceCache( 'defaults' );
2291 $_SESSION['wsUserID'] = 0;
2293 $this->clearCookie( 'UserID' );
2294 $this->clearCookie( 'Token' );
2296 # Remember when user logged out, to prevent seeing cached pages
2297 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2301 * Save this user's settings into the database.
2302 * @todo Only rarely do all these fields need to be set!
2304 function saveSettings() {
2306 if ( wfReadOnly() ) { return; }
2307 if ( 0 == $this->mId
) { return; }
2309 $this->mTouched
= self
::newTouchedTimestamp();
2311 $dbw = wfGetDB( DB_MASTER
);
2312 $dbw->update( 'user',
2314 'user_name' => $this->mName
,
2315 'user_password' => $this->mPassword
,
2316 'user_newpassword' => $this->mNewpassword
,
2317 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2318 'user_real_name' => $this->mRealName
,
2319 'user_email' => $this->mEmail
,
2320 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2321 'user_options' => $this->encodeOptions(),
2322 'user_touched' => $dbw->timestamp($this->mTouched
),
2323 'user_token' => $this->mToken
,
2324 'user_email_token' => $this->mEmailToken
,
2325 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2326 ), array( /* WHERE */
2327 'user_id' => $this->mId
2330 wfRunHooks( 'UserSaveSettings', array( $this ) );
2331 $this->clearSharedCache();
2335 * If only this user's username is known, and it exists, return the user ID.
2337 function idForName() {
2338 $s = trim( $this->getName() );
2339 if ( $s === '' ) return 0;
2341 $dbr = wfGetDB( DB_SLAVE
);
2342 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2343 if ( $id === false ) {
2350 * Add a user to the database, return the user object
2352 * @param $name \type{\string} Username to add
2353 * @param $params \arrayof{\string} Non-default parameters to save to the database:
2354 * - password The user's password. Password logins will be disabled if this is omitted.
2355 * - newpassword A temporary password mailed to the user
2356 * - email The user's email address
2357 * - email_authenticated The email authentication timestamp
2358 * - real_name The user's real name
2359 * - options An associative array of non-default options
2360 * - token Random authentication token. Do not set.
2361 * - registration Registration timestamp. Do not set.
2363 * @return \type{User} A new User object, or null if the username already exists
2365 static function createNew( $name, $params = array() ) {
2368 if ( isset( $params['options'] ) ) {
2369 $user->mOptions
= $params['options'] +
$user->mOptions
;
2370 unset( $params['options'] );
2372 $dbw = wfGetDB( DB_MASTER
);
2373 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2375 'user_id' => $seqVal,
2376 'user_name' => $name,
2377 'user_password' => $user->mPassword
,
2378 'user_newpassword' => $user->mNewpassword
,
2379 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2380 'user_email' => $user->mEmail
,
2381 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2382 'user_real_name' => $user->mRealName
,
2383 'user_options' => $user->encodeOptions(),
2384 'user_token' => $user->mToken
,
2385 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2386 'user_editcount' => 0,
2388 foreach ( $params as $name => $value ) {
2389 $fields["user_$name"] = $value;
2391 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2392 if ( $dbw->affectedRows() ) {
2393 $newUser = User
::newFromId( $dbw->insertId() );
2401 * Add this existing user object to the database
2403 function addToDatabase() {
2405 $dbw = wfGetDB( DB_MASTER
);
2406 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2407 $dbw->insert( 'user',
2409 'user_id' => $seqVal,
2410 'user_name' => $this->mName
,
2411 'user_password' => $this->mPassword
,
2412 'user_newpassword' => $this->mNewpassword
,
2413 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2414 'user_email' => $this->mEmail
,
2415 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2416 'user_real_name' => $this->mRealName
,
2417 'user_options' => $this->encodeOptions(),
2418 'user_token' => $this->mToken
,
2419 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2420 'user_editcount' => 0,
2423 $this->mId
= $dbw->insertId();
2425 // Clear instance cache other than user table data, which is already accurate
2426 $this->clearInstanceCache();
2430 * If this (non-anonymous) user is blocked, block any IP address
2431 * they've successfully logged in from.
2433 function spreadBlock() {
2434 wfDebug( __METHOD__
."()\n" );
2436 if ( $this->mId
== 0 ) {
2440 $userblock = Block
::newFromDB( '', $this->mId
);
2441 if ( !$userblock ) {
2445 $userblock->doAutoblock( wfGetIp() );
2450 * Generate a string which will be different for any combination of
2451 * user options which would produce different parser output.
2452 * This will be used as part of the hash key for the parser cache,
2453 * so users will the same options can share the same cached data
2456 * Extensions which require it should install 'PageRenderingHash' hook,
2457 * which will give them a chance to modify this key based on their own
2460 * @return \type{\string} Page rendering hash
2462 function getPageRenderingHash() {
2463 global $wgContLang, $wgUseDynamicDates, $wgLang;
2465 return $this->mHash
;
2468 // stubthreshold is only included below for completeness,
2469 // it will always be 0 when this function is called by parsercache.
2471 $confstr = $this->getOption( 'math' );
2472 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2473 if ( $wgUseDynamicDates ) {
2474 $confstr .= '!' . $this->getDatePreference();
2476 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2477 $confstr .= '!' . $wgLang->getCode();
2478 $confstr .= '!' . $this->getOption( 'thumbsize' );
2479 // add in language specific options, if any
2480 $extra = $wgContLang->getExtraHashOptions();
2483 // Give a chance for extensions to modify the hash, if they have
2484 // extra options or other effects on the parser cache.
2485 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2487 // Make it a valid memcached key fragment
2488 $confstr = str_replace( ' ', '_', $confstr );
2489 $this->mHash
= $confstr;
2494 * Get whether the user is explicitly blocked from account creation.
2495 * @return \type{\bool} True if blocked
2497 function isBlockedFromCreateAccount() {
2498 $this->getBlockedStatus();
2499 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2503 * Get whether the user is blocked from using Special:Emailuser.
2504 * @return \type{\bool} True if blocked
2506 function isBlockedFromEmailuser() {
2507 $this->getBlockedStatus();
2508 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2512 * Get whether the user is allowed to create an account.
2513 * @return \type{\bool} True if allowed
2515 function isAllowedToCreateAccount() {
2516 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2522 function setLoaded( $loaded ) {
2523 wfDeprecated( __METHOD__
);
2527 * Get this user's personal page title.
2529 * @return \type{Title} User's personal page title
2531 function getUserPage() {
2532 return Title
::makeTitle( NS_USER
, $this->getName() );
2536 * Get this user's talk page title.
2538 * @return \type{Title} User's talk page title
2540 function getTalkPage() {
2541 $title = $this->getUserPage();
2542 return $title->getTalkPage();
2546 * Get the maximum valid user ID.
2547 * @return \type{\int} %User ID
2550 function getMaxID() {
2551 static $res; // cache
2553 if ( isset( $res ) )
2556 $dbr = wfGetDB( DB_SLAVE
);
2557 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2562 * Determine whether the user is a newbie. Newbies are either
2563 * anonymous IPs, or the most recently created accounts.
2564 * @return \type{\bool} True if the user is a newbie
2566 function isNewbie() {
2567 return !$this->isAllowed( 'autoconfirmed' );
2571 * Is the user active? We check to see if they've made at least
2572 * X number of edits in the last Y days.
2574 * @return \type{\bool} True if the user is active, false if not.
2576 public function isActiveEditor() {
2577 global $wgActiveUserEditCount, $wgActiveUserDays;
2578 $dbr = wfGetDB( DB_SLAVE
);
2580 // Stolen without shame from RC
2581 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2582 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
2583 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2585 $res = $dbr->select( 'revision', '1',
2586 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2588 array('LIMIT' => $wgActiveUserEditCount ) );
2590 $count = $dbr->numRows($res);
2591 $dbr->freeResult($res);
2593 return $count == $wgActiveUserEditCount;
2597 * Check to see if the given clear-text password is one of the accepted passwords
2598 * @param $password \type{\string} user password.
2599 * @return \type{\bool} True if the given password is correct, otherwise False.
2601 function checkPassword( $password ) {
2605 // Even though we stop people from creating passwords that
2606 // are shorter than this, doesn't mean people wont be able
2607 // to. Certain authentication plugins do NOT want to save
2608 // domain passwords in a mysql database, so we should
2609 // check this (incase $wgAuth->strict() is false).
2610 if( !$this->isValidPassword( $password ) ) {
2614 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2616 } elseif( $wgAuth->strict() ) {
2617 /* Auth plugin doesn't allow local authentication */
2619 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2620 /* Auth plugin doesn't allow local authentication for this user name */
2623 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2625 } elseif ( function_exists( 'iconv' ) ) {
2626 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2627 # Check for this with iconv
2628 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2629 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2637 * Check if the given clear-text password matches the temporary password
2638 * sent by e-mail for password reset operations.
2639 * @return \type{\bool} True if matches, false otherwise
2641 function checkTemporaryPassword( $plaintext ) {
2642 return self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() );
2646 * Initialize (if necessary) and return a session token value
2647 * which can be used in edit forms to show that the user's
2648 * login credentials aren't being hijacked with a foreign form
2651 * @param $salt \twotypes{\string,\arrayof{\string}} Optional function-specific data for hashing
2652 * @return \type{\string} The new edit token
2654 function editToken( $salt = '' ) {
2655 if ( $this->isAnon() ) {
2656 return EDIT_TOKEN_SUFFIX
;
2658 if( !isset( $_SESSION['wsEditToken'] ) ) {
2659 $token = $this->generateToken();
2660 $_SESSION['wsEditToken'] = $token;
2662 $token = $_SESSION['wsEditToken'];
2664 if( is_array( $salt ) ) {
2665 $salt = implode( '|', $salt );
2667 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2672 * Generate a looking random token for various uses.
2674 * @param $salt \type{\string} Optional salt value
2675 * @return \type{\string} The new random token
2677 function generateToken( $salt = '' ) {
2678 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2679 return md5( $token . $salt );
2683 * Check given value against the token value stored in the session.
2684 * A match should confirm that the form was submitted from the
2685 * user's own login session, not a form submission from a third-party
2688 * @param $val \type{\string} Input value to compare
2689 * @param $salt \type{\string} Optional function-specific data for hashing
2690 * @return \type{\bool} Whether the token matches
2692 function matchEditToken( $val, $salt = '' ) {
2693 $sessionToken = $this->editToken( $salt );
2694 if ( $val != $sessionToken ) {
2695 wfDebug( "User::matchEditToken: broken session data\n" );
2697 return $val == $sessionToken;
2701 * Check given value against the token value stored in the session,
2702 * ignoring the suffix.
2704 * @param $val \type{\string} Input value to compare
2705 * @param $salt \type{\string} Optional function-specific data for hashing
2706 * @return \type{\bool} Whether the token matches
2708 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2709 $sessionToken = $this->editToken( $salt );
2710 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2714 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2715 * mail to the user's given address.
2717 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure.
2719 function sendConfirmationMail() {
2721 $expiration = null; // gets passed-by-ref and defined in next line.
2722 $token = $this->confirmationToken( $expiration );
2723 $url = $this->confirmationTokenUrl( $token );
2724 $invalidateURL = $this->invalidationTokenUrl( $token );
2725 $this->saveSettings();
2727 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2728 wfMsg( 'confirmemail_body',
2732 $wgLang->timeanddate( $expiration, false ),
2737 * Send an e-mail to this user's account. Does not check for
2738 * confirmed status or validity.
2740 * @param $subject \type{\string} Message subject
2741 * @param $body \type{\string} Message body
2742 * @param $from \type{\string} Optional From address; if unspecified, default $wgPasswordSender will be used
2743 * @param $replyto \type{\string} Reply-to address
2744 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure
2746 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2747 if( is_null( $from ) ) {
2748 global $wgPasswordSender;
2749 $from = $wgPasswordSender;
2752 $to = new MailAddress( $this );
2753 $sender = new MailAddress( $from );
2754 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2758 * Generate, store, and return a new e-mail confirmation code.
2759 * A hash (unsalted, since it's used as a key) is stored.
2761 * @note Call saveSettings() after calling this function to commit
2762 * this change to the database.
2764 * @param[out] &$expiration \type{\mixed} Accepts the expiration time
2765 * @return \type{\string} New token
2768 function confirmationToken( &$expiration ) {
2770 $expires = $now +
7 * 24 * 60 * 60;
2771 $expiration = wfTimestamp( TS_MW
, $expires );
2772 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2773 $hash = md5( $token );
2775 $this->mEmailToken
= $hash;
2776 $this->mEmailTokenExpires
= $expiration;
2781 * Return a URL the user can use to confirm their email address.
2782 * @param $token \type{\string} Accepts the email confirmation token
2783 * @return \type{\string} New token URL
2786 function confirmationTokenUrl( $token ) {
2787 return $this->getTokenUrl( 'ConfirmEmail', $token );
2790 * Return a URL the user can use to invalidate their email address.
2792 * @param $token \type{\string} Accepts the email confirmation token
2793 * @return \type{\string} New token URL
2796 function invalidationTokenUrl( $token ) {
2797 return $this->getTokenUrl( 'Invalidateemail', $token );
2801 * Internal function to format the e-mail validation/invalidation URLs.
2802 * This uses $wgArticlePath directly as a quickie hack to use the
2803 * hardcoded English names of the Special: pages, for ASCII safety.
2805 * @note Since these URLs get dropped directly into emails, using the
2806 * short English names avoids insanely long URL-encoded links, which
2807 * also sometimes can get corrupted in some browsers/mailers
2808 * (bug 6957 with Gmail and Internet Explorer).
2810 * @param $page \type{\string} Special page
2811 * @param $token \type{\string} Token
2812 * @return \type{\string} Formatted URL
2814 protected function getTokenUrl( $page, $token ) {
2815 global $wgArticlePath;
2819 "Special:$page/$token",
2824 * Mark the e-mail address confirmed.
2826 * @note Call saveSettings() after calling this function to commit the change.
2828 function confirmEmail() {
2829 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2834 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2835 * address if it was already confirmed.
2837 * @note Call saveSettings() after calling this function to commit the change.
2839 function invalidateEmail() {
2841 $this->mEmailToken
= null;
2842 $this->mEmailTokenExpires
= null;
2843 $this->setEmailAuthenticationTimestamp( null );
2848 * Set the e-mail authentication timestamp.
2849 * @param $timestamp \type{\string} TS_MW timestamp
2851 function setEmailAuthenticationTimestamp( $timestamp ) {
2853 $this->mEmailAuthenticated
= $timestamp;
2854 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2858 * Is this user allowed to send e-mails within limits of current
2859 * site configuration?
2860 * @return \type{\bool} True if allowed
2862 function canSendEmail() {
2863 $canSend = $this->isEmailConfirmed();
2864 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2869 * Is this user allowed to receive e-mails within limits of current
2870 * site configuration?
2871 * @return \type{\bool} True if allowed
2873 function canReceiveEmail() {
2874 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2878 * Is this user's e-mail address valid-looking and confirmed within
2879 * limits of the current site configuration?
2881 * @note If $wgEmailAuthentication is on, this may require the user to have
2882 * confirmed their address by returning a code or using a password
2883 * sent to the address from the wiki.
2885 * @return \type{\bool} True if confirmed
2887 function isEmailConfirmed() {
2888 global $wgEmailAuthentication;
2891 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2892 if( $this->isAnon() )
2894 if( !self
::isValidEmailAddr( $this->mEmail
) )
2896 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2905 * Check whether there is an outstanding request for e-mail confirmation.
2906 * @return \type{\bool} True if pending
2908 function isEmailConfirmationPending() {
2909 global $wgEmailAuthentication;
2910 return $wgEmailAuthentication &&
2911 !$this->isEmailConfirmed() &&
2912 $this->mEmailToken
&&
2913 $this->mEmailTokenExpires
> wfTimestamp();
2917 * Get the timestamp of account creation.
2919 * @return \twotypes{\string,\bool} string Timestamp of account creation, or false for
2920 * non-existent/anonymous user accounts.
2922 public function getRegistration() {
2923 return $this->mId
> 0
2924 ?
$this->mRegistration
2929 * Get the permissions associated with a given list of groups
2931 * @param $groups \arrayof{\string} List of internal group names
2932 * @return \arrayof{\string} List of permission key names for given groups combined
2934 static function getGroupPermissions( $groups ) {
2935 global $wgGroupPermissions;
2937 foreach( $groups as $group ) {
2938 if( isset( $wgGroupPermissions[$group] ) ) {
2939 $rights = array_merge( $rights,
2940 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2947 * Get all the groups who have a given permission
2949 * @param $role \type{\string} Role to check
2950 * @return \arrayof{\string} List of internal group names with the given permission
2952 static function getGroupsWithPermission( $role ) {
2953 global $wgGroupPermissions;
2954 $allowedGroups = array();
2955 foreach ( $wgGroupPermissions as $group => $rights ) {
2956 if ( isset( $rights[$role] ) && $rights[$role] ) {
2957 $allowedGroups[] = $group;
2960 return $allowedGroups;
2964 * Get the localized descriptive name for a group, if it exists
2966 * @param $group \type{\string} Internal group name
2967 * @return \type{\string} Localized descriptive group name
2969 static function getGroupName( $group ) {
2970 global $wgMessageCache;
2971 $wgMessageCache->loadAllMessages();
2972 $key = "group-$group";
2973 $name = wfMsg( $key );
2974 return $name == '' ||
wfEmptyMsg( $key, $name )
2980 * Get the localized descriptive name for a member of a group, if it exists
2982 * @param $group \type{\string} Internal group name
2983 * @return \type{\string} Localized name for group member
2985 static function getGroupMember( $group ) {
2986 global $wgMessageCache;
2987 $wgMessageCache->loadAllMessages();
2988 $key = "group-$group-member";
2989 $name = wfMsg( $key );
2990 return $name == '' ||
wfEmptyMsg( $key, $name )
2996 * Return the set of defined explicit groups.
2997 * The implicit groups (by default *, 'user' and 'autoconfirmed')
2998 * are not included, as they are defined automatically, not in the database.
2999 * @return \arrayof{\string} Array of internal group names
3001 static function getAllGroups() {
3002 global $wgGroupPermissions;
3004 array_keys( $wgGroupPermissions ),
3005 self
::getImplicitGroups()
3010 * Get a list of all available permissions.
3011 * @return \arrayof{\string} Array of permission names
3013 static function getAllRights() {
3014 if ( self
::$mAllRights === false ) {
3015 global $wgAvailableRights;
3016 if ( count( $wgAvailableRights ) ) {
3017 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3019 self
::$mAllRights = self
::$mCoreRights;
3021 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3023 return self
::$mAllRights;
3027 * Get a list of implicit groups
3028 * @return \arrayof{\string} Array of internal group names
3030 public static function getImplicitGroups() {
3031 global $wgImplicitGroups;
3032 $groups = $wgImplicitGroups;
3033 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3038 * Get the title of a page describing a particular group
3040 * @param $group \type{\string} Internal group name
3041 * @return \twotypes{Title,\bool} Title of the page if it exists, false otherwise
3043 static function getGroupPage( $group ) {
3044 global $wgMessageCache;
3045 $wgMessageCache->loadAllMessages();
3046 $page = wfMsgForContent( 'grouppage-' . $group );
3047 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3048 $title = Title
::newFromText( $page );
3049 if( is_object( $title ) )
3056 * Create a link to the group in HTML, if available;
3057 * else return the group name.
3059 * @param $group \type{\string} Internal name of the group
3060 * @param $text \type{\string} The text of the link
3061 * @return \type{\string} HTML link to the group
3063 static function makeGroupLinkHTML( $group, $text = '' ) {
3065 $text = self
::getGroupName( $group );
3067 $title = self
::getGroupPage( $group );
3070 $sk = $wgUser->getSkin();
3071 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3078 * Create a link to the group in Wikitext, if available;
3079 * else return the group name.
3081 * @param $group \type{\string} Internal name of the group
3082 * @param $text \type{\string} The text of the link
3083 * @return \type{\string} Wikilink to the group
3085 static function makeGroupLinkWiki( $group, $text = '' ) {
3087 $text = self
::getGroupName( $group );
3089 $title = self
::getGroupPage( $group );
3091 $page = $title->getPrefixedText();
3092 return "[[$page|$text]]";
3099 * Increment the user's edit-count field.
3100 * Will have no effect for anonymous users.
3102 function incEditCount() {
3103 if( !$this->isAnon() ) {
3104 $dbw = wfGetDB( DB_MASTER
);
3105 $dbw->update( 'user',
3106 array( 'user_editcount=user_editcount+1' ),
3107 array( 'user_id' => $this->getId() ),
3110 // Lazy initialization check...
3111 if( $dbw->affectedRows() == 0 ) {
3112 // Pull from a slave to be less cruel to servers
3113 // Accuracy isn't the point anyway here
3114 $dbr = wfGetDB( DB_SLAVE
);
3115 $count = $dbr->selectField( 'revision',
3117 array( 'rev_user' => $this->getId() ),
3120 // Now here's a goddamn hack...
3121 if( $dbr !== $dbw ) {
3122 // If we actually have a slave server, the count is
3123 // at least one behind because the current transaction
3124 // has not been committed and replicated.
3127 // But if DB_SLAVE is selecting the master, then the
3128 // count we just read includes the revision that was
3129 // just added in the working transaction.
3132 $dbw->update( 'user',
3133 array( 'user_editcount' => $count ),
3134 array( 'user_id' => $this->getId() ),
3138 // edit count in user cache too
3139 $this->invalidateCache();
3143 * Get the description of a given right
3145 * @param $right \type{\string} Right to query
3146 * @return \type{\string} Localized description of the right
3148 static function getRightDescription( $right ) {
3149 global $wgMessageCache;
3150 $wgMessageCache->loadAllMessages();
3151 $key = "right-$right";
3152 $name = wfMsg( $key );
3153 return $name == '' ||
wfEmptyMsg( $key, $name )
3159 * Make an old-style password hash
3161 * @param $password \type{\string} Plain-text password
3162 * @param $userId \type{\string} %User ID
3163 * @return \type{\string} Password hash
3165 static function oldCrypt( $password, $userId ) {
3166 global $wgPasswordSalt;
3167 if ( $wgPasswordSalt ) {
3168 return md5( $userId . '-' . md5( $password ) );
3170 return md5( $password );
3175 * Make a new-style password hash
3177 * @param $password \type{\string} Plain-text password
3178 * @param $salt \type{\string} Optional salt, may be random or the user ID.
3179 * If unspecified or false, will generate one automatically
3180 * @return \type{\string} Password hash
3182 static function crypt( $password, $salt = false ) {
3183 global $wgPasswordSalt;
3185 if($wgPasswordSalt) {
3186 if ( $salt === false ) {
3187 $salt = substr( wfGenerateToken(), 0, 8 );
3189 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3191 return ':A:' . md5( $password);
3196 * Compare a password hash with a plain-text password. Requires the user
3197 * ID if there's a chance that the hash is an old-style hash.
3199 * @param $hash \type{\string} Password hash
3200 * @param $password \type{\string} Plain-text password to compare
3201 * @param $userId \type{\string} %User ID for old-style password salt
3202 * @return \type{\bool} True if matches, false otherwise
3204 static function comparePasswords( $hash, $password, $userId = false ) {
3206 $type = substr( $hash, 0, 3 );
3207 if ( $type == ':A:' ) {
3209 return md5( $password ) === substr( $hash, 3 );
3210 } elseif ( $type == ':B:' ) {
3212 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3213 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3216 return self
::oldCrypt( $password, $userId ) === $hash;