11 require_once( 'WatchedItem.php' );
21 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
22 var $mRights, $mOptions;
23 var $mDataLoaded, $mNewpassword;
25 var $mBlockedby, $mBlockreason;
32 /** Construct using User:loadDefaults() */
34 $this->loadDefaults();
38 * Static factory method
40 * @param string $name Username, validated by Title:newFromText()
42 function newFromName( $name ) {
45 # Clean up name according to title rules
47 $t = Title
::newFromText( $name );
48 $u->setName( $t->getText() );
53 * Get username given an id.
54 * @param integer $id Database user id
55 * @return string Nickname of a user
58 function whoIs( $id ) {
59 $dbr =& wfGetDB( DB_SLAVE
);
60 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
64 * Get real username given an id.
65 * @param integer $id Database user id
66 * @return string Realname of a user
69 function whoIsReal( $id ) {
70 $dbr =& wfGetDB( DB_SLAVE
);
71 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
75 * Get database id given a user name
76 * @param string $name Nickname of a user
77 * @return integer|null Database user id (null: if non existent
80 function idFromName( $name ) {
81 $fname = "User::idFromName";
83 $nt = Title
::newFromText( $name );
84 if( is_null( $nt ) ) {
88 $dbr =& wfGetDB( DB_SLAVE
);
89 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
99 * does the string match an anonymous user IP address?
100 * @param string $name Nickname of a user
103 function isIP( $name ) {
104 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
108 * probably return a random password
109 * @return string probably a random password
111 * @todo Check what is doing really [AV]
113 function randomPassword() {
114 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
115 $l = strlen( $pwchars ) - 1;
117 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
118 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
119 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
120 $pwchars{mt_rand( 0, $l )};
125 * Set properties to default
126 * Used at construction. It will load per language default settings only
127 * if we have an available language object.
129 function loadDefaults() {
130 global $wgLang, $wgIP;
131 global $wgNamespacesToBeSearchedDefault;
133 $this->mId
= $this->mNewtalk
= 0;
134 $this->mName
= $wgIP;
135 $this->mRealName
= $this->mEmail
= '';
136 $this->mPassword
= $this->mNewpassword
= '';
137 $this->mRights
= array();
138 // Getting user defaults only if we have an available language
139 if(isset($wgLang)) { $this->loadDefaultFromLanguage(); }
141 foreach ($wgNamespacesToBeSearchedDefault as $nsnum => $val) {
142 $this->mOptions
['searchNs'.$nsnum] = $val;
144 unset( $this->mSkin
);
145 $this->mDataLoaded
= false;
146 $this->mBlockedby
= -1; # Unset
147 $this->mTouched
= '0'; # Allow any pages to be cached
148 $this->cookiePassword
= '';
149 $this->mHash
= false;
153 * Used to load user options from a language.
154 * This is not in loadDefault() cause we sometime create user before having
157 function loadDefaultFromLanguage(){
159 $defOpt = $wgLang->getDefaultUserOptions() ;
160 foreach ( $defOpt as $oname => $val ) {
161 $this->mOptions
[$oname] = $val;
166 * Get blocking information
169 function getBlockedStatus() {
170 global $wgIP, $wgBlockCache, $wgProxyList;
172 if ( -1 != $this->mBlockedby
) { return; }
174 $this->mBlockedby
= 0;
178 $block = new Block();
179 if ( $block->load( $wgIP , $this->mId
) ) {
180 $this->mBlockedby
= $block->mBy
;
181 $this->mBlockreason
= $block->mReason
;
186 if ( !$this->mBlockedby
) {
187 $block = $wgBlockCache->get( $wgIP );
188 if ( $block !== false ) {
189 $this->mBlockedby
= $block->mBy
;
190 $this->mBlockreason
= $block->mReason
;
195 if ( !$this->mBlockedby
) {
196 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
197 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
198 $this->mBlockedby
= "Proxy blocker";
204 * Check if user is blocked
205 * @return bool True if blocked, false otherwise
207 function isBlocked() {
208 $this->getBlockedStatus();
209 if ( 0 === $this->mBlockedby
) { return false; }
214 * Get name of blocker
215 * @return string name of blocker
217 function blockedBy() {
218 $this->getBlockedStatus();
219 return $this->mBlockedby
;
223 * Get blocking reason
224 * @return string Blocking reason
226 function blockedFor() {
227 $this->getBlockedStatus();
228 return $this->mBlockreason
;
232 * Initialise php session
234 function SetupSession() {
235 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
236 if( $wgSessionsInMemcached ) {
237 require_once( 'MemcachedSessions.php' );
238 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
239 # If it's left on 'user' or another setting from another
240 # application, it will end up failing. Try to recover.
241 ini_set ( 'session.save_handler', 'files' );
243 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
244 session_cache_limiter( 'private, must-revalidate' );
249 * Read datas from session
252 function loadFromSession() {
253 global $wgMemc, $wgDBname;
255 if ( isset( $_SESSION['wsUserID'] ) ) {
256 if ( 0 != $_SESSION['wsUserID'] ) {
257 $sId = $_SESSION['wsUserID'];
261 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
262 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
263 $_SESSION['wsUserID'] = $sId;
267 if ( isset( $_SESSION['wsUserName'] ) ) {
268 $sName = $_SESSION['wsUserName'];
269 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
270 $sName = $_COOKIE["{$wgDBname}UserName"];
271 $_SESSION['wsUserName'] = $sName;
276 $passwordCorrect = FALSE;
277 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
278 if($makenew = !$user) {
279 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
282 $user->loadFromDatabase();
284 wfDebug( "User::loadFromSession() got from cache!\n" );
287 if ( isset( $_SESSION['wsUserPassword'] ) ) {
288 $passwordCorrect = $_SESSION['wsUserPassword'] == $user->mPassword
;
289 } else if ( isset( $_COOKIE["{$wgDBname}Password"] ) ) {
290 $user->mCookiePassword
= $_COOKIE["{$wgDBname}Password"];
291 $_SESSION['wsUserPassword'] = $user->addSalt( $user->mCookiePassword
);
292 $passwordCorrect = $_SESSION['wsUserPassword'] == $user->mPassword
;
294 return new User(); # Can't log in from session
297 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
299 if($wgMemc->set( $key, $user ))
300 wfDebug( "User::loadFromSession() successfully saved user\n" );
302 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
304 $user->spreadBlock();
307 return new User(); # Can't log in from session
311 * Load a user from the database
313 function loadFromDatabase() {
314 global $wgCommandLineMode;
315 $fname = "User::loadFromDatabase";
316 if ( $this->mDataLoaded ||
$wgCommandLineMode ) {
321 $this->mId
= IntVal( $this->mId
);
323 # check in separate table if there are changes to the talk page
324 $this->mNewtalk
=0; # reset talk page status
325 $dbr =& wfGetDB( DB_SLAVE
);
327 $res = $dbr->select( 'user_newtalk', 1, array( 'user_id' => $this->mId
), $fname );
329 if ( $dbr->numRows($res)>0 ) {
332 $dbr->freeResult( $res );
334 global $wgDBname, $wgMemc;
335 $key = "$wgDBname:newtalk:ip:{$this->mName}";
336 $newtalk = $wgMemc->get( $key );
337 if( ! is_integer( $newtalk ) ){
338 $res = $dbr->select( 'user_newtalk', 1, array( 'user_ip' => $this->mName
), $fname );
340 $this->mNewtalk
= $dbr->numRows( $res ) > 0 ?
1 : 0;
341 $dbr->freeResult( $res );
343 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
345 $this->mNewtalk
= $newtalk ?
1 : 0;
349 $this->mDataLoaded
= true;
351 } # the following stuff is for non-anonymous users only
353 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
354 'user_real_name','user_options','user_touched' ),
355 array( 'user_id' => $this->mId
), $fname );
357 if ( $s !== false ) {
358 $this->mName
= $s->user_name
;
359 $this->mEmail
= $s->user_email
;
360 $this->mRealName
= $s->user_real_name
;
361 $this->mPassword
= $s->user_password
;
362 $this->mNewpassword
= $s->user_newpassword
;
363 $this->decodeOptions( $s->user_options
);
364 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
365 $this->mRights
= explode( ",", strtolower(
366 $dbr->selectField( 'user_rights', 'user_rights', array( 'user_id' => $this->mId
) )
370 $this->mDataLoaded
= true;
373 function getID() { return $this->mId
; }
374 function setID( $v ) {
376 $this->mDataLoaded
= false;
380 $this->loadFromDatabase();
384 function setName( $str ) {
385 $this->loadFromDatabase();
389 function getNewtalk() {
390 $this->loadFromDatabase();
391 return ( 0 != $this->mNewtalk
);
394 function setNewtalk( $val ) {
395 $this->loadFromDatabase();
396 $this->mNewtalk
= $val;
397 $this->invalidateCache();
400 function invalidateCache() {
401 $this->loadFromDatabase();
402 $this->mTouched
= wfTimestampNow();
403 # Don't forget to save the options after this or
404 # it won't take effect!
407 function validateCache( $timestamp ) {
408 $this->loadFromDatabase();
409 return ($timestamp >= $this->mTouched
);
414 * Will only be salted if $wgPasswordSalt is true
415 * @param string Password.
416 * @return string Salted password or clear password.
418 function addSalt( $p ) {
419 global $wgPasswordSalt;
421 return md5( "{$this->mId}-{$p}" );
427 * Encrypt a password.
428 * It can eventuall salt a password @see User::addSalt()
429 * @param string $p clear Password.
430 * @param string Encrypted password.
432 function encryptPassword( $p ) {
433 return $this->addSalt( md5( $p ) );
436 function setPassword( $str ) {
437 $this->loadFromDatabase();
438 $this->setCookiePassword( $str );
439 $this->mPassword
= $this->encryptPassword( $str );
440 $this->mNewpassword
= '';
443 function setCookiePassword( $str ) {
444 $this->loadFromDatabase();
445 $this->mCookiePassword
= md5( $str );
448 function setNewpassword( $str ) {
449 $this->loadFromDatabase();
450 $this->mNewpassword
= $this->encryptPassword( $str );
453 function getEmail() {
454 $this->loadFromDatabase();
455 return $this->mEmail
;
458 function setEmail( $str ) {
459 $this->loadFromDatabase();
460 $this->mEmail
= $str;
463 function getRealName() {
464 $this->loadFromDatabase();
465 return $this->mRealName
;
468 function setRealName( $str ) {
469 $this->loadFromDatabase();
470 $this->mRealName
= $str;
473 function getOption( $oname ) {
474 $this->loadFromDatabase();
475 if ( array_key_exists( $oname, $this->mOptions
) ) {
476 return $this->mOptions
[$oname];
482 function setOption( $oname, $val ) {
483 $this->loadFromDatabase();
484 if ( $oname == 'skin' ) {
485 # Clear cached skin, so the new one displays immediately in Special:Preferences
486 unset( $this->mSkin
);
488 $this->mOptions
[$oname] = $val;
489 $this->invalidateCache();
492 function getRights() {
493 $this->loadFromDatabase();
494 return $this->mRights
;
497 function addRight( $rname ) {
498 $this->loadFromDatabase();
499 array_push( $this->mRights
, $rname );
500 $this->invalidateCache();
504 $this->loadFromDatabase();
505 if ( 0 == $this->mId
) { return false; }
507 return in_array( 'sysop', $this->mRights
);
510 function isDeveloper() {
511 $this->loadFromDatabase();
512 if ( 0 == $this->mId
) { return false; }
514 return in_array( 'developer', $this->mRights
);
517 function isBureaucrat() {
518 $this->loadFromDatabase();
519 if ( 0 == $this->mId
) { return false; }
521 return in_array( 'bureaucrat', $this->mRights
);
525 * Whether the user is a bot
528 $this->loadFromDatabase();
530 # Why was this here? I need a UID=0 conversion script [TS]
531 # if ( 0 == $this->mId ) { return false; }
533 return in_array( 'bot', $this->mRights
);
537 * Load a skin if it doesn't exist or return it
538 * @todo FIXME : need to check the old failback system [AV]
540 function &getSkin() {
541 global $IP, $wgUsePHPTal;
542 if ( ! isset( $this->mSkin
) ) {
543 # get all skin names available
544 $skinNames = Skin
::getSkinNames();
546 $userSkin = $this->getOption( 'skin' );
547 if ( $userSkin == '' ) { $userSkin = 'standard'; }
549 if ( !isset( $skinNames[$userSkin] ) ) {
550 # in case the user skin could not be found find a replacement
555 # if phptal is enabled we should have monobook skin that
556 # superseed the good old SkinStandard.
557 if ( isset( $skinNames['monobook'] ) ) {
558 $fallback[0] = 'MonoBook';
561 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
562 $sn = $fallback[$userSkin];
567 # The user skin is available
568 $sn = $skinNames[$userSkin];
571 # Grab the skin class and initialise it. Each skin checks for PHPTal
572 # and will not load if it's not enabled.
573 require_once( $IP.'/skins/'.$sn.'.php' );
575 # Check if we got if not failback to default skin
577 if(!class_exists($sn)) {
578 #FIXME : should we print an error message instead of loading
580 $sn = 'SkinStandard';
581 require_once( $IP.'/skins/Standard.php' );
583 $this->mSkin
= new $sn;
589 * @param string $title Article title to look at
593 * Check watched status of an article
594 * @return bool True if article is watched
596 function isWatched( $title ) {
597 $wl = WatchedItem
::fromUserTitle( $this, $title );
598 return $wl->isWatched();
604 function addWatch( $title ) {
605 $wl = WatchedItem
::fromUserTitle( $this, $title );
607 $this->invalidateCache();
611 * Stop watching an article
613 function removeWatch( $title ) {
614 $wl = WatchedItem
::fromUserTitle( $this, $title );
616 $this->invalidateCache();
622 * @return string Encoding options
624 function encodeOptions() {
626 foreach ( $this->mOptions
as $oname => $oval ) {
627 array_push( $a, $oname.'='.$oval );
629 $s = implode( "\n", $a );
636 function decodeOptions( $str ) {
637 $a = explode( "\n", $str );
638 foreach ( $a as $s ) {
639 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
640 $this->mOptions
[$m[1]] = $m[2];
645 function setCookies() {
646 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
647 if ( 0 == $this->mId
) return;
648 $this->loadFromDatabase();
649 $exp = time() +
$wgCookieExpiration;
651 $_SESSION['wsUserID'] = $this->mId
;
652 setcookie( $wgDBname.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain );
654 $_SESSION['wsUserName'] = $this->mName
;
655 setcookie( $wgDBname.'UserName', $this->mName
, $exp, $wgCookiePath, $wgCookieDomain );
657 $_SESSION['wsUserPassword'] = $this->mPassword
;
658 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
659 setcookie( $wgDBname.'Password', $this->mCookiePassword
, $exp, $wgCookiePath, $wgCookieDomain );
661 setcookie( $wgDBname.'Password', '', time() - 3600 );
667 * It will clean the session cookie
670 global $wgCookiePath, $wgCookieDomain, $wgDBname;
673 $_SESSION['wsUserID'] = 0;
675 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
676 setcookie( $wgDBname.'Password', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
680 * Save object settings into database
682 function saveSettings() {
683 global $wgMemc, $wgDBname;
684 $fname = 'User::saveSettings';
686 $dbw =& wfGetDB( DB_MASTER
);
687 if ( ! $this->mNewtalk
) {
688 # Delete user_newtalk row
690 $dbw->delete( 'user_newtalk', array( 'user_id' => $this->mId
), $fname );
692 $dbw->delete( 'user_newtalk', array( 'user_ip' => $this->mName
), $fname );
693 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
696 if ( 0 == $this->mId
) { return; }
698 $dbw->update( 'user',
700 'user_name' => $this->mName
,
701 'user_password' => $this->mPassword
,
702 'user_newpassword' => $this->mNewpassword
,
703 'user_real_name' => $this->mRealName
,
704 'user_email' => $this->mEmail
,
705 'user_options' => $this->encodeOptions(),
706 'user_touched' => $dbw->timestamp($this->mTouched
)
707 ), array( /* WHERE */
708 'user_id' => $this->mId
711 $dbw->set( 'user_rights', 'user_rights', implode( ",", $this->mRights
),
712 'user_id='. $this->mId
, $fname );
713 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
717 * Checks if a user with the given name exists, returns the ID
719 function idForName() {
720 $fname = 'User::idForName';
723 $s = trim( $this->mName
);
724 if ( 0 == strcmp( '', $s ) ) return 0;
726 $dbr =& wfGetDB( DB_SLAVE
);
727 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
728 if ( $id === false ) {
735 * Add user object to the database
737 function addToDatabase() {
738 $fname = 'User::addToDatabase';
739 $dbw =& wfGetDB( DB_MASTER
);
740 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
741 $dbw->insert( 'user',
743 'user_id' => $seqVal,
744 'user_name' => $this->mName
,
745 'user_password' => $this->mPassword
,
746 'user_newpassword' => $this->mNewpassword
,
747 'user_email' => $this->mEmail
,
748 'user_real_name' => $this->mRealName
,
749 'user_options' => $this->encodeOptions()
752 $this->mId
= $dbw->insertId();
753 $dbw->insert( 'user_rights',
755 'user_id' => $this->mId
,
756 'user_rights' => implode( ',', $this->mRights
)
762 function spreadBlock() {
764 # If the (non-anonymous) user is blocked, this function will block any IP address
765 # that they successfully log on from.
766 $fname = 'User::spreadBlock';
768 wfDebug( "User:spreadBlock()\n" );
769 if ( $this->mId
== 0 ) {
773 $userblock = Block
::newFromDB( '', $this->mId
);
774 if ( !$userblock->isValid() ) {
778 # Check if this IP address is already blocked
779 $ipblock = Block
::newFromDB( $wgIP );
780 if ( $ipblock->isValid() ) {
781 # Just update the timestamp
782 $ipblock->updateTimestamp();
786 # Make a new block object with the desired properties
787 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
788 $ipblock->mAddress
= $wgIP;
790 $ipblock->mBy
= $userblock->mBy
;
791 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
792 $ipblock->mTimestamp
= wfTimestampNow();
794 # If the user is already blocked with an expiry date, we don't
795 # want to pile on top of that!
796 if($userblock->mExpiry
) {
797 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
799 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
807 function getPageRenderingHash() {
812 // stubthreshold is only included below for completeness,
813 // it will always be 0 when this function is called by parsercache.
815 $confstr = $this->getOption( 'math' );
816 $confstr .= '!' . $this->getOption( 'highlightbroken' );
817 $confstr .= '!' . $this->getOption( 'stubthreshold' );
818 $confstr .= '!' . $this->getOption( 'editsection' );
819 $confstr .= '!' . $this->getOption( 'editsectiononrightclick' );
820 $confstr .= '!' . $this->getOption( 'showtoc' );
821 $confstr .= '!' . $this->getOption( 'date' );
822 $confstr .= '!' . $this->getOption( 'numberheadings' );
824 $this->mHash
= $confstr;
828 function isAllowedToCreateAccount() {
829 global $wgWhitelistAccount;
832 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
833 foreach ($wgWhitelistAccount as $right => $ok) {
834 $userHasRight = (!strcmp($right, 'user') ||
in_array($right, $this->getRights()));
835 $allowed |
= ($ok && $userHasRight);
841 * Set mDataLoaded, return previous value
842 * Use this to prevent DB access in command-line scripts or similar situations
844 function setLoaded( $loaded ) {
845 return wfSetVar( $this->mDataLoaded
, $loaded );
848 function getUserPage() {
849 return Title
::makeTitle( NS_USER
, $this->mName
);
855 function getMaxID() {
856 $dbr =& wfGetDB( DB_SLAVE
);
857 return $dbr->selectField( 'user', 'max(user_id)', false );
861 * Determine whether the user is a newbie. Newbies are either
862 * anonymous IPs, or the 1% most recently created accounts.
863 * Bots and sysops are excluded.
864 * @return bool True if it is a newbie.
866 function isNewbie() {
867 return $this->mId
> User
::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() ||
$this->getID() == 0;
871 * Check to see if the given clear-text password is one of the accepted passwords
872 * @param string $password User password.
873 * @return bool True if the given password is correct otherwise False.
875 function checkPassword( $password ) {
876 $this->loadFromDatabase();
877 $ep = $this->encryptPassword( $password );
878 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
880 } elseif ( 0 == strcmp( $ep, $this->mNewpassword
) ) {
882 } elseif ( function_exists( 'iconv' ) ) {
883 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
884 # Check for this with iconv
885 /* $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
886 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {