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