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