Have the skin cache the highlightbroken and hover options to avoid asking the user...
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * See user.doc
4 *
5 * @package MediaWiki
6 */
7
8 /**
9 *
10 */
11 require_once( 'WatchedItem.php' );
12 require_once( 'Group.php' );
13
14 # Number of characters in user_token field
15 define( 'USER_TOKEN_LENGTH', 32 );
16
17 /**
18 *
19 * @package MediaWiki
20 */
21 class User {
22 /**#@+
23 * @access private
24 */
25 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
26 var $mRights, $mOptions;
27 var $mDataLoaded, $mNewpassword;
28 var $mSkin;
29 var $mBlockedby, $mBlockreason;
30 var $mTouched;
31 var $mToken;
32 var $mRealName;
33 var $mHash;
34 /** Array of group id the user belong to */
35 var $mGroups;
36 /**#@-*/
37
38 /** Construct using User:loadDefaults() */
39 function User() {
40 $this->loadDefaults();
41 }
42
43 /**
44 * Static factory method
45 * @static
46 * @param string $name Username, validated by Title:newFromText()
47 */
48 function newFromName( $name ) {
49 $u = new User();
50
51 # Clean up name according to title rules
52
53 $t = Title::newFromText( $name );
54 if( is_null( $t ) ) {
55 return NULL;
56 } else {
57 $u->setName( $t->getText() );
58 return $u;
59 }
60 }
61
62 /**
63 * Get username given an id.
64 * @param integer $id Database user id
65 * @return string Nickname of a user
66 * @static
67 */
68 function whoIs( $id ) {
69 $dbr =& wfGetDB( DB_SLAVE );
70 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
71 }
72
73 /**
74 * Get real username given an id.
75 * @param integer $id Database user id
76 * @return string Realname of a user
77 * @static
78 */
79 function whoIsReal( $id ) {
80 $dbr =& wfGetDB( DB_SLAVE );
81 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
82 }
83
84 /**
85 * Get database id given a user name
86 * @param string $name Nickname of a user
87 * @return integer|null Database user id (null: if non existent
88 * @static
89 */
90 function idFromName( $name ) {
91 $fname = "User::idFromName";
92
93 $nt = Title::newFromText( $name );
94 if( is_null( $nt ) ) {
95 # Illegal name
96 return null;
97 }
98 $dbr =& wfGetDB( DB_SLAVE );
99 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
100
101 if ( $s === false ) {
102 return 0;
103 } else {
104 return $s->user_id;
105 }
106 }
107
108 /**
109 * does the string match an anonymous user IP address?
110 * @param string $name Nickname of a user
111 * @static
112 */
113 function isIP( $name ) {
114 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
115 }
116
117 /**
118 * probably return a random password
119 * @return string probably a random password
120 * @static
121 * @todo Check what is doing really [AV]
122 */
123 function randomPassword() {
124 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
125 $l = strlen( $pwchars ) - 1;
126
127 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
128 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
129 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
130 $pwchars{mt_rand( 0, $l )};
131 return $np;
132 }
133
134 /**
135 * Set properties to default
136 * Used at construction. It will load per language default settings only
137 * if we have an available language object.
138 */
139 function loadDefaults() {
140 static $n=0;
141 $n++;
142 $fname = 'User::loadDefaults' . $n;
143 wfProfileIn( $fname );
144
145 global $wgContLang, $wgIP;
146 global $wgNamespacesToBeSearchedDefault;
147
148 $this->mId = 0;
149 $this->mNewtalk = -1;
150 $this->mName = $wgIP;
151 $this->mRealName = $this->mEmail = '';
152 $this->mPassword = $this->mNewpassword = '';
153 $this->mRights = array();
154 $this->mGroups = array();
155
156 // Getting user defaults only if we have an available language
157 if( isset( $wgContLang ) ) {
158 $this->loadDefaultFromLanguage();
159 }
160
161 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
162 $this->mOptions['searchNs'.$nsnum] = $val;
163 }
164 unset( $this->mSkin );
165 $this->mDataLoaded = false;
166 $this->mBlockedby = -1; # Unset
167 $this->mTouched = '0'; # Allow any pages to be cached
168 $this->setToken(); # Random
169 $this->mHash = false;
170 wfProfileOut( $fname );
171 }
172
173 /**
174 * Used to load user options from a language.
175 * This is not in loadDefault() cause we sometime create user before having
176 * a language object.
177 */
178 function loadDefaultFromLanguage(){
179 $fname = 'User::loadDefaultFromLanguage';
180 wfProfileIn( $fname );
181
182 /**
183 * Site defaults will override the global/language defaults
184 */
185 global $wgContLang, $wgDefaultUserOptions;
186 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptions();
187
188 /**
189 * default language setting
190 */
191 $variant = $wgContLang->getPreferredVariant();
192 $defOpt['variant'] = $variant;
193 $defOpt['language'] = $variant;
194
195 $this->mOptions = $defOpt;
196
197 wfProfileOut();
198 }
199
200 /**
201 * Get blocking information
202 * @access private
203 */
204 function getBlockedStatus() {
205 global $wgIP, $wgBlockCache, $wgProxyList;
206
207 if ( -1 != $this->mBlockedby ) { return; }
208
209 $this->mBlockedby = 0;
210
211 # User blocking
212 if ( $this->mId ) {
213 $block = new Block();
214 if ( $block->load( $wgIP , $this->mId ) ) {
215 $this->mBlockedby = $block->mBy;
216 $this->mBlockreason = $block->mReason;
217 }
218 }
219
220 # IP/range blocking
221 if ( !$this->mBlockedby ) {
222 $block = $wgBlockCache->get( $wgIP );
223 if ( $block !== false ) {
224 $this->mBlockedby = $block->mBy;
225 $this->mBlockreason = $block->mReason;
226 }
227 }
228
229 # Proxy blocking
230 if ( !$this->mBlockedby ) {
231 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
232 $this->mBlockreason = wfMsg( 'proxyblockreason' );
233 $this->mBlockedby = "Proxy blocker";
234 }
235 }
236 }
237
238 /**
239 * Check if user is blocked
240 * @return bool True if blocked, false otherwise
241 */
242 function isBlocked() {
243 $this->getBlockedStatus();
244 if ( 0 === $this->mBlockedby ) { return false; }
245 return true;
246 }
247
248 /**
249 * Get name of blocker
250 * @return string name of blocker
251 */
252 function blockedBy() {
253 $this->getBlockedStatus();
254 return $this->mBlockedby;
255 }
256
257 /**
258 * Get blocking reason
259 * @return string Blocking reason
260 */
261 function blockedFor() {
262 $this->getBlockedStatus();
263 return $this->mBlockreason;
264 }
265
266 /**
267 * Initialise php session
268 */
269 function SetupSession() {
270 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
271 if( $wgSessionsInMemcached ) {
272 require_once( 'MemcachedSessions.php' );
273 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
274 # If it's left on 'user' or another setting from another
275 # application, it will end up failing. Try to recover.
276 ini_set ( 'session.save_handler', 'files' );
277 }
278 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
279 session_cache_limiter( 'private, must-revalidate' );
280 @session_start();
281 }
282
283 /**
284 * Read datas from session
285 * @static
286 */
287 function loadFromSession() {
288 global $wgMemc, $wgDBname;
289
290 if ( isset( $_SESSION['wsUserID'] ) ) {
291 if ( 0 != $_SESSION['wsUserID'] ) {
292 $sId = $_SESSION['wsUserID'];
293 } else {
294 return new User();
295 }
296 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
297 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
298 $_SESSION['wsUserID'] = $sId;
299 } else {
300 return new User();
301 }
302 if ( isset( $_SESSION['wsUserName'] ) ) {
303 $sName = $_SESSION['wsUserName'];
304 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
305 $sName = $_COOKIE["{$wgDBname}UserName"];
306 $_SESSION['wsUserName'] = $sName;
307 } else {
308 return new User();
309 }
310
311 $passwordCorrect = FALSE;
312 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
313 if($makenew = !$user) {
314 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
315 $user = new User();
316 $user->mId = $sId;
317 $user->loadFromDatabase();
318 } else {
319 wfDebug( "User::loadFromSession() got from cache!\n" );
320 }
321
322 if ( isset( $_SESSION['wsToken'] ) ) {
323 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
324 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
325 $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
326 } else {
327 return new User(); # Can't log in from session
328 }
329
330 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
331 if($makenew) {
332 if($wgMemc->set( $key, $user ))
333 wfDebug( "User::loadFromSession() successfully saved user\n" );
334 else
335 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
336 }
337 $user->spreadBlock();
338 return $user;
339 }
340 return new User(); # Can't log in from session
341 }
342
343 /**
344 * Load a user from the database
345 */
346 function loadFromDatabase() {
347 global $wgCommandLineMode, $wgAnonGroupId, $wgLoggedInGroupId;
348 $fname = "User::loadFromDatabase";
349 if ( $this->mDataLoaded || $wgCommandLineMode ) {
350 return;
351 }
352
353 # Paranoia
354 $this->mId = IntVal( $this->mId );
355
356 /** Anonymous user */
357 if(!$this->mId) {
358 /** Get rights */
359 $anong = Group::newFromId($wgAnonGroupId);
360 if (!$anong)
361 wfDebugDieBacktrace("Please update your database schema "
362 ."and populate initial group data from "
363 ."maintenance/archives patches");
364 $anong->loadFromDatabase();
365 $this->mRights = explode(',', $anong->getRights());
366 $this->mDataLoaded = true;
367 return;
368 } # the following stuff is for non-anonymous users only
369
370 $dbr =& wfGetDB( DB_SLAVE );
371 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
372 'user_real_name','user_options','user_touched', 'user_token' ),
373 array( 'user_id' => $this->mId ), $fname );
374
375 if ( $s !== false ) {
376 $this->mName = $s->user_name;
377 $this->mEmail = $s->user_email;
378 $this->mRealName = $s->user_real_name;
379 $this->mPassword = $s->user_password;
380 $this->mNewpassword = $s->user_newpassword;
381 $this->decodeOptions( $s->user_options );
382 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
383 $this->mToken = $s->user_token;
384
385 // Get groups id
386 $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId ) );
387
388 while($group = $dbr->fetchRow($res)) {
389 $this->mGroups[] = $group[0];
390 }
391
392 // add the default group for logged in user
393 $this->mGroups[] = $wgLoggedInGroupId;
394
395 $this->mRights = array();
396 // now we merge groups rights to get this user rights
397 foreach($this->mGroups as $aGroupId) {
398 $g = Group::newFromId($aGroupId);
399 $g->loadFromDatabase();
400 $this->mRights = array_merge($this->mRights, explode(',', $g->getRights()));
401 }
402
403 // array merge duplicate rights which are part of several groups
404 $this->mRights = array_unique($this->mRights);
405
406 $dbr->freeResult($res);
407 }
408
409 $this->mDataLoaded = true;
410 }
411
412 function getID() { return $this->mId; }
413 function setID( $v ) {
414 $this->mId = $v;
415 $this->mDataLoaded = false;
416 }
417
418 function getName() {
419 $this->loadFromDatabase();
420 return $this->mName;
421 }
422
423 function setName( $str ) {
424 $this->loadFromDatabase();
425 $this->mName = $str;
426 }
427
428 function getNewtalk() {
429 $fname = 'User::getNewtalk';
430 $this->loadFromDatabase();
431
432 # Load the newtalk status if it is unloaded (mNewtalk=-1)
433 if ( $this->mNewtalk == -1 ) {
434 $this->mNewtalk=0; # reset talk page status
435 $dbr =& wfGetDB( DB_SLAVE );
436 if($this->mId) {
437 $res = $dbr->select( 'user_newtalk', 1, array( 'user_id' => $this->mId ), $fname );
438
439 if ( $dbr->numRows($res)>0 ) {
440 $this->mNewtalk= 1;
441 }
442 $dbr->freeResult( $res );
443 } else {
444 global $wgDBname, $wgMemc;
445 $key = "$wgDBname:newtalk:ip:{$this->mName}";
446 $newtalk = $wgMemc->get( $key );
447 if( ! is_integer( $newtalk ) ){
448 $res = $dbr->select( 'user_newtalk', 1, array( 'user_ip' => $this->mName ), $fname );
449
450 $this->mNewtalk = $dbr->numRows( $res ) > 0 ? 1 : 0;
451 $dbr->freeResult( $res );
452
453 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
454 } else {
455 $this->mNewtalk = $newtalk ? 1 : 0;
456 }
457 }
458 }
459
460 return ( 0 != $this->mNewtalk );
461 }
462
463 function setNewtalk( $val ) {
464 $this->loadFromDatabase();
465 $this->mNewtalk = $val;
466 $this->invalidateCache();
467 }
468
469 function invalidateCache() {
470 $this->loadFromDatabase();
471 $this->mTouched = wfTimestampNow();
472 # Don't forget to save the options after this or
473 # it won't take effect!
474 }
475
476 function validateCache( $timestamp ) {
477 $this->loadFromDatabase();
478 return ($timestamp >= $this->mTouched);
479 }
480
481 /**
482 * Salt a password.
483 * Will only be salted if $wgPasswordSalt is true
484 * @param string Password.
485 * @return string Salted password or clear password.
486 */
487 function addSalt( $p ) {
488 global $wgPasswordSalt;
489 if($wgPasswordSalt)
490 return md5( "{$this->mId}-{$p}" );
491 else
492 return $p;
493 }
494
495 /**
496 * Encrypt a password.
497 * It can eventuall salt a password @see User::addSalt()
498 * @param string $p clear Password.
499 * @param string Encrypted password.
500 */
501 function encryptPassword( $p ) {
502 return $this->addSalt( md5( $p ) );
503 }
504
505 # Set the password and reset the random token
506 function setPassword( $str ) {
507 $this->loadFromDatabase();
508 $this->setToken();
509 $this->mPassword = $this->encryptPassword( $str );
510 $this->mNewpassword = '';
511 }
512
513 # Set the random token (used for persistent authentication)
514 function setToken( $token = false ) {
515 if ( !$token ) {
516 $this->mToken = '';
517 # Take random data from PRNG
518 # This is reasonably secure if the PRNG has been seeded correctly
519 for ($i = 0; $i<USER_TOKEN_LENGTH / 4; $i++) {
520 $this->mToken .= sprintf( "%04X", mt_rand( 0, 65535 ) );
521 }
522 } else {
523 $this->mToken = $token;
524 }
525 }
526
527
528 function setCookiePassword( $str ) {
529 $this->loadFromDatabase();
530 $this->mCookiePassword = md5( $str );
531 }
532
533 function setNewpassword( $str ) {
534 $this->loadFromDatabase();
535 $this->mNewpassword = $this->encryptPassword( $str );
536 }
537
538 function getEmail() {
539 $this->loadFromDatabase();
540 return $this->mEmail;
541 }
542
543 function setEmail( $str ) {
544 $this->loadFromDatabase();
545 $this->mEmail = $str;
546 }
547
548 function getRealName() {
549 $this->loadFromDatabase();
550 return $this->mRealName;
551 }
552
553 function setRealName( $str ) {
554 $this->loadFromDatabase();
555 $this->mRealName = $str;
556 }
557
558 function getOption( $oname ) {
559 $this->loadFromDatabase();
560 if ( array_key_exists( $oname, $this->mOptions ) ) {
561 return $this->mOptions[$oname];
562 } else {
563 return '';
564 }
565 }
566
567 function setOption( $oname, $val ) {
568 $this->loadFromDatabase();
569 if ( $oname == 'skin' ) {
570 # Clear cached skin, so the new one displays immediately in Special:Preferences
571 unset( $this->mSkin );
572 }
573 $this->mOptions[$oname] = $val;
574 $this->invalidateCache();
575 }
576
577 function getRights() {
578 $this->loadFromDatabase();
579 return $this->mRights;
580 }
581
582 function addRight( $rname ) {
583 $this->loadFromDatabase();
584 array_push( $this->mRights, $rname );
585 $this->invalidateCache();
586 }
587
588 function getGroups() {
589 $this->loadFromDatabase();
590 return $this->mGroups;
591 }
592
593 function setGroups($groups) {
594 $this->loadFromDatabase();
595 $this->mGroups = $groups;
596 $this->invalidateCache();
597 }
598
599 /**
600 * Check if a user is sysop
601 * Die with backtrace. Use User:isAllowed() instead.
602 * @deprecated
603 */
604 function isSysop() {
605 /**
606 $this->loadFromDatabase();
607 if ( 0 == $this->mId ) { return false; }
608
609 return in_array( 'sysop', $this->mRights );
610 */
611 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
612 }
613
614 /** @deprecated */
615 function isDeveloper() {
616 /**
617 $this->loadFromDatabase();
618 if ( 0 == $this->mId ) { return false; }
619
620 return in_array( 'developer', $this->mRights );
621 */
622 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
623 }
624
625 /** @deprecated */
626 function isBureaucrat() {
627 /**
628 $this->loadFromDatabase();
629 if ( 0 == $this->mId ) { return false; }
630
631 return in_array( 'bureaucrat', $this->mRights );
632 */
633 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
634 }
635
636 /**
637 * Whether the user is a bot
638 * @todo need to be migrated to the new user level management sytem
639 */
640 function isBot() {
641 $this->loadFromDatabase();
642
643 # Why was this here? I need a UID=0 conversion script [TS]
644 # if ( 0 == $this->mId ) { return false; }
645
646 return in_array( 'bot', $this->mRights );
647 }
648
649 /**
650 * Check if user is allowed to access a feature / make an action
651 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
652 * @return boolean True: action is allowed, False: action should not be allowed
653 */
654 function isAllowed($action='') {
655 $this->loadFromDatabase();
656 return in_array( $action , $this->mRights );
657 }
658
659 /**
660 * Load a skin if it doesn't exist or return it
661 * @todo FIXME : need to check the old failback system [AV]
662 */
663 function &getSkin() {
664 global $IP;
665 if ( ! isset( $this->mSkin ) ) {
666 $fname = 'User::getSkin';
667 wfProfileIn( $fname );
668
669 # get all skin names available
670 $skinNames = Skin::getSkinNames();
671
672 # get the user skin
673 $userSkin = $this->getOption( 'skin' );
674 if ( $userSkin == '' ) { $userSkin = 'standard'; }
675
676 if ( !isset( $skinNames[$userSkin] ) ) {
677 # in case the user skin could not be found find a replacement
678 $fallback = array(
679 0 => 'Standard',
680 1 => 'Nostalgia',
681 2 => 'CologneBlue');
682 # if phptal is enabled we should have monobook skin that
683 # superseed the good old SkinStandard.
684 if ( isset( $skinNames['monobook'] ) ) {
685 $fallback[0] = 'MonoBook';
686 }
687
688 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
689 $sn = $fallback[$userSkin];
690 } else {
691 $sn = 'Standard';
692 }
693 } else {
694 # The user skin is available
695 $sn = $skinNames[$userSkin];
696 }
697
698 # Grab the skin class and initialise it. Each skin checks for PHPTal
699 # and will not load if it's not enabled.
700 require_once( $IP.'/skins/'.$sn.'.php' );
701
702 # Check if we got if not failback to default skin
703 $className = 'Skin'.$sn;
704 if( !class_exists( $className ) ) {
705 # DO NOT die if the class isn't found. This breaks maintenance
706 # scripts and can cause a user account to be unrecoverable
707 # except by SQL manipulation if a previously valid skin name
708 # is no longer valid.
709 $className = 'SkinStandard';
710 require_once( $IP.'/skins/Standard.php' );
711 }
712 $this->mSkin =& new $className;
713 wfProfileOut( $fname );
714 }
715 return $this->mSkin;
716 }
717
718 /**#@+
719 * @param string $title Article title to look at
720 */
721
722 /**
723 * Check watched status of an article
724 * @return bool True if article is watched
725 */
726 function isWatched( $title ) {
727 $wl = WatchedItem::fromUserTitle( $this, $title );
728 return $wl->isWatched();
729 }
730
731 /**
732 * Watch an article
733 */
734 function addWatch( $title ) {
735 $wl = WatchedItem::fromUserTitle( $this, $title );
736 $wl->addWatch();
737 $this->invalidateCache();
738 }
739
740 /**
741 * Stop watching an article
742 */
743 function removeWatch( $title ) {
744 $wl = WatchedItem::fromUserTitle( $this, $title );
745 $wl->removeWatch();
746 $this->invalidateCache();
747 }
748 /**#@-*/
749
750 /**
751 * @access private
752 * @return string Encoding options
753 */
754 function encodeOptions() {
755 $a = array();
756 foreach ( $this->mOptions as $oname => $oval ) {
757 array_push( $a, $oname.'='.$oval );
758 }
759 $s = implode( "\n", $a );
760 return $s;
761 }
762
763 /**
764 * @access private
765 */
766 function decodeOptions( $str ) {
767 $a = explode( "\n", $str );
768 foreach ( $a as $s ) {
769 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
770 $this->mOptions[$m[1]] = $m[2];
771 }
772 }
773 }
774
775 function setCookies() {
776 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
777 if ( 0 == $this->mId ) return;
778 $this->loadFromDatabase();
779 $exp = time() + $wgCookieExpiration;
780
781 $_SESSION['wsUserID'] = $this->mId;
782 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
783
784 $_SESSION['wsUserName'] = $this->mName;
785 setcookie( $wgDBname.'UserName', $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
786
787 $_SESSION['wsToken'] = $this->mToken;
788 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
789 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
790 } else {
791 setcookie( $wgDBname.'Token', '', time() - 3600 );
792 }
793 }
794
795 /**
796 * Logout user
797 * It will clean the session cookie
798 */
799 function logout() {
800 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
801 $this->loadDefaults();
802 $this->setLoaded( true );
803
804 $_SESSION['wsUserID'] = 0;
805
806 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
807 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
808 }
809
810 /**
811 * Save object settings into database
812 */
813 function saveSettings() {
814 global $wgMemc, $wgDBname;
815 $fname = 'User::saveSettings';
816
817 $dbw =& wfGetDB( DB_MASTER );
818 if ( ! $this->getNewtalk() ) {
819 # Delete user_newtalk row
820 if( $this->mId ) {
821 $dbw->delete( 'user_newtalk', array( 'user_id' => $this->mId ), $fname );
822 } else {
823 $dbw->delete( 'user_newtalk', array( 'user_ip' => $this->mName ), $fname );
824 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
825 }
826 }
827 if ( 0 == $this->mId ) { return; }
828
829 $dbw->update( 'user',
830 array( /* SET */
831 'user_name' => $this->mName,
832 'user_password' => $this->mPassword,
833 'user_newpassword' => $this->mNewpassword,
834 'user_real_name' => $this->mRealName,
835 'user_email' => $this->mEmail,
836 'user_options' => $this->encodeOptions(),
837 'user_touched' => $dbw->timestamp($this->mTouched),
838 'user_token' => $this->mToken
839 ), array( /* WHERE */
840 'user_id' => $this->mId
841 ), $fname
842 );
843 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights ),
844 'ur_user='. $this->mId, $fname );
845 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
846
847 // delete old groups
848 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId), $fname);
849
850 // save new ones
851 foreach ($this->mGroups as $group) {
852 $dbw->replace( 'user_groups',
853 array(array('ug_user','ug_group')),
854 array(
855 'ug_user' => $this->mId,
856 'ug_group' => $group
857 ), $fname
858 );
859 }
860 }
861
862 /**
863 * Checks if a user with the given name exists, returns the ID
864 */
865 function idForName() {
866 $fname = 'User::idForName';
867
868 $gotid = 0;
869 $s = trim( $this->mName );
870 if ( 0 == strcmp( '', $s ) ) return 0;
871
872 $dbr =& wfGetDB( DB_SLAVE );
873 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
874 if ( $id === false ) {
875 $id = 0;
876 }
877 return $id;
878 }
879
880 /**
881 * Add user object to the database
882 */
883 function addToDatabase() {
884 $fname = 'User::addToDatabase';
885 $dbw =& wfGetDB( DB_MASTER );
886 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
887 $dbw->insert( 'user',
888 array(
889 'user_id' => $seqVal,
890 'user_name' => $this->mName,
891 'user_password' => $this->mPassword,
892 'user_newpassword' => $this->mNewpassword,
893 'user_email' => $this->mEmail,
894 'user_real_name' => $this->mRealName,
895 'user_options' => $this->encodeOptions(),
896 'user_token' => $this->mToken
897 ), $fname
898 );
899 $this->mId = $dbw->insertId();
900 $dbw->insert( 'user_rights',
901 array(
902 'ur_user' => $this->mId,
903 'ur_rights' => implode( ',', $this->mRights )
904 ), $fname
905 );
906
907 foreach ($this->mGroups as $group) {
908 $dbw->insert( 'user_groups',
909 array(
910 'ug_user' => $this->mId,
911 'ug_group' => $group
912 ), $fname
913 );
914 }
915 }
916
917 function spreadBlock() {
918 global $wgIP;
919 # If the (non-anonymous) user is blocked, this function will block any IP address
920 # that they successfully log on from.
921 $fname = 'User::spreadBlock';
922
923 wfDebug( "User:spreadBlock()\n" );
924 if ( $this->mId == 0 ) {
925 return;
926 }
927
928 $userblock = Block::newFromDB( '', $this->mId );
929 if ( !$userblock->isValid() ) {
930 return;
931 }
932
933 # Check if this IP address is already blocked
934 $ipblock = Block::newFromDB( $wgIP );
935 if ( $ipblock->isValid() ) {
936 # Just update the timestamp
937 $ipblock->updateTimestamp();
938 return;
939 }
940
941 # Make a new block object with the desired properties
942 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
943 $ipblock->mAddress = $wgIP;
944 $ipblock->mUser = 0;
945 $ipblock->mBy = $userblock->mBy;
946 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
947 $ipblock->mTimestamp = wfTimestampNow();
948 $ipblock->mAuto = 1;
949 # If the user is already blocked with an expiry date, we don't
950 # want to pile on top of that!
951 if($userblock->mExpiry) {
952 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
953 } else {
954 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
955 }
956
957 # Insert it
958 $ipblock->insert();
959
960 }
961
962 function getPageRenderingHash() {
963 global $wgContLang;
964 if( $this->mHash ){
965 return $this->mHash;
966 }
967
968 // stubthreshold is only included below for completeness,
969 // it will always be 0 when this function is called by parsercache.
970
971 $confstr = $this->getOption( 'math' );
972 $confstr .= '!' . $this->getOption( 'highlightbroken' );
973 $confstr .= '!' . $this->getOption( 'stubthreshold' );
974 $confstr .= '!' . $this->getOption( 'editsection' );
975 $confstr .= '!' . $this->getOption( 'editsectiononrightclick' );
976 $confstr .= '!' . $this->getOption( 'showtoc' );
977 $confstr .= '!' . $this->getOption( 'date' );
978 $confstr .= '!' . $this->getOption( 'numberheadings' );
979 $confstr .= '!' . $this->getOption( 'language' );
980 // add in language variant option if there are multiple variants
981 // supported by the language object
982 if(sizeof($wgContLang->getVariants())>1) {
983 $confstr .= '!' . $this->getOption( 'variant' );
984 }
985
986 $this->mHash = $confstr;
987 return $confstr ;
988 }
989
990 function isAllowedToCreateAccount() {
991 global $wgWhitelistAccount;
992 $allowed = false;
993
994 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
995 foreach ($wgWhitelistAccount as $right => $ok) {
996 $userHasRight = (!strcmp($right, 'user') || in_array($right, $this->getRights()));
997 $allowed |= ($ok && $userHasRight);
998 }
999 return $allowed;
1000 }
1001
1002 /**
1003 * Set mDataLoaded, return previous value
1004 * Use this to prevent DB access in command-line scripts or similar situations
1005 */
1006 function setLoaded( $loaded ) {
1007 return wfSetVar( $this->mDataLoaded, $loaded );
1008 }
1009
1010 function getUserPage() {
1011 return Title::makeTitle( NS_USER, $this->mName );
1012 }
1013
1014 /**
1015 * @static
1016 */
1017 function getMaxID() {
1018 $dbr =& wfGetDB( DB_SLAVE );
1019 return $dbr->selectField( 'user', 'max(user_id)', false );
1020 }
1021
1022 /**
1023 * Determine whether the user is a newbie. Newbies are either
1024 * anonymous IPs, or the 1% most recently created accounts.
1025 * Bots and sysops are excluded.
1026 * @return bool True if it is a newbie.
1027 */
1028 function isNewbie() {
1029 return $this->mId > User::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() || $this->getID() == 0;
1030 }
1031
1032 /**
1033 * Check to see if the given clear-text password is one of the accepted passwords
1034 * @param string $password User password.
1035 * @return bool True if the given password is correct otherwise False.
1036 */
1037 function checkPassword( $password ) {
1038 $this->loadFromDatabase();
1039
1040 global $wgAuth;
1041 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1042 return true;
1043 } elseif( $wgAuth->strict() ) {
1044 /* Auth plugin doesn't allow local authentication */
1045 return false;
1046 }
1047
1048 $ep = $this->encryptPassword( $password );
1049 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1050 return true;
1051 } elseif ( 0 == strcmp( $ep, $this->mNewpassword ) ) {
1052 return true;
1053 } elseif ( function_exists( 'iconv' ) ) {
1054 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1055 # Check for this with iconv
1056 /* $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1057 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1058 return true;
1059 }*/
1060 }
1061 return false;
1062 }
1063 }
1064
1065 ?>