7 # Number of characters in user_token field
8 define( 'USER_TOKEN_LENGTH', 32 );
10 # Serialized record version
11 define( 'MW_USER_VERSION', 5 );
13 # Some punctuation to prevent editing from broken text-mangling proxies.
14 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
17 * Thrown by User::setPassword() on error
18 * @addtogroup Exception
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(
100 'mEmailAuthenticated',
102 'mEmailTokenExpires',
111 * The cache variable declarations
113 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
114 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
115 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
118 * Whether the cache variables have been loaded
123 * Initialisation data source if mDataLoaded==false. May be one of:
124 * defaults anonymous user initialised from class defaults
125 * name initialise from mName
126 * id initialise from mId
127 * session log in from cookies or session if possible
129 * Use the User::newFrom*() family of functions to set this.
134 * Lazy-initialised variables, invalidated with clearInstanceCache
136 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
137 $mBlockreason, $mBlock, $mEffectiveGroups;
140 * Lightweight constructor for anonymous user
141 * Use the User::newFrom* factory functions for other kinds of users
144 $this->clearInstanceCache( 'defaults' );
148 * Load the user table data for this object from the source given by mFrom
151 if ( $this->mDataLoaded
) {
154 wfProfileIn( __METHOD__
);
156 # Set it now to avoid infinite recursion in accessors
157 $this->mDataLoaded
= true;
159 switch ( $this->mFrom
) {
161 $this->loadDefaults();
164 $this->mId
= self
::idFromName( $this->mName
);
166 # Nonexistent user placeholder object
167 $this->loadDefaults( $this->mName
);
176 $this->loadFromSession();
179 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
181 wfProfileOut( __METHOD__
);
185 * Load user table data given mId
186 * @return false if the ID does not exist, true otherwise
189 function loadFromId() {
191 if ( $this->mId
== 0 ) {
192 $this->loadDefaults();
197 $key = wfMemcKey( 'user', 'id', $this->mId
);
198 $data = $wgMemc->get( $key );
199 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
200 # Object is expired, load from DB
205 wfDebug( "Cache miss for user {$this->mId}\n" );
207 if ( !$this->loadFromDatabase() ) {
208 # Can't load from ID, user is anonymous
211 $this->saveToCache();
213 wfDebug( "Got user {$this->mId} from cache\n" );
215 foreach ( self
::$mCacheVars as $name ) {
216 $this->$name = $data[$name];
223 * Save user data to the shared cache
225 function saveToCache() {
228 if ( $this->isAnon() ) {
229 // Anonymous users are uncached
233 foreach ( self
::$mCacheVars as $name ) {
234 $data[$name] = $this->$name;
236 $data['mVersion'] = MW_USER_VERSION
;
237 $key = wfMemcKey( 'user', 'id', $this->mId
);
239 $wgMemc->set( $key, $data );
243 * Static factory method for creation from username.
245 * This is slightly less efficient than newFromId(), so use newFromId() if
246 * you have both an ID and a name handy.
248 * @param string $name Username, validated by Title:newFromText()
249 * @param mixed $validate Validate username. Takes the same parameters as
250 * User::getCanonicalName(), except that true is accepted as an alias
251 * for 'valid', for BC.
253 * @return User object, or null if the username is invalid. If the username
254 * is not present in the database, the result will be a user object with
255 * a name, zero user ID and default settings.
258 static function newFromName( $name, $validate = 'valid' ) {
259 if ( $validate === true ) {
262 $name = self
::getCanonicalName( $name, $validate );
263 if ( $name === false ) {
266 # Create unloaded user object
274 static function newFromId( $id ) {
282 * Factory method to fetch whichever user has a given email confirmation code.
283 * This code is generated when an account is created or its e-mail address
286 * If the code is invalid or has expired, returns NULL.
288 * @param string $code
292 static function newFromConfirmationCode( $code ) {
293 $dbr = wfGetDB( DB_SLAVE
);
294 $id = $dbr->selectField( 'user', 'user_id', array(
295 'user_email_token' => md5( $code ),
296 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
298 if( $id !== false ) {
299 return User
::newFromId( $id );
306 * Create a new user object using data from session or cookies. If the
307 * login credentials are invalid, the result is an anonymous user.
312 static function newFromSession() {
314 $user->mFrom
= 'session';
319 * Create a new user object from a user row.
320 * The row should have all fields from the user table in it.
322 static function newFromRow( $row ) {
324 $user->loadFromRow( $row );
329 * Get username given an id.
330 * @param integer $id Database user id
331 * @return string Nickname of a user
334 static function whoIs( $id ) {
335 $dbr = wfGetDB( DB_SLAVE
);
336 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
340 * Get the real name of a user given their identifier
342 * @param int $id Database user id
343 * @return string Real name of a user
345 static function whoIsReal( $id ) {
346 $dbr = wfGetDB( DB_SLAVE
);
347 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
351 * Get database id given a user name
352 * @param string $name Nickname of a user
353 * @return integer|null Database user id (null: if non existent
356 static function idFromName( $name ) {
357 $nt = Title
::newFromText( $name );
358 if( is_null( $nt ) ) {
362 $dbr = wfGetDB( DB_SLAVE
);
363 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
365 if ( $s === false ) {
373 * Does the string match an anonymous IPv4 address?
375 * This function exists for username validation, in order to reject
376 * usernames which are similar in form to IP addresses. Strings such
377 * as 300.300.300.300 will return true because it looks like an IP
378 * address, despite not being strictly valid.
380 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
381 * address because the usemod software would "cloak" anonymous IP
382 * addresses like this, if we allowed accounts like this to be created
383 * new users could get the old edits of these anonymous users.
386 * @param string $name Nickname of a user
389 static function isIP( $name ) {
390 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User
::isIPv6($name);
391 /*return preg_match("/^
392 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
393 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
394 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
395 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
400 * Check if $name is an IPv6 IP.
402 static function isIPv6($name) {
404 * if it has any non-valid characters, it can't be a valid IPv6
407 if (preg_match("/[^:a-fA-F0-9]/", $name))
410 $parts = explode(":", $name);
411 if (count($parts) < 3)
413 foreach ($parts as $part) {
414 if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part))
421 * Is the input a valid username?
423 * Checks if the input is a valid username, we don't want an empty string,
424 * an IP address, anything that containins slashes (would mess up subpages),
425 * is longer than the maximum allowed username size or doesn't begin with
428 * @param string $name
432 static function isValidUserName( $name ) {
433 global $wgContLang, $wgMaxNameChars;
436 || User
::isIP( $name )
437 ||
strpos( $name, '/' ) !== false
438 ||
strlen( $name ) > $wgMaxNameChars
439 ||
$name != $wgContLang->ucfirst( $name ) ) {
440 wfDebugLog( 'username', __METHOD__
.
441 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
445 // Ensure that the name can't be misresolved as a different title,
446 // such as with extra namespace keys at the start.
447 $parsed = Title
::newFromText( $name );
448 if( is_null( $parsed )
449 ||
$parsed->getNamespace()
450 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
451 wfDebugLog( 'username', __METHOD__
.
452 ": '$name' invalid due to ambiguous prefixes" );
456 // Check an additional blacklist of troublemaker characters.
457 // Should these be merged into the title char list?
458 $unicodeBlacklist = '/[' .
459 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
460 '\x{00a0}' . # non-breaking space
461 '\x{2000}-\x{200f}' . # various whitespace
462 '\x{2028}-\x{202f}' . # breaks and control chars
463 '\x{3000}' . # ideographic space
464 '\x{e000}-\x{f8ff}' . # private use
466 if( preg_match( $unicodeBlacklist, $name ) ) {
467 wfDebugLog( 'username', __METHOD__
.
468 ": '$name' invalid due to blacklisted characters" );
476 * Usernames which fail to pass this function will be blocked
477 * from user login and new account registrations, but may be used
478 * internally by batch processes.
480 * If an account already exists in this form, login will be blocked
481 * by a failure to pass this function.
483 * @param string $name
486 static function isUsableName( $name ) {
487 global $wgReservedUsernames;
489 // Must be a valid username, obviously ;)
490 self
::isValidUserName( $name ) &&
492 // Certain names may be reserved for batch processes.
493 !in_array( $name, $wgReservedUsernames );
497 * Usernames which fail to pass this function will be blocked
498 * from new account registrations, but may be used internally
499 * either by batch processes or by user accounts which have
500 * already been created.
502 * Additional character blacklisting may be added here
503 * rather than in isValidUserName() to avoid disrupting
506 * @param string $name
509 static function isCreatableName( $name ) {
511 self
::isUsableName( $name ) &&
513 // Registration-time character blacklisting...
514 strpos( $name, '@' ) === false;
518 * Is the input a valid password for this user?
520 * @param string $password Desired password
523 function isValidPassword( $password ) {
524 global $wgMinimalPasswordLength, $wgContLang;
527 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
529 if( $result === false )
532 // Password needs to be long enough, and can't be the same as the username
533 return strlen( $password ) >= $wgMinimalPasswordLength
534 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
538 * Does a string look like an email address?
540 * There used to be a regular expression here, it got removed because it
541 * rejected valid addresses. Actually just check if there is '@' somewhere
542 * in the given address.
544 * @todo Check for RFC 2822 compilance (bug 959)
546 * @param string $addr email address
549 public static function isValidEmailAddr( $addr ) {
551 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
555 return strpos( $addr, '@' ) !== false;
559 * Given unvalidated user input, return a canonical username, or false if
560 * the username is invalid.
561 * @param string $name
562 * @param mixed $validate Type of validation to use:
563 * false No validation
564 * 'valid' Valid for batch processes
565 * 'usable' Valid for batch processes and login
566 * 'creatable' Valid for batch processes, login and account creation
568 static function getCanonicalName( $name, $validate = 'valid' ) {
569 # Force usernames to capital
571 $name = $wgContLang->ucfirst( $name );
573 # Reject names containing '#'; these will be cleaned up
574 # with title normalisation, but then it's too late to
576 if( strpos( $name, '#' ) !== false )
579 # Clean up name according to title rules
580 $t = Title
::newFromText( $name );
581 if( is_null( $t ) ) {
585 # Reject various classes of invalid names
586 $name = $t->getText();
588 $name = $wgAuth->getCanonicalName( $t->getText() );
590 switch ( $validate ) {
594 if ( !User
::isValidUserName( $name ) ) {
599 if ( !User
::isUsableName( $name ) ) {
604 if ( !User
::isCreatableName( $name ) ) {
609 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
615 * Count the number of edits of a user
617 * It should not be static and some day should be merged as proper member function / deprecated -- domas
619 * @param int $uid The user ID to check
623 static function edits( $uid ) {
624 wfProfileIn( __METHOD__
);
625 $dbr = wfGetDB( DB_SLAVE
);
626 // check if the user_editcount field has been initialized
627 $field = $dbr->selectField(
628 'user', 'user_editcount',
629 array( 'user_id' => $uid ),
633 if( $field === null ) { // it has not been initialized. do so.
634 $dbw = wfGetDB( DB_MASTER
);
635 $count = $dbr->selectField(
636 'revision', 'count(*)',
637 array( 'rev_user' => $uid ),
642 array( 'user_editcount' => $count ),
643 array( 'user_id' => $uid ),
649 wfProfileOut( __METHOD__
);
654 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
655 * @todo hash random numbers to improve security, like generateToken()
660 static function randomPassword() {
661 global $wgMinimalPasswordLength;
662 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
663 $l = strlen( $pwchars ) - 1;
665 $pwlength = max( 7, $wgMinimalPasswordLength );
666 $digit = mt_rand(0, $pwlength - 1);
668 for ( $i = 0; $i < $pwlength; $i++
) {
669 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
675 * Set cached properties to default. Note: this no longer clears
676 * uncached lazy-initialised properties. The constructor does that instead.
680 function loadDefaults( $name = false ) {
681 wfProfileIn( __METHOD__
);
683 global $wgCookiePrefix;
686 $this->mName
= $name;
687 $this->mRealName
= '';
688 $this->mPassword
= $this->mNewpassword
= '';
689 $this->mNewpassTime
= null;
691 $this->mOptions
= null; # Defer init
693 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
694 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
696 $this->mTouched
= '0'; # Allow any pages to be cached
699 $this->setToken(); # Random
700 $this->mEmailAuthenticated
= null;
701 $this->mEmailToken
= '';
702 $this->mEmailTokenExpires
= null;
703 $this->mRegistration
= wfTimestamp( TS_MW
);
704 $this->mGroups
= array();
706 wfProfileOut( __METHOD__
);
710 * Initialise php session
711 * @deprecated use wfSetupSession()
713 function SetupSession() {
714 wfDeprecated( __METHOD__
);
719 * Load user data from the session or login cookie. If there are no valid
720 * credentials, initialises the user as an anon.
721 * @return true if the user is logged in, false otherwise
723 private function loadFromSession() {
724 global $wgMemc, $wgCookiePrefix;
726 if ( isset( $_SESSION['wsUserID'] ) ) {
727 if ( 0 != $_SESSION['wsUserID'] ) {
728 $sId = $_SESSION['wsUserID'];
730 $this->loadDefaults();
733 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
734 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
735 $_SESSION['wsUserID'] = $sId;
737 $this->loadDefaults();
740 if ( isset( $_SESSION['wsUserName'] ) ) {
741 $sName = $_SESSION['wsUserName'];
742 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
743 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
744 $_SESSION['wsUserName'] = $sName;
746 $this->loadDefaults();
750 $passwordCorrect = FALSE;
752 if ( !$this->loadFromId() ) {
753 # Not a valid ID, loadFromId has switched the object to anon for us
757 if ( isset( $_SESSION['wsToken'] ) ) {
758 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
760 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
761 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
764 # No session or persistent login cookie
765 $this->loadDefaults();
769 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
770 $_SESSION['wsToken'] = $this->mToken
;
771 wfDebug( "Logged in from $from\n" );
774 # Invalid credentials
775 wfDebug( "Can't log in from $from, invalid credentials\n" );
776 $this->loadDefaults();
782 * Load user and user_group data from the database
783 * $this->mId must be set, this is how the user is identified.
785 * @return true if the user exists, false if the user is anonymous
788 function loadFromDatabase() {
790 $this->mId
= intval( $this->mId
);
792 /** Anonymous user */
794 $this->loadDefaults();
798 $dbr = wfGetDB( DB_MASTER
);
799 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
801 if ( $s !== false ) {
802 # Initialise user table data
803 $this->loadFromRow( $s );
804 $this->mGroups
= null; // deferred
805 $this->getEditCount(); // revalidation for nulls
810 $this->loadDefaults();
816 * Initialise the user object from a row from the user table
818 function loadFromRow( $row ) {
819 $this->mDataLoaded
= true;
821 if ( isset( $row->user_id
) ) {
822 $this->mId
= $row->user_id
;
824 $this->mName
= $row->user_name
;
825 $this->mRealName
= $row->user_real_name
;
826 $this->mPassword
= $row->user_password
;
827 $this->mNewpassword
= $row->user_newpassword
;
828 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
829 $this->mEmail
= $row->user_email
;
830 $this->decodeOptions( $row->user_options
);
831 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
832 $this->mToken
= $row->user_token
;
833 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
834 $this->mEmailToken
= $row->user_email_token
;
835 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
836 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
837 $this->mEditCount
= $row->user_editcount
;
841 * Load the groups from the database if they aren't already loaded
844 function loadGroups() {
845 if ( is_null( $this->mGroups
) ) {
846 $dbr = wfGetDB( DB_MASTER
);
847 $res = $dbr->select( 'user_groups',
849 array( 'ug_user' => $this->mId
),
851 $this->mGroups
= array();
852 while( $row = $dbr->fetchObject( $res ) ) {
853 $this->mGroups
[] = $row->ug_group
;
859 * Clear various cached data stored in this object.
860 * @param string $reloadFrom Reload user and user_groups table data from a
861 * given source. May be "name", "id", "defaults", "session" or false for
864 function clearInstanceCache( $reloadFrom = false ) {
865 $this->mNewtalk
= -1;
866 $this->mDatePreference
= null;
867 $this->mBlockedby
= -1; # Unset
868 $this->mHash
= false;
870 $this->mRights
= null;
871 $this->mEffectiveGroups
= null;
874 $this->mDataLoaded
= false;
875 $this->mFrom
= $reloadFrom;
880 * Combine the language default options with any site-specific options
881 * and add the default language variants.
882 * Not really private cause it's called by Language class
887 static function getDefaultOptions() {
888 global $wgNamespacesToBeSearchedDefault;
890 * Site defaults will override the global/language defaults
892 global $wgDefaultUserOptions, $wgContLang;
893 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
896 * default language setting
898 $variant = $wgContLang->getPreferredVariant( false );
899 $defOpt['variant'] = $variant;
900 $defOpt['language'] = $variant;
902 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
903 $defOpt['searchNs'.$nsnum] = $val;
909 * Get a given default option value.
916 function getDefaultOption( $opt ) {
917 $defOpts = User
::getDefaultOptions();
918 if( isset( $defOpts[$opt] ) ) {
919 return $defOpts[$opt];
926 * Get a list of user toggle names
929 static function getToggles() {
931 $extraToggles = array();
932 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
933 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
938 * Get blocking information
940 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
941 * non-critical checks are done against slaves. Check when actually saving should be done against
944 function getBlockedStatus( $bFromSlave = true ) {
945 global $wgEnableSorbs, $wgProxyWhitelist;
947 if ( -1 != $this->mBlockedby
) {
948 wfDebug( "User::getBlockedStatus: already loaded.\n" );
952 wfProfileIn( __METHOD__
);
953 wfDebug( __METHOD__
.": checking...\n" );
955 $this->mBlockedby
= 0;
956 $this->mHideName
= 0;
959 if ($this->isAllowed( 'ipblock-exempt' ) ) {
960 # Exempt from all types of IP-block
965 $this->mBlock
= new Block();
966 $this->mBlock
->fromMaster( !$bFromSlave );
967 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
968 wfDebug( __METHOD__
.": Found block.\n" );
969 $this->mBlockedby
= $this->mBlock
->mBy
;
970 $this->mBlockreason
= $this->mBlock
->mReason
;
971 $this->mHideName
= $this->mBlock
->mHideName
;
972 if ( $this->isLoggedIn() ) {
973 $this->spreadBlock();
976 $this->mBlock
= null;
977 wfDebug( __METHOD__
.": No block.\n" );
981 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
984 if ( wfIsLocallyBlockedProxy( $ip ) ) {
985 $this->mBlockedby
= wfMsg( 'proxyblocker' );
986 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
990 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
991 if ( $this->inSorbsBlacklist( $ip ) ) {
992 $this->mBlockedby
= wfMsg( 'sorbs' );
993 $this->mBlockreason
= wfMsg( 'sorbsreason' );
999 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1001 wfProfileOut( __METHOD__
);
1004 function inSorbsBlacklist( $ip ) {
1005 global $wgEnableSorbs, $wgSorbsUrl;
1007 return $wgEnableSorbs &&
1008 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1011 function inDnsBlacklist( $ip, $base ) {
1012 wfProfileIn( __METHOD__
);
1018 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
1020 for ( $i=4; $i>=1; $i-- ) {
1021 $host .= $m[$i] . '.';
1026 $ipList = gethostbynamel( $host );
1029 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1032 wfDebug( "Requested $host, not found in $base.\n" );
1036 wfProfileOut( __METHOD__
);
1041 * Is this user subject to rate limiting?
1045 public function isPingLimitable() {
1046 global $wgRateLimitsExcludedGroups;
1047 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
1051 * Primitive rate limits: enforce maximum actions per time period
1052 * to put a brake on flooding.
1054 * Note: when using a shared cache like memcached, IP-address
1055 * last-hit counters will be shared across wikis.
1057 * @return bool true if a rate limiter was tripped
1060 function pingLimiter( $action='edit' ) {
1062 # Call the 'PingLimiter' hook
1064 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1068 global $wgRateLimits;
1069 if( !isset( $wgRateLimits[$action] ) ) {
1073 # Some groups shouldn't trigger the ping limiter, ever
1074 if( !$this->isPingLimitable() )
1077 global $wgMemc, $wgRateLimitLog;
1078 wfProfileIn( __METHOD__
);
1080 $limits = $wgRateLimits[$action];
1082 $id = $this->getId();
1085 if( isset( $limits['anon'] ) && $id == 0 ) {
1086 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1089 if( isset( $limits['user'] ) && $id != 0 ) {
1090 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
1092 if( $this->isNewbie() ) {
1093 if( isset( $limits['newbie'] ) && $id != 0 ) {
1094 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1096 if( isset( $limits['ip'] ) ) {
1097 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1100 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1101 $subnet = $matches[1];
1102 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1107 foreach( $keys as $key => $limit ) {
1108 list( $max, $period ) = $limit;
1109 $summary = "(limit $max in {$period}s)";
1110 $count = $wgMemc->get( $key );
1112 if( $count > $max ) {
1113 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1114 if( $wgRateLimitLog ) {
1115 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1119 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1122 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1123 $wgMemc->add( $key, 1, intval( $period ) );
1125 $wgMemc->incr( $key );
1128 wfProfileOut( __METHOD__
);
1133 * Check if user is blocked
1134 * @return bool True if blocked, false otherwise
1136 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1137 wfDebug( "User::isBlocked: enter\n" );
1138 $this->getBlockedStatus( $bFromSlave );
1139 return $this->mBlockedby
!== 0;
1143 * Check if user is blocked from editing a particular article
1145 function isBlockedFrom( $title, $bFromSlave = false ) {
1146 global $wgBlockAllowsUTEdit;
1147 wfProfileIn( __METHOD__
);
1148 wfDebug( __METHOD__
.": enter\n" );
1150 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1151 $blocked = $this->isBlocked( $bFromSlave );
1152 # If a user's name is suppressed, they cannot make edits anywhere
1153 if ( !$this->mHideName
&& $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1154 $title->getNamespace() == NS_USER_TALK
) {
1156 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1158 wfProfileOut( __METHOD__
);
1163 * Get name of blocker
1164 * @return string name of blocker
1166 function blockedBy() {
1167 $this->getBlockedStatus();
1168 return $this->mBlockedby
;
1172 * Get blocking reason
1173 * @return string Blocking reason
1175 function blockedFor() {
1176 $this->getBlockedStatus();
1177 return $this->mBlockreason
;
1181 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1184 if( $this->mId
=== null and $this->mName
!== null
1185 and User
::isIP( $this->mName
) ) {
1186 // Special case, we know the user is anonymous
1188 } elseif( $this->mId
=== null ) {
1189 // Don't load if this was initialized from an ID
1196 * Set the user and reload all fields according to that ID
1197 * @deprecated use User::newFromId()
1199 function setID( $v ) {
1200 wfDeprecated( __METHOD__
);
1202 $this->clearInstanceCache( 'id' );
1206 * Get the user name, or the IP for anons
1208 function getName() {
1209 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1210 # Special case optimisation
1211 return $this->mName
;
1214 if ( $this->mName
=== false ) {
1216 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1218 return $this->mName
;
1223 * Set the user name.
1225 * This does not reload fields from the database according to the given
1226 * name. Rather, it is used to create a temporary "nonexistent user" for
1227 * later addition to the database. It can also be used to set the IP
1228 * address for an anonymous user to something other than the current
1231 * User::newFromName() has rougly the same function, when the named user
1234 function setName( $str ) {
1236 $this->mName
= $str;
1240 * Return the title dbkey form of the name, for eg user pages.
1244 function getTitleKey() {
1245 return str_replace( ' ', '_', $this->getName() );
1248 function getNewtalk() {
1251 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1252 if( $this->mNewtalk
=== -1 ) {
1253 $this->mNewtalk
= false; # reset talk page status
1255 # Check memcached separately for anons, who have no
1256 # entire User object stored in there.
1259 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1260 $newtalk = $wgMemc->get( $key );
1261 if( strval( $newtalk ) !== '' ) {
1262 $this->mNewtalk
= (bool)$newtalk;
1264 // Since we are caching this, make sure it is up to date by getting it
1266 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1267 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1270 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1274 return (bool)$this->mNewtalk
;
1278 * Return the talk page(s) this user has new messages on.
1280 function getNewMessageLinks() {
1282 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1285 if (!$this->getNewtalk())
1287 $up = $this->getUserPage();
1288 $utp = $up->getTalkPage();
1289 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1294 * Perform a user_newtalk check, uncached.
1295 * Use getNewtalk for a cached check.
1297 * @param string $field
1299 * @param bool $fromMaster True to fetch from the master, false for a slave
1303 function checkNewtalk( $field, $id, $fromMaster = false ) {
1304 if ( $fromMaster ) {
1305 $db = wfGetDB( DB_MASTER
);
1307 $db = wfGetDB( DB_SLAVE
);
1309 $ok = $db->selectField( 'user_newtalk', $field,
1310 array( $field => $id ), __METHOD__
);
1311 return $ok !== false;
1316 * @param string $field
1320 function updateNewtalk( $field, $id ) {
1321 $dbw = wfGetDB( DB_MASTER
);
1322 $dbw->insert( 'user_newtalk',
1323 array( $field => $id ),
1326 if ( $dbw->affectedRows() ) {
1327 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1330 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1336 * Clear the new messages flag for the given user
1337 * @param string $field
1341 function deleteNewtalk( $field, $id ) {
1342 $dbw = wfGetDB( DB_MASTER
);
1343 $dbw->delete( 'user_newtalk',
1344 array( $field => $id ),
1346 if ( $dbw->affectedRows() ) {
1347 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1350 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1356 * Update the 'You have new messages!' status.
1359 function setNewtalk( $val ) {
1360 if( wfReadOnly() ) {
1365 $this->mNewtalk
= $val;
1367 if( $this->isAnon() ) {
1369 $id = $this->getName();
1372 $id = $this->getId();
1377 $changed = $this->updateNewtalk( $field, $id );
1379 $changed = $this->deleteNewtalk( $field, $id );
1382 if( $this->isAnon() ) {
1383 // Anons have a separate memcached space, since
1384 // user records aren't kept for them.
1385 $key = wfMemcKey( 'newtalk', 'ip', $id );
1386 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1389 $this->invalidateCache();
1394 * Generate a current or new-future timestamp to be stored in the
1395 * user_touched field when we update things.
1397 private static function newTouchedTimestamp() {
1398 global $wgClockSkewFudge;
1399 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1403 * Clear user data from memcached.
1404 * Use after applying fun updates to the database; caller's
1405 * responsibility to update user_touched if appropriate.
1407 * Called implicitly from invalidateCache() and saveSettings().
1409 private function clearSharedCache() {
1412 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1417 * Immediately touch the user data cache for this account.
1418 * Updates user_touched field, and removes account data from memcached
1419 * for reload on the next hit.
1421 function invalidateCache() {
1424 $this->mTouched
= self
::newTouchedTimestamp();
1426 $dbw = wfGetDB( DB_MASTER
);
1427 $dbw->update( 'user',
1428 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1429 array( 'user_id' => $this->mId
),
1432 $this->clearSharedCache();
1436 function validateCache( $timestamp ) {
1438 return ($timestamp >= $this->mTouched
);
1442 * Encrypt a password.
1443 * It can eventually salt a password.
1444 * @see User::addSalt()
1445 * @param string $p clear Password.
1446 * @return string Encrypted password.
1448 function encryptPassword( $p ) {
1450 return wfEncryptPassword( $this->mId
, $p );
1454 * Set the password and reset the random token
1455 * Calls through to authentication plugin if necessary;
1456 * will have no effect if the auth plugin refuses to
1457 * pass the change through or if the legal password
1460 * As a special case, setting the password to null
1461 * wipes it, so the account cannot be logged in until
1462 * a new password is set, for instance via e-mail.
1464 * @param string $str
1465 * @throws PasswordError on failure
1467 function setPassword( $str ) {
1470 if( $str !== null ) {
1471 if( !$wgAuth->allowPasswordChange() ) {
1472 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1475 if( !$this->isValidPassword( $str ) ) {
1476 global $wgMinimalPasswordLength;
1477 throw new PasswordError( wfMsg( 'passwordtooshort',
1478 $wgMinimalPasswordLength ) );
1482 if( !$wgAuth->setPassword( $this, $str ) ) {
1483 throw new PasswordError( wfMsg( 'externaldberror' ) );
1486 $this->setInternalPassword( $str );
1492 * Set the password and reset the random token no matter
1495 * @param string $str
1497 function setInternalPassword( $str ) {
1501 if( $str === null ) {
1502 // Save an invalid hash...
1503 $this->mPassword
= '';
1505 $this->mPassword
= $this->encryptPassword( $str );
1507 $this->mNewpassword
= '';
1508 $this->mNewpassTime
= null;
1511 * Set the random token (used for persistent authentication)
1512 * Called from loadDefaults() among other places.
1515 function setToken( $token = false ) {
1516 global $wgSecretKey, $wgProxyKey;
1519 if ( $wgSecretKey ) {
1520 $key = $wgSecretKey;
1521 } elseif ( $wgProxyKey ) {
1526 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1528 $this->mToken
= $token;
1532 function setCookiePassword( $str ) {
1534 $this->mCookiePassword
= md5( $str );
1538 * Set the password for a password reminder or new account email
1539 * Sets the user_newpass_time field if $throttle is true
1541 function setNewpassword( $str, $throttle = true ) {
1543 $this->mNewpassword
= $this->encryptPassword( $str );
1545 $this->mNewpassTime
= wfTimestampNow();
1550 * Returns true if a password reminder email has already been sent within
1551 * the last $wgPasswordReminderResendTime hours
1553 function isPasswordReminderThrottled() {
1554 global $wgPasswordReminderResendTime;
1556 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1559 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1560 return time() < $expiry;
1563 function getEmail() {
1565 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1566 return $this->mEmail
;
1569 function getEmailAuthenticationTimestamp() {
1571 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1572 return $this->mEmailAuthenticated
;
1575 function setEmail( $str ) {
1577 $this->mEmail
= $str;
1578 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1581 function getRealName() {
1583 return $this->mRealName
;
1586 function setRealName( $str ) {
1588 $this->mRealName
= $str;
1592 * @param string $oname The option to check
1593 * @param string $defaultOverride A default value returned if the option does not exist
1596 function getOption( $oname, $defaultOverride = '' ) {
1599 if ( is_null( $this->mOptions
) ) {
1600 if($defaultOverride != '') {
1601 return $defaultOverride;
1603 $this->mOptions
= User
::getDefaultOptions();
1606 if ( array_key_exists( $oname, $this->mOptions
) ) {
1607 return trim( $this->mOptions
[$oname] );
1609 return $defaultOverride;
1614 * Get the user's date preference, including some important migration for
1617 function getDatePreference() {
1618 if ( is_null( $this->mDatePreference
) ) {
1620 $value = $this->getOption( 'date' );
1621 $map = $wgLang->getDatePreferenceMigrationMap();
1622 if ( isset( $map[$value] ) ) {
1623 $value = $map[$value];
1625 $this->mDatePreference
= $value;
1627 return $this->mDatePreference
;
1631 * @param string $oname The option to check
1632 * @return bool False if the option is not selected, true if it is
1634 function getBoolOption( $oname ) {
1635 return (bool)$this->getOption( $oname );
1639 * Get an option as an integer value from the source string.
1640 * @param string $oname The option to check
1641 * @param int $default Optional value to return if option is unset/blank.
1644 function getIntOption( $oname, $default=0 ) {
1645 $val = $this->getOption( $oname );
1649 return intval( $val );
1652 function setOption( $oname, $val ) {
1654 if ( is_null( $this->mOptions
) ) {
1655 $this->mOptions
= User
::getDefaultOptions();
1657 if ( $oname == 'skin' ) {
1658 # Clear cached skin, so the new one displays immediately in Special:Preferences
1659 unset( $this->mSkin
);
1661 // Filter out any newlines that may have passed through input validation.
1662 // Newlines are used to separate items in the options blob.
1663 $val = str_replace( "\r\n", "\n", $val );
1664 $val = str_replace( "\r", "\n", $val );
1665 $val = str_replace( "\n", " ", $val );
1666 $this->mOptions
[$oname] = $val;
1669 function getRights() {
1670 if ( is_null( $this->mRights
) ) {
1671 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1672 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1674 return $this->mRights
;
1678 * Get the list of explicit group memberships this user has.
1679 * The implicit * and user groups are not included.
1680 * @return array of strings
1682 function getGroups() {
1684 return $this->mGroups
;
1688 * Get the list of implicit group memberships this user has.
1689 * This includes all explicit groups, plus 'user' if logged in,
1690 * '*' for all accounts and autopromoted groups
1691 * @param boolean $recache Don't use the cache
1692 * @return array of strings
1694 function getEffectiveGroups( $recache = false ) {
1695 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1696 $this->mEffectiveGroups
= $this->getGroups();
1697 $this->mEffectiveGroups
[] = '*';
1698 if( $this->getId() ) {
1699 $this->mEffectiveGroups
[] = 'user';
1701 $this->mEffectiveGroups
= array_unique( array_merge(
1702 $this->mEffectiveGroups
,
1703 Autopromote
::getAutopromoteGroups( $this )
1706 # Hook for additional groups
1707 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1710 return $this->mEffectiveGroups
;
1713 /* Return the edit count for the user. This is where User::edits should have been */
1714 function getEditCount() {
1716 if ( !isset( $this->mEditCount
) ) {
1717 /* Populate the count, if it has not been populated yet */
1718 $this->mEditCount
= User
::edits($this->mId
);
1720 return $this->mEditCount
;
1728 * Add the user to the given group.
1729 * This takes immediate effect.
1730 * @param string $group
1732 function addGroup( $group ) {
1733 $dbw = wfGetDB( DB_MASTER
);
1734 if( $this->getId() ) {
1735 $dbw->insert( 'user_groups',
1737 'ug_user' => $this->getID(),
1738 'ug_group' => $group,
1741 array( 'IGNORE' ) );
1744 $this->loadGroups();
1745 $this->mGroups
[] = $group;
1746 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1748 $this->invalidateCache();
1752 * Remove the user from the given group.
1753 * This takes immediate effect.
1754 * @param string $group
1756 function removeGroup( $group ) {
1758 $dbw = wfGetDB( DB_MASTER
);
1759 $dbw->delete( 'user_groups',
1761 'ug_user' => $this->getID(),
1762 'ug_group' => $group,
1764 'User::removeGroup' );
1766 $this->loadGroups();
1767 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1768 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1770 $this->invalidateCache();
1775 * A more legible check for non-anonymousness.
1776 * Returns true if the user is not an anonymous visitor.
1780 function isLoggedIn() {
1781 return $this->getID() != 0;
1785 * A more legible check for anonymousness.
1786 * Returns true if the user is an anonymous visitor.
1791 return !$this->isLoggedIn();
1795 * Whether the user is a bot
1799 wfDeprecated( __METHOD__
);
1800 return $this->isAllowed( 'bot' );
1804 * Check if user is allowed to access a feature / make an action
1805 * @param string $action Action to be checked
1806 * @return boolean True: action is allowed, False: action should not be allowed
1808 function isAllowed($action='') {
1809 if ( $action === '' )
1810 // In the spirit of DWIM
1813 return in_array( $action, $this->getRights() );
1817 * Check whether to enable recent changes patrol features for this user
1820 public function useRCPatrol() {
1821 global $wgUseRCPatrol;
1822 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
1826 * Check whether to enable recent changes patrol features for this user
1829 public function useNPPatrol() {
1830 global $wgUseRCPatrol, $wgUseNPPatrol;
1831 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
1835 * Load a skin if it doesn't exist or return it
1836 * @todo FIXME : need to check the old failback system [AV]
1838 function &getSkin() {
1840 if ( ! isset( $this->mSkin
) ) {
1841 wfProfileIn( __METHOD__
);
1844 $userSkin = $this->getOption( 'skin' );
1845 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1847 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1848 wfProfileOut( __METHOD__
);
1850 return $this->mSkin
;
1854 * @param string $title Article title to look at
1858 * Check watched status of an article
1859 * @return bool True if article is watched
1861 function isWatched( $title ) {
1862 $wl = WatchedItem
::fromUserTitle( $this, $title );
1863 return $wl->isWatched();
1869 function addWatch( $title ) {
1870 $wl = WatchedItem
::fromUserTitle( $this, $title );
1872 $this->invalidateCache();
1876 * Stop watching an article
1878 function removeWatch( $title ) {
1879 $wl = WatchedItem
::fromUserTitle( $this, $title );
1881 $this->invalidateCache();
1885 * Clear the user's notification timestamp for the given title.
1886 * If e-notif e-mails are on, they will receive notification mails on
1887 * the next change of the page if it's watched etc.
1889 function clearNotification( &$title ) {
1890 global $wgUser, $wgUseEnotif;
1892 # Do nothing if the database is locked to writes
1893 if( wfReadOnly() ) {
1897 if ($title->getNamespace() == NS_USER_TALK
&&
1898 $title->getText() == $this->getName() ) {
1899 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1901 $this->setNewtalk( false );
1904 if( !$wgUseEnotif ) {
1908 if( $this->isAnon() ) {
1909 // Nothing else to do...
1913 // Only update the timestamp if the page is being watched.
1914 // The query to find out if it is watched is cached both in memcached and per-invocation,
1915 // and when it does have to be executed, it can be on a slave
1916 // If this is the user's newtalk page, we always update the timestamp
1917 if ($title->getNamespace() == NS_USER_TALK
&&
1918 $title->getText() == $wgUser->getName())
1921 } elseif ( $this->getID() == $wgUser->getID() ) {
1922 $watched = $title->userIsWatching();
1927 // If the page is watched by the user (or may be watched), update the timestamp on any
1928 // any matching rows
1930 $dbw = wfGetDB( DB_MASTER
);
1931 $dbw->update( 'watchlist',
1933 'wl_notificationtimestamp' => NULL
1934 ), array( /* WHERE */
1935 'wl_title' => $title->getDBkey(),
1936 'wl_namespace' => $title->getNamespace(),
1937 'wl_user' => $this->getID()
1938 ), 'User::clearLastVisited'
1946 * Resets all of the given user's page-change notification timestamps.
1947 * If e-notif e-mails are on, they will receive notification mails on
1948 * the next change of any watched page.
1950 * @param int $currentUser user ID number
1953 function clearAllNotifications( $currentUser ) {
1954 global $wgUseEnotif;
1955 if ( !$wgUseEnotif ) {
1956 $this->setNewtalk( false );
1959 if( $currentUser != 0 ) {
1961 $dbw = wfGetDB( DB_MASTER
);
1962 $dbw->update( 'watchlist',
1964 'wl_notificationtimestamp' => NULL
1965 ), array( /* WHERE */
1966 'wl_user' => $currentUser
1970 # we also need to clear here the "you have new message" notification for the own user_talk page
1971 # This is cleared one page view later in Article::viewUpdates();
1977 * @return string Encoding options
1979 function encodeOptions() {
1981 if ( is_null( $this->mOptions
) ) {
1982 $this->mOptions
= User
::getDefaultOptions();
1985 foreach ( $this->mOptions
as $oname => $oval ) {
1986 array_push( $a, $oname.'='.$oval );
1988 $s = implode( "\n", $a );
1995 function decodeOptions( $str ) {
1996 $this->mOptions
= array();
1997 $a = explode( "\n", $str );
1998 foreach ( $a as $s ) {
2000 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2001 $this->mOptions
[$m[1]] = $m[2];
2006 protected function setCookie( $name, $value, $exp=0 ) {
2007 global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly;
2009 $exp = time() +
$wgCookieExpiration;
2011 $httpOnlySafe = version_compare("5.2", PHP_VERSION
, "<");
2013 if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) {
2014 setcookie( $wgCookiePrefix . $name,
2020 $wgCookieHttpOnly );
2022 // setcookie() fails on PHP 5.1 if you give it future-compat paramters.
2024 setcookie( $wgCookiePrefix . $name,
2033 protected function clearCookie( $name ) {
2034 $this->setCookie( $name, '', time() - 86400 );
2037 function setCookies() {
2039 if ( 0 == $this->mId
) return;
2041 $_SESSION['wsUserID'] = $this->mId
;
2043 $this->setCookie( 'UserID', $this->mId
);
2044 $this->setCookie( 'UserName', $this->getName() );
2046 $_SESSION['wsUserName'] = $this->getName();
2048 $_SESSION['wsToken'] = $this->mToken
;
2049 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2050 $this->setCookie( 'Token', $this->mToken
);
2052 $this->clearCookie( 'Token' );
2061 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2067 * Really logout user
2068 * Clears the cookies and session, resets the instance cache
2070 function doLogout() {
2071 $this->clearInstanceCache( 'defaults' );
2073 $_SESSION['wsUserID'] = 0;
2075 $this->clearCookie( 'UserID' );
2076 $this->clearCookie( 'Token' );
2078 # Remember when user logged out, to prevent seeing cached pages
2079 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2083 * Save object settings into database
2084 * @todo Only rarely do all these fields need to be set!
2086 function saveSettings() {
2088 if ( wfReadOnly() ) { return; }
2089 if ( 0 == $this->mId
) { return; }
2091 $this->mTouched
= self
::newTouchedTimestamp();
2093 $dbw = wfGetDB( DB_MASTER
);
2094 $dbw->update( 'user',
2096 'user_name' => $this->mName
,
2097 'user_password' => $this->mPassword
,
2098 'user_newpassword' => $this->mNewpassword
,
2099 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2100 'user_real_name' => $this->mRealName
,
2101 'user_email' => $this->mEmail
,
2102 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2103 'user_options' => $this->encodeOptions(),
2104 'user_touched' => $dbw->timestamp($this->mTouched
),
2105 'user_token' => $this->mToken
,
2106 'user_email_token' => $this->mEmailToken
,
2107 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2108 ), array( /* WHERE */
2109 'user_id' => $this->mId
2112 wfRunHooks( 'UserSaveSettings', array( $this ) );
2113 $this->clearSharedCache();
2117 * Checks if a user with the given name exists, returns the ID.
2119 function idForName() {
2120 $s = trim( $this->getName() );
2121 if ( $s === '' ) return 0;
2123 $dbr = wfGetDB( DB_SLAVE
);
2124 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2125 if ( $id === false ) {
2132 * Add a user to the database, return the user object
2134 * @param string $name The user's name
2135 * @param array $params Associative array of non-default parameters to save to the database:
2136 * password The user's password. Password logins will be disabled if this is omitted.
2137 * newpassword A temporary password mailed to the user
2138 * email The user's email address
2139 * email_authenticated The email authentication timestamp
2140 * real_name The user's real name
2141 * options An associative array of non-default options
2142 * token Random authentication token. Do not set.
2143 * registration Registration timestamp. Do not set.
2145 * @return User object, or null if the username already exists
2147 static function createNew( $name, $params = array() ) {
2150 if ( isset( $params['options'] ) ) {
2151 $user->mOptions
= $params['options'] +
$user->mOptions
;
2152 unset( $params['options'] );
2154 $dbw = wfGetDB( DB_MASTER
);
2155 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2157 'user_id' => $seqVal,
2158 'user_name' => $name,
2159 'user_password' => $user->mPassword
,
2160 'user_newpassword' => $user->mNewpassword
,
2161 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2162 'user_email' => $user->mEmail
,
2163 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2164 'user_real_name' => $user->mRealName
,
2165 'user_options' => $user->encodeOptions(),
2166 'user_token' => $user->mToken
,
2167 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2168 'user_editcount' => 0,
2170 foreach ( $params as $name => $value ) {
2171 $fields["user_$name"] = $value;
2173 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2174 if ( $dbw->affectedRows() ) {
2175 $newUser = User
::newFromId( $dbw->insertId() );
2183 * Add an existing user object to the database
2185 function addToDatabase() {
2187 $dbw = wfGetDB( DB_MASTER
);
2188 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2189 $dbw->insert( 'user',
2191 'user_id' => $seqVal,
2192 'user_name' => $this->mName
,
2193 'user_password' => $this->mPassword
,
2194 'user_newpassword' => $this->mNewpassword
,
2195 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2196 'user_email' => $this->mEmail
,
2197 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2198 'user_real_name' => $this->mRealName
,
2199 'user_options' => $this->encodeOptions(),
2200 'user_token' => $this->mToken
,
2201 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2202 'user_editcount' => 0,
2205 $this->mId
= $dbw->insertId();
2207 # Clear instance cache other than user table data, which is already accurate
2208 $this->clearInstanceCache();
2212 * If the (non-anonymous) user is blocked, this function will block any IP address
2213 * that they successfully log on from.
2215 function spreadBlock() {
2216 wfDebug( __METHOD__
."()\n" );
2218 if ( $this->mId
== 0 ) {
2222 $userblock = Block
::newFromDB( '', $this->mId
);
2223 if ( !$userblock ) {
2227 $userblock->doAutoblock( wfGetIp() );
2232 * Generate a string which will be different for any combination of
2233 * user options which would produce different parser output.
2234 * This will be used as part of the hash key for the parser cache,
2235 * so users will the same options can share the same cached data
2238 * Extensions which require it should install 'PageRenderingHash' hook,
2239 * which will give them a chance to modify this key based on their own
2244 function getPageRenderingHash() {
2245 global $wgContLang, $wgUseDynamicDates, $wgLang;
2247 return $this->mHash
;
2250 // stubthreshold is only included below for completeness,
2251 // it will always be 0 when this function is called by parsercache.
2253 $confstr = $this->getOption( 'math' );
2254 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2255 if ( $wgUseDynamicDates ) {
2256 $confstr .= '!' . $this->getDatePreference();
2258 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2259 $confstr .= '!' . $wgLang->getCode();
2260 $confstr .= '!' . $this->getOption( 'thumbsize' );
2261 // add in language specific options, if any
2262 $extra = $wgContLang->getExtraHashOptions();
2265 // Give a chance for extensions to modify the hash, if they have
2266 // extra options or other effects on the parser cache.
2267 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2269 // Make it a valid memcached key fragment
2270 $confstr = str_replace( ' ', '_', $confstr );
2271 $this->mHash
= $confstr;
2275 function isBlockedFromCreateAccount() {
2276 $this->getBlockedStatus();
2277 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2281 * Determine if the user is blocked from using Special:Emailuser.
2286 function isBlockedFromEmailuser() {
2287 $this->getBlockedStatus();
2288 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2291 function isAllowedToCreateAccount() {
2292 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2298 function setLoaded( $loaded ) {
2299 wfDeprecated( __METHOD__
);
2303 * Get this user's personal page title.
2308 function getUserPage() {
2309 return Title
::makeTitle( NS_USER
, $this->getName() );
2313 * Get this user's talk page title.
2318 function getTalkPage() {
2319 $title = $this->getUserPage();
2320 return $title->getTalkPage();
2326 function getMaxID() {
2327 static $res; // cache
2329 if ( isset( $res ) )
2332 $dbr = wfGetDB( DB_SLAVE
);
2333 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2338 * Determine whether the user is a newbie. Newbies are either
2339 * anonymous IPs, or the most recently created accounts.
2340 * @return bool True if it is a newbie.
2342 function isNewbie() {
2343 return !$this->isAllowed( 'autoconfirmed' );
2347 * Check to see if the given clear-text password is one of the accepted passwords
2348 * @param string $password User password.
2349 * @return bool True if the given password is correct otherwise False.
2351 function checkPassword( $password ) {
2355 // Even though we stop people from creating passwords that
2356 // are shorter than this, doesn't mean people wont be able
2357 // to. Certain authentication plugins do NOT want to save
2358 // domain passwords in a mysql database, so we should
2359 // check this (incase $wgAuth->strict() is false).
2360 if( !$this->isValidPassword( $password ) ) {
2364 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2366 } elseif( $wgAuth->strict() ) {
2367 /* Auth plugin doesn't allow local authentication */
2369 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2370 /* Auth plugin doesn't allow local authentication for this user name */
2373 $ep = $this->encryptPassword( $password );
2374 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2376 } elseif ( function_exists( 'iconv' ) ) {
2377 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2378 # Check for this with iconv
2379 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2380 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2388 * Check if the given clear-text password matches the temporary password
2389 * sent by e-mail for password reset operations.
2392 function checkTemporaryPassword( $plaintext ) {
2393 $hash = $this->encryptPassword( $plaintext );
2394 return $hash === $this->mNewpassword
;
2398 * Initialize (if necessary) and return a session token value
2399 * which can be used in edit forms to show that the user's
2400 * login credentials aren't being hijacked with a foreign form
2403 * @param mixed $salt - Optional function-specific data for hash.
2404 * Use a string or an array of strings.
2408 function editToken( $salt = '' ) {
2409 if ( $this->isAnon() ) {
2410 return EDIT_TOKEN_SUFFIX
;
2412 if( !isset( $_SESSION['wsEditToken'] ) ) {
2413 $token = $this->generateToken();
2414 $_SESSION['wsEditToken'] = $token;
2416 $token = $_SESSION['wsEditToken'];
2418 if( is_array( $salt ) ) {
2419 $salt = implode( '|', $salt );
2421 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2426 * Generate a hex-y looking random token for various uses.
2427 * Could be made more cryptographically sure if someone cares.
2430 function generateToken( $salt = '' ) {
2431 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2432 return md5( $token . $salt );
2436 * Check given value against the token value stored in the session.
2437 * A match should confirm that the form was submitted from the
2438 * user's own login session, not a form submission from a third-party
2441 * @param string $val - the input value to compare
2442 * @param string $salt - Optional function-specific data for hash
2446 function matchEditToken( $val, $salt = '' ) {
2447 $sessionToken = $this->editToken( $salt );
2448 if ( $val != $sessionToken ) {
2449 wfDebug( "User::matchEditToken: broken session data\n" );
2451 return $val == $sessionToken;
2455 * Check whether the edit token is fine except for the suffix
2457 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2458 $sessionToken = $this->editToken( $salt );
2459 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2463 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2464 * mail to the user's given address.
2466 * Calls saveSettings() internally; as it has side effects, not committing changes
2467 * would be pretty silly.
2469 * @return mixed True on success, a WikiError object on failure.
2471 function sendConfirmationMail() {
2473 $expiration = null; // gets passed-by-ref and defined in next line.
2474 $token = $this->confirmationToken( $expiration );
2475 $url = $this->confirmationTokenUrl( $token );
2476 $invalidateURL = $this->invalidationTokenUrl( $token );
2477 $this->saveSettings();
2479 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2480 wfMsg( 'confirmemail_body',
2484 $wgLang->timeanddate( $expiration, false ),
2489 * Send an e-mail to this user's account. Does not check for
2490 * confirmed status or validity.
2492 * @param string $subject
2493 * @param string $body
2494 * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
2495 * @return mixed True on success, a WikiError object on failure.
2497 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2498 if( is_null( $from ) ) {
2499 global $wgPasswordSender;
2500 $from = $wgPasswordSender;
2503 $to = new MailAddress( $this );
2504 $sender = new MailAddress( $from );
2505 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2509 * Generate, store, and return a new e-mail confirmation code.
2510 * A hash (unsalted since it's used as a key) is stored.
2512 * Call saveSettings() after calling this function to commit
2513 * this change to the database.
2515 * @param &$expiration mixed output: accepts the expiration time
2519 function confirmationToken( &$expiration ) {
2521 $expires = $now +
7 * 24 * 60 * 60;
2522 $expiration = wfTimestamp( TS_MW
, $expires );
2523 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2524 $hash = md5( $token );
2526 $this->mEmailToken
= $hash;
2527 $this->mEmailTokenExpires
= $expiration;
2532 * Return a URL the user can use to confirm their email address.
2533 * @param $token: accepts the email confirmation token
2537 function confirmationTokenUrl( $token ) {
2538 $title = SpecialPage
::getTitleFor( 'Confirmemail', $token );
2539 return $title->getFullUrl();
2542 * Return a URL the user can use to invalidate their email address.
2543 * @param $token: accepts the email confirmation token
2547 function invalidationTokenUrl( $token ) {
2548 $title = SpecialPage
::getTitleFor( 'Invalidateemail', $token );
2549 return $title->getFullUrl();
2553 * Mark the e-mail address confirmed.
2555 * Call saveSettings() after calling this function to commit the change.
2557 function confirmEmail() {
2558 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2563 * Invalidate the user's email confirmation, unauthenticate the email
2564 * if it was already confirmed.
2566 * Call saveSettings() after calling this function to commit the change.
2568 function invalidateEmail() {
2570 $this->mEmailToken
= null;
2571 $this->mEmailTokenExpires
= null;
2572 $this->setEmailAuthenticationTimestamp( null );
2576 function setEmailAuthenticationTimestamp( $timestamp ) {
2578 $this->mEmailAuthenticated
= $timestamp;
2579 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2583 * Is this user allowed to send e-mails within limits of current
2584 * site configuration?
2587 function canSendEmail() {
2588 $canSend = $this->isEmailConfirmed();
2589 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2594 * Is this user allowed to receive e-mails within limits of current
2595 * site configuration?
2598 function canReceiveEmail() {
2599 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2603 * Is this user's e-mail address valid-looking and confirmed within
2604 * limits of the current site configuration?
2606 * If $wgEmailAuthentication is on, this may require the user to have
2607 * confirmed their address by returning a code or using a password
2608 * sent to the address from the wiki.
2612 function isEmailConfirmed() {
2613 global $wgEmailAuthentication;
2616 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2617 if( $this->isAnon() )
2619 if( !self
::isValidEmailAddr( $this->mEmail
) )
2621 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2630 * Return true if there is an outstanding request for e-mail confirmation.
2633 function isEmailConfirmationPending() {
2634 global $wgEmailAuthentication;
2635 return $wgEmailAuthentication &&
2636 !$this->isEmailConfirmed() &&
2637 $this->mEmailToken
&&
2638 $this->mEmailTokenExpires
> wfTimestamp();
2642 * Get the timestamp of account creation, or false for
2643 * non-existent/anonymous user accounts
2647 public function getRegistration() {
2648 return $this->mId
> 0
2649 ?
$this->mRegistration
2654 * @param array $groups list of groups
2655 * @return array list of permission key names for given groups combined
2658 static function getGroupPermissions( $groups ) {
2659 global $wgGroupPermissions;
2661 foreach( $groups as $group ) {
2662 if( isset( $wgGroupPermissions[$group] ) ) {
2663 $rights = array_merge( $rights,
2664 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2671 * @param string $group key name
2672 * @return string localized descriptive name for group, if provided
2675 static function getGroupName( $group ) {
2676 global $wgMessageCache;
2677 $wgMessageCache->loadAllMessages();
2678 $key = "group-$group";
2679 $name = wfMsg( $key );
2680 return $name == '' ||
wfEmptyMsg( $key, $name )
2686 * @param string $group key name
2687 * @return string localized descriptive name for member of a group, if provided
2690 static function getGroupMember( $group ) {
2691 global $wgMessageCache;
2692 $wgMessageCache->loadAllMessages();
2693 $key = "group-$group-member";
2694 $name = wfMsg( $key );
2695 return $name == '' ||
wfEmptyMsg( $key, $name )
2701 * Return the set of defined explicit groups.
2702 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2703 * groups are not included, as they are defined
2704 * automatically, not in the database.
2708 static function getAllGroups() {
2709 global $wgGroupPermissions;
2711 array_keys( $wgGroupPermissions ),
2712 self
::getImplicitGroups()
2717 * Get a list of implicit groups
2721 public static function getImplicitGroups() {
2722 global $wgImplicitGroups;
2723 $groups = $wgImplicitGroups;
2724 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
2729 * Get the title of a page describing a particular group
2731 * @param $group Name of the group
2734 static function getGroupPage( $group ) {
2735 global $wgMessageCache;
2736 $wgMessageCache->loadAllMessages();
2737 $page = wfMsgForContent( 'grouppage-' . $group );
2738 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2739 $title = Title
::newFromText( $page );
2740 if( is_object( $title ) )
2747 * Create a link to the group in HTML, if available
2749 * @param $group Name of the group
2750 * @param $text The text of the link
2753 static function makeGroupLinkHTML( $group, $text = '' ) {
2755 $text = self
::getGroupName( $group );
2757 $title = self
::getGroupPage( $group );
2760 $sk = $wgUser->getSkin();
2761 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2768 * Create a link to the group in Wikitext, if available
2770 * @param $group Name of the group
2771 * @param $text The text of the link (by default, the name of the group)
2774 static function makeGroupLinkWiki( $group, $text = '' ) {
2776 $text = self
::getGroupName( $group );
2778 $title = self
::getGroupPage( $group );
2780 $page = $title->getPrefixedText();
2781 return "[[$page|$text]]";
2788 * Increment the user's edit-count field.
2789 * Will have no effect for anonymous users.
2791 function incEditCount() {
2792 if( !$this->isAnon() ) {
2793 $dbw = wfGetDB( DB_MASTER
);
2794 $dbw->update( 'user',
2795 array( 'user_editcount=user_editcount+1' ),
2796 array( 'user_id' => $this->getId() ),
2799 // Lazy initialization check...
2800 if( $dbw->affectedRows() == 0 ) {
2801 // Pull from a slave to be less cruel to servers
2802 // Accuracy isn't the point anyway here
2803 $dbr = wfGetDB( DB_SLAVE
);
2804 $count = $dbr->selectField( 'revision',
2806 array( 'rev_user' => $this->getId() ),
2809 // Now here's a goddamn hack...
2810 if( $dbr !== $dbw ) {
2811 // If we actually have a slave server, the count is
2812 // at least one behind because the current transaction
2813 // has not been committed and replicated.
2816 // But if DB_SLAVE is selecting the master, then the
2817 // count we just read includes the revision that was
2818 // just added in the working transaction.
2821 $dbw->update( 'user',
2822 array( 'user_editcount' => $count ),
2823 array( 'user_id' => $this->getId() ),
2827 // edit count in user cache too
2828 $this->invalidateCache();
2831 static function getRightDescription( $right ) {
2832 global $wgMessageCache;
2833 $wgMessageCache->loadAllMessages();
2834 $key = "right-$right";
2835 $name = wfMsg( $key );
2836 return $name == '' ||
wfEmptyMsg( $key, $name )