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