XHTML fixes
[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 if( $wgSessionsInMemcached ) {
142 include_once( "MemcachedSessions.php" );
143 }
144 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
145 session_cache_limiter( "private, must-revalidate" );
146 session_start();
147 }
148
149 /* static */ function loadFromSession()
150 {
151 global $wgMemc, $wgDBname;
152
153 if ( isset( $_SESSION['wsUserID'] ) ) {
154 if ( 0 != $_SESSION['wsUserID'] ) {
155 $sId = $_SESSION['wsUserID'];
156 } else {
157 return new User();
158 }
159 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
160 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
161 $_SESSION['wsUserID'] = $sId;
162 } else {
163 return new User();
164 }
165 if ( isset( $_SESSION['wsUserName'] ) ) {
166 $sName = $_SESSION['wsUserName'];
167 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
168 $sName = $_COOKIE["{$wgDBname}UserName"];
169 $_SESSION['wsUserName'] = $sName;
170 } else {
171 return new User();
172 }
173
174 $passwordCorrect = FALSE;
175 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
176 if($makenew = !$user) {
177 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
178 $user = new User();
179 $user->mId = $sId;
180 $user->loadFromDatabase();
181 } else {
182 wfDebug( "User::loadFromSession() got from cache!\n" );
183 }
184
185 if ( isset( $_SESSION['wsUserPassword'] ) ) {
186 $passwordCorrect = $_SESSION['wsUserPassword'] == $user->mPassword;
187 } else if ( isset( $_COOKIE["{$wgDBname}Password"] ) ) {
188 $user->mCookiePassword = $_COOKIE["{$wgDBname}Password"];
189 $_SESSION['wsUserPassword'] = $user->addSalt( $user->mCookiePassword );
190 $passwordCorrect = $_SESSION['wsUserPassword'] == $user->mPassword;
191 } else {
192 return new User(); # Can't log in from session
193 }
194
195 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
196 if($makenew) {
197 if($wgMemc->set( $key, $user ))
198 wfDebug( "User::loadFromSession() successfully saved user\n" );
199 else
200 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
201 }
202 $user->spreadBlock();
203 return $user;
204 }
205 return new User(); # Can't log in from session
206 }
207
208 function loadFromDatabase()
209 {
210 global $wgCommandLineMode;
211 if ( $this->mDataLoaded || $wgCommandLineMode ) {
212 return;
213 }
214
215 # Paranoia
216 $this->mId = IntVal( $this->mId );
217
218 # check in separate table if there are changes to the talk page
219 $this->mNewtalk=0; # reset talk page status
220 if($this->mId) {
221 $sql = "SELECT 1 FROM user_newtalk WHERE user_id={$this->mId}";
222 $res = wfQuery ($sql, DB_READ, "User::loadFromDatabase" );
223
224 if (wfNumRows($res)>0) {
225 $this->mNewtalk= 1;
226 }
227 wfFreeResult( $res );
228 } else {
229 global $wgDBname, $wgMemc;
230 $key = "$wgDBname:newtalk:ip:{$this->mName}";
231 $newtalk = $wgMemc->get( $key );
232 if( ! is_integer( $newtalk ) ){
233 $sql = "SELECT 1 FROM user_newtalk WHERE user_ip='{$this->mName}'";
234 $res = wfQuery ($sql, DB_READ, "User::loadFromDatabase" );
235
236 $this->mNewtalk = (wfNumRows($res)>0) ? 1 : 0;
237 wfFreeResult( $res );
238
239 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
240 } else {
241 $this->mNewtalk = $newtalk ? 1 : 0;
242 }
243 }
244 if(!$this->mId) {
245 $this->mDataLoaded = true;
246 return;
247 } # the following stuff is for non-anonymous users only
248
249 $sql = "SELECT user_name,user_password,user_newpassword,user_email," .
250 "user_options,user_rights,user_touched FROM user WHERE user_id=" .
251 "{$this->mId}";
252 $res = wfQuery( $sql, DB_READ, "User::loadFromDatabase" );
253
254 if ( wfNumRows( $res ) > 0 ) {
255 $s = wfFetchObject( $res );
256 $this->mName = $s->user_name;
257 $this->mEmail = $s->user_email;
258 $this->mPassword = $s->user_password;
259 $this->mNewpassword = $s->user_newpassword;
260 $this->decodeOptions( $s->user_options );
261 $this->mRights = explode( ",", strtolower( $s->user_rights ) );
262 $this->mTouched = $s->user_touched;
263 }
264
265 wfFreeResult( $res );
266 $this->mDataLoaded = true;
267 }
268
269 function getID() { return $this->mId; }
270 function setID( $v ) {
271 $this->mId = $v;
272 $this->mDataLoaded = false;
273 }
274
275 function getName() {
276 $this->loadFromDatabase();
277 return $this->mName;
278 }
279
280 function setName( $str )
281 {
282 $this->loadFromDatabase();
283 $this->mName = $str;
284 }
285
286 function getNewtalk()
287 {
288 $this->loadFromDatabase();
289 return ( 0 != $this->mNewtalk );
290 }
291
292 function setNewtalk( $val )
293 {
294 $this->loadFromDatabase();
295 $this->mNewtalk = $val;
296 $this->invalidateCache();
297 }
298
299 function invalidateCache() {
300 $this->loadFromDatabase();
301 $this->mTouched = wfTimestampNow();
302 # Don't forget to save the options after this or
303 # it won't take effect!
304 }
305
306 function validateCache( $timestamp ) {
307 $this->loadFromDatabase();
308 return ($timestamp >= $this->mTouched);
309 }
310
311 function getPassword()
312 {
313 $this->loadFromDatabase();
314 return $this->mPassword;
315 }
316
317 function getNewpassword()
318 {
319 $this->loadFromDatabase();
320 return $this->mNewpassword;
321 }
322
323 function addSalt( $p )
324 {
325 global $wgPasswordSalt;
326 if($wgPasswordSalt)
327 return md5( "{$this->mId}-{$p}" );
328 else
329 return $p;
330 }
331
332 function encryptPassword( $p )
333 {
334 return $this->addSalt( md5( $p ) );
335 }
336
337 function setPassword( $str )
338 {
339 $this->loadFromDatabase();
340 $this->setCookiePassword( $str );
341 $this->mPassword = $this->encryptPassword( $str );
342 $this->mNewpassword = "";
343 }
344
345 function setCookiePassword( $str )
346 {
347 $this->loadFromDatabase();
348 $this->mCookiePassword = md5( $str );
349 }
350
351 function setNewpassword( $str )
352 {
353 $this->loadFromDatabase();
354 $this->mNewpassword = $this->encryptPassword( $str );
355 }
356
357 function getEmail()
358 {
359 $this->loadFromDatabase();
360 return $this->mEmail;
361 }
362
363 function setEmail( $str )
364 {
365 $this->loadFromDatabase();
366 $this->mEmail = $str;
367 }
368
369 function getOption( $oname )
370 {
371 $this->loadFromDatabase();
372 if ( array_key_exists( $oname, $this->mOptions ) ) {
373 return $this->mOptions[$oname];
374 } else {
375 return "";
376 }
377 }
378
379 function setOption( $oname, $val )
380 {
381 $this->loadFromDatabase();
382 $this->mOptions[$oname] = $val;
383 $this->invalidateCache();
384 }
385
386 function getRights()
387 {
388 $this->loadFromDatabase();
389 return $this->mRights;
390 }
391
392 function addRight( $rname )
393 {
394 $this->loadFromDatabase();
395 array_push( $this->mRights, $rname );
396 $this->invalidateCache();
397 }
398
399 function isSysop()
400 {
401 $this->loadFromDatabase();
402 if ( 0 == $this->mId ) { return false; }
403
404 return in_array( "sysop", $this->mRights );
405 }
406
407 function isDeveloper()
408 {
409 $this->loadFromDatabase();
410 if ( 0 == $this->mId ) { return false; }
411
412 return in_array( "developer", $this->mRights );
413 }
414
415 function isBureaucrat()
416 {
417 $this->loadFromDatabase();
418 if ( 0 == $this->mId ) { return false; }
419
420 return in_array( "bureaucrat", $this->mRights );
421 }
422
423 function isBot()
424 {
425 $this->loadFromDatabase();
426
427 # Why was this here? I need a UID=0 conversion script [TS]
428 # if ( 0 == $this->mId ) { return false; }
429
430 return in_array( "bot", $this->mRights );
431 }
432
433 function &getSkin()
434 {
435 if ( ! isset( $this->mSkin ) ) {
436 $skinNames = Skin::getSkinNames();
437 $s = $this->getOption( "skin" );
438 if ( "" == $s ) { $s = 'standard'; }
439
440 if ( !isset( $skinNames[$s] ) ) {
441 $fallback = array(
442 'standard' => "Standard",
443 'nostalgia' => "Nostalgia",
444 'cologneblue' => "Cologne Blue");
445 if(is_int($s) && isset( $fallback[$s]) ){
446 $sn = $fallback[$s];
447 } else {
448 $sn = "SkinStandard";
449 }
450 } else {
451 $sn = "Skin" . $skinNames[$s];
452 }
453 $this->mSkin = new $sn;
454 }
455 return $this->mSkin;
456 }
457
458 function isWatched( $title ) {
459 $wl = WatchedItem::fromUserTitle( $this, $title );
460 return $wl->isWatched();
461 }
462
463 function addWatch( $title ) {
464 $wl = WatchedItem::fromUserTitle( $this, $title );
465 $wl->addWatch();
466 $this->invalidateCache();
467 }
468
469 function removeWatch( $title ) {
470 $wl = WatchedItem::fromUserTitle( $this, $title );
471 $wl->removeWatch();
472 $this->invalidateCache();
473 }
474
475
476 /* private */ function encodeOptions()
477 {
478 $a = array();
479 foreach ( $this->mOptions as $oname => $oval ) {
480 array_push( $a, "{$oname}={$oval}" );
481 }
482 $s = implode( "\n", $a );
483 return wfStrencode( $s );
484 }
485
486 /* private */ function decodeOptions( $str )
487 {
488 $a = explode( "\n", $str );
489 foreach ( $a as $s ) {
490 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
491 $this->mOptions[$m[1]] = $m[2];
492 }
493 }
494 }
495
496 function setCookies()
497 {
498 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
499 if ( 0 == $this->mId ) return;
500 $this->loadFromDatabase();
501 $exp = time() + $wgCookieExpiration;
502
503 $_SESSION['wsUserID'] = $this->mId;
504 setcookie( "{$wgDBname}UserID", $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
505
506 $_SESSION['wsUserName'] = $this->mName;
507 setcookie( "{$wgDBname}UserName", $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
508
509 $_SESSION['wsUserPassword'] = $this->mPassword;
510 if ( 1 == $this->getOption( "rememberpassword" ) ) {
511 setcookie( "{$wgDBname}Password", $this->mCookiePassword, $exp, $wgCookiePath, $wgCookieDomain );
512 } else {
513 setcookie( "{$wgDBname}Password", "", time() - 3600 );
514 }
515 }
516
517 function logout()
518 {
519 global $wgCookiePath, $wgCookieDomain, $wgDBname;
520 $this->mId = 0;
521
522 $_SESSION['wsUserID'] = 0;
523
524 setcookie( "{$wgDBname}UserID", "", time() - 3600, $wgCookiePath, $wgCookieDomain );
525 setcookie( "{$wgDBname}Password", "", time() - 3600, $wgCookiePath, $wgCookieDomain );
526 }
527
528 function saveSettings()
529 {
530 global $wgMemc, $wgDBname;
531
532 if ( ! $this->mNewtalk ) {
533 if( $this->mId ) {
534 $sql="DELETE FROM user_newtalk WHERE user_id={$this->mId}";
535 wfQuery ($sql, DB_WRITE, "User::saveSettings");
536 } else {
537 $sql="DELETE FROM user_newtalk WHERE user_ip='{$this->mName}'";
538 wfQuery ($sql, DB_WRITE, "User::saveSettings");
539 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
540 }
541 }
542 if ( 0 == $this->mId ) { return; }
543
544 $sql = "UPDATE user SET " .
545 "user_name= '" . wfStrencode( $this->mName ) . "', " .
546 "user_password= '" . wfStrencode( $this->mPassword ) . "', " .
547 "user_newpassword= '" . wfStrencode( $this->mNewpassword ) . "', " .
548 "user_email= '" . wfStrencode( $this->mEmail ) . "', " .
549 "user_options= '" . $this->encodeOptions() . "', " .
550 "user_rights= '" . wfStrencode( implode( ",", $this->mRights ) ) . "', " .
551 "user_touched= '" . wfStrencode( $this->mTouched ) .
552 "' WHERE user_id={$this->mId}";
553 wfQuery( $sql, DB_WRITE, "User::saveSettings" );
554 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
555 }
556
557 # Checks if a user with the given name exists
558 #
559 function idForName()
560 {
561 $gotid = 0;
562 $s = trim( $this->mName );
563 if ( 0 == strcmp( "", $s ) ) return 0;
564
565 $sql = "SELECT user_id FROM user WHERE user_name='" .
566 wfStrencode( $s ) . "'";
567 $res = wfQuery( $sql, DB_READ, "User::idForName" );
568 if ( 0 == wfNumRows( $res ) ) { return 0; }
569
570 $s = wfFetchObject( $res );
571 if ( "" == $s ) return 0;
572
573 $gotid = $s->user_id;
574 wfFreeResult( $res );
575 return $gotid;
576 }
577
578 function addToDatabase()
579 {
580 $sql = "INSERT INTO user (user_name,user_password,user_newpassword," .
581 "user_email, user_rights, user_options) " .
582 " VALUES ('" . wfStrencode( $this->mName ) . "', '" .
583 wfStrencode( $this->mPassword ) . "', '" .
584 wfStrencode( $this->mNewpassword ) . "', '" .
585 wfStrencode( $this->mEmail ) . "', '" .
586 wfStrencode( implode( ",", $this->mRights ) ) . "', '" .
587 $this->encodeOptions() . "')";
588 wfQuery( $sql, DB_WRITE, "User::addToDatabase" );
589 $this->mId = $this->idForName();
590 }
591
592 function spreadBlock()
593 {
594 global $wgIP;
595 # If the (non-anonymous) user is blocked, this function will block any IP address
596 # that they successfully log on from.
597 $fname = "User::spreadBlock";
598
599 wfDebug( "User:spreadBlock()\n" );
600 if ( $this->mId == 0 ) {
601 return;
602 }
603
604 $userblock = Block::newFromDB( "", $this->mId );
605 if ( !$userblock->isValid() ) {
606 return;
607 }
608
609 # Check if this IP address is already blocked
610 $ipblock = Block::newFromDB( $wgIP );
611 if ( $ipblock->isValid() ) {
612 # Just update the timestamp
613 $ipblock->updateTimestamp();
614 return;
615 }
616
617 # Make a new block object with the desired properties
618 wfDebug( "Autoblocking {$this->mUserName}@{$wgIP}\n" );
619 $ipblock->mAddress = $wgIP;
620 $ipblock->mUser = 0;
621 $ipblock->mBy = $userblock->mBy;
622 $ipblock->mReason = wfMsg( "autoblocker", $this->getName(), $userblock->mReason );
623 $ipblock->mTimestamp = wfTimestampNow();
624 $ipblock->mAuto = 1;
625 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
626
627 # Insert it
628 $ipblock->insert();
629
630 }
631
632 function getPageRenderingHash(){
633 static $hash = false;
634 if( $hash ){
635 return $hash;
636 }
637
638 // stubthreshold is only included below for completeness,
639 // it will always be 0 when this function is called by parsercache.
640
641 $confstr = $this->getOption( "quickbar" );
642 $confstr .= "!" . $this->getOption( "underline" );
643 $confstr .= "!" . $this->getOption( "hover" );
644 $confstr .= "!" . $this->getOption( "skin" );
645 $confstr .= "!" . $this->getOption( "math" );
646 $confstr .= "!" . $this->getOption( "highlightbroken" );
647 $confstr .= "!" . $this->getOption( "stubthreshold" );
648 $confstr .= "!" . $this->getOption( "editsection" );
649 $confstr .= "!" . $this->getOption( "editsectiononrightclick" );
650 $confstr .= "!" . $this->getOption( "showtoc" );
651 $confstr .= "!" . $this->getOption( "date" );
652
653 if(strlen($confstr) > 32)
654 $hash = md5($confstr);
655 else
656 $hash = $confstr;
657 return $hash;
658 }
659
660 function isAllowedToCreateAccount()
661 {
662 global $wgWhitelistAccount;
663 $allowed = false;
664
665 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
666 foreach ($wgWhitelistAccount as $right => $ok) {
667 $userHasRight = (!strcmp($right, "user") || in_array($right, $this->getRights()));
668 $allowed |= ($ok && $userHasRight);
669 }
670 return $allowed;
671 }
672
673 # Set mDataLoaded, return previous value
674 # Use this to prevent DB access in command-line scripts or similar situations
675 function setLoaded( $loaded )
676 {
677 wfSetVar( $this->mDataLoaded, $loaded );
678 }
679 }
680
681 ?>