da07a23a7323d86a80e41087ddd41c2718440a9a
[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 if ( 0 === $this->mBlockedby ) { return false; }
382 return true;
383 }
384
385 /**
386 * Get name of blocker
387 * @return string name of blocker
388 */
389 function blockedBy() {
390 $this->getBlockedStatus();
391 return $this->mBlockedby;
392 }
393
394 /**
395 * Get blocking reason
396 * @return string Blocking reason
397 */
398 function blockedFor() {
399 $this->getBlockedStatus();
400 return $this->mBlockreason;
401 }
402
403 /**
404 * Initialise php session
405 */
406 function SetupSession() {
407 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
408 if( $wgSessionsInMemcached ) {
409 require_once( 'MemcachedSessions.php' );
410 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
411 # If it's left on 'user' or another setting from another
412 # application, it will end up failing. Try to recover.
413 ini_set ( 'session.save_handler', 'files' );
414 }
415 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
416 session_cache_limiter( 'private, must-revalidate' );
417 @session_start();
418 }
419
420 /**
421 * Read datas from session
422 * @static
423 */
424 function loadFromSession() {
425 global $wgMemc, $wgDBname;
426
427 if ( isset( $_SESSION['wsUserID'] ) ) {
428 if ( 0 != $_SESSION['wsUserID'] ) {
429 $sId = $_SESSION['wsUserID'];
430 } else {
431 return new User();
432 }
433 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
434 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
435 $_SESSION['wsUserID'] = $sId;
436 } else {
437 return new User();
438 }
439 if ( isset( $_SESSION['wsUserName'] ) ) {
440 $sName = $_SESSION['wsUserName'];
441 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
442 $sName = $_COOKIE["{$wgDBname}UserName"];
443 $_SESSION['wsUserName'] = $sName;
444 } else {
445 return new User();
446 }
447
448 $passwordCorrect = FALSE;
449 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
450 if($makenew = !$user) {
451 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
452 $user = new User();
453 $user->mId = $sId;
454 $user->loadFromDatabase();
455 } else {
456 wfDebug( "User::loadFromSession() got from cache!\n" );
457 }
458
459 if ( isset( $_SESSION['wsToken'] ) ) {
460 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
461 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
462 $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
463 } else {
464 return new User(); # Can't log in from session
465 }
466
467 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
468 if($makenew) {
469 if($wgMemc->set( $key, $user ))
470 wfDebug( "User::loadFromSession() successfully saved user\n" );
471 else
472 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
473 }
474 return $user;
475 }
476 return new User(); # Can't log in from session
477 }
478
479 /**
480 * Load a user from the database
481 */
482 function loadFromDatabase() {
483 global $wgCommandLineMode, $wgAnonGroupId, $wgLoggedInGroupId;
484 $fname = "User::loadFromDatabase";
485
486 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
487 # loading in a command line script, don't assume all command line scripts need it like this
488 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
489 if ( $this->mDataLoaded ) {
490 return;
491 }
492
493 # Paranoia
494 $this->mId = IntVal( $this->mId );
495
496 /** Anonymous user */
497 if(!$this->mId) {
498 /** Get rights */
499 $anong = Group::newFromId($wgAnonGroupId);
500 if (!$anong)
501 wfDebugDieBacktrace("Please update your database schema "
502 ."and populate initial group data from "
503 ."maintenance/archives patches");
504 $anong->loadFromDatabase();
505 $this->mRights = explode(',', $anong->getRights());
506 $this->mDataLoaded = true;
507 return;
508 } # the following stuff is for non-anonymous users only
509
510 $dbr =& wfGetDB( DB_SLAVE );
511 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
512 'user_email_authenticated',
513 'user_real_name','user_options','user_touched', 'user_token' ),
514 array( 'user_id' => $this->mId ), $fname );
515
516 if ( $s !== false ) {
517 $this->mName = $s->user_name;
518 $this->mEmail = $s->user_email;
519 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
520 $this->mRealName = $s->user_real_name;
521 $this->mPassword = $s->user_password;
522 $this->mNewpassword = $s->user_newpassword;
523 $this->decodeOptions( $s->user_options );
524 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
525 $this->mToken = $s->user_token;
526
527 // Get groups id
528 $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId ) );
529
530 while($group = $dbr->fetchRow($res)) {
531 $this->mGroups[] = $group[0];
532 }
533
534 // add the default group for logged in user
535 $this->mGroups[] = $wgLoggedInGroupId;
536
537 $this->mRights = array();
538 // now we merge groups rights to get this user rights
539 foreach($this->mGroups as $aGroupId) {
540 $g = Group::newFromId($aGroupId);
541 $g->loadFromDatabase();
542 $this->mRights = array_merge($this->mRights, explode(',', $g->getRights()));
543 }
544
545 // array merge duplicate rights which are part of several groups
546 $this->mRights = array_unique($this->mRights);
547
548 $dbr->freeResult($res);
549 }
550
551 $this->mDataLoaded = true;
552 }
553
554 function getID() { return $this->mId; }
555 function setID( $v ) {
556 $this->mId = $v;
557 $this->mDataLoaded = false;
558 }
559
560 function getName() {
561 $this->loadFromDatabase();
562 return $this->mName;
563 }
564
565 function setName( $str ) {
566 $this->loadFromDatabase();
567 $this->mName = $str;
568 }
569
570
571 /**
572 * Return the title dbkey form of the name, for eg user pages.
573 * @return string
574 * @access public
575 */
576 function getTitleKey() {
577 return str_replace( ' ', '_', $this->getName() );
578 }
579
580 function getNewtalk() {
581 $fname = 'User::getNewtalk';
582 $this->loadFromDatabase();
583
584 # Load the newtalk status if it is unloaded (mNewtalk=-1)
585 if( $this->mNewtalk == -1 ) {
586 $this->mNewtalk = 0; # reset talk page status
587
588 # Check memcached separately for anons, who have no
589 # entire User object stored in there.
590 if( !$this->mId ) {
591 global $wgDBname, $wgMemc;
592 $key = "$wgDBname:newtalk:ip:{$this->mName}";
593 $newtalk = $wgMemc->get( $key );
594 if( is_integer( $newtalk ) ) {
595 $this->mNewtalk = $newtalk ? 1 : 0;
596 return (bool)$this->mNewtalk;
597 }
598 }
599
600 $dbr =& wfGetDB( DB_SLAVE );
601 $res = $dbr->select( 'watchlist',
602 array( 'wl_user' ),
603 array( 'wl_title' => $this->getTitleKey(),
604 'wl_namespace' => NS_USER_TALK,
605 'wl_user' => $this->mId,
606 'wl_notificationtimestamp != 0' ),
607 'User::getNewtalk' );
608 if( $dbr->numRows($res) > 0 ) {
609 $this->mNewtalk = 1;
610 }
611 $dbr->freeResult( $res );
612
613 if( !$this->mId ) {
614 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
615 }
616 }
617
618 return ( 0 != $this->mNewtalk );
619 }
620
621 function setNewtalk( $val ) {
622 $this->loadFromDatabase();
623 $this->mNewtalk = $val;
624 $this->invalidateCache();
625 }
626
627 function invalidateCache() {
628 $this->loadFromDatabase();
629 $this->mTouched = wfTimestampNow();
630 # Don't forget to save the options after this or
631 # it won't take effect!
632 }
633
634 function validateCache( $timestamp ) {
635 $this->loadFromDatabase();
636 return ($timestamp >= $this->mTouched);
637 }
638
639 /**
640 * Salt a password.
641 * Will only be salted if $wgPasswordSalt is true
642 * @param string Password.
643 * @return string Salted password or clear password.
644 */
645 function addSalt( $p ) {
646 global $wgPasswordSalt;
647 if($wgPasswordSalt)
648 return md5( "{$this->mId}-{$p}" );
649 else
650 return $p;
651 }
652
653 /**
654 * Encrypt a password.
655 * It can eventuall salt a password @see User::addSalt()
656 * @param string $p clear Password.
657 * @param string Encrypted password.
658 */
659 function encryptPassword( $p ) {
660 return $this->addSalt( md5( $p ) );
661 }
662
663 # Set the password and reset the random token
664 function setPassword( $str ) {
665 $this->loadFromDatabase();
666 $this->setToken();
667 $this->mPassword = $this->encryptPassword( $str );
668 $this->mNewpassword = '';
669 }
670
671 # Set the random token (used for persistent authentication)
672 function setToken( $token = false ) {
673 global $wgSecretKey, $wgProxyKey, $wgDBname;
674 if ( !$token ) {
675 if ( $wgSecretKey ) {
676 $key = $wgSecretKey;
677 } elseif ( $wgProxyKey ) {
678 $key = $wgProxyKey;
679 } else {
680 $key = microtime();
681 }
682 $this->mToken = md5( $wgSecretKey . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId );
683 } else {
684 $this->mToken = $token;
685 }
686 }
687
688
689 function setCookiePassword( $str ) {
690 $this->loadFromDatabase();
691 $this->mCookiePassword = md5( $str );
692 }
693
694 function setNewpassword( $str ) {
695 $this->loadFromDatabase();
696 $this->mNewpassword = $this->encryptPassword( $str );
697 }
698
699 function getEmail() {
700 $this->loadFromDatabase();
701 return $this->mEmail;
702 }
703
704 function getEmailAuthenticationTimestamp() {
705 $this->loadFromDatabase();
706 return $this->mEmailAuthenticated;
707 }
708
709 function setEmail( $str ) {
710 $this->loadFromDatabase();
711 $this->mEmail = $str;
712 }
713
714 function getRealName() {
715 $this->loadFromDatabase();
716 return $this->mRealName;
717 }
718
719 function setRealName( $str ) {
720 $this->loadFromDatabase();
721 $this->mRealName = $str;
722 }
723
724 function getOption( $oname ) {
725 $this->loadFromDatabase();
726 if ( array_key_exists( $oname, $this->mOptions ) ) {
727 return $this->mOptions[$oname];
728 } else {
729 return '';
730 }
731 }
732
733 function setOption( $oname, $val ) {
734 $this->loadFromDatabase();
735 if ( $oname == 'skin' ) {
736 # Clear cached skin, so the new one displays immediately in Special:Preferences
737 unset( $this->mSkin );
738 }
739 $this->mOptions[$oname] = $val;
740 $this->invalidateCache();
741 }
742
743 function getRights() {
744 $this->loadFromDatabase();
745 return $this->mRights;
746 }
747
748 function addRight( $rname ) {
749 $this->loadFromDatabase();
750 array_push( $this->mRights, $rname );
751 $this->invalidateCache();
752 }
753
754 function getGroups() {
755 $this->loadFromDatabase();
756 return $this->mGroups;
757 }
758
759 function setGroups($groups) {
760 $this->loadFromDatabase();
761 $this->mGroups = $groups;
762 $this->invalidateCache();
763 }
764
765 /**
766 * A more legible check for non-anonymousness.
767 * Returns true if the user is not an anonymous visitor.
768 *
769 * @return bool
770 */
771 function isLoggedIn() {
772 return( $this->getID() != 0 );
773 }
774
775 /**
776 * A more legible check for anonymousness.
777 * Returns true if the user is an anonymous visitor.
778 *
779 * @return bool
780 */
781 function isAnon() {
782 return !$this->isLoggedIn();
783 }
784
785 /**
786 * Check if a user is sysop
787 * Die with backtrace. Use User:isAllowed() instead.
788 * @deprecated
789 */
790 function isSysop() {
791 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
792 }
793
794 /** @deprecated */
795 function isDeveloper() {
796 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
797 }
798
799 /** @deprecated */
800 function isBureaucrat() {
801 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
802 }
803
804 /**
805 * Whether the user is a bot
806 * @todo need to be migrated to the new user level management sytem
807 */
808 function isBot() {
809 $this->loadFromDatabase();
810
811 # Why was this here? I need a UID=0 conversion script [TS]
812 # if ( 0 == $this->mId ) { return false; }
813
814 return in_array( 'bot', $this->mRights );
815 }
816
817 /**
818 * Check if user is allowed to access a feature / make an action
819 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
820 * @return boolean True: action is allowed, False: action should not be allowed
821 */
822 function isAllowed($action='') {
823 $this->loadFromDatabase();
824 return in_array( $action , $this->mRights );
825 }
826
827 /**
828 * Load a skin if it doesn't exist or return it
829 * @todo FIXME : need to check the old failback system [AV]
830 */
831 function &getSkin() {
832 global $IP;
833 if ( ! isset( $this->mSkin ) ) {
834 $fname = 'User::getSkin';
835 wfProfileIn( $fname );
836
837 # get all skin names available
838 $skinNames = Skin::getSkinNames();
839
840 # get the user skin
841 $userSkin = $this->getOption( 'skin' );
842 if ( $userSkin == '' ) { $userSkin = 'standard'; }
843
844 if ( !isset( $skinNames[$userSkin] ) ) {
845 # in case the user skin could not be found find a replacement
846 $fallback = array(
847 0 => 'Standard',
848 1 => 'Nostalgia',
849 2 => 'CologneBlue');
850 # if phptal is enabled we should have monobook skin that
851 # superseed the good old SkinStandard.
852 if ( isset( $skinNames['monobook'] ) ) {
853 $fallback[0] = 'MonoBook';
854 }
855
856 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
857 $sn = $fallback[$userSkin];
858 } else {
859 $sn = 'Standard';
860 }
861 } else {
862 # The user skin is available
863 $sn = $skinNames[$userSkin];
864 }
865
866 # Grab the skin class and initialise it. Each skin checks for PHPTal
867 # and will not load if it's not enabled.
868 require_once( $IP.'/skins/'.$sn.'.php' );
869
870 # Check if we got if not failback to default skin
871 $className = 'Skin'.$sn;
872 if( !class_exists( $className ) ) {
873 # DO NOT die if the class isn't found. This breaks maintenance
874 # scripts and can cause a user account to be unrecoverable
875 # except by SQL manipulation if a previously valid skin name
876 # is no longer valid.
877 $className = 'SkinStandard';
878 require_once( $IP.'/skins/Standard.php' );
879 }
880 $this->mSkin =& new $className;
881 wfProfileOut( $fname );
882 }
883 return $this->mSkin;
884 }
885
886 /**#@+
887 * @param string $title Article title to look at
888 */
889
890 /**
891 * Check watched status of an article
892 * @return bool True if article is watched
893 */
894 function isWatched( $title ) {
895 $wl = WatchedItem::fromUserTitle( $this, $title );
896 return $wl->isWatched();
897 }
898
899 /**
900 * Watch an article
901 */
902 function addWatch( $title ) {
903 $wl = WatchedItem::fromUserTitle( $this, $title );
904 $wl->addWatch();
905 $this->invalidateCache();
906 }
907
908 /**
909 * Stop watching an article
910 */
911 function removeWatch( $title ) {
912 $wl = WatchedItem::fromUserTitle( $this, $title );
913 $wl->removeWatch();
914 $this->invalidateCache();
915 }
916
917 /**
918 * Clear the user's notification timestamp for the given title.
919 * If e-notif e-mails are on, they will receive notification mails on
920 * the next change of the page if it's watched etc.
921 */
922 function clearNotification( $title ) {
923 $userid = $this->getId();
924 if ($userid==0)
925 return;
926 $dbw =& wfGetDB( DB_MASTER );
927 $success = $dbw->update( 'watchlist',
928 array( /* SET */
929 'wl_notificationtimestamp' => 0
930 ), array( /* WHERE */
931 'wl_title' => $title->getDBkey(),
932 'wl_namespace' => $title->getNamespace(),
933 'wl_user' => $this->getId()
934 ), 'User::clearLastVisited'
935 );
936 }
937
938 /**#@-*/
939
940 /**
941 * Resets all of the given user's page-change notification timestamps.
942 * If e-notif e-mails are on, they will receive notification mails on
943 * the next change of any watched page.
944 *
945 * @param int $currentUser user ID number
946 * @access public
947 */
948 function clearAllNotifications( $currentUser ) {
949 if( $currentUser != 0 ) {
950
951 $dbw =& wfGetDB( DB_MASTER );
952 $success = $dbw->update( 'watchlist',
953 array( /* SET */
954 'wl_notificationtimestamp' => 0
955 ), array( /* WHERE */
956 'wl_user' => $currentUser
957 ), 'UserMailer::clearAll'
958 );
959
960 # we also need to clear here the "you have new message" notification for the own user_talk page
961 # This is cleared one page view later in Article::viewUpdates();
962 }
963 }
964
965 /**
966 * @access private
967 * @return string Encoding options
968 */
969 function encodeOptions() {
970 $a = array();
971 foreach ( $this->mOptions as $oname => $oval ) {
972 array_push( $a, $oname.'='.$oval );
973 }
974 $s = implode( "\n", $a );
975 return $s;
976 }
977
978 /**
979 * @access private
980 */
981 function decodeOptions( $str ) {
982 $a = explode( "\n", $str );
983 foreach ( $a as $s ) {
984 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
985 $this->mOptions[$m[1]] = $m[2];
986 }
987 }
988 }
989
990 function setCookies() {
991 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
992 if ( 0 == $this->mId ) return;
993 $this->loadFromDatabase();
994 $exp = time() + $wgCookieExpiration;
995
996 $_SESSION['wsUserID'] = $this->mId;
997 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
998
999 $_SESSION['wsUserName'] = $this->mName;
1000 setcookie( $wgDBname.'UserName', $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
1001
1002 $_SESSION['wsToken'] = $this->mToken;
1003 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1004 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
1005 } else {
1006 setcookie( $wgDBname.'Token', '', time() - 3600 );
1007 }
1008 }
1009
1010 /**
1011 * Logout user
1012 * It will clean the session cookie
1013 */
1014 function logout() {
1015 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1016 $this->loadDefaults();
1017 $this->setLoaded( true );
1018
1019 $_SESSION['wsUserID'] = 0;
1020
1021 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1022 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1023
1024 # Remember when user logged out, to prevent seeing cached pages
1025 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain );
1026 }
1027
1028 /**
1029 * Save object settings into database
1030 */
1031 function saveSettings() {
1032 global $wgMemc, $wgDBname;
1033 $fname = 'User::saveSettings';
1034
1035 $dbw =& wfGetDB( DB_MASTER );
1036 if ( ! $this->getNewtalk() ) {
1037 # Delete the watchlist entry for user_talk page X watched by user X
1038 $dbw->delete( 'watchlist',
1039 array( 'wl_user' => $this->mId,
1040 'wl_title' => $this->getTitleKey(),
1041 'wl_namespace' => NS_USER_TALK ),
1042 $fname );
1043 if( !$this->mId ) {
1044 # Anon users have a separate memcache space for newtalk
1045 # since they don't store their own info. Trim...
1046 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1047 }
1048 }
1049
1050 if ( 0 == $this->mId ) { return; }
1051
1052 $dbw->update( 'user',
1053 array( /* SET */
1054 'user_name' => $this->mName,
1055 'user_password' => $this->mPassword,
1056 'user_newpassword' => $this->mNewpassword,
1057 'user_real_name' => $this->mRealName,
1058 'user_email' => $this->mEmail,
1059 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1060 'user_options' => $this->encodeOptions(),
1061 'user_touched' => $dbw->timestamp($this->mTouched),
1062 'user_token' => $this->mToken
1063 ), array( /* WHERE */
1064 'user_id' => $this->mId
1065 ), $fname
1066 );
1067 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights ),
1068 'ur_user='. $this->mId, $fname );
1069 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1070
1071 // delete old groups
1072 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId), $fname);
1073
1074 // save new ones
1075 foreach ($this->mGroups as $group) {
1076 $dbw->replace( 'user_groups',
1077 array(array('ug_user','ug_group')),
1078 array(
1079 'ug_user' => $this->mId,
1080 'ug_group' => $group
1081 ), $fname
1082 );
1083 }
1084 }
1085
1086
1087 /**
1088 * Checks if a user with the given name exists, returns the ID
1089 */
1090 function idForName() {
1091 $fname = 'User::idForName';
1092
1093 $gotid = 0;
1094 $s = trim( $this->mName );
1095 if ( 0 == strcmp( '', $s ) ) return 0;
1096
1097 $dbr =& wfGetDB( DB_SLAVE );
1098 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1099 if ( $id === false ) {
1100 $id = 0;
1101 }
1102 return $id;
1103 }
1104
1105 /**
1106 * Add user object to the database
1107 */
1108 function addToDatabase() {
1109 $fname = 'User::addToDatabase';
1110 $dbw =& wfGetDB( DB_MASTER );
1111 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1112 $dbw->insert( 'user',
1113 array(
1114 'user_id' => $seqVal,
1115 'user_name' => $this->mName,
1116 'user_password' => $this->mPassword,
1117 'user_newpassword' => $this->mNewpassword,
1118 'user_email' => $this->mEmail,
1119 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1120 'user_real_name' => $this->mRealName,
1121 'user_options' => $this->encodeOptions(),
1122 'user_token' => $this->mToken
1123 ), $fname
1124 );
1125 $this->mId = $dbw->insertId();
1126 $dbw->insert( 'user_rights',
1127 array(
1128 'ur_user' => $this->mId,
1129 'ur_rights' => implode( ',', $this->mRights )
1130 ), $fname
1131 );
1132
1133 foreach ($this->mGroups as $group) {
1134 $dbw->insert( 'user_groups',
1135 array(
1136 'ug_user' => $this->mId,
1137 'ug_group' => $group
1138 ), $fname
1139 );
1140 }
1141 }
1142
1143 function spreadBlock() {
1144 global $wgIP;
1145 # If the (non-anonymous) user is blocked, this function will block any IP address
1146 # that they successfully log on from.
1147 $fname = 'User::spreadBlock';
1148
1149 wfDebug( "User:spreadBlock()\n" );
1150 if ( $this->mId == 0 ) {
1151 return;
1152 }
1153
1154 $userblock = Block::newFromDB( '', $this->mId );
1155 if ( !$userblock->isValid() ) {
1156 return;
1157 }
1158
1159 # Check if this IP address is already blocked
1160 $ipblock = Block::newFromDB( $wgIP );
1161 if ( $ipblock->isValid() ) {
1162 # Just update the timestamp
1163 $ipblock->updateTimestamp();
1164 return;
1165 }
1166
1167 # Make a new block object with the desired properties
1168 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1169 $ipblock->mAddress = $wgIP;
1170 $ipblock->mUser = 0;
1171 $ipblock->mBy = $userblock->mBy;
1172 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
1173 $ipblock->mTimestamp = wfTimestampNow();
1174 $ipblock->mAuto = 1;
1175 # If the user is already blocked with an expiry date, we don't
1176 # want to pile on top of that!
1177 if($userblock->mExpiry) {
1178 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
1179 } else {
1180 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
1181 }
1182
1183 # Insert it
1184 $ipblock->insert();
1185
1186 }
1187
1188 function getPageRenderingHash() {
1189 global $wgContLang;
1190 if( $this->mHash ){
1191 return $this->mHash;
1192 }
1193
1194 // stubthreshold is only included below for completeness,
1195 // it will always be 0 when this function is called by parsercache.
1196
1197 $confstr = $this->getOption( 'math' );
1198 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1199 $confstr .= '!' . $this->getOption( 'editsection' );
1200 $confstr .= '!' . $this->getOption( 'date' );
1201 $confstr .= '!' . $this->getOption( 'numberheadings' );
1202 $confstr .= '!' . $this->getOption( 'language' );
1203 $confstr .= '!' . $this->getOption( 'thumbsize' );
1204 // add in language specific options, if any
1205 $extra = $wgContLang->getExtraHashOptions();
1206 $confstr .= $extra;
1207
1208 $this->mHash = $confstr;
1209 return $confstr ;
1210 }
1211
1212 function isAllowedToCreateAccount() {
1213 global $wgWhitelistAccount;
1214 $allowed = false;
1215
1216 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1217 foreach ($wgWhitelistAccount as $right => $ok) {
1218 $userHasRight = (!strcmp($right, 'user') || in_array($right, $this->getRights()));
1219 $allowed |= ($ok && $userHasRight);
1220 }
1221 return $allowed;
1222 }
1223
1224 /**
1225 * Set mDataLoaded, return previous value
1226 * Use this to prevent DB access in command-line scripts or similar situations
1227 */
1228 function setLoaded( $loaded ) {
1229 return wfSetVar( $this->mDataLoaded, $loaded );
1230 }
1231
1232 /**
1233 * Get this user's personal page title.
1234 *
1235 * @return Title
1236 * @access public
1237 */
1238 function getUserPage() {
1239 return Title::makeTitle( NS_USER, $this->mName );
1240 }
1241
1242 /**
1243 * Get this user's talk page title.
1244 *
1245 * @return Title
1246 * @access public
1247 */
1248 function getTalkPage() {
1249 $title = $this->getUserPage();
1250 return $title->getTalkPage();
1251 }
1252
1253 /**
1254 * @static
1255 */
1256 function getMaxID() {
1257 $dbr =& wfGetDB( DB_SLAVE );
1258 return $dbr->selectField( 'user', 'max(user_id)', false );
1259 }
1260
1261 /**
1262 * Determine whether the user is a newbie. Newbies are either
1263 * anonymous IPs, or the 1% most recently created accounts.
1264 * Bots and sysops are excluded.
1265 * @return bool True if it is a newbie.
1266 */
1267 function isNewbie() {
1268 return $this->mId > User::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() || $this->getID() == 0;
1269 }
1270
1271 /**
1272 * Check to see if the given clear-text password is one of the accepted passwords
1273 * @param string $password User password.
1274 * @return bool True if the given password is correct otherwise False.
1275 */
1276 function checkPassword( $password ) {
1277 global $wgAuth;
1278 $this->loadFromDatabase();
1279
1280 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1281 return true;
1282 } elseif( $wgAuth->strict() ) {
1283 /* Auth plugin doesn't allow local authentication */
1284 return false;
1285 }
1286 $ep = $this->encryptPassword( $password );
1287 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1288 return true;
1289 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
1290 # If e-mail confirmation hasn't been done already,
1291 # we may as well confirm it here -- the user can only
1292 # get this password via e-mail.
1293 $this->mEmailAuthenticated = wfTimestampNow();
1294
1295 # use the temporary one-time password only once: clear it now !
1296 $this->mNewpassword = '';
1297 $this->saveSettings();
1298 return true;
1299 } elseif ( function_exists( 'iconv' ) ) {
1300 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1301 # Check for this with iconv
1302 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1303 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1304 return true;
1305 }
1306 }
1307 return false;
1308 }
1309
1310 /**
1311 * Initialize (if necessary) and return a session token value
1312 * which can be used in edit forms to show that the user's
1313 * login credentials aren't being hijacked with a foreign form
1314 * submission.
1315 *
1316 * @param mixed $salt - Optional function-specific data for hash.
1317 * Use a string or an array of strings.
1318 * @return string
1319 * @access public
1320 */
1321 function editToken( $salt = '' ) {
1322 if( !isset( $_SESSION['wsEditToken'] ) ) {
1323 $token = $this->generateToken();
1324 $_SESSION['wsEditToken'] = $token;
1325 } else {
1326 $token = $_SESSION['wsEditToken'];
1327 }
1328 if( is_array( $salt ) ) {
1329 $salt = implode( '|', $salt );
1330 }
1331 return md5( $token . $salt );
1332 }
1333
1334 /**
1335 * Generate a hex-y looking random token for various uses.
1336 * Could be made more cryptographically sure if someone cares.
1337 * @return string
1338 */
1339 function generateToken( $salt = '' ) {
1340 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1341 return md5( $token . $salt );
1342 }
1343
1344 /**
1345 * Check given value against the token value stored in the session.
1346 * A match should confirm that the form was submitted from the
1347 * user's own login session, not a form submission from a third-party
1348 * site.
1349 *
1350 * @param string $val - the input value to compare
1351 * @param string $salt - Optional function-specific data for hash
1352 * @return bool
1353 * @access public
1354 */
1355 function matchEditToken( $val, $salt = '' ) {
1356 return ( $val == $this->editToken( $salt ) );
1357 }
1358
1359 /**
1360 * Generate a new e-mail confirmation token and send a confirmation
1361 * mail to the user's given address.
1362 *
1363 * @return mixed True on success, a WikiError object on failure.
1364 */
1365 function sendConfirmationMail() {
1366 global $wgIP, $wgContLang;
1367 $url = $this->confirmationTokenUrl( $expiration );
1368 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1369 wfMsg( 'confirmemail_body',
1370 $wgIP,
1371 $this->getName(),
1372 $url,
1373 $wgContLang->timeanddate( $expiration, false ) ) );
1374 }
1375
1376 /**
1377 * Send an e-mail to this user's account. Does not check for
1378 * confirmed status or validity.
1379 *
1380 * @param string $subject
1381 * @param string $body
1382 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1383 * @return mixed True on success, a WikiError object on failure.
1384 */
1385 function sendMail( $subject, $body, $from = null ) {
1386 if( is_null( $from ) ) {
1387 global $wgPasswordSender;
1388 $from = $wgPasswordSender;
1389 }
1390
1391 require_once( 'UserMailer.php' );
1392 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1393
1394 if( $error == '' ) {
1395 return true;
1396 } else {
1397 return new WikiError( $error );
1398 }
1399 }
1400
1401 /**
1402 * Generate, store, and return a new e-mail confirmation code.
1403 * A hash (unsalted since it's used as a key) is stored.
1404 * @param &$expiration mixed output: accepts the expiration time
1405 * @return string
1406 * @access private
1407 */
1408 function confirmationToken( &$expiration ) {
1409 $fname = 'User::confirmationToken';
1410
1411 $now = time();
1412 $expires = $now + 7 * 24 * 60 * 60;
1413 $expiration = wfTimestamp( TS_MW, $expires );
1414
1415 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
1416 $hash = md5( $token );
1417
1418 $dbw =& wfGetDB( DB_MASTER );
1419 $dbw->update( 'user',
1420 array( 'user_email_token' => $hash,
1421 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1422 array( 'user_id' => $this->mId ),
1423 $fname );
1424
1425 return $token;
1426 }
1427
1428 /**
1429 * Generate and store a new e-mail confirmation token, and return
1430 * the URL the user can use to confirm.
1431 * @param &$expiration mixed output: accepts the expiration time
1432 * @return string
1433 * @access private
1434 */
1435 function confirmationTokenUrl( &$expiration ) {
1436 $token = $this->confirmationToken( $expiration );
1437 $title = Title::makeTitle( NS_SPECIAL, 'Confirmemail/' . $token );
1438 return $title->getFullUrl();
1439 }
1440
1441 /**
1442 * Mark the e-mail address confirmed and save.
1443 */
1444 function confirmEmail() {
1445 $this->loadFromDatabase();
1446 $this->mEmailAuthenticated = wfTimestampNow();
1447 $this->saveSettings();
1448 return true;
1449 }
1450
1451 /**
1452 * Is this user allowed to send e-mails within limits of current
1453 * site configuration?
1454 * @return bool
1455 */
1456 function canSendEmail() {
1457 return $this->isEmailConfirmed();
1458 }
1459
1460 /**
1461 * Is this user allowed to receive e-mails within limits of current
1462 * site configuration?
1463 * @return bool
1464 */
1465 function canReceiveEmail() {
1466 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1467 }
1468
1469 /**
1470 * Is this user's e-mail address valid-looking and confirmed within
1471 * limits of the current site configuration?
1472 *
1473 * If $wgEmailAuthentication is on, this may require the user to have
1474 * confirmed their address by returning a code or using a password
1475 * sent to the address from the wiki.
1476 *
1477 * @return bool
1478 */
1479 function isEmailConfirmed() {
1480 global $wgEmailAuthentication;
1481 $this->loadFromDatabase();
1482 if( $this->isAnon() )
1483 return false;
1484 if( !$this->isValidEmailAddr( $this->mEmail ) )
1485 return false;
1486 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
1487 return false;
1488 return true;
1489 }
1490 }
1491
1492 ?>