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