Update.
[mediawiki.git] / includes / User.php
blob0dacab26dd9f1f6da01b576cd07eaa8c9ef85b9a
1 <?php
2 /**
3 * See user.txt
5 * @package MediaWiki
6 */
8 # Number of characters in user_token field
9 define( 'USER_TOKEN_LENGTH', 32 );
11 # Serialized record version
12 define( 'MW_USER_VERSION', 4 );
14 # Some punctuation to prevent editing from broken text-mangling proxies.
15 # FIXME: this is embedded unescaped into HTML attributes in various
16 # places, so we can't safely include ' or " even though we really should.
17 define( 'EDIT_TOKEN_SUFFIX', '\\' );
19 /**
20 * Thrown by User::setPassword() on error
22 class PasswordError extends MWException {
23 // NOP
26 /**
28 * @package MediaWiki
30 class User {
32 /**
33 * A list of default user toggles, i.e. boolean user preferences that are
34 * displayed by Special:Preferences as checkboxes. This list can be
35 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
37 static public $mToggles = array(
38 'highlightbroken',
39 'justify',
40 'hideminor',
41 'extendwatchlist',
42 'usenewrc',
43 'numberheadings',
44 'showtoolbar',
45 'editondblclick',
46 'editsection',
47 'editsectiononrightclick',
48 'showtoc',
49 'rememberpassword',
50 'editwidth',
51 'watchcreations',
52 'watchdefault',
53 'watchdeletion',
54 'minordefault',
55 'previewontop',
56 'previewonfirst',
57 'nocache',
58 'enotifwatchlistpages',
59 'enotifusertalkpages',
60 'enotifminoredits',
61 'enotifrevealaddr',
62 'shownumberswatching',
63 'fancysig',
64 'externaleditor',
65 'externaldiff',
66 'showjumplinks',
67 'uselivepreview',
68 'forceeditsummary',
69 'watchlisthideown',
70 'watchlisthidebots',
71 'ccmeonemails',
74 /**
75 * List of member variables which are saved to the shared cache (memcached).
76 * Any operation which changes the corresponding database fields must
77 * call a cache-clearing function.
79 static $mCacheVars = array(
80 # user table
81 'mId',
82 'mName',
83 'mRealName',
84 'mPassword',
85 'mNewpassword',
86 'mNewpassTime',
87 'mEmail',
88 'mOptions',
89 'mTouched',
90 'mToken',
91 'mEmailAuthenticated',
92 'mEmailToken',
93 'mEmailTokenExpires',
94 'mRegistration',
96 # user_group table
97 'mGroups',
101 * The cache variable declarations
103 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
104 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
105 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
108 * Whether the cache variables have been loaded
110 var $mDataLoaded;
113 * Initialisation data source if mDataLoaded==false. May be one of:
114 * defaults anonymous user initialised from class defaults
115 * name initialise from mName
116 * id initialise from mId
117 * session log in from cookies or session if possible
119 * Use the User::newFrom*() family of functions to set this.
121 var $mFrom;
124 * Lazy-initialised variables, invalidated with clearInstanceCache
126 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
127 $mBlockreason, $mBlock, $mEffectiveGroups;
129 /**
130 * Lightweight constructor for anonymous user
131 * Use the User::newFrom* factory functions for other kinds of users
133 function User() {
134 $this->clearInstanceCache( 'defaults' );
138 * Load the user table data for this object from the source given by mFrom
140 function load() {
141 if ( $this->mDataLoaded ) {
142 return;
144 wfProfileIn( __METHOD__ );
146 # Set it now to avoid infinite recursion in accessors
147 $this->mDataLoaded = true;
149 switch ( $this->mFrom ) {
150 case 'defaults':
151 $this->loadDefaults();
152 break;
153 case 'name':
154 $this->mId = self::idFromName( $this->mName );
155 if ( !$this->mId ) {
156 # Nonexistent user placeholder object
157 $this->loadDefaults( $this->mName );
158 } else {
159 $this->loadFromId();
161 break;
162 case 'id':
163 $this->loadFromId();
164 break;
165 case 'session':
166 $this->loadFromSession();
167 break;
168 default:
169 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
171 wfProfileOut( __METHOD__ );
175 * Load user table data given mId
176 * @return false if the ID does not exist, true otherwise
177 * @private
179 function loadFromId() {
180 global $wgMemc;
181 if ( $this->mId == 0 ) {
182 $this->loadDefaults();
183 return false;
186 # Try cache
187 $key = wfMemcKey( 'user', 'id', $this->mId );
188 $data = $wgMemc->get( $key );
190 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
191 # Object is expired, load from DB
192 $data = false;
195 if ( !$data ) {
196 wfDebug( "Cache miss for user {$this->mId}\n" );
197 # Load from DB
198 if ( !$this->loadFromDatabase() ) {
199 # Can't load from ID, user is anonymous
200 return false;
203 # Save to cache
204 $data = array();
205 foreach ( self::$mCacheVars as $name ) {
206 $data[$name] = $this->$name;
208 $data['mVersion'] = MW_USER_VERSION;
209 $wgMemc->set( $key, $data );
210 } else {
211 wfDebug( "Got user {$this->mId} from cache\n" );
212 # Restore from cache
213 foreach ( self::$mCacheVars as $name ) {
214 $this->$name = $data[$name];
217 return true;
221 * Static factory method for creation from username.
223 * This is slightly less efficient than newFromId(), so use newFromId() if
224 * you have both an ID and a name handy.
226 * @param string $name Username, validated by Title:newFromText()
227 * @param mixed $validate Validate username. Takes the same parameters as
228 * User::getCanonicalName(), except that true is accepted as an alias
229 * for 'valid', for BC.
231 * @return User object, or null if the username is invalid. If the username
232 * is not present in the database, the result will be a user object with
233 * a name, zero user ID and default settings.
234 * @static
236 static function newFromName( $name, $validate = 'valid' ) {
237 if ( $validate === true ) {
238 $validate = 'valid';
240 $name = self::getCanonicalName( $name, $validate );
241 if ( $name === false ) {
242 return null;
243 } else {
244 # Create unloaded user object
245 $u = new User;
246 $u->mName = $name;
247 $u->mFrom = 'name';
248 return $u;
252 static function newFromId( $id ) {
253 $u = new User;
254 $u->mId = $id;
255 $u->mFrom = 'id';
256 return $u;
260 * Factory method to fetch whichever user has a given email confirmation code.
261 * This code is generated when an account is created or its e-mail address
262 * has changed.
264 * If the code is invalid or has expired, returns NULL.
266 * @param string $code
267 * @return User
268 * @static
270 static function newFromConfirmationCode( $code ) {
271 $dbr =& wfGetDB( DB_SLAVE );
272 $id = $dbr->selectField( 'user', 'user_id', array(
273 'user_email_token' => md5( $code ),
274 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
275 ) );
276 if( $id !== false ) {
277 return User::newFromId( $id );
278 } else {
279 return null;
284 * Create a new user object using data from session or cookies. If the
285 * login credentials are invalid, the result is an anonymous user.
287 * @return User
288 * @static
290 static function newFromSession() {
291 $user = new User;
292 $user->mFrom = 'session';
293 return $user;
297 * Get username given an id.
298 * @param integer $id Database user id
299 * @return string Nickname of a user
300 * @static
302 static function whoIs( $id ) {
303 $dbr =& wfGetDB( DB_SLAVE );
304 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
308 * Get real username given an id.
309 * @param integer $id Database user id
310 * @return string Realname of a user
311 * @static
313 static function whoIsReal( $id ) {
314 $dbr =& wfGetDB( DB_SLAVE );
315 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), 'User::whoIsReal' );
319 * Get database id given a user name
320 * @param string $name Nickname of a user
321 * @return integer|null Database user id (null: if non existent
322 * @static
324 static function idFromName( $name ) {
325 $nt = Title::newFromText( $name );
326 if( is_null( $nt ) ) {
327 # Illegal name
328 return null;
330 $dbr =& wfGetDB( DB_SLAVE );
331 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
333 if ( $s === false ) {
334 return 0;
335 } else {
336 return $s->user_id;
341 * Does the string match an anonymous IPv4 address?
343 * This function exists for username validation, in order to reject
344 * usernames which are similar in form to IP addresses. Strings such
345 * as 300.300.300.300 will return true because it looks like an IP
346 * address, despite not being strictly valid.
348 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
349 * address because the usemod software would "cloak" anonymous IP
350 * addresses like this, if we allowed accounts like this to be created
351 * new users could get the old edits of these anonymous users.
353 * @bug 3631
355 * @static
356 * @param string $name Nickname of a user
357 * @return bool
359 static function isIP( $name ) {
360 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name);
361 /*return preg_match("/^
362 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
363 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
364 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
365 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
366 $/x", $name);*/
370 * Is the input a valid username?
372 * Checks if the input is a valid username, we don't want an empty string,
373 * an IP address, anything that containins slashes (would mess up subpages),
374 * is longer than the maximum allowed username size or doesn't begin with
375 * a capital letter.
377 * @param string $name
378 * @return bool
379 * @static
381 static function isValidUserName( $name ) {
382 global $wgContLang, $wgMaxNameChars;
384 if ( $name == ''
385 || User::isIP( $name )
386 || strpos( $name, '/' ) !== false
387 || strlen( $name ) > $wgMaxNameChars
388 || $name != $wgContLang->ucfirst( $name ) )
389 return false;
391 // Ensure that the name can't be misresolved as a different title,
392 // such as with extra namespace keys at the start.
393 $parsed = Title::newFromText( $name );
394 if( is_null( $parsed )
395 || $parsed->getNamespace()
396 || strcmp( $name, $parsed->getPrefixedText() ) )
397 return false;
399 // Check an additional blacklist of troublemaker characters.
400 // Should these be merged into the title char list?
401 $unicodeBlacklist = '/[' .
402 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
403 '\x{00a0}' . # non-breaking space
404 '\x{2000}-\x{200f}' . # various whitespace
405 '\x{2028}-\x{202f}' . # breaks and control chars
406 '\x{3000}' . # ideographic space
407 '\x{e000}-\x{f8ff}' . # private use
408 ']/u';
409 if( preg_match( $unicodeBlacklist, $name ) ) {
410 return false;
413 return true;
417 * Usernames which fail to pass this function will be blocked
418 * from user login and new account registrations, but may be used
419 * internally by batch processes.
421 * If an account already exists in this form, login will be blocked
422 * by a failure to pass this function.
424 * @param string $name
425 * @return bool
427 static function isUsableName( $name ) {
428 global $wgReservedUsernames;
429 return
430 // Must be a usable username, obviously ;)
431 self::isValidUserName( $name ) &&
433 // Certain names may be reserved for batch processes.
434 !in_array( $name, $wgReservedUsernames );
438 * Usernames which fail to pass this function will be blocked
439 * from new account registrations, but may be used internally
440 * either by batch processes or by user accounts which have
441 * already been created.
443 * Additional character blacklisting may be added here
444 * rather than in isValidUserName() to avoid disrupting
445 * existing accounts.
447 * @param string $name
448 * @return bool
450 static function isCreatableName( $name ) {
451 return
452 self::isUsableName( $name ) &&
454 // Registration-time character blacklisting...
455 strpos( $name, '@' ) === false;
459 * Is the input a valid password?
461 * @param string $password
462 * @return bool
463 * @static
465 static function isValidPassword( $password ) {
466 global $wgMinimalPasswordLength;
467 return strlen( $password ) >= $wgMinimalPasswordLength;
471 * Does the string match roughly an email address ?
473 * There used to be a regular expression here, it got removed because it
474 * rejected valid addresses. Actually just check if there is '@' somewhere
475 * in the given address.
477 * @todo Check for RFC 2822 compilance
478 * @bug 959
480 * @param string $addr email address
481 * @static
482 * @return bool
484 static function isValidEmailAddr ( $addr ) {
485 return ( trim( $addr ) != '' ) &&
486 (false !== strpos( $addr, '@' ) );
490 * Given unvalidated user input, return a canonical username, or false if
491 * the username is invalid.
492 * @param string $name
493 * @param mixed $validate Type of validation to use:
494 * false No validation
495 * 'valid' Valid for batch processes
496 * 'usable' Valid for batch processes and login
497 * 'creatable' Valid for batch processes, login and account creation
499 static function getCanonicalName( $name, $validate = 'valid' ) {
500 # Force usernames to capital
501 global $wgContLang;
502 $name = $wgContLang->ucfirst( $name );
504 # Clean up name according to title rules
505 $t = Title::newFromText( $name );
506 if( is_null( $t ) ) {
507 return false;
510 # Reject various classes of invalid names
511 $name = $t->getText();
512 global $wgAuth;
513 $name = $wgAuth->getCanonicalName( $t->getText() );
515 switch ( $validate ) {
516 case false:
517 break;
518 case 'valid':
519 if ( !User::isValidUserName( $name ) ) {
520 $name = false;
522 break;
523 case 'usable':
524 if ( !User::isUsableName( $name ) ) {
525 $name = false;
527 break;
528 case 'creatable':
529 if ( !User::isCreatableName( $name ) ) {
530 $name = false;
532 break;
533 default:
534 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__ );
536 return $name;
540 * Count the number of edits of a user
542 * @param int $uid The user ID to check
543 * @return int
544 * @static
546 static function edits( $uid ) {
547 $dbr =& wfGetDB( DB_SLAVE );
548 return $dbr->selectField(
549 'revision', 'count(*)',
550 array( 'rev_user' => $uid ),
551 __METHOD__
556 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
557 * @todo: hash random numbers to improve security, like generateToken()
559 * @return string
560 * @static
562 static function randomPassword() {
563 global $wgMinimalPasswordLength;
564 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
565 $l = strlen( $pwchars ) - 1;
567 $pwlength = max( 7, $wgMinimalPasswordLength );
568 $digit = mt_rand(0, $pwlength - 1);
569 $np = '';
570 for ( $i = 0; $i < $pwlength; $i++ ) {
571 $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
573 return $np;
577 * Set cached properties to default. Note: this no longer clears
578 * uncached lazy-initialised properties. The constructor does that instead.
580 * @private
582 function loadDefaults( $name = false ) {
583 wfProfileIn( __METHOD__ );
585 global $wgCookiePrefix;
587 $this->mId = 0;
588 $this->mName = $name;
589 $this->mRealName = '';
590 $this->mPassword = $this->mNewpassword = '';
591 $this->mNewpassTime = null;
592 $this->mEmail = '';
593 $this->mOptions = null; # Defer init
595 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
596 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
597 } else {
598 $this->mTouched = '0'; # Allow any pages to be cached
601 $this->setToken(); # Random
602 $this->mEmailAuthenticated = null;
603 $this->mEmailToken = '';
604 $this->mEmailTokenExpires = null;
605 $this->mRegistration = wfTimestamp( TS_MW );
606 $this->mGroups = array();
608 wfProfileOut( __METHOD__ );
612 * Initialise php session
613 * @deprecated use wfSetupSession()
615 function SetupSession() {
616 wfSetupSession();
620 * Load user data from the session or login cookie. If there are no valid
621 * credentials, initialises the user as an anon.
622 * @return true if the user is logged in, false otherwise
624 * @private
626 function loadFromSession() {
627 global $wgMemc, $wgCookiePrefix;
629 if ( isset( $_SESSION['wsUserID'] ) ) {
630 if ( 0 != $_SESSION['wsUserID'] ) {
631 $sId = $_SESSION['wsUserID'];
632 } else {
633 $this->loadDefaults();
634 return false;
636 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
637 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
638 $_SESSION['wsUserID'] = $sId;
639 } else {
640 $this->loadDefaults();
641 return false;
643 if ( isset( $_SESSION['wsUserName'] ) ) {
644 $sName = $_SESSION['wsUserName'];
645 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
646 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
647 $_SESSION['wsUserName'] = $sName;
648 } else {
649 $this->loadDefaults();
650 return false;
653 $passwordCorrect = FALSE;
654 $this->mId = $sId;
655 if ( !$this->loadFromId() ) {
656 # Not a valid ID, loadFromId has switched the object to anon for us
657 return false;
660 if ( isset( $_SESSION['wsToken'] ) ) {
661 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
662 $from = 'session';
663 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
664 $passwordCorrect = $this->mToken == $_COOKIE["{$wgCookiePrefix}Token"];
665 $from = 'cookie';
666 } else {
667 # No session or persistent login cookie
668 $this->loadDefaults();
669 return false;
672 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
673 wfDebug( "Logged in from $from\n" );
674 return true;
675 } else {
676 # Invalid credentials
677 wfDebug( "Can't log in from $from, invalid credentials\n" );
678 $this->loadDefaults();
679 return false;
684 * Load user and user_group data from the database
685 * $this->mId must be set, this is how the user is identified.
687 * @return true if the user exists, false if the user is anonymous
688 * @private
690 function loadFromDatabase() {
691 # Paranoia
692 $this->mId = intval( $this->mId );
694 /** Anonymous user */
695 if( !$this->mId ) {
696 $this->loadDefaults();
697 return false;
700 $dbr =& wfGetDB( DB_SLAVE );
701 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
703 if ( $s !== false ) {
704 # Initialise user table data
705 $this->mName = $s->user_name;
706 $this->mRealName = $s->user_real_name;
707 $this->mPassword = $s->user_password;
708 $this->mNewpassword = $s->user_newpassword;
709 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $s->user_newpass_time );
710 $this->mEmail = $s->user_email;
711 $this->decodeOptions( $s->user_options );
712 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
713 $this->mToken = $s->user_token;
714 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
715 $this->mEmailToken = $s->user_email_token;
716 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $s->user_email_token_expires );
717 $this->mRegistration = wfTimestampOrNull( TS_MW, $s->user_registration );
719 # Load group data
720 $res = $dbr->select( 'user_groups',
721 array( 'ug_group' ),
722 array( 'ug_user' => $this->mId ),
723 __METHOD__ );
724 $this->mGroups = array();
725 while( $row = $dbr->fetchObject( $res ) ) {
726 $this->mGroups[] = $row->ug_group;
728 return true;
729 } else {
730 # Invalid user_id
731 $this->mId = 0;
732 $this->loadDefaults();
733 return false;
738 * Clear various cached data stored in this object.
739 * @param string $reloadFrom Reload user and user_groups table data from a
740 * given source. May be "name", "id", "defaults", "session" or false for
741 * no reload.
743 function clearInstanceCache( $reloadFrom = false ) {
744 $this->mNewtalk = -1;
745 $this->mDatePreference = null;
746 $this->mBlockedby = -1; # Unset
747 $this->mHash = false;
748 $this->mSkin = null;
749 $this->mRights = null;
750 $this->mEffectiveGroups = null;
752 if ( $reloadFrom ) {
753 $this->mDataLoaded = false;
754 $this->mFrom = $reloadFrom;
759 * Combine the language default options with any site-specific options
760 * and add the default language variants.
762 * @return array
763 * @static
764 * @private
766 function getDefaultOptions() {
767 global $wgNamespacesToBeSearchedDefault;
769 * Site defaults will override the global/language defaults
771 global $wgDefaultUserOptions, $wgContLang;
772 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
775 * default language setting
777 $variant = $wgContLang->getPreferredVariant( false );
778 $defOpt['variant'] = $variant;
779 $defOpt['language'] = $variant;
781 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
782 $defOpt['searchNs'.$nsnum] = $val;
784 return $defOpt;
788 * Get a given default option value.
790 * @param string $opt
791 * @return string
792 * @static
793 * @public
795 function getDefaultOption( $opt ) {
796 $defOpts = User::getDefaultOptions();
797 if( isset( $defOpts[$opt] ) ) {
798 return $defOpts[$opt];
799 } else {
800 return '';
805 * Get a list of user toggle names
806 * @return array
808 static function getToggles() {
809 global $wgContLang;
810 $extraToggles = array();
811 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
812 return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
817 * Get blocking information
818 * @private
819 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
820 * non-critical checks are done against slaves. Check when actually saving should be done against
821 * master.
823 function getBlockedStatus( $bFromSlave = true ) {
824 global $wgEnableSorbs, $wgProxyWhitelist;
826 if ( -1 != $this->mBlockedby ) {
827 wfDebug( "User::getBlockedStatus: already loaded.\n" );
828 return;
831 wfProfileIn( __METHOD__ );
832 wfDebug( __METHOD__.": checking...\n" );
834 $this->mBlockedby = 0;
835 $ip = wfGetIP();
837 # User/IP blocking
838 $this->mBlock = new Block();
839 $this->mBlock->fromMaster( !$bFromSlave );
840 if ( $this->mBlock->load( $ip , $this->mId ) ) {
841 wfDebug( __METHOD__.": Found block.\n" );
842 $this->mBlockedby = $this->mBlock->mBy;
843 $this->mBlockreason = $this->mBlock->mReason;
844 if ( $this->isLoggedIn() ) {
845 $this->spreadBlock();
847 } else {
848 $this->mBlock = null;
849 wfDebug( __METHOD__.": No block.\n" );
852 # Proxy blocking
853 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
855 # Local list
856 if ( wfIsLocallyBlockedProxy( $ip ) ) {
857 $this->mBlockedby = wfMsg( 'proxyblocker' );
858 $this->mBlockreason = wfMsg( 'proxyblockreason' );
861 # DNSBL
862 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
863 if ( $this->inSorbsBlacklist( $ip ) ) {
864 $this->mBlockedby = wfMsg( 'sorbs' );
865 $this->mBlockreason = wfMsg( 'sorbsreason' );
870 # Extensions
871 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
873 wfProfileOut( __METHOD__ );
876 function inSorbsBlacklist( $ip ) {
877 global $wgEnableSorbs, $wgSorbsUrl;
879 return $wgEnableSorbs &&
880 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
883 function inDnsBlacklist( $ip, $base ) {
884 wfProfileIn( __METHOD__ );
886 $found = false;
887 $host = '';
889 $m = array();
890 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
891 # Make hostname
892 for ( $i=4; $i>=1; $i-- ) {
893 $host .= $m[$i] . '.';
895 $host .= $base;
897 # Send query
898 $ipList = gethostbynamel( $host );
900 if ( $ipList ) {
901 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
902 $found = true;
903 } else {
904 wfDebug( "Requested $host, not found in $base.\n" );
908 wfProfileOut( __METHOD__ );
909 return $found;
913 * Primitive rate limits: enforce maximum actions per time period
914 * to put a brake on flooding.
916 * Note: when using a shared cache like memcached, IP-address
917 * last-hit counters will be shared across wikis.
919 * @return bool true if a rate limiter was tripped
920 * @public
922 function pingLimiter( $action='edit' ) {
923 global $wgRateLimits, $wgRateLimitsExcludedGroups;
924 if( !isset( $wgRateLimits[$action] ) ) {
925 return false;
928 # Some groups shouldn't trigger the ping limiter, ever
929 foreach( $this->getGroups() as $group ) {
930 if( array_search( $group, $wgRateLimitsExcludedGroups ) !== false )
931 return false;
934 global $wgMemc, $wgRateLimitLog;
935 wfProfileIn( __METHOD__ );
937 $limits = $wgRateLimits[$action];
938 $keys = array();
939 $id = $this->getId();
940 $ip = wfGetIP();
942 if( isset( $limits['anon'] ) && $id == 0 ) {
943 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
946 if( isset( $limits['user'] ) && $id != 0 ) {
947 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
949 if( $this->isNewbie() ) {
950 if( isset( $limits['newbie'] ) && $id != 0 ) {
951 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
953 if( isset( $limits['ip'] ) ) {
954 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
956 $matches = array();
957 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
958 $subnet = $matches[1];
959 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
963 $triggered = false;
964 foreach( $keys as $key => $limit ) {
965 list( $max, $period ) = $limit;
966 $summary = "(limit $max in {$period}s)";
967 $count = $wgMemc->get( $key );
968 if( $count ) {
969 if( $count > $max ) {
970 wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
971 if( $wgRateLimitLog ) {
972 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
974 $triggered = true;
975 } else {
976 wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
978 } else {
979 wfDebug( __METHOD__.": adding record for $key $summary\n" );
980 $wgMemc->add( $key, 1, intval( $period ) );
982 $wgMemc->incr( $key );
985 wfProfileOut( __METHOD__ );
986 return $triggered;
990 * Check if user is blocked
991 * @return bool True if blocked, false otherwise
993 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
994 wfDebug( "User::isBlocked: enter\n" );
995 $this->getBlockedStatus( $bFromSlave );
996 return $this->mBlockedby !== 0;
1000 * Check if user is blocked from editing a particular article
1002 function isBlockedFrom( $title, $bFromSlave = false ) {
1003 global $wgBlockAllowsUTEdit;
1004 wfProfileIn( __METHOD__ );
1005 wfDebug( __METHOD__.": enter\n" );
1007 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1008 $title->getNamespace() == NS_USER_TALK )
1010 $blocked = false;
1011 wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1012 } else {
1013 wfDebug( __METHOD__.": asking isBlocked()\n" );
1014 $blocked = $this->isBlocked( $bFromSlave );
1016 wfProfileOut( __METHOD__ );
1017 return $blocked;
1021 * Get name of blocker
1022 * @return string name of blocker
1024 function blockedBy() {
1025 $this->getBlockedStatus();
1026 return $this->mBlockedby;
1030 * Get blocking reason
1031 * @return string Blocking reason
1033 function blockedFor() {
1034 $this->getBlockedStatus();
1035 return $this->mBlockreason;
1039 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1041 function getID() {
1042 $this->load();
1043 return $this->mId;
1047 * Set the user and reload all fields according to that ID
1048 * @deprecated use User::newFromId()
1050 function setID( $v ) {
1051 $this->mId = $v;
1052 $this->clearInstanceCache( 'id' );
1056 * Get the user name, or the IP for anons
1058 function getName() {
1059 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1060 # Special case optimisation
1061 return $this->mName;
1062 } else {
1063 $this->load();
1064 if ( $this->mName === false ) {
1065 $this->mName = wfGetIP();
1067 return $this->mName;
1072 * Set the user name.
1074 * This does not reload fields from the database according to the given
1075 * name. Rather, it is used to create a temporary "nonexistent user" for
1076 * later addition to the database. It can also be used to set the IP
1077 * address for an anonymous user to something other than the current
1078 * remote IP.
1080 * User::newFromName() has rougly the same function, when the named user
1081 * does not exist.
1083 function setName( $str ) {
1084 $this->load();
1085 $this->mName = $str;
1089 * Return the title dbkey form of the name, for eg user pages.
1090 * @return string
1091 * @public
1093 function getTitleKey() {
1094 return str_replace( ' ', '_', $this->getName() );
1097 function getNewtalk() {
1098 $this->load();
1100 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1101 if( $this->mNewtalk === -1 ) {
1102 $this->mNewtalk = false; # reset talk page status
1104 # Check memcached separately for anons, who have no
1105 # entire User object stored in there.
1106 if( !$this->mId ) {
1107 global $wgMemc;
1108 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1109 $newtalk = $wgMemc->get( $key );
1110 if( is_integer( $newtalk ) ) {
1111 $this->mNewtalk = (bool)$newtalk;
1112 } else {
1113 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
1114 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
1116 } else {
1117 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1121 return (bool)$this->mNewtalk;
1125 * Return the talk page(s) this user has new messages on.
1127 function getNewMessageLinks() {
1128 $talks = array();
1129 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1130 return $talks;
1132 if (!$this->getNewtalk())
1133 return array();
1134 $up = $this->getUserPage();
1135 $utp = $up->getTalkPage();
1136 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1141 * Perform a user_newtalk check on current slaves; if the memcached data
1142 * is funky we don't want newtalk state to get stuck on save, as that's
1143 * damn annoying.
1145 * @param string $field
1146 * @param mixed $id
1147 * @return bool
1148 * @private
1150 function checkNewtalk( $field, $id ) {
1151 $dbr =& wfGetDB( DB_SLAVE );
1152 $ok = $dbr->selectField( 'user_newtalk', $field,
1153 array( $field => $id ), __METHOD__ );
1154 return $ok !== false;
1158 * Add or update the
1159 * @param string $field
1160 * @param mixed $id
1161 * @private
1163 function updateNewtalk( $field, $id ) {
1164 if( $this->checkNewtalk( $field, $id ) ) {
1165 wfDebug( __METHOD__." already set ($field, $id), ignoring\n" );
1166 return false;
1168 $dbw =& wfGetDB( DB_MASTER );
1169 $dbw->insert( 'user_newtalk',
1170 array( $field => $id ),
1171 __METHOD__,
1172 'IGNORE' );
1173 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1174 return true;
1178 * Clear the new messages flag for the given user
1179 * @param string $field
1180 * @param mixed $id
1181 * @private
1183 function deleteNewtalk( $field, $id ) {
1184 if( !$this->checkNewtalk( $field, $id ) ) {
1185 wfDebug( __METHOD__.": already gone ($field, $id), ignoring\n" );
1186 return false;
1188 $dbw =& wfGetDB( DB_MASTER );
1189 $dbw->delete( 'user_newtalk',
1190 array( $field => $id ),
1191 __METHOD__ );
1192 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1193 return true;
1197 * Update the 'You have new messages!' status.
1198 * @param bool $val
1200 function setNewtalk( $val ) {
1201 if( wfReadOnly() ) {
1202 return;
1205 $this->load();
1206 $this->mNewtalk = $val;
1208 if( $this->isAnon() ) {
1209 $field = 'user_ip';
1210 $id = $this->getName();
1211 } else {
1212 $field = 'user_id';
1213 $id = $this->getId();
1216 if( $val ) {
1217 $changed = $this->updateNewtalk( $field, $id );
1218 } else {
1219 $changed = $this->deleteNewtalk( $field, $id );
1222 if( $changed ) {
1223 if( $this->isAnon() ) {
1224 // Anons have a separate memcached space, since
1225 // user records aren't kept for them.
1226 global $wgMemc;
1227 $key = wfMemcKey( 'newtalk', 'ip', $val );
1228 $wgMemc->set( $key, $val ? 1 : 0 );
1229 } else {
1230 if( $val ) {
1231 // Make sure the user page is watched, so a notification
1232 // will be sent out if enabled.
1233 $this->addWatch( $this->getTalkPage() );
1236 $this->invalidateCache();
1241 * Generate a current or new-future timestamp to be stored in the
1242 * user_touched field when we update things.
1244 private static function newTouchedTimestamp() {
1245 global $wgClockSkewFudge;
1246 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1250 * Clear user data from memcached.
1251 * Use after applying fun updates to the database; caller's
1252 * responsibility to update user_touched if appropriate.
1254 * Called implicitly from invalidateCache() and saveSettings().
1256 private function clearSharedCache() {
1257 if( $this->mId ) {
1258 global $wgMemc;
1259 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1264 * Immediately touch the user data cache for this account.
1265 * Updates user_touched field, and removes account data from memcached
1266 * for reload on the next hit.
1268 function invalidateCache() {
1269 $this->load();
1270 if( $this->mId ) {
1271 $this->mTouched = self::newTouchedTimestamp();
1273 $dbw =& wfGetDB( DB_MASTER );
1274 $dbw->update( 'user',
1275 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1276 array( 'user_id' => $this->mId ),
1277 __METHOD__ );
1279 $this->clearSharedCache();
1283 function validateCache( $timestamp ) {
1284 $this->load();
1285 return ($timestamp >= $this->mTouched);
1289 * Encrypt a password.
1290 * It can eventuall salt a password @see User::addSalt()
1291 * @param string $p clear Password.
1292 * @return string Encrypted password.
1294 function encryptPassword( $p ) {
1295 $this->load();
1296 return wfEncryptPassword( $this->mId, $p );
1300 * Set the password and reset the random token
1301 * Calls through to authentication plugin if necessary;
1302 * will have no effect if the auth plugin refuses to
1303 * pass the change through or if the legal password
1304 * checks fail.
1306 * As a special case, setting the password to null
1307 * wipes it, so the account cannot be logged in until
1308 * a new password is set, for instance via e-mail.
1310 * @param string $str
1311 * @throws PasswordError on failure
1313 function setPassword( $str ) {
1314 global $wgAuth;
1316 if( $str !== null ) {
1317 if( !$wgAuth->allowPasswordChange() ) {
1318 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1321 if( !$this->isValidPassword( $str ) ) {
1322 global $wgMinimalPasswordLength;
1323 throw new PasswordError( wfMsg( 'passwordtooshort',
1324 $wgMinimalPasswordLength ) );
1328 if( !$wgAuth->setPassword( $this, $str ) ) {
1329 throw new PasswordError( wfMsg( 'externaldberror' ) );
1332 $this->load();
1333 $this->setToken();
1335 if( $str === null ) {
1336 // Save an invalid hash...
1337 $this->mPassword = '';
1338 } else {
1339 $this->mPassword = $this->encryptPassword( $str );
1341 $this->mNewpassword = '';
1342 $this->mNewpassTime = null;
1344 return true;
1348 * Set the random token (used for persistent authentication)
1349 * Called from loadDefaults() among other places.
1350 * @private
1352 function setToken( $token = false ) {
1353 global $wgSecretKey, $wgProxyKey;
1354 $this->load();
1355 if ( !$token ) {
1356 if ( $wgSecretKey ) {
1357 $key = $wgSecretKey;
1358 } elseif ( $wgProxyKey ) {
1359 $key = $wgProxyKey;
1360 } else {
1361 $key = microtime();
1363 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1364 } else {
1365 $this->mToken = $token;
1369 function setCookiePassword( $str ) {
1370 $this->load();
1371 $this->mCookiePassword = md5( $str );
1375 * Set the password for a password reminder or new account email
1376 * Sets the user_newpass_time field if $throttle is true
1378 function setNewpassword( $str, $throttle = true ) {
1379 $this->load();
1380 $this->mNewpassword = $this->encryptPassword( $str );
1381 if ( $throttle ) {
1382 $this->mNewpassTime = wfTimestampNow();
1387 * Returns true if a password reminder email has already been sent within
1388 * the last $wgPasswordReminderResendTime hours
1390 function isPasswordReminderThrottled() {
1391 global $wgPasswordReminderResendTime;
1392 $this->load();
1393 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1394 return false;
1396 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1397 return time() < $expiry;
1400 function getEmail() {
1401 $this->load();
1402 return $this->mEmail;
1405 function getEmailAuthenticationTimestamp() {
1406 $this->load();
1407 return $this->mEmailAuthenticated;
1410 function setEmail( $str ) {
1411 $this->load();
1412 $this->mEmail = $str;
1415 function getRealName() {
1416 $this->load();
1417 return $this->mRealName;
1420 function setRealName( $str ) {
1421 $this->load();
1422 $this->mRealName = $str;
1426 * @param string $oname The option to check
1427 * @param string $defaultOverride A default value returned if the option does not exist
1428 * @return string
1430 function getOption( $oname, $defaultOverride = '' ) {
1431 $this->load();
1433 if ( is_null( $this->mOptions ) ) {
1434 if($defaultOverride != '') {
1435 return $defaultOverride;
1437 $this->mOptions = User::getDefaultOptions();
1440 if ( array_key_exists( $oname, $this->mOptions ) ) {
1441 return trim( $this->mOptions[$oname] );
1442 } else {
1443 return $defaultOverride;
1448 * Get the user's date preference, including some important migration for
1449 * old user rows.
1451 function getDatePreference() {
1452 if ( is_null( $this->mDatePreference ) ) {
1453 global $wgLang;
1454 $value = $this->getOption( 'date' );
1455 $map = $wgLang->getDatePreferenceMigrationMap();
1456 if ( isset( $map[$value] ) ) {
1457 $value = $map[$value];
1459 $this->mDatePreference = $value;
1461 return $this->mDatePreference;
1465 * @param string $oname The option to check
1466 * @return bool False if the option is not selected, true if it is
1468 function getBoolOption( $oname ) {
1469 return (bool)$this->getOption( $oname );
1473 * Get an option as an integer value from the source string.
1474 * @param string $oname The option to check
1475 * @param int $default Optional value to return if option is unset/blank.
1476 * @return int
1478 function getIntOption( $oname, $default=0 ) {
1479 $val = $this->getOption( $oname );
1480 if( $val == '' ) {
1481 $val = $default;
1483 return intval( $val );
1486 function setOption( $oname, $val ) {
1487 $this->load();
1488 if ( is_null( $this->mOptions ) ) {
1489 $this->mOptions = User::getDefaultOptions();
1491 if ( $oname == 'skin' ) {
1492 # Clear cached skin, so the new one displays immediately in Special:Preferences
1493 unset( $this->mSkin );
1495 // Filter out any newlines that may have passed through input validation.
1496 // Newlines are used to separate items in the options blob.
1497 $val = str_replace( "\r\n", "\n", $val );
1498 $val = str_replace( "\r", "\n", $val );
1499 $val = str_replace( "\n", " ", $val );
1500 $this->mOptions[$oname] = $val;
1503 function getRights() {
1504 if ( is_null( $this->mRights ) ) {
1505 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1507 return $this->mRights;
1511 * Get the list of explicit group memberships this user has.
1512 * The implicit * and user groups are not included.
1513 * @return array of strings
1515 function getGroups() {
1516 $this->load();
1517 return $this->mGroups;
1521 * Get the list of implicit group memberships this user has.
1522 * This includes all explicit groups, plus 'user' if logged in
1523 * and '*' for all accounts.
1524 * @param boolean $recache Don't use the cache
1525 * @return array of strings
1527 function getEffectiveGroups( $recache = false ) {
1528 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1529 $this->load();
1530 $this->mEffectiveGroups = $this->mGroups;
1531 $this->mEffectiveGroups[] = '*';
1532 if( $this->mId ) {
1533 $this->mEffectiveGroups[] = 'user';
1535 global $wgAutoConfirmAge;
1536 $accountAge = time() - wfTimestampOrNull( TS_UNIX, $this->mRegistration );
1537 if( $accountAge >= $wgAutoConfirmAge ) {
1538 $this->mEffectiveGroups[] = 'autoconfirmed';
1541 # Implicit group for users whose email addresses are confirmed
1542 global $wgEmailAuthentication;
1543 if( self::isValidEmailAddr( $this->mEmail ) ) {
1544 if( $wgEmailAuthentication ) {
1545 if( $this->mEmailAuthenticated )
1546 $this->mEffectiveGroups[] = 'emailconfirmed';
1547 } else {
1548 $this->mEffectiveGroups[] = 'emailconfirmed';
1553 return $this->mEffectiveGroups;
1557 * Add the user to the given group.
1558 * This takes immediate effect.
1559 * @string $group
1561 function addGroup( $group ) {
1562 $this->load();
1563 $dbw =& wfGetDB( DB_MASTER );
1564 $dbw->insert( 'user_groups',
1565 array(
1566 'ug_user' => $this->getID(),
1567 'ug_group' => $group,
1569 'User::addGroup',
1570 array( 'IGNORE' ) );
1572 $this->mGroups[] = $group;
1573 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1575 $this->invalidateCache();
1579 * Remove the user from the given group.
1580 * This takes immediate effect.
1581 * @string $group
1583 function removeGroup( $group ) {
1584 $this->load();
1585 $dbw =& wfGetDB( DB_MASTER );
1586 $dbw->delete( 'user_groups',
1587 array(
1588 'ug_user' => $this->getID(),
1589 'ug_group' => $group,
1591 'User::removeGroup' );
1593 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
1594 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1596 $this->invalidateCache();
1601 * A more legible check for non-anonymousness.
1602 * Returns true if the user is not an anonymous visitor.
1604 * @return bool
1606 function isLoggedIn() {
1607 return( $this->getID() != 0 );
1611 * A more legible check for anonymousness.
1612 * Returns true if the user is an anonymous visitor.
1614 * @return bool
1616 function isAnon() {
1617 return !$this->isLoggedIn();
1621 * Whether the user is a bot
1622 * @deprecated
1624 function isBot() {
1625 return $this->isAllowed( 'bot' );
1629 * Check if user is allowed to access a feature / make an action
1630 * @param string $action Action to be checked
1631 * @return boolean True: action is allowed, False: action should not be allowed
1633 function isAllowed($action='') {
1634 if ( $action === '' )
1635 // In the spirit of DWIM
1636 return true;
1638 return in_array( $action, $this->getRights() );
1642 * Load a skin if it doesn't exist or return it
1643 * @todo FIXME : need to check the old failback system [AV]
1645 function &getSkin() {
1646 global $wgRequest;
1647 if ( ! isset( $this->mSkin ) ) {
1648 wfProfileIn( __METHOD__ );
1650 # get the user skin
1651 $userSkin = $this->getOption( 'skin' );
1652 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1654 $this->mSkin =& Skin::newFromKey( $userSkin );
1655 wfProfileOut( __METHOD__ );
1657 return $this->mSkin;
1660 /**#@+
1661 * @param string $title Article title to look at
1665 * Check watched status of an article
1666 * @return bool True if article is watched
1668 function isWatched( $title ) {
1669 $wl = WatchedItem::fromUserTitle( $this, $title );
1670 return $wl->isWatched();
1674 * Watch an article
1676 function addWatch( $title ) {
1677 $wl = WatchedItem::fromUserTitle( $this, $title );
1678 $wl->addWatch();
1679 $this->invalidateCache();
1683 * Stop watching an article
1685 function removeWatch( $title ) {
1686 $wl = WatchedItem::fromUserTitle( $this, $title );
1687 $wl->removeWatch();
1688 $this->invalidateCache();
1692 * Clear the user's notification timestamp for the given title.
1693 * If e-notif e-mails are on, they will receive notification mails on
1694 * the next change of the page if it's watched etc.
1696 function clearNotification( &$title ) {
1697 global $wgUser, $wgUseEnotif;
1699 if ($title->getNamespace() == NS_USER_TALK &&
1700 $title->getText() == $this->getName() ) {
1701 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1702 return;
1703 $this->setNewtalk( false );
1706 if( !$wgUseEnotif ) {
1707 return;
1710 if( $this->isAnon() ) {
1711 // Nothing else to do...
1712 return;
1715 // Only update the timestamp if the page is being watched.
1716 // The query to find out if it is watched is cached both in memcached and per-invocation,
1717 // and when it does have to be executed, it can be on a slave
1718 // If this is the user's newtalk page, we always update the timestamp
1719 if ($title->getNamespace() == NS_USER_TALK &&
1720 $title->getText() == $wgUser->getName())
1722 $watched = true;
1723 } elseif ( $this->getID() == $wgUser->getID() ) {
1724 $watched = $title->userIsWatching();
1725 } else {
1726 $watched = true;
1729 // If the page is watched by the user (or may be watched), update the timestamp on any
1730 // any matching rows
1731 if ( $watched ) {
1732 $dbw =& wfGetDB( DB_MASTER );
1733 $dbw->update( 'watchlist',
1734 array( /* SET */
1735 'wl_notificationtimestamp' => NULL
1736 ), array( /* WHERE */
1737 'wl_title' => $title->getDBkey(),
1738 'wl_namespace' => $title->getNamespace(),
1739 'wl_user' => $this->getID()
1740 ), 'User::clearLastVisited'
1745 /**#@-*/
1748 * Resets all of the given user's page-change notification timestamps.
1749 * If e-notif e-mails are on, they will receive notification mails on
1750 * the next change of any watched page.
1752 * @param int $currentUser user ID number
1753 * @public
1755 function clearAllNotifications( $currentUser ) {
1756 global $wgUseEnotif;
1757 if ( !$wgUseEnotif ) {
1758 $this->setNewtalk( false );
1759 return;
1761 if( $currentUser != 0 ) {
1763 $dbw =& wfGetDB( DB_MASTER );
1764 $dbw->update( 'watchlist',
1765 array( /* SET */
1766 'wl_notificationtimestamp' => NULL
1767 ), array( /* WHERE */
1768 'wl_user' => $currentUser
1769 ), 'UserMailer::clearAll'
1772 # we also need to clear here the "you have new message" notification for the own user_talk page
1773 # This is cleared one page view later in Article::viewUpdates();
1778 * @private
1779 * @return string Encoding options
1781 function encodeOptions() {
1782 $this->load();
1783 if ( is_null( $this->mOptions ) ) {
1784 $this->mOptions = User::getDefaultOptions();
1786 $a = array();
1787 foreach ( $this->mOptions as $oname => $oval ) {
1788 array_push( $a, $oname.'='.$oval );
1790 $s = implode( "\n", $a );
1791 return $s;
1795 * @private
1797 function decodeOptions( $str ) {
1798 $this->mOptions = array();
1799 $a = explode( "\n", $str );
1800 foreach ( $a as $s ) {
1801 $m = array();
1802 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1803 $this->mOptions[$m[1]] = $m[2];
1808 function setCookies() {
1809 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1810 $this->load();
1811 if ( 0 == $this->mId ) return;
1812 $exp = time() + $wgCookieExpiration;
1814 $_SESSION['wsUserID'] = $this->mId;
1815 setcookie( $wgCookiePrefix.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1817 $_SESSION['wsUserName'] = $this->getName();
1818 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1820 $_SESSION['wsToken'] = $this->mToken;
1821 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1822 setcookie( $wgCookiePrefix.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1823 } else {
1824 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1829 * Logout user
1830 * Clears the cookies and session, resets the instance cache
1832 function logout() {
1833 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1834 $this->clearInstanceCache( 'defaults' );
1836 $_SESSION['wsUserID'] = 0;
1838 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1839 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1841 # Remember when user logged out, to prevent seeing cached pages
1842 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1846 * Save object settings into database
1847 * @fixme Only rarely do all these fields need to be set!
1849 function saveSettings() {
1850 $this->load();
1851 if ( wfReadOnly() ) { return; }
1852 if ( 0 == $this->mId ) { return; }
1854 $this->mTouched = self::newTouchedTimestamp();
1856 $dbw =& wfGetDB( DB_MASTER );
1857 $dbw->update( 'user',
1858 array( /* SET */
1859 'user_name' => $this->mName,
1860 'user_password' => $this->mPassword,
1861 'user_newpassword' => $this->mNewpassword,
1862 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
1863 'user_real_name' => $this->mRealName,
1864 'user_email' => $this->mEmail,
1865 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1866 'user_options' => $this->encodeOptions(),
1867 'user_touched' => $dbw->timestamp($this->mTouched),
1868 'user_token' => $this->mToken
1869 ), array( /* WHERE */
1870 'user_id' => $this->mId
1871 ), __METHOD__
1873 $this->clearSharedCache();
1878 * Checks if a user with the given name exists, returns the ID
1880 function idForName() {
1881 $s = trim( $this->getName() );
1882 if ( 0 == strcmp( '', $s ) ) return 0;
1884 $dbr =& wfGetDB( DB_SLAVE );
1885 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
1886 if ( $id === false ) {
1887 $id = 0;
1889 return $id;
1893 * Add a user to the database, return the user object
1895 * @param string $name The user's name
1896 * @param array $params Associative array of non-default parameters to save to the database:
1897 * password The user's password. Password logins will be disabled if this is omitted.
1898 * newpassword A temporary password mailed to the user
1899 * email The user's email address
1900 * email_authenticated The email authentication timestamp
1901 * real_name The user's real name
1902 * options An associative array of non-default options
1903 * token Random authentication token. Do not set.
1904 * registration Registration timestamp. Do not set.
1906 * @return User object, or null if the username already exists
1908 static function createNew( $name, $params = array() ) {
1909 $user = new User;
1910 $user->load();
1911 if ( isset( $params['options'] ) ) {
1912 $user->mOptions = $params['options'] + $user->mOptions;
1913 unset( $params['options'] );
1915 $dbw =& wfGetDB( DB_MASTER );
1916 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1917 $fields = array(
1918 'user_id' => $seqVal,
1919 'user_name' => $name,
1920 'user_password' => $user->mPassword,
1921 'user_newpassword' => $user->mNewpassword,
1922 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
1923 'user_email' => $user->mEmail,
1924 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
1925 'user_real_name' => $user->mRealName,
1926 'user_options' => $user->encodeOptions(),
1927 'user_token' => $user->mToken,
1928 'user_registration' => $dbw->timestamp( $user->mRegistration ),
1930 foreach ( $params as $name => $value ) {
1931 $fields["user_$name"] = $value;
1933 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
1934 if ( $dbw->affectedRows() ) {
1935 $newUser = User::newFromId( $dbw->insertId() );
1936 } else {
1937 $newUser = null;
1939 return $newUser;
1943 * Add an existing user object to the database
1945 function addToDatabase() {
1946 $this->load();
1947 $dbw =& wfGetDB( DB_MASTER );
1948 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1949 $dbw->insert( 'user',
1950 array(
1951 'user_id' => $seqVal,
1952 'user_name' => $this->mName,
1953 'user_password' => $this->mPassword,
1954 'user_newpassword' => $this->mNewpassword,
1955 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
1956 'user_email' => $this->mEmail,
1957 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1958 'user_real_name' => $this->mRealName,
1959 'user_options' => $this->encodeOptions(),
1960 'user_token' => $this->mToken,
1961 'user_registration' => $dbw->timestamp( $this->mRegistration ),
1962 ), __METHOD__
1964 $this->mId = $dbw->insertId();
1966 # Clear instance cache other than user table data, which is already accurate
1967 $this->clearInstanceCache();
1971 * If the (non-anonymous) user is blocked, this function will block any IP address
1972 * that they successfully log on from.
1974 function spreadBlock() {
1975 wfDebug( __METHOD__."()\n" );
1976 $this->load();
1977 if ( $this->mId == 0 ) {
1978 return;
1981 $userblock = Block::newFromDB( '', $this->mId );
1982 if ( !$userblock ) {
1983 return;
1986 $userblock->doAutoblock( wfGetIp() );
1991 * Generate a string which will be different for any combination of
1992 * user options which would produce different parser output.
1993 * This will be used as part of the hash key for the parser cache,
1994 * so users will the same options can share the same cached data
1995 * safely.
1997 * Extensions which require it should install 'PageRenderingHash' hook,
1998 * which will give them a chance to modify this key based on their own
1999 * settings.
2001 * @return string
2003 function getPageRenderingHash() {
2004 global $wgContLang, $wgUseDynamicDates;
2005 if( $this->mHash ){
2006 return $this->mHash;
2009 // stubthreshold is only included below for completeness,
2010 // it will always be 0 when this function is called by parsercache.
2012 $confstr = $this->getOption( 'math' );
2013 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2014 if ( $wgUseDynamicDates ) {
2015 $confstr .= '!' . $this->getDatePreference();
2017 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2018 $confstr .= '!' . $this->getOption( 'language' );
2019 $confstr .= '!' . $this->getOption( 'thumbsize' );
2020 // add in language specific options, if any
2021 $extra = $wgContLang->getExtraHashOptions();
2022 $confstr .= $extra;
2024 // Give a chance for extensions to modify the hash, if they have
2025 // extra options or other effects on the parser cache.
2026 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2028 $this->mHash = $confstr;
2029 return $confstr;
2032 function isBlockedFromCreateAccount() {
2033 $this->getBlockedStatus();
2034 return $this->mBlock && $this->mBlock->mCreateAccount;
2037 function isAllowedToCreateAccount() {
2038 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2042 * @deprecated
2044 function setLoaded( $loaded ) {}
2047 * Get this user's personal page title.
2049 * @return Title
2050 * @public
2052 function getUserPage() {
2053 return Title::makeTitle( NS_USER, $this->getName() );
2057 * Get this user's talk page title.
2059 * @return Title
2060 * @public
2062 function getTalkPage() {
2063 $title = $this->getUserPage();
2064 return $title->getTalkPage();
2068 * @static
2070 function getMaxID() {
2071 static $res; // cache
2073 if ( isset( $res ) )
2074 return $res;
2075 else {
2076 $dbr =& wfGetDB( DB_SLAVE );
2077 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2082 * Determine whether the user is a newbie. Newbies are either
2083 * anonymous IPs, or the most recently created accounts.
2084 * @return bool True if it is a newbie.
2086 function isNewbie() {
2087 return !$this->isAllowed( 'autoconfirmed' );
2091 * Check to see if the given clear-text password is one of the accepted passwords
2092 * @param string $password User password.
2093 * @return bool True if the given password is correct otherwise False.
2095 function checkPassword( $password ) {
2096 global $wgAuth;
2097 $this->load();
2099 // Even though we stop people from creating passwords that
2100 // are shorter than this, doesn't mean people wont be able
2101 // to. Certain authentication plugins do NOT want to save
2102 // domain passwords in a mysql database, so we should
2103 // check this (incase $wgAuth->strict() is false).
2104 if( !$this->isValidPassword( $password ) ) {
2105 return false;
2108 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2109 return true;
2110 } elseif( $wgAuth->strict() ) {
2111 /* Auth plugin doesn't allow local authentication */
2112 return false;
2114 $ep = $this->encryptPassword( $password );
2115 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
2116 return true;
2117 } elseif ( function_exists( 'iconv' ) ) {
2118 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2119 # Check for this with iconv
2120 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2121 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
2122 return true;
2125 return false;
2129 * Check if the given clear-text password matches the temporary password
2130 * sent by e-mail for password reset operations.
2131 * @return bool
2133 function checkTemporaryPassword( $plaintext ) {
2134 $hash = $this->encryptPassword( $plaintext );
2135 return $hash === $this->mNewpassword;
2139 * Initialize (if necessary) and return a session token value
2140 * which can be used in edit forms to show that the user's
2141 * login credentials aren't being hijacked with a foreign form
2142 * submission.
2144 * @param mixed $salt - Optional function-specific data for hash.
2145 * Use a string or an array of strings.
2146 * @return string
2147 * @public
2149 function editToken( $salt = '' ) {
2150 if( !isset( $_SESSION['wsEditToken'] ) ) {
2151 $token = $this->generateToken();
2152 $_SESSION['wsEditToken'] = $token;
2153 } else {
2154 $token = $_SESSION['wsEditToken'];
2156 if( is_array( $salt ) ) {
2157 $salt = implode( '|', $salt );
2159 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2163 * Generate a hex-y looking random token for various uses.
2164 * Could be made more cryptographically sure if someone cares.
2165 * @return string
2167 function generateToken( $salt = '' ) {
2168 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2169 return md5( $token . $salt );
2173 * Check given value against the token value stored in the session.
2174 * A match should confirm that the form was submitted from the
2175 * user's own login session, not a form submission from a third-party
2176 * site.
2178 * @param string $val - the input value to compare
2179 * @param string $salt - Optional function-specific data for hash
2180 * @return bool
2181 * @public
2183 function matchEditToken( $val, $salt = '' ) {
2184 global $wgMemc;
2185 $sessionToken = $this->editToken( $salt );
2186 if ( $val != $sessionToken ) {
2187 wfDebug( "User::matchEditToken: broken session data\n" );
2189 return $val == $sessionToken;
2193 * Generate a new e-mail confirmation token and send a confirmation
2194 * mail to the user's given address.
2196 * @return mixed True on success, a WikiError object on failure.
2198 function sendConfirmationMail() {
2199 global $wgContLang;
2200 $expiration = null; // gets passed-by-ref and defined in next line.
2201 $url = $this->confirmationTokenUrl( $expiration );
2202 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2203 wfMsg( 'confirmemail_body',
2204 wfGetIP(),
2205 $this->getName(),
2206 $url,
2207 $wgContLang->timeanddate( $expiration, false ) ) );
2211 * Send an e-mail to this user's account. Does not check for
2212 * confirmed status or validity.
2214 * @param string $subject
2215 * @param string $body
2216 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2217 * @return mixed True on success, a WikiError object on failure.
2219 function sendMail( $subject, $body, $from = null ) {
2220 if( is_null( $from ) ) {
2221 global $wgPasswordSender;
2222 $from = $wgPasswordSender;
2225 require_once( 'UserMailer.php' );
2226 $to = new MailAddress( $this );
2227 $sender = new MailAddress( $from );
2228 $error = userMailer( $to, $sender, $subject, $body );
2230 if( $error == '' ) {
2231 return true;
2232 } else {
2233 return new WikiError( $error );
2238 * Generate, store, and return a new e-mail confirmation code.
2239 * A hash (unsalted since it's used as a key) is stored.
2240 * @param &$expiration mixed output: accepts the expiration time
2241 * @return string
2242 * @private
2244 function confirmationToken( &$expiration ) {
2245 $now = time();
2246 $expires = $now + 7 * 24 * 60 * 60;
2247 $expiration = wfTimestamp( TS_MW, $expires );
2249 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2250 $hash = md5( $token );
2252 $dbw =& wfGetDB( DB_MASTER );
2253 $dbw->update( 'user',
2254 array( 'user_email_token' => $hash,
2255 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2256 array( 'user_id' => $this->mId ),
2257 __METHOD__ );
2259 return $token;
2263 * Generate and store a new e-mail confirmation token, and return
2264 * the URL the user can use to confirm.
2265 * @param &$expiration mixed output: accepts the expiration time
2266 * @return string
2267 * @private
2269 function confirmationTokenUrl( &$expiration ) {
2270 $token = $this->confirmationToken( $expiration );
2271 $title = SpecialPage::getTitleFor( 'Confirmemail', $token );
2272 return $title->getFullUrl();
2276 * Mark the e-mail address confirmed and save.
2278 function confirmEmail() {
2279 $this->load();
2280 $this->mEmailAuthenticated = wfTimestampNow();
2281 $this->saveSettings();
2282 return true;
2286 * Is this user allowed to send e-mails within limits of current
2287 * site configuration?
2288 * @return bool
2290 function canSendEmail() {
2291 return $this->isEmailConfirmed();
2295 * Is this user allowed to receive e-mails within limits of current
2296 * site configuration?
2297 * @return bool
2299 function canReceiveEmail() {
2300 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2304 * Is this user's e-mail address valid-looking and confirmed within
2305 * limits of the current site configuration?
2307 * If $wgEmailAuthentication is on, this may require the user to have
2308 * confirmed their address by returning a code or using a password
2309 * sent to the address from the wiki.
2311 * @return bool
2313 function isEmailConfirmed() {
2314 global $wgEmailAuthentication;
2315 $this->load();
2316 $confirmed = true;
2317 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2318 if( $this->isAnon() )
2319 return false;
2320 if( !self::isValidEmailAddr( $this->mEmail ) )
2321 return false;
2322 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2323 return false;
2324 return true;
2325 } else {
2326 return $confirmed;
2331 * Return true if there is an outstanding request for e-mail confirmation.
2332 * @return bool
2334 function isEmailConfirmationPending() {
2335 global $wgEmailAuthentication;
2336 return $wgEmailAuthentication &&
2337 !$this->isEmailConfirmed() &&
2338 $this->mEmailToken &&
2339 $this->mEmailTokenExpires > wfTimestamp();
2343 * @param array $groups list of groups
2344 * @return array list of permission key names for given groups combined
2345 * @static
2347 static function getGroupPermissions( $groups ) {
2348 global $wgGroupPermissions;
2349 $rights = array();
2350 foreach( $groups as $group ) {
2351 if( isset( $wgGroupPermissions[$group] ) ) {
2352 $rights = array_merge( $rights,
2353 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2356 return $rights;
2360 * @param string $group key name
2361 * @return string localized descriptive name for group, if provided
2362 * @static
2364 static function getGroupName( $group ) {
2365 $key = "group-$group";
2366 $name = wfMsg( $key );
2367 if( $name == '' || wfEmptyMsg( $key, $name ) ) {
2368 return $group;
2369 } else {
2370 return $name;
2375 * @param string $group key name
2376 * @return string localized descriptive name for member of a group, if provided
2377 * @static
2379 static function getGroupMember( $group ) {
2380 $key = "group-$group-member";
2381 $name = wfMsg( $key );
2382 if( $name == '' || wfEmptyMsg( $key, $name ) ) {
2383 return $group;
2384 } else {
2385 return $name;
2390 * Return the set of defined explicit groups.
2391 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2392 * groups are not included, as they are defined
2393 * automatically, not in the database.
2394 * @return array
2395 * @static
2397 static function getAllGroups() {
2398 global $wgGroupPermissions;
2399 return array_diff(
2400 array_keys( $wgGroupPermissions ),
2401 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2405 * Get the title of a page describing a particular group
2407 * @param $group Name of the group
2408 * @return mixed
2410 static function getGroupPage( $group ) {
2411 $page = wfMsgForContent( 'grouppage-' . $group );
2412 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2413 $title = Title::newFromText( $page );
2414 if( is_object( $title ) )
2415 return $title;
2417 return false;
2421 * Create a link to the group in HTML, if available
2423 * @param $group Name of the group
2424 * @param $text The text of the link
2425 * @return mixed
2427 static function makeGroupLinkHTML( $group, $text = '' ) {
2428 if( $text == '' ) {
2429 $text = self::getGroupName( $group );
2431 $title = self::getGroupPage( $group );
2432 if( $title ) {
2433 global $wgUser;
2434 $sk = $wgUser->getSkin();
2435 return $sk->makeLinkObj( $title, $text );
2436 } else {
2437 return $text;
2442 * Create a link to the group in Wikitext, if available
2444 * @param $group Name of the group
2445 * @param $text The text of the link (by default, the name of the group)
2446 * @return mixed
2448 static function makeGroupLinkWiki( $group, $text = '' ) {
2449 if( $text == '' ) {
2450 $text = self::getGroupName( $group );
2452 $title = self::getGroupPage( $group );
2453 if( $title ) {
2454 $page = $title->getPrefixedText();
2455 return "[[$page|$text]]";
2456 } else {
2457 return $text;
2462 * Increment the user's edit-count field.
2463 * Will have no effect for anonymous users.
2465 function incEditCount() {
2466 if( !$this->isAnon() ) {
2467 $dbw = wfGetDB( DB_MASTER );
2468 $dbw->update( 'user',
2469 array( 'user_editcount=user_editcount+1' ),
2470 array( 'user_id' => $this->getId() ),
2471 __METHOD__ );
2473 // Lazy initialization check...
2474 if( $dbw->affectedRows() == 0 ) {
2475 // Pull from a slave to be less cruel to servers
2476 // Accuracy isn't the point anyway here
2477 $dbr = wfGetDB( DB_SLAVE );
2478 $count = $dbr->selectField( 'revision',
2479 'COUNT(rev_user)',
2480 array( 'rev_user' => $this->getId() ),
2481 __METHOD__ );
2483 // Now here's a goddamn hack...
2484 if( $dbr !== $dbw ) {
2485 // If we actually have a slave server, the count is
2486 // at least one behind because the current transaction
2487 // has not been committed and replicated.
2488 $count++;
2489 } else {
2490 // But if DB_SLAVE is selecting the master, then the
2491 // count we just read includes the revision that was
2492 // just added in the working transaction.
2495 $dbw->update( 'user',
2496 array( 'user_editcount' => $count ),
2497 array( 'user_id' => $this->getId() ),
2498 __METHOD__ );