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',
160 'override-export-depth',
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 ) {
591 global $wgInvalidUsernameCharacters;
593 self
::isUsableName( $name ) &&
595 // Registration-time character blacklisting...
596 !preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name );
600 * Is the input a valid password for this user?
602 * @param $password \string Desired password
603 * @return \bool True or false
605 function isValidPassword( $password ) {
606 global $wgMinimalPasswordLength, $wgContLang;
609 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
611 if( $result === false )
614 // Password needs to be long enough, and can't be the same as the username
615 return strlen( $password ) >= $wgMinimalPasswordLength
616 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
620 * Does a string look like an e-mail address?
622 * There used to be a regular expression here, it got removed because it
623 * rejected valid addresses. Actually just check if there is '@' somewhere
624 * in the given address.
626 * @todo Check for RFC 2822 compilance (bug 959)
628 * @param $addr \string E-mail address
629 * @return \bool True or false
631 public static function isValidEmailAddr( $addr ) {
633 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
637 return strpos( $addr, '@' ) !== false;
641 * Given unvalidated user input, return a canonical username, or false if
642 * the username is invalid.
643 * @param $name \string User input
644 * @param $validate \types{\string,\bool} Type of validation to use:
645 * - false No validation
646 * - 'valid' Valid for batch processes
647 * - 'usable' Valid for batch processes and login
648 * - 'creatable' Valid for batch processes, login and account creation
650 static function getCanonicalName( $name, $validate = 'valid' ) {
651 # Force usernames to capital
653 $name = $wgContLang->ucfirst( $name );
655 # Reject names containing '#'; these will be cleaned up
656 # with title normalisation, but then it's too late to
658 if( strpos( $name, '#' ) !== false )
661 # Clean up name according to title rules
662 $t = ($validate === 'valid') ?
663 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
664 # Check for invalid titles
665 if( is_null( $t ) ) {
669 # Reject various classes of invalid names
670 $name = $t->getText();
672 $name = $wgAuth->getCanonicalName( $t->getText() );
674 switch ( $validate ) {
678 if ( !User
::isValidUserName( $name ) ) {
683 if ( !User
::isUsableName( $name ) ) {
688 if ( !User
::isCreatableName( $name ) ) {
693 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
699 * Count the number of edits of a user
700 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
702 * @param $uid \int User ID to check
703 * @return \int The user's edit count
705 static function edits( $uid ) {
706 wfProfileIn( __METHOD__
);
707 $dbr = wfGetDB( DB_SLAVE
);
708 // check if the user_editcount field has been initialized
709 $field = $dbr->selectField(
710 'user', 'user_editcount',
711 array( 'user_id' => $uid ),
715 if( $field === null ) { // it has not been initialized. do so.
716 $dbw = wfGetDB( DB_MASTER
);
717 $count = $dbr->selectField(
718 'revision', 'count(*)',
719 array( 'rev_user' => $uid ),
724 array( 'user_editcount' => $count ),
725 array( 'user_id' => $uid ),
731 wfProfileOut( __METHOD__
);
736 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
737 * @todo hash random numbers to improve security, like generateToken()
739 * @return \string New random password
741 static function randomPassword() {
742 global $wgMinimalPasswordLength;
743 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
744 $l = strlen( $pwchars ) - 1;
746 $pwlength = max( 7, $wgMinimalPasswordLength );
747 $digit = mt_rand(0, $pwlength - 1);
749 for ( $i = 0; $i < $pwlength; $i++
) {
750 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
756 * Set cached properties to default.
758 * @note This no longer clears uncached lazy-initialised properties;
759 * the constructor does that instead.
762 function loadDefaults( $name = false ) {
763 wfProfileIn( __METHOD__
);
765 global $wgCookiePrefix;
768 $this->mName
= $name;
769 $this->mRealName
= '';
770 $this->mPassword
= $this->mNewpassword
= '';
771 $this->mNewpassTime
= null;
773 $this->mOptions
= null; # Defer init
775 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
776 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
778 $this->mTouched
= '0'; # Allow any pages to be cached
781 $this->setToken(); # Random
782 $this->mEmailAuthenticated
= null;
783 $this->mEmailToken
= '';
784 $this->mEmailTokenExpires
= null;
785 $this->mRegistration
= wfTimestamp( TS_MW
);
786 $this->mGroups
= array();
788 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
790 wfProfileOut( __METHOD__
);
794 * @deprecated Use wfSetupSession().
796 function SetupSession() {
797 wfDeprecated( __METHOD__
);
802 * Load user data from the session or login cookie. If there are no valid
803 * credentials, initialises the user as an anonymous user.
804 * @return \bool True if the user is logged in, false otherwise.
806 private function loadFromSession() {
807 global $wgMemc, $wgCookiePrefix;
810 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
811 if ( $result !== null ) {
815 if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
816 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
817 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
818 $this->loadDefaults(); // Possible collision!
819 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
820 cookie user ID ($sId) don't match!" );
823 $_SESSION['wsUserID'] = $sId;
824 } else if ( isset( $_SESSION['wsUserID'] ) ) {
825 if ( $_SESSION['wsUserID'] != 0 ) {
826 $sId = $_SESSION['wsUserID'];
828 $this->loadDefaults();
832 $this->loadDefaults();
836 if ( isset( $_SESSION['wsUserName'] ) ) {
837 $sName = $_SESSION['wsUserName'];
838 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
839 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
840 $_SESSION['wsUserName'] = $sName;
842 $this->loadDefaults();
846 $passwordCorrect = FALSE;
848 if ( !$this->loadFromId() ) {
849 # Not a valid ID, loadFromId has switched the object to anon for us
853 if ( isset( $_SESSION['wsToken'] ) ) {
854 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
856 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
857 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
860 # No session or persistent login cookie
861 $this->loadDefaults();
865 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
866 $_SESSION['wsToken'] = $this->mToken
;
867 wfDebug( "Logged in from $from\n" );
870 # Invalid credentials
871 wfDebug( "Can't log in from $from, invalid credentials\n" );
872 $this->loadDefaults();
878 * Load user and user_group data from the database.
879 * $this::mId must be set, this is how the user is identified.
881 * @return \bool True if the user exists, false if the user is anonymous
884 function loadFromDatabase() {
886 $this->mId
= intval( $this->mId
);
888 /** Anonymous user */
890 $this->loadDefaults();
894 $dbr = wfGetDB( DB_MASTER
);
895 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
897 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
899 if ( $s !== false ) {
900 # Initialise user table data
901 $this->loadFromRow( $s );
902 $this->mGroups
= null; // deferred
903 $this->getEditCount(); // revalidation for nulls
908 $this->loadDefaults();
914 * Initialize this object from a row from the user table.
916 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
918 function loadFromRow( $row ) {
919 $this->mDataLoaded
= true;
921 if ( isset( $row->user_id
) ) {
922 $this->mId
= intval( $row->user_id
);
924 $this->mName
= $row->user_name
;
925 $this->mRealName
= $row->user_real_name
;
926 $this->mPassword
= $row->user_password
;
927 $this->mNewpassword
= $row->user_newpassword
;
928 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
929 $this->mEmail
= $row->user_email
;
930 $this->decodeOptions( $row->user_options
);
931 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
932 $this->mToken
= $row->user_token
;
933 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
934 $this->mEmailToken
= $row->user_email_token
;
935 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
936 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
937 $this->mEditCount
= $row->user_editcount
;
941 * Load the groups from the database if they aren't already loaded.
944 function loadGroups() {
945 if ( is_null( $this->mGroups
) ) {
946 $dbr = wfGetDB( DB_MASTER
);
947 $res = $dbr->select( 'user_groups',
949 array( 'ug_user' => $this->mId
),
951 $this->mGroups
= array();
952 while( $row = $dbr->fetchObject( $res ) ) {
953 $this->mGroups
[] = $row->ug_group
;
959 * Clear various cached data stored in this object.
960 * @param $reloadFrom \string Reload user and user_groups table data from a
961 * given source. May be "name", "id", "defaults", "session", or false for
964 function clearInstanceCache( $reloadFrom = false ) {
965 $this->mNewtalk
= -1;
966 $this->mDatePreference
= null;
967 $this->mBlockedby
= -1; # Unset
968 $this->mHash
= false;
970 $this->mRights
= null;
971 $this->mEffectiveGroups
= null;
974 $this->mDataLoaded
= false;
975 $this->mFrom
= $reloadFrom;
980 * Combine the language default options with any site-specific options
981 * and add the default language variants.
983 * @return \type{\arrayof{\string}} Array of options
985 static function getDefaultOptions() {
986 global $wgNamespacesToBeSearchedDefault;
988 * Site defaults will override the global/language defaults
990 global $wgDefaultUserOptions, $wgContLang;
991 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
994 * default language setting
996 $variant = $wgContLang->getPreferredVariant( false );
997 $defOpt['variant'] = $variant;
998 $defOpt['language'] = $variant;
1000 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1001 $defOpt['searchNs'.$nsnum] = $val;
1007 * Get a given default option value.
1009 * @param $opt \string Name of option to retrieve
1010 * @return \string Default option value
1012 public static function getDefaultOption( $opt ) {
1013 $defOpts = self
::getDefaultOptions();
1014 if( isset( $defOpts[$opt] ) ) {
1015 return $defOpts[$opt];
1022 * Get a list of user toggle names
1023 * @return \type{\arrayof{\string}} Array of user toggle names
1025 static function getToggles() {
1026 global $wgContLang, $wgUseRCPatrol;
1027 $extraToggles = array();
1028 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1029 if( $wgUseRCPatrol ) {
1030 $extraToggles[] = 'hidepatrolled';
1031 $extraToggles[] = 'newpageshidepatrolled';
1032 $extraToggles[] = 'watchlisthidepatrolled';
1034 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1039 * Get blocking information
1041 * @param $bFromSlave \bool Whether to check the slave database first. To
1042 * improve performance, non-critical checks are done
1043 * against slaves. Check when actually saving should be
1044 * done against master.
1046 function getBlockedStatus( $bFromSlave = true ) {
1047 global $wgEnableSorbs, $wgProxyWhitelist;
1049 if ( -1 != $this->mBlockedby
) {
1050 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1054 wfProfileIn( __METHOD__
);
1055 wfDebug( __METHOD__
.": checking...\n" );
1057 // Initialize data...
1058 // Otherwise something ends up stomping on $this->mBlockedby when
1059 // things get lazy-loaded later, causing false positive block hits
1060 // due to -1 !== 0. Probably session-related... Nothing should be
1061 // overwriting mBlockedby, surely?
1064 $this->mBlockedby
= 0;
1065 $this->mHideName
= 0;
1066 $this->mAllowUsertalk
= 0;
1069 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1070 # Exempt from all types of IP-block
1075 $this->mBlock
= new Block();
1076 $this->mBlock
->fromMaster( !$bFromSlave );
1077 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1078 wfDebug( __METHOD__
.": Found block.\n" );
1079 $this->mBlockedby
= $this->mBlock
->mBy
;
1080 $this->mBlockreason
= $this->mBlock
->mReason
;
1081 $this->mHideName
= $this->mBlock
->mHideName
;
1082 $this->mAllowUsertalk
= $this->mBlock
->mAllowUsertalk
;
1083 if ( $this->isLoggedIn() ) {
1084 $this->spreadBlock();
1087 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1088 // apply to users. Note that the existence of $this->mBlock is not used to
1089 // check for edit blocks, $this->mBlockedby is instead.
1093 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1095 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1096 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1097 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1101 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1102 if ( $this->inSorbsBlacklist( $ip ) ) {
1103 $this->mBlockedby
= wfMsg( 'sorbs' );
1104 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1110 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1112 wfProfileOut( __METHOD__
);
1116 * Whether the given IP is in the SORBS blacklist.
1118 * @param $ip \string IP to check
1119 * @return \bool True if blacklisted.
1121 function inSorbsBlacklist( $ip ) {
1122 global $wgEnableSorbs, $wgSorbsUrl;
1124 return $wgEnableSorbs &&
1125 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1129 * Whether the given IP is in a given DNS blacklist.
1131 * @param $ip \string IP to check
1132 * @param $base \string URL of the DNS blacklist
1133 * @return \bool True if blacklisted.
1135 function inDnsBlacklist( $ip, $base ) {
1136 wfProfileIn( __METHOD__
);
1140 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1141 if( IP
::isIPv4($ip) ) {
1143 $host = "$ip.$base";
1146 $ipList = gethostbynamel( $host );
1149 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1152 wfDebug( "Requested $host, not found in $base.\n" );
1156 wfProfileOut( __METHOD__
);
1161 * Is this user subject to rate limiting?
1163 * @return \bool True if rate limited
1165 public function isPingLimitable() {
1166 global $wgRateLimitsExcludedGroups;
1167 global $wgRateLimitsExcludedIPs;
1168 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1169 // Deprecated, but kept for backwards-compatibility config
1172 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1173 // No other good way currently to disable rate limits
1174 // for specific IPs. :P
1175 // But this is a crappy hack and should die.
1178 return !$this->isAllowed('noratelimit');
1182 * Primitive rate limits: enforce maximum actions per time period
1183 * to put a brake on flooding.
1185 * @note When using a shared cache like memcached, IP-address
1186 * last-hit counters will be shared across wikis.
1188 * @param $action \string Action to enforce; 'edit' if unspecified
1189 * @return \bool True if a rate limiter was tripped
1191 function pingLimiter( $action='edit' ) {
1193 # Call the 'PingLimiter' hook
1195 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1199 global $wgRateLimits;
1200 if( !isset( $wgRateLimits[$action] ) ) {
1204 # Some groups shouldn't trigger the ping limiter, ever
1205 if( !$this->isPingLimitable() )
1208 global $wgMemc, $wgRateLimitLog;
1209 wfProfileIn( __METHOD__
);
1211 $limits = $wgRateLimits[$action];
1213 $id = $this->getId();
1217 if( isset( $limits['anon'] ) && $id == 0 ) {
1218 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1221 if( isset( $limits['user'] ) && $id != 0 ) {
1222 $userLimit = $limits['user'];
1224 if( $this->isNewbie() ) {
1225 if( isset( $limits['newbie'] ) && $id != 0 ) {
1226 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1228 if( isset( $limits['ip'] ) ) {
1229 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1232 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1233 $subnet = $matches[1];
1234 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1237 // Check for group-specific permissions
1238 // If more than one group applies, use the group with the highest limit
1239 foreach ( $this->getGroups() as $group ) {
1240 if ( isset( $limits[$group] ) ) {
1241 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1242 $userLimit = $limits[$group];
1246 // Set the user limit key
1247 if ( $userLimit !== false ) {
1248 wfDebug( __METHOD__
.": effective user limit: $userLimit\n" );
1249 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1253 foreach( $keys as $key => $limit ) {
1254 list( $max, $period ) = $limit;
1255 $summary = "(limit $max in {$period}s)";
1256 $count = $wgMemc->get( $key );
1258 if( $count > $max ) {
1259 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1260 if( $wgRateLimitLog ) {
1261 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1265 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1268 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1269 $wgMemc->add( $key, 1, intval( $period ) );
1271 $wgMemc->incr( $key );
1274 wfProfileOut( __METHOD__
);
1279 * Check if user is blocked
1281 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1282 * @return \bool True if blocked, false otherwise
1284 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1285 wfDebug( "User::isBlocked: enter\n" );
1286 $this->getBlockedStatus( $bFromSlave );
1287 return $this->mBlockedby
!== 0;
1291 * Check if user is blocked from editing a particular article
1293 * @param $title \string Title to check
1294 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1295 * @return \bool True if blocked, false otherwise
1297 function isBlockedFrom( $title, $bFromSlave = false ) {
1298 global $wgBlockAllowsUTEdit;
1299 wfProfileIn( __METHOD__
);
1300 wfDebug( __METHOD__
.": enter\n" );
1302 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1303 $blocked = $this->isBlocked( $bFromSlave );
1304 $allowUsertalk = ($wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false);
1305 # If a user's name is suppressed, they cannot make edits anywhere
1306 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1307 $title->getNamespace() == NS_USER_TALK
) {
1309 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1311 wfProfileOut( __METHOD__
);
1316 * If user is blocked, return the name of the user who placed the block
1317 * @return \string name of blocker
1319 function blockedBy() {
1320 $this->getBlockedStatus();
1321 return $this->mBlockedby
;
1325 * If user is blocked, return the specified reason for the block
1326 * @return \string Blocking reason
1328 function blockedFor() {
1329 $this->getBlockedStatus();
1330 return $this->mBlockreason
;
1334 * If user is blocked, return the ID for the block
1335 * @return \int Block ID
1337 function getBlockId() {
1338 $this->getBlockedStatus();
1339 return ($this->mBlock ?
$this->mBlock
->mId
: false);
1343 * Check if user is blocked on all wikis.
1344 * Do not use for actual edit permission checks!
1345 * This is intented for quick UI checks.
1347 * @param $ip \type{\string} IP address, uses current client if none given
1348 * @return \type{\bool} True if blocked, false otherwise
1350 function isBlockedGlobally( $ip = '' ) {
1351 if( $this->mBlockedGlobally
!== null ) {
1352 return $this->mBlockedGlobally
;
1354 // User is already an IP?
1355 if( IP
::isIPAddress( $this->getName() ) ) {
1356 $ip = $this->getName();
1361 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1362 $this->mBlockedGlobally
= (bool)$blocked;
1363 return $this->mBlockedGlobally
;
1367 * Check if user account is locked
1369 * @return \type{\bool} True if locked, false otherwise
1371 function isLocked() {
1372 if( $this->mLocked
!== null ) {
1373 return $this->mLocked
;
1376 $authUser = $wgAuth->getUserInstance( $this );
1377 $this->mLocked
= (bool)$authUser->isLocked();
1378 return $this->mLocked
;
1382 * Check if user account is hidden
1384 * @return \type{\bool} True if hidden, false otherwise
1386 function isHidden() {
1387 if( $this->mHideName
!== null ) {
1388 return $this->mHideName
;
1390 $this->getBlockedStatus();
1391 if( !$this->mHideName
) {
1393 $authUser = $wgAuth->getUserInstance( $this );
1394 $this->mHideName
= (bool)$authUser->isHidden();
1396 return $this->mHideName
;
1400 * Get the user's ID.
1401 * @return \int The user's ID; 0 if the user is anonymous or nonexistent
1404 if( $this->mId
=== null and $this->mName
!== null
1405 and User
::isIP( $this->mName
) ) {
1406 // Special case, we know the user is anonymous
1408 } elseif( $this->mId
=== null ) {
1409 // Don't load if this was initialized from an ID
1416 * Set the user and reload all fields according to a given ID
1417 * @param $v \int User ID to reload
1419 function setId( $v ) {
1421 $this->clearInstanceCache( 'id' );
1425 * Get the user name, or the IP of an anonymous user
1426 * @return \string User's name or IP address
1428 function getName() {
1429 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1430 # Special case optimisation
1431 return $this->mName
;
1434 if ( $this->mName
=== false ) {
1436 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1438 return $this->mName
;
1443 * Set the user name.
1445 * This does not reload fields from the database according to the given
1446 * name. Rather, it is used to create a temporary "nonexistent user" for
1447 * later addition to the database. It can also be used to set the IP
1448 * address for an anonymous user to something other than the current
1451 * @note User::newFromName() has rougly the same function, when the named user
1453 * @param $str \string New user name to set
1455 function setName( $str ) {
1457 $this->mName
= $str;
1461 * Get the user's name escaped by underscores.
1462 * @return \string Username escaped by underscores.
1464 function getTitleKey() {
1465 return str_replace( ' ', '_', $this->getName() );
1469 * Check if the user has new messages.
1470 * @return \bool True if the user has new messages
1472 function getNewtalk() {
1475 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1476 if( $this->mNewtalk
=== -1 ) {
1477 $this->mNewtalk
= false; # reset talk page status
1479 # Check memcached separately for anons, who have no
1480 # entire User object stored in there.
1483 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1484 $newtalk = $wgMemc->get( $key );
1485 if( strval( $newtalk ) !== '' ) {
1486 $this->mNewtalk
= (bool)$newtalk;
1488 // Since we are caching this, make sure it is up to date by getting it
1490 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1491 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1494 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1498 return (bool)$this->mNewtalk
;
1502 * Return the talk page(s) this user has new messages on.
1503 * @return \type{\arrayof{\string}} Array of page URLs
1505 function getNewMessageLinks() {
1507 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1510 if (!$this->getNewtalk())
1512 $up = $this->getUserPage();
1513 $utp = $up->getTalkPage();
1514 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1519 * Internal uncached check for new messages
1522 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1523 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1524 * @param $fromMaster \bool true to fetch from the master, false for a slave
1525 * @return \bool True if the user has new messages
1528 function checkNewtalk( $field, $id, $fromMaster = false ) {
1529 if ( $fromMaster ) {
1530 $db = wfGetDB( DB_MASTER
);
1532 $db = wfGetDB( DB_SLAVE
);
1534 $ok = $db->selectField( 'user_newtalk', $field,
1535 array( $field => $id ), __METHOD__
);
1536 return $ok !== false;
1540 * Add or update the new messages flag
1541 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1542 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1543 * @return \bool True if successful, false otherwise
1546 function updateNewtalk( $field, $id ) {
1547 $dbw = wfGetDB( DB_MASTER
);
1548 $dbw->insert( 'user_newtalk',
1549 array( $field => $id ),
1552 if ( $dbw->affectedRows() ) {
1553 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1556 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1562 * Clear the new messages flag for the given user
1563 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1564 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1565 * @return \bool True if successful, false otherwise
1568 function deleteNewtalk( $field, $id ) {
1569 $dbw = wfGetDB( DB_MASTER
);
1570 $dbw->delete( 'user_newtalk',
1571 array( $field => $id ),
1573 if ( $dbw->affectedRows() ) {
1574 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1577 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1583 * Update the 'You have new messages!' status.
1584 * @param $val \bool Whether the user has new messages
1586 function setNewtalk( $val ) {
1587 if( wfReadOnly() ) {
1592 $this->mNewtalk
= $val;
1594 if( $this->isAnon() ) {
1596 $id = $this->getName();
1599 $id = $this->getId();
1604 $changed = $this->updateNewtalk( $field, $id );
1606 $changed = $this->deleteNewtalk( $field, $id );
1609 if( $this->isAnon() ) {
1610 // Anons have a separate memcached space, since
1611 // user records aren't kept for them.
1612 $key = wfMemcKey( 'newtalk', 'ip', $id );
1613 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1616 $this->invalidateCache();
1621 * Generate a current or new-future timestamp to be stored in the
1622 * user_touched field when we update things.
1623 * @return \string Timestamp in TS_MW format
1625 private static function newTouchedTimestamp() {
1626 global $wgClockSkewFudge;
1627 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1631 * Clear user data from memcached.
1632 * Use after applying fun updates to the database; caller's
1633 * responsibility to update user_touched if appropriate.
1635 * Called implicitly from invalidateCache() and saveSettings().
1637 private function clearSharedCache() {
1641 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1646 * Immediately touch the user data cache for this account.
1647 * Updates user_touched field, and removes account data from memcached
1648 * for reload on the next hit.
1650 function invalidateCache() {
1653 $this->mTouched
= self
::newTouchedTimestamp();
1655 $dbw = wfGetDB( DB_MASTER
);
1656 $dbw->update( 'user',
1657 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1658 array( 'user_id' => $this->mId
),
1661 $this->clearSharedCache();
1666 * Validate the cache for this account.
1667 * @param $timestamp \string A timestamp in TS_MW format
1669 function validateCache( $timestamp ) {
1671 return ($timestamp >= $this->mTouched
);
1675 * Get the user touched timestamp
1677 function getTouched() {
1679 return $this->mTouched
;
1683 * Set the password and reset the random token.
1684 * Calls through to authentication plugin if necessary;
1685 * will have no effect if the auth plugin refuses to
1686 * pass the change through or if the legal password
1689 * As a special case, setting the password to null
1690 * wipes it, so the account cannot be logged in until
1691 * a new password is set, for instance via e-mail.
1693 * @param $str \string New password to set
1694 * @throws PasswordError on failure
1696 function setPassword( $str ) {
1699 if( $str !== null ) {
1700 if( !$wgAuth->allowPasswordChange() ) {
1701 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1704 if( !$this->isValidPassword( $str ) ) {
1705 global $wgMinimalPasswordLength;
1706 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1707 $wgMinimalPasswordLength ) );
1711 if( !$wgAuth->setPassword( $this, $str ) ) {
1712 throw new PasswordError( wfMsg( 'externaldberror' ) );
1715 $this->setInternalPassword( $str );
1721 * Set the password and reset the random token unconditionally.
1723 * @param $str \string New password to set
1725 function setInternalPassword( $str ) {
1729 if( $str === null ) {
1730 // Save an invalid hash...
1731 $this->mPassword
= '';
1733 $this->mPassword
= self
::crypt( $str );
1735 $this->mNewpassword
= '';
1736 $this->mNewpassTime
= null;
1740 * Get the user's current token.
1741 * @return \string Token
1743 function getToken() {
1745 return $this->mToken
;
1749 * Set the random token (used for persistent authentication)
1750 * Called from loadDefaults() among other places.
1752 * @param $token \string If specified, set the token to this value
1755 function setToken( $token = false ) {
1756 global $wgSecretKey, $wgProxyKey;
1759 if ( $wgSecretKey ) {
1760 $key = $wgSecretKey;
1761 } elseif ( $wgProxyKey ) {
1766 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1768 $this->mToken
= $token;
1773 * Set the cookie password
1775 * @param $str \string New cookie password
1778 function setCookiePassword( $str ) {
1780 $this->mCookiePassword
= md5( $str );
1784 * Set the password for a password reminder or new account email
1786 * @param $str \string New password to set
1787 * @param $throttle \bool If true, reset the throttle timestamp to the present
1789 function setNewpassword( $str, $throttle = true ) {
1791 $this->mNewpassword
= self
::crypt( $str );
1793 $this->mNewpassTime
= wfTimestampNow();
1798 * Has password reminder email been sent within the last
1799 * $wgPasswordReminderResendTime hours?
1800 * @return \bool True or false
1802 function isPasswordReminderThrottled() {
1803 global $wgPasswordReminderResendTime;
1805 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1808 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1809 return time() < $expiry;
1813 * Get the user's e-mail address
1814 * @return \string User's email address
1816 function getEmail() {
1818 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1819 return $this->mEmail
;
1823 * Get the timestamp of the user's e-mail authentication
1824 * @return \string TS_MW timestamp
1826 function getEmailAuthenticationTimestamp() {
1828 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1829 return $this->mEmailAuthenticated
;
1833 * Set the user's e-mail address
1834 * @param $str \string New e-mail address
1836 function setEmail( $str ) {
1838 $this->mEmail
= $str;
1839 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1843 * Get the user's real name
1844 * @return \string User's real name
1846 function getRealName() {
1848 return $this->mRealName
;
1852 * Set the user's real name
1853 * @param $str \string New real name
1855 function setRealName( $str ) {
1857 $this->mRealName
= $str;
1861 * Get the user's current setting for a given option.
1863 * @param $oname \string The option to check
1864 * @param $defaultOverride \string A default value returned if the option does not exist
1865 * @return \string User's current value for the option
1866 * @see getBoolOption()
1867 * @see getIntOption()
1869 function getOption( $oname, $defaultOverride = '' ) {
1872 if ( is_null( $this->mOptions
) ) {
1873 if($defaultOverride != '') {
1874 return $defaultOverride;
1876 $this->mOptions
= User
::getDefaultOptions();
1879 if ( array_key_exists( $oname, $this->mOptions
) ) {
1880 return trim( $this->mOptions
[$oname] );
1882 return $defaultOverride;
1887 * Get the user's current setting for a given option, as a boolean value.
1889 * @param $oname \string The option to check
1890 * @return \bool User's current value for the option
1893 function getBoolOption( $oname ) {
1894 return (bool)$this->getOption( $oname );
1899 * Get the user's current setting for a given option, as a boolean value.
1901 * @param $oname \string The option to check
1902 * @param $defaultOverride \int A default value returned if the option does not exist
1903 * @return \int User's current value for the option
1906 function getIntOption( $oname, $defaultOverride=0 ) {
1907 $val = $this->getOption( $oname );
1909 $val = $defaultOverride;
1911 return intval( $val );
1915 * Set the given option for a user.
1917 * @param $oname \string The option to set
1918 * @param $val \mixed New value to set
1920 function setOption( $oname, $val ) {
1922 if ( is_null( $this->mOptions
) ) {
1923 $this->mOptions
= User
::getDefaultOptions();
1925 if ( $oname == 'skin' ) {
1926 # Clear cached skin, so the new one displays immediately in Special:Preferences
1927 unset( $this->mSkin
);
1929 // Filter out any newlines that may have passed through input validation.
1930 // Newlines are used to separate items in the options blob.
1932 $val = str_replace( "\r\n", "\n", $val );
1933 $val = str_replace( "\r", "\n", $val );
1934 $val = str_replace( "\n", " ", $val );
1936 // Explicitly NULL values should refer to defaults
1937 global $wgDefaultUserOptions;
1938 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1939 $val = $wgDefaultUserOptions[$oname];
1941 $this->mOptions
[$oname] = $val;
1945 * Reset all options to the site defaults
1947 function restoreOptions() {
1948 $this->mOptions
= User
::getDefaultOptions();
1952 * Get the user's preferred date format.
1953 * @return \string User's preferred date format
1955 function getDatePreference() {
1956 // Important migration for old data rows
1957 if ( is_null( $this->mDatePreference
) ) {
1959 $value = $this->getOption( 'date' );
1960 $map = $wgLang->getDatePreferenceMigrationMap();
1961 if ( isset( $map[$value] ) ) {
1962 $value = $map[$value];
1964 $this->mDatePreference
= $value;
1966 return $this->mDatePreference
;
1970 * Get the permissions this user has.
1971 * @return \type{\arrayof{\string}} Array of permission names
1973 function getRights() {
1974 if ( is_null( $this->mRights
) ) {
1975 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1976 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1977 // Force reindexation of rights when a hook has unset one of them
1978 $this->mRights
= array_values( $this->mRights
);
1980 return $this->mRights
;
1984 * Get the list of explicit group memberships this user has.
1985 * The implicit * and user groups are not included.
1986 * @return \type{\arrayof{\string}} Array of internal group names
1988 function getGroups() {
1990 return $this->mGroups
;
1994 * Get the list of implicit group memberships this user has.
1995 * This includes all explicit groups, plus 'user' if logged in,
1996 * '*' for all accounts and autopromoted groups
1997 * @param $recache \bool Whether to avoid the cache
1998 * @return \type{\arrayof{\string}} Array of internal group names
2000 function getEffectiveGroups( $recache = false ) {
2001 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2002 $this->mEffectiveGroups
= $this->getGroups();
2003 $this->mEffectiveGroups
[] = '*';
2004 if( $this->getId() ) {
2005 $this->mEffectiveGroups
[] = 'user';
2007 $this->mEffectiveGroups
= array_unique( array_merge(
2008 $this->mEffectiveGroups
,
2009 Autopromote
::getAutopromoteGroups( $this )
2012 # Hook for additional groups
2013 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2016 return $this->mEffectiveGroups
;
2020 * Get the user's edit count.
2021 * @return \int User'e edit count
2023 function getEditCount() {
2024 if ($this->getId()) {
2025 if ( !isset( $this->mEditCount
) ) {
2026 /* Populate the count, if it has not been populated yet */
2027 $this->mEditCount
= User
::edits($this->mId
);
2029 return $this->mEditCount
;
2037 * Add the user to the given group.
2038 * This takes immediate effect.
2039 * @param $group \string Name of the group to add
2041 function addGroup( $group ) {
2042 $dbw = wfGetDB( DB_MASTER
);
2043 if( $this->getId() ) {
2044 $dbw->insert( 'user_groups',
2046 'ug_user' => $this->getID(),
2047 'ug_group' => $group,
2050 array( 'IGNORE' ) );
2053 $this->loadGroups();
2054 $this->mGroups
[] = $group;
2055 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2057 $this->invalidateCache();
2061 * Remove the user from the given group.
2062 * This takes immediate effect.
2063 * @param $group \string Name of the group to remove
2065 function removeGroup( $group ) {
2067 $dbw = wfGetDB( DB_MASTER
);
2068 $dbw->delete( 'user_groups',
2070 'ug_user' => $this->getID(),
2071 'ug_group' => $group,
2073 'User::removeGroup' );
2075 $this->loadGroups();
2076 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2077 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2079 $this->invalidateCache();
2084 * Get whether the user is logged in
2085 * @return \bool True or false
2087 function isLoggedIn() {
2088 return $this->getID() != 0;
2092 * Get whether the user is anonymous
2093 * @return \bool True or false
2096 return !$this->isLoggedIn();
2100 * Get whether the user is a bot
2101 * @return \bool True or false
2105 wfDeprecated( __METHOD__
);
2106 return $this->isAllowed( 'bot' );
2110 * Check if user is allowed to access a feature / make an action
2111 * @param $action \string action to be checked
2112 * @return \bool True if action is allowed, else false
2114 function isAllowed( $action = '' ) {
2115 if ( $action === '' )
2116 return true; // In the spirit of DWIM
2117 # Patrolling may not be enabled
2118 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2119 global $wgUseRCPatrol, $wgUseNPPatrol;
2120 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2123 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2124 # by misconfiguration: 0 == 'foo'
2125 return in_array( $action, $this->getRights(), true );
2129 * Check whether to enable recent changes patrol features for this user
2130 * @return \bool True or false
2132 public function useRCPatrol() {
2133 global $wgUseRCPatrol;
2134 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2138 * Check whether to enable new pages patrol features for this user
2139 * @return \bool True or false
2141 public function useNPPatrol() {
2142 global $wgUseRCPatrol, $wgUseNPPatrol;
2143 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
2147 * Get the current skin, loading it if required, and setting a title
2148 * @param Title $t The title to use in the skin
2149 * @return Skin The current skin
2150 * @todo FIXME : need to check the old failback system [AV]
2152 function &getSkin( $t = null ) {
2153 global $wgRequest, $wgAllowUserSkin, $wgDefaultSkin;
2154 if ( ! isset( $this->mSkin
) ) {
2155 wfProfileIn( __METHOD__
);
2157 if( $wgAllowUserSkin ) {
2159 $userSkin = $this->getOption( 'skin' );
2160 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2162 # if we're not allowing users to override, then use the default
2163 $userSkin = $wgDefaultSkin;
2166 $this->mSkin
=& Skin
::newFromKey( $userSkin );
2167 wfProfileOut( __METHOD__
);
2171 $t = $wgOut->getTitle();
2173 $this->mSkin
->setTitle( $t );
2174 return $this->mSkin
;
2178 * Check the watched status of an article.
2179 * @param $title \type{Title} Title of the article to look at
2180 * @return \bool True if article is watched
2182 function isWatched( $title ) {
2183 $wl = WatchedItem
::fromUserTitle( $this, $title );
2184 return $wl->isWatched();
2189 * @param $title \type{Title} Title of the article to look at
2191 function addWatch( $title ) {
2192 $wl = WatchedItem
::fromUserTitle( $this, $title );
2194 $this->invalidateCache();
2198 * Stop watching an article.
2199 * @param $title \type{Title} Title of the article to look at
2201 function removeWatch( $title ) {
2202 $wl = WatchedItem
::fromUserTitle( $this, $title );
2204 $this->invalidateCache();
2208 * Clear the user's notification timestamp for the given title.
2209 * If e-notif e-mails are on, they will receive notification mails on
2210 * the next change of the page if it's watched etc.
2211 * @param $title \type{Title} Title of the article to look at
2213 function clearNotification( &$title ) {
2214 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2216 # Do nothing if the database is locked to writes
2217 if( wfReadOnly() ) {
2221 if ($title->getNamespace() == NS_USER_TALK
&&
2222 $title->getText() == $this->getName() ) {
2223 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2225 $this->setNewtalk( false );
2228 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2232 if( $this->isAnon() ) {
2233 // Nothing else to do...
2237 // Only update the timestamp if the page is being watched.
2238 // The query to find out if it is watched is cached both in memcached and per-invocation,
2239 // and when it does have to be executed, it can be on a slave
2240 // If this is the user's newtalk page, we always update the timestamp
2241 if ($title->getNamespace() == NS_USER_TALK
&&
2242 $title->getText() == $wgUser->getName())
2245 } elseif ( $this->getId() == $wgUser->getId() ) {
2246 $watched = $title->userIsWatching();
2251 // If the page is watched by the user (or may be watched), update the timestamp on any
2252 // any matching rows
2254 $dbw = wfGetDB( DB_MASTER
);
2255 $dbw->update( 'watchlist',
2257 'wl_notificationtimestamp' => NULL
2258 ), array( /* WHERE */
2259 'wl_title' => $title->getDBkey(),
2260 'wl_namespace' => $title->getNamespace(),
2261 'wl_user' => $this->getID()
2268 * Resets all of the given user's page-change notification timestamps.
2269 * If e-notif e-mails are on, they will receive notification mails on
2270 * the next change of any watched page.
2272 * @param $currentUser \int User ID
2274 function clearAllNotifications( $currentUser ) {
2275 global $wgUseEnotif, $wgShowUpdatedMarker;
2276 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2277 $this->setNewtalk( false );
2280 if( $currentUser != 0 ) {
2281 $dbw = wfGetDB( DB_MASTER
);
2282 $dbw->update( 'watchlist',
2284 'wl_notificationtimestamp' => NULL
2285 ), array( /* WHERE */
2286 'wl_user' => $currentUser
2289 # We also need to clear here the "you have new message" notification for the own user_talk page
2290 # This is cleared one page view later in Article::viewUpdates();
2295 * Encode this user's options as a string
2296 * @return \string Encoded options
2299 function encodeOptions() {
2301 if ( is_null( $this->mOptions
) ) {
2302 $this->mOptions
= User
::getDefaultOptions();
2305 foreach ( $this->mOptions
as $oname => $oval ) {
2306 array_push( $a, $oname.'='.$oval );
2308 $s = implode( "\n", $a );
2313 * Set this user's options from an encoded string
2314 * @param $str \string Encoded options to import
2317 function decodeOptions( $str ) {
2318 $this->mOptions
= array();
2319 $a = explode( "\n", $str );
2320 foreach ( $a as $s ) {
2322 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2323 $this->mOptions
[$m[1]] = $m[2];
2329 * Set a cookie on the user's client. Wrapper for
2330 * WebResponse::setCookie
2331 * @param $name \string Name of the cookie to set
2332 * @param $value \string Value to set
2333 * @param $exp \int Expiration time, as a UNIX time value;
2334 * if 0 or not specified, use the default $wgCookieExpiration
2336 protected function setCookie( $name, $value, $exp=0 ) {
2338 $wgRequest->response()->setcookie( $name, $value, $exp );
2342 * Clear a cookie on the user's client
2343 * @param $name \string Name of the cookie to clear
2345 protected function clearCookie( $name ) {
2346 $this->setCookie( $name, '', time() - 86400 );
2350 * Set the default cookies for this session on the user's client.
2352 function setCookies() {
2354 if ( 0 == $this->mId
) return;
2356 'wsUserID' => $this->mId
,
2357 'wsToken' => $this->mToken
,
2358 'wsUserName' => $this->getName()
2361 'UserID' => $this->mId
,
2362 'UserName' => $this->getName(),
2364 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2365 $cookies['Token'] = $this->mToken
;
2367 $cookies['Token'] = false;
2370 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2371 #check for null, since the hook could cause a null value
2372 if ( !is_null( $session ) && isset( $_SESSION ) ){
2373 $_SESSION = $session +
$_SESSION;
2375 foreach ( $cookies as $name => $value ) {
2376 if ( $value === false ) {
2377 $this->clearCookie( $name );
2379 $this->setCookie( $name, $value );
2385 * Log this user out.
2389 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2395 * Clear the user's cookies and session, and reset the instance cache.
2399 function doLogout() {
2400 $this->clearInstanceCache( 'defaults' );
2402 $_SESSION['wsUserID'] = 0;
2404 $this->clearCookie( 'UserID' );
2405 $this->clearCookie( 'Token' );
2407 # Remember when user logged out, to prevent seeing cached pages
2408 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2412 * Save this user's settings into the database.
2413 * @todo Only rarely do all these fields need to be set!
2415 function saveSettings() {
2417 if ( wfReadOnly() ) { return; }
2418 if ( 0 == $this->mId
) { return; }
2420 $this->mTouched
= self
::newTouchedTimestamp();
2422 $dbw = wfGetDB( DB_MASTER
);
2423 $dbw->update( 'user',
2425 'user_name' => $this->mName
,
2426 'user_password' => $this->mPassword
,
2427 'user_newpassword' => $this->mNewpassword
,
2428 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2429 'user_real_name' => $this->mRealName
,
2430 'user_email' => $this->mEmail
,
2431 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2432 'user_options' => $this->encodeOptions(),
2433 'user_touched' => $dbw->timestamp($this->mTouched
),
2434 'user_token' => $this->mToken
,
2435 'user_email_token' => $this->mEmailToken
,
2436 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2437 ), array( /* WHERE */
2438 'user_id' => $this->mId
2441 wfRunHooks( 'UserSaveSettings', array( $this ) );
2442 $this->clearSharedCache();
2443 $this->getUserPage()->invalidateCache();
2447 * If only this user's username is known, and it exists, return the user ID.
2449 function idForName() {
2450 $s = trim( $this->getName() );
2451 if ( $s === '' ) return 0;
2453 $dbr = wfGetDB( DB_SLAVE
);
2454 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2455 if ( $id === false ) {
2462 * Add a user to the database, return the user object
2464 * @param $name \string Username to add
2465 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2466 * - password The user's password. Password logins will be disabled if this is omitted.
2467 * - newpassword A temporary password mailed to the user
2468 * - email The user's email address
2469 * - email_authenticated The email authentication timestamp
2470 * - real_name The user's real name
2471 * - options An associative array of non-default options
2472 * - token Random authentication token. Do not set.
2473 * - registration Registration timestamp. Do not set.
2475 * @return \type{User} A new User object, or null if the username already exists
2477 static function createNew( $name, $params = array() ) {
2480 if ( isset( $params['options'] ) ) {
2481 $user->mOptions
= $params['options'] +
$user->mOptions
;
2482 unset( $params['options'] );
2484 $dbw = wfGetDB( DB_MASTER
);
2485 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2487 'user_id' => $seqVal,
2488 'user_name' => $name,
2489 'user_password' => $user->mPassword
,
2490 'user_newpassword' => $user->mNewpassword
,
2491 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2492 'user_email' => $user->mEmail
,
2493 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2494 'user_real_name' => $user->mRealName
,
2495 'user_options' => $user->encodeOptions(),
2496 'user_token' => $user->mToken
,
2497 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2498 'user_editcount' => 0,
2500 foreach ( $params as $name => $value ) {
2501 $fields["user_$name"] = $value;
2503 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2504 if ( $dbw->affectedRows() ) {
2505 $newUser = User
::newFromId( $dbw->insertId() );
2513 * Add this existing user object to the database
2515 function addToDatabase() {
2517 $dbw = wfGetDB( DB_MASTER
);
2518 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2519 $dbw->insert( 'user',
2521 'user_id' => $seqVal,
2522 'user_name' => $this->mName
,
2523 'user_password' => $this->mPassword
,
2524 'user_newpassword' => $this->mNewpassword
,
2525 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2526 'user_email' => $this->mEmail
,
2527 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2528 'user_real_name' => $this->mRealName
,
2529 'user_options' => $this->encodeOptions(),
2530 'user_token' => $this->mToken
,
2531 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2532 'user_editcount' => 0,
2535 $this->mId
= $dbw->insertId();
2537 // Clear instance cache other than user table data, which is already accurate
2538 $this->clearInstanceCache();
2542 * If this (non-anonymous) user is blocked, block any IP address
2543 * they've successfully logged in from.
2545 function spreadBlock() {
2546 wfDebug( __METHOD__
."()\n" );
2548 if ( $this->mId
== 0 ) {
2552 $userblock = Block
::newFromDB( '', $this->mId
);
2553 if ( !$userblock ) {
2557 $userblock->doAutoblock( wfGetIp() );
2562 * Generate a string which will be different for any combination of
2563 * user options which would produce different parser output.
2564 * This will be used as part of the hash key for the parser cache,
2565 * so users will the same options can share the same cached data
2568 * Extensions which require it should install 'PageRenderingHash' hook,
2569 * which will give them a chance to modify this key based on their own
2572 * @return \string Page rendering hash
2574 function getPageRenderingHash() {
2575 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2577 return $this->mHash
;
2580 // stubthreshold is only included below for completeness,
2581 // it will always be 0 when this function is called by parsercache.
2583 $confstr = $this->getOption( 'math' );
2584 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2585 if ( $wgUseDynamicDates ) {
2586 $confstr .= '!' . $this->getDatePreference();
2588 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2589 $confstr .= '!' . $wgLang->getCode();
2590 $confstr .= '!' . $this->getOption( 'thumbsize' );
2591 // add in language specific options, if any
2592 $extra = $wgContLang->getExtraHashOptions();
2595 $confstr .= $wgRenderHashAppend;
2597 // Give a chance for extensions to modify the hash, if they have
2598 // extra options or other effects on the parser cache.
2599 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2601 // Make it a valid memcached key fragment
2602 $confstr = str_replace( ' ', '_', $confstr );
2603 $this->mHash
= $confstr;
2608 * Get whether the user is explicitly blocked from account creation.
2609 * @return \bool True if blocked
2611 function isBlockedFromCreateAccount() {
2612 $this->getBlockedStatus();
2613 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2617 * Get whether the user is blocked from using Special:Emailuser.
2618 * @return \bool True if blocked
2620 function isBlockedFromEmailuser() {
2621 $this->getBlockedStatus();
2622 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2626 * Get whether the user is allowed to create an account.
2627 * @return \bool True if allowed
2629 function isAllowedToCreateAccount() {
2630 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2636 function setLoaded( $loaded ) {
2637 wfDeprecated( __METHOD__
);
2641 * Get this user's personal page title.
2643 * @return \type{Title} User's personal page title
2645 function getUserPage() {
2646 return Title
::makeTitle( NS_USER
, $this->getName() );
2650 * Get this user's talk page title.
2652 * @return \type{Title} User's talk page title
2654 function getTalkPage() {
2655 $title = $this->getUserPage();
2656 return $title->getTalkPage();
2660 * Get the maximum valid user ID.
2661 * @return \int User ID
2664 function getMaxID() {
2665 static $res; // cache
2667 if ( isset( $res ) )
2670 $dbr = wfGetDB( DB_SLAVE
);
2671 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2676 * Determine whether the user is a newbie. Newbies are either
2677 * anonymous IPs, or the most recently created accounts.
2678 * @return \bool True if the user is a newbie
2680 function isNewbie() {
2681 return !$this->isAllowed( 'autoconfirmed' );
2685 * Is the user active? We check to see if they've made at least
2686 * X number of edits in the last Y days.
2688 * @return \bool True if the user is active, false if not.
2690 public function isActiveEditor() {
2691 global $wgActiveUserEditCount, $wgActiveUserDays;
2692 $dbr = wfGetDB( DB_SLAVE
);
2694 // Stolen without shame from RC
2695 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2696 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
2697 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2699 $res = $dbr->select( 'revision', '1',
2700 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2702 array('LIMIT' => $wgActiveUserEditCount ) );
2704 $count = $dbr->numRows($res);
2705 $dbr->freeResult($res);
2707 return $count == $wgActiveUserEditCount;
2711 * Check to see if the given clear-text password is one of the accepted passwords
2712 * @param $password \string user password.
2713 * @return \bool True if the given password is correct, otherwise False.
2715 function checkPassword( $password ) {
2719 // Even though we stop people from creating passwords that
2720 // are shorter than this, doesn't mean people wont be able
2721 // to. Certain authentication plugins do NOT want to save
2722 // domain passwords in a mysql database, so we should
2723 // check this (incase $wgAuth->strict() is false).
2724 if( !$this->isValidPassword( $password ) ) {
2728 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2730 } elseif( $wgAuth->strict() ) {
2731 /* Auth plugin doesn't allow local authentication */
2733 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2734 /* Auth plugin doesn't allow local authentication for this user name */
2737 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2739 } elseif ( function_exists( 'iconv' ) ) {
2740 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2741 # Check for this with iconv
2742 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2743 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2751 * Check if the given clear-text password matches the temporary password
2752 * sent by e-mail for password reset operations.
2753 * @return \bool True if matches, false otherwise
2755 function checkTemporaryPassword( $plaintext ) {
2756 global $wgNewPasswordExpiry;
2757 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
2759 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
2760 return ( time() < $expiry );
2767 * Initialize (if necessary) and return a session token value
2768 * which can be used in edit forms to show that the user's
2769 * login credentials aren't being hijacked with a foreign form
2772 * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2773 * @return \string The new edit token
2775 function editToken( $salt = '' ) {
2776 if ( $this->isAnon() ) {
2777 return EDIT_TOKEN_SUFFIX
;
2779 if( !isset( $_SESSION['wsEditToken'] ) ) {
2780 $token = $this->generateToken();
2781 $_SESSION['wsEditToken'] = $token;
2783 $token = $_SESSION['wsEditToken'];
2785 if( is_array( $salt ) ) {
2786 $salt = implode( '|', $salt );
2788 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2793 * Generate a looking random token for various uses.
2795 * @param $salt \string Optional salt value
2796 * @return \string The new random token
2798 function generateToken( $salt = '' ) {
2799 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2800 return md5( $token . $salt );
2804 * Check given value against the token value stored in the session.
2805 * A match should confirm that the form was submitted from the
2806 * user's own login session, not a form submission from a third-party
2809 * @param $val \string Input value to compare
2810 * @param $salt \string Optional function-specific data for hashing
2811 * @return \bool Whether the token matches
2813 function matchEditToken( $val, $salt = '' ) {
2814 $sessionToken = $this->editToken( $salt );
2815 if ( $val != $sessionToken ) {
2816 wfDebug( "User::matchEditToken: broken session data\n" );
2818 return $val == $sessionToken;
2822 * Check given value against the token value stored in the session,
2823 * ignoring the suffix.
2825 * @param $val \string Input value to compare
2826 * @param $salt \string Optional function-specific data for hashing
2827 * @return \bool Whether the token matches
2829 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2830 $sessionToken = $this->editToken( $salt );
2831 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2835 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2836 * mail to the user's given address.
2838 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure.
2840 function sendConfirmationMail() {
2842 $expiration = null; // gets passed-by-ref and defined in next line.
2843 $token = $this->confirmationToken( $expiration );
2844 $url = $this->confirmationTokenUrl( $token );
2845 $invalidateURL = $this->invalidationTokenUrl( $token );
2846 $this->saveSettings();
2848 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2849 wfMsg( 'confirmemail_body',
2853 $wgLang->timeanddate( $expiration, false ),
2858 * Send an e-mail to this user's account. Does not check for
2859 * confirmed status or validity.
2861 * @param $subject \string Message subject
2862 * @param $body \string Message body
2863 * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2864 * @param $replyto \string Reply-To address
2865 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure
2867 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2868 if( is_null( $from ) ) {
2869 global $wgPasswordSender;
2870 $from = $wgPasswordSender;
2873 $to = new MailAddress( $this );
2874 $sender = new MailAddress( $from );
2875 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2879 * Generate, store, and return a new e-mail confirmation code.
2880 * A hash (unsalted, since it's used as a key) is stored.
2882 * @note Call saveSettings() after calling this function to commit
2883 * this change to the database.
2885 * @param[out] &$expiration \mixed Accepts the expiration time
2886 * @return \string New token
2889 function confirmationToken( &$expiration ) {
2891 $expires = $now +
7 * 24 * 60 * 60;
2892 $expiration = wfTimestamp( TS_MW
, $expires );
2893 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2894 $hash = md5( $token );
2896 $this->mEmailToken
= $hash;
2897 $this->mEmailTokenExpires
= $expiration;
2902 * Return a URL the user can use to confirm their email address.
2903 * @param $token \string Accepts the email confirmation token
2904 * @return \string New token URL
2907 function confirmationTokenUrl( $token ) {
2908 return $this->getTokenUrl( 'ConfirmEmail', $token );
2911 * Return a URL the user can use to invalidate their email address.
2912 * @param $token \string Accepts the email confirmation token
2913 * @return \string New token URL
2916 function invalidationTokenUrl( $token ) {
2917 return $this->getTokenUrl( 'Invalidateemail', $token );
2921 * Internal function to format the e-mail validation/invalidation URLs.
2922 * This uses $wgArticlePath directly as a quickie hack to use the
2923 * hardcoded English names of the Special: pages, for ASCII safety.
2925 * @note Since these URLs get dropped directly into emails, using the
2926 * short English names avoids insanely long URL-encoded links, which
2927 * also sometimes can get corrupted in some browsers/mailers
2928 * (bug 6957 with Gmail and Internet Explorer).
2930 * @param $page \string Special page
2931 * @param $token \string Token
2932 * @return \string Formatted URL
2934 protected function getTokenUrl( $page, $token ) {
2935 global $wgArticlePath;
2939 "Special:$page/$token",
2944 * Mark the e-mail address confirmed.
2946 * @note Call saveSettings() after calling this function to commit the change.
2948 function confirmEmail() {
2949 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2954 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2955 * address if it was already confirmed.
2957 * @note Call saveSettings() after calling this function to commit the change.
2959 function invalidateEmail() {
2961 $this->mEmailToken
= null;
2962 $this->mEmailTokenExpires
= null;
2963 $this->setEmailAuthenticationTimestamp( null );
2968 * Set the e-mail authentication timestamp.
2969 * @param $timestamp \string TS_MW timestamp
2971 function setEmailAuthenticationTimestamp( $timestamp ) {
2973 $this->mEmailAuthenticated
= $timestamp;
2974 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2978 * Is this user allowed to send e-mails within limits of current
2979 * site configuration?
2980 * @return \bool True if allowed
2982 function canSendEmail() {
2983 global $wgEnableEmail, $wgEnableUserEmail;
2984 if( !$wgEnableEmail ||
!$wgEnableUserEmail ) {
2987 $canSend = $this->isEmailConfirmed();
2988 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2993 * Is this user allowed to receive e-mails within limits of current
2994 * site configuration?
2995 * @return \bool True if allowed
2997 function canReceiveEmail() {
2998 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3002 * Is this user's e-mail address valid-looking and confirmed within
3003 * limits of the current site configuration?
3005 * @note If $wgEmailAuthentication is on, this may require the user to have
3006 * confirmed their address by returning a code or using a password
3007 * sent to the address from the wiki.
3009 * @return \bool True if confirmed
3011 function isEmailConfirmed() {
3012 global $wgEmailAuthentication;
3015 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3016 if( $this->isAnon() )
3018 if( !self
::isValidEmailAddr( $this->mEmail
) )
3020 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3029 * Check whether there is an outstanding request for e-mail confirmation.
3030 * @return \bool True if pending
3032 function isEmailConfirmationPending() {
3033 global $wgEmailAuthentication;
3034 return $wgEmailAuthentication &&
3035 !$this->isEmailConfirmed() &&
3036 $this->mEmailToken
&&
3037 $this->mEmailTokenExpires
> wfTimestamp();
3041 * Get the timestamp of account creation.
3043 * @return \types{\string,\bool} string Timestamp of account creation, or false for
3044 * non-existent/anonymous user accounts.
3046 public function getRegistration() {
3047 return $this->getId() > 0
3048 ?
$this->mRegistration
3053 * Get the timestamp of the first edit
3055 * @return \types{\string,\bool} string Timestamp of first edit, or false for
3056 * non-existent/anonymous user accounts.
3058 public function getFirstEditTimestamp() {
3059 if( $this->getId() == 0 ) return false; // anons
3060 $dbr = wfGetDB( DB_SLAVE
);
3061 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3062 array( 'rev_user' => $this->getId() ),
3064 array( 'ORDER BY' => 'rev_timestamp ASC' )
3066 if( !$time ) return false; // no edits
3067 return wfTimestamp( TS_MW
, $time );
3071 * Get the permissions associated with a given list of groups
3073 * @param $groups \type{\arrayof{\string}} List of internal group names
3074 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3076 static function getGroupPermissions( $groups ) {
3077 global $wgGroupPermissions;
3079 foreach( $groups as $group ) {
3080 if( isset( $wgGroupPermissions[$group] ) ) {
3081 $rights = array_merge( $rights,
3082 // array_filter removes empty items
3083 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3086 return array_unique($rights);
3090 * Get all the groups who have a given permission
3092 * @param $role \string Role to check
3093 * @return \type{\arrayof{\string}} List of internal group names with the given permission
3095 static function getGroupsWithPermission( $role ) {
3096 global $wgGroupPermissions;
3097 $allowedGroups = array();
3098 foreach ( $wgGroupPermissions as $group => $rights ) {
3099 if ( isset( $rights[$role] ) && $rights[$role] ) {
3100 $allowedGroups[] = $group;
3103 return $allowedGroups;
3107 * Get the localized descriptive name for a group, if it exists
3109 * @param $group \string Internal group name
3110 * @return \string Localized descriptive group name
3112 static function getGroupName( $group ) {
3113 global $wgMessageCache;
3114 $wgMessageCache->loadAllMessages();
3115 $key = "group-$group";
3116 $name = wfMsg( $key );
3117 return $name == '' ||
wfEmptyMsg( $key, $name )
3123 * Get the localized descriptive name for a member of a group, if it exists
3125 * @param $group \string Internal group name
3126 * @return \string Localized name for group member
3128 static function getGroupMember( $group ) {
3129 global $wgMessageCache;
3130 $wgMessageCache->loadAllMessages();
3131 $key = "group-$group-member";
3132 $name = wfMsg( $key );
3133 return $name == '' ||
wfEmptyMsg( $key, $name )
3139 * Return the set of defined explicit groups.
3140 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3141 * are not included, as they are defined automatically, not in the database.
3142 * @return \type{\arrayof{\string}} Array of internal group names
3144 static function getAllGroups() {
3145 global $wgGroupPermissions;
3147 array_keys( $wgGroupPermissions ),
3148 self
::getImplicitGroups()
3153 * Get a list of all available permissions.
3154 * @return \type{\arrayof{\string}} Array of permission names
3156 static function getAllRights() {
3157 if ( self
::$mAllRights === false ) {
3158 global $wgAvailableRights;
3159 if ( count( $wgAvailableRights ) ) {
3160 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3162 self
::$mAllRights = self
::$mCoreRights;
3164 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3166 return self
::$mAllRights;
3170 * Get a list of implicit groups
3171 * @return \type{\arrayof{\string}} Array of internal group names
3173 public static function getImplicitGroups() {
3174 global $wgImplicitGroups;
3175 $groups = $wgImplicitGroups;
3176 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3181 * Get the title of a page describing a particular group
3183 * @param $group \string Internal group name
3184 * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3186 static function getGroupPage( $group ) {
3187 global $wgMessageCache;
3188 $wgMessageCache->loadAllMessages();
3189 $page = wfMsgForContent( 'grouppage-' . $group );
3190 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3191 $title = Title
::newFromText( $page );
3192 if( is_object( $title ) )
3199 * Create a link to the group in HTML, if available;
3200 * else return the group name.
3202 * @param $group \string Internal name of the group
3203 * @param $text \string The text of the link
3204 * @return \string HTML link to the group
3206 static function makeGroupLinkHTML( $group, $text = '' ) {
3208 $text = self
::getGroupName( $group );
3210 $title = self
::getGroupPage( $group );
3213 $sk = $wgUser->getSkin();
3214 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3221 * Create a link to the group in Wikitext, if available;
3222 * else return the group name.
3224 * @param $group \string Internal name of the group
3225 * @param $text \string The text of the link
3226 * @return \string Wikilink to the group
3228 static function makeGroupLinkWiki( $group, $text = '' ) {
3230 $text = self
::getGroupName( $group );
3232 $title = self
::getGroupPage( $group );
3234 $page = $title->getPrefixedText();
3235 return "[[$page|$text]]";
3242 * Returns an array of the groups that a particular group can add/remove.
3244 * @param $group String: the group to check for whether it can add/remove
3245 * @return Array array( 'add' => array( addablegroups ),
3246 * 'remove' => array( removablegroups ),
3247 * 'add-self' => array( addablegroups to self),
3248 * 'remove-self' => array( removable groups from self) )
3250 static function changeableByGroup( $group ) {
3251 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3253 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3254 if( empty($wgAddGroups[$group]) ) {
3255 // Don't add anything to $groups
3256 } elseif( $wgAddGroups[$group] === true ) {
3257 // You get everything
3258 $groups['add'] = self
::getAllGroups();
3259 } elseif( is_array($wgAddGroups[$group]) ) {
3260 $groups['add'] = $wgAddGroups[$group];
3263 // Same thing for remove
3264 if( empty($wgRemoveGroups[$group]) ) {
3265 } elseif($wgRemoveGroups[$group] === true ) {
3266 $groups['remove'] = self
::getAllGroups();
3267 } elseif( is_array($wgRemoveGroups[$group]) ) {
3268 $groups['remove'] = $wgRemoveGroups[$group];
3271 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3272 if( empty($wgGroupsAddToSelf['user']) ||
$wgGroupsAddToSelf['user'] !== true ) {
3273 foreach($wgGroupsAddToSelf as $key => $value) {
3274 if( is_int($key) ) {
3275 $wgGroupsAddToSelf['user'][] = $value;
3280 if( empty($wgGroupsRemoveFromSelf['user']) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
3281 foreach($wgGroupsRemoveFromSelf as $key => $value) {
3282 if( is_int($key) ) {
3283 $wgGroupsRemoveFromSelf['user'][] = $value;
3288 // Now figure out what groups the user can add to him/herself
3289 if( empty($wgGroupsAddToSelf[$group]) ) {
3290 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3291 // No idea WHY this would be used, but it's there
3292 $groups['add-self'] = User
::getAllGroups();
3293 } elseif( is_array($wgGroupsAddToSelf[$group]) ) {
3294 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3297 if( empty($wgGroupsRemoveFromSelf[$group]) ) {
3298 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3299 $groups['remove-self'] = User
::getAllGroups();
3300 } elseif( is_array($wgGroupsRemoveFromSelf[$group]) ) {
3301 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3308 * Returns an array of groups that this user can add and remove
3309 * @return Array array( 'add' => array( addablegroups ),
3310 * 'remove' => array( removablegroups ),
3311 * 'add-self' => array( addablegroups to self),
3312 * 'remove-self' => array( removable groups from self) )
3314 function changeableGroups() {
3315 if( $this->isAllowed( 'userrights' ) ) {
3316 // This group gives the right to modify everything (reverse-
3317 // compatibility with old "userrights lets you change
3319 // Using array_merge to make the groups reindexed
3320 $all = array_merge( User
::getAllGroups() );
3324 'add-self' => array(),
3325 'remove-self' => array()
3329 // Okay, it's not so simple, we will have to go through the arrays
3332 'remove' => array(),
3333 'add-self' => array(),
3334 'remove-self' => array() );
3335 $addergroups = $this->getEffectiveGroups();
3337 foreach ($addergroups as $addergroup) {
3338 $groups = array_merge_recursive(
3339 $groups, $this->changeableByGroup($addergroup)
3341 $groups['add'] = array_unique( $groups['add'] );
3342 $groups['remove'] = array_unique( $groups['remove'] );
3343 $groups['add-self'] = array_unique( $groups['add-self'] );
3344 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3350 * Increment the user's edit-count field.
3351 * Will have no effect for anonymous users.
3353 function incEditCount() {
3354 if( !$this->isAnon() ) {
3355 $dbw = wfGetDB( DB_MASTER
);
3356 $dbw->update( 'user',
3357 array( 'user_editcount=user_editcount+1' ),
3358 array( 'user_id' => $this->getId() ),
3361 // Lazy initialization check...
3362 if( $dbw->affectedRows() == 0 ) {
3363 // Pull from a slave to be less cruel to servers
3364 // Accuracy isn't the point anyway here
3365 $dbr = wfGetDB( DB_SLAVE
);
3366 $count = $dbr->selectField( 'revision',
3368 array( 'rev_user' => $this->getId() ),
3371 // Now here's a goddamn hack...
3372 if( $dbr !== $dbw ) {
3373 // If we actually have a slave server, the count is
3374 // at least one behind because the current transaction
3375 // has not been committed and replicated.
3378 // But if DB_SLAVE is selecting the master, then the
3379 // count we just read includes the revision that was
3380 // just added in the working transaction.
3383 $dbw->update( 'user',
3384 array( 'user_editcount' => $count ),
3385 array( 'user_id' => $this->getId() ),
3389 // edit count in user cache too
3390 $this->invalidateCache();
3394 * Get the description of a given right
3396 * @param $right \string Right to query
3397 * @return \string Localized description of the right
3399 static function getRightDescription( $right ) {
3400 global $wgMessageCache;
3401 $wgMessageCache->loadAllMessages();
3402 $key = "right-$right";
3403 $name = wfMsg( $key );
3404 return $name == '' ||
wfEmptyMsg( $key, $name )
3410 * Make an old-style password hash
3412 * @param $password \string Plain-text password
3413 * @param $userId \string User ID
3414 * @return \string Password hash
3416 static function oldCrypt( $password, $userId ) {
3417 global $wgPasswordSalt;
3418 if ( $wgPasswordSalt ) {
3419 return md5( $userId . '-' . md5( $password ) );
3421 return md5( $password );
3426 * Make a new-style password hash
3428 * @param $password \string Plain-text password
3429 * @param $salt \string Optional salt, may be random or the user ID.
3430 * If unspecified or false, will generate one automatically
3431 * @return \string Password hash
3433 static function crypt( $password, $salt = false ) {
3434 global $wgPasswordSalt;
3437 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3441 if( $wgPasswordSalt ) {
3442 if ( $salt === false ) {
3443 $salt = substr( wfGenerateToken(), 0, 8 );
3445 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3447 return ':A:' . md5( $password );
3452 * Compare a password hash with a plain-text password. Requires the user
3453 * ID if there's a chance that the hash is an old-style hash.
3455 * @param $hash \string Password hash
3456 * @param $password \string Plain-text password to compare
3457 * @param $userId \string User ID for old-style password salt
3460 static function comparePasswords( $hash, $password, $userId = false ) {
3462 $type = substr( $hash, 0, 3 );
3465 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3469 if ( $type == ':A:' ) {
3471 return md5( $password ) === substr( $hash, 3 );
3472 } elseif ( $type == ':B:' ) {
3474 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3475 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3478 return self
::oldCrypt( $password, $userId ) === $hash;
3483 * Add a newuser log entry for this user
3484 * @param $byEmail Boolean: account made by email?
3486 public function addNewUserLogEntry( $byEmail = false ) {
3487 global $wgUser, $wgContLang, $wgNewUserLog;
3488 if( empty($wgNewUserLog) ) {
3489 return true; // disabled
3491 $talk = $wgContLang->getFormattedNsText( NS_TALK
);
3492 if( $this->getName() == $wgUser->getName() ) {
3496 $action = 'create2';
3497 $message = $byEmail ?
wfMsgForContent( 'newuserlog-byemail' ) : '';
3499 $log = new LogPage( 'newusers' );
3500 $log->addEntry( $action, $this->getUserPage(), $message, array( $this->getId() ) );
3505 * Add an autocreate newuser log entry for this user
3506 * Used by things like CentralAuth and perhaps other authplugins.
3508 public function addNewUserLogEntryAutoCreate() {
3509 global $wgNewUserLog;
3510 if( empty($wgNewUserLog) ) {
3511 return true; // disabled
3513 $log = new LogPage( 'newusers', false );
3514 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );