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