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