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