Make sure that id taken from cookie is an int; otherwise it goes to 0
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 # See user.doc
3
4 include_once( "WatchedItem.php" );
5
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;
14
15 function User()
16 {
17 $this->loadDefaults();
18 }
19
20 # Static factory method
21 #
22 function newFromName( $name )
23 {
24 $u = new User();
25
26 # Clean up name according to title rules
27
28 $t = Title::newFromText( $name );
29 $u->setName( $t->getText() );
30 return $u;
31 }
32
33 /* static */ function whoIs( $id )
34 {
35 return wfGetSQL( "user", "user_name", "user_id=$id" );
36 }
37
38 /* static */ function idFromName( $name )
39 {
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" );
44
45 if ( 0 == wfNumRows( $res ) ) { return 0; }
46 else {
47 $s = wfFetchObject( $res );
48 return $s->user_id;
49 }
50 }
51
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);
55
56 }
57
58 /* static */ function randomPassword()
59 {
60 $pwchars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz";
61 $l = strlen( $pwchars ) - 1;
62
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;
69 }
70
71 function loadDefaults()
72 {
73 global $wgLang, $wgIP;
74 global $wgNamespacesToBeSearchedDefault;
75
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;
84 }
85 foreach ($wgNamespacesToBeSearchedDefault as $nsnum => $val) {
86 $this->mOptions["searchNs".$nsnum] = $val;
87 }
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 = "";
93 }
94
95 /* private */ function getBlockedStatus()
96 {
97 global $wgIP, $wgBlockCache;
98
99 if ( -1 != $this->mBlockedby ) { return; }
100
101 $this->mBlockedby = 0;
102
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;
109 }
110 }
111
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;
118 }
119 }
120 }
121
122 function isBlocked()
123 {
124 $this->getBlockedStatus();
125 if ( 0 == $this->mBlockedby ) { return false; }
126 return true;
127 }
128
129 function blockedBy() {
130 $this->getBlockedStatus();
131 return $this->mBlockedby;
132 }
133
134 function blockedFor() {
135 $this->getBlockedStatus();
136 return $this->mBlockreason;
137 }
138
139 function SetupSession() {
140 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
141 global $wsUserID, $wsUserName, $wsUserPassword, $wsUploadFiles;
142 if( $wgSessionsInMemcached ) {
143 include_once( "MemcachedSessions.php" );
144 }
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" );
152 }
153
154 /* static */ function loadFromSession()
155 {
156 global $HTTP_COOKIE_VARS, $wsUserID, $wsUserName, $wsUserPassword;
157 global $wgMemc, $wgDBname;
158
159 if ( isset( $wsUserID ) ) {
160 if ( 0 != $wsUserID ) {
161 $sId = $wsUserID;
162 } else {
163 return new User();
164 }
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();
170 }
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();
178 }
179
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" );
189 }
190
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
199 }
200
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" );
207 }
208 $user->spreadBlock();
209 return $user;
210 }
211 return new User(); # Can't log in from session
212 }
213
214 function loadFromDatabase()
215 {
216 if ( $this->mDataLoaded ) { return; }
217
218 # Paranoia
219 $this->mId = IntVal( $this->mId );
220
221 # check in separate table if there are changes to the talk page
222 $this->mNewtalk=0; # reset talk page status
223 if($this->mId) {
224 $sql = "SELECT 1 FROM user_newtalk WHERE user_id={$this->mId}";
225 $res = wfQuery ($sql, DB_READ, "User::loadFromDatabase" );
226
227 if (wfNumRows($res)>0) {
228 $this->mNewtalk= 1;
229 }
230 wfFreeResult( $res );
231 } else {
232 # TEST THIS @@@
233 global $wgDBname, $wgMemc;
234 $key = "$wgDBname:newtalk:ip:{$this->mName}";
235 $newtalk = $wgMemc->get( $key );
236 if( ! is_integer( $newtalk ) ){
237 $sql = "SELECT 1 FROM user_newtalk WHERE user_ip='{$this->mName}'";
238 $res = wfQuery ($sql, DB_READ, "User::loadFromDatabase" );
239
240 $this->mNewtalk = (wfNumRows($res)>0) ? 1 : 0;
241 wfFreeResult( $res );
242
243 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
244 } else {
245 $this->mNewtalk = $newtalk ? 1 : 0;
246 }
247 }
248 if(!$this->mId) {
249 $this->mDataLoaded = true;
250 return;
251 } # the following stuff is for non-anonymous users only
252
253 $sql = "SELECT user_name,user_password,user_newpassword,user_email," .
254 "user_options,user_rights,user_touched FROM user WHERE user_id=" .
255 "{$this->mId}";
256 $res = wfQuery( $sql, DB_READ, "User::loadFromDatabase" );
257
258 if ( wfNumRows( $res ) > 0 ) {
259 $s = wfFetchObject( $res );
260 $this->mName = $s->user_name;
261 $this->mEmail = $s->user_email;
262 $this->mPassword = $s->user_password;
263 $this->mNewpassword = $s->user_newpassword;
264 $this->decodeOptions( $s->user_options );
265 $this->mRights = explode( ",", strtolower( $s->user_rights ) );
266 $this->mTouched = $s->user_touched;
267 }
268
269 wfFreeResult( $res );
270 $this->mDataLoaded = true;
271 }
272
273 function getID() { return $this->mId; }
274 function setID( $v ) {
275 $this->mId = $v;
276 $this->mDataLoaded = false;
277 }
278
279 function getName() {
280 $this->loadFromDatabase();
281 return $this->mName;
282 }
283
284 function setName( $str )
285 {
286 $this->loadFromDatabase();
287 $this->mName = $str;
288 }
289
290 function getNewtalk()
291 {
292 $this->loadFromDatabase();
293 return ( 0 != $this->mNewtalk );
294 }
295
296 function setNewtalk( $val )
297 {
298 $this->loadFromDatabase();
299 $this->mNewtalk = $val;
300 $this->invalidateCache();
301 }
302
303 function invalidateCache() {
304 $this->loadFromDatabase();
305 $this->mTouched = wfTimestampNow();
306 # Don't forget to save the options after this or
307 # it won't take effect!
308 }
309
310 function validateCache( $timestamp ) {
311 $this->loadFromDatabase();
312 return ($timestamp >= $this->mTouched);
313 }
314
315 function getPassword()
316 {
317 $this->loadFromDatabase();
318 return $this->mPassword;
319 }
320
321 function getNewpassword()
322 {
323 $this->loadFromDatabase();
324 return $this->mNewpassword;
325 }
326
327 function addSalt( $p )
328 {
329 global $wgPasswordSalt;
330 if($wgPasswordSalt)
331 return md5( "{$this->mId}-{$p}" );
332 else
333 return $p;
334 }
335
336 function encryptPassword( $p )
337 {
338 return $this->addSalt( md5( $p ) );
339 }
340
341 function setPassword( $str )
342 {
343 $this->loadFromDatabase();
344 $this->setCookiePassword( $str );
345 $this->mPassword = $this->encryptPassword( $str );
346 $this->mNewpassword = "";
347 }
348
349 function setCookiePassword( $str )
350 {
351 $this->loadFromDatabase();
352 $this->mCookiePassword = md5( $str );
353 }
354
355 function setNewpassword( $str )
356 {
357 $this->loadFromDatabase();
358 $this->mNewpassword = $this->encryptPassword( $str );
359 }
360
361 function getEmail()
362 {
363 $this->loadFromDatabase();
364 return $this->mEmail;
365 }
366
367 function setEmail( $str )
368 {
369 $this->loadFromDatabase();
370 $this->mEmail = $str;
371 }
372
373 function getOption( $oname )
374 {
375 $this->loadFromDatabase();
376 if ( array_key_exists( $oname, $this->mOptions ) ) {
377 return $this->mOptions[$oname];
378 } else {
379 return "";
380 }
381 }
382
383 function setOption( $oname, $val )
384 {
385 $this->loadFromDatabase();
386 $this->mOptions[$oname] = $val;
387 $this->invalidateCache();
388 }
389
390 function getRights()
391 {
392 $this->loadFromDatabase();
393 return $this->mRights;
394 }
395
396 function addRight( $rname )
397 {
398 $this->loadFromDatabase();
399 array_push( $this->mRights, $rname );
400 $this->invalidateCache();
401 }
402
403 function isSysop()
404 {
405 $this->loadFromDatabase();
406 if ( 0 == $this->mId ) { return false; }
407
408 return in_array( "sysop", $this->mRights );
409 }
410
411 function isDeveloper()
412 {
413 $this->loadFromDatabase();
414 if ( 0 == $this->mId ) { return false; }
415
416 return in_array( "developer", $this->mRights );
417 }
418
419 function isBureaucrat()
420 {
421 $this->loadFromDatabase();
422 if ( 0 == $this->mId ) { return false; }
423
424 return in_array( "bureaucrat", $this->mRights );
425 }
426
427 function isBot()
428 {
429 $this->loadFromDatabase();
430 if ( 0 == $this->mId ) { return false; }
431
432 return in_array( "bot", $this->mRights );
433 }
434
435 function &getSkin()
436 {
437 if ( ! isset( $this->mSkin ) ) {
438 $skinNames = Skin::getSkinNames();
439 $s = $this->getOption( "skin" );
440 if ( "" == $s ) { $s = 0; }
441
442 if ( $s >= count( $skinNames ) ) { $sn = "SkinStandard"; }
443 else $sn = "Skin" . $skinNames[$s];
444 $this->mSkin = new $sn;
445 }
446 return $this->mSkin;
447 }
448
449 function isWatched( $title ) {
450 $wl = WatchedItem::fromUserTitle( $this, $title );
451 return $wl->isWatched();
452 }
453
454 function addWatch( $title ) {
455 $wl = WatchedItem::fromUserTitle( $this, $title );
456 $wl->addWatch();
457 $this->invalidateCache();
458 }
459
460 function removeWatch( $title ) {
461 $wl = WatchedItem::fromUserTitle( $this, $title );
462 $wl->removeWatch();
463 $this->invalidateCache();
464 }
465
466
467 /* private */ function encodeOptions()
468 {
469 $a = array();
470 foreach ( $this->mOptions as $oname => $oval ) {
471 array_push( $a, "{$oname}={$oval}" );
472 }
473 $s = implode( "\n", $a );
474 return wfStrencode( $s );
475 }
476
477 /* private */ function decodeOptions( $str )
478 {
479 $a = explode( "\n", $str );
480 foreach ( $a as $s ) {
481 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
482 $this->mOptions[$m[1]] = $m[2];
483 }
484 }
485 }
486
487 function setCookies()
488 {
489 global $wsUserID, $wsUserName, $wsUserPassword;
490 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
491 if ( 0 == $this->mId ) return;
492 $this->loadFromDatabase();
493 $exp = time() + $wgCookieExpiration;
494
495 $wsUserID = $this->mId;
496 setcookie( "{$wgDBname}UserID", $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
497
498 $wsUserName = $this->mName;
499 setcookie( "{$wgDBname}UserName", $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
500
501 $wsUserPassword = $this->mPassword;
502 if ( 1 == $this->getOption( "rememberpassword" ) ) {
503 setcookie( "{$wgDBname}Password", $this->mCookiePassword, $exp, $wgCookiePath, $wgCookieDomain );
504 } else {
505 setcookie( "{$wgDBname}Password", "", time() - 3600 );
506 }
507 }
508
509 function logout()
510 {
511 global $wsUserID, $wgCookiePath, $wgCookieDomain, $wgDBname;
512 $this->mId = 0;
513
514 $wsUserID = 0;
515
516 setcookie( "{$wgDBname}UserID", "", time() - 3600, $wgCookiePath, $wgCookieDomain );
517 setcookie( "{$wgDBname}Password", "", time() - 3600, $wgCookiePath, $wgCookieDomain );
518 }
519
520 function saveSettings()
521 {
522 global $wgMemc, $wgDBname;
523
524 if ( ! $this->mNewtalk ) {
525 if( $this->mId ) {
526 $sql="DELETE FROM user_newtalk WHERE user_id={$this->mId}";
527 wfQuery ($sql, DB_WRITE, "User::saveSettings");
528 } else {
529 $sql="DELETE FROM user_newtalk WHERE user_ip='{$this->mName}'";
530 wfQuery ($sql, DB_WRITE, "User::saveSettings");
531 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
532 }
533 }
534 if ( 0 == $this->mId ) { return; }
535
536 $sql = "UPDATE user SET " .
537 "user_name= '" . wfStrencode( $this->mName ) . "', " .
538 "user_password= '" . wfStrencode( $this->mPassword ) . "', " .
539 "user_newpassword= '" . wfStrencode( $this->mNewpassword ) . "', " .
540 "user_email= '" . wfStrencode( $this->mEmail ) . "', " .
541 "user_options= '" . $this->encodeOptions() . "', " .
542 "user_rights= '" . wfStrencode( implode( ",", $this->mRights ) ) . "', " .
543 "user_touched= '" . wfStrencode( $this->mTouched ) .
544 "' WHERE user_id={$this->mId}";
545 wfQuery( $sql, DB_WRITE, "User::saveSettings" );
546 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
547 }
548
549 # Checks if a user with the given name exists
550 #
551 function idForName()
552 {
553 $gotid = 0;
554 $s = trim( $this->mName );
555 if ( 0 == strcmp( "", $s ) ) return 0;
556
557 $sql = "SELECT user_id FROM user WHERE user_name='" .
558 wfStrencode( $s ) . "'";
559 $res = wfQuery( $sql, DB_READ, "User::idForName" );
560 if ( 0 == wfNumRows( $res ) ) { return 0; }
561
562 $s = wfFetchObject( $res );
563 if ( "" == $s ) return 0;
564
565 $gotid = $s->user_id;
566 wfFreeResult( $res );
567 return $gotid;
568 }
569
570 function addToDatabase()
571 {
572 $sql = "INSERT INTO user (user_name,user_password,user_newpassword," .
573 "user_email, user_rights, user_options) " .
574 " VALUES ('" . wfStrencode( $this->mName ) . "', '" .
575 wfStrencode( $this->mPassword ) . "', '" .
576 wfStrencode( $this->mNewpassword ) . "', '" .
577 wfStrencode( $this->mEmail ) . "', '" .
578 wfStrencode( implode( ",", $this->mRights ) ) . "', '" .
579 $this->encodeOptions() . "')";
580 wfQuery( $sql, DB_WRITE, "User::addToDatabase" );
581 $this->mId = $this->idForName();
582 }
583
584 function spreadBlock()
585 {
586 global $wgIP;
587 # If the (non-anonymous) user is blocked, this function will block any IP address
588 # that they successfully log on from.
589 $fname = "User::spreadBlock";
590
591 wfDebug( "User:spreadBlock()\n" );
592 if ( $this->mId == 0 ) {
593 return;
594 }
595
596 $userblock = Block::newFromDB( "", $this->mId );
597 if ( !$userblock->isValid() ) {
598 return;
599 }
600
601 # Check if this IP address is already blocked
602 $ipblock = Block::newFromDB( $wgIP );
603 if ( $ipblock->isValid() ) {
604 # Just update the timestamp
605 $ipblock->updateTimestamp();
606 return;
607 }
608
609 # Make a new block object with the desired properties
610 wfDebug( "Autoblocking {$this->mUserName}@{$wgIP}\n" );
611 $ipblock->mAddress = $wgIP;
612 $ipblock->mUser = 0;
613 $ipblock->mBy = $userblock->mBy;
614 $ipblock->mReason = wfMsg( "autoblocker", $this->getName(), $userblock->mReason );
615 $ipblock->mTimestamp = wfTimestampNow();
616 $ipblock->mAuto = 1;
617 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
618
619 # Insert it
620 $ipblock->insert();
621
622 }
623
624 function getPageRenderingHash(){
625 static $hash = false;
626 if( $hash ){
627 return $hash;
628 }
629
630 // stubthreshold is only included below for completeness,
631 // it will always be 0 when this function is called by parsercache.
632
633 $confstr = $this->getOption( "quickbar" );
634 $confstr .= "!" . $this->getOption( "underline" );
635 $confstr .= "!" . $this->getOption( "hover" );
636 $confstr .= "!" . $this->getOption( "skin" );
637 $confstr .= "!" . $this->getOption( "math" );
638 $confstr .= "!" . $this->getOption( "highlightbroken" );
639 $confstr .= "!" . $this->getOption( "stubthreshold" );
640 $confstr .= "!" . $this->getOption( "editsection" );
641 $confstr .= "!" . $this->getOption( "editsectiononrightclick" );
642 $confstr .= "!" . $this->getOption( "showtoc" );
643 $confstr .= "!" . $this->getOption( "date" );
644
645 if(strlen($confstr) > 32)
646 $hash = md5($confstr);
647 else
648 $hash = $confstr;
649 return $hash;
650 }
651
652 function isAllowedToCreateAccount()
653 {
654 global $wgWhitelistAccount;
655 $allowed = false;
656
657 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
658 foreach ($wgWhitelistAccount as $right => $ok) {
659 $userHasRight = (!strcmp($right, "user") || in_array($right, $this->getRights()));
660 $allowed |= ($ok && $userHasRight);
661 }
662 return $allowed;
663 }
664
665
666
667 }
668
669 ?>