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