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 $mEmailAuthenticationtimestamp;
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
47 * @param string $name Username, validated by Title:newFromText()
49 function newFromName( $name ) {
52 # Clean up name according to title rules
54 $t = Title
::newFromText( $name );
58 $u->setName( $t->getText() );
59 $u->setId( $u->idFromName( $t->getText() ) );
65 * Get username given an id.
66 * @param integer $id Database user id
67 * @return string Nickname of a user
70 function whoIs( $id ) {
71 $dbr =& wfGetDB( DB_SLAVE
);
72 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
76 * Get real username given an id.
77 * @param integer $id Database user id
78 * @return string Realname of a user
81 function whoIsReal( $id ) {
82 $dbr =& wfGetDB( DB_SLAVE
);
83 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
87 * Get database id given a user name
88 * @param string $name Nickname of a user
89 * @return integer|null Database user id (null: if non existent
92 function idFromName( $name ) {
93 $fname = "User::idFromName";
95 $nt = Title
::newFromText( $name );
96 if( is_null( $nt ) ) {
100 $dbr =& wfGetDB( DB_SLAVE
);
101 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
103 if ( $s === false ) {
111 * does the string match an anonymous user IP address?
112 * @param string $name Nickname of a user
115 function isIP( $name ) {
116 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
120 * does the string match roughly an email address ?
121 * @param string $addr email address
124 function isValidEmailAddr ( $addr ) {
125 return preg_match( '/^([a-z0-9_.-]+([a-z0-9_.-]+)*\@[a-z0-9_-]+([a-z0-9_.-]+)*([a-z.]{2,})+)$/', strtolower($addr));
129 * probably return a random password
130 * @return string probably a random password
132 * @todo Check what is doing really [AV]
134 function randomPassword() {
135 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
136 $l = strlen( $pwchars ) - 1;
138 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
139 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
140 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
141 $pwchars{mt_rand( 0, $l )};
146 * Set properties to default
147 * Used at construction. It will load per language default settings only
148 * if we have an available language object.
150 function loadDefaults() {
153 $fname = 'User::loadDefaults' . $n;
154 wfProfileIn( $fname );
156 global $wgContLang, $wgIP, $wgDBname;
157 global $wgNamespacesToBeSearchedDefault;
160 $this->mNewtalk
= -1;
161 $this->mName
= $wgIP;
162 $this->mRealName
= $this->mEmail
= '';
163 $this->mEmailAuthenticationtimestamp
= 0;
164 $this->mPassword
= $this->mNewpassword
= '';
165 $this->mRights
= array();
166 $this->mGroups
= array();
167 // Getting user defaults only if we have an available language
168 if( isset( $wgContLang ) ) {
169 $this->loadDefaultFromLanguage();
172 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
173 $this->mOptions
['searchNs'.$nsnum] = $val;
175 unset( $this->mSkin
);
176 $this->mDataLoaded
= false;
177 $this->mBlockedby
= -1; # Unset
178 $this->setToken(); # Random
179 $this->mHash
= false;
181 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
182 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgDBname.'LoggedOut'] );
185 $this->mTouched
= '0'; # Allow any pages to be cached
188 wfProfileOut( $fname );
192 * Used to load user options from a language.
193 * This is not in loadDefault() cause we sometime create user before having
196 function loadDefaultFromLanguage(){
197 $this->mOptions
= User
::getDefaultOptions();
201 * Combine the language default options with any site-specific options
202 * and add the default language variants.
208 function getDefaultOptions() {
210 * Site defaults will override the global/language defaults
212 global $wgContLang, $wgDefaultUserOptions;
213 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptions();
216 * default language setting
218 $variant = $wgContLang->getPreferredVariant();
219 $defOpt['variant'] = $variant;
220 $defOpt['language'] = $variant;
226 * Get a given default option value.
233 function getDefaultOption( $opt ) {
234 $defOpts = User
::getDefaultOptions();
235 if( isset( $defOpts[$opt] ) ) {
236 return $defOpts[$opt];
243 * Get blocking information
245 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
246 * non-critical checks are done against slaves. Check when actually saving should be done against
249 * Note that even if $bFromSlave is false, the check is done first against slave, then master.
250 * The logic is that if blocked on slave, we'll assume it's either blocked on master or
251 * just slightly outta sync and soon corrected - safer to block slightly more that less.
252 * And it's cheaper to check slave first, then master if needed, than master always.
254 function getBlockedStatus( $bFromSlave = false ) {
255 global $wgIP, $wgBlockCache, $wgProxyList;
257 if ( -1 != $this->mBlockedby
) { return; }
259 $this->mBlockedby
= 0;
263 $block = new Block();
264 $block->forUpdate( $bFromSlave );
265 if ( $block->load( $wgIP , $this->mId
) ) {
266 $this->mBlockedby
= $block->mBy
;
267 $this->mBlockreason
= $block->mReason
;
272 if ( !$this->mBlockedby
) {
273 # Check first against slave, and optionally from master.
274 $block = $wgBlockCache->get( $wgIP, true );
275 if ( !$block && !$bFromSlave )
277 # Not blocked: check against master, to make sure.
278 $wgBlockCache->clearLocal( );
279 $block = $wgBlockCache->get( $wgIP, false );
281 if ( $block !== false ) {
282 $this->mBlockedby
= $block->mBy
;
283 $this->mBlockreason
= $block->mReason
;
288 if ( !$this->mBlockedby
) {
289 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
290 $this->mBlockedby
= wfMsg( 'proxyblocker' );
291 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
297 * Check if user is blocked
298 * @return bool True if blocked, false otherwise
300 function isBlocked( $bFromSlave = false ) {
301 $this->getBlockedStatus( $bFromSlave );
302 if ( 0 === $this->mBlockedby
) { return false; }
307 * Get name of blocker
308 * @return string name of blocker
310 function blockedBy() {
311 $this->getBlockedStatus();
312 return $this->mBlockedby
;
316 * Get blocking reason
317 * @return string Blocking reason
319 function blockedFor() {
320 $this->getBlockedStatus();
321 return $this->mBlockreason
;
325 * Initialise php session
327 function SetupSession() {
328 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
329 if( $wgSessionsInMemcached ) {
330 require_once( 'MemcachedSessions.php' );
331 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
332 # If it's left on 'user' or another setting from another
333 # application, it will end up failing. Try to recover.
334 ini_set ( 'session.save_handler', 'files' );
336 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
337 session_cache_limiter( 'private, must-revalidate' );
342 * Read datas from session
345 function loadFromSession() {
346 global $wgMemc, $wgDBname;
348 if ( isset( $_SESSION['wsUserID'] ) ) {
349 if ( 0 != $_SESSION['wsUserID'] ) {
350 $sId = $_SESSION['wsUserID'];
354 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
355 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
356 $_SESSION['wsUserID'] = $sId;
360 if ( isset( $_SESSION['wsUserName'] ) ) {
361 $sName = $_SESSION['wsUserName'];
362 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
363 $sName = $_COOKIE["{$wgDBname}UserName"];
364 $_SESSION['wsUserName'] = $sName;
369 $passwordCorrect = FALSE;
370 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
371 if($makenew = !$user) {
372 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
375 $user->loadFromDatabase();
377 wfDebug( "User::loadFromSession() got from cache!\n" );
380 if ( isset( $_SESSION['wsToken'] ) ) {
381 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken
;
382 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
383 $passwordCorrect = $user->mToken
== $_COOKIE["{$wgDBname}Token"];
385 return new User(); # Can't log in from session
388 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
390 if($wgMemc->set( $key, $user ))
391 wfDebug( "User::loadFromSession() successfully saved user\n" );
393 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
395 $user->spreadBlock();
398 return new User(); # Can't log in from session
402 * Load a user from the database
404 function loadFromDatabase() {
405 global $wgCommandLineMode, $wgAnonGroupId, $wgLoggedInGroupId;
406 $fname = "User::loadFromDatabase";
408 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
409 # loading in a command line script, don't assume all command line scripts need it like this
410 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
411 if ( $this->mDataLoaded
) {
416 $this->mId
= IntVal( $this->mId
);
418 /** Anonymous user */
421 $anong = Group
::newFromId($wgAnonGroupId);
423 wfDebugDieBacktrace("Please update your database schema "
424 ."and populate initial group data from "
425 ."maintenance/archives patches");
426 $anong->loadFromDatabase();
427 $this->mRights
= explode(',', $anong->getRights());
428 $this->mDataLoaded
= true;
430 } # the following stuff is for non-anonymous users only
432 $dbr =& wfGetDB( DB_SLAVE
);
433 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
434 'user_emailauthenticationtimestamp',
435 'user_real_name','user_options','user_touched', 'user_token' ),
436 array( 'user_id' => $this->mId
), $fname );
438 if ( $s !== false ) {
439 $this->mName
= $s->user_name
;
440 $this->mEmail
= $s->user_email
;
441 $this->mEmailAuthenticationtimestamp
= wfTimestamp(TS_MW
,$s->user_emailauthenticationtimestamp
);
442 $this->mRealName
= $s->user_real_name
;
443 $this->mPassword
= $s->user_password
;
444 $this->mNewpassword
= $s->user_newpassword
;
445 $this->decodeOptions( $s->user_options
);
446 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
447 $this->mToken
= $s->user_token
;
450 $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId
) );
452 while($group = $dbr->fetchRow($res)) {
453 $this->mGroups
[] = $group[0];
456 // add the default group for logged in user
457 $this->mGroups
[] = $wgLoggedInGroupId;
459 $this->mRights
= array();
460 // now we merge groups rights to get this user rights
461 foreach($this->mGroups
as $aGroupId) {
462 $g = Group
::newFromId($aGroupId);
463 $g->loadFromDatabase();
464 $this->mRights
= array_merge($this->mRights
, explode(',', $g->getRights()));
467 // array merge duplicate rights which are part of several groups
468 $this->mRights
= array_unique($this->mRights
);
470 $dbr->freeResult($res);
473 $this->mDataLoaded
= true;
476 function getID() { return $this->mId
; }
477 function setID( $v ) {
479 $this->mDataLoaded
= false;
483 $this->loadFromDatabase();
487 function setName( $str ) {
488 $this->loadFromDatabase();
494 * Return the title dbkey form of the name, for eg user pages.
498 function getTitleKey() {
499 return str_replace( ' ', '_', $this->getName() );
502 function getNewtalk() {
503 $fname = 'User::getNewtalk';
504 $this->loadFromDatabase();
506 # Load the newtalk status if it is unloaded (mNewtalk=-1)
507 if( $this->mNewtalk
== -1 ) {
508 $this->mNewtalk
= 0; # reset talk page status
510 # Check memcached separately for anons, who have no
511 # entire User object stored in there.
513 global $wgDBname, $wgMemc;
514 $key = "$wgDBname:newtalk:ip:{$this->mName}";
515 $newtalk = $wgMemc->get( $key );
516 if( is_integer( $newtalk ) ) {
517 $this->mNewtalk
= $newtalk ?
1 : 0;
518 return (bool)$this->mNewtalk
;
522 $dbr =& wfGetDB( DB_SLAVE
);
523 $res = $dbr->select( 'watchlist',
525 array( 'wl_title' => $this->getTitleKey(),
526 'wl_namespace' => NS_USER_TALK
,
527 'wl_user' => $this->mId
,
528 'wl_notificationtimestamp != 0' ),
529 'User::getNewtalk' );
530 if( $dbr->numRows($res) > 0 ) {
533 $dbr->freeResult( $res );
536 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
540 return ( 0 != $this->mNewtalk
);
543 function setNewtalk( $val ) {
544 $this->loadFromDatabase();
545 $this->mNewtalk
= $val;
546 $this->invalidateCache();
549 function invalidateCache() {
550 $this->loadFromDatabase();
551 $this->mTouched
= wfTimestampNow();
552 # Don't forget to save the options after this or
553 # it won't take effect!
556 function validateCache( $timestamp ) {
557 $this->loadFromDatabase();
558 return ($timestamp >= $this->mTouched
);
563 * Will only be salted if $wgPasswordSalt is true
564 * @param string Password.
565 * @return string Salted password or clear password.
567 function addSalt( $p ) {
568 global $wgPasswordSalt;
570 return md5( "{$this->mId}-{$p}" );
576 * Encrypt a password.
577 * It can eventuall salt a password @see User::addSalt()
578 * @param string $p clear Password.
579 * @param string Encrypted password.
581 function encryptPassword( $p ) {
582 return $this->addSalt( md5( $p ) );
585 # Set the password and reset the random token
586 function setPassword( $str ) {
587 $this->loadFromDatabase();
589 $this->mPassword
= $this->encryptPassword( $str );
590 $this->mNewpassword
= '';
593 # Set the random token (used for persistent authentication)
594 function setToken( $token = false ) {
597 # Take random data from PRNG
598 # This is reasonably secure if the PRNG has been seeded correctly
599 for ($i = 0; $i<USER_TOKEN_LENGTH
/ 4; $i++
) {
600 $this->mToken
.= sprintf( "%04X", mt_rand( 0, 65535 ) );
603 $this->mToken
= $token;
608 function setCookiePassword( $str ) {
609 $this->loadFromDatabase();
610 $this->mCookiePassword
= md5( $str );
613 function setNewpassword( $str ) {
614 $this->loadFromDatabase();
615 $this->mNewpassword
= $this->encryptPassword( $str );
618 function getEmail() {
619 $this->loadFromDatabase();
620 return $this->mEmail
;
623 function getEmailAuthenticationtimestamp() {
624 $this->loadFromDatabase();
625 return $this->mEmailAuthenticationtimestamp
;
628 function setEmail( $str ) {
629 $this->loadFromDatabase();
630 $this->mEmail
= $str;
633 function getRealName() {
634 $this->loadFromDatabase();
635 return $this->mRealName
;
638 function setRealName( $str ) {
639 $this->loadFromDatabase();
640 $this->mRealName
= $str;
643 function getOption( $oname ) {
644 $this->loadFromDatabase();
645 if ( array_key_exists( $oname, $this->mOptions
) ) {
646 return $this->mOptions
[$oname];
652 function setOption( $oname, $val ) {
653 $this->loadFromDatabase();
654 if ( $oname == 'skin' ) {
655 # Clear cached skin, so the new one displays immediately in Special:Preferences
656 unset( $this->mSkin
);
658 $this->mOptions
[$oname] = $val;
659 $this->invalidateCache();
662 function getRights() {
663 $this->loadFromDatabase();
664 return $this->mRights
;
667 function addRight( $rname ) {
668 $this->loadFromDatabase();
669 array_push( $this->mRights
, $rname );
670 $this->invalidateCache();
673 function getGroups() {
674 $this->loadFromDatabase();
675 return $this->mGroups
;
678 function setGroups($groups) {
679 $this->loadFromDatabase();
680 $this->mGroups
= $groups;
681 $this->invalidateCache();
685 * A more legible check for non-anonymousness.
686 * Returns true if the user is not an anonymous visitor.
690 function isLoggedIn() {
691 return( $this->getID() != 0 );
695 * A more legible check for anonymousness.
696 * Returns true if the user is an anonymous visitor.
701 return !$this->isLoggedIn();
705 * Check if a user is sysop
706 * Die with backtrace. Use User:isAllowed() instead.
711 $this->loadFromDatabase();
712 if ( 0 == $this->mId ) { return false; }
714 return in_array( 'sysop', $this->mRights );
716 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
720 function isDeveloper() {
722 $this->loadFromDatabase();
723 if ( 0 == $this->mId ) { return false; }
725 return in_array( 'developer', $this->mRights );
727 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
731 function isBureaucrat() {
733 $this->loadFromDatabase();
734 if ( 0 == $this->mId ) { return false; }
736 return in_array( 'bureaucrat', $this->mRights );
738 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
742 * Whether the user is a bot
743 * @todo need to be migrated to the new user level management sytem
746 $this->loadFromDatabase();
748 # Why was this here? I need a UID=0 conversion script [TS]
749 # if ( 0 == $this->mId ) { return false; }
751 return in_array( 'bot', $this->mRights
);
755 * Check if user is allowed to access a feature / make an action
756 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
757 * @return boolean True: action is allowed, False: action should not be allowed
759 function isAllowed($action='') {
760 $this->loadFromDatabase();
761 return in_array( $action , $this->mRights
);
765 * Load a skin if it doesn't exist or return it
766 * @todo FIXME : need to check the old failback system [AV]
768 function &getSkin() {
770 if ( ! isset( $this->mSkin
) ) {
771 $fname = 'User::getSkin';
772 wfProfileIn( $fname );
774 # get all skin names available
775 $skinNames = Skin
::getSkinNames();
778 $userSkin = $this->getOption( 'skin' );
779 if ( $userSkin == '' ) { $userSkin = 'standard'; }
781 if ( !isset( $skinNames[$userSkin] ) ) {
782 # in case the user skin could not be found find a replacement
787 # if phptal is enabled we should have monobook skin that
788 # superseed the good old SkinStandard.
789 if ( isset( $skinNames['monobook'] ) ) {
790 $fallback[0] = 'MonoBook';
793 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
794 $sn = $fallback[$userSkin];
799 # The user skin is available
800 $sn = $skinNames[$userSkin];
803 # Grab the skin class and initialise it. Each skin checks for PHPTal
804 # and will not load if it's not enabled.
805 require_once( $IP.'/skins/'.$sn.'.php' );
807 # Check if we got if not failback to default skin
808 $className = 'Skin'.$sn;
809 if( !class_exists( $className ) ) {
810 # DO NOT die if the class isn't found. This breaks maintenance
811 # scripts and can cause a user account to be unrecoverable
812 # except by SQL manipulation if a previously valid skin name
813 # is no longer valid.
814 $className = 'SkinStandard';
815 require_once( $IP.'/skins/Standard.php' );
817 $this->mSkin
=& new $className;
818 wfProfileOut( $fname );
824 * @param string $title Article title to look at
828 * Check watched status of an article
829 * @return bool True if article is watched
831 function isWatched( $title ) {
832 $wl = WatchedItem
::fromUserTitle( $this, $title );
833 return $wl->isWatched();
839 function addWatch( $title ) {
840 $wl = WatchedItem
::fromUserTitle( $this, $title );
842 $this->invalidateCache();
846 * Stop watching an article
848 function removeWatch( $title ) {
849 $wl = WatchedItem
::fromUserTitle( $this, $title );
851 $this->invalidateCache();
855 * Clear the user's notification timestamp for the given title.
856 * If e-notif e-mails are on, they will receive notification mails on
857 * the next change of the page if it's watched etc.
859 function clearNotification( $title ) {
860 $userid = $this->getId();
863 $dbw =& wfGetDB( DB_MASTER
);
864 $success = $dbw->update( 'watchlist',
866 'wl_notificationtimestamp' => $dbw->timestamp(0)
867 ), array( /* WHERE */
868 'wl_title' => $title->getDBkey(),
869 'wl_namespace' => $title->getNamespace(),
870 'wl_user' => $this->getId()
871 ), 'User::clearLastVisited'
878 * Resets all of the given user's page-change notification timestamps.
879 * If e-notif e-mails are on, they will receive notification mails on
880 * the next change of any watched page.
882 * @param int $currentUser user ID number
885 function clearAllNotifications( $currentUser ) {
886 if( $currentUser != 0 ) {
888 $dbw =& wfGetDB( DB_MASTER
);
889 $success = $dbw->update( 'watchlist',
891 'wl_notificationtimestamp' => 0
892 ), array( /* WHERE */
893 'wl_user' => $currentUser
894 ), 'UserMailer::clearAll'
897 # we also need to clear here the "you have new message" notification for the own user_talk page
898 # This is cleared one page view later in Article::viewUpdates();
904 * @return string Encoding options
906 function encodeOptions() {
908 foreach ( $this->mOptions
as $oname => $oval ) {
909 array_push( $a, $oname.'='.$oval );
911 $s = implode( "\n", $a );
918 function decodeOptions( $str ) {
919 $a = explode( "\n", $str );
920 foreach ( $a as $s ) {
921 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
922 $this->mOptions
[$m[1]] = $m[2];
927 function setCookies() {
928 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
929 if ( 0 == $this->mId
) return;
930 $this->loadFromDatabase();
931 $exp = time() +
$wgCookieExpiration;
933 $_SESSION['wsUserID'] = $this->mId
;
934 setcookie( $wgDBname.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain );
936 $_SESSION['wsUserName'] = $this->mName
;
937 setcookie( $wgDBname.'UserName', $this->mName
, $exp, $wgCookiePath, $wgCookieDomain );
939 $_SESSION['wsToken'] = $this->mToken
;
940 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
941 setcookie( $wgDBname.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain );
943 setcookie( $wgDBname.'Token', '', time() - 3600 );
949 * It will clean the session cookie
952 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
953 $this->loadDefaults();
954 $this->setLoaded( true );
956 $_SESSION['wsUserID'] = 0;
958 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
959 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
961 # Remember when user logged out, to prevent seeing cached pages
962 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain );
966 * Save object settings into database
968 function saveSettings() {
969 global $wgMemc, $wgDBname;
970 $fname = 'User::saveSettings';
972 $dbw =& wfGetDB( DB_MASTER
);
973 if ( ! $this->getNewtalk() ) {
974 # Delete the watchlist entry for user_talk page X watched by user X
975 $dbw->delete( 'watchlist',
976 array( 'wl_user' => $this->mId
,
977 'wl_title' => $this->getTitleKey(),
978 'wl_namespace' => NS_USER_TALK
),
981 # Anon users have a separate memcache space for newtalk
982 # since they don't store their own info. Trim...
983 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
987 if ( 0 == $this->mId
) { return; }
989 $dbw->update( 'user',
991 'user_name' => $this->mName
,
992 'user_password' => $this->mPassword
,
993 'user_newpassword' => $this->mNewpassword
,
994 'user_real_name' => $this->mRealName
,
995 'user_email' => $this->mEmail
,
996 'user_emailauthenticationtimestamp' => $dbw->timestamp($this->mEmailAuthenticationtimestamp
),
997 'user_options' => $this->encodeOptions(),
998 'user_touched' => $dbw->timestamp($this->mTouched
),
999 'user_token' => $this->mToken
1000 ), array( /* WHERE */
1001 'user_id' => $this->mId
1004 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights
),
1005 'ur_user='. $this->mId
, $fname );
1006 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1008 // delete old groups
1009 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId
), $fname);
1012 foreach ($this->mGroups
as $group) {
1013 $dbw->replace( 'user_groups',
1014 array(array('ug_user','ug_group')),
1016 'ug_user' => $this->mId
,
1017 'ug_group' => $group
1025 * Checks if a user with the given name exists, returns the ID
1027 function idForName() {
1028 $fname = 'User::idForName';
1031 $s = trim( $this->mName
);
1032 if ( 0 == strcmp( '', $s ) ) return 0;
1034 $dbr =& wfGetDB( DB_SLAVE
);
1035 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1036 if ( $id === false ) {
1043 * Add user object to the database
1045 function addToDatabase() {
1046 $fname = 'User::addToDatabase';
1047 $dbw =& wfGetDB( DB_MASTER
);
1048 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1049 $dbw->insert( 'user',
1051 'user_id' => $seqVal,
1052 'user_name' => $this->mName
,
1053 'user_password' => $this->mPassword
,
1054 'user_newpassword' => $this->mNewpassword
,
1055 'user_email' => $this->mEmail
,
1056 'user_emailauthenticationtimestamp' => $dbw->timestamp($this->mEmailAuthenticationtimestamp
),
1057 'user_real_name' => $this->mRealName
,
1058 'user_options' => $this->encodeOptions(),
1059 'user_token' => $this->mToken
1062 $this->mId
= $dbw->insertId();
1063 $dbw->insert( 'user_rights',
1065 'ur_user' => $this->mId
,
1066 'ur_rights' => implode( ',', $this->mRights
)
1070 foreach ($this->mGroups
as $group) {
1071 $dbw->insert( 'user_groups',
1073 'ug_user' => $this->mId
,
1074 'ug_group' => $group
1080 function spreadBlock() {
1082 # If the (non-anonymous) user is blocked, this function will block any IP address
1083 # that they successfully log on from.
1084 $fname = 'User::spreadBlock';
1086 wfDebug( "User:spreadBlock()\n" );
1087 if ( $this->mId
== 0 ) {
1091 $userblock = Block
::newFromDB( '', $this->mId
);
1092 if ( !$userblock->isValid() ) {
1096 # Check if this IP address is already blocked
1097 $ipblock = Block
::newFromDB( $wgIP );
1098 if ( $ipblock->isValid() ) {
1099 # Just update the timestamp
1100 $ipblock->updateTimestamp();
1104 # Make a new block object with the desired properties
1105 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1106 $ipblock->mAddress
= $wgIP;
1107 $ipblock->mUser
= 0;
1108 $ipblock->mBy
= $userblock->mBy
;
1109 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1110 $ipblock->mTimestamp
= wfTimestampNow();
1111 $ipblock->mAuto
= 1;
1112 # If the user is already blocked with an expiry date, we don't
1113 # want to pile on top of that!
1114 if($userblock->mExpiry
) {
1115 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1117 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1125 function getPageRenderingHash() {
1128 return $this->mHash
;
1131 // stubthreshold is only included below for completeness,
1132 // it will always be 0 when this function is called by parsercache.
1134 $confstr = $this->getOption( 'math' );
1135 $confstr .= '!' . $this->getOption( 'highlightbroken' );
1136 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1137 $confstr .= '!' . $this->getOption( 'editsection' );
1138 $confstr .= '!' . $this->getOption( 'editsectiononrightclick' );
1139 $confstr .= '!' . $this->getOption( 'showtoc' );
1140 $confstr .= '!' . $this->getOption( 'date' );
1141 $confstr .= '!' . $this->getOption( 'numberheadings' );
1142 $confstr .= '!' . $this->getOption( 'language' );
1143 // add in language specific options, if any
1144 $extra = $wgContLang->getExtraHashOptions();
1147 $this->mHash
= $confstr;
1151 function isAllowedToCreateAccount() {
1152 global $wgWhitelistAccount;
1155 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1156 foreach ($wgWhitelistAccount as $right => $ok) {
1157 $userHasRight = (!strcmp($right, 'user') ||
in_array($right, $this->getRights()));
1158 $allowed |
= ($ok && $userHasRight);
1164 * Set mDataLoaded, return previous value
1165 * Use this to prevent DB access in command-line scripts or similar situations
1167 function setLoaded( $loaded ) {
1168 return wfSetVar( $this->mDataLoaded
, $loaded );
1172 * Get this user's personal page title.
1177 function getUserPage() {
1178 return Title
::makeTitle( NS_USER
, $this->mName
);
1182 * Get this user's talk page title.
1187 function getTalkPage() {
1188 $title = $this->getUserPage();
1189 return $title->getTalkPage();
1195 function getMaxID() {
1196 $dbr =& wfGetDB( DB_SLAVE
);
1197 return $dbr->selectField( 'user', 'max(user_id)', false );
1201 * Determine whether the user is a newbie. Newbies are either
1202 * anonymous IPs, or the 1% most recently created accounts.
1203 * Bots and sysops are excluded.
1204 * @return bool True if it is a newbie.
1206 function isNewbie() {
1207 return $this->mId
> User
::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() ||
$this->getID() == 0;
1211 * Check to see if the given clear-text password is one of the accepted passwords
1212 * @param string $password User password.
1213 * @return bool True if the given password is correct otherwise False.
1215 function checkPassword( $password ) {
1217 $this->loadFromDatabase();
1219 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1221 } elseif( $wgAuth->strict() ) {
1222 /* Auth plugin doesn't allow local authentication */
1225 $ep = $this->encryptPassword( $password );
1226 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
1228 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
1229 $this->mEmailAuthenticationtimestamp
= wfTimestampNow();
1230 $this->mNewpassword
= ''; # use the temporary one-time password only once: clear it now !
1231 $this->saveSettings();
1233 } elseif ( function_exists( 'iconv' ) ) {
1234 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1235 # Check for this with iconv
1236 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1237 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
1245 * Initialize (if necessary) and return a session token value
1246 * which can be used in edit forms to show that the user's
1247 * login credentials aren't being hijacked with a foreign form
1250 * @param mixed $salt - Optional function-specific data for hash.
1251 * Use a string or an array of strings.
1255 function editToken( $salt = '' ) {
1256 if( !isset( $_SESSION['wsEditToken'] ) ) {
1257 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1258 $_SESSION['wsEditToken'] = $token;
1260 $token = $_SESSION['wsEditToken'];
1262 if( is_array( $salt ) ) {
1263 $salt = implode( '|', $salt );
1265 return md5( $token . $salt );
1269 * Check given value against the token value stored in the session.
1270 * A match should confirm that the form was submitted from the
1271 * user's own login session, not a form submission from a third-party
1274 * @param string $val - the input value to compare
1275 * @param string $salt - Optional function-specific data for hash
1279 function matchEditToken( $val, $salt = '' ) {
1280 return ( $val == $this->editToken( $salt ) );