Oops, left debug output in
[mediawiki.git] / includes / User.php
blob0948c9ea1265ca10ac8f907c27c45c5ac52efa4b
1 <?php
2 # See user.doc
4 include_once( "WatchedItem.php" );
6 class User {
7 /* private */ var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
8 /* private */ var $mRights, $mOptions;
9 /* private */ var $mDataLoaded, $mNewpassword;
10 /* private */ var $mSkin;
11 /* private */ var $mBlockedby, $mBlockreason;
12 /* private */ var $mTouched;
13 /* private */ var $mCookiePassword;
15 function User()
17 $this->loadDefaults();
20 # Static factory method
22 function newFromName( $name )
24 $u = new User();
26 # Clean up name according to title rules
28 $t = Title::newFromText( $name );
29 $u->setName( $t->getText() );
30 return $u;
33 /* static */ function whoIs( $id )
35 return wfGetSQL( "user", "user_name", "user_id=$id" );
38 /* static */ function idFromName( $name )
40 $nt = Title::newFromText( $name );
41 $sql = "SELECT user_id FROM user WHERE user_name='" .
42 wfStrencode( $nt->getText() ) . "'";
43 $res = wfQuery( $sql, DB_READ, "User::idFromName" );
45 if ( 0 == wfNumRows( $res ) ) { return 0; }
46 else {
47 $s = wfFetchObject( $res );
48 return $s->user_id;
52 # does the string match an anonymous user IP address?
53 /* static */ function isIP( $name ) {
54 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
58 /* static */ function randomPassword()
60 $pwchars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz";
61 $l = strlen( $pwchars ) - 1;
63 wfSeedRandom();
64 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
65 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
66 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
67 $pwchars{mt_rand( 0, $l )};
68 return $np;
71 function loadDefaults()
73 global $wgLang, $wgIP;
74 global $wgNamespacesToBeSearchedDefault;
76 $this->mId = $this->mNewtalk = 0;
77 $this->mName = $wgIP;
78 $this->mEmail = "";
79 $this->mPassword = $this->mNewpassword = "";
80 $this->mRights = array();
81 $defOpt = $wgLang->getDefaultUserOptions() ;
82 foreach ( $defOpt as $oname => $val ) {
83 $this->mOptions[$oname] = $val;
85 foreach ($wgNamespacesToBeSearchedDefault as $nsnum => $val) {
86 $this->mOptions["searchNs".$nsnum] = $val;
88 unset( $this->mSkin );
89 $this->mDataLoaded = false;
90 $this->mBlockedby = -1; # Unset
91 $this->mTouched = '0'; # Allow any pages to be cached
92 $this->cookiePassword = "";
95 /* private */ function getBlockedStatus()
97 global $wgIP, $wgBlockCache;
99 if ( -1 != $this->mBlockedby ) { return; }
101 $this->mBlockedby = 0;
103 # User blocking
104 if ( $this->mId ) {
105 $block = new Block();
106 if ( $block->load( $wgIP , $this->mId ) ) {
107 $this->mBlockedby = $block->mBy;
108 $this->mBlockreason = $block->mReason;
112 # IP/range blocking
113 if ( !$this->mBlockedby ) {
114 $block = $wgBlockCache->get( $wgIP );
115 if ( $block !== false ) {
116 $this->mBlockedby = $block->mBy;
117 $this->mBlockreason = $block->mReason;
122 function isBlocked()
124 $this->getBlockedStatus();
125 if ( 0 == $this->mBlockedby ) { return false; }
126 return true;
129 function blockedBy() {
130 $this->getBlockedStatus();
131 return $this->mBlockedby;
134 function blockedFor() {
135 $this->getBlockedStatus();
136 return $this->mBlockreason;
139 function SetupSession() {
140 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
141 global $wsUserID, $wsUserName, $wsUserPassword, $wsUploadFiles;
142 if( $wgSessionsInMemcached ) {
143 include_once( "MemcachedSessions.php" );
145 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
146 session_cache_limiter( "private, must-revalidate" );
147 session_start();
148 session_register( "wsUserID" );
149 session_register( "wsUserName" );
150 session_register( "wsUserPassword" );
151 session_register( "wsUploadFiles" );
154 /* static */ function loadFromSession()
156 global $HTTP_COOKIE_VARS, $wsUserID, $wsUserName, $wsUserPassword;
157 global $wgMemc, $wgDBname;
159 if ( isset( $wsUserID ) ) {
160 if ( 0 != $wsUserID ) {
161 $sId = $wsUserID;
162 } else {
163 return new User();
165 } else if ( isset( $HTTP_COOKIE_VARS["{$wgDBname}UserID"] ) ) {
166 $sId = IntVal( $HTTP_COOKIE_VARS["{$wgDBname}UserID"] );
167 $wsUserID = $sId;
168 } else {
169 return new User();
171 if ( isset( $wsUserName ) ) {
172 $sName = $wsUserName;
173 } else if ( isset( $HTTP_COOKIE_VARS["{$wgDBname}UserName"] ) ) {
174 $sName = $HTTP_COOKIE_VARS["{$wgDBname}UserName"];
175 $wsUserName = $sName;
176 } else {
177 return new User();
180 $passwordCorrect = FALSE;
181 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
182 if($makenew = !$user) {
183 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
184 $user = new User();
185 $user->mId = $sId;
186 $user->loadFromDatabase();
187 } else {
188 wfDebug( "User::loadFromSession() got from cache!\n" );
191 if ( isset( $wsUserPassword ) ) {
192 $passwordCorrect = $wsUserPassword == $user->mPassword;
193 } else if ( isset( $HTTP_COOKIE_VARS["{$wgDBname}Password"] ) ) {
194 $user->mCookiePassword = $HTTP_COOKIE_VARS["{$wgDBname}Password"];
195 $wsUserPassword = $user->addSalt( $user->mCookiePassword );
196 $passwordCorrect = $wsUserPassword == $user->mPassword;
197 } else {
198 return new User(); # Can't log in from session
201 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
202 if($makenew) {
203 if($wgMemc->set( $key, $user ))
204 wfDebug( "User::loadFromSession() successfully saved user\n" );
205 else
206 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
208 $user->spreadBlock();
209 return $user;
211 return new User(); # Can't log in from session
214 function loadFromDatabase()
216 global $wgCommandLineMode;
217 if ( $this->mDataLoaded || $wgCommandLineMode ) {
218 return;
221 # Paranoia
222 $this->mId = IntVal( $this->mId );
224 # check in separate table if there are changes to the talk page
225 $this->mNewtalk=0; # reset talk page status
226 if($this->mId) {
227 $sql = "SELECT 1 FROM user_newtalk WHERE user_id={$this->mId}";
228 $res = wfQuery ($sql, DB_READ, "User::loadFromDatabase" );
230 if (wfNumRows($res)>0) {
231 $this->mNewtalk= 1;
233 wfFreeResult( $res );
234 } else {
235 # TEST THIS @@@
236 global $wgDBname, $wgMemc;
237 $key = "$wgDBname:newtalk:ip:{$this->mName}";
238 $newtalk = $wgMemc->get( $key );
239 if( ! is_integer( $newtalk ) ){
240 $sql = "SELECT 1 FROM user_newtalk WHERE user_ip='{$this->mName}'";
241 $res = wfQuery ($sql, DB_READ, "User::loadFromDatabase" );
243 $this->mNewtalk = (wfNumRows($res)>0) ? 1 : 0;
244 wfFreeResult( $res );
246 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
247 } else {
248 $this->mNewtalk = $newtalk ? 1 : 0;
251 if(!$this->mId) {
252 $this->mDataLoaded = true;
253 return;
254 } # the following stuff is for non-anonymous users only
256 $sql = "SELECT user_name,user_password,user_newpassword,user_email," .
257 "user_options,user_rights,user_touched FROM user WHERE user_id=" .
258 "{$this->mId}";
259 $res = wfQuery( $sql, DB_READ, "User::loadFromDatabase" );
261 if ( wfNumRows( $res ) > 0 ) {
262 $s = wfFetchObject( $res );
263 $this->mName = $s->user_name;
264 $this->mEmail = $s->user_email;
265 $this->mPassword = $s->user_password;
266 $this->mNewpassword = $s->user_newpassword;
267 $this->decodeOptions( $s->user_options );
268 $this->mRights = explode( ",", strtolower( $s->user_rights ) );
269 $this->mTouched = $s->user_touched;
272 wfFreeResult( $res );
273 $this->mDataLoaded = true;
276 function getID() { return $this->mId; }
277 function setID( $v ) {
278 $this->mId = $v;
279 $this->mDataLoaded = false;
282 function getName() {
283 $this->loadFromDatabase();
284 return $this->mName;
287 function setName( $str )
289 $this->loadFromDatabase();
290 $this->mName = $str;
293 function getNewtalk()
295 $this->loadFromDatabase();
296 return ( 0 != $this->mNewtalk );
299 function setNewtalk( $val )
301 $this->loadFromDatabase();
302 $this->mNewtalk = $val;
303 $this->invalidateCache();
306 function invalidateCache() {
307 $this->loadFromDatabase();
308 $this->mTouched = wfTimestampNow();
309 # Don't forget to save the options after this or
310 # it won't take effect!
313 function validateCache( $timestamp ) {
314 $this->loadFromDatabase();
315 return ($timestamp >= $this->mTouched);
318 function getPassword()
320 $this->loadFromDatabase();
321 return $this->mPassword;
324 function getNewpassword()
326 $this->loadFromDatabase();
327 return $this->mNewpassword;
330 function addSalt( $p )
332 global $wgPasswordSalt;
333 if($wgPasswordSalt)
334 return md5( "{$this->mId}-{$p}" );
335 else
336 return $p;
339 function encryptPassword( $p )
341 return $this->addSalt( md5( $p ) );
344 function setPassword( $str )
346 $this->loadFromDatabase();
347 $this->setCookiePassword( $str );
348 $this->mPassword = $this->encryptPassword( $str );
349 $this->mNewpassword = "";
352 function setCookiePassword( $str )
354 $this->loadFromDatabase();
355 $this->mCookiePassword = md5( $str );
358 function setNewpassword( $str )
360 $this->loadFromDatabase();
361 $this->mNewpassword = $this->encryptPassword( $str );
364 function getEmail()
366 $this->loadFromDatabase();
367 return $this->mEmail;
370 function setEmail( $str )
372 $this->loadFromDatabase();
373 $this->mEmail = $str;
376 function getOption( $oname )
378 $this->loadFromDatabase();
379 if ( array_key_exists( $oname, $this->mOptions ) ) {
380 return $this->mOptions[$oname];
381 } else {
382 return "";
386 function setOption( $oname, $val )
388 $this->loadFromDatabase();
389 $this->mOptions[$oname] = $val;
390 $this->invalidateCache();
393 function getRights()
395 $this->loadFromDatabase();
396 return $this->mRights;
399 function addRight( $rname )
401 $this->loadFromDatabase();
402 array_push( $this->mRights, $rname );
403 $this->invalidateCache();
406 function isSysop()
408 $this->loadFromDatabase();
409 if ( 0 == $this->mId ) { return false; }
411 return in_array( "sysop", $this->mRights );
414 function isDeveloper()
416 $this->loadFromDatabase();
417 if ( 0 == $this->mId ) { return false; }
419 return in_array( "developer", $this->mRights );
422 function isBureaucrat()
424 $this->loadFromDatabase();
425 if ( 0 == $this->mId ) { return false; }
427 return in_array( "bureaucrat", $this->mRights );
430 function isBot()
432 $this->loadFromDatabase();
433 if ( 0 == $this->mId ) { return false; }
435 return in_array( "bot", $this->mRights );
438 function &getSkin()
440 if ( ! isset( $this->mSkin ) ) {
441 $skinNames = Skin::getSkinNames();
442 $s = $this->getOption( "skin" );
443 if ( "" == $s ) { $s = 0; }
445 if ( $s >= count( $skinNames ) ) { $sn = "SkinStandard"; }
446 else $sn = "Skin" . $skinNames[$s];
447 $this->mSkin = new $sn;
449 return $this->mSkin;
452 function isWatched( $title ) {
453 $wl = WatchedItem::fromUserTitle( $this, $title );
454 return $wl->isWatched();
457 function addWatch( $title ) {
458 $wl = WatchedItem::fromUserTitle( $this, $title );
459 $wl->addWatch();
460 $this->invalidateCache();
463 function removeWatch( $title ) {
464 $wl = WatchedItem::fromUserTitle( $this, $title );
465 $wl->removeWatch();
466 $this->invalidateCache();
470 /* private */ function encodeOptions()
472 $a = array();
473 foreach ( $this->mOptions as $oname => $oval ) {
474 array_push( $a, "{$oname}={$oval}" );
476 $s = implode( "\n", $a );
477 return wfStrencode( $s );
480 /* private */ function decodeOptions( $str )
482 $a = explode( "\n", $str );
483 foreach ( $a as $s ) {
484 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
485 $this->mOptions[$m[1]] = $m[2];
490 function setCookies()
492 global $wsUserID, $wsUserName, $wsUserPassword;
493 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
494 if ( 0 == $this->mId ) return;
495 $this->loadFromDatabase();
496 $exp = time() + $wgCookieExpiration;
498 $wsUserID = $this->mId;
499 setcookie( "{$wgDBname}UserID", $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
501 $wsUserName = $this->mName;
502 setcookie( "{$wgDBname}UserName", $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
504 $wsUserPassword = $this->mPassword;
505 if ( 1 == $this->getOption( "rememberpassword" ) ) {
506 setcookie( "{$wgDBname}Password", $this->mCookiePassword, $exp, $wgCookiePath, $wgCookieDomain );
507 } else {
508 setcookie( "{$wgDBname}Password", "", time() - 3600 );
512 function logout()
514 global $wsUserID, $wgCookiePath, $wgCookieDomain, $wgDBname;
515 $this->mId = 0;
517 $wsUserID = 0;
519 setcookie( "{$wgDBname}UserID", "", time() - 3600, $wgCookiePath, $wgCookieDomain );
520 setcookie( "{$wgDBname}Password", "", time() - 3600, $wgCookiePath, $wgCookieDomain );
523 function saveSettings()
525 global $wgMemc, $wgDBname;
527 if ( ! $this->mNewtalk ) {
528 if( $this->mId ) {
529 $sql="DELETE FROM user_newtalk WHERE user_id={$this->mId}";
530 wfQuery ($sql, DB_WRITE, "User::saveSettings");
531 } else {
532 $sql="DELETE FROM user_newtalk WHERE user_ip='{$this->mName}'";
533 wfQuery ($sql, DB_WRITE, "User::saveSettings");
534 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
537 if ( 0 == $this->mId ) { return; }
539 $sql = "UPDATE user SET " .
540 "user_name= '" . wfStrencode( $this->mName ) . "', " .
541 "user_password= '" . wfStrencode( $this->mPassword ) . "', " .
542 "user_newpassword= '" . wfStrencode( $this->mNewpassword ) . "', " .
543 "user_email= '" . wfStrencode( $this->mEmail ) . "', " .
544 "user_options= '" . $this->encodeOptions() . "', " .
545 "user_rights= '" . wfStrencode( implode( ",", $this->mRights ) ) . "', " .
546 "user_touched= '" . wfStrencode( $this->mTouched ) .
547 "' WHERE user_id={$this->mId}";
548 wfQuery( $sql, DB_WRITE, "User::saveSettings" );
549 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
552 # Checks if a user with the given name exists
554 function idForName()
556 $gotid = 0;
557 $s = trim( $this->mName );
558 if ( 0 == strcmp( "", $s ) ) return 0;
560 $sql = "SELECT user_id FROM user WHERE user_name='" .
561 wfStrencode( $s ) . "'";
562 $res = wfQuery( $sql, DB_READ, "User::idForName" );
563 if ( 0 == wfNumRows( $res ) ) { return 0; }
565 $s = wfFetchObject( $res );
566 if ( "" == $s ) return 0;
568 $gotid = $s->user_id;
569 wfFreeResult( $res );
570 return $gotid;
573 function addToDatabase()
575 $sql = "INSERT INTO user (user_name,user_password,user_newpassword," .
576 "user_email, user_rights, user_options) " .
577 " VALUES ('" . wfStrencode( $this->mName ) . "', '" .
578 wfStrencode( $this->mPassword ) . "', '" .
579 wfStrencode( $this->mNewpassword ) . "', '" .
580 wfStrencode( $this->mEmail ) . "', '" .
581 wfStrencode( implode( ",", $this->mRights ) ) . "', '" .
582 $this->encodeOptions() . "')";
583 wfQuery( $sql, DB_WRITE, "User::addToDatabase" );
584 $this->mId = $this->idForName();
587 function spreadBlock()
589 global $wgIP;
590 # If the (non-anonymous) user is blocked, this function will block any IP address
591 # that they successfully log on from.
592 $fname = "User::spreadBlock";
594 wfDebug( "User:spreadBlock()\n" );
595 if ( $this->mId == 0 ) {
596 return;
599 $userblock = Block::newFromDB( "", $this->mId );
600 if ( !$userblock->isValid() ) {
601 return;
604 # Check if this IP address is already blocked
605 $ipblock = Block::newFromDB( $wgIP );
606 if ( $ipblock->isValid() ) {
607 # Just update the timestamp
608 $ipblock->updateTimestamp();
609 return;
612 # Make a new block object with the desired properties
613 wfDebug( "Autoblocking {$this->mUserName}@{$wgIP}\n" );
614 $ipblock->mAddress = $wgIP;
615 $ipblock->mUser = 0;
616 $ipblock->mBy = $userblock->mBy;
617 $ipblock->mReason = wfMsg( "autoblocker", $this->getName(), $userblock->mReason );
618 $ipblock->mTimestamp = wfTimestampNow();
619 $ipblock->mAuto = 1;
620 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
622 # Insert it
623 $ipblock->insert();
627 function getPageRenderingHash(){
628 static $hash = false;
629 if( $hash ){
630 return $hash;
633 // stubthreshold is only included below for completeness,
634 // it will always be 0 when this function is called by parsercache.
636 $confstr = $this->getOption( "quickbar" );
637 $confstr .= "!" . $this->getOption( "underline" );
638 $confstr .= "!" . $this->getOption( "hover" );
639 $confstr .= "!" . $this->getOption( "skin" );
640 $confstr .= "!" . $this->getOption( "math" );
641 $confstr .= "!" . $this->getOption( "highlightbroken" );
642 $confstr .= "!" . $this->getOption( "stubthreshold" );
643 $confstr .= "!" . $this->getOption( "editsection" );
644 $confstr .= "!" . $this->getOption( "editsectiononrightclick" );
645 $confstr .= "!" . $this->getOption( "showtoc" );
646 $confstr .= "!" . $this->getOption( "date" );
648 if(strlen($confstr) > 32)
649 $hash = md5($confstr);
650 else
651 $hash = $confstr;
652 return $hash;
655 function isAllowedToCreateAccount()
657 global $wgWhitelistAccount;
658 $allowed = false;
660 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
661 foreach ($wgWhitelistAccount as $right => $ok) {
662 $userHasRight = (!strcmp($right, "user") || in_array($right, $this->getRights()));
663 $allowed |= ($ok && $userHasRight);
665 return $allowed;