Merged my changes from REL1_4
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * See user.doc
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 $mEmailAuthenticationtimestamp;
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 * @static
47 * @param string $name Username, validated by Title:newFromText()
48 */
49 function newFromName( $name ) {
50 $u = new User();
51
52 # Clean up name according to title rules
53
54 $t = Title::newFromText( $name );
55 if( is_null( $t ) ) {
56 return NULL;
57 } else {
58 $u->setName( $t->getText() );
59 $u->setId( $u->idFromName( $t->getText() ) );
60 return $u;
61 }
62 }
63
64 /**
65 * Get username given an id.
66 * @param integer $id Database user id
67 * @return string Nickname of a user
68 * @static
69 */
70 function whoIs( $id ) {
71 $dbr =& wfGetDB( DB_SLAVE );
72 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
73 }
74
75 /**
76 * Get real username given an id.
77 * @param integer $id Database user id
78 * @return string Realname of a user
79 * @static
80 */
81 function whoIsReal( $id ) {
82 $dbr =& wfGetDB( DB_SLAVE );
83 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
84 }
85
86 /**
87 * Get database id given a user name
88 * @param string $name Nickname of a user
89 * @return integer|null Database user id (null: if non existent
90 * @static
91 */
92 function idFromName( $name ) {
93 $fname = "User::idFromName";
94
95 $nt = Title::newFromText( $name );
96 if( is_null( $nt ) ) {
97 # Illegal name
98 return null;
99 }
100 $dbr =& wfGetDB( DB_SLAVE );
101 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
102
103 if ( $s === false ) {
104 return 0;
105 } else {
106 return $s->user_id;
107 }
108 }
109
110 /**
111 * does the string match an anonymous user IP address?
112 * @param string $name Nickname of a user
113 * @static
114 */
115 function isIP( $name ) {
116 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
117 }
118
119 /**
120 * does the string match roughly an email address ?
121 * @param string $addr email address
122 * @static
123 */
124 function isValidEmailAddr ( $addr ) {
125 return preg_match( '/^([a-z0-9_.-]+([a-z0-9_.-]+)*\@[a-z0-9_-]+([a-z0-9_.-]+)*([a-z.]{2,})+)$/', strtolower($addr));
126 }
127
128 /**
129 * probably return a random password
130 * @return string probably a random password
131 * @static
132 * @todo Check what is doing really [AV]
133 */
134 function randomPassword() {
135 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
136 $l = strlen( $pwchars ) - 1;
137
138 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
139 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
140 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
141 $pwchars{mt_rand( 0, $l )};
142 return $np;
143 }
144
145 /**
146 * Set properties to default
147 * Used at construction. It will load per language default settings only
148 * if we have an available language object.
149 */
150 function loadDefaults() {
151 static $n=0;
152 $n++;
153 $fname = 'User::loadDefaults' . $n;
154 wfProfileIn( $fname );
155
156 global $wgContLang, $wgIP;
157 global $wgNamespacesToBeSearchedDefault;
158
159 $this->mId = 0;
160 $this->mNewtalk = -1;
161 $this->mName = $wgIP;
162 $this->mRealName = $this->mEmail = '';
163 $this->mEmailAuthenticationtimestamp = 0;
164 $this->mPassword = $this->mNewpassword = '';
165 $this->mRights = array();
166 $this->mGroups = array();
167 // Getting user defaults only if we have an available language
168 if( isset( $wgContLang ) ) {
169 $this->loadDefaultFromLanguage();
170 }
171
172 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
173 $this->mOptions['searchNs'.$nsnum] = $val;
174 }
175 unset( $this->mSkin );
176 $this->mDataLoaded = false;
177 $this->mBlockedby = -1; # Unset
178 $this->mTouched = '0'; # Allow any pages to be cached
179 $this->setToken(); # Random
180 $this->mHash = false;
181 wfProfileOut( $fname );
182 }
183
184 /**
185 * Used to load user options from a language.
186 * This is not in loadDefault() cause we sometime create user before having
187 * a language object.
188 */
189 function loadDefaultFromLanguage(){
190 $this->mOptions = User::getDefaultOptions();
191 }
192
193 /**
194 * Combine the language default options with any site-specific options
195 * and add the default language variants.
196 *
197 * @return array
198 * @static
199 * @access private
200 */
201 function getDefaultOptions() {
202 /**
203 * Site defaults will override the global/language defaults
204 */
205 global $wgContLang, $wgDefaultUserOptions;
206 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptions();
207
208 /**
209 * default language setting
210 */
211 $variant = $wgContLang->getPreferredVariant();
212 $defOpt['variant'] = $variant;
213 $defOpt['language'] = $variant;
214
215 return $defOpt;
216 }
217
218 /**
219 * Get a given default option value.
220 *
221 * @param string $opt
222 * @return string
223 * @static
224 * @access public
225 */
226 function getDefaultOption( $opt ) {
227 $defOpts = User::getDefaultOptions();
228 if( isset( $defOpts[$opt] ) ) {
229 return $defOpts[$opt];
230 } else {
231 return '';
232 }
233 }
234
235 /**
236 * Get blocking information
237 * @access private
238 */
239 function getBlockedStatus() {
240 global $wgIP, $wgBlockCache, $wgProxyList;
241
242 if ( -1 != $this->mBlockedby ) { return; }
243
244 $this->mBlockedby = 0;
245
246 # User blocking
247 if ( $this->mId ) {
248 $block = new Block();
249 if ( $block->load( $wgIP , $this->mId ) ) {
250 $this->mBlockedby = $block->mBy;
251 $this->mBlockreason = $block->mReason;
252 }
253 }
254
255 # IP/range blocking
256 if ( !$this->mBlockedby ) {
257 $block = $wgBlockCache->get( $wgIP );
258 if ( $block !== false ) {
259 $this->mBlockedby = $block->mBy;
260 $this->mBlockreason = $block->mReason;
261 }
262 }
263
264 # Proxy blocking
265 if ( !$this->mBlockedby ) {
266 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
267 $this->mBlockreason = wfMsg( 'proxyblockreason' );
268 $this->mBlockedby = "Proxy blocker";
269 }
270 }
271 }
272
273 /**
274 * Check if user is blocked
275 * @return bool True if blocked, false otherwise
276 */
277 function isBlocked() {
278 $this->getBlockedStatus();
279 if ( 0 === $this->mBlockedby ) { return false; }
280 return true;
281 }
282
283 /**
284 * Get name of blocker
285 * @return string name of blocker
286 */
287 function blockedBy() {
288 $this->getBlockedStatus();
289 return $this->mBlockedby;
290 }
291
292 /**
293 * Get blocking reason
294 * @return string Blocking reason
295 */
296 function blockedFor() {
297 $this->getBlockedStatus();
298 return $this->mBlockreason;
299 }
300
301 /**
302 * Initialise php session
303 */
304 function SetupSession() {
305 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
306 if( $wgSessionsInMemcached ) {
307 require_once( 'MemcachedSessions.php' );
308 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
309 # If it's left on 'user' or another setting from another
310 # application, it will end up failing. Try to recover.
311 ini_set ( 'session.save_handler', 'files' );
312 }
313 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
314 session_cache_limiter( 'private, must-revalidate' );
315 @session_start();
316 }
317
318 /**
319 * Read datas from session
320 * @static
321 */
322 function loadFromSession() {
323 global $wgMemc, $wgDBname;
324
325 if ( isset( $_SESSION['wsUserID'] ) ) {
326 if ( 0 != $_SESSION['wsUserID'] ) {
327 $sId = $_SESSION['wsUserID'];
328 } else {
329 return new User();
330 }
331 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
332 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
333 $_SESSION['wsUserID'] = $sId;
334 } else {
335 return new User();
336 }
337 if ( isset( $_SESSION['wsUserName'] ) ) {
338 $sName = $_SESSION['wsUserName'];
339 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
340 $sName = $_COOKIE["{$wgDBname}UserName"];
341 $_SESSION['wsUserName'] = $sName;
342 } else {
343 return new User();
344 }
345
346 $passwordCorrect = FALSE;
347 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
348 if($makenew = !$user) {
349 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
350 $user = new User();
351 $user->mId = $sId;
352 $user->loadFromDatabase();
353 } else {
354 wfDebug( "User::loadFromSession() got from cache!\n" );
355 }
356
357 if ( isset( $_SESSION['wsToken'] ) ) {
358 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
359 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
360 $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
361 } else {
362 return new User(); # Can't log in from session
363 }
364
365 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
366 if($makenew) {
367 if($wgMemc->set( $key, $user ))
368 wfDebug( "User::loadFromSession() successfully saved user\n" );
369 else
370 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
371 }
372 $user->spreadBlock();
373 return $user;
374 }
375 return new User(); # Can't log in from session
376 }
377
378 /**
379 * Load a user from the database
380 */
381 function loadFromDatabase() {
382 global $wgCommandLineMode, $wgAnonGroupId, $wgLoggedInGroupId;
383 $fname = "User::loadFromDatabase";
384 if ( $this->mDataLoaded || $wgCommandLineMode ) {
385 return;
386 }
387
388 # Paranoia
389 $this->mId = IntVal( $this->mId );
390
391 /** Anonymous user */
392 if(!$this->mId) {
393 /** Get rights */
394 $anong = Group::newFromId($wgAnonGroupId);
395 if (!$anong)
396 wfDebugDieBacktrace("Please update your database schema "
397 ."and populate initial group data from "
398 ."maintenance/archives patches");
399 $anong->loadFromDatabase();
400 $this->mRights = explode(',', $anong->getRights());
401 $this->mDataLoaded = true;
402 return;
403 } # the following stuff is for non-anonymous users only
404
405 $dbr =& wfGetDB( DB_SLAVE );
406 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
407 'user_emailauthenticationtimestamp',
408 'user_real_name','user_options','user_touched', 'user_token' ),
409 array( 'user_id' => $this->mId ), $fname );
410
411 if ( $s !== false ) {
412 $this->mName = $s->user_name;
413 $this->mEmail = $s->user_email;
414 $this->mEmailAuthenticationtimestamp = $s->user_emailauthenticationtimestamp;
415 $this->mRealName = $s->user_real_name;
416 $this->mPassword = $s->user_password;
417 $this->mNewpassword = $s->user_newpassword;
418 $this->decodeOptions( $s->user_options );
419 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
420 $this->mToken = $s->user_token;
421
422 // Get groups id
423 $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId ) );
424
425 while($group = $dbr->fetchRow($res)) {
426 $this->mGroups[] = $group[0];
427 }
428
429 // add the default group for logged in user
430 $this->mGroups[] = $wgLoggedInGroupId;
431
432 $this->mRights = array();
433 // now we merge groups rights to get this user rights
434 foreach($this->mGroups as $aGroupId) {
435 $g = Group::newFromId($aGroupId);
436 $g->loadFromDatabase();
437 $this->mRights = array_merge($this->mRights, explode(',', $g->getRights()));
438 }
439
440 // array merge duplicate rights which are part of several groups
441 $this->mRights = array_unique($this->mRights);
442
443 $dbr->freeResult($res);
444 }
445
446 $this->mDataLoaded = true;
447 }
448
449 function getID() { return $this->mId; }
450 function setID( $v ) {
451 $this->mId = $v;
452 $this->mDataLoaded = false;
453 }
454
455 function getName() {
456 $this->loadFromDatabase();
457 return $this->mName;
458 }
459
460 function setName( $str ) {
461 $this->loadFromDatabase();
462 $this->mName = $str;
463 }
464
465
466 /**
467 * Return the title dbkey form of the name, for eg user pages.
468 * @return string
469 * @access public
470 */
471 function getTitleKey() {
472 return str_replace( ' ', '_', $this->getName() );
473 }
474
475 function getNewtalk() {
476 $fname = 'User::getNewtalk';
477 $this->loadFromDatabase();
478
479 # Load the newtalk status if it is unloaded (mNewtalk=-1)
480 if( $this->mNewtalk == -1 ) {
481 $this->mNewtalk = 0; # reset talk page status
482
483 # Check memcached separately for anons, who have no
484 # entire User object stored in there.
485 if( !$this->mId ) {
486 global $wgDBname, $wgMemc;
487 $key = "$wgDBname:newtalk:ip:{$this->mName}";
488 $newtalk = $wgMemc->get( $key );
489 if( is_integer( $newtalk ) ) {
490 $this->mNewtalk = $newtalk ? 1 : 0;
491 return (bool)$this->mNewtalk;
492 }
493 }
494
495 $dbr =& wfGetDB( DB_SLAVE );
496 $res = $dbr->select( 'watchlist',
497 array( 'wl_user' ),
498 array( 'wl_title' => $this->getTitleKey(),
499 'wl_namespace' => NS_USER_TALK,
500 'wl_user' => $this->mId,
501 'wl_notificationtimestamp != 0' ),
502 'User::getNewtalk' );
503 if( $dbr->numRows($res) > 0 ) {
504 $this->mNewtalk = 1;
505 }
506 $dbr->freeResult( $res );
507
508 if( !$this->mId ) {
509 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
510 }
511 }
512
513 return ( 0 != $this->mNewtalk );
514 }
515
516 function setNewtalk( $val ) {
517 $this->loadFromDatabase();
518 $this->mNewtalk = $val;
519 $this->invalidateCache();
520 }
521
522 function invalidateCache() {
523 $this->loadFromDatabase();
524 $this->mTouched = wfTimestampNow();
525 # Don't forget to save the options after this or
526 # it won't take effect!
527 }
528
529 function validateCache( $timestamp ) {
530 $this->loadFromDatabase();
531 return ($timestamp >= $this->mTouched);
532 }
533
534 /**
535 * Salt a password.
536 * Will only be salted if $wgPasswordSalt is true
537 * @param string Password.
538 * @return string Salted password or clear password.
539 */
540 function addSalt( $p ) {
541 global $wgPasswordSalt;
542 if($wgPasswordSalt)
543 return md5( "{$this->mId}-{$p}" );
544 else
545 return $p;
546 }
547
548 /**
549 * Encrypt a password.
550 * It can eventuall salt a password @see User::addSalt()
551 * @param string $p clear Password.
552 * @param string Encrypted password.
553 */
554 function encryptPassword( $p ) {
555 return $this->addSalt( md5( $p ) );
556 }
557
558 # Set the password and reset the random token
559 function setPassword( $str ) {
560 $this->loadFromDatabase();
561 $this->setToken();
562 $this->mPassword = $this->encryptPassword( $str );
563 $this->mNewpassword = '';
564 }
565
566 # Set the random token (used for persistent authentication)
567 function setToken( $token = false ) {
568 if ( !$token ) {
569 $this->mToken = '';
570 # Take random data from PRNG
571 # This is reasonably secure if the PRNG has been seeded correctly
572 for ($i = 0; $i<USER_TOKEN_LENGTH / 4; $i++) {
573 $this->mToken .= sprintf( "%04X", mt_rand( 0, 65535 ) );
574 }
575 } else {
576 $this->mToken = $token;
577 }
578 }
579
580
581 function setCookiePassword( $str ) {
582 $this->loadFromDatabase();
583 $this->mCookiePassword = md5( $str );
584 }
585
586 function setNewpassword( $str ) {
587 $this->loadFromDatabase();
588 $this->mNewpassword = $this->encryptPassword( $str );
589 }
590
591 function getEmail() {
592 $this->loadFromDatabase();
593 return $this->mEmail;
594 }
595
596 function getEmailAuthenticationtimestamp() {
597 $this->loadFromDatabase();
598 return $this->mEmailAuthenticationtimestamp;
599 }
600
601 function setEmail( $str ) {
602 $this->loadFromDatabase();
603 $this->mEmail = $str;
604 }
605
606 function getRealName() {
607 $this->loadFromDatabase();
608 return $this->mRealName;
609 }
610
611 function setRealName( $str ) {
612 $this->loadFromDatabase();
613 $this->mRealName = $str;
614 }
615
616 function getOption( $oname ) {
617 $this->loadFromDatabase();
618 if ( array_key_exists( $oname, $this->mOptions ) ) {
619 return $this->mOptions[$oname];
620 } else {
621 return '';
622 }
623 }
624
625 function setOption( $oname, $val ) {
626 $this->loadFromDatabase();
627 if ( $oname == 'skin' ) {
628 # Clear cached skin, so the new one displays immediately in Special:Preferences
629 unset( $this->mSkin );
630 }
631 $this->mOptions[$oname] = $val;
632 $this->invalidateCache();
633 }
634
635 function getRights() {
636 $this->loadFromDatabase();
637 return $this->mRights;
638 }
639
640 function addRight( $rname ) {
641 $this->loadFromDatabase();
642 array_push( $this->mRights, $rname );
643 $this->invalidateCache();
644 }
645
646 function getGroups() {
647 $this->loadFromDatabase();
648 return $this->mGroups;
649 }
650
651 function setGroups($groups) {
652 $this->loadFromDatabase();
653 $this->mGroups = $groups;
654 $this->invalidateCache();
655 }
656
657 /**
658 * Check if a user is sysop
659 * Die with backtrace. Use User:isAllowed() instead.
660 * @deprecated
661 */
662 function isSysop() {
663 /**
664 $this->loadFromDatabase();
665 if ( 0 == $this->mId ) { return false; }
666
667 return in_array( 'sysop', $this->mRights );
668 */
669 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
670 }
671
672 /** @deprecated */
673 function isDeveloper() {
674 /**
675 $this->loadFromDatabase();
676 if ( 0 == $this->mId ) { return false; }
677
678 return in_array( 'developer', $this->mRights );
679 */
680 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
681 }
682
683 /** @deprecated */
684 function isBureaucrat() {
685 /**
686 $this->loadFromDatabase();
687 if ( 0 == $this->mId ) { return false; }
688
689 return in_array( 'bureaucrat', $this->mRights );
690 */
691 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
692 }
693
694 /**
695 * Whether the user is a bot
696 * @todo need to be migrated to the new user level management sytem
697 */
698 function isBot() {
699 $this->loadFromDatabase();
700
701 # Why was this here? I need a UID=0 conversion script [TS]
702 # if ( 0 == $this->mId ) { return false; }
703
704 return in_array( 'bot', $this->mRights );
705 }
706
707 /**
708 * Check if user is allowed to access a feature / make an action
709 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
710 * @return boolean True: action is allowed, False: action should not be allowed
711 */
712 function isAllowed($action='') {
713 $this->loadFromDatabase();
714 return in_array( $action , $this->mRights );
715 }
716
717 /**
718 * Load a skin if it doesn't exist or return it
719 * @todo FIXME : need to check the old failback system [AV]
720 */
721 function &getSkin() {
722 global $IP;
723 if ( ! isset( $this->mSkin ) ) {
724 $fname = 'User::getSkin';
725 wfProfileIn( $fname );
726
727 # get all skin names available
728 $skinNames = Skin::getSkinNames();
729
730 # get the user skin
731 $userSkin = $this->getOption( 'skin' );
732 if ( $userSkin == '' ) { $userSkin = 'standard'; }
733
734 if ( !isset( $skinNames[$userSkin] ) ) {
735 # in case the user skin could not be found find a replacement
736 $fallback = array(
737 0 => 'Standard',
738 1 => 'Nostalgia',
739 2 => 'CologneBlue');
740 # if phptal is enabled we should have monobook skin that
741 # superseed the good old SkinStandard.
742 if ( isset( $skinNames['monobook'] ) ) {
743 $fallback[0] = 'MonoBook';
744 }
745
746 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
747 $sn = $fallback[$userSkin];
748 } else {
749 $sn = 'Standard';
750 }
751 } else {
752 # The user skin is available
753 $sn = $skinNames[$userSkin];
754 }
755
756 # Grab the skin class and initialise it. Each skin checks for PHPTal
757 # and will not load if it's not enabled.
758 require_once( $IP.'/skins/'.$sn.'.php' );
759
760 # Check if we got if not failback to default skin
761 $className = 'Skin'.$sn;
762 if( !class_exists( $className ) ) {
763 # DO NOT die if the class isn't found. This breaks maintenance
764 # scripts and can cause a user account to be unrecoverable
765 # except by SQL manipulation if a previously valid skin name
766 # is no longer valid.
767 $className = 'SkinStandard';
768 require_once( $IP.'/skins/Standard.php' );
769 }
770 $this->mSkin =& new $className;
771 wfProfileOut( $fname );
772 }
773 return $this->mSkin;
774 }
775
776 /**#@+
777 * @param string $title Article title to look at
778 */
779
780 /**
781 * Check watched status of an article
782 * @return bool True if article is watched
783 */
784 function isWatched( $title ) {
785 $wl = WatchedItem::fromUserTitle( $this, $title );
786 return $wl->isWatched();
787 }
788
789 /**
790 * Watch an article
791 */
792 function addWatch( $title ) {
793 $wl = WatchedItem::fromUserTitle( $this, $title );
794 $wl->addWatch();
795 $this->invalidateCache();
796 }
797
798 /**
799 * Stop watching an article
800 */
801 function removeWatch( $title ) {
802 $wl = WatchedItem::fromUserTitle( $this, $title );
803 $wl->removeWatch();
804 $this->invalidateCache();
805 }
806
807 /**
808 * Clear the user's notification timestamp for the given title.
809 * If e-notif e-mails are on, they will receive notification mails on
810 * the next change of the page if it's watched etc.
811 */
812 function clearNotification( $title ) {
813 $dbw =& wfGetDB( DB_MASTER );
814 $success = $dbw->update( 'watchlist',
815 array( /* SET */
816 'wl_notificationtimestamp' => 0
817 ), array( /* WHERE */
818 'wl_title' => $title->getDBkey(),
819 'wl_namespace' => $title->getNamespace(),
820 'wl_user' => $this->getId()
821 ), 'User::clearLastVisited'
822 );
823 }
824
825 /**#@-*/
826
827 /**
828 * Resets all of the given user's page-change notification timestamps.
829 * If e-notif e-mails are on, they will receive notification mails on
830 * the next change of any watched page.
831 *
832 * @param int $currentUser user ID number
833 * @access public
834 */
835 function clearAllNotifications( $currentUser ) {
836 if( $currentUser != 0 ) {
837
838 $dbw =& wfGetDB( DB_MASTER );
839 $success = $dbw->update( 'watchlist',
840 array( /* SET */
841 'wl_notificationtimestamp' => 0
842 ), array( /* WHERE */
843 'wl_user' => $currentUser
844 ), 'UserMailer::clearAll'
845 );
846
847 # we also need to clear here the "you have new message" notification for the own user_talk page
848 # This is cleared one page view later in Article::viewUpdates();
849 }
850 }
851
852 /**
853 * @access private
854 * @return string Encoding options
855 */
856 function encodeOptions() {
857 $a = array();
858 foreach ( $this->mOptions as $oname => $oval ) {
859 array_push( $a, $oname.'='.$oval );
860 }
861 $s = implode( "\n", $a );
862 return $s;
863 }
864
865 /**
866 * @access private
867 */
868 function decodeOptions( $str ) {
869 $a = explode( "\n", $str );
870 foreach ( $a as $s ) {
871 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
872 $this->mOptions[$m[1]] = $m[2];
873 }
874 }
875 }
876
877 function setCookies() {
878 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
879 if ( 0 == $this->mId ) return;
880 $this->loadFromDatabase();
881 $exp = time() + $wgCookieExpiration;
882
883 $_SESSION['wsUserID'] = $this->mId;
884 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
885
886 $_SESSION['wsUserName'] = $this->mName;
887 setcookie( $wgDBname.'UserName', $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
888
889 $_SESSION['wsToken'] = $this->mToken;
890 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
891 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
892 } else {
893 setcookie( $wgDBname.'Token', '', time() - 3600 );
894 }
895 }
896
897 /**
898 * Logout user
899 * It will clean the session cookie
900 */
901 function logout() {
902 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
903 $this->loadDefaults();
904 $this->setLoaded( true );
905
906 $_SESSION['wsUserID'] = 0;
907
908 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
909 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
910 }
911
912 /**
913 * Save object settings into database
914 */
915 function saveSettings() {
916 global $wgMemc, $wgDBname;
917 $fname = 'User::saveSettings';
918
919 $dbw =& wfGetDB( DB_MASTER );
920 if ( ! $this->getNewtalk() ) {
921 # Delete the watchlist entry for user_talk page X watched by user X
922 $dbw->delete( 'watchlist',
923 array( 'wl_user' => $this->mId,
924 'wl_title' => $this->getTitleKey(),
925 'wl_namespace' => NS_USER_TALK ),
926 $fname );
927 if( !$this->mId ) {
928 # Anon users have a separate memcache space for newtalk
929 # since they don't store their own info. Trim...
930 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
931 }
932 }
933
934 if ( 0 == $this->mId ) { return; }
935
936 $dbw->update( 'user',
937 array( /* SET */
938 'user_name' => $this->mName,
939 'user_password' => $this->mPassword,
940 'user_newpassword' => $this->mNewpassword,
941 'user_real_name' => $this->mRealName,
942 'user_email' => $this->mEmail,
943 'user_emailauthenticationtimestamp' => $this->mEmailAuthenticationtimestamp,
944 'user_options' => $this->encodeOptions(),
945 'user_touched' => $dbw->timestamp($this->mTouched),
946 'user_token' => $this->mToken
947 ), array( /* WHERE */
948 'user_id' => $this->mId
949 ), $fname
950 );
951 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights ),
952 'ur_user='. $this->mId, $fname );
953 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
954
955 // delete old groups
956 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId), $fname);
957
958 // save new ones
959 foreach ($this->mGroups as $group) {
960 $dbw->replace( 'user_groups',
961 array(array('ug_user','ug_group')),
962 array(
963 'ug_user' => $this->mId,
964 'ug_group' => $group
965 ), $fname
966 );
967 }
968 }
969
970
971 /**
972 * Checks if a user with the given name exists, returns the ID
973 */
974 function idForName() {
975 $fname = 'User::idForName';
976
977 $gotid = 0;
978 $s = trim( $this->mName );
979 if ( 0 == strcmp( '', $s ) ) return 0;
980
981 $dbr =& wfGetDB( DB_SLAVE );
982 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
983 if ( $id === false ) {
984 $id = 0;
985 }
986 return $id;
987 }
988
989 /**
990 * Add user object to the database
991 */
992 function addToDatabase() {
993 $fname = 'User::addToDatabase';
994 $dbw =& wfGetDB( DB_MASTER );
995 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
996 $dbw->insert( 'user',
997 array(
998 'user_id' => $seqVal,
999 'user_name' => $this->mName,
1000 'user_password' => $this->mPassword,
1001 'user_newpassword' => $this->mNewpassword,
1002 'user_email' => $this->mEmail,
1003 'user_emailauthenticationtimestamp' => $this->mEmailAuthenticationtimestamp,
1004 'user_real_name' => $this->mRealName,
1005 'user_options' => $this->encodeOptions(),
1006 'user_token' => $this->mToken
1007 ), $fname
1008 );
1009 $this->mId = $dbw->insertId();
1010 $dbw->insert( 'user_rights',
1011 array(
1012 'ur_user' => $this->mId,
1013 'ur_rights' => implode( ',', $this->mRights )
1014 ), $fname
1015 );
1016
1017 foreach ($this->mGroups as $group) {
1018 $dbw->insert( 'user_groups',
1019 array(
1020 'ug_user' => $this->mId,
1021 'ug_group' => $group
1022 ), $fname
1023 );
1024 }
1025 }
1026
1027 function spreadBlock() {
1028 global $wgIP;
1029 # If the (non-anonymous) user is blocked, this function will block any IP address
1030 # that they successfully log on from.
1031 $fname = 'User::spreadBlock';
1032
1033 wfDebug( "User:spreadBlock()\n" );
1034 if ( $this->mId == 0 ) {
1035 return;
1036 }
1037
1038 $userblock = Block::newFromDB( '', $this->mId );
1039 if ( !$userblock->isValid() ) {
1040 return;
1041 }
1042
1043 # Check if this IP address is already blocked
1044 $ipblock = Block::newFromDB( $wgIP );
1045 if ( $ipblock->isValid() ) {
1046 # Just update the timestamp
1047 $ipblock->updateTimestamp();
1048 return;
1049 }
1050
1051 # Make a new block object with the desired properties
1052 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1053 $ipblock->mAddress = $wgIP;
1054 $ipblock->mUser = 0;
1055 $ipblock->mBy = $userblock->mBy;
1056 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
1057 $ipblock->mTimestamp = wfTimestampNow();
1058 $ipblock->mAuto = 1;
1059 # If the user is already blocked with an expiry date, we don't
1060 # want to pile on top of that!
1061 if($userblock->mExpiry) {
1062 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
1063 } else {
1064 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
1065 }
1066
1067 # Insert it
1068 $ipblock->insert();
1069
1070 }
1071
1072 function getPageRenderingHash() {
1073 global $wgContLang;
1074 if( $this->mHash ){
1075 return $this->mHash;
1076 }
1077
1078 // stubthreshold is only included below for completeness,
1079 // it will always be 0 when this function is called by parsercache.
1080
1081 $confstr = $this->getOption( 'math' );
1082 $confstr .= '!' . $this->getOption( 'highlightbroken' );
1083 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1084 $confstr .= '!' . $this->getOption( 'editsection' );
1085 $confstr .= '!' . $this->getOption( 'editsectiononrightclick' );
1086 $confstr .= '!' . $this->getOption( 'showtoc' );
1087 $confstr .= '!' . $this->getOption( 'date' );
1088 $confstr .= '!' . $this->getOption( 'numberheadings' );
1089 $confstr .= '!' . $this->getOption( 'language' );
1090 // add in language specific options, if any
1091 $extra = $wgContLang->getExtraHashOptions();
1092 $confstr .= $extra;
1093
1094 $this->mHash = $confstr;
1095 return $confstr ;
1096 }
1097
1098 function isAllowedToCreateAccount() {
1099 global $wgWhitelistAccount;
1100 $allowed = false;
1101
1102 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1103 foreach ($wgWhitelistAccount as $right => $ok) {
1104 $userHasRight = (!strcmp($right, 'user') || in_array($right, $this->getRights()));
1105 $allowed |= ($ok && $userHasRight);
1106 }
1107 return $allowed;
1108 }
1109
1110 /**
1111 * Set mDataLoaded, return previous value
1112 * Use this to prevent DB access in command-line scripts or similar situations
1113 */
1114 function setLoaded( $loaded ) {
1115 return wfSetVar( $this->mDataLoaded, $loaded );
1116 }
1117
1118 function getUserPage() {
1119 return Title::makeTitle( NS_USER, $this->mName );
1120 }
1121
1122 /**
1123 * @static
1124 */
1125 function getMaxID() {
1126 $dbr =& wfGetDB( DB_SLAVE );
1127 return $dbr->selectField( 'user', 'max(user_id)', false );
1128 }
1129
1130 /**
1131 * Determine whether the user is a newbie. Newbies are either
1132 * anonymous IPs, or the 1% most recently created accounts.
1133 * Bots and sysops are excluded.
1134 * @return bool True if it is a newbie.
1135 */
1136 function isNewbie() {
1137 return $this->mId > User::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() || $this->getID() == 0;
1138 }
1139
1140 /**
1141 * Check to see if the given clear-text password is one of the accepted passwords
1142 * @param string $password User password.
1143 * @return bool True if the given password is correct otherwise False.
1144 */
1145 function checkPassword( $password ) {
1146 global $wgAuth;
1147 $this->loadFromDatabase();
1148
1149 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1150 return true;
1151 } elseif( $wgAuth->strict() ) {
1152 /* Auth plugin doesn't allow local authentication */
1153 return false;
1154 }
1155 $ep = $this->encryptPassword( $password );
1156 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1157 return true;
1158 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
1159 $this->mEmailAuthenticationtimestamp = wfTimestampNow();
1160 $this->mNewpassword = ''; # use the temporary one-time password only once: clear it now !
1161 $this->saveSettings();
1162 return true;
1163 } elseif ( function_exists( 'iconv' ) ) {
1164 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1165 # Check for this with iconv
1166 /* $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1167 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1168 return true;
1169 }*/
1170 }
1171 return false;
1172 }
1173 }
1174
1175 ?>