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