Major changes to user groups:
[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 return in_array( 'bot', $this->mRights );
810 }
811
812 /**
813 * Check if user is allowed to access a feature / make an action
814 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
815 * @return boolean True: action is allowed, False: action should not be allowed
816 */
817 function isAllowed($action='') {
818 $this->loadFromDatabase();
819 return in_array( $action , $this->mRights );
820 }
821
822 /**
823 * Load a skin if it doesn't exist or return it
824 * @todo FIXME : need to check the old failback system [AV]
825 */
826 function &getSkin() {
827 global $IP;
828 if ( ! isset( $this->mSkin ) ) {
829 $fname = 'User::getSkin';
830 wfProfileIn( $fname );
831
832 # get all skin names available
833 $skinNames = Skin::getSkinNames();
834
835 # get the user skin
836 $userSkin = $this->getOption( 'skin' );
837 if ( $userSkin == '' ) { $userSkin = 'standard'; }
838
839 if ( !isset( $skinNames[$userSkin] ) ) {
840 # in case the user skin could not be found find a replacement
841 $fallback = array(
842 0 => 'Standard',
843 1 => 'Nostalgia',
844 2 => 'CologneBlue');
845 # if phptal is enabled we should have monobook skin that
846 # superseed the good old SkinStandard.
847 if ( isset( $skinNames['monobook'] ) ) {
848 $fallback[0] = 'MonoBook';
849 }
850
851 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
852 $sn = $fallback[$userSkin];
853 } else {
854 $sn = 'Standard';
855 }
856 } else {
857 # The user skin is available
858 $sn = $skinNames[$userSkin];
859 }
860
861 # Grab the skin class and initialise it. Each skin checks for PHPTal
862 # and will not load if it's not enabled.
863 require_once( $IP.'/skins/'.$sn.'.php' );
864
865 # Check if we got if not failback to default skin
866 $className = 'Skin'.$sn;
867 if( !class_exists( $className ) ) {
868 # DO NOT die if the class isn't found. This breaks maintenance
869 # scripts and can cause a user account to be unrecoverable
870 # except by SQL manipulation if a previously valid skin name
871 # is no longer valid.
872 $className = 'SkinStandard';
873 require_once( $IP.'/skins/Standard.php' );
874 }
875 $this->mSkin =& new $className;
876 wfProfileOut( $fname );
877 }
878 return $this->mSkin;
879 }
880
881 /**#@+
882 * @param string $title Article title to look at
883 */
884
885 /**
886 * Check watched status of an article
887 * @return bool True if article is watched
888 */
889 function isWatched( $title ) {
890 $wl = WatchedItem::fromUserTitle( $this, $title );
891 return $wl->isWatched();
892 }
893
894 /**
895 * Watch an article
896 */
897 function addWatch( $title ) {
898 $wl = WatchedItem::fromUserTitle( $this, $title );
899 $wl->addWatch();
900 $this->invalidateCache();
901 }
902
903 /**
904 * Stop watching an article
905 */
906 function removeWatch( $title ) {
907 $wl = WatchedItem::fromUserTitle( $this, $title );
908 $wl->removeWatch();
909 $this->invalidateCache();
910 }
911
912 /**
913 * Clear the user's notification timestamp for the given title.
914 * If e-notif e-mails are on, they will receive notification mails on
915 * the next change of the page if it's watched etc.
916 */
917 function clearNotification( $title ) {
918 $userid = $this->getId();
919 if ($userid==0)
920 return;
921 $dbw =& wfGetDB( DB_MASTER );
922 $success = $dbw->update( 'watchlist',
923 array( /* SET */
924 'wl_notificationtimestamp' => 0
925 ), array( /* WHERE */
926 'wl_title' => $title->getDBkey(),
927 'wl_namespace' => $title->getNamespace(),
928 'wl_user' => $this->getId()
929 ), 'User::clearLastVisited'
930 );
931 }
932
933 /**#@-*/
934
935 /**
936 * Resets all of the given user's page-change notification timestamps.
937 * If e-notif e-mails are on, they will receive notification mails on
938 * the next change of any watched page.
939 *
940 * @param int $currentUser user ID number
941 * @access public
942 */
943 function clearAllNotifications( $currentUser ) {
944 if( $currentUser != 0 ) {
945
946 $dbw =& wfGetDB( DB_MASTER );
947 $success = $dbw->update( 'watchlist',
948 array( /* SET */
949 'wl_notificationtimestamp' => 0
950 ), array( /* WHERE */
951 'wl_user' => $currentUser
952 ), 'UserMailer::clearAll'
953 );
954
955 # we also need to clear here the "you have new message" notification for the own user_talk page
956 # This is cleared one page view later in Article::viewUpdates();
957 }
958 }
959
960 /**
961 * @access private
962 * @return string Encoding options
963 */
964 function encodeOptions() {
965 $a = array();
966 foreach ( $this->mOptions as $oname => $oval ) {
967 array_push( $a, $oname.'='.$oval );
968 }
969 $s = implode( "\n", $a );
970 return $s;
971 }
972
973 /**
974 * @access private
975 */
976 function decodeOptions( $str ) {
977 $a = explode( "\n", $str );
978 foreach ( $a as $s ) {
979 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
980 $this->mOptions[$m[1]] = $m[2];
981 }
982 }
983 }
984
985 function setCookies() {
986 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
987 if ( 0 == $this->mId ) return;
988 $this->loadFromDatabase();
989 $exp = time() + $wgCookieExpiration;
990
991 $_SESSION['wsUserID'] = $this->mId;
992 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
993
994 $_SESSION['wsUserName'] = $this->mName;
995 setcookie( $wgDBname.'UserName', $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
996
997 $_SESSION['wsToken'] = $this->mToken;
998 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
999 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
1000 } else {
1001 setcookie( $wgDBname.'Token', '', time() - 3600 );
1002 }
1003 }
1004
1005 /**
1006 * Logout user
1007 * It will clean the session cookie
1008 */
1009 function logout() {
1010 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1011 $this->loadDefaults();
1012 $this->setLoaded( true );
1013
1014 $_SESSION['wsUserID'] = 0;
1015
1016 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1017 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1018
1019 # Remember when user logged out, to prevent seeing cached pages
1020 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain );
1021 }
1022
1023 /**
1024 * Save object settings into database
1025 */
1026 function saveSettings() {
1027 global $wgMemc, $wgDBname;
1028 $fname = 'User::saveSettings';
1029
1030 $dbw =& wfGetDB( DB_MASTER );
1031 if ( ! $this->getNewtalk() ) {
1032 # Delete the watchlist entry for user_talk page X watched by user X
1033 $dbw->delete( 'watchlist',
1034 array( 'wl_user' => $this->mId,
1035 'wl_title' => $this->getTitleKey(),
1036 'wl_namespace' => NS_USER_TALK ),
1037 $fname );
1038 if( !$this->mId ) {
1039 # Anon users have a separate memcache space for newtalk
1040 # since they don't store their own info. Trim...
1041 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1042 }
1043 }
1044
1045 if ( 0 == $this->mId ) { return; }
1046
1047 $dbw->update( 'user',
1048 array( /* SET */
1049 'user_name' => $this->mName,
1050 'user_password' => $this->mPassword,
1051 'user_newpassword' => $this->mNewpassword,
1052 'user_real_name' => $this->mRealName,
1053 'user_email' => $this->mEmail,
1054 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1055 'user_options' => $this->encodeOptions(),
1056 'user_touched' => $dbw->timestamp($this->mTouched),
1057 'user_token' => $this->mToken
1058 ), array( /* WHERE */
1059 'user_id' => $this->mId
1060 ), $fname
1061 );
1062 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights ),
1063 'ur_user='. $this->mId, $fname );
1064 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1065
1066 // delete old groups
1067 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId), $fname);
1068
1069 // save new ones
1070 foreach ($this->mGroups as $group) {
1071 $dbw->replace( 'user_groups',
1072 array(array('ug_user','ug_group')),
1073 array(
1074 'ug_user' => $this->mId,
1075 'ug_group' => $group
1076 ), $fname
1077 );
1078 }
1079 }
1080
1081
1082 /**
1083 * Checks if a user with the given name exists, returns the ID
1084 */
1085 function idForName() {
1086 $fname = 'User::idForName';
1087
1088 $gotid = 0;
1089 $s = trim( $this->mName );
1090 if ( 0 == strcmp( '', $s ) ) return 0;
1091
1092 $dbr =& wfGetDB( DB_SLAVE );
1093 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1094 if ( $id === false ) {
1095 $id = 0;
1096 }
1097 return $id;
1098 }
1099
1100 /**
1101 * Add user object to the database
1102 */
1103 function addToDatabase() {
1104 $fname = 'User::addToDatabase';
1105 $dbw =& wfGetDB( DB_MASTER );
1106 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1107 $dbw->insert( 'user',
1108 array(
1109 'user_id' => $seqVal,
1110 'user_name' => $this->mName,
1111 'user_password' => $this->mPassword,
1112 'user_newpassword' => $this->mNewpassword,
1113 'user_email' => $this->mEmail,
1114 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1115 'user_real_name' => $this->mRealName,
1116 'user_options' => $this->encodeOptions(),
1117 'user_token' => $this->mToken
1118 ), $fname
1119 );
1120 $this->mId = $dbw->insertId();
1121 $dbw->insert( 'user_rights',
1122 array(
1123 'ur_user' => $this->mId,
1124 'ur_rights' => implode( ',', $this->mRights )
1125 ), $fname
1126 );
1127
1128 foreach ($this->mGroups as $group) {
1129 $dbw->insert( 'user_groups',
1130 array(
1131 'ug_user' => $this->mId,
1132 'ug_group' => $group
1133 ), $fname
1134 );
1135 }
1136 }
1137
1138 function spreadBlock() {
1139 global $wgIP;
1140 # If the (non-anonymous) user is blocked, this function will block any IP address
1141 # that they successfully log on from.
1142 $fname = 'User::spreadBlock';
1143
1144 wfDebug( "User:spreadBlock()\n" );
1145 if ( $this->mId == 0 ) {
1146 return;
1147 }
1148
1149 $userblock = Block::newFromDB( '', $this->mId );
1150 if ( !$userblock->isValid() ) {
1151 return;
1152 }
1153
1154 # Check if this IP address is already blocked
1155 $ipblock = Block::newFromDB( $wgIP );
1156 if ( $ipblock->isValid() ) {
1157 # Just update the timestamp
1158 $ipblock->updateTimestamp();
1159 return;
1160 }
1161
1162 # Make a new block object with the desired properties
1163 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1164 $ipblock->mAddress = $wgIP;
1165 $ipblock->mUser = 0;
1166 $ipblock->mBy = $userblock->mBy;
1167 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
1168 $ipblock->mTimestamp = wfTimestampNow();
1169 $ipblock->mAuto = 1;
1170 # If the user is already blocked with an expiry date, we don't
1171 # want to pile on top of that!
1172 if($userblock->mExpiry) {
1173 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
1174 } else {
1175 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
1176 }
1177
1178 # Insert it
1179 $ipblock->insert();
1180
1181 }
1182
1183 function getPageRenderingHash() {
1184 global $wgContLang;
1185 if( $this->mHash ){
1186 return $this->mHash;
1187 }
1188
1189 // stubthreshold is only included below for completeness,
1190 // it will always be 0 when this function is called by parsercache.
1191
1192 $confstr = $this->getOption( 'math' );
1193 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1194 $confstr .= '!' . $this->getOption( 'editsection' );
1195 $confstr .= '!' . $this->getOption( 'date' );
1196 $confstr .= '!' . $this->getOption( 'numberheadings' );
1197 $confstr .= '!' . $this->getOption( 'language' );
1198 $confstr .= '!' . $this->getOption( 'thumbsize' );
1199 // add in language specific options, if any
1200 $extra = $wgContLang->getExtraHashOptions();
1201 $confstr .= $extra;
1202
1203 $this->mHash = $confstr;
1204 return $confstr ;
1205 }
1206
1207 function isAllowedToCreateAccount() {
1208 global $wgWhitelistAccount;
1209 $allowed = false;
1210
1211 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1212 foreach ($wgWhitelistAccount as $right => $ok) {
1213 $userHasRight = (!strcmp($right, 'user') || in_array($right, $this->getRights()));
1214 $allowed |= ($ok && $userHasRight);
1215 }
1216 return $allowed;
1217 }
1218
1219 /**
1220 * Set mDataLoaded, return previous value
1221 * Use this to prevent DB access in command-line scripts or similar situations
1222 */
1223 function setLoaded( $loaded ) {
1224 return wfSetVar( $this->mDataLoaded, $loaded );
1225 }
1226
1227 /**
1228 * Get this user's personal page title.
1229 *
1230 * @return Title
1231 * @access public
1232 */
1233 function getUserPage() {
1234 return Title::makeTitle( NS_USER, $this->mName );
1235 }
1236
1237 /**
1238 * Get this user's talk page title.
1239 *
1240 * @return Title
1241 * @access public
1242 */
1243 function getTalkPage() {
1244 $title = $this->getUserPage();
1245 return $title->getTalkPage();
1246 }
1247
1248 /**
1249 * @static
1250 */
1251 function getMaxID() {
1252 $dbr =& wfGetDB( DB_SLAVE );
1253 return $dbr->selectField( 'user', 'max(user_id)', false );
1254 }
1255
1256 /**
1257 * Determine whether the user is a newbie. Newbies are either
1258 * anonymous IPs, or the 1% most recently created accounts.
1259 * Bots and sysops are excluded.
1260 * @return bool True if it is a newbie.
1261 */
1262 function isNewbie() {
1263 return $this->mId > User::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() || $this->getID() == 0;
1264 }
1265
1266 /**
1267 * Check to see if the given clear-text password is one of the accepted passwords
1268 * @param string $password User password.
1269 * @return bool True if the given password is correct otherwise False.
1270 */
1271 function checkPassword( $password ) {
1272 global $wgAuth;
1273 $this->loadFromDatabase();
1274
1275 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1276 return true;
1277 } elseif( $wgAuth->strict() ) {
1278 /* Auth plugin doesn't allow local authentication */
1279 return false;
1280 }
1281 $ep = $this->encryptPassword( $password );
1282 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1283 return true;
1284 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
1285 # If e-mail confirmation hasn't been done already,
1286 # we may as well confirm it here -- the user can only
1287 # get this password via e-mail.
1288 $this->mEmailAuthenticated = wfTimestampNow();
1289
1290 # use the temporary one-time password only once: clear it now !
1291 $this->mNewpassword = '';
1292 $this->saveSettings();
1293 return true;
1294 } elseif ( function_exists( 'iconv' ) ) {
1295 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1296 # Check for this with iconv
1297 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1298 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1299 return true;
1300 }
1301 }
1302 return false;
1303 }
1304
1305 /**
1306 * Initialize (if necessary) and return a session token value
1307 * which can be used in edit forms to show that the user's
1308 * login credentials aren't being hijacked with a foreign form
1309 * submission.
1310 *
1311 * @param mixed $salt - Optional function-specific data for hash.
1312 * Use a string or an array of strings.
1313 * @return string
1314 * @access public
1315 */
1316 function editToken( $salt = '' ) {
1317 if( !isset( $_SESSION['wsEditToken'] ) ) {
1318 $token = $this->generateToken();
1319 $_SESSION['wsEditToken'] = $token;
1320 } else {
1321 $token = $_SESSION['wsEditToken'];
1322 }
1323 if( is_array( $salt ) ) {
1324 $salt = implode( '|', $salt );
1325 }
1326 return md5( $token . $salt );
1327 }
1328
1329 /**
1330 * Generate a hex-y looking random token for various uses.
1331 * Could be made more cryptographically sure if someone cares.
1332 * @return string
1333 */
1334 function generateToken( $salt = '' ) {
1335 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1336 return md5( $token . $salt );
1337 }
1338
1339 /**
1340 * Check given value against the token value stored in the session.
1341 * A match should confirm that the form was submitted from the
1342 * user's own login session, not a form submission from a third-party
1343 * site.
1344 *
1345 * @param string $val - the input value to compare
1346 * @param string $salt - Optional function-specific data for hash
1347 * @return bool
1348 * @access public
1349 */
1350 function matchEditToken( $val, $salt = '' ) {
1351 return ( $val == $this->editToken( $salt ) );
1352 }
1353
1354 /**
1355 * Generate a new e-mail confirmation token and send a confirmation
1356 * mail to the user's given address.
1357 *
1358 * @return mixed True on success, a WikiError object on failure.
1359 */
1360 function sendConfirmationMail() {
1361 global $wgIP, $wgContLang;
1362 $url = $this->confirmationTokenUrl( $expiration );
1363 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1364 wfMsg( 'confirmemail_body',
1365 $wgIP,
1366 $this->getName(),
1367 $url,
1368 $wgContLang->timeanddate( $expiration, false ) ) );
1369 }
1370
1371 /**
1372 * Send an e-mail to this user's account. Does not check for
1373 * confirmed status or validity.
1374 *
1375 * @param string $subject
1376 * @param string $body
1377 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1378 * @return mixed True on success, a WikiError object on failure.
1379 */
1380 function sendMail( $subject, $body, $from = null ) {
1381 if( is_null( $from ) ) {
1382 global $wgPasswordSender;
1383 $from = $wgPasswordSender;
1384 }
1385
1386 require_once( 'UserMailer.php' );
1387 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1388
1389 if( $error == '' ) {
1390 return true;
1391 } else {
1392 return new WikiError( $error );
1393 }
1394 }
1395
1396 /**
1397 * Generate, store, and return a new e-mail confirmation code.
1398 * A hash (unsalted since it's used as a key) is stored.
1399 * @param &$expiration mixed output: accepts the expiration time
1400 * @return string
1401 * @access private
1402 */
1403 function confirmationToken( &$expiration ) {
1404 $fname = 'User::confirmationToken';
1405
1406 $now = time();
1407 $expires = $now + 7 * 24 * 60 * 60;
1408 $expiration = wfTimestamp( TS_MW, $expires );
1409
1410 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
1411 $hash = md5( $token );
1412
1413 $dbw =& wfGetDB( DB_MASTER );
1414 $dbw->update( 'user',
1415 array( 'user_email_token' => $hash,
1416 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1417 array( 'user_id' => $this->mId ),
1418 $fname );
1419
1420 return $token;
1421 }
1422
1423 /**
1424 * Generate and store a new e-mail confirmation token, and return
1425 * the URL the user can use to confirm.
1426 * @param &$expiration mixed output: accepts the expiration time
1427 * @return string
1428 * @access private
1429 */
1430 function confirmationTokenUrl( &$expiration ) {
1431 $token = $this->confirmationToken( $expiration );
1432 $title = Title::makeTitle( NS_SPECIAL, 'Confirmemail/' . $token );
1433 return $title->getFullUrl();
1434 }
1435
1436 /**
1437 * Mark the e-mail address confirmed and save.
1438 */
1439 function confirmEmail() {
1440 $this->loadFromDatabase();
1441 $this->mEmailAuthenticated = wfTimestampNow();
1442 $this->saveSettings();
1443 return true;
1444 }
1445
1446 /**
1447 * Is this user allowed to send e-mails within limits of current
1448 * site configuration?
1449 * @return bool
1450 */
1451 function canSendEmail() {
1452 return $this->isEmailConfirmed();
1453 }
1454
1455 /**
1456 * Is this user allowed to receive e-mails within limits of current
1457 * site configuration?
1458 * @return bool
1459 */
1460 function canReceiveEmail() {
1461 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1462 }
1463
1464 /**
1465 * Is this user's e-mail address valid-looking and confirmed within
1466 * limits of the current site configuration?
1467 *
1468 * If $wgEmailAuthentication is on, this may require the user to have
1469 * confirmed their address by returning a code or using a password
1470 * sent to the address from the wiki.
1471 *
1472 * @return bool
1473 */
1474 function isEmailConfirmed() {
1475 global $wgEmailAuthentication;
1476 $this->loadFromDatabase();
1477 if( $this->isAnon() )
1478 return false;
1479 if( !$this->isValidEmailAddr( $this->mEmail ) )
1480 return false;
1481 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
1482 return false;
1483 return true;
1484 }
1485 }
1486
1487 ?>