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