3 * Implements the User class for the %MediaWiki software.
8 * \int Number of characters in user_token field.
11 define( 'USER_TOKEN_LENGTH', 32 );
14 * \int Serialized record version.
17 define( 'MW_USER_VERSION', 6 );
20 * \string Some punctuation to prevent editing from broken text-mangling proxies.
23 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
26 * Thrown by User::setPassword() on error.
29 class PasswordError
extends MWException
{
34 * The User object encapsulates all of the user-specific settings (user_id,
35 * name, rights, password, email address, options, last login time). Client
36 * classes use the getXXX() functions to access these fields. These functions
37 * do all the work of determining whether the user is logged in,
38 * whether the requested option can be satisfied from cookies or
39 * whether a database query is needed. Most of the settings needed
40 * for rendering normal pages are set in the cookie to minimize use
46 * \type{\arrayof{\string}} A list of default user toggles, i.e., boolean user
47 * preferences that are displayed by Special:Preferences as checkboxes.
48 * This list can be extended via the UserToggles hook or by
49 * $wgContLang::getExtraUserToggles().
52 public static $mToggles = array(
62 'editsectiononrightclick',
74 'enotifwatchlistpages',
75 'enotifusertalkpages',
78 'shownumberswatching',
98 * \type{\arrayof{\string}} List of member variables which are saved to the
99 * shared cache (memcached). Any operation which changes the
100 * corresponding database fields must call a cache-clearing function.
103 static $mCacheVars = array(
115 'mEmailAuthenticated',
117 'mEmailTokenExpires',
125 * \type{\arrayof{\string}} Core rights.
126 * Each of these should have a corresponding message of the form
130 static $mCoreRights = array(
156 'move-rootuserpages',
179 'userrights-interwiki',
183 * \string Cached results of getAllRights()
185 static $mAllRights = false;
187 /** @name Cache variables */
189 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
190 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
191 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
195 * \bool Whether the cache variables have been loaded.
197 var $mDataLoaded, $mAuthLoaded;
200 * \string Initialization data source if mDataLoaded==false. May be one of:
201 * - 'defaults' anonymous user initialised from class defaults
202 * - 'name' initialise from mName
203 * - 'id' initialise from mId
204 * - 'session' log in from cookies or session if possible
206 * Use the User::newFrom*() family of functions to set this.
210 /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
212 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
213 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
214 $mLocked, $mHideName;
218 * Lightweight constructor for an anonymous user.
219 * Use the User::newFrom* factory functions for other kinds of users.
223 * @see newFromConfirmationCode()
224 * @see newFromSession()
228 $this->clearInstanceCache( 'defaults' );
232 * Load the user table data for this object from the source given by mFrom.
235 if ( $this->mDataLoaded
) {
238 wfProfileIn( __METHOD__
);
240 # Set it now to avoid infinite recursion in accessors
241 $this->mDataLoaded
= true;
243 switch ( $this->mFrom
) {
245 $this->loadDefaults();
248 $this->mId
= self
::idFromName( $this->mName
);
250 # Nonexistent user placeholder object
251 $this->loadDefaults( $this->mName
);
260 $this->loadFromSession();
261 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
264 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
266 wfProfileOut( __METHOD__
);
270 * Load user table data, given mId has already been set.
271 * @return \bool false if the ID does not exist, true otherwise
274 function loadFromId() {
276 if ( $this->mId
== 0 ) {
277 $this->loadDefaults();
282 $key = wfMemcKey( 'user', 'id', $this->mId
);
283 $data = $wgMemc->get( $key );
284 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
285 # Object is expired, load from DB
290 wfDebug( "Cache miss for user {$this->mId}\n" );
292 if ( !$this->loadFromDatabase() ) {
293 # Can't load from ID, user is anonymous
296 $this->saveToCache();
298 wfDebug( "Got user {$this->mId} from cache\n" );
300 foreach ( self
::$mCacheVars as $name ) {
301 $this->$name = $data[$name];
308 * Save user data to the shared cache
310 function saveToCache() {
313 if ( $this->isAnon() ) {
314 // Anonymous users are uncached
318 foreach ( self
::$mCacheVars as $name ) {
319 $data[$name] = $this->$name;
321 $data['mVersion'] = MW_USER_VERSION
;
322 $key = wfMemcKey( 'user', 'id', $this->mId
);
324 $wgMemc->set( $key, $data );
328 /** @name newFrom*() static factory methods */
332 * Static factory method for creation from username.
334 * This is slightly less efficient than newFromId(), so use newFromId() if
335 * you have both an ID and a name handy.
337 * @param $name \string Username, validated by Title::newFromText()
338 * @param $validate \mixed Validate username. Takes the same parameters as
339 * User::getCanonicalName(), except that true is accepted as an alias
340 * for 'valid', for BC.
342 * @return \type{User} The User object, or null if the username is invalid. If the
343 * username is not present in the database, the result will be a user object
344 * with a name, zero user ID and default settings.
346 static function newFromName( $name, $validate = 'valid' ) {
347 if ( $validate === true ) {
350 $name = self
::getCanonicalName( $name, $validate );
351 if ( $name === false ) {
354 # Create unloaded user object
363 * Static factory method for creation from a given user ID.
365 * @param $id \int Valid user ID
366 * @return \type{User} The corresponding User object
368 static function newFromId( $id ) {
376 * Factory method to fetch whichever user has a given email confirmation code.
377 * This code is generated when an account is created or its e-mail address
380 * If the code is invalid or has expired, returns NULL.
382 * @param $code \string Confirmation code
383 * @return \type{User}
385 static function newFromConfirmationCode( $code ) {
386 $dbr = wfGetDB( DB_SLAVE
);
387 $id = $dbr->selectField( 'user', 'user_id', array(
388 'user_email_token' => md5( $code ),
389 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
391 if( $id !== false ) {
392 return User
::newFromId( $id );
399 * Create a new user object using data from session or cookies. If the
400 * login credentials are invalid, the result is an anonymous user.
402 * @return \type{User}
404 static function newFromSession() {
406 $user->mFrom
= 'session';
411 * Create a new user object from a user row.
412 * The row should have all fields from the user table in it.
413 * @param $row array A row from the user table
414 * @return \type{User}
416 static function newFromRow( $row ) {
418 $user->loadFromRow( $row );
426 * Get the username corresponding to a given user ID
427 * @param $id \int User ID
428 * @return \string The corresponding username
430 static function whoIs( $id ) {
431 $dbr = wfGetDB( DB_SLAVE
);
432 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
436 * Get the real name of a user given their user ID
438 * @param $id \int User ID
439 * @return \string The corresponding user's real name
441 static function whoIsReal( $id ) {
442 $dbr = wfGetDB( DB_SLAVE
);
443 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
447 * Get database id given a user name
448 * @param $name \string Username
449 * @return \types{\int,\null} The corresponding user's ID, or null if user is nonexistent
451 static function idFromName( $name ) {
452 $nt = Title
::makeTitleSafe( NS_USER
, $name );
453 if( is_null( $nt ) ) {
457 $dbr = wfGetDB( DB_SLAVE
);
458 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
460 if ( $s === false ) {
468 * Does the string match an anonymous IPv4 address?
470 * This function exists for username validation, in order to reject
471 * usernames which are similar in form to IP addresses. Strings such
472 * as 300.300.300.300 will return true because it looks like an IP
473 * address, despite not being strictly valid.
475 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
476 * address because the usemod software would "cloak" anonymous IP
477 * addresses like this, if we allowed accounts like this to be created
478 * new users could get the old edits of these anonymous users.
480 * @param $name \string String to match
481 * @return \bool True or false
483 static function isIP( $name ) {
484 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
488 * Is the input a valid username?
490 * Checks if the input is a valid username, we don't want an empty string,
491 * an IP address, anything that containins slashes (would mess up subpages),
492 * is longer than the maximum allowed username size or doesn't begin with
495 * @param $name \string String to match
496 * @return \bool True or false
498 static function isValidUserName( $name ) {
499 global $wgContLang, $wgMaxNameChars;
502 || User
::isIP( $name )
503 ||
strpos( $name, '/' ) !== false
504 ||
strlen( $name ) > $wgMaxNameChars
505 ||
$name != $wgContLang->ucfirst( $name ) ) {
506 wfDebugLog( 'username', __METHOD__
.
507 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
511 // Ensure that the name can't be misresolved as a different title,
512 // such as with extra namespace keys at the start.
513 $parsed = Title
::newFromText( $name );
514 if( is_null( $parsed )
515 ||
$parsed->getNamespace()
516 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
517 wfDebugLog( 'username', __METHOD__
.
518 ": '$name' invalid due to ambiguous prefixes" );
522 // Check an additional blacklist of troublemaker characters.
523 // Should these be merged into the title char list?
524 $unicodeBlacklist = '/[' .
525 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
526 '\x{00a0}' . # non-breaking space
527 '\x{2000}-\x{200f}' . # various whitespace
528 '\x{2028}-\x{202f}' . # breaks and control chars
529 '\x{3000}' . # ideographic space
530 '\x{e000}-\x{f8ff}' . # private use
532 if( preg_match( $unicodeBlacklist, $name ) ) {
533 wfDebugLog( 'username', __METHOD__
.
534 ": '$name' invalid due to blacklisted characters" );
542 * Usernames which fail to pass this function will be blocked
543 * from user login and new account registrations, but may be used
544 * internally by batch processes.
546 * If an account already exists in this form, login will be blocked
547 * by a failure to pass this function.
549 * @param $name \string String to match
550 * @return \bool True or false
552 static function isUsableName( $name ) {
553 global $wgReservedUsernames;
554 // Must be a valid username, obviously ;)
555 if ( !self
::isValidUserName( $name ) ) {
559 static $reservedUsernames = false;
560 if ( !$reservedUsernames ) {
561 $reservedUsernames = $wgReservedUsernames;
562 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
565 // Certain names may be reserved for batch processes.
566 foreach ( $reservedUsernames as $reserved ) {
567 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
568 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
570 if ( $reserved == $name ) {
578 * Usernames which fail to pass this function will be blocked
579 * from new account registrations, but may be used internally
580 * either by batch processes or by user accounts which have
581 * already been created.
583 * Additional character blacklisting may be added here
584 * rather than in isValidUserName() to avoid disrupting
587 * @param $name \string String to match
588 * @return \bool True or false
590 static function isCreatableName( $name ) {
592 self
::isUsableName( $name ) &&
594 // Registration-time character blacklisting...
595 strpos( $name, '@' ) === false;
599 * Is the input a valid password for this user?
601 * @param $password \string Desired password
602 * @return \bool True or false
604 function isValidPassword( $password ) {
605 global $wgMinimalPasswordLength, $wgContLang;
608 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
610 if( $result === false )
613 // Password needs to be long enough, and can't be the same as the username
614 return strlen( $password ) >= $wgMinimalPasswordLength
615 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
619 * Does a string look like an e-mail address?
621 * There used to be a regular expression here, it got removed because it
622 * rejected valid addresses. Actually just check if there is '@' somewhere
623 * in the given address.
625 * @todo Check for RFC 2822 compilance (bug 959)
627 * @param $addr \string E-mail address
628 * @return \bool True or false
630 public static function isValidEmailAddr( $addr ) {
632 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
636 return strpos( $addr, '@' ) !== false;
640 * Given unvalidated user input, return a canonical username, or false if
641 * the username is invalid.
642 * @param $name \string User input
643 * @param $validate \types{\string,\bool} Type of validation to use:
644 * - false No validation
645 * - 'valid' Valid for batch processes
646 * - 'usable' Valid for batch processes and login
647 * - 'creatable' Valid for batch processes, login and account creation
649 static function getCanonicalName( $name, $validate = 'valid' ) {
650 # Force usernames to capital
652 $name = $wgContLang->ucfirst( $name );
654 # Reject names containing '#'; these will be cleaned up
655 # with title normalisation, but then it's too late to
657 if( strpos( $name, '#' ) !== false )
660 # Clean up name according to title rules
661 $t = ($validate === 'valid') ?
662 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
663 # Check for invalid titles
664 if( is_null( $t ) ) {
668 # Reject various classes of invalid names
669 $name = $t->getText();
671 $name = $wgAuth->getCanonicalName( $t->getText() );
673 switch ( $validate ) {
677 if ( !User
::isValidUserName( $name ) ) {
682 if ( !User
::isUsableName( $name ) ) {
687 if ( !User
::isCreatableName( $name ) ) {
692 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
698 * Count the number of edits of a user
699 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
701 * @param $uid \int User ID to check
702 * @return \int The user's edit count
704 static function edits( $uid ) {
705 wfProfileIn( __METHOD__
);
706 $dbr = wfGetDB( DB_SLAVE
);
707 // check if the user_editcount field has been initialized
708 $field = $dbr->selectField(
709 'user', 'user_editcount',
710 array( 'user_id' => $uid ),
714 if( $field === null ) { // it has not been initialized. do so.
715 $dbw = wfGetDB( DB_MASTER
);
716 $count = $dbr->selectField(
717 'revision', 'count(*)',
718 array( 'rev_user' => $uid ),
723 array( 'user_editcount' => $count ),
724 array( 'user_id' => $uid ),
730 wfProfileOut( __METHOD__
);
735 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
736 * @todo hash random numbers to improve security, like generateToken()
738 * @return \string New random password
740 static function randomPassword() {
741 global $wgMinimalPasswordLength;
742 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
743 $l = strlen( $pwchars ) - 1;
745 $pwlength = max( 7, $wgMinimalPasswordLength );
746 $digit = mt_rand(0, $pwlength - 1);
748 for ( $i = 0; $i < $pwlength; $i++
) {
749 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
755 * Set cached properties to default.
757 * @note This no longer clears uncached lazy-initialised properties;
758 * the constructor does that instead.
761 function loadDefaults( $name = false ) {
762 wfProfileIn( __METHOD__
);
764 global $wgCookiePrefix;
767 $this->mName
= $name;
768 $this->mRealName
= '';
769 $this->mPassword
= $this->mNewpassword
= '';
770 $this->mNewpassTime
= null;
772 $this->mOptions
= null; # Defer init
774 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
775 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
777 $this->mTouched
= '0'; # Allow any pages to be cached
780 $this->setToken(); # Random
781 $this->mEmailAuthenticated
= null;
782 $this->mEmailToken
= '';
783 $this->mEmailTokenExpires
= null;
784 $this->mRegistration
= wfTimestamp( TS_MW
);
785 $this->mGroups
= array();
787 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
789 wfProfileOut( __METHOD__
);
793 * @deprecated Use wfSetupSession().
795 function SetupSession() {
796 wfDeprecated( __METHOD__
);
801 * Load user data from the session or login cookie. If there are no valid
802 * credentials, initialises the user as an anonymous user.
803 * @return \bool True if the user is logged in, false otherwise.
805 private function loadFromSession() {
806 global $wgMemc, $wgCookiePrefix;
809 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
810 if ( $result !== null ) {
814 if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
815 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
816 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
817 $this->loadDefaults(); // Possible collision!
818 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
819 cookie user ID ($sId) don't match!" );
822 $_SESSION['wsUserID'] = $sId;
823 } else if ( isset( $_SESSION['wsUserID'] ) ) {
824 if ( $_SESSION['wsUserID'] != 0 ) {
825 $sId = $_SESSION['wsUserID'];
827 $this->loadDefaults();
831 $this->loadDefaults();
835 if ( isset( $_SESSION['wsUserName'] ) ) {
836 $sName = $_SESSION['wsUserName'];
837 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
838 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
839 $_SESSION['wsUserName'] = $sName;
841 $this->loadDefaults();
845 $passwordCorrect = FALSE;
847 if ( !$this->loadFromId() ) {
848 # Not a valid ID, loadFromId has switched the object to anon for us
852 if ( isset( $_SESSION['wsToken'] ) ) {
853 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
855 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
856 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
859 # No session or persistent login cookie
860 $this->loadDefaults();
864 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
865 $_SESSION['wsToken'] = $this->mToken
;
866 wfDebug( "Logged in from $from\n" );
869 # Invalid credentials
870 wfDebug( "Can't log in from $from, invalid credentials\n" );
871 $this->loadDefaults();
877 * Load user and user_group data from the database.
878 * $this::mId must be set, this is how the user is identified.
880 * @return \bool True if the user exists, false if the user is anonymous
883 function loadFromDatabase() {
885 $this->mId
= intval( $this->mId
);
887 /** Anonymous user */
889 $this->loadDefaults();
893 $dbr = wfGetDB( DB_MASTER
);
894 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
896 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
898 if ( $s !== false ) {
899 # Initialise user table data
900 $this->loadFromRow( $s );
901 $this->mGroups
= null; // deferred
902 $this->getEditCount(); // revalidation for nulls
907 $this->loadDefaults();
913 * Initialize this object from a row from the user table.
915 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
917 function loadFromRow( $row ) {
918 $this->mDataLoaded
= true;
920 if ( isset( $row->user_id
) ) {
921 $this->mId
= intval( $row->user_id
);
923 $this->mName
= $row->user_name
;
924 $this->mRealName
= $row->user_real_name
;
925 $this->mPassword
= $row->user_password
;
926 $this->mNewpassword
= $row->user_newpassword
;
927 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
928 $this->mEmail
= $row->user_email
;
929 $this->decodeOptions( $row->user_options
);
930 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
931 $this->mToken
= $row->user_token
;
932 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
933 $this->mEmailToken
= $row->user_email_token
;
934 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
935 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
936 $this->mEditCount
= $row->user_editcount
;
940 * Load the groups from the database if they aren't already loaded.
943 function loadGroups() {
944 if ( is_null( $this->mGroups
) ) {
945 $dbr = wfGetDB( DB_MASTER
);
946 $res = $dbr->select( 'user_groups',
948 array( 'ug_user' => $this->mId
),
950 $this->mGroups
= array();
951 while( $row = $dbr->fetchObject( $res ) ) {
952 $this->mGroups
[] = $row->ug_group
;
958 * Clear various cached data stored in this object.
959 * @param $reloadFrom \string Reload user and user_groups table data from a
960 * given source. May be "name", "id", "defaults", "session", or false for
963 function clearInstanceCache( $reloadFrom = false ) {
964 $this->mNewtalk
= -1;
965 $this->mDatePreference
= null;
966 $this->mBlockedby
= -1; # Unset
967 $this->mHash
= false;
969 $this->mRights
= null;
970 $this->mEffectiveGroups
= null;
973 $this->mDataLoaded
= false;
974 $this->mFrom
= $reloadFrom;
979 * Combine the language default options with any site-specific options
980 * and add the default language variants.
982 * @return \type{\arrayof{\string}} Array of options
984 static function getDefaultOptions() {
985 global $wgNamespacesToBeSearchedDefault;
987 * Site defaults will override the global/language defaults
989 global $wgDefaultUserOptions, $wgContLang;
990 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
993 * default language setting
995 $variant = $wgContLang->getPreferredVariant( false );
996 $defOpt['variant'] = $variant;
997 $defOpt['language'] = $variant;
999 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1000 $defOpt['searchNs'.$nsnum] = $val;
1006 * Get a given default option value.
1008 * @param $opt \string Name of option to retrieve
1009 * @return \string Default option value
1011 public static function getDefaultOption( $opt ) {
1012 $defOpts = self
::getDefaultOptions();
1013 if( isset( $defOpts[$opt] ) ) {
1014 return $defOpts[$opt];
1021 * Get a list of user toggle names
1022 * @return \type{\arrayof{\string}} Array of user toggle names
1024 static function getToggles() {
1025 global $wgContLang, $wgUseRCPatrol;
1026 $extraToggles = array();
1027 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1028 if( $wgUseRCPatrol ) {
1029 $extraToggles[] = 'hidepatrolled';
1030 $extraToggles[] = 'newpageshidepatrolled';
1031 $extraToggles[] = 'watchlisthidepatrolled';
1033 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1038 * Get blocking information
1040 * @param $bFromSlave \bool Whether to check the slave database first. To
1041 * improve performance, non-critical checks are done
1042 * against slaves. Check when actually saving should be
1043 * done against master.
1045 function getBlockedStatus( $bFromSlave = true ) {
1046 global $wgEnableSorbs, $wgProxyWhitelist;
1048 if ( -1 != $this->mBlockedby
) {
1049 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1053 wfProfileIn( __METHOD__
);
1054 wfDebug( __METHOD__
.": checking...\n" );
1056 // Initialize data...
1057 // Otherwise something ends up stomping on $this->mBlockedby when
1058 // things get lazy-loaded later, causing false positive block hits
1059 // due to -1 !== 0. Probably session-related... Nothing should be
1060 // overwriting mBlockedby, surely?
1063 $this->mBlockedby
= 0;
1064 $this->mHideName
= 0;
1065 $this->mAllowUsertalk
= 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 $this->mAllowUsertalk
= $this->mBlock
->mAllowUsertalk
;
1082 if ( $this->isLoggedIn() ) {
1083 $this->spreadBlock();
1086 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1087 // apply to users. Note that the existence of $this->mBlock is not used to
1088 // check for edit blocks, $this->mBlockedby is instead.
1092 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1094 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1095 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1096 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1100 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1101 if ( $this->inSorbsBlacklist( $ip ) ) {
1102 $this->mBlockedby
= wfMsg( 'sorbs' );
1103 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1109 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1111 wfProfileOut( __METHOD__
);
1115 * Whether the given IP is in the SORBS blacklist.
1117 * @param $ip \string IP to check
1118 * @return \bool True if blacklisted.
1120 function inSorbsBlacklist( $ip ) {
1121 global $wgEnableSorbs, $wgSorbsUrl;
1123 return $wgEnableSorbs &&
1124 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1128 * Whether the given IP is in a given DNS blacklist.
1130 * @param $ip \string IP to check
1131 * @param $base \string URL of the DNS blacklist
1132 * @return \bool True if blacklisted.
1134 function inDnsBlacklist( $ip, $base ) {
1135 wfProfileIn( __METHOD__
);
1139 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1140 if( IP
::isIPv4($ip) ) {
1142 $host = "$ip.$base";
1145 $ipList = gethostbynamel( $host );
1148 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1151 wfDebug( "Requested $host, not found in $base.\n" );
1155 wfProfileOut( __METHOD__
);
1160 * Is this user subject to rate limiting?
1162 * @return \bool True if rate limited
1164 public function isPingLimitable() {
1165 global $wgRateLimitsExcludedGroups;
1166 global $wgRateLimitsExcludedIPs;
1167 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1168 // Deprecated, but kept for backwards-compatibility config
1171 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1172 // No other good way currently to disable rate limits
1173 // for specific IPs. :P
1174 // But this is a crappy hack and should die.
1177 return !$this->isAllowed('noratelimit');
1181 * Primitive rate limits: enforce maximum actions per time period
1182 * to put a brake on flooding.
1184 * @note When using a shared cache like memcached, IP-address
1185 * last-hit counters will be shared across wikis.
1187 * @param $action \string Action to enforce; 'edit' if unspecified
1188 * @return \bool True if a rate limiter was tripped
1190 function pingLimiter( $action='edit' ) {
1192 # Call the 'PingLimiter' hook
1194 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1198 global $wgRateLimits;
1199 if( !isset( $wgRateLimits[$action] ) ) {
1203 # Some groups shouldn't trigger the ping limiter, ever
1204 if( !$this->isPingLimitable() )
1207 global $wgMemc, $wgRateLimitLog;
1208 wfProfileIn( __METHOD__
);
1210 $limits = $wgRateLimits[$action];
1212 $id = $this->getId();
1216 if( isset( $limits['anon'] ) && $id == 0 ) {
1217 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1220 if( isset( $limits['user'] ) && $id != 0 ) {
1221 $userLimit = $limits['user'];
1223 if( $this->isNewbie() ) {
1224 if( isset( $limits['newbie'] ) && $id != 0 ) {
1225 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1227 if( isset( $limits['ip'] ) ) {
1228 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1231 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1232 $subnet = $matches[1];
1233 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1236 // Check for group-specific permissions
1237 // If more than one group applies, use the group with the highest limit
1238 foreach ( $this->getGroups() as $group ) {
1239 if ( isset( $limits[$group] ) ) {
1240 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1241 $userLimit = $limits[$group];
1245 // Set the user limit key
1246 if ( $userLimit !== false ) {
1247 wfDebug( __METHOD__
.": effective user limit: $userLimit\n" );
1248 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1252 foreach( $keys as $key => $limit ) {
1253 list( $max, $period ) = $limit;
1254 $summary = "(limit $max in {$period}s)";
1255 $count = $wgMemc->get( $key );
1257 if( $count > $max ) {
1258 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1259 if( $wgRateLimitLog ) {
1260 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1264 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1267 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1268 $wgMemc->add( $key, 1, intval( $period ) );
1270 $wgMemc->incr( $key );
1273 wfProfileOut( __METHOD__
);
1278 * Check if user is blocked
1280 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1281 * @return \bool True if blocked, false otherwise
1283 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1284 wfDebug( "User::isBlocked: enter\n" );
1285 $this->getBlockedStatus( $bFromSlave );
1286 return $this->mBlockedby
!== 0;
1290 * Check if user is blocked from editing a particular article
1292 * @param $title \string Title to check
1293 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1294 * @return \bool True if blocked, false otherwise
1296 function isBlockedFrom( $title, $bFromSlave = false ) {
1297 global $wgBlockAllowsUTEdit;
1298 wfProfileIn( __METHOD__
);
1299 wfDebug( __METHOD__
.": enter\n" );
1301 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1302 $blocked = $this->isBlocked( $bFromSlave );
1303 $allowUsertalk = ($wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false);
1304 # If a user's name is suppressed, they cannot make edits anywhere
1305 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1306 $title->getNamespace() == NS_USER_TALK
) {
1308 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1310 wfProfileOut( __METHOD__
);
1315 * If user is blocked, return the name of the user who placed the block
1316 * @return \string name of blocker
1318 function blockedBy() {
1319 $this->getBlockedStatus();
1320 return $this->mBlockedby
;
1324 * If user is blocked, return the specified reason for the block
1325 * @return \string Blocking reason
1327 function blockedFor() {
1328 $this->getBlockedStatus();
1329 return $this->mBlockreason
;
1333 * If user is blocked, return the ID for the block
1334 * @return \int Block ID
1336 function getBlockId() {
1337 $this->getBlockedStatus();
1338 return ($this->mBlock ?
$this->mBlock
->mId
: false);
1342 * Check if user is blocked on all wikis.
1343 * Do not use for actual edit permission checks!
1344 * This is intented for quick UI checks.
1346 * @param $ip \type{\string} IP address, uses current client if none given
1347 * @return \type{\bool} True if blocked, false otherwise
1349 function isBlockedGlobally( $ip = '' ) {
1350 if( $this->mBlockedGlobally
!== null ) {
1351 return $this->mBlockedGlobally
;
1353 // User is already an IP?
1354 if( IP
::isIPAddress( $this->getName() ) ) {
1355 $ip = $this->getName();
1360 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1361 $this->mBlockedGlobally
= (bool)$blocked;
1362 return $this->mBlockedGlobally
;
1366 * Check if user account is locked
1368 * @return \type{\bool} True if locked, false otherwise
1370 function isLocked() {
1371 if( $this->mLocked
!== null ) {
1372 return $this->mLocked
;
1375 $authUser = $wgAuth->getUserInstance( $this );
1376 $this->mLocked
= (bool)$authUser->isLocked();
1377 return $this->mLocked
;
1381 * Check if user account is hidden
1383 * @return \type{\bool} True if hidden, false otherwise
1385 function isHidden() {
1386 if( $this->mHideName
!== null ) {
1387 return $this->mHideName
;
1389 $this->getBlockedStatus();
1390 if( !$this->mHideName
) {
1392 $authUser = $wgAuth->getUserInstance( $this );
1393 $this->mHideName
= (bool)$authUser->isHidden();
1395 return $this->mHideName
;
1399 * Get the user's ID.
1400 * @return \int The user's ID; 0 if the user is anonymous or nonexistent
1403 if( $this->mId
=== null and $this->mName
!== null
1404 and User
::isIP( $this->mName
) ) {
1405 // Special case, we know the user is anonymous
1407 } elseif( $this->mId
=== null ) {
1408 // Don't load if this was initialized from an ID
1415 * Set the user and reload all fields according to a given ID
1416 * @param $v \int User ID to reload
1418 function setId( $v ) {
1420 $this->clearInstanceCache( 'id' );
1424 * Get the user name, or the IP of an anonymous user
1425 * @return \string User's name or IP address
1427 function getName() {
1428 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1429 # Special case optimisation
1430 return $this->mName
;
1433 if ( $this->mName
=== false ) {
1435 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1437 return $this->mName
;
1442 * Set the user name.
1444 * This does not reload fields from the database according to the given
1445 * name. Rather, it is used to create a temporary "nonexistent user" for
1446 * later addition to the database. It can also be used to set the IP
1447 * address for an anonymous user to something other than the current
1450 * @note User::newFromName() has rougly the same function, when the named user
1452 * @param $str \string New user name to set
1454 function setName( $str ) {
1456 $this->mName
= $str;
1460 * Get the user's name escaped by underscores.
1461 * @return \string Username escaped by underscores.
1463 function getTitleKey() {
1464 return str_replace( ' ', '_', $this->getName() );
1468 * Check if the user has new messages.
1469 * @return \bool True if the user has new messages
1471 function getNewtalk() {
1474 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1475 if( $this->mNewtalk
=== -1 ) {
1476 $this->mNewtalk
= false; # reset talk page status
1478 # Check memcached separately for anons, who have no
1479 # entire User object stored in there.
1482 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1483 $newtalk = $wgMemc->get( $key );
1484 if( strval( $newtalk ) !== '' ) {
1485 $this->mNewtalk
= (bool)$newtalk;
1487 // Since we are caching this, make sure it is up to date by getting it
1489 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1490 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1493 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1497 return (bool)$this->mNewtalk
;
1501 * Return the talk page(s) this user has new messages on.
1502 * @return \type{\arrayof{\string}} Array of page URLs
1504 function getNewMessageLinks() {
1506 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1509 if (!$this->getNewtalk())
1511 $up = $this->getUserPage();
1512 $utp = $up->getTalkPage();
1513 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1518 * Internal uncached check for new messages
1521 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1522 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1523 * @param $fromMaster \bool true to fetch from the master, false for a slave
1524 * @return \bool True if the user has new messages
1527 function checkNewtalk( $field, $id, $fromMaster = false ) {
1528 if ( $fromMaster ) {
1529 $db = wfGetDB( DB_MASTER
);
1531 $db = wfGetDB( DB_SLAVE
);
1533 $ok = $db->selectField( 'user_newtalk', $field,
1534 array( $field => $id ), __METHOD__
);
1535 return $ok !== false;
1539 * Add or update the new messages flag
1540 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1541 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1542 * @return \bool True if successful, false otherwise
1545 function updateNewtalk( $field, $id ) {
1546 $dbw = wfGetDB( DB_MASTER
);
1547 $dbw->insert( 'user_newtalk',
1548 array( $field => $id ),
1551 if ( $dbw->affectedRows() ) {
1552 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1555 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1561 * Clear the new messages flag for the given user
1562 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1563 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1564 * @return \bool True if successful, false otherwise
1567 function deleteNewtalk( $field, $id ) {
1568 $dbw = wfGetDB( DB_MASTER
);
1569 $dbw->delete( 'user_newtalk',
1570 array( $field => $id ),
1572 if ( $dbw->affectedRows() ) {
1573 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1576 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1582 * Update the 'You have new messages!' status.
1583 * @param $val \bool Whether the user has new messages
1585 function setNewtalk( $val ) {
1586 if( wfReadOnly() ) {
1591 $this->mNewtalk
= $val;
1593 if( $this->isAnon() ) {
1595 $id = $this->getName();
1598 $id = $this->getId();
1603 $changed = $this->updateNewtalk( $field, $id );
1605 $changed = $this->deleteNewtalk( $field, $id );
1608 if( $this->isAnon() ) {
1609 // Anons have a separate memcached space, since
1610 // user records aren't kept for them.
1611 $key = wfMemcKey( 'newtalk', 'ip', $id );
1612 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1615 $this->invalidateCache();
1620 * Generate a current or new-future timestamp to be stored in the
1621 * user_touched field when we update things.
1622 * @return \string Timestamp in TS_MW format
1624 private static function newTouchedTimestamp() {
1625 global $wgClockSkewFudge;
1626 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1630 * Clear user data from memcached.
1631 * Use after applying fun updates to the database; caller's
1632 * responsibility to update user_touched if appropriate.
1634 * Called implicitly from invalidateCache() and saveSettings().
1636 private function clearSharedCache() {
1640 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1645 * Immediately touch the user data cache for this account.
1646 * Updates user_touched field, and removes account data from memcached
1647 * for reload on the next hit.
1649 function invalidateCache() {
1652 $this->mTouched
= self
::newTouchedTimestamp();
1654 $dbw = wfGetDB( DB_MASTER
);
1655 $dbw->update( 'user',
1656 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1657 array( 'user_id' => $this->mId
),
1660 $this->clearSharedCache();
1665 * Validate the cache for this account.
1666 * @param $timestamp \string A timestamp in TS_MW format
1668 function validateCache( $timestamp ) {
1670 return ($timestamp >= $this->mTouched
);
1674 * Get the user touched timestamp
1676 function getTouched() {
1678 return $this->mTouched
;
1682 * Set the password and reset the random token.
1683 * Calls through to authentication plugin if necessary;
1684 * will have no effect if the auth plugin refuses to
1685 * pass the change through or if the legal password
1688 * As a special case, setting the password to null
1689 * wipes it, so the account cannot be logged in until
1690 * a new password is set, for instance via e-mail.
1692 * @param $str \string New password to set
1693 * @throws PasswordError on failure
1695 function setPassword( $str ) {
1698 if( $str !== null ) {
1699 if( !$wgAuth->allowPasswordChange() ) {
1700 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1703 if( !$this->isValidPassword( $str ) ) {
1704 global $wgMinimalPasswordLength;
1705 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1706 $wgMinimalPasswordLength ) );
1710 if( !$wgAuth->setPassword( $this, $str ) ) {
1711 throw new PasswordError( wfMsg( 'externaldberror' ) );
1714 $this->setInternalPassword( $str );
1720 * Set the password and reset the random token unconditionally.
1722 * @param $str \string New password to set
1724 function setInternalPassword( $str ) {
1728 if( $str === null ) {
1729 // Save an invalid hash...
1730 $this->mPassword
= '';
1732 $this->mPassword
= self
::crypt( $str );
1734 $this->mNewpassword
= '';
1735 $this->mNewpassTime
= null;
1739 * Get the user's current token.
1740 * @return \string Token
1742 function getToken() {
1744 return $this->mToken
;
1748 * Set the random token (used for persistent authentication)
1749 * Called from loadDefaults() among other places.
1751 * @param $token \string If specified, set the token to this value
1754 function setToken( $token = false ) {
1755 global $wgSecretKey, $wgProxyKey;
1758 if ( $wgSecretKey ) {
1759 $key = $wgSecretKey;
1760 } elseif ( $wgProxyKey ) {
1765 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1767 $this->mToken
= $token;
1772 * Set the cookie password
1774 * @param $str \string New cookie password
1777 function setCookiePassword( $str ) {
1779 $this->mCookiePassword
= md5( $str );
1783 * Set the password for a password reminder or new account email
1785 * @param $str \string New password to set
1786 * @param $throttle \bool If true, reset the throttle timestamp to the present
1788 function setNewpassword( $str, $throttle = true ) {
1790 $this->mNewpassword
= self
::crypt( $str );
1792 $this->mNewpassTime
= wfTimestampNow();
1797 * Has password reminder email been sent within the last
1798 * $wgPasswordReminderResendTime hours?
1799 * @return \bool True or false
1801 function isPasswordReminderThrottled() {
1802 global $wgPasswordReminderResendTime;
1804 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1807 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1808 return time() < $expiry;
1812 * Get the user's e-mail address
1813 * @return \string User's email address
1815 function getEmail() {
1817 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1818 return $this->mEmail
;
1822 * Get the timestamp of the user's e-mail authentication
1823 * @return \string TS_MW timestamp
1825 function getEmailAuthenticationTimestamp() {
1827 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1828 return $this->mEmailAuthenticated
;
1832 * Set the user's e-mail address
1833 * @param $str \string New e-mail address
1835 function setEmail( $str ) {
1837 $this->mEmail
= $str;
1838 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1842 * Get the user's real name
1843 * @return \string User's real name
1845 function getRealName() {
1847 return $this->mRealName
;
1851 * Set the user's real name
1852 * @param $str \string New real name
1854 function setRealName( $str ) {
1856 $this->mRealName
= $str;
1860 * Get the user's current setting for a given option.
1862 * @param $oname \string The option to check
1863 * @param $defaultOverride \string A default value returned if the option does not exist
1864 * @return \string User's current value for the option
1865 * @see getBoolOption()
1866 * @see getIntOption()
1868 function getOption( $oname, $defaultOverride = '' ) {
1871 if ( is_null( $this->mOptions
) ) {
1872 if($defaultOverride != '') {
1873 return $defaultOverride;
1875 $this->mOptions
= User
::getDefaultOptions();
1878 if ( array_key_exists( $oname, $this->mOptions
) ) {
1879 return trim( $this->mOptions
[$oname] );
1881 return $defaultOverride;
1886 * Get the user's current setting for a given option, as a boolean value.
1888 * @param $oname \string The option to check
1889 * @return \bool User's current value for the option
1892 function getBoolOption( $oname ) {
1893 return (bool)$this->getOption( $oname );
1898 * Get the user's current setting for a given option, as a boolean value.
1900 * @param $oname \string The option to check
1901 * @param $defaultOverride \int A default value returned if the option does not exist
1902 * @return \int User's current value for the option
1905 function getIntOption( $oname, $defaultOverride=0 ) {
1906 $val = $this->getOption( $oname );
1908 $val = $defaultOverride;
1910 return intval( $val );
1914 * Set the given option for a user.
1916 * @param $oname \string The option to set
1917 * @param $val \mixed New value to set
1919 function setOption( $oname, $val ) {
1921 if ( is_null( $this->mOptions
) ) {
1922 $this->mOptions
= User
::getDefaultOptions();
1924 if ( $oname == 'skin' ) {
1925 # Clear cached skin, so the new one displays immediately in Special:Preferences
1926 unset( $this->mSkin
);
1928 // Filter out any newlines that may have passed through input validation.
1929 // Newlines are used to separate items in the options blob.
1931 $val = str_replace( "\r\n", "\n", $val );
1932 $val = str_replace( "\r", "\n", $val );
1933 $val = str_replace( "\n", " ", $val );
1935 // Explicitly NULL values should refer to defaults
1936 global $wgDefaultUserOptions;
1937 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1938 $val = $wgDefaultUserOptions[$oname];
1940 $this->mOptions
[$oname] = $val;
1944 * Reset all options to the site defaults
1946 function restoreOptions() {
1947 $this->mOptions
= User
::getDefaultOptions();
1951 * Get the user's preferred date format.
1952 * @return \string User's preferred date format
1954 function getDatePreference() {
1955 // Important migration for old data rows
1956 if ( is_null( $this->mDatePreference
) ) {
1958 $value = $this->getOption( 'date' );
1959 $map = $wgLang->getDatePreferenceMigrationMap();
1960 if ( isset( $map[$value] ) ) {
1961 $value = $map[$value];
1963 $this->mDatePreference
= $value;
1965 return $this->mDatePreference
;
1969 * Get the permissions this user has.
1970 * @return \type{\arrayof{\string}} Array of permission names
1972 function getRights() {
1973 if ( is_null( $this->mRights
) ) {
1974 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1975 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1976 // Force reindexation of rights when a hook has unset one of them
1977 $this->mRights
= array_values( $this->mRights
);
1979 return $this->mRights
;
1983 * Get the list of explicit group memberships this user has.
1984 * The implicit * and user groups are not included.
1985 * @return \type{\arrayof{\string}} Array of internal group names
1987 function getGroups() {
1989 return $this->mGroups
;
1993 * Get the list of implicit group memberships this user has.
1994 * This includes all explicit groups, plus 'user' if logged in,
1995 * '*' for all accounts and autopromoted groups
1996 * @param $recache \bool Whether to avoid the cache
1997 * @return \type{\arrayof{\string}} Array of internal group names
1999 function getEffectiveGroups( $recache = false ) {
2000 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2001 $this->mEffectiveGroups
= $this->getGroups();
2002 $this->mEffectiveGroups
[] = '*';
2003 if( $this->getId() ) {
2004 $this->mEffectiveGroups
[] = 'user';
2006 $this->mEffectiveGroups
= array_unique( array_merge(
2007 $this->mEffectiveGroups
,
2008 Autopromote
::getAutopromoteGroups( $this )
2011 # Hook for additional groups
2012 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2015 return $this->mEffectiveGroups
;
2019 * Get the user's edit count.
2020 * @return \int User'e edit count
2022 function getEditCount() {
2024 if ( !isset( $this->mEditCount
) ) {
2025 /* Populate the count, if it has not been populated yet */
2026 $this->mEditCount
= User
::edits($this->mId
);
2028 return $this->mEditCount
;
2036 * Add the user to the given group.
2037 * This takes immediate effect.
2038 * @param $group \string Name of the group to add
2040 function addGroup( $group ) {
2041 $dbw = wfGetDB( DB_MASTER
);
2042 if( $this->getId() ) {
2043 $dbw->insert( 'user_groups',
2045 'ug_user' => $this->getID(),
2046 'ug_group' => $group,
2049 array( 'IGNORE' ) );
2052 $this->loadGroups();
2053 $this->mGroups
[] = $group;
2054 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2056 $this->invalidateCache();
2060 * Remove the user from the given group.
2061 * This takes immediate effect.
2062 * @param $group \string Name of the group to remove
2064 function removeGroup( $group ) {
2066 $dbw = wfGetDB( DB_MASTER
);
2067 $dbw->delete( 'user_groups',
2069 'ug_user' => $this->getID(),
2070 'ug_group' => $group,
2072 'User::removeGroup' );
2074 $this->loadGroups();
2075 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2076 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2078 $this->invalidateCache();
2083 * Get whether the user is logged in
2084 * @return \bool True or false
2086 function isLoggedIn() {
2087 return $this->getID() != 0;
2091 * Get whether the user is anonymous
2092 * @return \bool True or false
2095 return !$this->isLoggedIn();
2099 * Get whether the user is a bot
2100 * @return \bool True or false
2104 wfDeprecated( __METHOD__
);
2105 return $this->isAllowed( 'bot' );
2109 * Check if user is allowed to access a feature / make an action
2110 * @param $action \string action to be checked
2111 * @return \bool True if action is allowed, else false
2113 function isAllowed( $action = '' ) {
2114 if ( $action === '' )
2115 return true; // In the spirit of DWIM
2116 # Patrolling may not be enabled
2117 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2118 global $wgUseRCPatrol, $wgUseNPPatrol;
2119 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2122 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2123 # by misconfiguration: 0 == 'foo'
2124 return in_array( $action, $this->getRights(), true );
2128 * Check whether to enable recent changes patrol features for this user
2129 * @return \bool True or false
2131 public function useRCPatrol() {
2132 global $wgUseRCPatrol;
2133 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2137 * Check whether to enable new pages patrol features for this user
2138 * @return \bool True or false
2140 public function useNPPatrol() {
2141 global $wgUseRCPatrol, $wgUseNPPatrol;
2142 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2146 * Get the current skin, loading it if required
2147 * @return \type{Skin} Current skin
2148 * @todo FIXME : need to check the old failback system [AV]
2150 function &getSkin() {
2151 global $wgRequest, $wgAllowUserSkin, $wgDefaultSkin;
2152 if ( ! isset( $this->mSkin
) ) {
2153 wfProfileIn( __METHOD__
);
2155 if( $wgAllowUserSkin ) {
2157 $userSkin = $this->getOption( 'skin' );
2158 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2160 # if we're not allowing users to override, then use the default
2161 $userSkin = $wgDefaultSkin;
2164 $this->mSkin
=& Skin
::newFromKey( $userSkin );
2165 wfProfileOut( __METHOD__
);
2167 return $this->mSkin
;
2171 * Check the watched status of an article.
2172 * @param $title \type{Title} Title of the article to look at
2173 * @return \bool True if article is watched
2175 function isWatched( $title ) {
2176 $wl = WatchedItem
::fromUserTitle( $this, $title );
2177 return $wl->isWatched();
2182 * @param $title \type{Title} Title of the article to look at
2184 function addWatch( $title ) {
2185 $wl = WatchedItem
::fromUserTitle( $this, $title );
2187 $this->invalidateCache();
2191 * Stop watching an article.
2192 * @param $title \type{Title} Title of the article to look at
2194 function removeWatch( $title ) {
2195 $wl = WatchedItem
::fromUserTitle( $this, $title );
2197 $this->invalidateCache();
2201 * Clear the user's notification timestamp for the given title.
2202 * If e-notif e-mails are on, they will receive notification mails on
2203 * the next change of the page if it's watched etc.
2204 * @param $title \type{Title} Title of the article to look at
2206 function clearNotification( &$title ) {
2207 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2209 # Do nothing if the database is locked to writes
2210 if( wfReadOnly() ) {
2214 if ($title->getNamespace() == NS_USER_TALK
&&
2215 $title->getText() == $this->getName() ) {
2216 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2218 $this->setNewtalk( false );
2221 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2225 if( $this->isAnon() ) {
2226 // Nothing else to do...
2230 // Only update the timestamp if the page is being watched.
2231 // The query to find out if it is watched is cached both in memcached and per-invocation,
2232 // and when it does have to be executed, it can be on a slave
2233 // If this is the user's newtalk page, we always update the timestamp
2234 if ($title->getNamespace() == NS_USER_TALK
&&
2235 $title->getText() == $wgUser->getName())
2238 } elseif ( $this->getId() == $wgUser->getId() ) {
2239 $watched = $title->userIsWatching();
2244 // If the page is watched by the user (or may be watched), update the timestamp on any
2245 // any matching rows
2247 $dbw = wfGetDB( DB_MASTER
);
2248 $dbw->update( 'watchlist',
2250 'wl_notificationtimestamp' => NULL
2251 ), array( /* WHERE */
2252 'wl_title' => $title->getDBkey(),
2253 'wl_namespace' => $title->getNamespace(),
2254 'wl_user' => $this->getID()
2261 * Resets all of the given user's page-change notification timestamps.
2262 * If e-notif e-mails are on, they will receive notification mails on
2263 * the next change of any watched page.
2265 * @param $currentUser \int User ID
2267 function clearAllNotifications( $currentUser ) {
2268 global $wgUseEnotif, $wgShowUpdatedMarker;
2269 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2270 $this->setNewtalk( false );
2273 if( $currentUser != 0 ) {
2274 $dbw = wfGetDB( DB_MASTER
);
2275 $dbw->update( 'watchlist',
2277 'wl_notificationtimestamp' => NULL
2278 ), array( /* WHERE */
2279 'wl_user' => $currentUser
2282 # We also need to clear here the "you have new message" notification for the own user_talk page
2283 # This is cleared one page view later in Article::viewUpdates();
2288 * Encode this user's options as a string
2289 * @return \string Encoded options
2292 function encodeOptions() {
2294 if ( is_null( $this->mOptions
) ) {
2295 $this->mOptions
= User
::getDefaultOptions();
2298 foreach ( $this->mOptions
as $oname => $oval ) {
2299 array_push( $a, $oname.'='.$oval );
2301 $s = implode( "\n", $a );
2306 * Set this user's options from an encoded string
2307 * @param $str \string Encoded options to import
2310 function decodeOptions( $str ) {
2311 $this->mOptions
= array();
2312 $a = explode( "\n", $str );
2313 foreach ( $a as $s ) {
2315 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2316 $this->mOptions
[$m[1]] = $m[2];
2322 * Set a cookie on the user's client. Wrapper for
2323 * WebResponse::setCookie
2324 * @param $name \string Name of the cookie to set
2325 * @param $value \string Value to set
2326 * @param $exp \int Expiration time, as a UNIX time value;
2327 * if 0 or not specified, use the default $wgCookieExpiration
2329 protected function setCookie( $name, $value, $exp=0 ) {
2331 $wgRequest->response()->setcookie( $name, $value, $exp );
2335 * Clear a cookie on the user's client
2336 * @param $name \string Name of the cookie to clear
2338 protected function clearCookie( $name ) {
2339 $this->setCookie( $name, '', time() - 86400 );
2343 * Set the default cookies for this session on the user's client.
2345 function setCookies() {
2347 if ( 0 == $this->mId
) return;
2349 'wsUserID' => $this->mId
,
2350 'wsToken' => $this->mToken
,
2351 'wsUserName' => $this->getName()
2354 'UserID' => $this->mId
,
2355 'UserName' => $this->getName(),
2357 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2358 $cookies['Token'] = $this->mToken
;
2360 $cookies['Token'] = false;
2363 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2364 #check for null, since the hook could cause a null value
2365 if ( !is_null( $session ) && isset( $_SESSION ) ){
2366 $_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();
2436 $this->getUserPage()->invalidateCache();
2440 * If only this user's username is known, and it exists, return the user ID.
2442 function idForName() {
2443 $s = trim( $this->getName() );
2444 if ( $s === '' ) return 0;
2446 $dbr = wfGetDB( DB_SLAVE
);
2447 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2448 if ( $id === false ) {
2455 * Add a user to the database, return the user object
2457 * @param $name \string Username to add
2458 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2459 * - password The user's password. Password logins will be disabled if this is omitted.
2460 * - newpassword A temporary password mailed to the user
2461 * - email The user's email address
2462 * - email_authenticated The email authentication timestamp
2463 * - real_name The user's real name
2464 * - options An associative array of non-default options
2465 * - token Random authentication token. Do not set.
2466 * - registration Registration timestamp. Do not set.
2468 * @return \type{User} A new User object, or null if the username already exists
2470 static function createNew( $name, $params = array() ) {
2473 if ( isset( $params['options'] ) ) {
2474 $user->mOptions
= $params['options'] +
$user->mOptions
;
2475 unset( $params['options'] );
2477 $dbw = wfGetDB( DB_MASTER
);
2478 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2480 'user_id' => $seqVal,
2481 'user_name' => $name,
2482 'user_password' => $user->mPassword
,
2483 'user_newpassword' => $user->mNewpassword
,
2484 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2485 'user_email' => $user->mEmail
,
2486 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2487 'user_real_name' => $user->mRealName
,
2488 'user_options' => $user->encodeOptions(),
2489 'user_token' => $user->mToken
,
2490 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2491 'user_editcount' => 0,
2493 foreach ( $params as $name => $value ) {
2494 $fields["user_$name"] = $value;
2496 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2497 if ( $dbw->affectedRows() ) {
2498 $newUser = User
::newFromId( $dbw->insertId() );
2506 * Add this existing user object to the database
2508 function addToDatabase() {
2510 $dbw = wfGetDB( DB_MASTER
);
2511 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2512 $dbw->insert( 'user',
2514 'user_id' => $seqVal,
2515 'user_name' => $this->mName
,
2516 'user_password' => $this->mPassword
,
2517 'user_newpassword' => $this->mNewpassword
,
2518 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2519 'user_email' => $this->mEmail
,
2520 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2521 'user_real_name' => $this->mRealName
,
2522 'user_options' => $this->encodeOptions(),
2523 'user_token' => $this->mToken
,
2524 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2525 'user_editcount' => 0,
2528 $this->mId
= $dbw->insertId();
2530 // Clear instance cache other than user table data, which is already accurate
2531 $this->clearInstanceCache();
2535 * If this (non-anonymous) user is blocked, block any IP address
2536 * they've successfully logged in from.
2538 function spreadBlock() {
2539 wfDebug( __METHOD__
."()\n" );
2541 if ( $this->mId
== 0 ) {
2545 $userblock = Block
::newFromDB( '', $this->mId
);
2546 if ( !$userblock ) {
2550 $userblock->doAutoblock( wfGetIp() );
2555 * Generate a string which will be different for any combination of
2556 * user options which would produce different parser output.
2557 * This will be used as part of the hash key for the parser cache,
2558 * so users will the same options can share the same cached data
2561 * Extensions which require it should install 'PageRenderingHash' hook,
2562 * which will give them a chance to modify this key based on their own
2565 * @return \string Page rendering hash
2567 function getPageRenderingHash() {
2568 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2570 return $this->mHash
;
2573 // stubthreshold is only included below for completeness,
2574 // it will always be 0 when this function is called by parsercache.
2576 $confstr = $this->getOption( 'math' );
2577 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2578 if ( $wgUseDynamicDates ) {
2579 $confstr .= '!' . $this->getDatePreference();
2581 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2582 $confstr .= '!' . $wgLang->getCode();
2583 $confstr .= '!' . $this->getOption( 'thumbsize' );
2584 // add in language specific options, if any
2585 $extra = $wgContLang->getExtraHashOptions();
2588 $confstr .= $wgRenderHashAppend;
2590 // Give a chance for extensions to modify the hash, if they have
2591 // extra options or other effects on the parser cache.
2592 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2594 // Make it a valid memcached key fragment
2595 $confstr = str_replace( ' ', '_', $confstr );
2596 $this->mHash
= $confstr;
2601 * Get whether the user is explicitly blocked from account creation.
2602 * @return \bool True if blocked
2604 function isBlockedFromCreateAccount() {
2605 $this->getBlockedStatus();
2606 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2610 * Get whether the user is blocked from using Special:Emailuser.
2611 * @return \bool True if blocked
2613 function isBlockedFromEmailuser() {
2614 $this->getBlockedStatus();
2615 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2619 * Get whether the user is allowed to create an account.
2620 * @return \bool True if allowed
2622 function isAllowedToCreateAccount() {
2623 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2629 function setLoaded( $loaded ) {
2630 wfDeprecated( __METHOD__
);
2634 * Get this user's personal page title.
2636 * @return \type{Title} User's personal page title
2638 function getUserPage() {
2639 return Title
::makeTitle( NS_USER
, $this->getName() );
2643 * Get this user's talk page title.
2645 * @return \type{Title} User's talk page title
2647 function getTalkPage() {
2648 $title = $this->getUserPage();
2649 return $title->getTalkPage();
2653 * Get the maximum valid user ID.
2654 * @return \int User ID
2657 function getMaxID() {
2658 static $res; // cache
2660 if ( isset( $res ) )
2663 $dbr = wfGetDB( DB_SLAVE
);
2664 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2669 * Determine whether the user is a newbie. Newbies are either
2670 * anonymous IPs, or the most recently created accounts.
2671 * @return \bool True if the user is a newbie
2673 function isNewbie() {
2674 return !$this->isAllowed( 'autoconfirmed' );
2678 * Is the user active? We check to see if they've made at least
2679 * X number of edits in the last Y days.
2681 * @return \bool True if the user is active, false if not.
2683 public function isActiveEditor() {
2684 global $wgActiveUserEditCount, $wgActiveUserDays;
2685 $dbr = wfGetDB( DB_SLAVE
);
2687 // Stolen without shame from RC
2688 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2689 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
2690 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2692 $res = $dbr->select( 'revision', '1',
2693 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2695 array('LIMIT' => $wgActiveUserEditCount ) );
2697 $count = $dbr->numRows($res);
2698 $dbr->freeResult($res);
2700 return $count == $wgActiveUserEditCount;
2704 * Check to see if the given clear-text password is one of the accepted passwords
2705 * @param $password \string user password.
2706 * @return \bool True if the given password is correct, otherwise False.
2708 function checkPassword( $password ) {
2712 // Even though we stop people from creating passwords that
2713 // are shorter than this, doesn't mean people wont be able
2714 // to. Certain authentication plugins do NOT want to save
2715 // domain passwords in a mysql database, so we should
2716 // check this (incase $wgAuth->strict() is false).
2717 if( !$this->isValidPassword( $password ) ) {
2721 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2723 } elseif( $wgAuth->strict() ) {
2724 /* Auth plugin doesn't allow local authentication */
2726 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2727 /* Auth plugin doesn't allow local authentication for this user name */
2730 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2732 } elseif ( function_exists( 'iconv' ) ) {
2733 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2734 # Check for this with iconv
2735 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2736 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2744 * Check if the given clear-text password matches the temporary password
2745 * sent by e-mail for password reset operations.
2746 * @return \bool True if matches, false otherwise
2748 function checkTemporaryPassword( $plaintext ) {
2749 global $wgNewPasswordExpiry;
2750 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
2752 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
2753 return ( time() < $expiry );
2760 * Initialize (if necessary) and return a session token value
2761 * which can be used in edit forms to show that the user's
2762 * login credentials aren't being hijacked with a foreign form
2765 * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2766 * @return \string The new edit token
2768 function editToken( $salt = '' ) {
2769 if ( $this->isAnon() ) {
2770 return EDIT_TOKEN_SUFFIX
;
2772 if( !isset( $_SESSION['wsEditToken'] ) ) {
2773 $token = $this->generateToken();
2774 $_SESSION['wsEditToken'] = $token;
2776 $token = $_SESSION['wsEditToken'];
2778 if( is_array( $salt ) ) {
2779 $salt = implode( '|', $salt );
2781 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2786 * Generate a looking random token for various uses.
2788 * @param $salt \string Optional salt value
2789 * @return \string The new random token
2791 function generateToken( $salt = '' ) {
2792 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2793 return md5( $token . $salt );
2797 * Check given value against the token value stored in the session.
2798 * A match should confirm that the form was submitted from the
2799 * user's own login session, not a form submission from a third-party
2802 * @param $val \string Input value to compare
2803 * @param $salt \string Optional function-specific data for hashing
2804 * @return \bool Whether the token matches
2806 function matchEditToken( $val, $salt = '' ) {
2807 $sessionToken = $this->editToken( $salt );
2808 if ( $val != $sessionToken ) {
2809 wfDebug( "User::matchEditToken: broken session data\n" );
2811 return $val == $sessionToken;
2815 * Check given value against the token value stored in the session,
2816 * ignoring the suffix.
2818 * @param $val \string Input value to compare
2819 * @param $salt \string Optional function-specific data for hashing
2820 * @return \bool Whether the token matches
2822 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2823 $sessionToken = $this->editToken( $salt );
2824 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2828 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2829 * mail to the user's given address.
2831 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure.
2833 function sendConfirmationMail() {
2835 $expiration = null; // gets passed-by-ref and defined in next line.
2836 $token = $this->confirmationToken( $expiration );
2837 $url = $this->confirmationTokenUrl( $token );
2838 $invalidateURL = $this->invalidationTokenUrl( $token );
2839 $this->saveSettings();
2841 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2842 wfMsg( 'confirmemail_body',
2846 $wgLang->timeanddate( $expiration, false ),
2851 * Send an e-mail to this user's account. Does not check for
2852 * confirmed status or validity.
2854 * @param $subject \string Message subject
2855 * @param $body \string Message body
2856 * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2857 * @param $replyto \string Reply-To address
2858 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure
2860 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2861 if( is_null( $from ) ) {
2862 global $wgPasswordSender;
2863 $from = $wgPasswordSender;
2866 $to = new MailAddress( $this );
2867 $sender = new MailAddress( $from );
2868 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2872 * Generate, store, and return a new e-mail confirmation code.
2873 * A hash (unsalted, since it's used as a key) is stored.
2875 * @note Call saveSettings() after calling this function to commit
2876 * this change to the database.
2878 * @param[out] &$expiration \mixed Accepts the expiration time
2879 * @return \string New token
2882 function confirmationToken( &$expiration ) {
2884 $expires = $now +
7 * 24 * 60 * 60;
2885 $expiration = wfTimestamp( TS_MW
, $expires );
2886 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2887 $hash = md5( $token );
2889 $this->mEmailToken
= $hash;
2890 $this->mEmailTokenExpires
= $expiration;
2895 * Return a URL the user can use to confirm their email address.
2896 * @param $token \string Accepts the email confirmation token
2897 * @return \string New token URL
2900 function confirmationTokenUrl( $token ) {
2901 return $this->getTokenUrl( 'ConfirmEmail', $token );
2904 * Return a URL the user can use to invalidate their email address.
2905 * @param $token \string Accepts the email confirmation token
2906 * @return \string New token URL
2909 function invalidationTokenUrl( $token ) {
2910 return $this->getTokenUrl( 'Invalidateemail', $token );
2914 * Internal function to format the e-mail validation/invalidation URLs.
2915 * This uses $wgArticlePath directly as a quickie hack to use the
2916 * hardcoded English names of the Special: pages, for ASCII safety.
2918 * @note Since these URLs get dropped directly into emails, using the
2919 * short English names avoids insanely long URL-encoded links, which
2920 * also sometimes can get corrupted in some browsers/mailers
2921 * (bug 6957 with Gmail and Internet Explorer).
2923 * @param $page \string Special page
2924 * @param $token \string Token
2925 * @return \string Formatted URL
2927 protected function getTokenUrl( $page, $token ) {
2928 global $wgArticlePath;
2932 "Special:$page/$token",
2937 * Mark the e-mail address confirmed.
2939 * @note Call saveSettings() after calling this function to commit the change.
2941 function confirmEmail() {
2942 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2947 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2948 * address if it was already confirmed.
2950 * @note Call saveSettings() after calling this function to commit the change.
2952 function invalidateEmail() {
2954 $this->mEmailToken
= null;
2955 $this->mEmailTokenExpires
= null;
2956 $this->setEmailAuthenticationTimestamp( null );
2961 * Set the e-mail authentication timestamp.
2962 * @param $timestamp \string TS_MW timestamp
2964 function setEmailAuthenticationTimestamp( $timestamp ) {
2966 $this->mEmailAuthenticated
= $timestamp;
2967 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2971 * Is this user allowed to send e-mails within limits of current
2972 * site configuration?
2973 * @return \bool True if allowed
2975 function canSendEmail() {
2976 global $wgEnableEmail, $wgEnableUserEmail;
2977 if( !$wgEnableEmail ||
!$wgEnableUserEmail ) {
2980 $canSend = $this->isEmailConfirmed();
2981 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2986 * Is this user allowed to receive e-mails within limits of current
2987 * site configuration?
2988 * @return \bool True if allowed
2990 function canReceiveEmail() {
2991 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2995 * Is this user's e-mail address valid-looking and confirmed within
2996 * limits of the current site configuration?
2998 * @note If $wgEmailAuthentication is on, this may require the user to have
2999 * confirmed their address by returning a code or using a password
3000 * sent to the address from the wiki.
3002 * @return \bool True if confirmed
3004 function isEmailConfirmed() {
3005 global $wgEmailAuthentication;
3008 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3009 if( $this->isAnon() )
3011 if( !self
::isValidEmailAddr( $this->mEmail
) )
3013 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3022 * Check whether there is an outstanding request for e-mail confirmation.
3023 * @return \bool True if pending
3025 function isEmailConfirmationPending() {
3026 global $wgEmailAuthentication;
3027 return $wgEmailAuthentication &&
3028 !$this->isEmailConfirmed() &&
3029 $this->mEmailToken
&&
3030 $this->mEmailTokenExpires
> wfTimestamp();
3034 * Get the timestamp of account creation.
3036 * @return \types{\string,\bool} string Timestamp of account creation, or false for
3037 * non-existent/anonymous user accounts.
3039 public function getRegistration() {
3040 return $this->getId() > 0
3041 ?
$this->mRegistration
3046 * Get the timestamp of the first edit
3048 * @return \types{\string,\bool} string Timestamp of first edit, or false for
3049 * non-existent/anonymous user accounts.
3051 public function getFirstEditTimestamp() {
3052 if( $this->getId() == 0 ) return false; // anons
3053 $dbr = wfGetDB( DB_SLAVE
);
3054 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3055 array( 'rev_user' => $this->getId() ),
3057 array( 'ORDER BY' => 'rev_timestamp ASC' )
3059 if( !$time ) return false; // no edits
3060 return wfTimestamp( TS_MW
, $time );
3064 * Get the permissions associated with a given list of groups
3066 * @param $groups \type{\arrayof{\string}} List of internal group names
3067 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3069 static function getGroupPermissions( $groups ) {
3070 global $wgGroupPermissions;
3072 foreach( $groups as $group ) {
3073 if( isset( $wgGroupPermissions[$group] ) ) {
3074 $rights = array_merge( $rights,
3075 // array_filter removes empty items
3076 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3079 return array_unique($rights);
3083 * Get all the groups who have a given permission
3085 * @param $role \string Role to check
3086 * @return \type{\arrayof{\string}} List of internal group names with the given permission
3088 static function getGroupsWithPermission( $role ) {
3089 global $wgGroupPermissions;
3090 $allowedGroups = array();
3091 foreach ( $wgGroupPermissions as $group => $rights ) {
3092 if ( isset( $rights[$role] ) && $rights[$role] ) {
3093 $allowedGroups[] = $group;
3096 return $allowedGroups;
3100 * Get the localized descriptive name for a group, if it exists
3102 * @param $group \string Internal group name
3103 * @return \string Localized descriptive group name
3105 static function getGroupName( $group ) {
3106 global $wgMessageCache;
3107 $wgMessageCache->loadAllMessages();
3108 $key = "group-$group";
3109 $name = wfMsg( $key );
3110 return $name == '' ||
wfEmptyMsg( $key, $name )
3116 * Get the localized descriptive name for a member of a group, if it exists
3118 * @param $group \string Internal group name
3119 * @return \string Localized name for group member
3121 static function getGroupMember( $group ) {
3122 global $wgMessageCache;
3123 $wgMessageCache->loadAllMessages();
3124 $key = "group-$group-member";
3125 $name = wfMsg( $key );
3126 return $name == '' ||
wfEmptyMsg( $key, $name )
3132 * Return the set of defined explicit groups.
3133 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3134 * are not included, as they are defined automatically, not in the database.
3135 * @return \type{\arrayof{\string}} Array of internal group names
3137 static function getAllGroups() {
3138 global $wgGroupPermissions;
3140 array_keys( $wgGroupPermissions ),
3141 self
::getImplicitGroups()
3146 * Get a list of all available permissions.
3147 * @return \type{\arrayof{\string}} Array of permission names
3149 static function getAllRights() {
3150 if ( self
::$mAllRights === false ) {
3151 global $wgAvailableRights;
3152 if ( count( $wgAvailableRights ) ) {
3153 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3155 self
::$mAllRights = self
::$mCoreRights;
3157 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3159 return self
::$mAllRights;
3163 * Get a list of implicit groups
3164 * @return \type{\arrayof{\string}} Array of internal group names
3166 public static function getImplicitGroups() {
3167 global $wgImplicitGroups;
3168 $groups = $wgImplicitGroups;
3169 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3174 * Get the title of a page describing a particular group
3176 * @param $group \string Internal group name
3177 * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3179 static function getGroupPage( $group ) {
3180 global $wgMessageCache;
3181 $wgMessageCache->loadAllMessages();
3182 $page = wfMsgForContent( 'grouppage-' . $group );
3183 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3184 $title = Title
::newFromText( $page );
3185 if( is_object( $title ) )
3192 * Create a link to the group in HTML, if available;
3193 * else return the group name.
3195 * @param $group \string Internal name of the group
3196 * @param $text \string The text of the link
3197 * @return \string HTML link to the group
3199 static function makeGroupLinkHTML( $group, $text = '' ) {
3201 $text = self
::getGroupName( $group );
3203 $title = self
::getGroupPage( $group );
3206 $sk = $wgUser->getSkin();
3207 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3214 * Create a link to the group in Wikitext, if available;
3215 * else return the group name.
3217 * @param $group \string Internal name of the group
3218 * @param $text \string The text of the link
3219 * @return \string Wikilink to the group
3221 static function makeGroupLinkWiki( $group, $text = '' ) {
3223 $text = self
::getGroupName( $group );
3225 $title = self
::getGroupPage( $group );
3227 $page = $title->getPrefixedText();
3228 return "[[$page|$text]]";
3235 * Increment the user's edit-count field.
3236 * Will have no effect for anonymous users.
3238 function incEditCount() {
3239 if( !$this->isAnon() ) {
3240 $dbw = wfGetDB( DB_MASTER
);
3241 $dbw->update( 'user',
3242 array( 'user_editcount=user_editcount+1' ),
3243 array( 'user_id' => $this->getId() ),
3246 // Lazy initialization check...
3247 if( $dbw->affectedRows() == 0 ) {
3248 // Pull from a slave to be less cruel to servers
3249 // Accuracy isn't the point anyway here
3250 $dbr = wfGetDB( DB_SLAVE
);
3251 $count = $dbr->selectField( 'revision',
3253 array( 'rev_user' => $this->getId() ),
3256 // Now here's a goddamn hack...
3257 if( $dbr !== $dbw ) {
3258 // If we actually have a slave server, the count is
3259 // at least one behind because the current transaction
3260 // has not been committed and replicated.
3263 // But if DB_SLAVE is selecting the master, then the
3264 // count we just read includes the revision that was
3265 // just added in the working transaction.
3268 $dbw->update( 'user',
3269 array( 'user_editcount' => $count ),
3270 array( 'user_id' => $this->getId() ),
3274 // edit count in user cache too
3275 $this->invalidateCache();
3279 * Get the description of a given right
3281 * @param $right \string Right to query
3282 * @return \string Localized description of the right
3284 static function getRightDescription( $right ) {
3285 global $wgMessageCache;
3286 $wgMessageCache->loadAllMessages();
3287 $key = "right-$right";
3288 $name = wfMsg( $key );
3289 return $name == '' ||
wfEmptyMsg( $key, $name )
3295 * Make an old-style password hash
3297 * @param $password \string Plain-text password
3298 * @param $userId \string User ID
3299 * @return \string Password hash
3301 static function oldCrypt( $password, $userId ) {
3302 global $wgPasswordSalt;
3303 if ( $wgPasswordSalt ) {
3304 return md5( $userId . '-' . md5( $password ) );
3306 return md5( $password );
3311 * Make a new-style password hash
3313 * @param $password \string Plain-text password
3314 * @param $salt \string Optional salt, may be random or the user ID.
3315 * If unspecified or false, will generate one automatically
3316 * @return \string Password hash
3318 static function crypt( $password, $salt = false ) {
3319 global $wgPasswordSalt;
3322 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3326 if( $wgPasswordSalt ) {
3327 if ( $salt === false ) {
3328 $salt = substr( wfGenerateToken(), 0, 8 );
3330 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3332 return ':A:' . md5( $password );
3337 * Compare a password hash with a plain-text password. Requires the user
3338 * ID if there's a chance that the hash is an old-style hash.
3340 * @param $hash \string Password hash
3341 * @param $password \string Plain-text password to compare
3342 * @param $userId \string User ID for old-style password salt
3345 static function comparePasswords( $hash, $password, $userId = false ) {
3347 $type = substr( $hash, 0, 3 );
3350 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3354 if ( $type == ':A:' ) {
3356 return md5( $password ) === substr( $hash, 3 );
3357 } elseif ( $type == ':B:' ) {
3359 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3360 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3363 return self
::oldCrypt( $password, $userId ) === $hash;
3368 * Add a newuser log entry for this user
3369 * @param $byEmail Boolean: account made by email?
3371 public function addNewUserLogEntry( $byEmail = false ) {
3372 global $wgUser, $wgContLang, $wgNewUserLog;
3373 if( empty($wgNewUserLog) ) {
3374 return true; // disabled
3376 $talk = $wgContLang->getFormattedNsText( NS_TALK
);
3377 if( $this->getName() == $wgUser->getName() ) {
3381 $action = 'create2';
3382 $message = $byEmail ?
wfMsgForContent( 'newuserlog-byemail' ) : '';
3384 $log = new LogPage( 'newusers' );
3385 $log->addEntry( $action, $this->getUserPage(), $message, array( $this->getId() ) );
3390 * Add an autocreate newuser log entry for this user
3391 * Used by things like CentralAuth and perhaps other authplugins.
3393 public function addNewUserLogEntryAutoCreate() {
3394 global $wgNewUserLog;
3395 if( empty($wgNewUserLog) ) {
3396 return true; // disabled
3398 $log = new LogPage( 'newusers', false );
3399 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );