compatibility modifications in preparation for the new memcached client
[lhc/web/wiklou.git] / includes / User.php
1 <?
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 ;
74 global $wgNamespacesToBeSearchedDefault;
75
76 $this->mId = $this->mNewtalk = 0;
77 $this->mName = getenv( "REMOTE_ADDR" );
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 $wgBadRanges, $wgBadUserAgents, $wgRangeBlockUser, $wgRangeBlockReason;
98
99 if ( -1 != $this->mBlockedby ) { return; }
100
101 # Range/user-agent blocking
102
103 $fBlock = false; # Mmmm, Hungarian
104 if ( ( !is_array( $wgBadUserAgents ) ||
105 array_key_exists( getenv( "HTTP_USER_AGENT" ), $wgBadUserAgents ) ) &&
106 is_array( $wgBadRanges ) )
107 {
108 $iIp = ip2long( getenv( "REMOTE_ADDR" ) );
109 foreach ( $wgBadRanges as $range ) {
110 $start = ip2long( $range[0] );
111 $end = ip2long( $range[1] );
112 if ( $iIp >= $start && $iIp <= $end ) {
113 $fBlock = true;
114 break;
115 }
116 }
117 }
118
119 if ( $fBlock ) {
120 $this->mBlockedby = $wgRangeBlockUser;
121 $this->mBlockreason = $wgRangeBlockReason;
122 return;
123 }
124
125 # User/IP blocking
126
127 $block = new Block();
128 if ( !$block->load( getenv( "REMOTE_ADDR" ), $this->mId ) ) {
129 wfDebug( getenv( "REMOTE_ADDR" ) ." is not blocked\n" );
130 $this->mBlockedby = 0;
131 return;
132 }
133
134 $this->mBlockedby = $block->mBy;
135 $this->mBlockreason = $block->mReason;
136 }
137
138 function isBlocked()
139 {
140 $this->getBlockedStatus();
141 if ( 0 == $this->mBlockedby ) { return false; }
142 return true;
143 }
144
145 function blockedBy() {
146 $this->getBlockedStatus();
147 return $this->mBlockedby;
148 }
149
150 function blockedFor() {
151 $this->getBlockedStatus();
152 return $this->mBlockreason;
153 }
154
155 /* static */ function loadFromSession()
156 {
157 global $HTTP_COOKIE_VARS, $wsUserID, $wsUserName, $wsUserPassword;
158 global $wgMemc, $wgDBname;
159
160 if ( isset( $wsUserID ) ) {
161 if ( 0 != $wsUserID ) {
162 $sId = $wsUserID;
163 } else {
164 return new User();
165 }
166 } else if ( isset( $HTTP_COOKIE_VARS["{$wgDBname}UserID"] ) ) {
167 $sId = $HTTP_COOKIE_VARS["{$wgDBname}UserID"];
168 $wsUserID = $sId;
169 } else {
170 return new User();
171 }
172 if ( isset( $wsUserName ) ) {
173 $sName = $wsUserName;
174 } else if ( isset( $HTTP_COOKIE_VARS["{$wgDBname}UserName"] ) ) {
175 $sName = $HTTP_COOKIE_VARS["{$wgDBname}UserName"];
176 $wsUserName = $sName;
177 } else {
178 return new User();
179 }
180
181 $passwordCorrect = FALSE;
182 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
183 if($makenew = !$user) {
184 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
185 $user = new User();
186 $user->mId = $sId;
187 $user->loadFromDatabase();
188 } else {
189 wfDebug( "User::loadFromSession() got from cache!\n" );
190 }
191
192 if ( isset( $wsUserPassword ) ) {
193 $passwordCorrect = $wsUserPassword == $user->mPassword;
194 } else if ( isset( $HTTP_COOKIE_VARS["{$wgDBname}Password"] ) ) {
195 $user->mCookiePassword = $HTTP_COOKIE_VARS["{$wgDBname}Password"];
196 $wsUserPassword = $user->addSalt( $user->mCookiePassword );
197 $passwordCorrect = $wsUserPassword == $user->mPassword;
198 } else {
199 return new User(); # Can't log in from session
200 }
201
202 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
203 if($makenew) {
204 if($wgMemc->set( $key, $user ))
205 wfDebug( "User::loadFromSession() successfully saved user\n" );
206 else
207 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
208 }
209 $user->spreadBlock();
210 return $user;
211 }
212 return new User(); # Can't log in from session
213 }
214
215 function loadFromDatabase()
216 {
217 if ( $this->mDataLoaded ) { return; }
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 isBot()
417 {
418 $this->loadFromDatabase();
419 if ( 0 == $this->mId ) { return false; }
420
421 return in_array( "bot", $this->mRights );
422 }
423
424 function &getSkin()
425 {
426 if ( ! isset( $this->mSkin ) ) {
427 $skinNames = Skin::getSkinNames();
428 $s = $this->getOption( "skin" );
429 if ( "" == $s ) { $s = 0; }
430
431 if ( $s >= count( $skinNames ) ) { $sn = "SkinStandard"; }
432 else $sn = "Skin" . $skinNames[$s];
433 $this->mSkin = new $sn;
434 }
435 return $this->mSkin;
436 }
437
438 function isWatched( $title ) {
439 $wl = WatchedItem::fromUserTitle( $this, $title );
440 return $wl->isWatched();
441 }
442
443 function addWatch( $title ) {
444 $wl = WatchedItem::fromUserTitle( $this, $title );
445 $wl->addWatch();
446 $this->invalidateCache();
447 }
448
449 function removeWatch( $title ) {
450 $wl = WatchedItem::fromUserTitle( $this, $title );
451 $wl->removeWatch();
452 $this->invalidateCache();
453 }
454
455
456 /* private */ function encodeOptions()
457 {
458 $a = array();
459 foreach ( $this->mOptions as $oname => $oval ) {
460 array_push( $a, "{$oname}={$oval}" );
461 }
462 $s = implode( "\n", $a );
463 return wfStrencode( $s );
464 }
465
466 /* private */ function decodeOptions( $str )
467 {
468 $a = explode( "\n", $str );
469 foreach ( $a as $s ) {
470 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
471 $this->mOptions[$m[1]] = $m[2];
472 }
473 }
474 }
475
476 function setCookies()
477 {
478 global $wsUserID, $wsUserName, $wsUserPassword;
479 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
480 if ( 0 == $this->mId ) return;
481 $this->loadFromDatabase();
482 $exp = time() + $wgCookieExpiration;
483
484 $wsUserID = $this->mId;
485 setcookie( "{$wgDBname}UserID", $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
486
487 $wsUserName = $this->mName;
488 setcookie( "{$wgDBname}UserName", $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
489
490 $wsUserPassword = $this->mPassword;
491 if ( 1 == $this->getOption( "rememberpassword" ) ) {
492 setcookie( "{$wgDBname}Password", $this->mCookiePassword, $exp, $wgCookiePath, $wgCookieDomain );
493 } else {
494 setcookie( "{$wgDBname}Password", "", time() - 3600 );
495 }
496 }
497
498 function logout()
499 {
500 global $wsUserID, $wgCookiePath, $wgCookieDomain, $wgDBname;
501 $this->mId = 0;
502
503 $wsUserID = 0;
504
505 setcookie( "{$wgDBname}UserID", "", time() - 3600, $wgCookiePath, $wgCookieDomain );
506 setcookie( "{$wgDBname}Password", "", time() - 3600, $wgCookiePath, $wgCookieDomain );
507 }
508
509 function saveSettings()
510 {
511 global $wgMemc, $wgDBname;
512
513 if ( ! $this->mNewtalk ) {
514 if( $this->mId ) {
515 $sql="DELETE FROM user_newtalk WHERE user_id={$this->mId}";
516 wfQuery ($sql, DB_WRITE, "User::saveSettings");
517 } else {
518 $sql="DELETE FROM user_newtalk WHERE user_ip='{$this->mName}'";
519 wfQuery ($sql, DB_WRITE, "User::saveSettings");
520 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
521 }
522 }
523 if ( 0 == $this->mId ) { return; }
524
525 $sql = "UPDATE user SET " .
526 "user_name= '" . wfStrencode( $this->mName ) . "', " .
527 "user_password= '" . wfStrencode( $this->mPassword ) . "', " .
528 "user_newpassword= '" . wfStrencode( $this->mNewpassword ) . "', " .
529 "user_email= '" . wfStrencode( $this->mEmail ) . "', " .
530 "user_options= '" . $this->encodeOptions() . "', " .
531 "user_rights= '" . wfStrencode( implode( ",", $this->mRights ) ) . "', " .
532 "user_touched= '" . wfStrencode( $this->mTouched ) .
533 "' WHERE user_id={$this->mId}";
534 wfQuery( $sql, DB_WRITE, "User::saveSettings" );
535 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
536 }
537
538 # Checks if a user with the given name exists
539 #
540 function idForName()
541 {
542 $gotid = 0;
543 $s = trim( $this->mName );
544 if ( 0 == strcmp( "", $s ) ) return 0;
545
546 $sql = "SELECT user_id FROM user WHERE user_name='" .
547 wfStrencode( $s ) . "'";
548 $res = wfQuery( $sql, DB_READ, "User::idForName" );
549 if ( 0 == wfNumRows( $res ) ) { return 0; }
550
551 $s = wfFetchObject( $res );
552 if ( "" == $s ) return 0;
553
554 $gotid = $s->user_id;
555 wfFreeResult( $res );
556 return $gotid;
557 }
558
559 function addToDatabase()
560 {
561 $sql = "INSERT INTO user (user_name,user_password,user_newpassword," .
562 "user_email, user_rights, user_options) " .
563 " VALUES ('" . wfStrencode( $this->mName ) . "', '" .
564 wfStrencode( $this->mPassword ) . "', '" .
565 wfStrencode( $this->mNewpassword ) . "', '" .
566 wfStrencode( $this->mEmail ) . "', '" .
567 wfStrencode( implode( ",", $this->mRights ) ) . "', '" .
568 $this->encodeOptions() . "')";
569 wfQuery( $sql, DB_WRITE, "User::addToDatabase" );
570 $this->mId = $this->idForName();
571 }
572
573 function spreadBlock()
574 {
575 # If the (non-anonymous) user is blocked, this function will block any IP address
576 # that they successfully log on from.
577 $fname = "User::spreadBlock";
578
579 wfDebug( "User:spreadBlock()\n" );
580 if ( $this->mId == 0 ) {
581 return;
582 }
583
584 $userblock = Block::newFromDB( "", $this->mId );
585 if ( !$userblock->isValid() ) {
586 return;
587 }
588
589 # Check if this IP address is already blocked
590 $addr = getenv( "REMOTE_ADDR" );
591 $ipblock = Block::newFromDB( $addr );
592 if ( $ipblock->isValid() ) {
593 # Just update the timestamp
594 $ipblock->updateTimestamp();
595 return;
596 }
597
598 # Make a new block object with the desired properties
599 wfDebug( "Autoblocking {$this->mUserName}@{$addr}\n" );
600 $ipblock->mAddress = $addr;
601 $ipblock->mUser = 0;
602 $ipblock->mBy = $userblock->mBy;
603 $ipblock->mReason = wfMsg( "autoblocker", $this->getName(), $userblock->mReason );
604 $ipblock->mTimestamp = wfTimestampNow();
605 $ipblock->mAuto = 1;
606
607 # Insert it
608 $ipblock->insert();
609
610 }
611
612 function getPageRenderingHash(){
613 static $hash = false;
614 if( $hash ){
615 return $hash;
616 }
617
618 // stubthreshold is only included below for completeness,
619 // it will always be 0 when this function is called by parsercache.
620
621 $confstr = $this->getOption( "quickbar" );
622 $confstr .= "!" . $this->getOption( "underline" );
623 $confstr .= "!" . $this->getOption( "hover" );
624 $confstr .= "!" . $this->getOption( "skin" );
625 $confstr .= "!" . $this->getOption( "math" );
626 $confstr .= "!" . $this->getOption( "highlightbroken" );
627 $confstr .= "!" . $this->getOption( "stubthreshold" );
628 $confstr .= "!" . $this->getOption( "editsection" );
629 $confstr .= "!" . $this->getOption( "editsectiononrightclick" );
630 $confstr .= "!" . $this->getOption( "showtoc" );
631 $confstr .= "!" . $this->getOption( "date" );
632
633 if(strlen($confstr) > 32)
634 $hash = md5($confstr);
635 else
636 $hash = $confstr;
637 return $hash;
638 }
639
640 function isAllowedToCreateAccount()
641 {
642 global $wgWhitelistAccount;
643 $allowed = false;
644
645 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
646 foreach ($wgWhitelistAccount as $right => $ok) {
647 $userHasRight = (!strcmp($right, "user") || in_array($right, $this->getRights()));
648 $allowed |= ($ok && $userHasRight);
649 }
650 return $allowed;
651 }
652
653
654
655 }
656
657 ?>