changing wfQuery to allow replication
[lhc/web/wiklou.git] / includes / User.php
1 <?
2 # See user.doc
3
4 class User {
5 /* private */ var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
6 /* private */ var $mRights, $mOptions;
7 /* private */ var $mDataLoaded, $mNewpassword;
8 /* private */ var $mSkin;
9 /* private */ var $mBlockedby, $mBlockreason;
10 /* private */ var $mTouched;
11 /* private */ var $mCookiePassword;
12
13 function User()
14 {
15 $this->loadDefaults();
16 }
17
18 # Static factory method
19 #
20 function newFromName( $name )
21 {
22 $u = new User();
23
24 # Clean up name according to title rules
25
26 $t = Title::newFromText( $name );
27 $u->setName( $t->getText() );
28 return $u;
29 }
30
31 /* static */ function whoIs( $id )
32 {
33 return wfGetSQL( "user", "user_name", "user_id=$id" );
34 }
35
36 /* static */ function idFromName( $name )
37 {
38 $nt = Title::newFromText( $name );
39 $sql = "SELECT user_id FROM user WHERE user_name='" .
40 wfStrencode( $nt->getText() ) . "'";
41 $res = wfQuery( $sql, DB_READ, "User::idFromName" );
42
43 if ( 0 == wfNumRows( $res ) ) { return 0; }
44 else {
45 $s = wfFetchObject( $res );
46 return $s->user_id;
47 }
48 }
49
50 # does the string match an anonymous user IP address?
51 /* static */ function isIP( $name ) {
52 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
53
54 }
55
56 /* static */ function randomPassword()
57 {
58 $pwchars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz";
59 $l = strlen( $pwchars ) - 1;
60
61 wfSeedRandom();
62 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
63 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
64 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
65 $pwchars{mt_rand( 0, $l )};
66 return $np;
67 }
68
69 function loadDefaults()
70 {
71 global $wgLang ;
72 global $wgNamespacesToBeSearchedDefault;
73
74 $this->mId = $this->mNewtalk = 0;
75 $this->mName = getenv( "REMOTE_ADDR" );
76 $this->mEmail = "";
77 $this->mPassword = $this->mNewpassword = "";
78 $this->mRights = array();
79 $defOpt = $wgLang->getDefaultUserOptions() ;
80 foreach ( $defOpt as $oname => $val ) {
81 $this->mOptions[$oname] = $val;
82 }
83 foreach ($wgNamespacesToBeSearchedDefault as $nsnum => $val) {
84 $this->mOptions["searchNs".$nsnum] = $val;
85 }
86 unset( $this->mSkin );
87 $this->mDataLoaded = false;
88 $this->mBlockedby = -1; # Unset
89 $this->mTouched = '0'; # Allow any pages to be cached
90 $this->cookiePassword = "";
91 }
92
93 /* private */ function getBlockedStatus()
94 {
95 if ( -1 != $this->mBlockedby ) { return; }
96
97 $block = new Block();
98 if ( !$block->load( getenv( "REMOTE_ADDR" ), $this->mId ) ) {
99 wfDebug( getenv( "REMOTE_ADDR" ) ." is not blocked\n" );
100 $this->mBlockedby = 0;
101 return;
102 }
103
104 $this->mBlockedby = $block->mBy;
105 $this->mBlockreason = $block->mReason;
106 }
107
108 function isBlocked()
109 {
110 $this->getBlockedStatus();
111 if ( 0 == $this->mBlockedby ) { return false; }
112 return true;
113 }
114
115 function blockedBy() {
116 $this->getBlockedStatus();
117 return $this->mBlockedby;
118 }
119
120 function blockedFor() {
121 $this->getBlockedStatus();
122 return $this->mBlockreason;
123 }
124
125 /* static */ function loadFromSession()
126 {
127 global $HTTP_COOKIE_VARS, $wsUserID, $wsUserName, $wsUserPassword;
128 global $wgMemc, $wgDBname;
129
130 if ( isset( $wsUserID ) ) {
131 if ( 0 != $wsUserID ) {
132 $sId = $wsUserID;
133 } else {
134 return new User();
135 }
136 } else if ( isset( $HTTP_COOKIE_VARS["wcUserID"] ) ) {
137 $sId = $HTTP_COOKIE_VARS["wcUserID"];
138 $wsUserID = $sId;
139 } else {
140 return new User();
141 }
142 if ( isset( $wsUserName ) ) {
143 $sName = $wsUserName;
144 } else if ( isset( $HTTP_COOKIE_VARS["wcUserName"] ) ) {
145 $sName = $HTTP_COOKIE_VARS["wcUserName"];
146 $wsUserName = $sName;
147 } else {
148 return new User();
149 }
150
151 $passwordCorrect = FALSE;
152 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
153 if($makenew = !$user) {
154 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
155 $user = new User();
156 $user->mId = $sId;
157 $user->loadFromDatabase();
158 } else {
159 wfDebug( "User::loadFromSession() got from cache!\n" );
160 }
161
162 if ( isset( $wsUserPassword ) ) {
163 $passwordCorrect = $wsUserPassword == $user->mPassword;
164 } else if ( isset( $HTTP_COOKIE_VARS["wcUserPassword"] ) ) {
165 $user->mCookiePassword = $HTTP_COOKIE_VARS["wcUserPassword"];
166 $wsUserPassword = $user->addSalt( $user->mCookiePassword );
167 $passwordCorrect = $wsUserPassword == $user->mPassword;
168 } else {
169 return new User(); # Can't log in from session
170 }
171
172 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
173 if($makenew) {
174 if($wgMemc->set( $key, $user ))
175 wfDebug( "User::loadFromSession() successfully saved user\n" );
176 else
177 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
178 }
179 $user->spreadBlock();
180 return $user;
181 }
182 return new User(); # Can't log in from session
183 }
184
185 function loadFromDatabase()
186 {
187 if ( $this->mDataLoaded ) { return; }
188 # check in separate table if there are changes to the talk page
189 $this->mNewtalk=0; # reset talk page status
190 if($this->mId) {
191 $sql = "SELECT 1 FROM user_newtalk WHERE user_id={$this->mId}";
192 $res = wfQuery ($sql, DB_READ, "User::loadFromDatabase" );
193
194 if (wfNumRows($res)>0) {
195 $this->mNewtalk= 1;
196 }
197 wfFreeResult( $res );
198 } else {
199 global $wgDBname, $wgMemc;
200 $key = "$wgDBname:newtalk:ip:{$this->mName}";
201 $newtalk = $wgMemc->get( $key );
202 if($newtalk === false) {
203 $sql = "SELECT 1 FROM user_newtalk WHERE user_ip='{$this->mName}'";
204 $res = wfQuery ($sql, DB_READ "User::loadFromDatabase" );
205
206 $this->mNewtalk = (wfNumRows($res)>0) ? 1 : 0;
207 wfFreeResult( $res );
208
209 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
210 } else {
211 $this->mNewtalk = $newtalk ? 1 : 0;
212 }
213 }
214 if(!$this->mId) {
215 $this->mDataLoaded = true;
216 return;
217 } # the following stuff is for non-anonymous users only
218
219 $sql = "SELECT user_name,user_password,user_newpassword,user_email," .
220 "user_options,user_rights,user_touched FROM user WHERE user_id=" .
221 "{$this->mId}";
222 $res = wfQuery( $sql, DB_READ, "User::loadFromDatabase" );
223
224 if ( wfNumRows( $res ) > 0 ) {
225 $s = wfFetchObject( $res );
226 $this->mName = $s->user_name;
227 $this->mEmail = $s->user_email;
228 $this->mPassword = $s->user_password;
229 $this->mNewpassword = $s->user_newpassword;
230 $this->decodeOptions( $s->user_options );
231 $this->mRights = explode( ",", strtolower( $s->user_rights ) );
232 $this->mTouched = $s->user_touched;
233 }
234
235 wfFreeResult( $res );
236 $this->mDataLoaded = true;
237 }
238
239 function getID() { return $this->mId; }
240 function setID( $v ) {
241 $this->mId = $v;
242 $this->mDataLoaded = false;
243 }
244
245 function getName() {
246 $this->loadFromDatabase();
247 return $this->mName;
248 }
249
250 function setName( $str )
251 {
252 $this->loadFromDatabase();
253 $this->mName = $str;
254 }
255
256 function getNewtalk()
257 {
258 $this->loadFromDatabase();
259 return ( 0 != $this->mNewtalk );
260 }
261
262 function setNewtalk( $val )
263 {
264 $this->loadFromDatabase();
265 $this->mNewtalk = $val;
266 $this->invalidateCache();
267 }
268
269 function invalidateCache() {
270 $this->loadFromDatabase();
271 $this->mTouched = wfTimestampNow();
272 # Don't forget to save the options after this or
273 # it won't take effect!
274 }
275
276 function validateCache( $timestamp ) {
277 $this->loadFromDatabase();
278 return ($timestamp >= $this->mTouched);
279 }
280
281 function getPassword()
282 {
283 $this->loadFromDatabase();
284 return $this->mPassword;
285 }
286
287 function getNewpassword()
288 {
289 $this->loadFromDatabase();
290 return $this->mNewpassword;
291 }
292
293 function addSalt( $p )
294 {
295 global $wgPasswordSalt;
296 if($wgPasswordSalt)
297 return md5( "{$this->mId}-{$p}" );
298 else
299 return $p;
300 }
301
302 function encryptPassword( $p )
303 {
304 return $this->addSalt( md5( $p ) );
305 }
306
307 function setPassword( $str )
308 {
309 $this->loadFromDatabase();
310 $this->setCookiePassword( $str );
311 $this->mPassword = $this->encryptPassword( $str );
312 $this->mNewpassword = "";
313 }
314
315 function setCookiePassword( $str )
316 {
317 $this->loadFromDatabase();
318 $this->mCookiePassword = md5( $str );
319 }
320
321 function setNewpassword( $str )
322 {
323 $this->loadFromDatabase();
324 $this->mNewpassword = $this->encryptPassword( $str );
325 }
326
327 function getEmail()
328 {
329 $this->loadFromDatabase();
330 return $this->mEmail;
331 }
332
333 function setEmail( $str )
334 {
335 $this->loadFromDatabase();
336 $this->mEmail = $str;
337 }
338
339 function getOption( $oname )
340 {
341 $this->loadFromDatabase();
342 if ( array_key_exists( $oname, $this->mOptions ) ) {
343 return $this->mOptions[$oname];
344 } else {
345 return "";
346 }
347 }
348
349 function setOption( $oname, $val )
350 {
351 $this->loadFromDatabase();
352 $this->mOptions[$oname] = $val;
353 $this->invalidateCache();
354 }
355
356 function getRights()
357 {
358 $this->loadFromDatabase();
359 return $this->mRights;
360 }
361
362 function addRight( $rname )
363 {
364 $this->loadFromDatabase();
365 array_push( $this->mRights, $rname );
366 $this->invalidateCache();
367 }
368
369 function isSysop()
370 {
371 $this->loadFromDatabase();
372 if ( 0 == $this->mId ) { return false; }
373
374 return in_array( "sysop", $this->mRights );
375 }
376
377 function isDeveloper()
378 {
379 $this->loadFromDatabase();
380 if ( 0 == $this->mId ) { return false; }
381
382 return in_array( "developer", $this->mRights );
383 }
384
385 function isBot()
386 {
387 $this->loadFromDatabase();
388 if ( 0 == $this->mId ) { return false; }
389
390 return in_array( "bot", $this->mRights );
391 }
392
393 function &getSkin()
394 {
395 if ( ! isset( $this->mSkin ) ) {
396 $skinNames = Skin::getSkinNames();
397 $s = $this->getOption( "skin" );
398 if ( "" == $s ) { $s = 0; }
399
400 if ( $s >= count( $skinNames ) ) { $sn = "SkinStandard"; }
401 else $sn = "Skin" . $skinNames[$s];
402 $this->mSkin = new $sn;
403 }
404 return $this->mSkin;
405 }
406
407 function isWatched( $title )
408 {
409 # Note - $title should be a Title _object_
410 # Pages and their talk pages are considered equivalent for watching;
411 # remember that talk namespaces are numbered as page namespace+1.
412 if( $this->mId ) {
413 $sql = "SELECT 1 FROM watchlist
414 WHERE wl_user={$this->mId} AND
415 wl_namespace = " . ($title->getNamespace() & ~1) . " AND
416 wl_title='" . wfStrencode( $title->getDBkey() ) . "'";
417 $res = wfQuery( $sql, DB_READ );
418 return (wfNumRows( $res ) > 0);
419 } else {
420 return false;
421 }
422 }
423
424 function addWatch( $title )
425 {
426 if( $this->mId ) {
427 # REPLACE instead of INSERT because occasionally someone
428 # accidentally reloads a watch-add operation.
429 $sql = "REPLACE INTO watchlist (wl_user, wl_namespace,wl_title)
430 VALUES ({$this->mId}," . (($title->getNamespace() | 1) - 1) .
431 ",'" . wfStrencode( $title->getDBkey() ) . "')";
432 wfQuery( $sql, DB_WRITE );
433 $this->invalidateCache();
434 }
435 }
436
437 function removeWatch( $title )
438 {
439 if( $this->mId ) {
440 $sql = "DELETE FROM watchlist WHERE wl_user={$this->mId} AND
441 wl_namespace=" . (($title->getNamespace() | 1) - 1) .
442 " AND wl_title='" . wfStrencode( $title->getDBkey() ) . "'";
443 wfQuery( $sql, DB_WRITE );
444 $this->invalidateCache();
445 }
446 }
447
448
449 /* private */ function encodeOptions()
450 {
451 $a = array();
452 foreach ( $this->mOptions as $oname => $oval ) {
453 array_push( $a, "{$oname}={$oval}" );
454 }
455 $s = implode( "\n", $a );
456 return wfStrencode( $s );
457 }
458
459 /* private */ function decodeOptions( $str )
460 {
461 $a = explode( "\n", $str );
462 foreach ( $a as $s ) {
463 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
464 $this->mOptions[$m[1]] = $m[2];
465 }
466 }
467 }
468
469 function setCookies()
470 {
471 global $wsUserID, $wsUserName, $wsUserPassword;
472 global $wgCookieExpiration;
473 if ( 0 == $this->mId ) return;
474 $this->loadFromDatabase();
475 $exp = time() + $wgCookieExpiration;
476
477 $wsUserID = $this->mId;
478 setcookie( "wcUserID", $this->mId, $exp, "/" );
479
480 $wsUserName = $this->mName;
481 setcookie( "wcUserName", $this->mName, $exp, "/" );
482
483 $wsUserPassword = $this->mPassword;
484 if ( 1 == $this->getOption( "rememberpassword" ) ) {
485 setcookie( "wcUserPassword", $this->mCookiePassword, $exp, "/" );
486 } else {
487 setcookie( "wcUserPassword", "", time() - 3600 );
488 }
489 }
490
491 function logout()
492 {
493 global $wsUserID;
494 $this->mId = 0;
495
496 $wsUserID = 0;
497
498 setcookie( "wcUserID", "", time() - 3600 );
499 setcookie( "wcUserPassword", "", time() - 3600 );
500 }
501
502 function saveSettings()
503 {
504 global $wgMemc, $wgDBname;
505
506 if ( ! $this->mNewtalk ) {
507 if( $this->mId ) {
508 $sql="DELETE FROM user_newtalk WHERE user_id={$this->mId}";
509 wfQuery ($sql, DB_WRITE, "User::saveSettings");
510 } else {
511 $sql="DELETE FROM user_newtalk WHERE user_ip='{$this->mName}'";
512 wfQuery ($sql, DB_WRITE, "User::saveSettings");
513 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
514 }
515 }
516 if ( 0 == $this->mId ) { return; }
517
518 $sql = "UPDATE user SET " .
519 "user_name= '" . wfStrencode( $this->mName ) . "', " .
520 "user_password= '" . wfStrencode( $this->mPassword ) . "', " .
521 "user_newpassword= '" . wfStrencode( $this->mNewpassword ) . "', " .
522 "user_email= '" . wfStrencode( $this->mEmail ) . "', " .
523 "user_options= '" . $this->encodeOptions() . "', " .
524 "user_rights= '" . wfStrencode( implode( ",", $this->mRights ) ) . "', " .
525 "user_touched= '" . wfStrencode( $this->mTouched ) .
526 "' WHERE user_id={$this->mId}";
527 wfQuery( $sql, DB_WRITE, "User::saveSettings" );
528 #$wgMemc->replace( "$wgDBname:user:id:$this->mId", $this );
529 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
530 }
531
532 # Checks if a user with the given name exists
533 #
534 function idForName()
535 {
536 $gotid = 0;
537 $s = trim( $this->mName );
538 if ( 0 == strcmp( "", $s ) ) return 0;
539
540 $sql = "SELECT user_id FROM user WHERE user_name='" .
541 wfStrencode( $s ) . "'";
542 $res = wfQuery( $sql, DB_READ, "User::idForName" );
543 if ( 0 == wfNumRows( $res ) ) { return 0; }
544
545 $s = wfFetchObject( $res );
546 if ( "" == $s ) return 0;
547
548 $gotid = $s->user_id;
549 wfFreeResult( $res );
550 return $gotid;
551 }
552
553 function addToDatabase()
554 {
555 $sql = "INSERT INTO user (user_name,user_password,user_newpassword," .
556 "user_email, user_rights, user_options) " .
557 " VALUES ('" . wfStrencode( $this->mName ) . "', '" .
558 wfStrencode( $this->mPassword ) . "', '" .
559 wfStrencode( $this->mNewpassword ) . "', '" .
560 wfStrencode( $this->mEmail ) . "', '" .
561 wfStrencode( implode( ",", $this->mRights ) ) . "', '" .
562 $this->encodeOptions() . "')";
563 wfQuery( $sql, DB_WRITE, "User::addToDatabase" );
564 $this->mId = $this->idForName();
565 }
566
567 function spreadBlock()
568 {
569 # If the (non-anonymous) user is blocked, this function will block any IP address
570 # that they successfully log on from.
571 $fname = "User::spreadBlock";
572
573 wfDebug( "User:spreadBlock()\n" );
574 if ( $this->mId == 0 ) {
575 return;
576 }
577
578 $userblock = Block::newFromDB( "", $this->mId );
579 if ( !$userblock->isValid() ) {
580 return;
581 }
582
583 # Check if this IP address is already blocked
584 $addr = getenv( "REMOTE_ADDR" );
585 $ipblock = Block::newFromDB( $addr );
586 if ( $ipblock->isValid() ) {
587 # Just update the timestamp
588 $ipblock->updateTimestamp();
589 return;
590 }
591
592 # Make a new block object with the desired properties
593 wfDebug( "Autoblocking {$this->mUserName}@{$addr}\n" );
594 $ipblock->mAddress = $addr;
595 $ipblock->mUser = 0;
596 $ipblock->mBy = $userblock->mBy;
597 $ipblock->mReason = str_replace( "$1", $this->getName(), wfMsg( "autoblocker" ) );
598 $ipblock->mReason = str_replace( "$2", $userblock->mReason, $ipblock->mReason );
599 $ipblock->mTimestamp = wfTimestampNow();
600 $ipblock->mAuto = 1;
601
602 # Insert it
603 $ipblock->insert();
604
605 }
606
607
608 function isAllowedToCreateAccount()
609 {
610 global $wgWhitelistAccount;
611 $allowed = false;
612
613 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
614 foreach ($wgWhitelistAccount as $right => $ok) {
615 $userHasRight = (!strcmp($right, "user") || in_array($right, $this->getRights()));
616 $allowed |= ($ok && $userHasRight);
617 }
618 return $allowed;
619 }
620
621
622
623 }
624
625 ?>