include_once -> require_once
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 # See user.doc
3
4 require_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 /* private */ var $mRealName;
15
16 function User()
17 {
18 $this->loadDefaults();
19 }
20
21 # Static factory method
22 #
23 function newFromName( $name )
24 {
25 $u = new User();
26
27 # Clean up name according to title rules
28
29 $t = Title::newFromText( $name );
30 $u->setName( $t->getText() );
31 return $u;
32 }
33
34 /* static */ function whoIs( $id )
35 {
36 return wfGetSQL( "user", "user_name", "user_id=$id" );
37 }
38
39 /* static */ function whoIsReal( $id )
40 {
41 return wfGetSQL( "user", "user_real_name", "user_id=$id" );
42 }
43
44 /* static */ function idFromName( $name )
45 {
46 $nt = Title::newFromText( $name );
47 if( is_null( $nt ) ) {
48 # Illegal name
49 return null;
50 }
51 $sql = "SELECT user_id FROM user WHERE user_name='" .
52 wfStrencode( $nt->getText() ) . "'";
53 $res = wfQuery( $sql, DB_READ, "User::idFromName" );
54
55 if ( 0 == wfNumRows( $res ) ) {
56 return 0;
57 } else {
58 $s = wfFetchObject( $res );
59 wfFreeResult( $res );
60 return $s->user_id;
61 }
62 }
63
64 # does the string match an anonymous user IP address?
65 /* static */ function isIP( $name ) {
66 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
67
68 }
69
70 /* static */ function randomPassword()
71 {
72 $pwchars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz";
73 $l = strlen( $pwchars ) - 1;
74
75 wfSeedRandom();
76 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
77 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
78 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
79 $pwchars{mt_rand( 0, $l )};
80 return $np;
81 }
82
83 function loadDefaults()
84 {
85 global $wgLang, $wgIP;
86 global $wgNamespacesToBeSearchedDefault;
87
88 $this->mId = $this->mNewtalk = 0;
89 $this->mName = $wgIP;
90 $this->mEmail = "";
91 $this->mPassword = $this->mNewpassword = "";
92 $this->mRights = array();
93 $defOpt = $wgLang->getDefaultUserOptions() ;
94 foreach ( $defOpt as $oname => $val ) {
95 $this->mOptions[$oname] = $val;
96 }
97 foreach ($wgNamespacesToBeSearchedDefault as $nsnum => $val) {
98 $this->mOptions["searchNs".$nsnum] = $val;
99 }
100 unset( $this->mSkin );
101 $this->mDataLoaded = false;
102 $this->mBlockedby = -1; # Unset
103 $this->mTouched = '0'; # Allow any pages to be cached
104 $this->cookiePassword = "";
105 }
106
107 /* private */ function getBlockedStatus()
108 {
109 global $wgIP, $wgBlockCache;
110
111 if ( -1 != $this->mBlockedby ) { return; }
112
113 $this->mBlockedby = 0;
114
115 # User blocking
116 if ( $this->mId ) {
117 $block = new Block();
118 if ( $block->load( $wgIP , $this->mId ) ) {
119 $this->mBlockedby = $block->mBy;
120 $this->mBlockreason = $block->mReason;
121 }
122 }
123
124 # IP/range blocking
125 if ( !$this->mBlockedby ) {
126 $block = $wgBlockCache->get( $wgIP );
127 if ( $block !== false ) {
128 $this->mBlockedby = $block->mBy;
129 $this->mBlockreason = $block->mReason;
130 }
131 }
132 }
133
134 function isBlocked()
135 {
136 $this->getBlockedStatus();
137 if ( 0 == $this->mBlockedby ) { return false; }
138 return true;
139 }
140
141 function blockedBy() {
142 $this->getBlockedStatus();
143 return $this->mBlockedby;
144 }
145
146 function blockedFor() {
147 $this->getBlockedStatus();
148 return $this->mBlockreason;
149 }
150
151 function SetupSession() {
152 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
153 if( $wgSessionsInMemcached ) {
154 require_once( "MemcachedSessions.php" );
155 }
156 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
157 session_cache_limiter( "private, must-revalidate" );
158 @session_start();
159 }
160
161 /* static */ function loadFromSession()
162 {
163 global $wgMemc, $wgDBname;
164
165 if ( isset( $_SESSION['wsUserID'] ) ) {
166 if ( 0 != $_SESSION['wsUserID'] ) {
167 $sId = $_SESSION['wsUserID'];
168 } else {
169 return new User();
170 }
171 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
172 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
173 $_SESSION['wsUserID'] = $sId;
174 } else {
175 return new User();
176 }
177 if ( isset( $_SESSION['wsUserName'] ) ) {
178 $sName = $_SESSION['wsUserName'];
179 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
180 $sName = $_COOKIE["{$wgDBname}UserName"];
181 $_SESSION['wsUserName'] = $sName;
182 } else {
183 return new User();
184 }
185
186 $passwordCorrect = FALSE;
187 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
188 if($makenew = !$user) {
189 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
190 $user = new User();
191 $user->mId = $sId;
192 $user->loadFromDatabase();
193 } else {
194 wfDebug( "User::loadFromSession() got from cache!\n" );
195 }
196
197 if ( isset( $_SESSION['wsUserPassword'] ) ) {
198 $passwordCorrect = $_SESSION['wsUserPassword'] == $user->mPassword;
199 } else if ( isset( $_COOKIE["{$wgDBname}Password"] ) ) {
200 $user->mCookiePassword = $_COOKIE["{$wgDBname}Password"];
201 $_SESSION['wsUserPassword'] = $user->addSalt( $user->mCookiePassword );
202 $passwordCorrect = $_SESSION['wsUserPassword'] == $user->mPassword;
203 } else {
204 return new User(); # Can't log in from session
205 }
206
207 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
208 if($makenew) {
209 if($wgMemc->set( $key, $user ))
210 wfDebug( "User::loadFromSession() successfully saved user\n" );
211 else
212 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
213 }
214 $user->spreadBlock();
215 return $user;
216 }
217 return new User(); # Can't log in from session
218 }
219
220 function loadFromDatabase()
221 {
222 global $wgCommandLineMode;
223 if ( $this->mDataLoaded || $wgCommandLineMode ) {
224 return;
225 }
226
227 # Paranoia
228 $this->mId = IntVal( $this->mId );
229
230 # check in separate table if there are changes to the talk page
231 $this->mNewtalk=0; # reset talk page status
232 if($this->mId) {
233 $sql = "SELECT 1 FROM user_newtalk WHERE user_id={$this->mId}";
234 $res = wfQuery ($sql, DB_READ, "User::loadFromDatabase" );
235
236 if (wfNumRows($res)>0) {
237 $this->mNewtalk= 1;
238 }
239 wfFreeResult( $res );
240 } else {
241 global $wgDBname, $wgMemc;
242 $key = "$wgDBname:newtalk:ip:{$this->mName}";
243 $newtalk = $wgMemc->get( $key );
244 if( ! is_integer( $newtalk ) ){
245 $sql = "SELECT 1 FROM user_newtalk WHERE user_ip='{$this->mName}'";
246 $res = wfQuery ($sql, DB_READ, "User::loadFromDatabase" );
247
248 $this->mNewtalk = (wfNumRows($res)>0) ? 1 : 0;
249 wfFreeResult( $res );
250
251 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
252 } else {
253 $this->mNewtalk = $newtalk ? 1 : 0;
254 }
255 }
256 if(!$this->mId) {
257 $this->mDataLoaded = true;
258 return;
259 } # the following stuff is for non-anonymous users only
260
261 $sql = "SELECT user_name,user_password,user_newpassword,user_email," .
262 "user_real_name,user_options,user_rights,user_touched " .
263 " FROM user WHERE user_id=" . $this->mId;
264 $res = wfQuery( $sql, DB_READ, "User::loadFromDatabase" );
265
266 if ( wfNumRows( $res ) > 0 ) {
267 $s = wfFetchObject( $res );
268 $this->mName = $s->user_name;
269 $this->mEmail = $s->user_email;
270 $this->mRealName = $s->user_real_name;
271 $this->mPassword = $s->user_password;
272 $this->mNewpassword = $s->user_newpassword;
273 $this->decodeOptions( $s->user_options );
274 $this->mRights = explode( ",", strtolower( $s->user_rights ) );
275 $this->mTouched = $s->user_touched;
276 }
277
278 wfFreeResult( $res );
279 $this->mDataLoaded = true;
280 }
281
282 function getID() { return $this->mId; }
283 function setID( $v ) {
284 $this->mId = $v;
285 $this->mDataLoaded = false;
286 }
287
288 function getName() {
289 $this->loadFromDatabase();
290 return $this->mName;
291 }
292
293 function setName( $str )
294 {
295 $this->loadFromDatabase();
296 $this->mName = $str;
297 }
298
299 function getNewtalk()
300 {
301 $this->loadFromDatabase();
302 return ( 0 != $this->mNewtalk );
303 }
304
305 function setNewtalk( $val )
306 {
307 $this->loadFromDatabase();
308 $this->mNewtalk = $val;
309 $this->invalidateCache();
310 }
311
312 function invalidateCache() {
313 $this->loadFromDatabase();
314 $this->mTouched = wfTimestampNow();
315 # Don't forget to save the options after this or
316 # it won't take effect!
317 }
318
319 function validateCache( $timestamp ) {
320 $this->loadFromDatabase();
321 return ($timestamp >= $this->mTouched);
322 }
323
324 function getPassword()
325 {
326 $this->loadFromDatabase();
327 return $this->mPassword;
328 }
329
330 function getNewpassword()
331 {
332 $this->loadFromDatabase();
333 return $this->mNewpassword;
334 }
335
336 function addSalt( $p )
337 {
338 global $wgPasswordSalt;
339 if($wgPasswordSalt)
340 return md5( "{$this->mId}-{$p}" );
341 else
342 return $p;
343 }
344
345 function encryptPassword( $p )
346 {
347 return $this->addSalt( md5( $p ) );
348 }
349
350 function setPassword( $str )
351 {
352 $this->loadFromDatabase();
353 $this->setCookiePassword( $str );
354 $this->mPassword = $this->encryptPassword( $str );
355 $this->mNewpassword = "";
356 }
357
358 function setCookiePassword( $str )
359 {
360 $this->loadFromDatabase();
361 $this->mCookiePassword = md5( $str );
362 }
363
364 function setNewpassword( $str )
365 {
366 $this->loadFromDatabase();
367 $this->mNewpassword = $this->encryptPassword( $str );
368 }
369
370 function getEmail()
371 {
372 $this->loadFromDatabase();
373 return $this->mEmail;
374 }
375
376 function setEmail( $str )
377 {
378 $this->loadFromDatabase();
379 $this->mEmail = $str;
380 }
381
382 function getRealName()
383 {
384 $this->loadFromDatabase();
385 return $this->mRealName;
386 }
387
388 function setRealName( $str )
389 {
390 $this->loadFromDatabase();
391 $this->mRealName = $str;
392 }
393
394 function getOption( $oname )
395 {
396 $this->loadFromDatabase();
397 if ( array_key_exists( $oname, $this->mOptions ) ) {
398 return $this->mOptions[$oname];
399 } else {
400 return "";
401 }
402 }
403
404 function setOption( $oname, $val )
405 {
406 $this->loadFromDatabase();
407 if ( $oname == 'skin' ) {
408 # Clear cached skin, so the new one displays immediately in Special:Preferences
409 unset( $this->mSkin );
410 }
411 $this->mOptions[$oname] = $val;
412 $this->invalidateCache();
413 }
414
415 function getRights()
416 {
417 $this->loadFromDatabase();
418 return $this->mRights;
419 }
420
421 function addRight( $rname )
422 {
423 $this->loadFromDatabase();
424 array_push( $this->mRights, $rname );
425 $this->invalidateCache();
426 }
427
428 function isSysop()
429 {
430 $this->loadFromDatabase();
431 if ( 0 == $this->mId ) { return false; }
432
433 return in_array( "sysop", $this->mRights );
434 }
435
436 function isDeveloper()
437 {
438 $this->loadFromDatabase();
439 if ( 0 == $this->mId ) { return false; }
440
441 return in_array( "developer", $this->mRights );
442 }
443
444 function isBureaucrat()
445 {
446 $this->loadFromDatabase();
447 if ( 0 == $this->mId ) { return false; }
448
449 return in_array( "bureaucrat", $this->mRights );
450 }
451
452 function isBot()
453 {
454 $this->loadFromDatabase();
455
456 # Why was this here? I need a UID=0 conversion script [TS]
457 # if ( 0 == $this->mId ) { return false; }
458
459 return in_array( "bot", $this->mRights );
460 }
461
462 function &getSkin()
463 {
464 if ( ! isset( $this->mSkin ) ) {
465 $skinNames = Skin::getSkinNames();
466 $s = $this->getOption( "skin" );
467 if ( "" == $s ) { $s = 'standard'; }
468
469 if ( !isset( $skinNames[$s] ) ) {
470 $fallback = array(
471 'standard' => "Standard",
472 'nostalgia' => "Nostalgia",
473 'cologneblue' => "Cologne Blue");
474 if(is_int($s) && isset( $fallback[$s]) ){
475 $sn = $fallback[$s];
476 } else {
477 $sn = "SkinStandard";
478 }
479 } else {
480 $sn = "Skin" . $skinNames[$s];
481 }
482 $this->mSkin = new $sn;
483 }
484 return $this->mSkin;
485 }
486
487 function isWatched( $title ) {
488 $wl = WatchedItem::fromUserTitle( $this, $title );
489 return $wl->isWatched();
490 }
491
492 function addWatch( $title ) {
493 $wl = WatchedItem::fromUserTitle( $this, $title );
494 $wl->addWatch();
495 $this->invalidateCache();
496 }
497
498 function removeWatch( $title ) {
499 $wl = WatchedItem::fromUserTitle( $this, $title );
500 $wl->removeWatch();
501 $this->invalidateCache();
502 }
503
504
505 /* private */ function encodeOptions()
506 {
507 $a = array();
508 foreach ( $this->mOptions as $oname => $oval ) {
509 array_push( $a, "{$oname}={$oval}" );
510 }
511 $s = implode( "\n", $a );
512 return wfStrencode( $s );
513 }
514
515 /* private */ function decodeOptions( $str )
516 {
517 $a = explode( "\n", $str );
518 foreach ( $a as $s ) {
519 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
520 $this->mOptions[$m[1]] = $m[2];
521 }
522 }
523 }
524
525 function setCookies()
526 {
527 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
528 if ( 0 == $this->mId ) return;
529 $this->loadFromDatabase();
530 $exp = time() + $wgCookieExpiration;
531
532 $_SESSION['wsUserID'] = $this->mId;
533 setcookie( "{$wgDBname}UserID", $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
534
535 $_SESSION['wsUserName'] = $this->mName;
536 setcookie( "{$wgDBname}UserName", $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
537
538 $_SESSION['wsUserPassword'] = $this->mPassword;
539 if ( 1 == $this->getOption( "rememberpassword" ) ) {
540 setcookie( "{$wgDBname}Password", $this->mCookiePassword, $exp, $wgCookiePath, $wgCookieDomain );
541 } else {
542 setcookie( "{$wgDBname}Password", "", time() - 3600 );
543 }
544 }
545
546 function logout()
547 {
548 global $wgCookiePath, $wgCookieDomain, $wgDBname;
549 $this->mId = 0;
550
551 $_SESSION['wsUserID'] = 0;
552
553 setcookie( "{$wgDBname}UserID", "", time() - 3600, $wgCookiePath, $wgCookieDomain );
554 setcookie( "{$wgDBname}Password", "", time() - 3600, $wgCookiePath, $wgCookieDomain );
555 }
556
557 function saveSettings()
558 {
559 global $wgMemc, $wgDBname;
560
561 if ( ! $this->mNewtalk ) {
562 if( $this->mId ) {
563 $sql="DELETE FROM user_newtalk WHERE user_id={$this->mId}";
564 wfQuery ($sql, DB_WRITE, "User::saveSettings");
565 } else {
566 $sql="DELETE FROM user_newtalk WHERE user_ip='{$this->mName}'";
567 wfQuery ($sql, DB_WRITE, "User::saveSettings");
568 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
569 }
570 }
571 if ( 0 == $this->mId ) { return; }
572
573 $sql = "UPDATE user SET " .
574 "user_name= '" . wfStrencode( $this->mName ) . "', " .
575 "user_password= '" . wfStrencode( $this->mPassword ) . "', " .
576 "user_newpassword= '" . wfStrencode( $this->mNewpassword ) . "', " .
577 "user_real_name= '" . wfStrencode( $this->mRealName ) . "', " .
578 "user_email= '" . wfStrencode( $this->mEmail ) . "', " .
579 "user_options= '" . $this->encodeOptions() . "', " .
580 "user_rights= '" . wfStrencode( implode( ",", $this->mRights ) ) . "', " .
581 "user_touched= '" . wfStrencode( $this->mTouched ) .
582 "' WHERE user_id={$this->mId}";
583 wfQuery( $sql, DB_WRITE, "User::saveSettings" );
584 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
585 }
586
587 # Checks if a user with the given name exists
588 #
589 function idForName()
590 {
591 $gotid = 0;
592 $s = trim( $this->mName );
593 if ( 0 == strcmp( "", $s ) ) return 0;
594
595 $sql = "SELECT user_id FROM user WHERE user_name='" .
596 wfStrencode( $s ) . "'";
597 $res = wfQuery( $sql, DB_READ, "User::idForName" );
598 if ( 0 == wfNumRows( $res ) ) { return 0; }
599
600 $s = wfFetchObject( $res );
601 if ( "" == $s ) return 0;
602
603 $gotid = $s->user_id;
604 wfFreeResult( $res );
605 return $gotid;
606 }
607
608 function addToDatabase()
609 {
610 $sql = "INSERT INTO user (user_name,user_password,user_newpassword," .
611 "user_email, user_real_name, user_rights, user_options) " .
612 " VALUES ('" . wfStrencode( $this->mName ) . "', '" .
613 wfStrencode( $this->mPassword ) . "', '" .
614 wfStrencode( $this->mNewpassword ) . "', '" .
615 wfStrencode( $this->mEmail ) . "', '" .
616 wfStrencode( $this->mRealName ) . "', '" .
617 wfStrencode( implode( ",", $this->mRights ) ) . "', '" .
618 $this->encodeOptions() . "')";
619 wfQuery( $sql, DB_WRITE, "User::addToDatabase" );
620 $this->mId = $this->idForName();
621 }
622
623 function spreadBlock()
624 {
625 global $wgIP;
626 # If the (non-anonymous) user is blocked, this function will block any IP address
627 # that they successfully log on from.
628 $fname = "User::spreadBlock";
629
630 wfDebug( "User:spreadBlock()\n" );
631 if ( $this->mId == 0 ) {
632 return;
633 }
634
635 $userblock = Block::newFromDB( "", $this->mId );
636 if ( !$userblock->isValid() ) {
637 return;
638 }
639
640 # Check if this IP address is already blocked
641 $ipblock = Block::newFromDB( $wgIP );
642 if ( $ipblock->isValid() ) {
643 # Just update the timestamp
644 $ipblock->updateTimestamp();
645 return;
646 }
647
648 # Make a new block object with the desired properties
649 wfDebug( "Autoblocking {$this->mUserName}@{$wgIP}\n" );
650 $ipblock->mAddress = $wgIP;
651 $ipblock->mUser = 0;
652 $ipblock->mBy = $userblock->mBy;
653 $ipblock->mReason = wfMsg( "autoblocker", $this->getName(), $userblock->mReason );
654 $ipblock->mTimestamp = wfTimestampNow();
655 $ipblock->mAuto = 1;
656 # If the user is already blocked with an expiry date, we don't
657 # want to pile on top of that!
658 if($userblock->mExpiry) {
659 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
660 } else {
661 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
662 }
663
664 # Insert it
665 $ipblock->insert();
666
667 }
668
669 function getPageRenderingHash(){
670 static $hash = false;
671 if( $hash ){
672 return $hash;
673 }
674
675 // stubthreshold is only included below for completeness,
676 // it will always be 0 when this function is called by parsercache.
677
678 $confstr = $this->getOption( "quickbar" );
679 $confstr .= "!" . $this->getOption( "underline" );
680 $confstr .= "!" . $this->getOption( "hover" );
681 $confstr .= "!" . $this->getOption( "skin" );
682 $confstr .= "!" . $this->getOption( "math" );
683 $confstr .= "!" . $this->getOption( "highlightbroken" );
684 $confstr .= "!" . $this->getOption( "stubthreshold" );
685 $confstr .= "!" . $this->getOption( "editsection" );
686 $confstr .= "!" . $this->getOption( "editsectiononrightclick" );
687 $confstr .= "!" . $this->getOption( "showtoc" );
688 $confstr .= "!" . $this->getOption( "date" );
689
690 if(strlen($confstr) > 32)
691 $hash = md5($confstr);
692 else
693 $hash = $confstr;
694 return $hash;
695 }
696
697 function isAllowedToCreateAccount()
698 {
699 global $wgWhitelistAccount;
700 $allowed = false;
701
702 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
703 foreach ($wgWhitelistAccount as $right => $ok) {
704 $userHasRight = (!strcmp($right, "user") || in_array($right, $this->getRights()));
705 $allowed |= ($ok && $userHasRight);
706 }
707 return $allowed;
708 }
709
710 # Set mDataLoaded, return previous value
711 # Use this to prevent DB access in command-line scripts or similar situations
712 function setLoaded( $loaded )
713 {
714 wfSetVar( $this->mDataLoaded, $loaded );
715 }
716
717 function getUserPage() {
718 return Title::makeTitle( NS_USER, $this->mName );
719 }
720 }
721
722 ?>