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