11 require_once( 'WatchedItem.php' );
13 # Number of characters in user_token field
14 define( 'USER_TOKEN_LENGTH', 32 );
24 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
25 var $mEmailAuthenticated;
26 var $mRights, $mOptions;
27 var $mDataLoaded, $mNewpassword;
29 var $mBlockedby, $mBlockreason;
36 /** Construct using User:loadDefaults() */
38 $this->loadDefaults();
42 * Static factory method
43 * @param string $name Username, validated by Title:newFromText()
47 function newFromName( $name ) {
50 # Clean up name according to title rules
52 $t = Title
::newFromText( $name );
56 $u->setName( $t->getText() );
57 $u->setId( $u->idFromName( $t->getText() ) );
63 * Factory method to fetch whichever use has a given email confirmation code.
64 * This code is generated when an account is created or its e-mail address
67 * If the code is invalid or has expired, returns NULL.
73 function newFromConfirmationCode( $code ) {
74 $dbr =& wfGetDB( DB_SLAVE
);
75 $name = $dbr->selectField( 'user', 'user_name', array(
76 'user_email_token' => md5( $code ),
77 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
79 if( is_string( $name ) ) {
80 return User
::newFromName( $name );
87 * Get username given an id.
88 * @param integer $id Database user id
89 * @return string Nickname of a user
92 function whoIs( $id ) {
93 $dbr =& wfGetDB( DB_SLAVE
);
94 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
98 * Get real username given an id.
99 * @param integer $id Database user id
100 * @return string Realname of a user
103 function whoIsReal( $id ) {
104 $dbr =& wfGetDB( DB_SLAVE
);
105 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
109 * Get database id given a user name
110 * @param string $name Nickname of a user
111 * @return integer|null Database user id (null: if non existent
114 function idFromName( $name ) {
115 $fname = "User::idFromName";
117 $nt = Title
::newFromText( $name );
118 if( is_null( $nt ) ) {
122 $dbr =& wfGetDB( DB_SLAVE
);
123 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
125 if ( $s === false ) {
133 * does the string match an anonymous IPv4 address?
136 * @param string $name Nickname of a user
139 function isIP( $name ) {
140 return preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/",$name);
141 /*return preg_match("/^
142 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
143 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
144 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
145 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
150 * does the string match roughly an email address ?
154 * @param string $addr email address
158 function isValidEmailAddr ( $addr ) {
159 # There used to be a regular expression here, it got removed because it
160 # rejected valid addresses.
161 return ( trim( $addr ) != '' ) &&
162 (false !== strpos( $addr, '@' ) );
166 * probably return a random password
167 * @return string probably a random password
169 * @todo Check what is doing really [AV]
171 function randomPassword() {
172 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
173 $l = strlen( $pwchars ) - 1;
175 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
176 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
177 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
178 $pwchars{mt_rand( 0, $l )};
183 * Set properties to default
184 * Used at construction. It will load per language default settings only
185 * if we have an available language object.
187 function loadDefaults() {
190 $fname = 'User::loadDefaults' . $n;
191 wfProfileIn( $fname );
193 global $wgContLang, $wgIP, $wgDBname;
194 global $wgNamespacesToBeSearchedDefault;
197 $this->mNewtalk
= -1;
198 $this->mName
= $wgIP;
199 $this->mRealName
= $this->mEmail
= '';
200 $this->mEmailAuthenticated
= null;
201 $this->mPassword
= $this->mNewpassword
= '';
202 $this->mRights
= array();
203 $this->mGroups
= array();
204 $this->mOptions
= User
::getDefaultOptions();
206 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
207 $this->mOptions
['searchNs'.$nsnum] = $val;
209 unset( $this->mSkin
);
210 $this->mDataLoaded
= false;
211 $this->mBlockedby
= -1; # Unset
212 $this->setToken(); # Random
213 $this->mHash
= false;
215 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
216 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgDBname.'LoggedOut'] );
219 $this->mTouched
= '0'; # Allow any pages to be cached
222 wfProfileOut( $fname );
226 * Combine the language default options with any site-specific options
227 * and add the default language variants.
233 function getDefaultOptions() {
235 * Site defaults will override the global/language defaults
237 global $wgContLang, $wgDefaultUserOptions;
238 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptions();
241 * default language setting
243 $variant = $wgContLang->getPreferredVariant();
244 $defOpt['variant'] = $variant;
245 $defOpt['language'] = $variant;
251 * Get a given default option value.
258 function getDefaultOption( $opt ) {
259 $defOpts = User
::getDefaultOptions();
260 if( isset( $defOpts[$opt] ) ) {
261 return $defOpts[$opt];
268 * Get blocking information
270 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
271 * non-critical checks are done against slaves. Check when actually saving should be done against
274 * Note that even if $bFromSlave is false, the check is done first against slave, then master.
275 * The logic is that if blocked on slave, we'll assume it's either blocked on master or
276 * just slightly outta sync and soon corrected - safer to block slightly more that less.
277 * And it's cheaper to check slave first, then master if needed, than master always.
279 function getBlockedStatus( $bFromSlave = true ) {
280 global $wgIP, $wgBlockCache, $wgProxyList, $wgEnableSorbs, $wgProxyWhitelist;
282 if ( -1 != $this->mBlockedby
) { return; }
284 $this->mBlockedby
= 0;
288 $block = new Block();
289 $block->forUpdate( $bFromSlave );
290 if ( $block->load( $wgIP , $this->mId
) ) {
291 $this->mBlockedby
= $block->mBy
;
292 $this->mBlockreason
= $block->mReason
;
293 $this->spreadBlock();
298 if ( !$this->mBlockedby
) {
299 # Check first against slave, and optionally from master.
300 $block = $wgBlockCache->get( $wgIP, true );
301 if ( !$block && !$bFromSlave )
303 # Not blocked: check against master, to make sure.
304 $wgBlockCache->clearLocal( );
305 $block = $wgBlockCache->get( $wgIP, false );
307 if ( $block !== false ) {
308 $this->mBlockedby
= $block->mBy
;
309 $this->mBlockreason
= $block->mReason
;
314 if ( !$this->isSysop() && !in_array( $wgIP, $wgProxyWhitelist ) ) {
317 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
318 $this->mBlockedby
= wfMsg( 'proxyblocker' );
319 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
323 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
324 if ( $this->inSorbsBlacklist( $wgIP ) ) {
325 $this->mBlockedby
= wfMsg( 'sorbs' );
326 $this->mBlockreason
= wfMsg( 'sorbsreason' );
332 function inSorbsBlacklist( $ip ) {
333 global $wgEnableSorbs;
334 return $wgEnableSorbs &&
335 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
338 function inOpmBlacklist( $ip ) {
340 return $wgEnableOpm &&
341 $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
344 function inDnsBlacklist( $ip, $base ) {
345 $fname = 'User::inDnsBlacklist';
346 wfProfileIn( $fname );
351 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
353 for ( $i=4; $i>=1; $i-- ) {
354 $host .= $m[$i] . '.';
359 $ipList = gethostbynamel( $host );
362 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
365 wfDebug( "Requested $host, not found in $base.\n" );
369 wfProfileOut( $fname );
374 * Primitive rate limits: enforce maximum actions per time period
375 * to put a brake on flooding.
377 * Note: when using a shared cache like memcached, IP-address
378 * last-hit counters will be shared across wikis.
380 * @return bool true if a rate limiter was tripped
383 function pingLimiter( $action='edit' ) {
384 global $wgRateLimits;
385 if( !isset( $wgRateLimits[$action] ) ) {
388 if( $this->isAllowed( 'delete' ) ) {
393 global $wgMemc, $wgIP, $wgDBname, $wgRateLimitLog;
394 $fname = 'User::pingLimiter';
395 $limits = $wgRateLimits[$action];
397 $id = $this->getId();
399 if( isset( $limits['anon'] ) && $id == 0 ) {
400 $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
403 if( isset( $limits['user'] ) && $id != 0 ) {
404 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
406 if( $this->isNewbie() ) {
407 if( isset( $limits['newbie'] ) && $id != 0 ) {
408 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
410 if( isset( $limits['ip'] ) ) {
411 $keys["mediawiki:limiter:$action:ip:$wgIP"] = $limits['ip'];
413 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $wgIP, $matches ) ) {
414 $subnet = $matches[1];
415 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
420 foreach( $keys as $key => $limit ) {
421 list( $max, $period ) = $limit;
422 $summary = "(limit $max in {$period}s)";
423 $count = $wgMemc->get( $key );
425 if( $count > $max ) {
426 wfDebug( "$fname: tripped! $key at $count $summary\n" );
427 if( $wgRateLimitLog ) {
428 @error_log
( wfTimestamp( TS_MW
) . ' ' . $wgDBname . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
432 wfDebug( "$fname: ok. $key at $count $summary\n" );
435 wfDebug( "$fname: adding record for $key $summary\n" );
436 $wgMemc->add( $key, 1, IntVal( $period ) );
438 $wgMemc->incr( $key );
445 * Check if user is blocked
446 * @return bool True if blocked, false otherwise
448 function isBlocked( $bFromSlave = false ) {
449 $this->getBlockedStatus( $bFromSlave );
450 return $this->mBlockedby
!== 0;
454 * Get name of blocker
455 * @return string name of blocker
457 function blockedBy() {
458 $this->getBlockedStatus();
459 return $this->mBlockedby
;
463 * Get blocking reason
464 * @return string Blocking reason
466 function blockedFor() {
467 $this->getBlockedStatus();
468 return $this->mBlockreason
;
472 * Initialise php session
474 function SetupSession() {
475 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
476 if( $wgSessionsInMemcached ) {
477 require_once( 'MemcachedSessions.php' );
478 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
479 # If it's left on 'user' or another setting from another
480 # application, it will end up failing. Try to recover.
481 ini_set ( 'session.save_handler', 'files' );
483 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
484 session_cache_limiter( 'private, must-revalidate' );
489 * Read datas from session
492 function loadFromSession() {
493 global $wgMemc, $wgDBname;
495 if ( isset( $_SESSION['wsUserID'] ) ) {
496 if ( 0 != $_SESSION['wsUserID'] ) {
497 $sId = $_SESSION['wsUserID'];
501 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
502 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
503 $_SESSION['wsUserID'] = $sId;
507 if ( isset( $_SESSION['wsUserName'] ) ) {
508 $sName = $_SESSION['wsUserName'];
509 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
510 $sName = $_COOKIE["{$wgDBname}UserName"];
511 $_SESSION['wsUserName'] = $sName;
516 $passwordCorrect = FALSE;
517 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
518 if($makenew = !$user) {
519 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
522 $user->loadFromDatabase();
524 wfDebug( "User::loadFromSession() got from cache!\n" );
527 if ( isset( $_SESSION['wsToken'] ) ) {
528 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken
;
529 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
530 $passwordCorrect = $user->mToken
== $_COOKIE["{$wgDBname}Token"];
532 return new User(); # Can't log in from session
535 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
537 if($wgMemc->set( $key, $user ))
538 wfDebug( "User::loadFromSession() successfully saved user\n" );
540 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
544 return new User(); # Can't log in from session
548 * Load a user from the database
550 function loadFromDatabase() {
551 global $wgCommandLineMode;
552 $fname = "User::loadFromDatabase";
554 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
555 # loading in a command line script, don't assume all command line scripts need it like this
556 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
557 if ( $this->mDataLoaded
) {
562 $this->mId
= IntVal( $this->mId
);
564 /** Anonymous user */
567 $this->mRights
= $this->getGroupPermissions( array( '*' ) );
568 $this->mDataLoaded
= true;
570 } # the following stuff is for non-anonymous users only
572 $dbr =& wfGetDB( DB_SLAVE
);
573 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
574 'user_email_authenticated',
575 'user_real_name','user_options','user_touched', 'user_token' ),
576 array( 'user_id' => $this->mId
), $fname );
578 if ( $s !== false ) {
579 $this->mName
= $s->user_name
;
580 $this->mEmail
= $s->user_email
;
581 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
582 $this->mRealName
= $s->user_real_name
;
583 $this->mPassword
= $s->user_password
;
584 $this->mNewpassword
= $s->user_newpassword
;
585 $this->decodeOptions( $s->user_options
);
586 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
587 $this->mToken
= $s->user_token
;
589 $res = $dbr->select( 'user_groups',
591 array( 'ug_user' => $this->mId
),
593 $this->mGroups
= array();
594 while( $row = $dbr->fetchObject( $res ) ) {
595 $this->mGroups
[] = $row->ug_group
;
597 $effectiveGroups = array_merge( array( '*', 'user' ), $this->mGroups
);
598 $this->mRights
= $this->getGroupPermissions( $effectiveGroups );
601 $this->mDataLoaded
= true;
604 function getID() { return $this->mId
; }
605 function setID( $v ) {
607 $this->mDataLoaded
= false;
611 $this->loadFromDatabase();
615 function setName( $str ) {
616 $this->loadFromDatabase();
622 * Return the title dbkey form of the name, for eg user pages.
626 function getTitleKey() {
627 return str_replace( ' ', '_', $this->getName() );
630 function getNewtalk() {
631 $fname = 'User::getNewtalk';
632 $this->loadFromDatabase();
634 # Load the newtalk status if it is unloaded (mNewtalk=-1)
635 if( $this->mNewtalk
== -1 ) {
636 $this->mNewtalk
= 0; # reset talk page status
638 # Check memcached separately for anons, who have no
639 # entire User object stored in there.
641 global $wgDBname, $wgMemc;
642 $key = "$wgDBname:newtalk:ip:{$this->mName}";
643 $newtalk = $wgMemc->get( $key );
644 if( is_integer( $newtalk ) ) {
645 $this->mNewtalk
= $newtalk ?
1 : 0;
646 return (bool)$this->mNewtalk
;
650 $dbr =& wfGetDB( DB_SLAVE
);
651 $res = $dbr->select( 'watchlist',
653 array( 'wl_title' => $this->getTitleKey(),
654 'wl_namespace' => NS_USER_TALK
,
655 'wl_user' => $this->mId
,
656 'wl_notificationtimestamp != 0' ),
657 'User::getNewtalk' );
658 if( $dbr->numRows($res) > 0 ) {
661 $dbr->freeResult( $res );
664 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
668 return ( 0 != $this->mNewtalk
);
671 function setNewtalk( $val ) {
672 $this->loadFromDatabase();
673 $this->mNewtalk
= $val;
674 $this->invalidateCache();
677 function invalidateCache() {
678 global $wgClockSkewFudge;
679 $this->loadFromDatabase();
680 $this->mTouched
= wfTimestamp(TS_MW
, time() +
$wgClockSkewFudge );
681 # Don't forget to save the options after this or
682 # it won't take effect!
685 function validateCache( $timestamp ) {
686 $this->loadFromDatabase();
687 return ($timestamp >= $this->mTouched
);
692 * Will only be salted if $wgPasswordSalt is true
693 * @param string Password.
694 * @return string Salted password or clear password.
696 function addSalt( $p ) {
697 global $wgPasswordSalt;
699 return md5( "{$this->mId}-{$p}" );
705 * Encrypt a password.
706 * It can eventuall salt a password @see User::addSalt()
707 * @param string $p clear Password.
708 * @param string Encrypted password.
710 function encryptPassword( $p ) {
711 return $this->addSalt( md5( $p ) );
714 # Set the password and reset the random token
715 function setPassword( $str ) {
716 $this->loadFromDatabase();
718 $this->mPassword
= $this->encryptPassword( $str );
719 $this->mNewpassword
= '';
722 # Set the random token (used for persistent authentication)
723 function setToken( $token = false ) {
724 global $wgSecretKey, $wgProxyKey, $wgDBname;
726 if ( $wgSecretKey ) {
728 } elseif ( $wgProxyKey ) {
733 $this->mToken
= md5( $wgSecretKey . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId
);
735 $this->mToken
= $token;
740 function setCookiePassword( $str ) {
741 $this->loadFromDatabase();
742 $this->mCookiePassword
= md5( $str );
745 function setNewpassword( $str ) {
746 $this->loadFromDatabase();
747 $this->mNewpassword
= $this->encryptPassword( $str );
750 function getEmail() {
751 $this->loadFromDatabase();
752 return $this->mEmail
;
755 function getEmailAuthenticationTimestamp() {
756 $this->loadFromDatabase();
757 return $this->mEmailAuthenticated
;
760 function setEmail( $str ) {
761 $this->loadFromDatabase();
762 $this->mEmail
= $str;
765 function getRealName() {
766 $this->loadFromDatabase();
767 return $this->mRealName
;
770 function setRealName( $str ) {
771 $this->loadFromDatabase();
772 $this->mRealName
= $str;
775 function getOption( $oname ) {
776 $this->loadFromDatabase();
777 if ( array_key_exists( $oname, $this->mOptions
) ) {
778 return trim( $this->mOptions
[$oname] );
784 function setOption( $oname, $val ) {
785 $this->loadFromDatabase();
786 if ( $oname == 'skin' ) {
787 # Clear cached skin, so the new one displays immediately in Special:Preferences
788 unset( $this->mSkin
);
790 $this->mOptions
[$oname] = $val;
791 $this->invalidateCache();
794 function getRights() {
795 $this->loadFromDatabase();
796 return $this->mRights
;
800 * Get the list of explicit group memberships this user has.
801 * The implicit * and user groups are not included.
802 * @return array of strings
804 function getGroups() {
805 $this->loadFromDatabase();
806 return $this->mGroups
;
810 * Get the list of implicit group memberships this user has.
811 * This includes all explicit groups, plus 'user' if logged in
812 * and '*' for all accounts.
813 * @return array of strings
815 function getEffectiveGroups() {
816 $base = array( '*' );
817 if( $this->isLoggedIn() ) {
820 return array_merge( $base, $this->getGroups() );
824 * Remove the user from the given group.
825 * This takes immediate effect.
828 function addGroup( $group ) {
829 $dbw =& wfGetDB( DB_MASTER
);
830 $dbw->insert( 'user_groups',
832 'ug_user' => $this->getID(),
833 'ug_group' => $group,
838 $this->mGroups
= array_merge( $this->mGroups
, array( $group ) );
839 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups() );
841 $this->invalidateCache();
842 $this->saveSettings();
846 * Remove the user from the given group.
847 * This takes immediate effect.
850 function removeGroup( $group ) {
851 $dbw =& wfGetDB( DB_MASTER
);
852 $dbw->delete( 'user_groups',
854 'ug_user' => $this->getID(),
855 'ug_group' => $group,
857 'User::removeGroup' );
859 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
860 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups() );
862 $this->invalidateCache();
863 $this->saveSettings();
868 * A more legible check for non-anonymousness.
869 * Returns true if the user is not an anonymous visitor.
873 function isLoggedIn() {
874 return( $this->getID() != 0 );
878 * A more legible check for anonymousness.
879 * Returns true if the user is an anonymous visitor.
884 return !$this->isLoggedIn();
888 * Check if a user is sysop
889 * Die with backtrace. Use User:isAllowed() instead.
893 return $this->isAllowed( 'protect' );
897 function isDeveloper() {
898 return $this->isAllowed( 'siteadmin' );
902 function isBureaucrat() {
903 return $this->isAllowed( 'makesysop' );
907 * Whether the user is a bot
908 * @todo need to be migrated to the new user level management sytem
911 $this->loadFromDatabase();
912 return in_array( 'bot', $this->mRights
);
916 * Check if user is allowed to access a feature / make an action
917 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
918 * @return boolean True: action is allowed, False: action should not be allowed
920 function isAllowed($action='') {
921 $this->loadFromDatabase();
922 return in_array( $action , $this->mRights
);
926 * Load a skin if it doesn't exist or return it
927 * @todo FIXME : need to check the old failback system [AV]
929 function &getSkin() {
931 if ( ! isset( $this->mSkin
) ) {
932 $fname = 'User::getSkin';
933 wfProfileIn( $fname );
935 # get all skin names available
936 $skinNames = Skin
::getSkinNames();
939 $userSkin = $this->getOption( 'skin' );
940 if ( $userSkin == '' ) { $userSkin = 'standard'; }
942 if ( !isset( $skinNames[$userSkin] ) ) {
943 # in case the user skin could not be found find a replacement
948 # if phptal is enabled we should have monobook skin that
949 # superseed the good old SkinStandard.
950 if ( isset( $skinNames['monobook'] ) ) {
951 $fallback[0] = 'MonoBook';
954 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
955 $sn = $fallback[$userSkin];
960 # The user skin is available
961 $sn = $skinNames[$userSkin];
964 # Grab the skin class and initialise it. Each skin checks for PHPTal
965 # and will not load if it's not enabled.
966 require_once( $IP.'/skins/'.$sn.'.php' );
968 # Check if we got if not failback to default skin
969 $className = 'Skin'.$sn;
970 if( !class_exists( $className ) ) {
971 # DO NOT die if the class isn't found. This breaks maintenance
972 # scripts and can cause a user account to be unrecoverable
973 # except by SQL manipulation if a previously valid skin name
974 # is no longer valid.
975 $className = 'SkinStandard';
976 require_once( $IP.'/skins/Standard.php' );
978 $this->mSkin
=& new $className;
979 wfProfileOut( $fname );
985 * @param string $title Article title to look at
989 * Check watched status of an article
990 * @return bool True if article is watched
992 function isWatched( $title ) {
993 $wl = WatchedItem
::fromUserTitle( $this, $title );
994 return $wl->isWatched();
1000 function addWatch( $title ) {
1001 $wl = WatchedItem
::fromUserTitle( $this, $title );
1003 $this->invalidateCache();
1007 * Stop watching an article
1009 function removeWatch( $title ) {
1010 $wl = WatchedItem
::fromUserTitle( $this, $title );
1012 $this->invalidateCache();
1016 * Clear the user's notification timestamp for the given title.
1017 * If e-notif e-mails are on, they will receive notification mails on
1018 * the next change of the page if it's watched etc.
1020 function clearNotification( &$title ) {
1023 $userid = $this->getID();
1027 // Only update the timestamp if the page is being watched.
1028 // The query to find out if it is watched is cached both in memcached and per-invocation,
1029 // and when it does have to be executed, it can be on a slave
1030 // If this is the user's newtalk page, we always update the timestamp
1031 if ($title->getNamespace() == NS_USER_TALK
&&
1032 $title->getText() == $wgUser->getName())
1035 } elseif ( $this->getID() == $wgUser->getID() ) {
1036 $watched = $title->userIsWatching();
1041 // If the page is watched by the user (or may be watched), update the timestamp on any
1042 // any matching rows
1044 $dbw =& wfGetDB( DB_MASTER
);
1045 $success = $dbw->update( 'watchlist',
1047 'wl_notificationtimestamp' => 0
1048 ), array( /* WHERE */
1049 'wl_title' => $title->getDBkey(),
1050 'wl_namespace' => $title->getNamespace(),
1051 'wl_user' => $this->getID()
1052 ), 'User::clearLastVisited'
1060 * Resets all of the given user's page-change notification timestamps.
1061 * If e-notif e-mails are on, they will receive notification mails on
1062 * the next change of any watched page.
1064 * @param int $currentUser user ID number
1067 function clearAllNotifications( $currentUser ) {
1068 if( $currentUser != 0 ) {
1070 $dbw =& wfGetDB( DB_MASTER
);
1071 $success = $dbw->update( 'watchlist',
1073 'wl_notificationtimestamp' => 0
1074 ), array( /* WHERE */
1075 'wl_user' => $currentUser
1076 ), 'UserMailer::clearAll'
1079 # we also need to clear here the "you have new message" notification for the own user_talk page
1080 # This is cleared one page view later in Article::viewUpdates();
1086 * @return string Encoding options
1088 function encodeOptions() {
1090 foreach ( $this->mOptions
as $oname => $oval ) {
1091 array_push( $a, $oname.'='.$oval );
1093 $s = implode( "\n", $a );
1100 function decodeOptions( $str ) {
1101 $a = explode( "\n", $str );
1102 foreach ( $a as $s ) {
1103 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1104 $this->mOptions
[$m[1]] = $m[2];
1109 function setCookies() {
1110 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
1111 if ( 0 == $this->mId
) return;
1112 $this->loadFromDatabase();
1113 $exp = time() +
$wgCookieExpiration;
1115 $_SESSION['wsUserID'] = $this->mId
;
1116 setcookie( $wgDBname.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain );
1118 $_SESSION['wsUserName'] = $this->mName
;
1119 setcookie( $wgDBname.'UserName', $this->mName
, $exp, $wgCookiePath, $wgCookieDomain );
1121 $_SESSION['wsToken'] = $this->mToken
;
1122 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1123 setcookie( $wgDBname.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain );
1125 setcookie( $wgDBname.'Token', '', time() - 3600 );
1131 * It will clean the session cookie
1134 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1135 $this->loadDefaults();
1136 $this->setLoaded( true );
1138 $_SESSION['wsUserID'] = 0;
1140 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1141 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1143 # Remember when user logged out, to prevent seeing cached pages
1144 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain );
1148 * Save object settings into database
1150 function saveSettings() {
1151 global $wgMemc, $wgDBname;
1152 $fname = 'User::saveSettings';
1154 $dbw =& wfGetDB( DB_MASTER
);
1155 if ( ! $this->getNewtalk() ) {
1156 # Delete the watchlist entry for user_talk page X watched by user X
1157 $dbw->delete( 'watchlist',
1158 array( 'wl_user' => $this->mId
,
1159 'wl_title' => $this->getTitleKey(),
1160 'wl_namespace' => NS_USER_TALK
),
1163 # Anon users have a separate memcache space for newtalk
1164 # since they don't store their own info. Trim...
1165 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1169 if ( 0 == $this->mId
) { return; }
1171 $dbw->update( 'user',
1173 'user_name' => $this->mName
,
1174 'user_password' => $this->mPassword
,
1175 'user_newpassword' => $this->mNewpassword
,
1176 'user_real_name' => $this->mRealName
,
1177 'user_email' => $this->mEmail
,
1178 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1179 'user_options' => $this->encodeOptions(),
1180 'user_touched' => $dbw->timestamp($this->mTouched
),
1181 'user_token' => $this->mToken
1182 ), array( /* WHERE */
1183 'user_id' => $this->mId
1186 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
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();
1230 function spreadBlock() {
1232 # If the (non-anonymous) user is blocked, this function will block any IP address
1233 # that they successfully log on from.
1234 $fname = 'User::spreadBlock';
1236 wfDebug( "User:spreadBlock()\n" );
1237 if ( $this->mId
== 0 ) {
1241 $userblock = Block
::newFromDB( '', $this->mId
);
1242 if ( !$userblock->isValid() ) {
1246 # Check if this IP address is already blocked
1247 $ipblock = Block
::newFromDB( $wgIP );
1248 if ( $ipblock->isValid() ) {
1249 # Just update the timestamp
1250 $ipblock->updateTimestamp();
1254 # Make a new block object with the desired properties
1255 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1256 $ipblock->mAddress
= $wgIP;
1257 $ipblock->mUser
= 0;
1258 $ipblock->mBy
= $userblock->mBy
;
1259 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1260 $ipblock->mTimestamp
= wfTimestampNow();
1261 $ipblock->mAuto
= 1;
1262 # If the user is already blocked with an expiry date, we don't
1263 # want to pile on top of that!
1264 if($userblock->mExpiry
) {
1265 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1267 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1275 function getPageRenderingHash() {
1278 return $this->mHash
;
1281 // stubthreshold is only included below for completeness,
1282 // it will always be 0 when this function is called by parsercache.
1284 $confstr = $this->getOption( 'math' );
1285 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1286 $confstr .= '!' . $this->getOption( 'editsection' );
1287 $confstr .= '!' . $this->getOption( 'date' );
1288 $confstr .= '!' . $this->getOption( 'numberheadings' );
1289 $confstr .= '!' . $this->getOption( 'language' );
1290 $confstr .= '!' . $this->getOption( 'thumbsize' );
1291 // add in language specific options, if any
1292 $extra = $wgContLang->getExtraHashOptions();
1295 $this->mHash
= $confstr;
1299 function isAllowedToCreateAccount() {
1300 return $this->isAllowed( 'createaccount' );
1304 * Set mDataLoaded, return previous value
1305 * Use this to prevent DB access in command-line scripts or similar situations
1307 function setLoaded( $loaded ) {
1308 return wfSetVar( $this->mDataLoaded
, $loaded );
1312 * Get this user's personal page title.
1317 function getUserPage() {
1318 return Title
::makeTitle( NS_USER
, $this->mName
);
1322 * Get this user's talk page title.
1327 function getTalkPage() {
1328 $title = $this->getUserPage();
1329 return $title->getTalkPage();
1335 function getMaxID() {
1336 $dbr =& wfGetDB( DB_SLAVE
);
1337 return $dbr->selectField( 'user', 'max(user_id)', false );
1341 * Determine whether the user is a newbie. Newbies are either
1342 * anonymous IPs, or the 1% most recently created accounts.
1343 * Bots and sysops are excluded.
1344 * @return bool True if it is a newbie.
1346 function isNewbie() {
1347 return $this->isAnon() ||
$this->mId
> User
::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot();
1351 * Check to see if the given clear-text password is one of the accepted passwords
1352 * @param string $password User password.
1353 * @return bool True if the given password is correct otherwise False.
1355 function checkPassword( $password ) {
1356 global $wgAuth, $wgMinimalPasswordLength;
1357 $this->loadFromDatabase();
1359 // Even though we stop people from creating passwords that
1360 // are shorter than this, doesn't mean people wont be able
1361 // to. Certain authentication plugins do NOT want to save
1362 // domain passwords in a mysql database, so we should
1363 // check this (incase $wgAuth->strict() is false).
1364 if( strlen( $password ) < $wgMinimalPasswordLength ) {
1368 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1370 } elseif( $wgAuth->strict() ) {
1371 /* Auth plugin doesn't allow local authentication */
1374 $ep = $this->encryptPassword( $password );
1375 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
1377 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
1379 } elseif ( function_exists( 'iconv' ) ) {
1380 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1381 # Check for this with iconv
1382 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1383 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
1391 * Initialize (if necessary) and return a session token value
1392 * which can be used in edit forms to show that the user's
1393 * login credentials aren't being hijacked with a foreign form
1396 * @param mixed $salt - Optional function-specific data for hash.
1397 * Use a string or an array of strings.
1401 function editToken( $salt = '' ) {
1402 if( !isset( $_SESSION['wsEditToken'] ) ) {
1403 $token = $this->generateToken();
1404 $_SESSION['wsEditToken'] = $token;
1406 $token = $_SESSION['wsEditToken'];
1408 if( is_array( $salt ) ) {
1409 $salt = implode( '|', $salt );
1411 return md5( $token . $salt );
1415 * Generate a hex-y looking random token for various uses.
1416 * Could be made more cryptographically sure if someone cares.
1419 function generateToken( $salt = '' ) {
1420 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1421 return md5( $token . $salt );
1425 * Check given value against the token value stored in the session.
1426 * A match should confirm that the form was submitted from the
1427 * user's own login session, not a form submission from a third-party
1430 * @param string $val - the input value to compare
1431 * @param string $salt - Optional function-specific data for hash
1435 function matchEditToken( $val, $salt = '' ) {
1436 return ( $val == $this->editToken( $salt ) );
1440 * Generate a new e-mail confirmation token and send a confirmation
1441 * mail to the user's given address.
1443 * @return mixed True on success, a WikiError object on failure.
1445 function sendConfirmationMail() {
1446 global $wgIP, $wgContLang;
1447 $url = $this->confirmationTokenUrl( $expiration );
1448 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1449 wfMsg( 'confirmemail_body',
1453 $wgContLang->timeanddate( $expiration, false ) ) );
1457 * Send an e-mail to this user's account. Does not check for
1458 * confirmed status or validity.
1460 * @param string $subject
1461 * @param string $body
1462 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1463 * @return mixed True on success, a WikiError object on failure.
1465 function sendMail( $subject, $body, $from = null ) {
1466 if( is_null( $from ) ) {
1467 global $wgPasswordSender;
1468 $from = $wgPasswordSender;
1471 require_once( 'UserMailer.php' );
1472 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1474 if( $error == '' ) {
1477 return new WikiError( $error );
1482 * Generate, store, and return a new e-mail confirmation code.
1483 * A hash (unsalted since it's used as a key) is stored.
1484 * @param &$expiration mixed output: accepts the expiration time
1488 function confirmationToken( &$expiration ) {
1489 $fname = 'User::confirmationToken';
1492 $expires = $now +
7 * 24 * 60 * 60;
1493 $expiration = wfTimestamp( TS_MW
, $expires );
1495 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
1496 $hash = md5( $token );
1498 $dbw =& wfGetDB( DB_MASTER
);
1499 $dbw->update( 'user',
1500 array( 'user_email_token' => $hash,
1501 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1502 array( 'user_id' => $this->mId
),
1509 * Generate and store a new e-mail confirmation token, and return
1510 * the URL the user can use to confirm.
1511 * @param &$expiration mixed output: accepts the expiration time
1515 function confirmationTokenUrl( &$expiration ) {
1516 $token = $this->confirmationToken( $expiration );
1517 $title = Title
::makeTitle( NS_SPECIAL
, 'Confirmemail/' . $token );
1518 return $title->getFullUrl();
1522 * Mark the e-mail address confirmed and save.
1524 function confirmEmail() {
1525 $this->loadFromDatabase();
1526 $this->mEmailAuthenticated
= wfTimestampNow();
1527 $this->saveSettings();
1532 * Is this user allowed to send e-mails within limits of current
1533 * site configuration?
1536 function canSendEmail() {
1537 return $this->isEmailConfirmed();
1541 * Is this user allowed to receive e-mails within limits of current
1542 * site configuration?
1545 function canReceiveEmail() {
1546 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1550 * Is this user's e-mail address valid-looking and confirmed within
1551 * limits of the current site configuration?
1553 * If $wgEmailAuthentication is on, this may require the user to have
1554 * confirmed their address by returning a code or using a password
1555 * sent to the address from the wiki.
1559 function isEmailConfirmed() {
1560 global $wgEmailAuthentication;
1561 $this->loadFromDatabase();
1562 if( $this->isAnon() )
1564 if( !$this->isValidEmailAddr( $this->mEmail
) )
1566 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
1572 * @param array $groups list of groups
1573 * @return array list of permission key names for given groups combined
1576 function getGroupPermissions( $groups ) {
1577 global $wgGroupPermissions;
1579 foreach( $groups as $group ) {
1580 if( isset( $wgGroupPermissions[$group] ) ) {
1581 $rights = array_merge( $rights,
1582 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
1589 * @param string $group key name
1590 * @return string localized descriptive name, if provided
1593 function getGroupName( $group ) {
1594 $key = "group-$group-name";
1595 $name = wfMsg( $key );
1596 if( $name == '' ||
$name == "<$key>" ) {
1604 * Return the set of defined explicit groups.
1605 * The * and 'user' groups are not included.
1609 function getAllGroups() {
1610 global $wgGroupPermissions;
1612 array_keys( $wgGroupPermissions ),
1613 array( '*', 'user' ) );