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