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