Rework the user_groups system, again, into something that seems to actually
[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
13 # Number of characters in user_token field
14 define( 'USER_TOKEN_LENGTH', 32 );
15
16 /**
17 *
18 * @package MediaWiki
19 */
20 class User {
21 /**#@+
22 * @access private
23 */
24 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
25 var $mEmailAuthenticated;
26 var $mRights, $mOptions;
27 var $mDataLoaded, $mNewpassword;
28 var $mSkin;
29 var $mBlockedby, $mBlockreason;
30 var $mTouched;
31 var $mToken;
32 var $mRealName;
33 var $mHash;
34 var $mGroups;
35
36 /** Construct using User:loadDefaults() */
37 function User() {
38 $this->loadDefaults();
39 }
40
41 /**
42 * Static factory method
43 * @param string $name Username, validated by Title:newFromText()
44 * @return User
45 * @static
46 */
47 function newFromName( $name ) {
48 $u = new User();
49
50 # Clean up name according to title rules
51
52 $t = Title::newFromText( $name );
53 if( is_null( $t ) ) {
54 return NULL;
55 } else {
56 $u->setName( $t->getText() );
57 $u->setId( $u->idFromName( $t->getText() ) );
58 return $u;
59 }
60 }
61
62 /**
63 * Factory method to fetch whichever use has a given email confirmation code.
64 * This code is generated when an account is created or its e-mail address
65 * has changed.
66 *
67 * If the code is invalid or has expired, returns NULL.
68 *
69 * @param string $code
70 * @return User
71 * @static
72 */
73 function newFromConfirmationCode( $code ) {
74 $dbr =& wfGetDB( DB_SLAVE );
75 $name = $dbr->selectField( 'user', 'user_name', array(
76 'user_email_token' => md5( $code ),
77 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
78 ) );
79 if( is_string( $name ) ) {
80 return User::newFromName( $name );
81 } else {
82 return null;
83 }
84 }
85
86 /**
87 * Get username given an id.
88 * @param integer $id Database user id
89 * @return string Nickname of a user
90 * @static
91 */
92 function whoIs( $id ) {
93 $dbr =& wfGetDB( DB_SLAVE );
94 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
95 }
96
97 /**
98 * Get real username given an id.
99 * @param integer $id Database user id
100 * @return string Realname of a user
101 * @static
102 */
103 function whoIsReal( $id ) {
104 $dbr =& wfGetDB( DB_SLAVE );
105 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
106 }
107
108 /**
109 * Get database id given a user name
110 * @param string $name Nickname of a user
111 * @return integer|null Database user id (null: if non existent
112 * @static
113 */
114 function idFromName( $name ) {
115 $fname = "User::idFromName";
116
117 $nt = Title::newFromText( $name );
118 if( is_null( $nt ) ) {
119 # Illegal name
120 return null;
121 }
122 $dbr =& wfGetDB( DB_SLAVE );
123 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
124
125 if ( $s === false ) {
126 return 0;
127 } else {
128 return $s->user_id;
129 }
130 }
131
132 /**
133 * does the string match an anonymous IPv4 address?
134 *
135 * @static
136 * @param string $name Nickname of a user
137 * @return bool
138 */
139 function isIP( $name ) {
140 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
141 /*return preg_match("/^
142 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
143 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
144 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
145 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
146 $/x", $name);*/
147 }
148
149 /**
150 * does the string match roughly an email address ?
151 *
152 * @bug 959
153 *
154 * @param string $addr email address
155 * @static
156 * @return bool
157 */
158 function isValidEmailAddr ( $addr ) {
159 # There used to be a regular expression here, it got removed because it
160 # rejected valid addresses.
161 return ( trim( $addr ) != '' ) &&
162 (false !== strpos( $addr, '@' ) );
163 }
164
165 /**
166 * probably return a random password
167 * @return string probably a random password
168 * @static
169 * @todo Check what is doing really [AV]
170 */
171 function randomPassword() {
172 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
173 $l = strlen( $pwchars ) - 1;
174
175 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
176 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
177 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
178 $pwchars{mt_rand( 0, $l )};
179 return $np;
180 }
181
182 /**
183 * Set properties to default
184 * Used at construction. It will load per language default settings only
185 * if we have an available language object.
186 */
187 function loadDefaults() {
188 static $n=0;
189 $n++;
190 $fname = 'User::loadDefaults' . $n;
191 wfProfileIn( $fname );
192
193 global $wgContLang, $wgIP, $wgDBname;
194 global $wgNamespacesToBeSearchedDefault;
195
196 $this->mId = 0;
197 $this->mNewtalk = -1;
198 $this->mName = $wgIP;
199 $this->mRealName = $this->mEmail = '';
200 $this->mEmailAuthenticated = null;
201 $this->mPassword = $this->mNewpassword = '';
202 $this->mRights = array();
203 $this->mGroups = array();
204 // Getting user defaults only if we have an available language
205 if( isset( $wgContLang ) ) {
206 $this->loadDefaultFromLanguage();
207 }
208
209 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
210 $this->mOptions['searchNs'.$nsnum] = $val;
211 }
212 unset( $this->mSkin );
213 $this->mDataLoaded = false;
214 $this->mBlockedby = -1; # Unset
215 $this->setToken(); # Random
216 $this->mHash = false;
217
218 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
219 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgDBname.'LoggedOut'] );
220 }
221 else {
222 $this->mTouched = '0'; # Allow any pages to be cached
223 }
224
225 wfProfileOut( $fname );
226 }
227
228 /**
229 * Used to load user options from a language.
230 * This is not in loadDefault() cause we sometime create user before having
231 * a language object.
232 */
233 function loadDefaultFromLanguage(){
234 $this->mOptions = User::getDefaultOptions();
235 }
236
237 /**
238 * Combine the language default options with any site-specific options
239 * and add the default language variants.
240 *
241 * @return array
242 * @static
243 * @access private
244 */
245 function getDefaultOptions() {
246 /**
247 * Site defaults will override the global/language defaults
248 */
249 global $wgContLang, $wgDefaultUserOptions;
250 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptions();
251
252 /**
253 * default language setting
254 */
255 $variant = $wgContLang->getPreferredVariant();
256 $defOpt['variant'] = $variant;
257 $defOpt['language'] = $variant;
258
259 return $defOpt;
260 }
261
262 /**
263 * Get a given default option value.
264 *
265 * @param string $opt
266 * @return string
267 * @static
268 * @access public
269 */
270 function getDefaultOption( $opt ) {
271 $defOpts = User::getDefaultOptions();
272 if( isset( $defOpts[$opt] ) ) {
273 return $defOpts[$opt];
274 } else {
275 return '';
276 }
277 }
278
279 /**
280 * Get blocking information
281 * @access private
282 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
283 * non-critical checks are done against slaves. Check when actually saving should be done against
284 * master.
285 *
286 * Note that even if $bFromSlave is false, the check is done first against slave, then master.
287 * The logic is that if blocked on slave, we'll assume it's either blocked on master or
288 * just slightly outta sync and soon corrected - safer to block slightly more that less.
289 * And it's cheaper to check slave first, then master if needed, than master always.
290 */
291 function getBlockedStatus( $bFromSlave = true ) {
292 global $wgIP, $wgBlockCache, $wgProxyList, $wgEnableSorbs, $wgProxyWhitelist;
293
294 if ( -1 != $this->mBlockedby ) { return; }
295
296 $this->mBlockedby = 0;
297
298 # User blocking
299 if ( $this->mId ) {
300 $block = new Block();
301 $block->forUpdate( $bFromSlave );
302 if ( $block->load( $wgIP , $this->mId ) ) {
303 $this->mBlockedby = $block->mBy;
304 $this->mBlockreason = $block->mReason;
305 $this->spreadBlock();
306 }
307 }
308
309 # IP/range blocking
310 if ( !$this->mBlockedby ) {
311 # Check first against slave, and optionally from master.
312 $block = $wgBlockCache->get( $wgIP, true );
313 if ( !$block && !$bFromSlave )
314 {
315 # Not blocked: check against master, to make sure.
316 $wgBlockCache->clearLocal( );
317 $block = $wgBlockCache->get( $wgIP, false );
318 }
319 if ( $block !== false ) {
320 $this->mBlockedby = $block->mBy;
321 $this->mBlockreason = $block->mReason;
322 }
323 }
324
325 # Proxy blocking
326 if ( !$this->isSysop() && !in_array( $wgIP, $wgProxyWhitelist ) ) {
327
328 # Local list
329 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
330 $this->mBlockedby = wfMsg( 'proxyblocker' );
331 $this->mBlockreason = wfMsg( 'proxyblockreason' );
332 }
333
334 # DNSBL
335 if ( !$this->mBlockedby && $wgEnableSorbs ) {
336 if ( $this->inSorbsBlacklist( $wgIP ) ) {
337 $this->mBlockedby = wfMsg( 'sorbs' );
338 $this->mBlockreason = wfMsg( 'sorbsreason' );
339 }
340 }
341 }
342 }
343
344 function inSorbsBlacklist( $ip ) {
345 global $wgEnableSorbs;
346 return $wgEnableSorbs &&
347 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
348 }
349
350 function inOpmBlacklist( $ip ) {
351 global $wgEnableOpm;
352 return $wgEnableOpm &&
353 $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
354 }
355
356 function inDnsBlacklist( $ip, $base ) {
357 $fname = 'User::inDnsBlacklist';
358 wfProfileIn( $fname );
359
360 $found = false;
361 $host = '';
362
363 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
364 # Make hostname
365 for ( $i=4; $i>=1; $i-- ) {
366 $host .= $m[$i] . '.';
367 }
368 $host .= $base;
369
370 # Send query
371 $ipList = gethostbynamel( $host );
372
373 if ( $ipList ) {
374 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
375 $found = true;
376 } else {
377 wfDebug( "Requested $host, not found in $base.\n" );
378 }
379 }
380
381 wfProfileOut( $fname );
382 return $found;
383 }
384
385 /**
386 * Primitive rate limits: enforce maximum actions per time period
387 * to put a brake on flooding.
388 *
389 * Note: when using a shared cache like memcached, IP-address
390 * last-hit counters will be shared across wikis.
391 *
392 * @return bool true if a rate limiter was tripped
393 * @access public
394 */
395 function pingLimiter( $action='edit' ) {
396 global $wgRateLimits;
397 if( !isset( $wgRateLimits[$action] ) ) {
398 return false;
399 }
400 if( $this->isAllowed( 'delete' ) ) {
401 // goddam cabal
402 return false;
403 }
404
405 global $wgMemc, $wgIP, $wgDBname, $wgRateLimitLog;
406 $fname = 'User::pingLimiter';
407 $limits = $wgRateLimits[$action];
408 $keys = array();
409 $id = $this->getId();
410
411 if( isset( $limits['anon'] ) && $id == 0 ) {
412 $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
413 }
414
415 if( isset( $limits['user'] ) && $id != 0 ) {
416 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
417 }
418 if( $this->isNewbie() ) {
419 if( isset( $limits['newbie'] ) && $id != 0 ) {
420 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
421 }
422 if( isset( $limits['ip'] ) ) {
423 $keys["mediawiki:limiter:$action:ip:$wgIP"] = $limits['ip'];
424 }
425 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $wgIP, $matches ) ) {
426 $subnet = $matches[1];
427 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
428 }
429 }
430
431 $triggered = false;
432 foreach( $keys as $key => $limit ) {
433 list( $max, $period ) = $limit;
434 $summary = "(limit $max in {$period}s)";
435 $count = $wgMemc->get( $key );
436 if( $count ) {
437 if( $count > $max ) {
438 wfDebug( "$fname: tripped! $key at $count $summary\n" );
439 if( $wgRateLimitLog ) {
440 @error_log( wfTimestamp( TS_MW ) . ' ' . $wgDBname . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
441 }
442 $triggered = true;
443 } else {
444 wfDebug( "$fname: ok. $key at $count $summary\n" );
445 }
446 } else {
447 wfDebug( "$fname: adding record for $key $summary\n" );
448 $wgMemc->add( $key, 1, IntVal( $period ) );
449 }
450 $wgMemc->incr( $key );
451 }
452
453 return $triggered;
454 }
455
456 /**
457 * Check if user is blocked
458 * @return bool True if blocked, false otherwise
459 */
460 function isBlocked( $bFromSlave = false ) {
461 $this->getBlockedStatus( $bFromSlave );
462 return $this->mBlockedby !== 0;
463 }
464
465 /**
466 * Get name of blocker
467 * @return string name of blocker
468 */
469 function blockedBy() {
470 $this->getBlockedStatus();
471 return $this->mBlockedby;
472 }
473
474 /**
475 * Get blocking reason
476 * @return string Blocking reason
477 */
478 function blockedFor() {
479 $this->getBlockedStatus();
480 return $this->mBlockreason;
481 }
482
483 /**
484 * Initialise php session
485 */
486 function SetupSession() {
487 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
488 if( $wgSessionsInMemcached ) {
489 require_once( 'MemcachedSessions.php' );
490 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
491 # If it's left on 'user' or another setting from another
492 # application, it will end up failing. Try to recover.
493 ini_set ( 'session.save_handler', 'files' );
494 }
495 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
496 session_cache_limiter( 'private, must-revalidate' );
497 @session_start();
498 }
499
500 /**
501 * Read datas from session
502 * @static
503 */
504 function loadFromSession() {
505 global $wgMemc, $wgDBname;
506
507 if ( isset( $_SESSION['wsUserID'] ) ) {
508 if ( 0 != $_SESSION['wsUserID'] ) {
509 $sId = $_SESSION['wsUserID'];
510 } else {
511 return new User();
512 }
513 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
514 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
515 $_SESSION['wsUserID'] = $sId;
516 } else {
517 return new User();
518 }
519 if ( isset( $_SESSION['wsUserName'] ) ) {
520 $sName = $_SESSION['wsUserName'];
521 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
522 $sName = $_COOKIE["{$wgDBname}UserName"];
523 $_SESSION['wsUserName'] = $sName;
524 } else {
525 return new User();
526 }
527
528 $passwordCorrect = FALSE;
529 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
530 if($makenew = !$user) {
531 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
532 $user = new User();
533 $user->mId = $sId;
534 $user->loadFromDatabase();
535 } else {
536 wfDebug( "User::loadFromSession() got from cache!\n" );
537 }
538
539 if ( isset( $_SESSION['wsToken'] ) ) {
540 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
541 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
542 $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
543 } else {
544 return new User(); # Can't log in from session
545 }
546
547 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
548 if($makenew) {
549 if($wgMemc->set( $key, $user ))
550 wfDebug( "User::loadFromSession() successfully saved user\n" );
551 else
552 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
553 }
554 return $user;
555 }
556 return new User(); # Can't log in from session
557 }
558
559 /**
560 * Load a user from the database
561 */
562 function loadFromDatabase() {
563 global $wgCommandLineMode;
564 $fname = "User::loadFromDatabase";
565
566 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
567 # loading in a command line script, don't assume all command line scripts need it like this
568 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
569 if ( $this->mDataLoaded ) {
570 return;
571 }
572
573 # Paranoia
574 $this->mId = IntVal( $this->mId );
575
576 /** Anonymous user */
577 if( !$this->mId ) {
578 /** Get rights */
579 $this->mRights = $this->getGroupPermissions( array( '*' ) );
580 $this->mDataLoaded = true;
581 return;
582 } # the following stuff is for non-anonymous users only
583
584 $dbr =& wfGetDB( DB_SLAVE );
585 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
586 'user_email_authenticated',
587 'user_real_name','user_options','user_touched', 'user_token' ),
588 array( 'user_id' => $this->mId ), $fname );
589
590 if ( $s !== false ) {
591 $this->mName = $s->user_name;
592 $this->mEmail = $s->user_email;
593 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
594 $this->mRealName = $s->user_real_name;
595 $this->mPassword = $s->user_password;
596 $this->mNewpassword = $s->user_newpassword;
597 $this->decodeOptions( $s->user_options );
598 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
599 $this->mToken = $s->user_token;
600
601 $res = $dbr->select( 'user_groups',
602 array( 'ug_group' ),
603 array( 'ug_user' => $this->mId ),
604 $fname );
605 $this->mGroups = array();
606 while( $row = $dbr->fetchObject( $res ) ) {
607 $this->mGroups[] = $row->ug_group;
608 }
609 $effectiveGroups = array_merge( array( '*', 'user' ), $this->mGroups );
610 $this->mRights = $this->getGroupPermissions( $effectiveGroups );
611 }
612
613 $this->mDataLoaded = true;
614 }
615
616 function getID() { return $this->mId; }
617 function setID( $v ) {
618 $this->mId = $v;
619 $this->mDataLoaded = false;
620 }
621
622 function getName() {
623 $this->loadFromDatabase();
624 return $this->mName;
625 }
626
627 function setName( $str ) {
628 $this->loadFromDatabase();
629 $this->mName = $str;
630 }
631
632
633 /**
634 * Return the title dbkey form of the name, for eg user pages.
635 * @return string
636 * @access public
637 */
638 function getTitleKey() {
639 return str_replace( ' ', '_', $this->getName() );
640 }
641
642 function getNewtalk() {
643 $fname = 'User::getNewtalk';
644 $this->loadFromDatabase();
645
646 # Load the newtalk status if it is unloaded (mNewtalk=-1)
647 if( $this->mNewtalk == -1 ) {
648 $this->mNewtalk = 0; # reset talk page status
649
650 # Check memcached separately for anons, who have no
651 # entire User object stored in there.
652 if( !$this->mId ) {
653 global $wgDBname, $wgMemc;
654 $key = "$wgDBname:newtalk:ip:{$this->mName}";
655 $newtalk = $wgMemc->get( $key );
656 if( is_integer( $newtalk ) ) {
657 $this->mNewtalk = $newtalk ? 1 : 0;
658 return (bool)$this->mNewtalk;
659 }
660 }
661
662 $dbr =& wfGetDB( DB_SLAVE );
663 $res = $dbr->select( 'watchlist',
664 array( 'wl_user' ),
665 array( 'wl_title' => $this->getTitleKey(),
666 'wl_namespace' => NS_USER_TALK,
667 'wl_user' => $this->mId,
668 'wl_notificationtimestamp != 0' ),
669 'User::getNewtalk' );
670 if( $dbr->numRows($res) > 0 ) {
671 $this->mNewtalk = 1;
672 }
673 $dbr->freeResult( $res );
674
675 if( !$this->mId ) {
676 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
677 }
678 }
679
680 return ( 0 != $this->mNewtalk );
681 }
682
683 function setNewtalk( $val ) {
684 $this->loadFromDatabase();
685 $this->mNewtalk = $val;
686 $this->invalidateCache();
687 }
688
689 function invalidateCache() {
690 $this->loadFromDatabase();
691 $this->mTouched = wfTimestampNow();
692 # Don't forget to save the options after this or
693 # it won't take effect!
694 }
695
696 function validateCache( $timestamp ) {
697 $this->loadFromDatabase();
698 return ($timestamp >= $this->mTouched);
699 }
700
701 /**
702 * Salt a password.
703 * Will only be salted if $wgPasswordSalt is true
704 * @param string Password.
705 * @return string Salted password or clear password.
706 */
707 function addSalt( $p ) {
708 global $wgPasswordSalt;
709 if($wgPasswordSalt)
710 return md5( "{$this->mId}-{$p}" );
711 else
712 return $p;
713 }
714
715 /**
716 * Encrypt a password.
717 * It can eventuall salt a password @see User::addSalt()
718 * @param string $p clear Password.
719 * @param string Encrypted password.
720 */
721 function encryptPassword( $p ) {
722 return $this->addSalt( md5( $p ) );
723 }
724
725 # Set the password and reset the random token
726 function setPassword( $str ) {
727 $this->loadFromDatabase();
728 $this->setToken();
729 $this->mPassword = $this->encryptPassword( $str );
730 $this->mNewpassword = '';
731 }
732
733 # Set the random token (used for persistent authentication)
734 function setToken( $token = false ) {
735 global $wgSecretKey, $wgProxyKey, $wgDBname;
736 if ( !$token ) {
737 if ( $wgSecretKey ) {
738 $key = $wgSecretKey;
739 } elseif ( $wgProxyKey ) {
740 $key = $wgProxyKey;
741 } else {
742 $key = microtime();
743 }
744 $this->mToken = md5( $wgSecretKey . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId );
745 } else {
746 $this->mToken = $token;
747 }
748 }
749
750
751 function setCookiePassword( $str ) {
752 $this->loadFromDatabase();
753 $this->mCookiePassword = md5( $str );
754 }
755
756 function setNewpassword( $str ) {
757 $this->loadFromDatabase();
758 $this->mNewpassword = $this->encryptPassword( $str );
759 }
760
761 function getEmail() {
762 $this->loadFromDatabase();
763 return $this->mEmail;
764 }
765
766 function getEmailAuthenticationTimestamp() {
767 $this->loadFromDatabase();
768 return $this->mEmailAuthenticated;
769 }
770
771 function setEmail( $str ) {
772 $this->loadFromDatabase();
773 $this->mEmail = $str;
774 }
775
776 function getRealName() {
777 $this->loadFromDatabase();
778 return $this->mRealName;
779 }
780
781 function setRealName( $str ) {
782 $this->loadFromDatabase();
783 $this->mRealName = $str;
784 }
785
786 function getOption( $oname ) {
787 $this->loadFromDatabase();
788 if ( array_key_exists( $oname, $this->mOptions ) ) {
789 return $this->mOptions[$oname];
790 } else {
791 return '';
792 }
793 }
794
795 function setOption( $oname, $val ) {
796 $this->loadFromDatabase();
797 if ( $oname == 'skin' ) {
798 # Clear cached skin, so the new one displays immediately in Special:Preferences
799 unset( $this->mSkin );
800 }
801 $this->mOptions[$oname] = $val;
802 $this->invalidateCache();
803 }
804
805 function getRights() {
806 $this->loadFromDatabase();
807 return $this->mRights;
808 }
809
810 /**
811 * Get the list of explicit group memberships this user has.
812 * The implicit * and user groups are not included.
813 * @return array of strings
814 */
815 function getGroups() {
816 $this->loadFromDatabase();
817 return $this->mGroups;
818 }
819
820 /**
821 * Get the list of implicit group memberships this user has.
822 * This includes all explicit groups, plus 'user' if logged in
823 * and '*' for all accounts.
824 * @return array of strings
825 */
826 function getEffectiveGroups() {
827 $base = array( '*' );
828 if( $this->isLoggedIn() ) {
829 $base[] = 'user';
830 }
831 return array_merge( $base, $this->getGroups() );
832 }
833
834 /**
835 * Remove the user from the given group.
836 * This takes immediate effect.
837 * @string $group
838 */
839 function addGroup( $group ) {
840 $dbw =& wfGetDB( DB_MASTER );
841 $dbw->insert( 'user_groups',
842 array(
843 'ug_user' => $this->getID(),
844 'ug_group' => $group,
845 ),
846 'User::addGroup',
847 array( 'IGNORE' ) );
848
849 $this->mGroups = array_merge( $this->mGroups, array( $group ) );
850 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
851
852 $this->invalidateCache();
853 $this->saveSettings();
854 }
855
856 /**
857 * Remove the user from the given group.
858 * This takes immediate effect.
859 * @string $group
860 */
861 function removeGroup( $group ) {
862 $dbw =& wfGetDB( DB_MASTER );
863 $dbw->delete( 'user_groups',
864 array(
865 'ug_user' => $this->getID(),
866 'ug_group' => $group,
867 ),
868 'User::removeGroup' );
869
870 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
871 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
872
873 $this->invalidateCache();
874 $this->saveSettings();
875 }
876
877
878 /**
879 * A more legible check for non-anonymousness.
880 * Returns true if the user is not an anonymous visitor.
881 *
882 * @return bool
883 */
884 function isLoggedIn() {
885 return( $this->getID() != 0 );
886 }
887
888 /**
889 * A more legible check for anonymousness.
890 * Returns true if the user is an anonymous visitor.
891 *
892 * @return bool
893 */
894 function isAnon() {
895 return !$this->isLoggedIn();
896 }
897
898 /**
899 * Check if a user is sysop
900 * Die with backtrace. Use User:isAllowed() instead.
901 * @deprecated
902 */
903 function isSysop() {
904 return $this->isAllowed( 'protect' );
905 }
906
907 /** @deprecated */
908 function isDeveloper() {
909 return $this->isAllowed( 'siteadmin' );
910 }
911
912 /** @deprecated */
913 function isBureaucrat() {
914 return $this->isAllowed( 'makesysop' );
915 }
916
917 /**
918 * Whether the user is a bot
919 * @todo need to be migrated to the new user level management sytem
920 */
921 function isBot() {
922 $this->loadFromDatabase();
923 return in_array( 'bot', $this->mRights );
924 }
925
926 /**
927 * Check if user is allowed to access a feature / make an action
928 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
929 * @return boolean True: action is allowed, False: action should not be allowed
930 */
931 function isAllowed($action='') {
932 $this->loadFromDatabase();
933 return in_array( $action , $this->mRights );
934 }
935
936 /**
937 * Load a skin if it doesn't exist or return it
938 * @todo FIXME : need to check the old failback system [AV]
939 */
940 function &getSkin() {
941 global $IP;
942 if ( ! isset( $this->mSkin ) ) {
943 $fname = 'User::getSkin';
944 wfProfileIn( $fname );
945
946 # get all skin names available
947 $skinNames = Skin::getSkinNames();
948
949 # get the user skin
950 $userSkin = $this->getOption( 'skin' );
951 if ( $userSkin == '' ) { $userSkin = 'standard'; }
952
953 if ( !isset( $skinNames[$userSkin] ) ) {
954 # in case the user skin could not be found find a replacement
955 $fallback = array(
956 0 => 'Standard',
957 1 => 'Nostalgia',
958 2 => 'CologneBlue');
959 # if phptal is enabled we should have monobook skin that
960 # superseed the good old SkinStandard.
961 if ( isset( $skinNames['monobook'] ) ) {
962 $fallback[0] = 'MonoBook';
963 }
964
965 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
966 $sn = $fallback[$userSkin];
967 } else {
968 $sn = 'Standard';
969 }
970 } else {
971 # The user skin is available
972 $sn = $skinNames[$userSkin];
973 }
974
975 # Grab the skin class and initialise it. Each skin checks for PHPTal
976 # and will not load if it's not enabled.
977 require_once( $IP.'/skins/'.$sn.'.php' );
978
979 # Check if we got if not failback to default skin
980 $className = 'Skin'.$sn;
981 if( !class_exists( $className ) ) {
982 # DO NOT die if the class isn't found. This breaks maintenance
983 # scripts and can cause a user account to be unrecoverable
984 # except by SQL manipulation if a previously valid skin name
985 # is no longer valid.
986 $className = 'SkinStandard';
987 require_once( $IP.'/skins/Standard.php' );
988 }
989 $this->mSkin =& new $className;
990 wfProfileOut( $fname );
991 }
992 return $this->mSkin;
993 }
994
995 /**#@+
996 * @param string $title Article title to look at
997 */
998
999 /**
1000 * Check watched status of an article
1001 * @return bool True if article is watched
1002 */
1003 function isWatched( $title ) {
1004 $wl = WatchedItem::fromUserTitle( $this, $title );
1005 return $wl->isWatched();
1006 }
1007
1008 /**
1009 * Watch an article
1010 */
1011 function addWatch( $title ) {
1012 $wl = WatchedItem::fromUserTitle( $this, $title );
1013 $wl->addWatch();
1014 $this->invalidateCache();
1015 }
1016
1017 /**
1018 * Stop watching an article
1019 */
1020 function removeWatch( $title ) {
1021 $wl = WatchedItem::fromUserTitle( $this, $title );
1022 $wl->removeWatch();
1023 $this->invalidateCache();
1024 }
1025
1026 /**
1027 * Clear the user's notification timestamp for the given title.
1028 * If e-notif e-mails are on, they will receive notification mails on
1029 * the next change of the page if it's watched etc.
1030 */
1031 function clearNotification( &$title ) {
1032 global $wgUser;
1033
1034 $userid = $this->getID();
1035 if ($userid==0)
1036 return;
1037
1038 // Only update the timestamp if the page is being watched.
1039 // The query to find out if it is watched is cached both in memcached and per-invocation,
1040 // and when it does have to be executed, it can be on a slave
1041 // If this is the user's newtalk page, we always update the timestamp
1042 if ($title->getNamespace() == NS_USER_TALK &&
1043 $title->getText() == $wgUser->getName())
1044 {
1045 $watched = true;
1046 } elseif ( $this->getID() == $wgUser->getID() ) {
1047 $watched = $title->userIsWatching();
1048 } else {
1049 $watched = true;
1050 }
1051
1052 // If the page is watched by the user (or may be watched), update the timestamp on any
1053 // any matching rows
1054 if ( $watched ) {
1055 $dbw =& wfGetDB( DB_MASTER );
1056 $success = $dbw->update( 'watchlist',
1057 array( /* SET */
1058 'wl_notificationtimestamp' => 0
1059 ), array( /* WHERE */
1060 'wl_title' => $title->getDBkey(),
1061 'wl_namespace' => $title->getNamespace(),
1062 'wl_user' => $this->getID()
1063 ), 'User::clearLastVisited'
1064 );
1065 }
1066 }
1067
1068 /**#@-*/
1069
1070 /**
1071 * Resets all of the given user's page-change notification timestamps.
1072 * If e-notif e-mails are on, they will receive notification mails on
1073 * the next change of any watched page.
1074 *
1075 * @param int $currentUser user ID number
1076 * @access public
1077 */
1078 function clearAllNotifications( $currentUser ) {
1079 if( $currentUser != 0 ) {
1080
1081 $dbw =& wfGetDB( DB_MASTER );
1082 $success = $dbw->update( 'watchlist',
1083 array( /* SET */
1084 'wl_notificationtimestamp' => 0
1085 ), array( /* WHERE */
1086 'wl_user' => $currentUser
1087 ), 'UserMailer::clearAll'
1088 );
1089
1090 # we also need to clear here the "you have new message" notification for the own user_talk page
1091 # This is cleared one page view later in Article::viewUpdates();
1092 }
1093 }
1094
1095 /**
1096 * @access private
1097 * @return string Encoding options
1098 */
1099 function encodeOptions() {
1100 $a = array();
1101 foreach ( $this->mOptions as $oname => $oval ) {
1102 array_push( $a, $oname.'='.$oval );
1103 }
1104 $s = implode( "\n", $a );
1105 return $s;
1106 }
1107
1108 /**
1109 * @access private
1110 */
1111 function decodeOptions( $str ) {
1112 $a = explode( "\n", $str );
1113 foreach ( $a as $s ) {
1114 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1115 $this->mOptions[$m[1]] = $m[2];
1116 }
1117 }
1118 }
1119
1120 function setCookies() {
1121 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
1122 if ( 0 == $this->mId ) return;
1123 $this->loadFromDatabase();
1124 $exp = time() + $wgCookieExpiration;
1125
1126 $_SESSION['wsUserID'] = $this->mId;
1127 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
1128
1129 $_SESSION['wsUserName'] = $this->mName;
1130 setcookie( $wgDBname.'UserName', $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
1131
1132 $_SESSION['wsToken'] = $this->mToken;
1133 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1134 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
1135 } else {
1136 setcookie( $wgDBname.'Token', '', time() - 3600 );
1137 }
1138 }
1139
1140 /**
1141 * Logout user
1142 * It will clean the session cookie
1143 */
1144 function logout() {
1145 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1146 $this->loadDefaults();
1147 $this->setLoaded( true );
1148
1149 $_SESSION['wsUserID'] = 0;
1150
1151 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1152 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1153
1154 # Remember when user logged out, to prevent seeing cached pages
1155 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain );
1156 }
1157
1158 /**
1159 * Save object settings into database
1160 */
1161 function saveSettings() {
1162 global $wgMemc, $wgDBname;
1163 $fname = 'User::saveSettings';
1164
1165 $dbw =& wfGetDB( DB_MASTER );
1166 if ( ! $this->getNewtalk() ) {
1167 # Delete the watchlist entry for user_talk page X watched by user X
1168 $dbw->delete( 'watchlist',
1169 array( 'wl_user' => $this->mId,
1170 'wl_title' => $this->getTitleKey(),
1171 'wl_namespace' => NS_USER_TALK ),
1172 $fname );
1173 if( !$this->mId ) {
1174 # Anon users have a separate memcache space for newtalk
1175 # since they don't store their own info. Trim...
1176 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1177 }
1178 }
1179
1180 if ( 0 == $this->mId ) { return; }
1181
1182 $dbw->update( 'user',
1183 array( /* SET */
1184 'user_name' => $this->mName,
1185 'user_password' => $this->mPassword,
1186 'user_newpassword' => $this->mNewpassword,
1187 'user_real_name' => $this->mRealName,
1188 'user_email' => $this->mEmail,
1189 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1190 'user_options' => $this->encodeOptions(),
1191 'user_touched' => $dbw->timestamp($this->mTouched),
1192 'user_token' => $this->mToken
1193 ), array( /* WHERE */
1194 'user_id' => $this->mId
1195 ), $fname
1196 );
1197 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1198 }
1199
1200
1201 /**
1202 * Checks if a user with the given name exists, returns the ID
1203 */
1204 function idForName() {
1205 $fname = 'User::idForName';
1206
1207 $gotid = 0;
1208 $s = trim( $this->mName );
1209 if ( 0 == strcmp( '', $s ) ) return 0;
1210
1211 $dbr =& wfGetDB( DB_SLAVE );
1212 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1213 if ( $id === false ) {
1214 $id = 0;
1215 }
1216 return $id;
1217 }
1218
1219 /**
1220 * Add user object to the database
1221 */
1222 function addToDatabase() {
1223 $fname = 'User::addToDatabase';
1224 $dbw =& wfGetDB( DB_MASTER );
1225 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1226 $dbw->insert( 'user',
1227 array(
1228 'user_id' => $seqVal,
1229 'user_name' => $this->mName,
1230 'user_password' => $this->mPassword,
1231 'user_newpassword' => $this->mNewpassword,
1232 'user_email' => $this->mEmail,
1233 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1234 'user_real_name' => $this->mRealName,
1235 'user_options' => $this->encodeOptions(),
1236 'user_token' => $this->mToken
1237 ), $fname
1238 );
1239 $this->mId = $dbw->insertId();
1240 }
1241
1242 function spreadBlock() {
1243 global $wgIP;
1244 # If the (non-anonymous) user is blocked, this function will block any IP address
1245 # that they successfully log on from.
1246 $fname = 'User::spreadBlock';
1247
1248 wfDebug( "User:spreadBlock()\n" );
1249 if ( $this->mId == 0 ) {
1250 return;
1251 }
1252
1253 $userblock = Block::newFromDB( '', $this->mId );
1254 if ( !$userblock->isValid() ) {
1255 return;
1256 }
1257
1258 # Check if this IP address is already blocked
1259 $ipblock = Block::newFromDB( $wgIP );
1260 if ( $ipblock->isValid() ) {
1261 # Just update the timestamp
1262 $ipblock->updateTimestamp();
1263 return;
1264 }
1265
1266 # Make a new block object with the desired properties
1267 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1268 $ipblock->mAddress = $wgIP;
1269 $ipblock->mUser = 0;
1270 $ipblock->mBy = $userblock->mBy;
1271 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
1272 $ipblock->mTimestamp = wfTimestampNow();
1273 $ipblock->mAuto = 1;
1274 # If the user is already blocked with an expiry date, we don't
1275 # want to pile on top of that!
1276 if($userblock->mExpiry) {
1277 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
1278 } else {
1279 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
1280 }
1281
1282 # Insert it
1283 $ipblock->insert();
1284
1285 }
1286
1287 function getPageRenderingHash() {
1288 global $wgContLang;
1289 if( $this->mHash ){
1290 return $this->mHash;
1291 }
1292
1293 // stubthreshold is only included below for completeness,
1294 // it will always be 0 when this function is called by parsercache.
1295
1296 $confstr = $this->getOption( 'math' );
1297 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1298 $confstr .= '!' . $this->getOption( 'editsection' );
1299 $confstr .= '!' . $this->getOption( 'date' );
1300 $confstr .= '!' . $this->getOption( 'numberheadings' );
1301 $confstr .= '!' . $this->getOption( 'language' );
1302 $confstr .= '!' . $this->getOption( 'thumbsize' );
1303 // add in language specific options, if any
1304 $extra = $wgContLang->getExtraHashOptions();
1305 $confstr .= $extra;
1306
1307 $this->mHash = $confstr;
1308 return $confstr ;
1309 }
1310
1311 function isAllowedToCreateAccount() {
1312 global $wgWhitelistAccount;
1313 $allowed = false;
1314
1315 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1316 foreach ($wgWhitelistAccount as $right => $ok) {
1317 $userHasRight = (!strcmp($right, 'user') || in_array($right, $this->getRights()));
1318 $allowed |= ($ok && $userHasRight);
1319 }
1320 return $allowed;
1321 }
1322
1323 /**
1324 * Set mDataLoaded, return previous value
1325 * Use this to prevent DB access in command-line scripts or similar situations
1326 */
1327 function setLoaded( $loaded ) {
1328 return wfSetVar( $this->mDataLoaded, $loaded );
1329 }
1330
1331 /**
1332 * Get this user's personal page title.
1333 *
1334 * @return Title
1335 * @access public
1336 */
1337 function getUserPage() {
1338 return Title::makeTitle( NS_USER, $this->mName );
1339 }
1340
1341 /**
1342 * Get this user's talk page title.
1343 *
1344 * @return Title
1345 * @access public
1346 */
1347 function getTalkPage() {
1348 $title = $this->getUserPage();
1349 return $title->getTalkPage();
1350 }
1351
1352 /**
1353 * @static
1354 */
1355 function getMaxID() {
1356 $dbr =& wfGetDB( DB_SLAVE );
1357 return $dbr->selectField( 'user', 'max(user_id)', false );
1358 }
1359
1360 /**
1361 * Determine whether the user is a newbie. Newbies are either
1362 * anonymous IPs, or the 1% most recently created accounts.
1363 * Bots and sysops are excluded.
1364 * @return bool True if it is a newbie.
1365 */
1366 function isNewbie() {
1367 return $this->isAnon() || $this->mId > User::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot();
1368 }
1369
1370 /**
1371 * Check to see if the given clear-text password is one of the accepted passwords
1372 * @param string $password User password.
1373 * @return bool True if the given password is correct otherwise False.
1374 */
1375 function checkPassword( $password ) {
1376 global $wgAuth, $wgMinimalPasswordLength;
1377 $this->loadFromDatabase();
1378
1379 // Even though we stop people from creating passwords that
1380 // are shorter than this, doesn't mean people wont be able
1381 // to. Certain authentication plugins do NOT want to save
1382 // domain passwords in a mysql database, so we should
1383 // check this (incase $wgAuth->strict() is false).
1384 if( strlen( $password ) < $wgMinimalPasswordLength ) {
1385 return false;
1386 }
1387
1388 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1389 return true;
1390 } elseif( $wgAuth->strict() ) {
1391 /* Auth plugin doesn't allow local authentication */
1392 return false;
1393 }
1394 $ep = $this->encryptPassword( $password );
1395 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1396 return true;
1397 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
1398 return true;
1399 } elseif ( function_exists( 'iconv' ) ) {
1400 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1401 # Check for this with iconv
1402 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1403 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1404 return true;
1405 }
1406 }
1407 return false;
1408 }
1409
1410 /**
1411 * Initialize (if necessary) and return a session token value
1412 * which can be used in edit forms to show that the user's
1413 * login credentials aren't being hijacked with a foreign form
1414 * submission.
1415 *
1416 * @param mixed $salt - Optional function-specific data for hash.
1417 * Use a string or an array of strings.
1418 * @return string
1419 * @access public
1420 */
1421 function editToken( $salt = '' ) {
1422 if( !isset( $_SESSION['wsEditToken'] ) ) {
1423 $token = $this->generateToken();
1424 $_SESSION['wsEditToken'] = $token;
1425 } else {
1426 $token = $_SESSION['wsEditToken'];
1427 }
1428 if( is_array( $salt ) ) {
1429 $salt = implode( '|', $salt );
1430 }
1431 return md5( $token . $salt );
1432 }
1433
1434 /**
1435 * Generate a hex-y looking random token for various uses.
1436 * Could be made more cryptographically sure if someone cares.
1437 * @return string
1438 */
1439 function generateToken( $salt = '' ) {
1440 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1441 return md5( $token . $salt );
1442 }
1443
1444 /**
1445 * Check given value against the token value stored in the session.
1446 * A match should confirm that the form was submitted from the
1447 * user's own login session, not a form submission from a third-party
1448 * site.
1449 *
1450 * @param string $val - the input value to compare
1451 * @param string $salt - Optional function-specific data for hash
1452 * @return bool
1453 * @access public
1454 */
1455 function matchEditToken( $val, $salt = '' ) {
1456 return ( $val == $this->editToken( $salt ) );
1457 }
1458
1459 /**
1460 * Generate a new e-mail confirmation token and send a confirmation
1461 * mail to the user's given address.
1462 *
1463 * @return mixed True on success, a WikiError object on failure.
1464 */
1465 function sendConfirmationMail() {
1466 global $wgIP, $wgContLang;
1467 $url = $this->confirmationTokenUrl( $expiration );
1468 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1469 wfMsg( 'confirmemail_body',
1470 $wgIP,
1471 $this->getName(),
1472 $url,
1473 $wgContLang->timeanddate( $expiration, false ) ) );
1474 }
1475
1476 /**
1477 * Send an e-mail to this user's account. Does not check for
1478 * confirmed status or validity.
1479 *
1480 * @param string $subject
1481 * @param string $body
1482 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1483 * @return mixed True on success, a WikiError object on failure.
1484 */
1485 function sendMail( $subject, $body, $from = null ) {
1486 if( is_null( $from ) ) {
1487 global $wgPasswordSender;
1488 $from = $wgPasswordSender;
1489 }
1490
1491 require_once( 'UserMailer.php' );
1492 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1493
1494 if( $error == '' ) {
1495 return true;
1496 } else {
1497 return new WikiError( $error );
1498 }
1499 }
1500
1501 /**
1502 * Generate, store, and return a new e-mail confirmation code.
1503 * A hash (unsalted since it's used as a key) is stored.
1504 * @param &$expiration mixed output: accepts the expiration time
1505 * @return string
1506 * @access private
1507 */
1508 function confirmationToken( &$expiration ) {
1509 $fname = 'User::confirmationToken';
1510
1511 $now = time();
1512 $expires = $now + 7 * 24 * 60 * 60;
1513 $expiration = wfTimestamp( TS_MW, $expires );
1514
1515 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
1516 $hash = md5( $token );
1517
1518 $dbw =& wfGetDB( DB_MASTER );
1519 $dbw->update( 'user',
1520 array( 'user_email_token' => $hash,
1521 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1522 array( 'user_id' => $this->mId ),
1523 $fname );
1524
1525 return $token;
1526 }
1527
1528 /**
1529 * Generate and store a new e-mail confirmation token, and return
1530 * the URL the user can use to confirm.
1531 * @param &$expiration mixed output: accepts the expiration time
1532 * @return string
1533 * @access private
1534 */
1535 function confirmationTokenUrl( &$expiration ) {
1536 $token = $this->confirmationToken( $expiration );
1537 $title = Title::makeTitle( NS_SPECIAL, 'Confirmemail/' . $token );
1538 return $title->getFullUrl();
1539 }
1540
1541 /**
1542 * Mark the e-mail address confirmed and save.
1543 */
1544 function confirmEmail() {
1545 $this->loadFromDatabase();
1546 $this->mEmailAuthenticated = wfTimestampNow();
1547 $this->saveSettings();
1548 return true;
1549 }
1550
1551 /**
1552 * Is this user allowed to send e-mails within limits of current
1553 * site configuration?
1554 * @return bool
1555 */
1556 function canSendEmail() {
1557 return $this->isEmailConfirmed();
1558 }
1559
1560 /**
1561 * Is this user allowed to receive e-mails within limits of current
1562 * site configuration?
1563 * @return bool
1564 */
1565 function canReceiveEmail() {
1566 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1567 }
1568
1569 /**
1570 * Is this user's e-mail address valid-looking and confirmed within
1571 * limits of the current site configuration?
1572 *
1573 * If $wgEmailAuthentication is on, this may require the user to have
1574 * confirmed their address by returning a code or using a password
1575 * sent to the address from the wiki.
1576 *
1577 * @return bool
1578 */
1579 function isEmailConfirmed() {
1580 global $wgEmailAuthentication;
1581 $this->loadFromDatabase();
1582 if( $this->isAnon() )
1583 return false;
1584 if( !$this->isValidEmailAddr( $this->mEmail ) )
1585 return false;
1586 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
1587 return false;
1588 return true;
1589 }
1590
1591 /**
1592 * @param array $groups list of groups
1593 * @return array list of permission key names for given groups combined
1594 * @static
1595 */
1596 function getGroupPermissions( $groups ) {
1597 global $wgGroupPermissions;
1598 $rights = array();
1599 foreach( $groups as $group ) {
1600 if( isset( $wgGroupPermissions[$group] ) ) {
1601 $rights = array_merge( $rights, $wgGroupPermissions[$group] );
1602 }
1603 }
1604 return $rights;
1605 }
1606
1607 /**
1608 * @param string $group key name
1609 * @return string localized descriptive name, if provided
1610 * @static
1611 */
1612 function getGroupName( $group ) {
1613 $key = "group-$group-name";
1614 $name = wfMsg( $key );
1615 if( $name == '' || $name == "&lt;$key&gt;" ) {
1616 return $group;
1617 } else {
1618 return $name;
1619 }
1620 }
1621
1622 /**
1623 * Return the set of defined explicit groups.
1624 * The * and 'user' groups are not included.
1625 * @return array
1626 * @static
1627 */
1628 function getAllGroups() {
1629 global $wgGroupPermissions;
1630 return array_diff(
1631 array_keys( $wgGroupPermissions ),
1632 array( '*', 'user' ) );
1633 }
1634
1635 }
1636
1637 ?>