Include timestamp and database in rate limiter log (applying live patch)
[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 global $wgEnableSorbs;
348 return $wgEnableSorbs &&
349 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
350 }
351
352 function inOpmBlacklist( $ip ) {
353 global $wgEnableOpm;
354 return $wgEnableOpm &&
355 $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
356 }
357
358 function inDnsBlacklist( $ip, $base ) {
359 $fname = 'User::inDnsBlacklist';
360 wfProfileIn( $fname );
361
362 $found = false;
363 $host = '';
364
365 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
366 # Make hostname
367 for ( $i=4; $i>=1; $i-- ) {
368 $host .= $m[$i] . '.';
369 }
370 $host .= $base;
371
372 # Send query
373 $ipList = gethostbynamel( $host );
374
375 if ( $ipList ) {
376 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
377 $found = true;
378 } else {
379 wfDebug( "Requested $host, not found in $base.\n" );
380 }
381 }
382
383 wfProfileOut( $fname );
384 return $found;
385 }
386
387 /**
388 * Primitive rate limits: enforce maximum actions per time period
389 * to put a brake on flooding.
390 *
391 * Note: when using a shared cache like memcached, IP-address
392 * last-hit counters will be shared across wikis.
393 *
394 * @return bool true if a rate limiter was tripped
395 * @access public
396 */
397 function pingLimiter( $action='edit' ) {
398 global $wgRateLimits;
399 if( !isset( $wgRateLimits[$action] ) ) {
400 return false;
401 }
402 if( $this->isAllowed( 'delete' ) ) {
403 // goddam cabal
404 return false;
405 }
406
407 global $wgMemc, $wgIP, $wgDBname, $wgRateLimitLog;
408 $fname = 'User::pingLimiter';
409 $limits = $wgRateLimits[$action];
410 $keys = array();
411 $id = $this->getId();
412
413 if( isset( $limits['anon'] ) && $id == 0 ) {
414 $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
415 }
416
417 if( isset( $limits['user'] ) && $id != 0 ) {
418 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
419 }
420 if( $this->isNewbie() ) {
421 if( isset( $limits['newbie'] ) && $id != 0 ) {
422 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
423 }
424 if( isset( $limits['ip'] ) ) {
425 $keys["mediawiki:limiter:$action:ip:$wgIP"] = $limits['ip'];
426 }
427 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $wgIP, $matches ) ) {
428 $subnet = $matches[1];
429 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
430 }
431 }
432
433 $triggered = false;
434 foreach( $keys as $key => $limit ) {
435 list( $max, $period ) = $limit;
436 $summary = "(limit $max in {$period}s)";
437 $count = $wgMemc->get( $key );
438 if( $count ) {
439 if( $count > $max ) {
440 wfDebug( "$fname: tripped! $key at $count $summary\n" );
441 if( $wgRateLimitLog ) {
442 @error_log( wfTimestamp( TS_MW ) . ' ' . $wgDBname . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
443 }
444 $triggered = true;
445 } else {
446 wfDebug( "$fname: ok. $key at $count $summary\n" );
447 }
448 } else {
449 wfDebug( "$fname: adding record for $key $summary\n" );
450 $wgMemc->add( $key, 1, IntVal( $period ) );
451 }
452 $wgMemc->incr( $key );
453 }
454
455 return $triggered;
456 }
457
458 /**
459 * Check if user is blocked
460 * @return bool True if blocked, false otherwise
461 */
462 function isBlocked( $bFromSlave = false ) {
463 $this->getBlockedStatus( $bFromSlave );
464 return $this->mBlockedby !== 0;
465 }
466
467 /**
468 * Get name of blocker
469 * @return string name of blocker
470 */
471 function blockedBy() {
472 $this->getBlockedStatus();
473 return $this->mBlockedby;
474 }
475
476 /**
477 * Get blocking reason
478 * @return string Blocking reason
479 */
480 function blockedFor() {
481 $this->getBlockedStatus();
482 return $this->mBlockreason;
483 }
484
485 /**
486 * Initialise php session
487 */
488 function SetupSession() {
489 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
490 if( $wgSessionsInMemcached ) {
491 require_once( 'MemcachedSessions.php' );
492 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
493 # If it's left on 'user' or another setting from another
494 # application, it will end up failing. Try to recover.
495 ini_set ( 'session.save_handler', 'files' );
496 }
497 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
498 session_cache_limiter( 'private, must-revalidate' );
499 @session_start();
500 }
501
502 /**
503 * Read datas from session
504 * @static
505 */
506 function loadFromSession() {
507 global $wgMemc, $wgDBname;
508
509 if ( isset( $_SESSION['wsUserID'] ) ) {
510 if ( 0 != $_SESSION['wsUserID'] ) {
511 $sId = $_SESSION['wsUserID'];
512 } else {
513 return new User();
514 }
515 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
516 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
517 $_SESSION['wsUserID'] = $sId;
518 } else {
519 return new User();
520 }
521 if ( isset( $_SESSION['wsUserName'] ) ) {
522 $sName = $_SESSION['wsUserName'];
523 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
524 $sName = $_COOKIE["{$wgDBname}UserName"];
525 $_SESSION['wsUserName'] = $sName;
526 } else {
527 return new User();
528 }
529
530 $passwordCorrect = FALSE;
531 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
532 if($makenew = !$user) {
533 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
534 $user = new User();
535 $user->mId = $sId;
536 $user->loadFromDatabase();
537 } else {
538 wfDebug( "User::loadFromSession() got from cache!\n" );
539 }
540
541 if ( isset( $_SESSION['wsToken'] ) ) {
542 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
543 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
544 $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
545 } else {
546 return new User(); # Can't log in from session
547 }
548
549 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
550 if($makenew) {
551 if($wgMemc->set( $key, $user ))
552 wfDebug( "User::loadFromSession() successfully saved user\n" );
553 else
554 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
555 }
556 return $user;
557 }
558 return new User(); # Can't log in from session
559 }
560
561 /**
562 * Load a user from the database
563 */
564 function loadFromDatabase() {
565 global $wgCommandLineMode, $wgAnonGroupId, $wgLoggedInGroupId;
566 $fname = "User::loadFromDatabase";
567
568 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
569 # loading in a command line script, don't assume all command line scripts need it like this
570 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
571 if ( $this->mDataLoaded ) {
572 return;
573 }
574
575 # Paranoia
576 $this->mId = IntVal( $this->mId );
577
578 /** Anonymous user */
579 if(!$this->mId) {
580 /** Get rights */
581 $anong = Group::newFromId($wgAnonGroupId);
582 if (!$anong)
583 wfDebugDieBacktrace("Please update your database schema "
584 ."and populate initial group data from "
585 ."maintenance/archives patches");
586 $anong->loadFromDatabase();
587 $this->mRights = explode(',', $anong->getRights());
588 $this->mDataLoaded = true;
589 return;
590 } # the following stuff is for non-anonymous users only
591
592 $dbr =& wfGetDB( DB_SLAVE );
593 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
594 'user_email_authenticated',
595 'user_real_name','user_options','user_touched', 'user_token' ),
596 array( 'user_id' => $this->mId ), $fname );
597
598 if ( $s !== false ) {
599 $this->mName = $s->user_name;
600 $this->mEmail = $s->user_email;
601 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
602 $this->mRealName = $s->user_real_name;
603 $this->mPassword = $s->user_password;
604 $this->mNewpassword = $s->user_newpassword;
605 $this->decodeOptions( $s->user_options );
606 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
607 $this->mToken = $s->user_token;
608
609 // Get groups id
610 $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId ) );
611
612 // add the default group for logged in user
613 $this->mGroups = array( $wgLoggedInGroupId );
614
615 while($group = $dbr->fetchRow($res)) {
616 if ( $group[0] != $wgLoggedInGroupId ) {
617 $this->mGroups[] = $group[0];
618 }
619 }
620
621
622 $this->mRights = array();
623 // now we merge groups rights to get this user rights
624 foreach($this->mGroups as $aGroupId) {
625 $g = Group::newFromId($aGroupId);
626 $g->loadFromDatabase();
627 $this->mRights = array_merge($this->mRights, explode(',', $g->getRights()));
628 }
629
630 // array merge duplicate rights which are part of several groups
631 $this->mRights = array_unique($this->mRights);
632
633 $dbr->freeResult($res);
634 }
635
636 $this->mDataLoaded = true;
637 }
638
639 function getID() { return $this->mId; }
640 function setID( $v ) {
641 $this->mId = $v;
642 $this->mDataLoaded = false;
643 }
644
645 function getName() {
646 $this->loadFromDatabase();
647 return $this->mName;
648 }
649
650 function setName( $str ) {
651 $this->loadFromDatabase();
652 $this->mName = $str;
653 }
654
655
656 /**
657 * Return the title dbkey form of the name, for eg user pages.
658 * @return string
659 * @access public
660 */
661 function getTitleKey() {
662 return str_replace( ' ', '_', $this->getName() );
663 }
664
665 function getNewtalk() {
666 $fname = 'User::getNewtalk';
667 $this->loadFromDatabase();
668
669 # Load the newtalk status if it is unloaded (mNewtalk=-1)
670 if( $this->mNewtalk == -1 ) {
671 $this->mNewtalk = 0; # reset talk page status
672
673 # Check memcached separately for anons, who have no
674 # entire User object stored in there.
675 if( !$this->mId ) {
676 global $wgDBname, $wgMemc;
677 $key = "$wgDBname:newtalk:ip:{$this->mName}";
678 $newtalk = $wgMemc->get( $key );
679 if( is_integer( $newtalk ) ) {
680 $this->mNewtalk = $newtalk ? 1 : 0;
681 return (bool)$this->mNewtalk;
682 }
683 }
684
685 $dbr =& wfGetDB( DB_SLAVE );
686 $res = $dbr->select( 'watchlist',
687 array( 'wl_user' ),
688 array( 'wl_title' => $this->getTitleKey(),
689 'wl_namespace' => NS_USER_TALK,
690 'wl_user' => $this->mId,
691 'wl_notificationtimestamp != 0' ),
692 'User::getNewtalk' );
693 if( $dbr->numRows($res) > 0 ) {
694 $this->mNewtalk = 1;
695 }
696 $dbr->freeResult( $res );
697
698 if( !$this->mId ) {
699 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
700 }
701 }
702
703 return ( 0 != $this->mNewtalk );
704 }
705
706 function setNewtalk( $val ) {
707 $this->loadFromDatabase();
708 $this->mNewtalk = $val;
709 $this->invalidateCache();
710 }
711
712 function invalidateCache() {
713 $this->loadFromDatabase();
714 $this->mTouched = wfTimestampNow();
715 # Don't forget to save the options after this or
716 # it won't take effect!
717 }
718
719 function validateCache( $timestamp ) {
720 $this->loadFromDatabase();
721 return ($timestamp >= $this->mTouched);
722 }
723
724 /**
725 * Salt a password.
726 * Will only be salted if $wgPasswordSalt is true
727 * @param string Password.
728 * @return string Salted password or clear password.
729 */
730 function addSalt( $p ) {
731 global $wgPasswordSalt;
732 if($wgPasswordSalt)
733 return md5( "{$this->mId}-{$p}" );
734 else
735 return $p;
736 }
737
738 /**
739 * Encrypt a password.
740 * It can eventuall salt a password @see User::addSalt()
741 * @param string $p clear Password.
742 * @param string Encrypted password.
743 */
744 function encryptPassword( $p ) {
745 return $this->addSalt( md5( $p ) );
746 }
747
748 # Set the password and reset the random token
749 function setPassword( $str ) {
750 $this->loadFromDatabase();
751 $this->setToken();
752 $this->mPassword = $this->encryptPassword( $str );
753 $this->mNewpassword = '';
754 }
755
756 # Set the random token (used for persistent authentication)
757 function setToken( $token = false ) {
758 global $wgSecretKey, $wgProxyKey, $wgDBname;
759 if ( !$token ) {
760 if ( $wgSecretKey ) {
761 $key = $wgSecretKey;
762 } elseif ( $wgProxyKey ) {
763 $key = $wgProxyKey;
764 } else {
765 $key = microtime();
766 }
767 $this->mToken = md5( $wgSecretKey . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId );
768 } else {
769 $this->mToken = $token;
770 }
771 }
772
773
774 function setCookiePassword( $str ) {
775 $this->loadFromDatabase();
776 $this->mCookiePassword = md5( $str );
777 }
778
779 function setNewpassword( $str ) {
780 $this->loadFromDatabase();
781 $this->mNewpassword = $this->encryptPassword( $str );
782 }
783
784 function getEmail() {
785 $this->loadFromDatabase();
786 return $this->mEmail;
787 }
788
789 function getEmailAuthenticationTimestamp() {
790 $this->loadFromDatabase();
791 return $this->mEmailAuthenticated;
792 }
793
794 function setEmail( $str ) {
795 $this->loadFromDatabase();
796 $this->mEmail = $str;
797 }
798
799 function getRealName() {
800 $this->loadFromDatabase();
801 return $this->mRealName;
802 }
803
804 function setRealName( $str ) {
805 $this->loadFromDatabase();
806 $this->mRealName = $str;
807 }
808
809 function getOption( $oname ) {
810 $this->loadFromDatabase();
811 if ( array_key_exists( $oname, $this->mOptions ) ) {
812 return $this->mOptions[$oname];
813 } else {
814 return '';
815 }
816 }
817
818 function setOption( $oname, $val ) {
819 $this->loadFromDatabase();
820 if ( $oname == 'skin' ) {
821 # Clear cached skin, so the new one displays immediately in Special:Preferences
822 unset( $this->mSkin );
823 }
824 $this->mOptions[$oname] = $val;
825 $this->invalidateCache();
826 }
827
828 function getRights() {
829 $this->loadFromDatabase();
830 return $this->mRights;
831 }
832
833 function addRight( $rname ) {
834 $this->loadFromDatabase();
835 array_push( $this->mRights, $rname );
836 $this->invalidateCache();
837 }
838
839 function getGroups() {
840 $this->loadFromDatabase();
841 return $this->mGroups;
842 }
843
844 function setGroups($groups) {
845 $this->loadFromDatabase();
846 $this->mGroups = $groups;
847 $this->invalidateCache();
848 }
849
850 /**
851 * A more legible check for non-anonymousness.
852 * Returns true if the user is not an anonymous visitor.
853 *
854 * @return bool
855 */
856 function isLoggedIn() {
857 return( $this->getID() != 0 );
858 }
859
860 /**
861 * A more legible check for anonymousness.
862 * Returns true if the user is an anonymous visitor.
863 *
864 * @return bool
865 */
866 function isAnon() {
867 return !$this->isLoggedIn();
868 }
869
870 /**
871 * Check if a user is sysop
872 * Die with backtrace. Use User:isAllowed() instead.
873 * @deprecated
874 */
875 function isSysop() {
876 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
877 }
878
879 /** @deprecated */
880 function isDeveloper() {
881 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
882 }
883
884 /** @deprecated */
885 function isBureaucrat() {
886 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
887 }
888
889 /**
890 * Whether the user is a bot
891 * @todo need to be migrated to the new user level management sytem
892 */
893 function isBot() {
894 $this->loadFromDatabase();
895 return in_array( 'bot', $this->mRights );
896 }
897
898 /**
899 * Check if user is allowed to access a feature / make an action
900 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
901 * @return boolean True: action is allowed, False: action should not be allowed
902 */
903 function isAllowed($action='') {
904 $this->loadFromDatabase();
905 return in_array( $action , $this->mRights );
906 }
907
908 /**
909 * Load a skin if it doesn't exist or return it
910 * @todo FIXME : need to check the old failback system [AV]
911 */
912 function &getSkin() {
913 global $IP;
914 if ( ! isset( $this->mSkin ) ) {
915 $fname = 'User::getSkin';
916 wfProfileIn( $fname );
917
918 # get all skin names available
919 $skinNames = Skin::getSkinNames();
920
921 # get the user skin
922 $userSkin = $this->getOption( 'skin' );
923 if ( $userSkin == '' ) { $userSkin = 'standard'; }
924
925 if ( !isset( $skinNames[$userSkin] ) ) {
926 # in case the user skin could not be found find a replacement
927 $fallback = array(
928 0 => 'Standard',
929 1 => 'Nostalgia',
930 2 => 'CologneBlue');
931 # if phptal is enabled we should have monobook skin that
932 # superseed the good old SkinStandard.
933 if ( isset( $skinNames['monobook'] ) ) {
934 $fallback[0] = 'MonoBook';
935 }
936
937 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
938 $sn = $fallback[$userSkin];
939 } else {
940 $sn = 'Standard';
941 }
942 } else {
943 # The user skin is available
944 $sn = $skinNames[$userSkin];
945 }
946
947 # Grab the skin class and initialise it. Each skin checks for PHPTal
948 # and will not load if it's not enabled.
949 require_once( $IP.'/skins/'.$sn.'.php' );
950
951 # Check if we got if not failback to default skin
952 $className = 'Skin'.$sn;
953 if( !class_exists( $className ) ) {
954 # DO NOT die if the class isn't found. This breaks maintenance
955 # scripts and can cause a user account to be unrecoverable
956 # except by SQL manipulation if a previously valid skin name
957 # is no longer valid.
958 $className = 'SkinStandard';
959 require_once( $IP.'/skins/Standard.php' );
960 }
961 $this->mSkin =& new $className;
962 wfProfileOut( $fname );
963 }
964 return $this->mSkin;
965 }
966
967 /**#@+
968 * @param string $title Article title to look at
969 */
970
971 /**
972 * Check watched status of an article
973 * @return bool True if article is watched
974 */
975 function isWatched( $title ) {
976 $wl = WatchedItem::fromUserTitle( $this, $title );
977 return $wl->isWatched();
978 }
979
980 /**
981 * Watch an article
982 */
983 function addWatch( $title ) {
984 $wl = WatchedItem::fromUserTitle( $this, $title );
985 $wl->addWatch();
986 $this->invalidateCache();
987 }
988
989 /**
990 * Stop watching an article
991 */
992 function removeWatch( $title ) {
993 $wl = WatchedItem::fromUserTitle( $this, $title );
994 $wl->removeWatch();
995 $this->invalidateCache();
996 }
997
998 /**
999 * Clear the user's notification timestamp for the given title.
1000 * If e-notif e-mails are on, they will receive notification mails on
1001 * the next change of the page if it's watched etc.
1002 */
1003 function clearNotification( &$title ) {
1004 global $wgUser;
1005
1006 $userid = $this->getID();
1007 if ($userid==0)
1008 return;
1009
1010 // Only update the timestamp if the page is being watched.
1011 // The query to find out if it is watched is cached both in memcached and per-invocation,
1012 // and when it does have to be executed, it can be on a slave
1013 // If this is the user's newtalk page, we always update the timestamp
1014 if ($title->getNamespace() == NS_USER_TALK &&
1015 $title->getText() == $wgUser->getName())
1016 {
1017 $watched = true;
1018 } elseif ( $this->getID() == $wgUser->getID() ) {
1019 $watched = $title->userIsWatching();
1020 } else {
1021 $watched = true;
1022 }
1023
1024 // If the page is watched by the user (or may be watched), update the timestamp on any
1025 // any matching rows
1026 if ( $watched ) {
1027 $dbw =& wfGetDB( DB_MASTER );
1028 $success = $dbw->update( 'watchlist',
1029 array( /* SET */
1030 'wl_notificationtimestamp' => 0
1031 ), array( /* WHERE */
1032 'wl_title' => $title->getDBkey(),
1033 'wl_namespace' => $title->getNamespace(),
1034 'wl_user' => $this->getID()
1035 ), 'User::clearLastVisited'
1036 );
1037 }
1038 }
1039
1040 /**#@-*/
1041
1042 /**
1043 * Resets all of the given user's page-change notification timestamps.
1044 * If e-notif e-mails are on, they will receive notification mails on
1045 * the next change of any watched page.
1046 *
1047 * @param int $currentUser user ID number
1048 * @access public
1049 */
1050 function clearAllNotifications( $currentUser ) {
1051 if( $currentUser != 0 ) {
1052
1053 $dbw =& wfGetDB( DB_MASTER );
1054 $success = $dbw->update( 'watchlist',
1055 array( /* SET */
1056 'wl_notificationtimestamp' => 0
1057 ), array( /* WHERE */
1058 'wl_user' => $currentUser
1059 ), 'UserMailer::clearAll'
1060 );
1061
1062 # we also need to clear here the "you have new message" notification for the own user_talk page
1063 # This is cleared one page view later in Article::viewUpdates();
1064 }
1065 }
1066
1067 /**
1068 * @access private
1069 * @return string Encoding options
1070 */
1071 function encodeOptions() {
1072 $a = array();
1073 foreach ( $this->mOptions as $oname => $oval ) {
1074 array_push( $a, $oname.'='.$oval );
1075 }
1076 $s = implode( "\n", $a );
1077 return $s;
1078 }
1079
1080 /**
1081 * @access private
1082 */
1083 function decodeOptions( $str ) {
1084 $a = explode( "\n", $str );
1085 foreach ( $a as $s ) {
1086 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1087 $this->mOptions[$m[1]] = $m[2];
1088 }
1089 }
1090 }
1091
1092 function setCookies() {
1093 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
1094 if ( 0 == $this->mId ) return;
1095 $this->loadFromDatabase();
1096 $exp = time() + $wgCookieExpiration;
1097
1098 $_SESSION['wsUserID'] = $this->mId;
1099 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
1100
1101 $_SESSION['wsUserName'] = $this->mName;
1102 setcookie( $wgDBname.'UserName', $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
1103
1104 $_SESSION['wsToken'] = $this->mToken;
1105 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1106 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
1107 } else {
1108 setcookie( $wgDBname.'Token', '', time() - 3600 );
1109 }
1110 }
1111
1112 /**
1113 * Logout user
1114 * It will clean the session cookie
1115 */
1116 function logout() {
1117 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1118 $this->loadDefaults();
1119 $this->setLoaded( true );
1120
1121 $_SESSION['wsUserID'] = 0;
1122
1123 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1124 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1125
1126 # Remember when user logged out, to prevent seeing cached pages
1127 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain );
1128 }
1129
1130 /**
1131 * Save object settings into database
1132 */
1133 function saveSettings() {
1134 global $wgMemc, $wgDBname;
1135 $fname = 'User::saveSettings';
1136
1137 $dbw =& wfGetDB( DB_MASTER );
1138 if ( ! $this->getNewtalk() ) {
1139 # Delete the watchlist entry for user_talk page X watched by user X
1140 $dbw->delete( 'watchlist',
1141 array( 'wl_user' => $this->mId,
1142 'wl_title' => $this->getTitleKey(),
1143 'wl_namespace' => NS_USER_TALK ),
1144 $fname );
1145 if( !$this->mId ) {
1146 # Anon users have a separate memcache space for newtalk
1147 # since they don't store their own info. Trim...
1148 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1149 }
1150 }
1151
1152 if ( 0 == $this->mId ) { return; }
1153
1154 $dbw->update( 'user',
1155 array( /* SET */
1156 'user_name' => $this->mName,
1157 'user_password' => $this->mPassword,
1158 'user_newpassword' => $this->mNewpassword,
1159 'user_real_name' => $this->mRealName,
1160 'user_email' => $this->mEmail,
1161 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1162 'user_options' => $this->encodeOptions(),
1163 'user_touched' => $dbw->timestamp($this->mTouched),
1164 'user_token' => $this->mToken
1165 ), array( /* WHERE */
1166 'user_id' => $this->mId
1167 ), $fname
1168 );
1169 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights ),
1170 'ur_user='. $this->mId, $fname );
1171 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1172
1173 // delete old groups
1174 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId), $fname);
1175
1176 // save new ones
1177 foreach ($this->mGroups as $group) {
1178 $dbw->replace( 'user_groups',
1179 array(array('ug_user','ug_group')),
1180 array(
1181 'ug_user' => $this->mId,
1182 'ug_group' => $group
1183 ), $fname
1184 );
1185 }
1186 }
1187
1188
1189 /**
1190 * Checks if a user with the given name exists, returns the ID
1191 */
1192 function idForName() {
1193 $fname = 'User::idForName';
1194
1195 $gotid = 0;
1196 $s = trim( $this->mName );
1197 if ( 0 == strcmp( '', $s ) ) return 0;
1198
1199 $dbr =& wfGetDB( DB_SLAVE );
1200 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1201 if ( $id === false ) {
1202 $id = 0;
1203 }
1204 return $id;
1205 }
1206
1207 /**
1208 * Add user object to the database
1209 */
1210 function addToDatabase() {
1211 $fname = 'User::addToDatabase';
1212 $dbw =& wfGetDB( DB_MASTER );
1213 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1214 $dbw->insert( 'user',
1215 array(
1216 'user_id' => $seqVal,
1217 'user_name' => $this->mName,
1218 'user_password' => $this->mPassword,
1219 'user_newpassword' => $this->mNewpassword,
1220 'user_email' => $this->mEmail,
1221 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1222 'user_real_name' => $this->mRealName,
1223 'user_options' => $this->encodeOptions(),
1224 'user_token' => $this->mToken
1225 ), $fname
1226 );
1227 $this->mId = $dbw->insertId();
1228 $dbw->insert( 'user_rights',
1229 array(
1230 'ur_user' => $this->mId,
1231 'ur_rights' => implode( ',', $this->mRights )
1232 ), $fname
1233 );
1234
1235 foreach ($this->mGroups as $group) {
1236 $dbw->insert( 'user_groups',
1237 array(
1238 'ug_user' => $this->mId,
1239 'ug_group' => $group
1240 ), $fname
1241 );
1242 }
1243 }
1244
1245 function spreadBlock() {
1246 global $wgIP;
1247 # If the (non-anonymous) user is blocked, this function will block any IP address
1248 # that they successfully log on from.
1249 $fname = 'User::spreadBlock';
1250
1251 wfDebug( "User:spreadBlock()\n" );
1252 if ( $this->mId == 0 ) {
1253 return;
1254 }
1255
1256 $userblock = Block::newFromDB( '', $this->mId );
1257 if ( !$userblock->isValid() ) {
1258 return;
1259 }
1260
1261 # Check if this IP address is already blocked
1262 $ipblock = Block::newFromDB( $wgIP );
1263 if ( $ipblock->isValid() ) {
1264 # Just update the timestamp
1265 $ipblock->updateTimestamp();
1266 return;
1267 }
1268
1269 # Make a new block object with the desired properties
1270 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1271 $ipblock->mAddress = $wgIP;
1272 $ipblock->mUser = 0;
1273 $ipblock->mBy = $userblock->mBy;
1274 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
1275 $ipblock->mTimestamp = wfTimestampNow();
1276 $ipblock->mAuto = 1;
1277 # If the user is already blocked with an expiry date, we don't
1278 # want to pile on top of that!
1279 if($userblock->mExpiry) {
1280 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
1281 } else {
1282 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
1283 }
1284
1285 # Insert it
1286 $ipblock->insert();
1287
1288 }
1289
1290 function getPageRenderingHash() {
1291 global $wgContLang;
1292 if( $this->mHash ){
1293 return $this->mHash;
1294 }
1295
1296 // stubthreshold is only included below for completeness,
1297 // it will always be 0 when this function is called by parsercache.
1298
1299 $confstr = $this->getOption( 'math' );
1300 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1301 $confstr .= '!' . $this->getOption( 'editsection' );
1302 $confstr .= '!' . $this->getOption( 'date' );
1303 $confstr .= '!' . $this->getOption( 'numberheadings' );
1304 $confstr .= '!' . $this->getOption( 'language' );
1305 $confstr .= '!' . $this->getOption( 'thumbsize' );
1306 // add in language specific options, if any
1307 $extra = $wgContLang->getExtraHashOptions();
1308 $confstr .= $extra;
1309
1310 $this->mHash = $confstr;
1311 return $confstr ;
1312 }
1313
1314 function isAllowedToCreateAccount() {
1315 global $wgWhitelistAccount;
1316 $allowed = false;
1317
1318 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1319 foreach ($wgWhitelistAccount as $right => $ok) {
1320 $userHasRight = (!strcmp($right, 'user') || in_array($right, $this->getRights()));
1321 $allowed |= ($ok && $userHasRight);
1322 }
1323 return $allowed;
1324 }
1325
1326 /**
1327 * Set mDataLoaded, return previous value
1328 * Use this to prevent DB access in command-line scripts or similar situations
1329 */
1330 function setLoaded( $loaded ) {
1331 return wfSetVar( $this->mDataLoaded, $loaded );
1332 }
1333
1334 /**
1335 * Get this user's personal page title.
1336 *
1337 * @return Title
1338 * @access public
1339 */
1340 function getUserPage() {
1341 return Title::makeTitle( NS_USER, $this->mName );
1342 }
1343
1344 /**
1345 * Get this user's talk page title.
1346 *
1347 * @return Title
1348 * @access public
1349 */
1350 function getTalkPage() {
1351 $title = $this->getUserPage();
1352 return $title->getTalkPage();
1353 }
1354
1355 /**
1356 * @static
1357 */
1358 function getMaxID() {
1359 $dbr =& wfGetDB( DB_SLAVE );
1360 return $dbr->selectField( 'user', 'max(user_id)', false );
1361 }
1362
1363 /**
1364 * Determine whether the user is a newbie. Newbies are either
1365 * anonymous IPs, or the 1% most recently created accounts.
1366 * Bots and sysops are excluded.
1367 * @return bool True if it is a newbie.
1368 */
1369 function isNewbie() {
1370 return $this->isAnon() || $this->mId > User::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot();
1371 }
1372
1373 /**
1374 * Check to see if the given clear-text password is one of the accepted passwords
1375 * @param string $password User password.
1376 * @return bool True if the given password is correct otherwise False.
1377 */
1378 function checkPassword( $password ) {
1379 global $wgAuth;
1380 $this->loadFromDatabase();
1381
1382 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1383 return true;
1384 } elseif( $wgAuth->strict() ) {
1385 /* Auth plugin doesn't allow local authentication */
1386 return false;
1387 }
1388 $ep = $this->encryptPassword( $password );
1389 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1390 return true;
1391 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
1392 return true;
1393 } elseif ( function_exists( 'iconv' ) ) {
1394 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1395 # Check for this with iconv
1396 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1397 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1398 return true;
1399 }
1400 }
1401 return false;
1402 }
1403
1404 /**
1405 * Initialize (if necessary) and return a session token value
1406 * which can be used in edit forms to show that the user's
1407 * login credentials aren't being hijacked with a foreign form
1408 * submission.
1409 *
1410 * @param mixed $salt - Optional function-specific data for hash.
1411 * Use a string or an array of strings.
1412 * @return string
1413 * @access public
1414 */
1415 function editToken( $salt = '' ) {
1416 if( !isset( $_SESSION['wsEditToken'] ) ) {
1417 $token = $this->generateToken();
1418 $_SESSION['wsEditToken'] = $token;
1419 } else {
1420 $token = $_SESSION['wsEditToken'];
1421 }
1422 if( is_array( $salt ) ) {
1423 $salt = implode( '|', $salt );
1424 }
1425 return md5( $token . $salt );
1426 }
1427
1428 /**
1429 * Generate a hex-y looking random token for various uses.
1430 * Could be made more cryptographically sure if someone cares.
1431 * @return string
1432 */
1433 function generateToken( $salt = '' ) {
1434 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1435 return md5( $token . $salt );
1436 }
1437
1438 /**
1439 * Check given value against the token value stored in the session.
1440 * A match should confirm that the form was submitted from the
1441 * user's own login session, not a form submission from a third-party
1442 * site.
1443 *
1444 * @param string $val - the input value to compare
1445 * @param string $salt - Optional function-specific data for hash
1446 * @return bool
1447 * @access public
1448 */
1449 function matchEditToken( $val, $salt = '' ) {
1450 return ( $val == $this->editToken( $salt ) );
1451 }
1452
1453 /**
1454 * Generate a new e-mail confirmation token and send a confirmation
1455 * mail to the user's given address.
1456 *
1457 * @return mixed True on success, a WikiError object on failure.
1458 */
1459 function sendConfirmationMail() {
1460 global $wgIP, $wgContLang;
1461 $url = $this->confirmationTokenUrl( $expiration );
1462 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1463 wfMsg( 'confirmemail_body',
1464 $wgIP,
1465 $this->getName(),
1466 $url,
1467 $wgContLang->timeanddate( $expiration, false ) ) );
1468 }
1469
1470 /**
1471 * Send an e-mail to this user's account. Does not check for
1472 * confirmed status or validity.
1473 *
1474 * @param string $subject
1475 * @param string $body
1476 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1477 * @return mixed True on success, a WikiError object on failure.
1478 */
1479 function sendMail( $subject, $body, $from = null ) {
1480 if( is_null( $from ) ) {
1481 global $wgPasswordSender;
1482 $from = $wgPasswordSender;
1483 }
1484
1485 require_once( 'UserMailer.php' );
1486 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1487
1488 if( $error == '' ) {
1489 return true;
1490 } else {
1491 return new WikiError( $error );
1492 }
1493 }
1494
1495 /**
1496 * Generate, store, and return a new e-mail confirmation code.
1497 * A hash (unsalted since it's used as a key) is stored.
1498 * @param &$expiration mixed output: accepts the expiration time
1499 * @return string
1500 * @access private
1501 */
1502 function confirmationToken( &$expiration ) {
1503 $fname = 'User::confirmationToken';
1504
1505 $now = time();
1506 $expires = $now + 7 * 24 * 60 * 60;
1507 $expiration = wfTimestamp( TS_MW, $expires );
1508
1509 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
1510 $hash = md5( $token );
1511
1512 $dbw =& wfGetDB( DB_MASTER );
1513 $dbw->update( 'user',
1514 array( 'user_email_token' => $hash,
1515 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1516 array( 'user_id' => $this->mId ),
1517 $fname );
1518
1519 return $token;
1520 }
1521
1522 /**
1523 * Generate and store a new e-mail confirmation token, and return
1524 * the URL the user can use to confirm.
1525 * @param &$expiration mixed output: accepts the expiration time
1526 * @return string
1527 * @access private
1528 */
1529 function confirmationTokenUrl( &$expiration ) {
1530 $token = $this->confirmationToken( $expiration );
1531 $title = Title::makeTitle( NS_SPECIAL, 'Confirmemail/' . $token );
1532 return $title->getFullUrl();
1533 }
1534
1535 /**
1536 * Mark the e-mail address confirmed and save.
1537 */
1538 function confirmEmail() {
1539 $this->loadFromDatabase();
1540 $this->mEmailAuthenticated = wfTimestampNow();
1541 $this->saveSettings();
1542 return true;
1543 }
1544
1545 /**
1546 * Is this user allowed to send e-mails within limits of current
1547 * site configuration?
1548 * @return bool
1549 */
1550 function canSendEmail() {
1551 return $this->isEmailConfirmed();
1552 }
1553
1554 /**
1555 * Is this user allowed to receive e-mails within limits of current
1556 * site configuration?
1557 * @return bool
1558 */
1559 function canReceiveEmail() {
1560 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1561 }
1562
1563 /**
1564 * Is this user's e-mail address valid-looking and confirmed within
1565 * limits of the current site configuration?
1566 *
1567 * If $wgEmailAuthentication is on, this may require the user to have
1568 * confirmed their address by returning a code or using a password
1569 * sent to the address from the wiki.
1570 *
1571 * @return bool
1572 */
1573 function isEmailConfirmed() {
1574 global $wgEmailAuthentication;
1575 $this->loadFromDatabase();
1576 if( $this->isAnon() )
1577 return false;
1578 if( !$this->isValidEmailAddr( $this->mEmail ) )
1579 return false;
1580 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
1581 return false;
1582 return true;
1583 }
1584 }
1585
1586 ?>