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