11 require_once( 'WatchedItem.php' );
12 require_once( 'Group.php' );
14 # Number of characters in user_token field
15 define( 'USER_TOKEN_LENGTH', 32 );
25 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
26 var $mEmailAuthenticated;
27 var $mRights, $mOptions;
28 var $mDataLoaded, $mNewpassword;
30 var $mBlockedby, $mBlockreason;
35 /** Array of group id the user belong to */
39 /** Construct using User:loadDefaults() */
41 $this->loadDefaults();
45 * Static factory method
46 * @param string $name Username, validated by Title:newFromText()
50 function newFromName( $name ) {
53 # Clean up name according to title rules
55 $t = Title
::newFromText( $name );
59 $u->setName( $t->getText() );
60 $u->setId( $u->idFromName( $t->getText() ) );
66 * Factory method to fetch whichever use has a given email confirmation code.
67 * This code is generated when an account is created or its e-mail address
70 * If the code is invalid or has expired, returns NULL.
76 function newFromConfirmationCode( $code ) {
77 $dbr =& wfGetDB( DB_SLAVE
);
78 $name = $dbr->selectField( 'user', 'user_name', array(
79 'user_email_token' => md5( $code ),
80 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
82 if( is_string( $name ) ) {
83 return User
::newFromName( $name );
90 * Get username given an id.
91 * @param integer $id Database user id
92 * @return string Nickname of a user
95 function whoIs( $id ) {
96 $dbr =& wfGetDB( DB_SLAVE
);
97 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
101 * Get real username given an id.
102 * @param integer $id Database user id
103 * @return string Realname of a user
106 function whoIsReal( $id ) {
107 $dbr =& wfGetDB( DB_SLAVE
);
108 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
112 * Get database id given a user name
113 * @param string $name Nickname of a user
114 * @return integer|null Database user id (null: if non existent
117 function idFromName( $name ) {
118 $fname = "User::idFromName";
120 $nt = Title
::newFromText( $name );
121 if( is_null( $nt ) ) {
125 $dbr =& wfGetDB( DB_SLAVE
);
126 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
128 if ( $s === false ) {
136 * does the string match an anonymous IPv4 address?
139 * @param string $name Nickname of a user
142 function isIP( $name ) {
143 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
144 /*return preg_match("/^
145 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
146 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
147 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
148 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
153 * does the string match roughly an email address ?
157 * @param string $addr email address
161 function isValidEmailAddr ( $addr ) {
162 # There used to be a regular expression here, it got removed because it
163 # rejected valid addresses.
164 return ( trim( $addr ) != '' ) &&
165 (false !== strpos( $addr, '@' ) );
169 * probably return a random password
170 * @return string probably a random password
172 * @todo Check what is doing really [AV]
174 function randomPassword() {
175 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
176 $l = strlen( $pwchars ) - 1;
178 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
179 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
180 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
181 $pwchars{mt_rand( 0, $l )};
186 * Set properties to default
187 * Used at construction. It will load per language default settings only
188 * if we have an available language object.
190 function loadDefaults() {
193 $fname = 'User::loadDefaults' . $n;
194 wfProfileIn( $fname );
196 global $wgContLang, $wgIP, $wgDBname;
197 global $wgNamespacesToBeSearchedDefault;
200 $this->mNewtalk
= -1;
201 $this->mName
= $wgIP;
202 $this->mRealName
= $this->mEmail
= '';
203 $this->mEmailAuthenticated
= null;
204 $this->mPassword
= $this->mNewpassword
= '';
205 $this->mRights
= array();
206 $this->mGroups
= array();
207 // Getting user defaults only if we have an available language
208 if( isset( $wgContLang ) ) {
209 $this->loadDefaultFromLanguage();
212 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
213 $this->mOptions
['searchNs'.$nsnum] = $val;
215 unset( $this->mSkin
);
216 $this->mDataLoaded
= false;
217 $this->mBlockedby
= -1; # Unset
218 $this->setToken(); # Random
219 $this->mHash
= false;
221 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
222 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgDBname.'LoggedOut'] );
225 $this->mTouched
= '0'; # Allow any pages to be cached
228 wfProfileOut( $fname );
232 * Used to load user options from a language.
233 * This is not in loadDefault() cause we sometime create user before having
236 function loadDefaultFromLanguage(){
237 $this->mOptions
= User
::getDefaultOptions();
241 * Combine the language default options with any site-specific options
242 * and add the default language variants.
248 function getDefaultOptions() {
250 * Site defaults will override the global/language defaults
252 global $wgContLang, $wgDefaultUserOptions;
253 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptions();
256 * default language setting
258 $variant = $wgContLang->getPreferredVariant();
259 $defOpt['variant'] = $variant;
260 $defOpt['language'] = $variant;
266 * Get a given default option value.
273 function getDefaultOption( $opt ) {
274 $defOpts = User
::getDefaultOptions();
275 if( isset( $defOpts[$opt] ) ) {
276 return $defOpts[$opt];
283 * Get blocking information
285 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
286 * non-critical checks are done against slaves. Check when actually saving should be done against
289 * Note that even if $bFromSlave is false, the check is done first against slave, then master.
290 * The logic is that if blocked on slave, we'll assume it's either blocked on master or
291 * just slightly outta sync and soon corrected - safer to block slightly more that less.
292 * And it's cheaper to check slave first, then master if needed, than master always.
294 function getBlockedStatus() {
295 global $wgIP, $wgBlockCache, $wgProxyList, $wgEnableSorbs, $bFromSlave;
297 if ( -1 != $this->mBlockedby
) { return; }
299 $this->mBlockedby
= 0;
303 $block = new Block();
304 $block->forUpdate( $bFromSlave );
305 if ( $block->load( $wgIP , $this->mId
) ) {
306 $this->mBlockedby
= $block->mBy
;
307 $this->mBlockreason
= $block->mReason
;
308 $this->spreadBlock();
313 if ( !$this->mBlockedby
) {
314 # Check first against slave, and optionally from master.
315 $block = $wgBlockCache->get( $wgIP, true );
316 if ( !$block && !$bFromSlave )
318 # Not blocked: check against master, to make sure.
319 $wgBlockCache->clearLocal( );
320 $block = $wgBlockCache->get( $wgIP, false );
322 if ( $block !== false ) {
323 $this->mBlockedby
= $block->mBy
;
324 $this->mBlockreason
= $block->mReason
;
329 if ( !$this->mBlockedby
) {
330 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
331 $this->mBlockedby
= wfMsg( 'proxyblocker' );
332 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
337 if ( !$this->mBlockedby
&& $wgEnableSorbs ) {
338 if ( $this->inSorbsBlacklist( $wgIP ) ) {
339 $this->mBlockedby
= wfMsg( 'sorbs' );
340 $this->mBlockreason
= wfMsg( 'sorbsreason' );
346 function inSorbsBlacklist( $ip ) {
347 global $wgEnableSorbs;
348 return $wgEnableSorbs &&
349 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
352 function inOpmBlacklist( $ip ) {
354 return $wgEnableOpm &&
355 $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
358 function inDnsBlacklist( $ip, $base ) {
359 $fname = 'User::inDnsBlacklist';
360 wfProfileIn( $fname );
365 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
367 for ( $i=4; $i>=1; $i-- ) {
368 $host .= $m[$i] . '.';
373 $ipList = gethostbynamel( $host );
376 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
379 wfDebug( "Requested $host, not found in $base.\n" );
383 wfProfileOut( $fname );
388 * Primitive rate limits: enforce maximum actions per time period
389 * to put a brake on flooding.
391 * Note: when using a shared cache like memcached, IP-address
392 * last-hit counters will be shared across wikis.
394 * @return bool true if a rate limiter was tripped
397 function pingLimiter( $action='edit' ) {
398 global $wgRateLimits;
399 if( !isset( $wgRateLimits[$action] ) ) {
402 if( $this->isAllowed( 'delete' ) ) {
407 global $wgMemc, $wgIP, $wgDBname, $wgRateLimitLog;
408 $fname = 'User::pingLimiter';
409 $limits = $wgRateLimits[$action];
411 $id = $this->getId();
413 if( isset( $limits['anon'] ) && $id == 0 ) {
414 $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
417 if( isset( $limits['user'] ) && $id != 0 ) {
418 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
420 if( $this->isNewbie() ) {
421 if( isset( $limits['newbie'] ) && $id != 0 ) {
422 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
424 if( isset( $limits['ip'] ) ) {
425 $keys["mediawiki:limiter:$action:ip:$wgIP"] = $limits['ip'];
427 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $wgIP, $matches ) ) {
428 $subnet = $matches[1];
429 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
434 foreach( $keys as $key => $limit ) {
435 list( $max, $period ) = $limit;
436 $summary = "(limit $max in {$period}s)";
437 $count = $wgMemc->get( $key );
439 if( $count > $max ) {
440 wfDebug( "$fname: tripped! $key at $count $summary\n" );
441 if( $wgRateLimitLog ) {
442 @error_log
( $this->getName() . ": tripped $key at $count $summary\n", 3, $wgRateLimitLog );
446 wfDebug( "$fname: ok. $key at $count $summary\n" );
449 wfDebug( "$fname: adding record for $key $summary\n" );
450 $wgMemc->add( $key, 1, IntVal( $period ) );
452 $wgMemc->incr( $key );
459 * Check if user is blocked
460 * @return bool True if blocked, false otherwise
462 function isBlocked( $bFromSlave = false ) {
463 $this->getBlockedStatus( $bFromSlave );
464 return $this->mBlockedby
!== 0;
468 * Get name of blocker
469 * @return string name of blocker
471 function blockedBy() {
472 $this->getBlockedStatus();
473 return $this->mBlockedby
;
477 * Get blocking reason
478 * @return string Blocking reason
480 function blockedFor() {
481 $this->getBlockedStatus();
482 return $this->mBlockreason
;
486 * Initialise php session
488 function SetupSession() {
489 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
490 if( $wgSessionsInMemcached ) {
491 require_once( 'MemcachedSessions.php' );
492 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
493 # If it's left on 'user' or another setting from another
494 # application, it will end up failing. Try to recover.
495 ini_set ( 'session.save_handler', 'files' );
497 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
498 session_cache_limiter( 'private, must-revalidate' );
503 * Read datas from session
506 function loadFromSession() {
507 global $wgMemc, $wgDBname;
509 if ( isset( $_SESSION['wsUserID'] ) ) {
510 if ( 0 != $_SESSION['wsUserID'] ) {
511 $sId = $_SESSION['wsUserID'];
515 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
516 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
517 $_SESSION['wsUserID'] = $sId;
521 if ( isset( $_SESSION['wsUserName'] ) ) {
522 $sName = $_SESSION['wsUserName'];
523 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
524 $sName = $_COOKIE["{$wgDBname}UserName"];
525 $_SESSION['wsUserName'] = $sName;
530 $passwordCorrect = FALSE;
531 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
532 if($makenew = !$user) {
533 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
536 $user->loadFromDatabase();
538 wfDebug( "User::loadFromSession() got from cache!\n" );
541 if ( isset( $_SESSION['wsToken'] ) ) {
542 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken
;
543 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
544 $passwordCorrect = $user->mToken
== $_COOKIE["{$wgDBname}Token"];
546 return new User(); # Can't log in from session
549 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
551 if($wgMemc->set( $key, $user ))
552 wfDebug( "User::loadFromSession() successfully saved user\n" );
554 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
558 return new User(); # Can't log in from session
562 * Load a user from the database
564 function loadFromDatabase() {
565 global $wgCommandLineMode, $wgAnonGroupId, $wgLoggedInGroupId;
566 $fname = "User::loadFromDatabase";
568 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
569 # loading in a command line script, don't assume all command line scripts need it like this
570 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
571 if ( $this->mDataLoaded
) {
576 $this->mId
= IntVal( $this->mId
);
578 /** Anonymous user */
581 $anong = Group
::newFromId($wgAnonGroupId);
583 wfDebugDieBacktrace("Please update your database schema "
584 ."and populate initial group data from "
585 ."maintenance/archives patches");
586 $anong->loadFromDatabase();
587 $this->mRights
= explode(',', $anong->getRights());
588 $this->mDataLoaded
= true;
590 } # the following stuff is for non-anonymous users only
592 $dbr =& wfGetDB( DB_SLAVE
);
593 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
594 'user_email_authenticated',
595 'user_real_name','user_options','user_touched', 'user_token' ),
596 array( 'user_id' => $this->mId
), $fname );
598 if ( $s !== false ) {
599 $this->mName
= $s->user_name
;
600 $this->mEmail
= $s->user_email
;
601 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
602 $this->mRealName
= $s->user_real_name
;
603 $this->mPassword
= $s->user_password
;
604 $this->mNewpassword
= $s->user_newpassword
;
605 $this->decodeOptions( $s->user_options
);
606 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
607 $this->mToken
= $s->user_token
;
610 $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId
) );
612 // add the default group for logged in user
613 $this->mGroups
= array( $wgLoggedInGroupId );
615 while($group = $dbr->fetchRow($res)) {
616 if ( $group[0] != $wgLoggedInGroupId ) {
617 $this->mGroups
[] = $group[0];
622 $this->mRights
= array();
623 // now we merge groups rights to get this user rights
624 foreach($this->mGroups
as $aGroupId) {
625 $g = Group
::newFromId($aGroupId);
626 $g->loadFromDatabase();
627 $this->mRights
= array_merge($this->mRights
, explode(',', $g->getRights()));
630 // array merge duplicate rights which are part of several groups
631 $this->mRights
= array_unique($this->mRights
);
633 $dbr->freeResult($res);
636 $this->mDataLoaded
= true;
639 function getID() { return $this->mId
; }
640 function setID( $v ) {
642 $this->mDataLoaded
= false;
646 $this->loadFromDatabase();
650 function setName( $str ) {
651 $this->loadFromDatabase();
657 * Return the title dbkey form of the name, for eg user pages.
661 function getTitleKey() {
662 return str_replace( ' ', '_', $this->getName() );
665 function getNewtalk() {
666 $fname = 'User::getNewtalk';
667 $this->loadFromDatabase();
669 # Load the newtalk status if it is unloaded (mNewtalk=-1)
670 if( $this->mNewtalk
== -1 ) {
671 $this->mNewtalk
= 0; # reset talk page status
673 # Check memcached separately for anons, who have no
674 # entire User object stored in there.
676 global $wgDBname, $wgMemc;
677 $key = "$wgDBname:newtalk:ip:{$this->mName}";
678 $newtalk = $wgMemc->get( $key );
679 if( is_integer( $newtalk ) ) {
680 $this->mNewtalk
= $newtalk ?
1 : 0;
681 return (bool)$this->mNewtalk
;
685 $dbr =& wfGetDB( DB_SLAVE
);
686 $res = $dbr->select( 'watchlist',
688 array( 'wl_title' => $this->getTitleKey(),
689 'wl_namespace' => NS_USER_TALK
,
690 'wl_user' => $this->mId
,
691 'wl_notificationtimestamp != 0' ),
692 'User::getNewtalk' );
693 if( $dbr->numRows($res) > 0 ) {
696 $dbr->freeResult( $res );
699 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
703 return ( 0 != $this->mNewtalk
);
706 function setNewtalk( $val ) {
707 $this->loadFromDatabase();
708 $this->mNewtalk
= $val;
709 $this->invalidateCache();
712 function invalidateCache() {
713 $this->loadFromDatabase();
714 $this->mTouched
= wfTimestampNow();
715 # Don't forget to save the options after this or
716 # it won't take effect!
719 function validateCache( $timestamp ) {
720 $this->loadFromDatabase();
721 return ($timestamp >= $this->mTouched
);
726 * Will only be salted if $wgPasswordSalt is true
727 * @param string Password.
728 * @return string Salted password or clear password.
730 function addSalt( $p ) {
731 global $wgPasswordSalt;
733 return md5( "{$this->mId}-{$p}" );
739 * Encrypt a password.
740 * It can eventuall salt a password @see User::addSalt()
741 * @param string $p clear Password.
742 * @param string Encrypted password.
744 function encryptPassword( $p ) {
745 return $this->addSalt( md5( $p ) );
748 # Set the password and reset the random token
749 function setPassword( $str ) {
750 $this->loadFromDatabase();
752 $this->mPassword
= $this->encryptPassword( $str );
753 $this->mNewpassword
= '';
756 # Set the random token (used for persistent authentication)
757 function setToken( $token = false ) {
758 global $wgSecretKey, $wgProxyKey, $wgDBname;
760 if ( $wgSecretKey ) {
762 } elseif ( $wgProxyKey ) {
767 $this->mToken
= md5( $wgSecretKey . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId
);
769 $this->mToken
= $token;
774 function setCookiePassword( $str ) {
775 $this->loadFromDatabase();
776 $this->mCookiePassword
= md5( $str );
779 function setNewpassword( $str ) {
780 $this->loadFromDatabase();
781 $this->mNewpassword
= $this->encryptPassword( $str );
784 function getEmail() {
785 $this->loadFromDatabase();
786 return $this->mEmail
;
789 function getEmailAuthenticationTimestamp() {
790 $this->loadFromDatabase();
791 return $this->mEmailAuthenticated
;
794 function setEmail( $str ) {
795 $this->loadFromDatabase();
796 $this->mEmail
= $str;
799 function getRealName() {
800 $this->loadFromDatabase();
801 return $this->mRealName
;
804 function setRealName( $str ) {
805 $this->loadFromDatabase();
806 $this->mRealName
= $str;
809 function getOption( $oname ) {
810 $this->loadFromDatabase();
811 if ( array_key_exists( $oname, $this->mOptions
) ) {
812 return $this->mOptions
[$oname];
818 function setOption( $oname, $val ) {
819 $this->loadFromDatabase();
820 if ( $oname == 'skin' ) {
821 # Clear cached skin, so the new one displays immediately in Special:Preferences
822 unset( $this->mSkin
);
824 $this->mOptions
[$oname] = $val;
825 $this->invalidateCache();
828 function getRights() {
829 $this->loadFromDatabase();
830 return $this->mRights
;
833 function addRight( $rname ) {
834 $this->loadFromDatabase();
835 array_push( $this->mRights
, $rname );
836 $this->invalidateCache();
839 function getGroups() {
840 $this->loadFromDatabase();
841 return $this->mGroups
;
844 function setGroups($groups) {
845 $this->loadFromDatabase();
846 $this->mGroups
= $groups;
847 $this->invalidateCache();
851 * A more legible check for non-anonymousness.
852 * Returns true if the user is not an anonymous visitor.
856 function isLoggedIn() {
857 return( $this->getID() != 0 );
861 * A more legible check for anonymousness.
862 * Returns true if the user is an anonymous visitor.
867 return !$this->isLoggedIn();
871 * Check if a user is sysop
872 * Die with backtrace. Use User:isAllowed() instead.
876 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
880 function isDeveloper() {
881 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
885 function isBureaucrat() {
886 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
890 * Whether the user is a bot
891 * @todo need to be migrated to the new user level management sytem
894 $this->loadFromDatabase();
895 return in_array( 'bot', $this->mRights
);
899 * Check if user is allowed to access a feature / make an action
900 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
901 * @return boolean True: action is allowed, False: action should not be allowed
903 function isAllowed($action='') {
904 $this->loadFromDatabase();
905 return in_array( $action , $this->mRights
);
909 * Load a skin if it doesn't exist or return it
910 * @todo FIXME : need to check the old failback system [AV]
912 function &getSkin() {
914 if ( ! isset( $this->mSkin
) ) {
915 $fname = 'User::getSkin';
916 wfProfileIn( $fname );
918 # get all skin names available
919 $skinNames = Skin
::getSkinNames();
922 $userSkin = $this->getOption( 'skin' );
923 if ( $userSkin == '' ) { $userSkin = 'standard'; }
925 if ( !isset( $skinNames[$userSkin] ) ) {
926 # in case the user skin could not be found find a replacement
931 # if phptal is enabled we should have monobook skin that
932 # superseed the good old SkinStandard.
933 if ( isset( $skinNames['monobook'] ) ) {
934 $fallback[0] = 'MonoBook';
937 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
938 $sn = $fallback[$userSkin];
943 # The user skin is available
944 $sn = $skinNames[$userSkin];
947 # Grab the skin class and initialise it. Each skin checks for PHPTal
948 # and will not load if it's not enabled.
949 require_once( $IP.'/skins/'.$sn.'.php' );
951 # Check if we got if not failback to default skin
952 $className = 'Skin'.$sn;
953 if( !class_exists( $className ) ) {
954 # DO NOT die if the class isn't found. This breaks maintenance
955 # scripts and can cause a user account to be unrecoverable
956 # except by SQL manipulation if a previously valid skin name
957 # is no longer valid.
958 $className = 'SkinStandard';
959 require_once( $IP.'/skins/Standard.php' );
961 $this->mSkin
=& new $className;
962 wfProfileOut( $fname );
968 * @param string $title Article title to look at
972 * Check watched status of an article
973 * @return bool True if article is watched
975 function isWatched( $title ) {
976 $wl = WatchedItem
::fromUserTitle( $this, $title );
977 return $wl->isWatched();
983 function addWatch( $title ) {
984 $wl = WatchedItem
::fromUserTitle( $this, $title );
986 $this->invalidateCache();
990 * Stop watching an article
992 function removeWatch( $title ) {
993 $wl = WatchedItem
::fromUserTitle( $this, $title );
995 $this->invalidateCache();
999 * Clear the user's notification timestamp for the given title.
1000 * If e-notif e-mails are on, they will receive notification mails on
1001 * the next change of the page if it's watched etc.
1003 function clearNotification( &$title ) {
1006 $userid = $this->getID();
1010 // Only update the timestamp if the page is being watched.
1011 // The query to find out if it is watched is cached both in memcached and per-invocation,
1012 // and when it does have to be executed, it can be on a slave
1013 // If this is the user's newtalk page, we always update the timestamp
1014 if ($title->getNamespace() == NS_USER_TALK
&&
1015 $title->getText() == $wgUser->getName())
1018 } elseif ( $this->getID() == $wgUser->getID() ) {
1019 $watched = $title->userIsWatching();
1024 // If the page is watched by the user (or may be watched), update the timestamp on any
1025 // any matching rows
1027 $dbw =& wfGetDB( DB_MASTER
);
1028 $success = $dbw->update( 'watchlist',
1030 'wl_notificationtimestamp' => 0
1031 ), array( /* WHERE */
1032 'wl_title' => $title->getDBkey(),
1033 'wl_namespace' => $title->getNamespace(),
1034 'wl_user' => $this->getID()
1035 ), 'User::clearLastVisited'
1043 * Resets all of the given user's page-change notification timestamps.
1044 * If e-notif e-mails are on, they will receive notification mails on
1045 * the next change of any watched page.
1047 * @param int $currentUser user ID number
1050 function clearAllNotifications( $currentUser ) {
1051 if( $currentUser != 0 ) {
1053 $dbw =& wfGetDB( DB_MASTER
);
1054 $success = $dbw->update( 'watchlist',
1056 'wl_notificationtimestamp' => 0
1057 ), array( /* WHERE */
1058 'wl_user' => $currentUser
1059 ), 'UserMailer::clearAll'
1062 # we also need to clear here the "you have new message" notification for the own user_talk page
1063 # This is cleared one page view later in Article::viewUpdates();
1069 * @return string Encoding options
1071 function encodeOptions() {
1073 foreach ( $this->mOptions
as $oname => $oval ) {
1074 array_push( $a, $oname.'='.$oval );
1076 $s = implode( "\n", $a );
1083 function decodeOptions( $str ) {
1084 $a = explode( "\n", $str );
1085 foreach ( $a as $s ) {
1086 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1087 $this->mOptions
[$m[1]] = $m[2];
1092 function setCookies() {
1093 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
1094 if ( 0 == $this->mId
) return;
1095 $this->loadFromDatabase();
1096 $exp = time() +
$wgCookieExpiration;
1098 $_SESSION['wsUserID'] = $this->mId
;
1099 setcookie( $wgDBname.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain );
1101 $_SESSION['wsUserName'] = $this->mName
;
1102 setcookie( $wgDBname.'UserName', $this->mName
, $exp, $wgCookiePath, $wgCookieDomain );
1104 $_SESSION['wsToken'] = $this->mToken
;
1105 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1106 setcookie( $wgDBname.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain );
1108 setcookie( $wgDBname.'Token', '', time() - 3600 );
1114 * It will clean the session cookie
1117 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1118 $this->loadDefaults();
1119 $this->setLoaded( true );
1121 $_SESSION['wsUserID'] = 0;
1123 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1124 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1126 # Remember when user logged out, to prevent seeing cached pages
1127 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain );
1131 * Save object settings into database
1133 function saveSettings() {
1134 global $wgMemc, $wgDBname;
1135 $fname = 'User::saveSettings';
1137 $dbw =& wfGetDB( DB_MASTER
);
1138 if ( ! $this->getNewtalk() ) {
1139 # Delete the watchlist entry for user_talk page X watched by user X
1140 $dbw->delete( 'watchlist',
1141 array( 'wl_user' => $this->mId
,
1142 'wl_title' => $this->getTitleKey(),
1143 'wl_namespace' => NS_USER_TALK
),
1146 # Anon users have a separate memcache space for newtalk
1147 # since they don't store their own info. Trim...
1148 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1152 if ( 0 == $this->mId
) { return; }
1154 $dbw->update( 'user',
1156 'user_name' => $this->mName
,
1157 'user_password' => $this->mPassword
,
1158 'user_newpassword' => $this->mNewpassword
,
1159 'user_real_name' => $this->mRealName
,
1160 'user_email' => $this->mEmail
,
1161 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1162 'user_options' => $this->encodeOptions(),
1163 'user_touched' => $dbw->timestamp($this->mTouched
),
1164 'user_token' => $this->mToken
1165 ), array( /* WHERE */
1166 'user_id' => $this->mId
1169 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights
),
1170 'ur_user='. $this->mId
, $fname );
1171 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1173 // delete old groups
1174 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId
), $fname);
1177 foreach ($this->mGroups
as $group) {
1178 $dbw->replace( 'user_groups',
1179 array(array('ug_user','ug_group')),
1181 'ug_user' => $this->mId
,
1182 'ug_group' => $group
1190 * Checks if a user with the given name exists, returns the ID
1192 function idForName() {
1193 $fname = 'User::idForName';
1196 $s = trim( $this->mName
);
1197 if ( 0 == strcmp( '', $s ) ) return 0;
1199 $dbr =& wfGetDB( DB_SLAVE
);
1200 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1201 if ( $id === false ) {
1208 * Add user object to the database
1210 function addToDatabase() {
1211 $fname = 'User::addToDatabase';
1212 $dbw =& wfGetDB( DB_MASTER
);
1213 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1214 $dbw->insert( 'user',
1216 'user_id' => $seqVal,
1217 'user_name' => $this->mName
,
1218 'user_password' => $this->mPassword
,
1219 'user_newpassword' => $this->mNewpassword
,
1220 'user_email' => $this->mEmail
,
1221 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1222 'user_real_name' => $this->mRealName
,
1223 'user_options' => $this->encodeOptions(),
1224 'user_token' => $this->mToken
1227 $this->mId
= $dbw->insertId();
1228 $dbw->insert( 'user_rights',
1230 'ur_user' => $this->mId
,
1231 'ur_rights' => implode( ',', $this->mRights
)
1235 foreach ($this->mGroups
as $group) {
1236 $dbw->insert( 'user_groups',
1238 'ug_user' => $this->mId
,
1239 'ug_group' => $group
1245 function spreadBlock() {
1247 # If the (non-anonymous) user is blocked, this function will block any IP address
1248 # that they successfully log on from.
1249 $fname = 'User::spreadBlock';
1251 wfDebug( "User:spreadBlock()\n" );
1252 if ( $this->mId
== 0 ) {
1256 $userblock = Block
::newFromDB( '', $this->mId
);
1257 if ( !$userblock->isValid() ) {
1261 # Check if this IP address is already blocked
1262 $ipblock = Block
::newFromDB( $wgIP );
1263 if ( $ipblock->isValid() ) {
1264 # Just update the timestamp
1265 $ipblock->updateTimestamp();
1269 # Make a new block object with the desired properties
1270 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1271 $ipblock->mAddress
= $wgIP;
1272 $ipblock->mUser
= 0;
1273 $ipblock->mBy
= $userblock->mBy
;
1274 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1275 $ipblock->mTimestamp
= wfTimestampNow();
1276 $ipblock->mAuto
= 1;
1277 # If the user is already blocked with an expiry date, we don't
1278 # want to pile on top of that!
1279 if($userblock->mExpiry
) {
1280 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1282 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1290 function getPageRenderingHash() {
1293 return $this->mHash
;
1296 // stubthreshold is only included below for completeness,
1297 // it will always be 0 when this function is called by parsercache.
1299 $confstr = $this->getOption( 'math' );
1300 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1301 $confstr .= '!' . $this->getOption( 'editsection' );
1302 $confstr .= '!' . $this->getOption( 'date' );
1303 $confstr .= '!' . $this->getOption( 'numberheadings' );
1304 $confstr .= '!' . $this->getOption( 'language' );
1305 $confstr .= '!' . $this->getOption( 'thumbsize' );
1306 // add in language specific options, if any
1307 $extra = $wgContLang->getExtraHashOptions();
1310 $this->mHash
= $confstr;
1314 function isAllowedToCreateAccount() {
1315 global $wgWhitelistAccount;
1318 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1319 foreach ($wgWhitelistAccount as $right => $ok) {
1320 $userHasRight = (!strcmp($right, 'user') ||
in_array($right, $this->getRights()));
1321 $allowed |
= ($ok && $userHasRight);
1327 * Set mDataLoaded, return previous value
1328 * Use this to prevent DB access in command-line scripts or similar situations
1330 function setLoaded( $loaded ) {
1331 return wfSetVar( $this->mDataLoaded
, $loaded );
1335 * Get this user's personal page title.
1340 function getUserPage() {
1341 return Title
::makeTitle( NS_USER
, $this->mName
);
1345 * Get this user's talk page title.
1350 function getTalkPage() {
1351 $title = $this->getUserPage();
1352 return $title->getTalkPage();
1358 function getMaxID() {
1359 $dbr =& wfGetDB( DB_SLAVE
);
1360 return $dbr->selectField( 'user', 'max(user_id)', false );
1364 * Determine whether the user is a newbie. Newbies are either
1365 * anonymous IPs, or the 1% most recently created accounts.
1366 * Bots and sysops are excluded.
1367 * @return bool True if it is a newbie.
1369 function isNewbie() {
1370 return $this->isAnon() ||
$this->mId
> User
::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot();
1374 * Check to see if the given clear-text password is one of the accepted passwords
1375 * @param string $password User password.
1376 * @return bool True if the given password is correct otherwise False.
1378 function checkPassword( $password ) {
1380 $this->loadFromDatabase();
1382 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1384 } elseif( $wgAuth->strict() ) {
1385 /* Auth plugin doesn't allow local authentication */
1388 $ep = $this->encryptPassword( $password );
1389 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
1391 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
1393 } elseif ( function_exists( 'iconv' ) ) {
1394 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1395 # Check for this with iconv
1396 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1397 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
1405 * Initialize (if necessary) and return a session token value
1406 * which can be used in edit forms to show that the user's
1407 * login credentials aren't being hijacked with a foreign form
1410 * @param mixed $salt - Optional function-specific data for hash.
1411 * Use a string or an array of strings.
1415 function editToken( $salt = '' ) {
1416 if( !isset( $_SESSION['wsEditToken'] ) ) {
1417 $token = $this->generateToken();
1418 $_SESSION['wsEditToken'] = $token;
1420 $token = $_SESSION['wsEditToken'];
1422 if( is_array( $salt ) ) {
1423 $salt = implode( '|', $salt );
1425 return md5( $token . $salt );
1429 * Generate a hex-y looking random token for various uses.
1430 * Could be made more cryptographically sure if someone cares.
1433 function generateToken( $salt = '' ) {
1434 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1435 return md5( $token . $salt );
1439 * Check given value against the token value stored in the session.
1440 * A match should confirm that the form was submitted from the
1441 * user's own login session, not a form submission from a third-party
1444 * @param string $val - the input value to compare
1445 * @param string $salt - Optional function-specific data for hash
1449 function matchEditToken( $val, $salt = '' ) {
1450 return ( $val == $this->editToken( $salt ) );
1454 * Generate a new e-mail confirmation token and send a confirmation
1455 * mail to the user's given address.
1457 * @return mixed True on success, a WikiError object on failure.
1459 function sendConfirmationMail() {
1460 global $wgIP, $wgContLang;
1461 $url = $this->confirmationTokenUrl( $expiration );
1462 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1463 wfMsg( 'confirmemail_body',
1467 $wgContLang->timeanddate( $expiration, false ) ) );
1471 * Send an e-mail to this user's account. Does not check for
1472 * confirmed status or validity.
1474 * @param string $subject
1475 * @param string $body
1476 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1477 * @return mixed True on success, a WikiError object on failure.
1479 function sendMail( $subject, $body, $from = null ) {
1480 if( is_null( $from ) ) {
1481 global $wgPasswordSender;
1482 $from = $wgPasswordSender;
1485 require_once( 'UserMailer.php' );
1486 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1488 if( $error == '' ) {
1491 return new WikiError( $error );
1496 * Generate, store, and return a new e-mail confirmation code.
1497 * A hash (unsalted since it's used as a key) is stored.
1498 * @param &$expiration mixed output: accepts the expiration time
1502 function confirmationToken( &$expiration ) {
1503 $fname = 'User::confirmationToken';
1506 $expires = $now +
7 * 24 * 60 * 60;
1507 $expiration = wfTimestamp( TS_MW
, $expires );
1509 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
1510 $hash = md5( $token );
1512 $dbw =& wfGetDB( DB_MASTER
);
1513 $dbw->update( 'user',
1514 array( 'user_email_token' => $hash,
1515 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1516 array( 'user_id' => $this->mId
),
1523 * Generate and store a new e-mail confirmation token, and return
1524 * the URL the user can use to confirm.
1525 * @param &$expiration mixed output: accepts the expiration time
1529 function confirmationTokenUrl( &$expiration ) {
1530 $token = $this->confirmationToken( $expiration );
1531 $title = Title
::makeTitle( NS_SPECIAL
, 'Confirmemail/' . $token );
1532 return $title->getFullUrl();
1536 * Mark the e-mail address confirmed and save.
1538 function confirmEmail() {
1539 $this->loadFromDatabase();
1540 $this->mEmailAuthenticated
= wfTimestampNow();
1541 $this->saveSettings();
1546 * Is this user allowed to send e-mails within limits of current
1547 * site configuration?
1550 function canSendEmail() {
1551 return $this->isEmailConfirmed();
1555 * Is this user allowed to receive e-mails within limits of current
1556 * site configuration?
1559 function canReceiveEmail() {
1560 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1564 * Is this user's e-mail address valid-looking and confirmed within
1565 * limits of the current site configuration?
1567 * If $wgEmailAuthentication is on, this may require the user to have
1568 * confirmed their address by returning a code or using a password
1569 * sent to the address from the wiki.
1573 function isEmailConfirmed() {
1574 global $wgEmailAuthentication;
1575 $this->loadFromDatabase();
1576 if( $this->isAnon() )
1578 if( !$this->isValidEmailAddr( $this->mEmail
) )
1580 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )