Allowing user functions to work in command-line scripts, this will probably break...
[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
385 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
386 # loading in a command line script, don't assume all command line scripts need it like this
387 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
388 if ( $this->mDataLoaded ) {
389 return;
390 }
391
392 # Paranoia
393 $this->mId = IntVal( $this->mId );
394
395 /** Anonymous user */
396 if(!$this->mId) {
397 /** Get rights */
398 $anong = Group::newFromId($wgAnonGroupId);
399 if (!$anong)
400 wfDebugDieBacktrace("Please update your database schema "
401 ."and populate initial group data from "
402 ."maintenance/archives patches");
403 $anong->loadFromDatabase();
404 $this->mRights = explode(',', $anong->getRights());
405 $this->mDataLoaded = true;
406 return;
407 } # the following stuff is for non-anonymous users only
408
409 $dbr =& wfGetDB( DB_SLAVE );
410 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
411 'user_emailauthenticationtimestamp',
412 'user_real_name','user_options','user_touched', 'user_token' ),
413 array( 'user_id' => $this->mId ), $fname );
414
415 if ( $s !== false ) {
416 $this->mName = $s->user_name;
417 $this->mEmail = $s->user_email;
418 $this->mEmailAuthenticationtimestamp = wfTimestamp(TS_MW,$s->user_emailauthenticationtimestamp);
419 $this->mRealName = $s->user_real_name;
420 $this->mPassword = $s->user_password;
421 $this->mNewpassword = $s->user_newpassword;
422 $this->decodeOptions( $s->user_options );
423 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
424 $this->mToken = $s->user_token;
425
426 // Get groups id
427 $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId ) );
428
429 while($group = $dbr->fetchRow($res)) {
430 $this->mGroups[] = $group[0];
431 }
432
433 // add the default group for logged in user
434 $this->mGroups[] = $wgLoggedInGroupId;
435
436 $this->mRights = array();
437 // now we merge groups rights to get this user rights
438 foreach($this->mGroups as $aGroupId) {
439 $g = Group::newFromId($aGroupId);
440 $g->loadFromDatabase();
441 $this->mRights = array_merge($this->mRights, explode(',', $g->getRights()));
442 }
443
444 // array merge duplicate rights which are part of several groups
445 $this->mRights = array_unique($this->mRights);
446
447 $dbr->freeResult($res);
448 }
449
450 $this->mDataLoaded = true;
451 }
452
453 function getID() { return $this->mId; }
454 function setID( $v ) {
455 $this->mId = $v;
456 $this->mDataLoaded = false;
457 }
458
459 function getName() {
460 $this->loadFromDatabase();
461 return $this->mName;
462 }
463
464 function setName( $str ) {
465 $this->loadFromDatabase();
466 $this->mName = $str;
467 }
468
469
470 /**
471 * Return the title dbkey form of the name, for eg user pages.
472 * @return string
473 * @access public
474 */
475 function getTitleKey() {
476 return str_replace( ' ', '_', $this->getName() );
477 }
478
479 function getNewtalk() {
480 $fname = 'User::getNewtalk';
481 $this->loadFromDatabase();
482
483 # Load the newtalk status if it is unloaded (mNewtalk=-1)
484 if( $this->mNewtalk == -1 ) {
485 $this->mNewtalk = 0; # reset talk page status
486
487 # Check memcached separately for anons, who have no
488 # entire User object stored in there.
489 if( !$this->mId ) {
490 global $wgDBname, $wgMemc;
491 $key = "$wgDBname:newtalk:ip:{$this->mName}";
492 $newtalk = $wgMemc->get( $key );
493 if( is_integer( $newtalk ) ) {
494 $this->mNewtalk = $newtalk ? 1 : 0;
495 return (bool)$this->mNewtalk;
496 }
497 }
498
499 $dbr =& wfGetDB( DB_SLAVE );
500 $res = $dbr->select( 'watchlist',
501 array( 'wl_user' ),
502 array( 'wl_title' => $this->getTitleKey(),
503 'wl_namespace' => NS_USER_TALK,
504 'wl_user' => $this->mId,
505 'wl_notificationtimestamp != 0' ),
506 'User::getNewtalk' );
507 if( $dbr->numRows($res) > 0 ) {
508 $this->mNewtalk = 1;
509 }
510 $dbr->freeResult( $res );
511
512 if( !$this->mId ) {
513 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
514 }
515 }
516
517 return ( 0 != $this->mNewtalk );
518 }
519
520 function setNewtalk( $val ) {
521 $this->loadFromDatabase();
522 $this->mNewtalk = $val;
523 $this->invalidateCache();
524 }
525
526 function invalidateCache() {
527 $this->loadFromDatabase();
528 $this->mTouched = wfTimestampNow();
529 # Don't forget to save the options after this or
530 # it won't take effect!
531 }
532
533 function validateCache( $timestamp ) {
534 $this->loadFromDatabase();
535 return ($timestamp >= $this->mTouched);
536 }
537
538 /**
539 * Salt a password.
540 * Will only be salted if $wgPasswordSalt is true
541 * @param string Password.
542 * @return string Salted password or clear password.
543 */
544 function addSalt( $p ) {
545 global $wgPasswordSalt;
546 if($wgPasswordSalt)
547 return md5( "{$this->mId}-{$p}" );
548 else
549 return $p;
550 }
551
552 /**
553 * Encrypt a password.
554 * It can eventuall salt a password @see User::addSalt()
555 * @param string $p clear Password.
556 * @param string Encrypted password.
557 */
558 function encryptPassword( $p ) {
559 return $this->addSalt( md5( $p ) );
560 }
561
562 # Set the password and reset the random token
563 function setPassword( $str ) {
564 $this->loadFromDatabase();
565 $this->setToken();
566 $this->mPassword = $this->encryptPassword( $str );
567 $this->mNewpassword = '';
568 }
569
570 # Set the random token (used for persistent authentication)
571 function setToken( $token = false ) {
572 if ( !$token ) {
573 $this->mToken = '';
574 # Take random data from PRNG
575 # This is reasonably secure if the PRNG has been seeded correctly
576 for ($i = 0; $i<USER_TOKEN_LENGTH / 4; $i++) {
577 $this->mToken .= sprintf( "%04X", mt_rand( 0, 65535 ) );
578 }
579 } else {
580 $this->mToken = $token;
581 }
582 }
583
584
585 function setCookiePassword( $str ) {
586 $this->loadFromDatabase();
587 $this->mCookiePassword = md5( $str );
588 }
589
590 function setNewpassword( $str ) {
591 $this->loadFromDatabase();
592 $this->mNewpassword = $this->encryptPassword( $str );
593 }
594
595 function getEmail() {
596 $this->loadFromDatabase();
597 return $this->mEmail;
598 }
599
600 function getEmailAuthenticationtimestamp() {
601 $this->loadFromDatabase();
602 return $this->mEmailAuthenticationtimestamp;
603 }
604
605 function setEmail( $str ) {
606 $this->loadFromDatabase();
607 $this->mEmail = $str;
608 }
609
610 function getRealName() {
611 $this->loadFromDatabase();
612 return $this->mRealName;
613 }
614
615 function setRealName( $str ) {
616 $this->loadFromDatabase();
617 $this->mRealName = $str;
618 }
619
620 function getOption( $oname ) {
621 $this->loadFromDatabase();
622 if ( array_key_exists( $oname, $this->mOptions ) ) {
623 return $this->mOptions[$oname];
624 } else {
625 return '';
626 }
627 }
628
629 function setOption( $oname, $val ) {
630 $this->loadFromDatabase();
631 if ( $oname == 'skin' ) {
632 # Clear cached skin, so the new one displays immediately in Special:Preferences
633 unset( $this->mSkin );
634 }
635 $this->mOptions[$oname] = $val;
636 $this->invalidateCache();
637 }
638
639 function getRights() {
640 $this->loadFromDatabase();
641 return $this->mRights;
642 }
643
644 function addRight( $rname ) {
645 $this->loadFromDatabase();
646 array_push( $this->mRights, $rname );
647 $this->invalidateCache();
648 }
649
650 function getGroups() {
651 $this->loadFromDatabase();
652 return $this->mGroups;
653 }
654
655 function setGroups($groups) {
656 $this->loadFromDatabase();
657 $this->mGroups = $groups;
658 $this->invalidateCache();
659 }
660
661 /**
662 * Check if a user is sysop
663 * Die with backtrace. Use User:isAllowed() instead.
664 * @deprecated
665 */
666 function isSysop() {
667 /**
668 $this->loadFromDatabase();
669 if ( 0 == $this->mId ) { return false; }
670
671 return in_array( 'sysop', $this->mRights );
672 */
673 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
674 }
675
676 /** @deprecated */
677 function isDeveloper() {
678 /**
679 $this->loadFromDatabase();
680 if ( 0 == $this->mId ) { return false; }
681
682 return in_array( 'developer', $this->mRights );
683 */
684 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
685 }
686
687 /** @deprecated */
688 function isBureaucrat() {
689 /**
690 $this->loadFromDatabase();
691 if ( 0 == $this->mId ) { return false; }
692
693 return in_array( 'bureaucrat', $this->mRights );
694 */
695 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
696 }
697
698 /**
699 * Whether the user is a bot
700 * @todo need to be migrated to the new user level management sytem
701 */
702 function isBot() {
703 $this->loadFromDatabase();
704
705 # Why was this here? I need a UID=0 conversion script [TS]
706 # if ( 0 == $this->mId ) { return false; }
707
708 return in_array( 'bot', $this->mRights );
709 }
710
711 /**
712 * Check if user is allowed to access a feature / make an action
713 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
714 * @return boolean True: action is allowed, False: action should not be allowed
715 */
716 function isAllowed($action='') {
717 $this->loadFromDatabase();
718 return in_array( $action , $this->mRights );
719 }
720
721 /**
722 * Load a skin if it doesn't exist or return it
723 * @todo FIXME : need to check the old failback system [AV]
724 */
725 function &getSkin() {
726 global $IP;
727 if ( ! isset( $this->mSkin ) ) {
728 $fname = 'User::getSkin';
729 wfProfileIn( $fname );
730
731 # get all skin names available
732 $skinNames = Skin::getSkinNames();
733
734 # get the user skin
735 $userSkin = $this->getOption( 'skin' );
736 if ( $userSkin == '' ) { $userSkin = 'standard'; }
737
738 if ( !isset( $skinNames[$userSkin] ) ) {
739 # in case the user skin could not be found find a replacement
740 $fallback = array(
741 0 => 'Standard',
742 1 => 'Nostalgia',
743 2 => 'CologneBlue');
744 # if phptal is enabled we should have monobook skin that
745 # superseed the good old SkinStandard.
746 if ( isset( $skinNames['monobook'] ) ) {
747 $fallback[0] = 'MonoBook';
748 }
749
750 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
751 $sn = $fallback[$userSkin];
752 } else {
753 $sn = 'Standard';
754 }
755 } else {
756 # The user skin is available
757 $sn = $skinNames[$userSkin];
758 }
759
760 # Grab the skin class and initialise it. Each skin checks for PHPTal
761 # and will not load if it's not enabled.
762 require_once( $IP.'/skins/'.$sn.'.php' );
763
764 # Check if we got if not failback to default skin
765 $className = 'Skin'.$sn;
766 if( !class_exists( $className ) ) {
767 # DO NOT die if the class isn't found. This breaks maintenance
768 # scripts and can cause a user account to be unrecoverable
769 # except by SQL manipulation if a previously valid skin name
770 # is no longer valid.
771 $className = 'SkinStandard';
772 require_once( $IP.'/skins/Standard.php' );
773 }
774 $this->mSkin =& new $className;
775 wfProfileOut( $fname );
776 }
777 return $this->mSkin;
778 }
779
780 /**#@+
781 * @param string $title Article title to look at
782 */
783
784 /**
785 * Check watched status of an article
786 * @return bool True if article is watched
787 */
788 function isWatched( $title ) {
789 $wl = WatchedItem::fromUserTitle( $this, $title );
790 return $wl->isWatched();
791 }
792
793 /**
794 * Watch an article
795 */
796 function addWatch( $title ) {
797 $wl = WatchedItem::fromUserTitle( $this, $title );
798 $wl->addWatch();
799 $this->invalidateCache();
800 }
801
802 /**
803 * Stop watching an article
804 */
805 function removeWatch( $title ) {
806 $wl = WatchedItem::fromUserTitle( $this, $title );
807 $wl->removeWatch();
808 $this->invalidateCache();
809 }
810
811 /**
812 * Clear the user's notification timestamp for the given title.
813 * If e-notif e-mails are on, they will receive notification mails on
814 * the next change of the page if it's watched etc.
815 */
816 function clearNotification( $title ) {
817 $userid = $this->getId();
818 if ($userid==0)
819 return;
820 $dbw =& wfGetDB( DB_MASTER );
821 $success = $dbw->update( 'watchlist',
822 array( /* SET */
823 'wl_notificationtimestamp' => $dbw->timestamp(0)
824 ), array( /* WHERE */
825 'wl_title' => $title->getDBkey(),
826 'wl_namespace' => $title->getNamespace(),
827 'wl_user' => $this->getId()
828 ), 'User::clearLastVisited'
829 );
830 }
831
832 /**#@-*/
833
834 /**
835 * Resets all of the given user's page-change notification timestamps.
836 * If e-notif e-mails are on, they will receive notification mails on
837 * the next change of any watched page.
838 *
839 * @param int $currentUser user ID number
840 * @access public
841 */
842 function clearAllNotifications( $currentUser ) {
843 if( $currentUser != 0 ) {
844
845 $dbw =& wfGetDB( DB_MASTER );
846 $success = $dbw->update( 'watchlist',
847 array( /* SET */
848 'wl_notificationtimestamp' => 0
849 ), array( /* WHERE */
850 'wl_user' => $currentUser
851 ), 'UserMailer::clearAll'
852 );
853
854 # we also need to clear here the "you have new message" notification for the own user_talk page
855 # This is cleared one page view later in Article::viewUpdates();
856 }
857 }
858
859 /**
860 * @access private
861 * @return string Encoding options
862 */
863 function encodeOptions() {
864 $a = array();
865 foreach ( $this->mOptions as $oname => $oval ) {
866 array_push( $a, $oname.'='.$oval );
867 }
868 $s = implode( "\n", $a );
869 return $s;
870 }
871
872 /**
873 * @access private
874 */
875 function decodeOptions( $str ) {
876 $a = explode( "\n", $str );
877 foreach ( $a as $s ) {
878 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
879 $this->mOptions[$m[1]] = $m[2];
880 }
881 }
882 }
883
884 function setCookies() {
885 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
886 if ( 0 == $this->mId ) return;
887 $this->loadFromDatabase();
888 $exp = time() + $wgCookieExpiration;
889
890 $_SESSION['wsUserID'] = $this->mId;
891 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
892
893 $_SESSION['wsUserName'] = $this->mName;
894 setcookie( $wgDBname.'UserName', $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
895
896 $_SESSION['wsToken'] = $this->mToken;
897 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
898 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
899 } else {
900 setcookie( $wgDBname.'Token', '', time() - 3600 );
901 }
902 }
903
904 /**
905 * Logout user
906 * It will clean the session cookie
907 */
908 function logout() {
909 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
910 $this->loadDefaults();
911 $this->setLoaded( true );
912
913 $_SESSION['wsUserID'] = 0;
914
915 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
916 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
917 }
918
919 /**
920 * Save object settings into database
921 */
922 function saveSettings() {
923 global $wgMemc, $wgDBname;
924 $fname = 'User::saveSettings';
925
926 $dbw =& wfGetDB( DB_MASTER );
927 if ( ! $this->getNewtalk() ) {
928 # Delete the watchlist entry for user_talk page X watched by user X
929 $dbw->delete( 'watchlist',
930 array( 'wl_user' => $this->mId,
931 'wl_title' => $this->getTitleKey(),
932 'wl_namespace' => NS_USER_TALK ),
933 $fname );
934 if( !$this->mId ) {
935 # Anon users have a separate memcache space for newtalk
936 # since they don't store their own info. Trim...
937 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
938 }
939 }
940
941 if ( 0 == $this->mId ) { return; }
942
943 $dbw->update( 'user',
944 array( /* SET */
945 'user_name' => $this->mName,
946 'user_password' => $this->mPassword,
947 'user_newpassword' => $this->mNewpassword,
948 'user_real_name' => $this->mRealName,
949 'user_email' => $this->mEmail,
950 'user_emailauthenticationtimestamp' => $dbw->timestamp($this->mEmailAuthenticationtimestamp),
951 'user_options' => $this->encodeOptions(),
952 'user_touched' => $dbw->timestamp($this->mTouched),
953 'user_token' => $this->mToken
954 ), array( /* WHERE */
955 'user_id' => $this->mId
956 ), $fname
957 );
958 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights ),
959 'ur_user='. $this->mId, $fname );
960 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
961
962 // delete old groups
963 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId), $fname);
964
965 // save new ones
966 foreach ($this->mGroups as $group) {
967 $dbw->replace( 'user_groups',
968 array(array('ug_user','ug_group')),
969 array(
970 'ug_user' => $this->mId,
971 'ug_group' => $group
972 ), $fname
973 );
974 }
975 }
976
977
978 /**
979 * Checks if a user with the given name exists, returns the ID
980 */
981 function idForName() {
982 $fname = 'User::idForName';
983
984 $gotid = 0;
985 $s = trim( $this->mName );
986 if ( 0 == strcmp( '', $s ) ) return 0;
987
988 $dbr =& wfGetDB( DB_SLAVE );
989 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
990 if ( $id === false ) {
991 $id = 0;
992 }
993 return $id;
994 }
995
996 /**
997 * Add user object to the database
998 */
999 function addToDatabase() {
1000 $fname = 'User::addToDatabase';
1001 $dbw =& wfGetDB( DB_MASTER );
1002 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1003 $dbw->insert( 'user',
1004 array(
1005 'user_id' => $seqVal,
1006 'user_name' => $this->mName,
1007 'user_password' => $this->mPassword,
1008 'user_newpassword' => $this->mNewpassword,
1009 'user_email' => $this->mEmail,
1010 'user_emailauthenticationtimestamp' => $dbw->timestamp($this->mEmailAuthenticationtimestamp),
1011 'user_real_name' => $this->mRealName,
1012 'user_options' => $this->encodeOptions(),
1013 'user_token' => $this->mToken
1014 ), $fname
1015 );
1016 $this->mId = $dbw->insertId();
1017 $dbw->insert( 'user_rights',
1018 array(
1019 'ur_user' => $this->mId,
1020 'ur_rights' => implode( ',', $this->mRights )
1021 ), $fname
1022 );
1023
1024 foreach ($this->mGroups as $group) {
1025 $dbw->insert( 'user_groups',
1026 array(
1027 'ug_user' => $this->mId,
1028 'ug_group' => $group
1029 ), $fname
1030 );
1031 }
1032 }
1033
1034 function spreadBlock() {
1035 global $wgIP;
1036 # If the (non-anonymous) user is blocked, this function will block any IP address
1037 # that they successfully log on from.
1038 $fname = 'User::spreadBlock';
1039
1040 wfDebug( "User:spreadBlock()\n" );
1041 if ( $this->mId == 0 ) {
1042 return;
1043 }
1044
1045 $userblock = Block::newFromDB( '', $this->mId );
1046 if ( !$userblock->isValid() ) {
1047 return;
1048 }
1049
1050 # Check if this IP address is already blocked
1051 $ipblock = Block::newFromDB( $wgIP );
1052 if ( $ipblock->isValid() ) {
1053 # Just update the timestamp
1054 $ipblock->updateTimestamp();
1055 return;
1056 }
1057
1058 # Make a new block object with the desired properties
1059 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1060 $ipblock->mAddress = $wgIP;
1061 $ipblock->mUser = 0;
1062 $ipblock->mBy = $userblock->mBy;
1063 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
1064 $ipblock->mTimestamp = wfTimestampNow();
1065 $ipblock->mAuto = 1;
1066 # If the user is already blocked with an expiry date, we don't
1067 # want to pile on top of that!
1068 if($userblock->mExpiry) {
1069 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
1070 } else {
1071 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
1072 }
1073
1074 # Insert it
1075 $ipblock->insert();
1076
1077 }
1078
1079 function getPageRenderingHash() {
1080 global $wgContLang;
1081 if( $this->mHash ){
1082 return $this->mHash;
1083 }
1084
1085 // stubthreshold is only included below for completeness,
1086 // it will always be 0 when this function is called by parsercache.
1087
1088 $confstr = $this->getOption( 'math' );
1089 $confstr .= '!' . $this->getOption( 'highlightbroken' );
1090 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1091 $confstr .= '!' . $this->getOption( 'editsection' );
1092 $confstr .= '!' . $this->getOption( 'editsectiononrightclick' );
1093 $confstr .= '!' . $this->getOption( 'showtoc' );
1094 $confstr .= '!' . $this->getOption( 'date' );
1095 $confstr .= '!' . $this->getOption( 'numberheadings' );
1096 $confstr .= '!' . $this->getOption( 'language' );
1097 // add in language specific options, if any
1098 $extra = $wgContLang->getExtraHashOptions();
1099 $confstr .= $extra;
1100
1101 $this->mHash = $confstr;
1102 return $confstr ;
1103 }
1104
1105 function isAllowedToCreateAccount() {
1106 global $wgWhitelistAccount;
1107 $allowed = false;
1108
1109 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1110 foreach ($wgWhitelistAccount as $right => $ok) {
1111 $userHasRight = (!strcmp($right, 'user') || in_array($right, $this->getRights()));
1112 $allowed |= ($ok && $userHasRight);
1113 }
1114 return $allowed;
1115 }
1116
1117 /**
1118 * Set mDataLoaded, return previous value
1119 * Use this to prevent DB access in command-line scripts or similar situations
1120 */
1121 function setLoaded( $loaded ) {
1122 return wfSetVar( $this->mDataLoaded, $loaded );
1123 }
1124
1125 function getUserPage() {
1126 return Title::makeTitle( NS_USER, $this->mName );
1127 }
1128
1129 /**
1130 * @static
1131 */
1132 function getMaxID() {
1133 $dbr =& wfGetDB( DB_SLAVE );
1134 return $dbr->selectField( 'user', 'max(user_id)', false );
1135 }
1136
1137 /**
1138 * Determine whether the user is a newbie. Newbies are either
1139 * anonymous IPs, or the 1% most recently created accounts.
1140 * Bots and sysops are excluded.
1141 * @return bool True if it is a newbie.
1142 */
1143 function isNewbie() {
1144 return $this->mId > User::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() || $this->getID() == 0;
1145 }
1146
1147 /**
1148 * Check to see if the given clear-text password is one of the accepted passwords
1149 * @param string $password User password.
1150 * @return bool True if the given password is correct otherwise False.
1151 */
1152 function checkPassword( $password ) {
1153 global $wgAuth;
1154 $this->loadFromDatabase();
1155
1156 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1157 return true;
1158 } elseif( $wgAuth->strict() ) {
1159 /* Auth plugin doesn't allow local authentication */
1160 return false;
1161 }
1162 $ep = $this->encryptPassword( $password );
1163 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1164 return true;
1165 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
1166 $this->mEmailAuthenticationtimestamp = wfTimestampNow();
1167 $this->mNewpassword = ''; # use the temporary one-time password only once: clear it now !
1168 $this->saveSettings();
1169 return true;
1170 } elseif ( function_exists( 'iconv' ) ) {
1171 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1172 # Check for this with iconv
1173 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1174 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1175 return true;
1176 }
1177 }
1178 return false;
1179 }
1180 }
1181
1182 ?>