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