7 # Number of characters in user_token field
8 define( 'USER_TOKEN_LENGTH', 32 );
10 # Serialized record version
11 define( 'MW_USER_VERSION', 6 );
13 # Some punctuation to prevent editing from broken text-mangling proxies.
14 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
17 * Thrown by User::setPassword() on error
20 class PasswordError
extends MWException
{
25 * The User object encapsulates all of the user-specific settings (user_id,
26 * name, rights, password, email address, options, last login time). Client
27 * classes use the getXXX() functions to access these fields. These functions
28 * do all the work of determining whether the user is logged in,
29 * whether the requested option can be satisfied from cookies or
30 * whether a database query is needed. Most of the settings needed
31 * for rendering normal pages are set in the cookie to minimize use
37 * A list of default user toggles, i.e. boolean user preferences that are
38 * displayed by Special:Preferences as checkboxes. This list can be
39 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
41 static public $mToggles = array(
51 'editsectiononrightclick',
63 'enotifwatchlistpages',
64 'enotifusertalkpages',
67 'shownumberswatching',
83 * List of member variables which are saved to the shared cache (memcached).
84 * Any operation which changes the corresponding database fields must
85 * call a cache-clearing function.
87 static $mCacheVars = array(
99 'mEmailAuthenticated',
101 'mEmailTokenExpires',
110 * Each of these should have a corresponding message of the form "right-$right"
112 static $mCoreRights = array(
153 static $mAllRights = false;
156 * The cache variable declarations
158 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
159 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
160 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
163 * Whether the cache variables have been loaded
168 * Initialisation data source if mDataLoaded==false. May be one of:
169 * defaults anonymous user initialised from class defaults
170 * name initialise from mName
171 * id initialise from mId
172 * session log in from cookies or session if possible
174 * Use the User::newFrom*() family of functions to set this.
179 * Lazy-initialised variables, invalidated with clearInstanceCache
181 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
182 $mBlockreason, $mBlock, $mEffectiveGroups;
185 * Lightweight constructor for anonymous user
186 * Use the User::newFrom* factory functions for other kinds of users
189 $this->clearInstanceCache( 'defaults' );
193 * Load the user table data for this object from the source given by mFrom
196 if ( $this->mDataLoaded
) {
199 wfProfileIn( __METHOD__
);
201 # Set it now to avoid infinite recursion in accessors
202 $this->mDataLoaded
= true;
204 switch ( $this->mFrom
) {
206 $this->loadDefaults();
209 $this->mId
= self
::idFromName( $this->mName
);
211 # Nonexistent user placeholder object
212 $this->loadDefaults( $this->mName
);
221 $this->loadFromSession();
224 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
226 wfProfileOut( __METHOD__
);
230 * Load user table data given mId
231 * @return false if the ID does not exist, true otherwise
234 function loadFromId() {
236 if ( $this->mId
== 0 ) {
237 $this->loadDefaults();
242 $key = wfMemcKey( 'user', 'id', $this->mId
);
243 $data = $wgMemc->get( $key );
244 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
245 # Object is expired, load from DB
250 wfDebug( "Cache miss for user {$this->mId}\n" );
252 if ( !$this->loadFromDatabase() ) {
253 # Can't load from ID, user is anonymous
256 $this->saveToCache();
258 wfDebug( "Got user {$this->mId} from cache\n" );
260 foreach ( self
::$mCacheVars as $name ) {
261 $this->$name = $data[$name];
268 * Save user data to the shared cache
270 function saveToCache() {
273 if ( $this->isAnon() ) {
274 // Anonymous users are uncached
278 foreach ( self
::$mCacheVars as $name ) {
279 $data[$name] = $this->$name;
281 $data['mVersion'] = MW_USER_VERSION
;
282 $key = wfMemcKey( 'user', 'id', $this->mId
);
284 $wgMemc->set( $key, $data );
288 * Static factory method for creation from username.
290 * This is slightly less efficient than newFromId(), so use newFromId() if
291 * you have both an ID and a name handy.
293 * @param $name String: username, validated by Title:newFromText()
294 * @param $validate Mixed: validate username. Takes the same parameters as
295 * User::getCanonicalName(), except that true is accepted as an alias
296 * for 'valid', for BC.
298 * @return User object, or null if the username is invalid. If the username
299 * is not present in the database, the result will be a user object with
300 * a name, zero user ID and default settings.
302 static function newFromName( $name, $validate = 'valid' ) {
303 if ( $validate === true ) {
306 $name = self
::getCanonicalName( $name, $validate );
307 if ( $name === false ) {
310 # Create unloaded user object
318 static function newFromId( $id ) {
326 * Factory method to fetch whichever user has a given email confirmation code.
327 * This code is generated when an account is created or its e-mail address
330 * If the code is invalid or has expired, returns NULL.
332 * @param $code string
335 static function newFromConfirmationCode( $code ) {
336 $dbr = wfGetDB( DB_SLAVE
);
337 $id = $dbr->selectField( 'user', 'user_id', array(
338 'user_email_token' => md5( $code ),
339 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
341 if( $id !== false ) {
342 return User
::newFromId( $id );
349 * Create a new user object using data from session or cookies. If the
350 * login credentials are invalid, the result is an anonymous user.
354 static function newFromSession() {
356 $user->mFrom
= 'session';
361 * Create a new user object from a user row.
362 * The row should have all fields from the user table in it.
364 static function newFromRow( $row ) {
366 $user->loadFromRow( $row );
371 * Get username given an id.
372 * @param $id Integer: database user id
373 * @return string Nickname of a user
375 static function whoIs( $id ) {
376 $dbr = wfGetDB( DB_SLAVE
);
377 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
381 * Get the real name of a user given their identifier
383 * @param $id Int: database user id
384 * @return string Real name of a user
386 static function whoIsReal( $id ) {
387 $dbr = wfGetDB( DB_SLAVE
);
388 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
392 * Get database id given a user name
393 * @param $name String: nickname of a user
394 * @return integer|null Database user id (null: if non existent
397 static function idFromName( $name ) {
398 $nt = Title
::newFromText( $name );
399 if( is_null( $nt ) ) {
403 $dbr = wfGetDB( DB_SLAVE
);
404 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
406 if ( $s === false ) {
414 * Does the string match an anonymous IPv4 address?
416 * This function exists for username validation, in order to reject
417 * usernames which are similar in form to IP addresses. Strings such
418 * as 300.300.300.300 will return true because it looks like an IP
419 * address, despite not being strictly valid.
421 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
422 * address because the usemod software would "cloak" anonymous IP
423 * addresses like this, if we allowed accounts like this to be created
424 * new users could get the old edits of these anonymous users.
426 * @param $name String: nickname of a user
429 static function isIP( $name ) {
430 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
434 * Is the input a valid username?
436 * Checks if the input is a valid username, we don't want an empty string,
437 * an IP address, anything that containins slashes (would mess up subpages),
438 * is longer than the maximum allowed username size or doesn't begin with
441 * @param $name string
444 static function isValidUserName( $name ) {
445 global $wgContLang, $wgMaxNameChars;
448 || User
::isIP( $name )
449 ||
strpos( $name, '/' ) !== false
450 ||
strlen( $name ) > $wgMaxNameChars
451 ||
$name != $wgContLang->ucfirst( $name ) ) {
452 wfDebugLog( 'username', __METHOD__
.
453 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
457 // Ensure that the name can't be misresolved as a different title,
458 // such as with extra namespace keys at the start.
459 $parsed = Title
::newFromText( $name );
460 if( is_null( $parsed )
461 ||
$parsed->getNamespace()
462 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
463 wfDebugLog( 'username', __METHOD__
.
464 ": '$name' invalid due to ambiguous prefixes" );
468 // Check an additional blacklist of troublemaker characters.
469 // Should these be merged into the title char list?
470 $unicodeBlacklist = '/[' .
471 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
472 '\x{00a0}' . # non-breaking space
473 '\x{2000}-\x{200f}' . # various whitespace
474 '\x{2028}-\x{202f}' . # breaks and control chars
475 '\x{3000}' . # ideographic space
476 '\x{e000}-\x{f8ff}' . # private use
478 if( preg_match( $unicodeBlacklist, $name ) ) {
479 wfDebugLog( 'username', __METHOD__
.
480 ": '$name' invalid due to blacklisted characters" );
488 * Usernames which fail to pass this function will be blocked
489 * from user login and new account registrations, but may be used
490 * internally by batch processes.
492 * If an account already exists in this form, login will be blocked
493 * by a failure to pass this function.
495 * @param $name string
498 static function isUsableName( $name ) {
499 global $wgReservedUsernames;
501 // Must be a valid username, obviously ;)
502 self
::isValidUserName( $name ) &&
504 // Certain names may be reserved for batch processes.
505 !in_array( $name, $wgReservedUsernames );
509 * Usernames which fail to pass this function will be blocked
510 * from new account registrations, but may be used internally
511 * either by batch processes or by user accounts which have
512 * already been created.
514 * Additional character blacklisting may be added here
515 * rather than in isValidUserName() to avoid disrupting
518 * @param $name string
521 static function isCreatableName( $name ) {
523 self
::isUsableName( $name ) &&
525 // Registration-time character blacklisting...
526 strpos( $name, '@' ) === false;
530 * Is the input a valid password for this user?
532 * @param $password String: desired password
535 function isValidPassword( $password ) {
536 global $wgMinimalPasswordLength, $wgContLang;
539 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
541 if( $result === false )
544 // Password needs to be long enough, and can't be the same as the username
545 return strlen( $password ) >= $wgMinimalPasswordLength
546 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
550 * Does a string look like an email address?
552 * There used to be a regular expression here, it got removed because it
553 * rejected valid addresses. Actually just check if there is '@' somewhere
554 * in the given address.
556 * @todo Check for RFC 2822 compilance (bug 959)
558 * @param $addr String: email address
561 public static function isValidEmailAddr( $addr ) {
563 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
567 return strpos( $addr, '@' ) !== false;
571 * Given unvalidated user input, return a canonical username, or false if
572 * the username is invalid.
573 * @param $name string
574 * @param $validate Mixed: type of validation to use:
575 * false No validation
576 * 'valid' Valid for batch processes
577 * 'usable' Valid for batch processes and login
578 * 'creatable' Valid for batch processes, login and account creation
580 static function getCanonicalName( $name, $validate = 'valid' ) {
581 # Force usernames to capital
583 $name = $wgContLang->ucfirst( $name );
585 # Reject names containing '#'; these will be cleaned up
586 # with title normalisation, but then it's too late to
588 if( strpos( $name, '#' ) !== false )
591 # Clean up name according to title rules
592 $t = Title
::newFromText( $name );
593 if( is_null( $t ) ) {
597 # Reject various classes of invalid names
598 $name = $t->getText();
600 $name = $wgAuth->getCanonicalName( $t->getText() );
602 switch ( $validate ) {
606 if ( !User
::isValidUserName( $name ) ) {
611 if ( !User
::isUsableName( $name ) ) {
616 if ( !User
::isCreatableName( $name ) ) {
621 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
627 * Count the number of edits of a user
629 * It should not be static and some day should be merged as proper member function / deprecated -- domas
631 * @param $uid Int: the user ID to check
634 static function edits( $uid ) {
635 wfProfileIn( __METHOD__
);
636 $dbr = wfGetDB( DB_SLAVE
);
637 // check if the user_editcount field has been initialized
638 $field = $dbr->selectField(
639 'user', 'user_editcount',
640 array( 'user_id' => $uid ),
644 if( $field === null ) { // it has not been initialized. do so.
645 $dbw = wfGetDB( DB_MASTER
);
646 $count = $dbr->selectField(
647 'revision', 'count(*)',
648 array( 'rev_user' => $uid ),
653 array( 'user_editcount' => $count ),
654 array( 'user_id' => $uid ),
660 wfProfileOut( __METHOD__
);
665 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
666 * @todo hash random numbers to improve security, like generateToken()
670 static function randomPassword() {
671 global $wgMinimalPasswordLength;
672 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
673 $l = strlen( $pwchars ) - 1;
675 $pwlength = max( 7, $wgMinimalPasswordLength );
676 $digit = mt_rand(0, $pwlength - 1);
678 for ( $i = 0; $i < $pwlength; $i++
) {
679 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
685 * Set cached properties to default. Note: this no longer clears
686 * uncached lazy-initialised properties. The constructor does that instead.
690 function loadDefaults( $name = false ) {
691 wfProfileIn( __METHOD__
);
693 global $wgCookiePrefix;
696 $this->mName
= $name;
697 $this->mRealName
= '';
698 $this->mPassword
= $this->mNewpassword
= '';
699 $this->mNewpassTime
= null;
701 $this->mOptions
= null; # Defer init
703 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
704 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
706 $this->mTouched
= '0'; # Allow any pages to be cached
709 $this->setToken(); # Random
710 $this->mEmailAuthenticated
= null;
711 $this->mEmailToken
= '';
712 $this->mEmailTokenExpires
= null;
713 $this->mRegistration
= wfTimestamp( TS_MW
);
714 $this->mGroups
= array();
716 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
718 wfProfileOut( __METHOD__
);
722 * Initialise php session
723 * @deprecated use wfSetupSession()
725 function SetupSession() {
726 wfDeprecated( __METHOD__
);
731 * Load user data from the session or login cookie. If there are no valid
732 * credentials, initialises the user as an anon.
733 * @return true if the user is logged in, false otherwise
735 private function loadFromSession() {
736 global $wgMemc, $wgCookiePrefix;
739 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
740 if ( $result !== null ) {
744 if ( isset( $_SESSION['wsUserID'] ) ) {
745 if ( 0 != $_SESSION['wsUserID'] ) {
746 $sId = $_SESSION['wsUserID'];
748 $this->loadDefaults();
751 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
752 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
753 $_SESSION['wsUserID'] = $sId;
755 $this->loadDefaults();
758 if ( isset( $_SESSION['wsUserName'] ) ) {
759 $sName = $_SESSION['wsUserName'];
760 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
761 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
762 $_SESSION['wsUserName'] = $sName;
764 $this->loadDefaults();
768 $passwordCorrect = FALSE;
770 if ( !$this->loadFromId() ) {
771 # Not a valid ID, loadFromId has switched the object to anon for us
775 if ( isset( $_SESSION['wsToken'] ) ) {
776 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
778 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
779 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
782 # No session or persistent login cookie
783 $this->loadDefaults();
787 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
788 $_SESSION['wsToken'] = $this->mToken
;
789 wfDebug( "Logged in from $from\n" );
792 # Invalid credentials
793 wfDebug( "Can't log in from $from, invalid credentials\n" );
794 $this->loadDefaults();
800 * Load user and user_group data from the database
801 * $this->mId must be set, this is how the user is identified.
803 * @return true if the user exists, false if the user is anonymous
806 function loadFromDatabase() {
808 $this->mId
= intval( $this->mId
);
810 /** Anonymous user */
812 $this->loadDefaults();
816 $dbr = wfGetDB( DB_MASTER
);
817 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
819 if ( $s !== false ) {
820 # Initialise user table data
821 $this->loadFromRow( $s );
822 $this->mGroups
= null; // deferred
823 $this->getEditCount(); // revalidation for nulls
828 $this->loadDefaults();
834 * Initialise the user object from a row from the user table
836 function loadFromRow( $row ) {
837 $this->mDataLoaded
= true;
839 if ( isset( $row->user_id
) ) {
840 $this->mId
= $row->user_id
;
842 $this->mName
= $row->user_name
;
843 $this->mRealName
= $row->user_real_name
;
844 $this->mPassword
= $row->user_password
;
845 $this->mNewpassword
= $row->user_newpassword
;
846 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
847 $this->mEmail
= $row->user_email
;
848 $this->decodeOptions( $row->user_options
);
849 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
850 $this->mToken
= $row->user_token
;
851 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
852 $this->mEmailToken
= $row->user_email_token
;
853 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
854 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
855 $this->mEditCount
= $row->user_editcount
;
859 * Load the groups from the database if they aren't already loaded
862 function loadGroups() {
863 if ( is_null( $this->mGroups
) ) {
864 $dbr = wfGetDB( DB_MASTER
);
865 $res = $dbr->select( 'user_groups',
867 array( 'ug_user' => $this->mId
),
869 $this->mGroups
= array();
870 while( $row = $dbr->fetchObject( $res ) ) {
871 $this->mGroups
[] = $row->ug_group
;
877 * Clear various cached data stored in this object.
878 * @param $reloadFrom String: reload user and user_groups table data from a
879 * given source. May be "name", "id", "defaults", "session" or false for
882 function clearInstanceCache( $reloadFrom = false ) {
883 $this->mNewtalk
= -1;
884 $this->mDatePreference
= null;
885 $this->mBlockedby
= -1; # Unset
886 $this->mHash
= false;
888 $this->mRights
= null;
889 $this->mEffectiveGroups
= null;
892 $this->mDataLoaded
= false;
893 $this->mFrom
= $reloadFrom;
898 * Combine the language default options with any site-specific options
899 * and add the default language variants.
900 * Not really private cause it's called by Language class
904 static function getDefaultOptions() {
905 global $wgNamespacesToBeSearchedDefault;
907 * Site defaults will override the global/language defaults
909 global $wgDefaultUserOptions, $wgContLang;
910 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
913 * default language setting
915 $variant = $wgContLang->getPreferredVariant( false );
916 $defOpt['variant'] = $variant;
917 $defOpt['language'] = $variant;
919 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
920 $defOpt['searchNs'.$nsnum] = $val;
926 * Get a given default option value.
931 public static function getDefaultOption( $opt ) {
932 $defOpts = self
::getDefaultOptions();
933 if( isset( $defOpts[$opt] ) ) {
934 return $defOpts[$opt];
941 * Get a list of user toggle names
944 static function getToggles() {
946 $extraToggles = array();
947 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
948 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
953 * Get blocking information
955 * @param $bFromSlave Bool: specify whether to check slave or master. To
956 * improve performance, non-critical checks are done
957 * against slaves. Check when actually saving should be
958 * done against master.
960 function getBlockedStatus( $bFromSlave = true ) {
961 global $wgEnableSorbs, $wgProxyWhitelist;
963 if ( -1 != $this->mBlockedby
) {
964 wfDebug( "User::getBlockedStatus: already loaded.\n" );
968 wfProfileIn( __METHOD__
);
969 wfDebug( __METHOD__
.": checking...\n" );
971 // Initialize data...
972 // Otherwise something ends up stomping on $this->mBlockedby when
973 // things get lazy-loaded later, causing false positive block hits
974 // due to -1 !== 0. Probably session-related... Nothing should be
975 // overwriting mBlockedby, surely?
978 $this->mBlockedby
= 0;
979 $this->mHideName
= 0;
982 if ($this->isAllowed( 'ipblock-exempt' ) ) {
983 # Exempt from all types of IP-block
988 $this->mBlock
= new Block();
989 $this->mBlock
->fromMaster( !$bFromSlave );
990 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
991 wfDebug( __METHOD__
.": Found block.\n" );
992 $this->mBlockedby
= $this->mBlock
->mBy
;
993 $this->mBlockreason
= $this->mBlock
->mReason
;
994 $this->mHideName
= $this->mBlock
->mHideName
;
995 if ( $this->isLoggedIn() ) {
996 $this->spreadBlock();
999 $this->mBlock
= null;
1000 wfDebug( __METHOD__
.": No block.\n" );
1004 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1006 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1007 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1008 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1012 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1013 if ( $this->inSorbsBlacklist( $ip ) ) {
1014 $this->mBlockedby
= wfMsg( 'sorbs' );
1015 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1021 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1023 wfProfileOut( __METHOD__
);
1026 function inSorbsBlacklist( $ip ) {
1027 global $wgEnableSorbs, $wgSorbsUrl;
1029 return $wgEnableSorbs &&
1030 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1033 function inDnsBlacklist( $ip, $base ) {
1034 wfProfileIn( __METHOD__
);
1040 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
1042 for ( $i=4; $i>=1; $i-- ) {
1043 $host .= $m[$i] . '.';
1048 $ipList = gethostbynamel( $host );
1051 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1054 wfDebug( "Requested $host, not found in $base.\n" );
1058 wfProfileOut( __METHOD__
);
1063 * Is this user subject to rate limiting?
1067 public function isPingLimitable() {
1068 global $wgRateLimitsExcludedGroups;
1069 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1070 // Deprecated, but kept for backwards-compatibility config
1073 return !$this->isAllowed('noratelimit');
1077 * Primitive rate limits: enforce maximum actions per time period
1078 * to put a brake on flooding.
1080 * Note: when using a shared cache like memcached, IP-address
1081 * last-hit counters will be shared across wikis.
1083 * @return bool true if a rate limiter was tripped
1085 function pingLimiter( $action='edit' ) {
1087 # Call the 'PingLimiter' hook
1089 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1093 global $wgRateLimits;
1094 if( !isset( $wgRateLimits[$action] ) ) {
1098 # Some groups shouldn't trigger the ping limiter, ever
1099 if( !$this->isPingLimitable() )
1102 global $wgMemc, $wgRateLimitLog;
1103 wfProfileIn( __METHOD__
);
1105 $limits = $wgRateLimits[$action];
1107 $id = $this->getId();
1111 if( isset( $limits['anon'] ) && $id == 0 ) {
1112 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1115 if( isset( $limits['user'] ) && $id != 0 ) {
1116 $userLimit = $limits['user'];
1118 if( $this->isNewbie() ) {
1119 if( isset( $limits['newbie'] ) && $id != 0 ) {
1120 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1122 if( isset( $limits['ip'] ) ) {
1123 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1126 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1127 $subnet = $matches[1];
1128 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1131 // Check for group-specific permissions
1132 // If more than one group applies, use the group with the highest limit
1133 foreach ( $this->getGroups() as $group ) {
1134 if ( isset( $limits[$group] ) ) {
1135 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1136 $userLimit = $limits[$group];
1140 // Set the user limit key
1141 if ( $userLimit !== false ) {
1142 wfDebug( __METHOD__
.": effective user limit: $userLimit\n" );
1143 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1147 foreach( $keys as $key => $limit ) {
1148 list( $max, $period ) = $limit;
1149 $summary = "(limit $max in {$period}s)";
1150 $count = $wgMemc->get( $key );
1152 if( $count > $max ) {
1153 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1154 if( $wgRateLimitLog ) {
1155 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1159 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1162 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1163 $wgMemc->add( $key, 1, intval( $period ) );
1165 $wgMemc->incr( $key );
1168 wfProfileOut( __METHOD__
);
1173 * Check if user is blocked
1174 * @return bool True if blocked, false otherwise
1176 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1177 wfDebug( "User::isBlocked: enter\n" );
1178 $this->getBlockedStatus( $bFromSlave );
1179 return $this->mBlockedby
!== 0;
1183 * Check if user is blocked from editing a particular article
1185 function isBlockedFrom( $title, $bFromSlave = false ) {
1186 global $wgBlockAllowsUTEdit;
1187 wfProfileIn( __METHOD__
);
1188 wfDebug( __METHOD__
.": enter\n" );
1190 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1191 $blocked = $this->isBlocked( $bFromSlave );
1192 # If a user's name is suppressed, they cannot make edits anywhere
1193 if ( !$this->mHideName
&& $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1194 $title->getNamespace() == NS_USER_TALK
) {
1196 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1198 wfProfileOut( __METHOD__
);
1203 * Get name of blocker
1204 * @return string name of blocker
1206 function blockedBy() {
1207 $this->getBlockedStatus();
1208 return $this->mBlockedby
;
1212 * Get blocking reason
1213 * @return string Blocking reason
1215 function blockedFor() {
1216 $this->getBlockedStatus();
1217 return $this->mBlockreason
;
1221 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1224 if( $this->mId
=== null and $this->mName
!== null
1225 and User
::isIP( $this->mName
) ) {
1226 // Special case, we know the user is anonymous
1228 } elseif( $this->mId
=== null ) {
1229 // Don't load if this was initialized from an ID
1236 * Set the user and reload all fields according to that ID
1238 function setId( $v ) {
1240 $this->clearInstanceCache( 'id' );
1244 * Get the user name, or the IP for anons
1246 function getName() {
1247 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1248 # Special case optimisation
1249 return $this->mName
;
1252 if ( $this->mName
=== false ) {
1254 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1256 return $this->mName
;
1261 * Set the user name.
1263 * This does not reload fields from the database according to the given
1264 * name. Rather, it is used to create a temporary "nonexistent user" for
1265 * later addition to the database. It can also be used to set the IP
1266 * address for an anonymous user to something other than the current
1269 * User::newFromName() has rougly the same function, when the named user
1272 function setName( $str ) {
1274 $this->mName
= $str;
1278 * Return the title dbkey form of the name, for eg user pages.
1281 function getTitleKey() {
1282 return str_replace( ' ', '_', $this->getName() );
1285 function getNewtalk() {
1288 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1289 if( $this->mNewtalk
=== -1 ) {
1290 $this->mNewtalk
= false; # reset talk page status
1292 # Check memcached separately for anons, who have no
1293 # entire User object stored in there.
1296 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1297 $newtalk = $wgMemc->get( $key );
1298 if( strval( $newtalk ) !== '' ) {
1299 $this->mNewtalk
= (bool)$newtalk;
1301 // Since we are caching this, make sure it is up to date by getting it
1303 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1304 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1307 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1311 return (bool)$this->mNewtalk
;
1315 * Return the talk page(s) this user has new messages on.
1317 function getNewMessageLinks() {
1319 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1322 if (!$this->getNewtalk())
1324 $up = $this->getUserPage();
1325 $utp = $up->getTalkPage();
1326 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1331 * Perform a user_newtalk check, uncached.
1332 * Use getNewtalk for a cached check.
1334 * @param $field string
1336 * @param $fromMaster Bool: true to fetch from the master, false for a slave
1340 function checkNewtalk( $field, $id, $fromMaster = false ) {
1341 if ( $fromMaster ) {
1342 $db = wfGetDB( DB_MASTER
);
1344 $db = wfGetDB( DB_SLAVE
);
1346 $ok = $db->selectField( 'user_newtalk', $field,
1347 array( $field => $id ), __METHOD__
);
1348 return $ok !== false;
1353 * @param $field string
1357 function updateNewtalk( $field, $id ) {
1358 $dbw = wfGetDB( DB_MASTER
);
1359 $dbw->insert( 'user_newtalk',
1360 array( $field => $id ),
1363 if ( $dbw->affectedRows() ) {
1364 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1367 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1373 * Clear the new messages flag for the given user
1374 * @param $field string
1378 function deleteNewtalk( $field, $id ) {
1379 $dbw = wfGetDB( DB_MASTER
);
1380 $dbw->delete( 'user_newtalk',
1381 array( $field => $id ),
1383 if ( $dbw->affectedRows() ) {
1384 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1387 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1393 * Update the 'You have new messages!' status.
1396 function setNewtalk( $val ) {
1397 if( wfReadOnly() ) {
1402 $this->mNewtalk
= $val;
1404 if( $this->isAnon() ) {
1406 $id = $this->getName();
1409 $id = $this->getId();
1414 $changed = $this->updateNewtalk( $field, $id );
1416 $changed = $this->deleteNewtalk( $field, $id );
1419 if( $this->isAnon() ) {
1420 // Anons have a separate memcached space, since
1421 // user records aren't kept for them.
1422 $key = wfMemcKey( 'newtalk', 'ip', $id );
1423 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1426 $this->invalidateCache();
1431 * Generate a current or new-future timestamp to be stored in the
1432 * user_touched field when we update things.
1434 private static function newTouchedTimestamp() {
1435 global $wgClockSkewFudge;
1436 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1440 * Clear user data from memcached.
1441 * Use after applying fun updates to the database; caller's
1442 * responsibility to update user_touched if appropriate.
1444 * Called implicitly from invalidateCache() and saveSettings().
1446 private function clearSharedCache() {
1449 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1454 * Immediately touch the user data cache for this account.
1455 * Updates user_touched field, and removes account data from memcached
1456 * for reload on the next hit.
1458 function invalidateCache() {
1461 $this->mTouched
= self
::newTouchedTimestamp();
1463 $dbw = wfGetDB( DB_MASTER
);
1464 $dbw->update( 'user',
1465 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1466 array( 'user_id' => $this->mId
),
1469 $this->clearSharedCache();
1473 function validateCache( $timestamp ) {
1475 return ($timestamp >= $this->mTouched
);
1479 * Set the password and reset the random token
1480 * Calls through to authentication plugin if necessary;
1481 * will have no effect if the auth plugin refuses to
1482 * pass the change through or if the legal password
1485 * As a special case, setting the password to null
1486 * wipes it, so the account cannot be logged in until
1487 * a new password is set, for instance via e-mail.
1489 * @param $str string
1490 * @throws PasswordError on failure
1492 function setPassword( $str ) {
1495 if( $str !== null ) {
1496 if( !$wgAuth->allowPasswordChange() ) {
1497 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1500 if( !$this->isValidPassword( $str ) ) {
1501 global $wgMinimalPasswordLength;
1502 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1503 $wgMinimalPasswordLength ) );
1507 if( !$wgAuth->setPassword( $this, $str ) ) {
1508 throw new PasswordError( wfMsg( 'externaldberror' ) );
1511 $this->setInternalPassword( $str );
1517 * Set the password and reset the random token no matter
1520 * @param $str string
1522 function setInternalPassword( $str ) {
1526 if( $str === null ) {
1527 // Save an invalid hash...
1528 $this->mPassword
= '';
1530 $this->mPassword
= self
::crypt( $str );
1532 $this->mNewpassword
= '';
1533 $this->mNewpassTime
= null;
1536 function getToken() {
1538 return $this->mToken
;
1542 * Set the random token (used for persistent authentication)
1543 * Called from loadDefaults() among other places.
1546 function setToken( $token = false ) {
1547 global $wgSecretKey, $wgProxyKey;
1550 if ( $wgSecretKey ) {
1551 $key = $wgSecretKey;
1552 } elseif ( $wgProxyKey ) {
1557 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1559 $this->mToken
= $token;
1563 function setCookiePassword( $str ) {
1565 $this->mCookiePassword
= md5( $str );
1569 * Set the password for a password reminder or new account email
1570 * Sets the user_newpass_time field if $throttle is true
1572 function setNewpassword( $str, $throttle = true ) {
1574 $this->mNewpassword
= self
::crypt( $str );
1576 $this->mNewpassTime
= wfTimestampNow();
1581 * Returns true if a password reminder email has already been sent within
1582 * the last $wgPasswordReminderResendTime hours
1584 function isPasswordReminderThrottled() {
1585 global $wgPasswordReminderResendTime;
1587 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1590 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1591 return time() < $expiry;
1594 function getEmail() {
1596 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1597 return $this->mEmail
;
1600 function getEmailAuthenticationTimestamp() {
1602 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1603 return $this->mEmailAuthenticated
;
1606 function setEmail( $str ) {
1608 $this->mEmail
= $str;
1609 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1612 function getRealName() {
1614 return $this->mRealName
;
1617 function setRealName( $str ) {
1619 $this->mRealName
= $str;
1623 * @param $oname String: the option to check
1624 * @param $defaultOverride String: A default value returned if the option does not exist
1627 function getOption( $oname, $defaultOverride = '' ) {
1630 if ( is_null( $this->mOptions
) ) {
1631 if($defaultOverride != '') {
1632 return $defaultOverride;
1634 $this->mOptions
= User
::getDefaultOptions();
1637 if ( array_key_exists( $oname, $this->mOptions
) ) {
1638 return trim( $this->mOptions
[$oname] );
1640 return $defaultOverride;
1645 * Get the user's date preference, including some important migration for
1648 function getDatePreference() {
1649 if ( is_null( $this->mDatePreference
) ) {
1651 $value = $this->getOption( 'date' );
1652 $map = $wgLang->getDatePreferenceMigrationMap();
1653 if ( isset( $map[$value] ) ) {
1654 $value = $map[$value];
1656 $this->mDatePreference
= $value;
1658 return $this->mDatePreference
;
1662 * @param $oname String: the option to check
1663 * @return bool False if the option is not selected, true if it is
1665 function getBoolOption( $oname ) {
1666 return (bool)$this->getOption( $oname );
1670 * Get an option as an integer value from the source string.
1671 * @param $oname String: the option to check
1672 * @param $default Int: optional value to return if option is unset/blank.
1675 function getIntOption( $oname, $default=0 ) {
1676 $val = $this->getOption( $oname );
1680 return intval( $val );
1683 function setOption( $oname, $val ) {
1685 if ( is_null( $this->mOptions
) ) {
1686 $this->mOptions
= User
::getDefaultOptions();
1688 if ( $oname == 'skin' ) {
1689 # Clear cached skin, so the new one displays immediately in Special:Preferences
1690 unset( $this->mSkin
);
1692 // Filter out any newlines that may have passed through input validation.
1693 // Newlines are used to separate items in the options blob.
1695 $val = str_replace( "\r\n", "\n", $val );
1696 $val = str_replace( "\r", "\n", $val );
1697 $val = str_replace( "\n", " ", $val );
1699 // Explicitly NULL values should refer to defaults
1700 global $wgDefaultUserOptions;
1701 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1702 $val = $wgDefaultUserOptions[$oname];
1704 $this->mOptions
[$oname] = $val;
1707 function getRights() {
1708 if ( is_null( $this->mRights
) ) {
1709 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1710 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1711 // Force reindexation of rights when a hook has unset one of them
1712 $this->mRights
= array_values( $this->mRights
);
1714 return $this->mRights
;
1718 * Get the list of explicit group memberships this user has.
1719 * The implicit * and user groups are not included.
1720 * @return array of strings
1722 function getGroups() {
1724 return $this->mGroups
;
1728 * Get the list of implicit group memberships this user has.
1729 * This includes all explicit groups, plus 'user' if logged in,
1730 * '*' for all accounts and autopromoted groups
1731 * @param $recache Boolean: don't use the cache
1732 * @return array of strings
1734 function getEffectiveGroups( $recache = false ) {
1735 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1736 $this->mEffectiveGroups
= $this->getGroups();
1737 $this->mEffectiveGroups
[] = '*';
1738 if( $this->getId() ) {
1739 $this->mEffectiveGroups
[] = 'user';
1741 $this->mEffectiveGroups
= array_unique( array_merge(
1742 $this->mEffectiveGroups
,
1743 Autopromote
::getAutopromoteGroups( $this )
1746 # Hook for additional groups
1747 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1750 return $this->mEffectiveGroups
;
1753 /* Return the edit count for the user. This is where User::edits should have been */
1754 function getEditCount() {
1756 if ( !isset( $this->mEditCount
) ) {
1757 /* Populate the count, if it has not been populated yet */
1758 $this->mEditCount
= User
::edits($this->mId
);
1760 return $this->mEditCount
;
1768 * Add the user to the given group.
1769 * This takes immediate effect.
1770 * @param $group string
1772 function addGroup( $group ) {
1773 $dbw = wfGetDB( DB_MASTER
);
1774 if( $this->getId() ) {
1775 $dbw->insert( 'user_groups',
1777 'ug_user' => $this->getID(),
1778 'ug_group' => $group,
1781 array( 'IGNORE' ) );
1784 $this->loadGroups();
1785 $this->mGroups
[] = $group;
1786 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1788 $this->invalidateCache();
1792 * Remove the user from the given group.
1793 * This takes immediate effect.
1794 * @param $group string
1796 function removeGroup( $group ) {
1798 $dbw = wfGetDB( DB_MASTER
);
1799 $dbw->delete( 'user_groups',
1801 'ug_user' => $this->getID(),
1802 'ug_group' => $group,
1804 'User::removeGroup' );
1806 $this->loadGroups();
1807 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1808 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1810 $this->invalidateCache();
1815 * A more legible check for non-anonymousness.
1816 * Returns true if the user is not an anonymous visitor.
1820 function isLoggedIn() {
1821 return $this->getID() != 0;
1825 * A more legible check for anonymousness.
1826 * Returns true if the user is an anonymous visitor.
1831 return !$this->isLoggedIn();
1835 * Whether the user is a bot
1839 wfDeprecated( __METHOD__
);
1840 return $this->isAllowed( 'bot' );
1844 * Check if user is allowed to access a feature / make an action
1845 * @param $action String: action to be checked
1846 * @return boolean True: action is allowed, False: action should not be allowed
1848 function isAllowed($action='') {
1849 if ( $action === '' )
1850 // In the spirit of DWIM
1853 return in_array( $action, $this->getRights() );
1857 * Check whether to enable recent changes patrol features for this user
1860 public function useRCPatrol() {
1861 global $wgUseRCPatrol;
1862 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
1866 * Check whether to enable recent changes patrol features for this user
1869 public function useNPPatrol() {
1870 global $wgUseRCPatrol, $wgUseNPPatrol;
1871 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
1875 * Load a skin if it doesn't exist or return it
1876 * @todo FIXME : need to check the old failback system [AV]
1878 function &getSkin() {
1880 if ( ! isset( $this->mSkin
) ) {
1881 wfProfileIn( __METHOD__
);
1884 $userSkin = $this->getOption( 'skin' );
1885 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1887 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1888 wfProfileOut( __METHOD__
);
1890 return $this->mSkin
;
1894 * @param $title Title: article title to look at
1898 * Check watched status of an article
1899 * @return bool True if article is watched
1901 function isWatched( $title ) {
1902 $wl = WatchedItem
::fromUserTitle( $this, $title );
1903 return $wl->isWatched();
1909 function addWatch( $title ) {
1910 $wl = WatchedItem
::fromUserTitle( $this, $title );
1912 $this->invalidateCache();
1916 * Stop watching an article
1918 function removeWatch( $title ) {
1919 $wl = WatchedItem
::fromUserTitle( $this, $title );
1921 $this->invalidateCache();
1925 * Clear the user's notification timestamp for the given title.
1926 * If e-notif e-mails are on, they will receive notification mails on
1927 * the next change of the page if it's watched etc.
1929 function clearNotification( &$title ) {
1930 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
1932 # Do nothing if the database is locked to writes
1933 if( wfReadOnly() ) {
1937 if ($title->getNamespace() == NS_USER_TALK
&&
1938 $title->getText() == $this->getName() ) {
1939 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1941 $this->setNewtalk( false );
1944 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
1948 if( $this->isAnon() ) {
1949 // Nothing else to do...
1953 // Only update the timestamp if the page is being watched.
1954 // The query to find out if it is watched is cached both in memcached and per-invocation,
1955 // and when it does have to be executed, it can be on a slave
1956 // If this is the user's newtalk page, we always update the timestamp
1957 if ($title->getNamespace() == NS_USER_TALK
&&
1958 $title->getText() == $wgUser->getName())
1961 } elseif ( $this->getId() == $wgUser->getId() ) {
1962 $watched = $title->userIsWatching();
1967 // If the page is watched by the user (or may be watched), update the timestamp on any
1968 // any matching rows
1970 $dbw = wfGetDB( DB_MASTER
);
1971 $dbw->update( 'watchlist',
1973 'wl_notificationtimestamp' => NULL
1974 ), array( /* WHERE */
1975 'wl_title' => $title->getDBkey(),
1976 'wl_namespace' => $title->getNamespace(),
1977 'wl_user' => $this->getID()
1986 * Resets all of the given user's page-change notification timestamps.
1987 * If e-notif e-mails are on, they will receive notification mails on
1988 * the next change of any watched page.
1990 * @param $currentUser Int: user ID number
1992 function clearAllNotifications( $currentUser ) {
1993 global $wgUseEnotif, $wgShowUpdatedMarker;
1994 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
1995 $this->setNewtalk( false );
1998 if( $currentUser != 0 ) {
1999 $dbw = wfGetDB( DB_MASTER
);
2000 $dbw->update( 'watchlist',
2002 'wl_notificationtimestamp' => NULL
2003 ), array( /* WHERE */
2004 'wl_user' => $currentUser
2007 # We also need to clear here the "you have new message" notification for the own user_talk page
2008 # This is cleared one page view later in Article::viewUpdates();
2014 * @return string Encoding options
2016 function encodeOptions() {
2018 if ( is_null( $this->mOptions
) ) {
2019 $this->mOptions
= User
::getDefaultOptions();
2022 foreach ( $this->mOptions
as $oname => $oval ) {
2023 array_push( $a, $oname.'='.$oval );
2025 $s = implode( "\n", $a );
2032 function decodeOptions( $str ) {
2033 $this->mOptions
= array();
2034 $a = explode( "\n", $str );
2035 foreach ( $a as $s ) {
2037 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2038 $this->mOptions
[$m[1]] = $m[2];
2043 protected function setCookie( $name, $value, $exp=0 ) {
2044 global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly;
2046 $exp = time() +
$wgCookieExpiration;
2048 $httpOnlySafe = wfHttpOnlySafe();
2049 wfDebugLog( 'cookie',
2050 'setcookie: "' . implode( '", "',
2052 $wgCookiePrefix . $name,
2058 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2059 if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) {
2060 setcookie( $wgCookiePrefix . $name,
2066 $wgCookieHttpOnly );
2068 // setcookie() fails on PHP 5.1 if you give it future-compat paramters.
2070 setcookie( $wgCookiePrefix . $name,
2079 protected function clearCookie( $name ) {
2080 $this->setCookie( $name, '', time() - 86400 );
2083 function setCookies() {
2085 if ( 0 == $this->mId
) return;
2087 'wsUserID' => $this->mId
,
2088 'wsToken' => $this->mToken
,
2089 'wsUserName' => $this->getName()
2092 'UserID' => $this->mId
,
2093 'UserName' => $this->getName(),
2095 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2096 $cookies['Token'] = $this->mToken
;
2098 $cookies['Token'] = false;
2101 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2102 $_SESSION = $session +
$_SESSION;
2103 foreach ( $cookies as $name => $value ) {
2104 if ( $value === false ) {
2105 $this->clearCookie( $name );
2107 $this->setCookie( $name, $value );
2117 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2123 * Really logout user
2124 * Clears the cookies and session, resets the instance cache
2126 function doLogout() {
2127 $this->clearInstanceCache( 'defaults' );
2129 $_SESSION['wsUserID'] = 0;
2131 $this->clearCookie( 'UserID' );
2132 $this->clearCookie( 'Token' );
2134 # Remember when user logged out, to prevent seeing cached pages
2135 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2139 * Save object settings into database
2140 * @todo Only rarely do all these fields need to be set!
2142 function saveSettings() {
2144 if ( wfReadOnly() ) { return; }
2145 if ( 0 == $this->mId
) { return; }
2147 $this->mTouched
= self
::newTouchedTimestamp();
2149 $dbw = wfGetDB( DB_MASTER
);
2150 $dbw->update( 'user',
2152 'user_name' => $this->mName
,
2153 'user_password' => $this->mPassword
,
2154 'user_newpassword' => $this->mNewpassword
,
2155 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2156 'user_real_name' => $this->mRealName
,
2157 'user_email' => $this->mEmail
,
2158 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2159 'user_options' => $this->encodeOptions(),
2160 'user_touched' => $dbw->timestamp($this->mTouched
),
2161 'user_token' => $this->mToken
,
2162 'user_email_token' => $this->mEmailToken
,
2163 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2164 ), array( /* WHERE */
2165 'user_id' => $this->mId
2168 wfRunHooks( 'UserSaveSettings', array( $this ) );
2169 $this->clearSharedCache();
2173 * Checks if a user with the given name exists, returns the ID.
2175 function idForName() {
2176 $s = trim( $this->getName() );
2177 if ( $s === '' ) return 0;
2179 $dbr = wfGetDB( DB_SLAVE
);
2180 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2181 if ( $id === false ) {
2188 * Add a user to the database, return the user object
2190 * @param $name String: the user's name
2191 * @param $params Associative array of non-default parameters to save to the database:
2192 * password The user's password. Password logins will be disabled if this is omitted.
2193 * newpassword A temporary password mailed to the user
2194 * email The user's email address
2195 * email_authenticated The email authentication timestamp
2196 * real_name The user's real name
2197 * options An associative array of non-default options
2198 * token Random authentication token. Do not set.
2199 * registration Registration timestamp. Do not set.
2201 * @return User object, or null if the username already exists
2203 static function createNew( $name, $params = array() ) {
2206 if ( isset( $params['options'] ) ) {
2207 $user->mOptions
= $params['options'] +
$user->mOptions
;
2208 unset( $params['options'] );
2210 $dbw = wfGetDB( DB_MASTER
);
2211 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2213 'user_id' => $seqVal,
2214 'user_name' => $name,
2215 'user_password' => $user->mPassword
,
2216 'user_newpassword' => $user->mNewpassword
,
2217 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2218 'user_email' => $user->mEmail
,
2219 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2220 'user_real_name' => $user->mRealName
,
2221 'user_options' => $user->encodeOptions(),
2222 'user_token' => $user->mToken
,
2223 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2224 'user_editcount' => 0,
2226 foreach ( $params as $name => $value ) {
2227 $fields["user_$name"] = $value;
2229 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2230 if ( $dbw->affectedRows() ) {
2231 $newUser = User
::newFromId( $dbw->insertId() );
2239 * Add an existing user object to the database
2241 function addToDatabase() {
2243 $dbw = wfGetDB( DB_MASTER
);
2244 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2245 $dbw->insert( 'user',
2247 'user_id' => $seqVal,
2248 'user_name' => $this->mName
,
2249 'user_password' => $this->mPassword
,
2250 'user_newpassword' => $this->mNewpassword
,
2251 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2252 'user_email' => $this->mEmail
,
2253 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2254 'user_real_name' => $this->mRealName
,
2255 'user_options' => $this->encodeOptions(),
2256 'user_token' => $this->mToken
,
2257 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2258 'user_editcount' => 0,
2261 $this->mId
= $dbw->insertId();
2263 # Clear instance cache other than user table data, which is already accurate
2264 $this->clearInstanceCache();
2268 * If the (non-anonymous) user is blocked, this function will block any IP address
2269 * that they successfully log on from.
2271 function spreadBlock() {
2272 wfDebug( __METHOD__
."()\n" );
2274 if ( $this->mId
== 0 ) {
2278 $userblock = Block
::newFromDB( '', $this->mId
);
2279 if ( !$userblock ) {
2283 $userblock->doAutoblock( wfGetIp() );
2288 * Generate a string which will be different for any combination of
2289 * user options which would produce different parser output.
2290 * This will be used as part of the hash key for the parser cache,
2291 * so users will the same options can share the same cached data
2294 * Extensions which require it should install 'PageRenderingHash' hook,
2295 * which will give them a chance to modify this key based on their own
2300 function getPageRenderingHash() {
2301 global $wgContLang, $wgUseDynamicDates, $wgLang;
2303 return $this->mHash
;
2306 // stubthreshold is only included below for completeness,
2307 // it will always be 0 when this function is called by parsercache.
2309 $confstr = $this->getOption( 'math' );
2310 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2311 if ( $wgUseDynamicDates ) {
2312 $confstr .= '!' . $this->getDatePreference();
2314 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2315 $confstr .= '!' . $wgLang->getCode();
2316 $confstr .= '!' . $this->getOption( 'thumbsize' );
2317 // add in language specific options, if any
2318 $extra = $wgContLang->getExtraHashOptions();
2321 // Give a chance for extensions to modify the hash, if they have
2322 // extra options or other effects on the parser cache.
2323 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2325 // Make it a valid memcached key fragment
2326 $confstr = str_replace( ' ', '_', $confstr );
2327 $this->mHash
= $confstr;
2331 function isBlockedFromCreateAccount() {
2332 $this->getBlockedStatus();
2333 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2337 * Determine if the user is blocked from using Special:Emailuser.
2341 function isBlockedFromEmailuser() {
2342 $this->getBlockedStatus();
2343 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2346 function isAllowedToCreateAccount() {
2347 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2353 function setLoaded( $loaded ) {
2354 wfDeprecated( __METHOD__
);
2358 * Get this user's personal page title.
2362 function getUserPage() {
2363 return Title
::makeTitle( NS_USER
, $this->getName() );
2367 * Get this user's talk page title.
2371 function getTalkPage() {
2372 $title = $this->getUserPage();
2373 return $title->getTalkPage();
2379 function getMaxID() {
2380 static $res; // cache
2382 if ( isset( $res ) )
2385 $dbr = wfGetDB( DB_SLAVE
);
2386 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2391 * Determine whether the user is a newbie. Newbies are either
2392 * anonymous IPs, or the most recently created accounts.
2393 * @return bool True if it is a newbie.
2395 function isNewbie() {
2396 return !$this->isAllowed( 'autoconfirmed' );
2400 * Is the user active? We check to see if they've made at least
2401 * X number of edits in the last Y days.
2403 * @return bool true if the user is active, false if not
2405 public function isActiveEditor() {
2406 global $wgActiveUserEditCount, $wgActiveUserDays;
2407 $dbr = wfGetDB( DB_SLAVE
);
2409 // Stolen without shame from RC
2410 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2411 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
2412 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2414 $res = $dbr->select( 'revision', '1',
2415 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2417 array('LIMIT' => $wgActiveUserEditCount ) );
2419 $count = $dbr->numRows($res);
2420 $dbr->freeResult($res);
2422 return $count == $wgActiveUserEditCount;
2426 * Check to see if the given clear-text password is one of the accepted passwords
2427 * @param $password String: user password.
2428 * @return bool True if the given password is correct otherwise False.
2430 function checkPassword( $password ) {
2434 // Even though we stop people from creating passwords that
2435 // are shorter than this, doesn't mean people wont be able
2436 // to. Certain authentication plugins do NOT want to save
2437 // domain passwords in a mysql database, so we should
2438 // check this (incase $wgAuth->strict() is false).
2439 if( !$this->isValidPassword( $password ) ) {
2443 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2445 } elseif( $wgAuth->strict() ) {
2446 /* Auth plugin doesn't allow local authentication */
2448 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2449 /* Auth plugin doesn't allow local authentication for this user name */
2452 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2454 } elseif ( function_exists( 'iconv' ) ) {
2455 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2456 # Check for this with iconv
2457 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2458 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2466 * Check if the given clear-text password matches the temporary password
2467 * sent by e-mail for password reset operations.
2470 function checkTemporaryPassword( $plaintext ) {
2471 return self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() );
2475 * Initialize (if necessary) and return a session token value
2476 * which can be used in edit forms to show that the user's
2477 * login credentials aren't being hijacked with a foreign form
2480 * @param $salt Mixed: optional function-specific data for hash.
2481 * Use a string or an array of strings.
2484 function editToken( $salt = '' ) {
2485 if ( $this->isAnon() ) {
2486 return EDIT_TOKEN_SUFFIX
;
2488 if( !isset( $_SESSION['wsEditToken'] ) ) {
2489 $token = $this->generateToken();
2490 $_SESSION['wsEditToken'] = $token;
2492 $token = $_SESSION['wsEditToken'];
2494 if( is_array( $salt ) ) {
2495 $salt = implode( '|', $salt );
2497 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2502 * Generate a hex-y looking random token for various uses.
2503 * Could be made more cryptographically sure if someone cares.
2506 function generateToken( $salt = '' ) {
2507 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2508 return md5( $token . $salt );
2512 * Check given value against the token value stored in the session.
2513 * A match should confirm that the form was submitted from the
2514 * user's own login session, not a form submission from a third-party
2517 * @param $val String: the input value to compare
2518 * @param $salt String: optional function-specific data for hash
2521 function matchEditToken( $val, $salt = '' ) {
2522 $sessionToken = $this->editToken( $salt );
2523 if ( $val != $sessionToken ) {
2524 wfDebug( "User::matchEditToken: broken session data\n" );
2526 return $val == $sessionToken;
2530 * Check whether the edit token is fine except for the suffix
2532 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2533 $sessionToken = $this->editToken( $salt );
2534 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2538 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2539 * mail to the user's given address.
2541 * Calls saveSettings() internally; as it has side effects, not committing changes
2542 * would be pretty silly.
2544 * @return mixed True on success, a WikiError object on failure.
2546 function sendConfirmationMail() {
2548 $expiration = null; // gets passed-by-ref and defined in next line.
2549 $token = $this->confirmationToken( $expiration );
2550 $url = $this->confirmationTokenUrl( $token );
2551 $invalidateURL = $this->invalidationTokenUrl( $token );
2552 $this->saveSettings();
2554 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2555 wfMsg( 'confirmemail_body',
2559 $wgLang->timeanddate( $expiration, false ),
2564 * Send an e-mail to this user's account. Does not check for
2565 * confirmed status or validity.
2567 * @param $subject string
2568 * @param $body string
2569 * @param $from string: optional from address; default $wgPasswordSender will be used otherwise.
2570 * @param $replyto string
2571 * @return mixed True on success, a WikiError object on failure.
2573 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2574 if( is_null( $from ) ) {
2575 global $wgPasswordSender;
2576 $from = $wgPasswordSender;
2579 $to = new MailAddress( $this );
2580 $sender = new MailAddress( $from );
2581 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2585 * Generate, store, and return a new e-mail confirmation code.
2586 * A hash (unsalted since it's used as a key) is stored.
2588 * Call saveSettings() after calling this function to commit
2589 * this change to the database.
2591 * @param &$expiration mixed output: accepts the expiration time
2595 function confirmationToken( &$expiration ) {
2597 $expires = $now +
7 * 24 * 60 * 60;
2598 $expiration = wfTimestamp( TS_MW
, $expires );
2599 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2600 $hash = md5( $token );
2602 $this->mEmailToken
= $hash;
2603 $this->mEmailTokenExpires
= $expiration;
2608 * Return a URL the user can use to confirm their email address.
2609 * @param $token accepts the email confirmation token
2613 function confirmationTokenUrl( $token ) {
2614 return $this->getTokenUrl( 'ConfirmEmail', $token );
2617 * Return a URL the user can use to invalidate their email address.
2618 * @param $token accepts the email confirmation token
2622 function invalidationTokenUrl( $token ) {
2623 return $this->getTokenUrl( 'Invalidateemail', $token );
2627 * Internal function to format the e-mail validation/invalidation URLs.
2628 * This uses $wgArticlePath directly as a quickie hack to use the
2629 * hardcoded English names of the Special: pages, for ASCII safety.
2631 * Since these URLs get dropped directly into emails, using the
2632 * short English names avoids insanely long URL-encoded links, which
2633 * also sometimes can get corrupted in some browsers/mailers
2634 * (bug 6957 with Gmail and Internet Explorer).
2636 protected function getTokenUrl( $page, $token ) {
2637 global $wgArticlePath;
2641 "Special:$page/$token",
2646 * Mark the e-mail address confirmed.
2648 * Call saveSettings() after calling this function to commit the change.
2650 function confirmEmail() {
2651 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2656 * Invalidate the user's email confirmation, unauthenticate the email
2657 * if it was already confirmed.
2659 * Call saveSettings() after calling this function to commit the change.
2661 function invalidateEmail() {
2663 $this->mEmailToken
= null;
2664 $this->mEmailTokenExpires
= null;
2665 $this->setEmailAuthenticationTimestamp( null );
2669 function setEmailAuthenticationTimestamp( $timestamp ) {
2671 $this->mEmailAuthenticated
= $timestamp;
2672 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2676 * Is this user allowed to send e-mails within limits of current
2677 * site configuration?
2680 function canSendEmail() {
2681 $canSend = $this->isEmailConfirmed();
2682 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2687 * Is this user allowed to receive e-mails within limits of current
2688 * site configuration?
2691 function canReceiveEmail() {
2692 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2696 * Is this user's e-mail address valid-looking and confirmed within
2697 * limits of the current site configuration?
2699 * If $wgEmailAuthentication is on, this may require the user to have
2700 * confirmed their address by returning a code or using a password
2701 * sent to the address from the wiki.
2705 function isEmailConfirmed() {
2706 global $wgEmailAuthentication;
2709 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2710 if( $this->isAnon() )
2712 if( !self
::isValidEmailAddr( $this->mEmail
) )
2714 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2723 * Return true if there is an outstanding request for e-mail confirmation.
2726 function isEmailConfirmationPending() {
2727 global $wgEmailAuthentication;
2728 return $wgEmailAuthentication &&
2729 !$this->isEmailConfirmed() &&
2730 $this->mEmailToken
&&
2731 $this->mEmailTokenExpires
> wfTimestamp();
2735 * Get the timestamp of account creation, or false for
2736 * non-existent/anonymous user accounts
2740 public function getRegistration() {
2741 return $this->mId
> 0
2742 ?
$this->mRegistration
2747 * @param $groups Array: list of groups
2748 * @return array list of permission key names for given groups combined
2750 static function getGroupPermissions( $groups ) {
2751 global $wgGroupPermissions;
2753 foreach( $groups as $group ) {
2754 if( isset( $wgGroupPermissions[$group] ) ) {
2755 $rights = array_merge( $rights,
2756 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2763 * @param $group String: key name
2764 * @return string localized descriptive name for group, if provided
2766 static function getGroupName( $group ) {
2767 global $wgMessageCache;
2768 $wgMessageCache->loadAllMessages();
2769 $key = "group-$group";
2770 $name = wfMsg( $key );
2771 return $name == '' ||
wfEmptyMsg( $key, $name )
2777 * @param $group String: key name
2778 * @return string localized descriptive name for member of a group, if provided
2780 static function getGroupMember( $group ) {
2781 global $wgMessageCache;
2782 $wgMessageCache->loadAllMessages();
2783 $key = "group-$group-member";
2784 $name = wfMsg( $key );
2785 return $name == '' ||
wfEmptyMsg( $key, $name )
2791 * Return the set of defined explicit groups.
2792 * The implicit groups (by default *, 'user' and 'autoconfirmed')
2793 * are not included, as they are defined automatically,
2794 * not in the database.
2797 static function getAllGroups() {
2798 global $wgGroupPermissions;
2800 array_keys( $wgGroupPermissions ),
2801 self
::getImplicitGroups()
2806 * Get a list of all available permissions
2808 static function getAllRights() {
2809 if ( self
::$mAllRights === false ) {
2810 global $wgAvailableRights;
2811 if ( count( $wgAvailableRights ) ) {
2812 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
2814 self
::$mAllRights = self
::$mCoreRights;
2816 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
2818 return self
::$mAllRights;
2822 * Get a list of implicit groups
2826 public static function getImplicitGroups() {
2827 global $wgImplicitGroups;
2828 $groups = $wgImplicitGroups;
2829 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
2834 * Get the title of a page describing a particular group
2836 * @param $group Name of the group
2839 static function getGroupPage( $group ) {
2840 global $wgMessageCache;
2841 $wgMessageCache->loadAllMessages();
2842 $page = wfMsgForContent( 'grouppage-' . $group );
2843 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2844 $title = Title
::newFromText( $page );
2845 if( is_object( $title ) )
2852 * Create a link to the group in HTML, if available
2854 * @param $group Name of the group
2855 * @param $text The text of the link
2858 static function makeGroupLinkHTML( $group, $text = '' ) {
2860 $text = self
::getGroupName( $group );
2862 $title = self
::getGroupPage( $group );
2865 $sk = $wgUser->getSkin();
2866 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2873 * Create a link to the group in Wikitext, if available
2875 * @param $group Name of the group
2876 * @param $text The text of the link (by default, the name of the group)
2879 static function makeGroupLinkWiki( $group, $text = '' ) {
2881 $text = self
::getGroupName( $group );
2883 $title = self
::getGroupPage( $group );
2885 $page = $title->getPrefixedText();
2886 return "[[$page|$text]]";
2893 * Increment the user's edit-count field.
2894 * Will have no effect for anonymous users.
2896 function incEditCount() {
2897 if( !$this->isAnon() ) {
2898 $dbw = wfGetDB( DB_MASTER
);
2899 $dbw->update( 'user',
2900 array( 'user_editcount=user_editcount+1' ),
2901 array( 'user_id' => $this->getId() ),
2904 // Lazy initialization check...
2905 if( $dbw->affectedRows() == 0 ) {
2906 // Pull from a slave to be less cruel to servers
2907 // Accuracy isn't the point anyway here
2908 $dbr = wfGetDB( DB_SLAVE
);
2909 $count = $dbr->selectField( 'revision',
2911 array( 'rev_user' => $this->getId() ),
2914 // Now here's a goddamn hack...
2915 if( $dbr !== $dbw ) {
2916 // If we actually have a slave server, the count is
2917 // at least one behind because the current transaction
2918 // has not been committed and replicated.
2921 // But if DB_SLAVE is selecting the master, then the
2922 // count we just read includes the revision that was
2923 // just added in the working transaction.
2926 $dbw->update( 'user',
2927 array( 'user_editcount' => $count ),
2928 array( 'user_id' => $this->getId() ),
2932 // edit count in user cache too
2933 $this->invalidateCache();
2936 static function getRightDescription( $right ) {
2937 global $wgMessageCache;
2938 $wgMessageCache->loadAllMessages();
2939 $key = "right-$right";
2940 $name = wfMsg( $key );
2941 return $name == '' ||
wfEmptyMsg( $key, $name )
2947 * Make an old-style password hash
2949 * @param $password String: plain-text password
2950 * @param $userId String: user ID
2952 static function oldCrypt( $password, $userId ) {
2953 global $wgPasswordSalt;
2954 if ( $wgPasswordSalt ) {
2955 return md5( $userId . '-' . md5( $password ) );
2957 return md5( $password );
2962 * Make a new-style password hash
2964 * @param $password String: plain-text password
2965 * @param $salt String: salt, may be random or the user ID. False to generate a salt.
2967 static function crypt( $password, $salt = false ) {
2968 global $wgPasswordSalt;
2970 if($wgPasswordSalt) {
2971 if ( $salt === false ) {
2972 $salt = substr( wfGenerateToken(), 0, 8 );
2974 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
2976 return ':A:' . md5( $password);
2981 * Compare a password hash with a plain-text password. Requires the user
2982 * ID if there's a chance that the hash is an old-style hash.
2984 * @param $hash String: password hash
2985 * @param $password String: plain-text password to compare
2986 * @param $userId String: user ID for old-style password salt
2988 static function comparePasswords( $hash, $password, $userId = false ) {
2990 $type = substr( $hash, 0, 3 );
2991 if ( $type == ':A:' ) {
2993 return md5( $password ) === substr( $hash, 3 );
2994 } elseif ( $type == ':B:' ) {
2996 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
2997 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3000 return self
::oldCrypt( $password, $userId ) === $hash;