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