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