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