* Add some summaries for <table> elements
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * See user.txt
4 *
5 * @package MediaWiki
6 */
7
8 # Number of characters in user_token field
9 define( 'USER_TOKEN_LENGTH', 32 );
10
11 # Serialized record version
12 define( 'MW_USER_VERSION', 4 );
13
14 # Some punctuation to prevent editing from broken text-mangling proxies.
15 # FIXME: this is embedded unescaped into HTML attributes in various
16 # places, so we can't safely include ' or " even though we really should.
17 define( 'EDIT_TOKEN_SUFFIX', '\\' );
18
19 /**
20 *
21 * @package MediaWiki
22 */
23 class User {
24
25 /**
26 * A list of default user toggles, i.e. boolean user preferences that are
27 * displayed by Special:Preferences as checkboxes. This list can be
28 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
29 */
30 static public $mToggles = array(
31 'highlightbroken',
32 'justify',
33 'hideminor',
34 'extendwatchlist',
35 'usenewrc',
36 'numberheadings',
37 'showtoolbar',
38 'editondblclick',
39 'editsection',
40 'editsectiononrightclick',
41 'showtoc',
42 'rememberpassword',
43 'editwidth',
44 'watchcreations',
45 'watchdefault',
46 'minordefault',
47 'previewontop',
48 'previewonfirst',
49 'nocache',
50 'enotifwatchlistpages',
51 'enotifusertalkpages',
52 'enotifminoredits',
53 'enotifrevealaddr',
54 'shownumberswatching',
55 'fancysig',
56 'externaleditor',
57 'externaldiff',
58 'showjumplinks',
59 'uselivepreview',
60 'autopatrol',
61 'forceeditsummary',
62 'watchlisthideown',
63 'watchlisthidebots',
64 'ccmeonemails',
65 );
66
67 /**
68 * List of member variables which are saved to the shared cache (memcached).
69 * Any operation which changes the corresponding database fields must
70 * call a cache-clearing function.
71 */
72 static $mCacheVars = array(
73 # user table
74 'mId',
75 'mName',
76 'mRealName',
77 'mPassword',
78 'mNewpassword',
79 'mNewpassTime',
80 'mEmail',
81 'mOptions',
82 'mTouched',
83 'mToken',
84 'mEmailAuthenticated',
85 'mEmailToken',
86 'mEmailTokenExpires',
87 'mRegistration',
88
89 # user_group table
90 'mGroups',
91 );
92
93 /**
94 * The cache variable declarations
95 */
96 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
97 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
98 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
99
100 /**
101 * Whether the cache variables have been loaded
102 */
103 var $mDataLoaded;
104
105 /**
106 * Initialisation data source if mDataLoaded==false. May be one of:
107 * defaults anonymous user initialised from class defaults
108 * name initialise from mName
109 * id initialise from mId
110 * session log in from cookies or session if possible
111 *
112 * Use the User::newFrom*() family of functions to set this.
113 */
114 var $mFrom;
115
116 /**
117 * Lazy-initialised variables, invalidated with clearInstanceCache
118 */
119 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
120 $mBlockreason, $mBlock, $mEffectiveGroups;
121
122 /**
123 * Lightweight constructor for anonymous user
124 * Use the User::newFrom* factory functions for other kinds of users
125 */
126 function User() {
127 $this->clearInstanceCache( 'defaults' );
128 }
129
130 /**
131 * Load the user table data for this object from the source given by mFrom
132 */
133 function load() {
134 if ( $this->mDataLoaded ) {
135 return;
136 }
137 wfProfileIn( __METHOD__ );
138
139 # Set it now to avoid infinite recursion in accessors
140 $this->mDataLoaded = true;
141
142 switch ( $this->mFrom ) {
143 case 'defaults':
144 $this->loadDefaults();
145 break;
146 case 'name':
147 $this->mId = self::idFromName( $this->mName );
148 if ( !$this->mId ) {
149 # Nonexistent user placeholder object
150 $this->loadDefaults( $this->mName );
151 } else {
152 $this->loadFromId();
153 }
154 break;
155 case 'id':
156 $this->loadFromId();
157 break;
158 case 'session':
159 $this->loadFromSession();
160 break;
161 default:
162 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
163 }
164 wfProfileOut( __METHOD__ );
165 }
166
167 /**
168 * Load user table data given mId
169 * @return false if the ID does not exist, true otherwise
170 * @private
171 */
172 function loadFromId() {
173 global $wgMemc;
174 if ( $this->mId == 0 ) {
175 $this->loadDefaults();
176 return false;
177 }
178
179 # Try cache
180 $key = wfMemcKey( 'user', 'id', $this->mId );
181 $data = $wgMemc->get( $key );
182
183 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
184 # Object is expired, load from DB
185 $data = false;
186 }
187
188 if ( !$data ) {
189 wfDebug( "Cache miss for user {$this->mId}\n" );
190 # Load from DB
191 if ( !$this->loadFromDatabase() ) {
192 # Can't load from ID, user is anonymous
193 return false;
194 }
195
196 # Save to cache
197 $data = array();
198 foreach ( self::$mCacheVars as $name ) {
199 $data[$name] = $this->$name;
200 }
201 $data['mVersion'] = MW_USER_VERSION;
202 $wgMemc->set( $key, $data );
203 } else {
204 wfDebug( "Got user {$this->mId} from cache\n" );
205 # Restore from cache
206 foreach ( self::$mCacheVars as $name ) {
207 $this->$name = $data[$name];
208 }
209 }
210 return true;
211 }
212
213 /**
214 * Static factory method for creation from username.
215 *
216 * This is slightly less efficient than newFromId(), so use newFromId() if
217 * you have both an ID and a name handy.
218 *
219 * @param string $name Username, validated by Title:newFromText()
220 * @param mixed $validate Validate username. Takes the same parameters as
221 * User::getCanonicalName(), except that true is accepted as an alias
222 * for 'valid', for BC.
223 *
224 * @return User object, or null if the username is invalid. If the username
225 * is not present in the database, the result will be a user object with
226 * a name, zero user ID and default settings.
227 * @static
228 */
229 static function newFromName( $name, $validate = 'valid' ) {
230 if ( $validate === true ) {
231 $validate = 'valid';
232 }
233 $name = self::getCanonicalName( $name, $validate );
234 if ( $name === false ) {
235 return null;
236 } else {
237 # Create unloaded user object
238 $u = new User;
239 $u->mName = $name;
240 $u->mFrom = 'name';
241 return $u;
242 }
243 }
244
245 static function newFromId( $id ) {
246 $u = new User;
247 $u->mId = $id;
248 $u->mFrom = 'id';
249 return $u;
250 }
251
252 /**
253 * Factory method to fetch whichever user has a given email confirmation code.
254 * This code is generated when an account is created or its e-mail address
255 * has changed.
256 *
257 * If the code is invalid or has expired, returns NULL.
258 *
259 * @param string $code
260 * @return User
261 * @static
262 */
263 static function newFromConfirmationCode( $code ) {
264 $dbr =& wfGetDB( DB_SLAVE );
265 $id = $dbr->selectField( 'user', 'user_id', array(
266 'user_email_token' => md5( $code ),
267 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
268 ) );
269 if( $id !== false ) {
270 return User::newFromId( $id );
271 } else {
272 return null;
273 }
274 }
275
276 /**
277 * Create a new user object using data from session or cookies. If the
278 * login credentials are invalid, the result is an anonymous user.
279 *
280 * @return User
281 * @static
282 */
283 static function newFromSession() {
284 $user = new User;
285 $user->mFrom = 'session';
286 return $user;
287 }
288
289 /**
290 * Get username given an id.
291 * @param integer $id Database user id
292 * @return string Nickname of a user
293 * @static
294 */
295 static function whoIs( $id ) {
296 $dbr =& wfGetDB( DB_SLAVE );
297 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
298 }
299
300 /**
301 * Get real username given an id.
302 * @param integer $id Database user id
303 * @return string Realname of a user
304 * @static
305 */
306 static function whoIsReal( $id ) {
307 $dbr =& wfGetDB( DB_SLAVE );
308 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), 'User::whoIsReal' );
309 }
310
311 /**
312 * Get database id given a user name
313 * @param string $name Nickname of a user
314 * @return integer|null Database user id (null: if non existent
315 * @static
316 */
317 static function idFromName( $name ) {
318 $nt = Title::newFromText( $name );
319 if( is_null( $nt ) ) {
320 # Illegal name
321 return null;
322 }
323 $dbr =& wfGetDB( DB_SLAVE );
324 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
325
326 if ( $s === false ) {
327 return 0;
328 } else {
329 return $s->user_id;
330 }
331 }
332
333 /**
334 * Does the string match an anonymous IPv4 address?
335 *
336 * This function exists for username validation, in order to reject
337 * usernames which are similar in form to IP addresses. Strings such
338 * as 300.300.300.300 will return true because it looks like an IP
339 * address, despite not being strictly valid.
340 *
341 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
342 * address because the usemod software would "cloak" anonymous IP
343 * addresses like this, if we allowed accounts like this to be created
344 * new users could get the old edits of these anonymous users.
345 *
346 * @bug 3631
347 *
348 * @static
349 * @param string $name Nickname of a user
350 * @return bool
351 */
352 static function isIP( $name ) {
353 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name);
354 /*return preg_match("/^
355 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
356 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
357 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
358 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
359 $/x", $name);*/
360 }
361
362 /**
363 * Is the input a valid username?
364 *
365 * Checks if the input is a valid username, we don't want an empty string,
366 * an IP address, anything that containins slashes (would mess up subpages),
367 * is longer than the maximum allowed username size or doesn't begin with
368 * a capital letter.
369 *
370 * @param string $name
371 * @return bool
372 * @static
373 */
374 static function isValidUserName( $name ) {
375 global $wgContLang, $wgMaxNameChars;
376
377 if ( $name == ''
378 || User::isIP( $name )
379 || strpos( $name, '/' ) !== false
380 || strlen( $name ) > $wgMaxNameChars
381 || $name != $wgContLang->ucfirst( $name ) )
382 return false;
383
384 // Ensure that the name can't be misresolved as a different title,
385 // such as with extra namespace keys at the start.
386 $parsed = Title::newFromText( $name );
387 if( is_null( $parsed )
388 || $parsed->getNamespace()
389 || strcmp( $name, $parsed->getPrefixedText() ) )
390 return false;
391
392 // Check an additional blacklist of troublemaker characters.
393 // Should these be merged into the title char list?
394 $unicodeBlacklist = '/[' .
395 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
396 '\x{00a0}' . # non-breaking space
397 '\x{2000}-\x{200f}' . # various whitespace
398 '\x{2028}-\x{202f}' . # breaks and control chars
399 '\x{3000}' . # ideographic space
400 '\x{e000}-\x{f8ff}' . # private use
401 ']/u';
402 if( preg_match( $unicodeBlacklist, $name ) ) {
403 return false;
404 }
405
406 return true;
407 }
408
409 /**
410 * Usernames which fail to pass this function will be blocked
411 * from user login and new account registrations, but may be used
412 * internally by batch processes.
413 *
414 * If an account already exists in this form, login will be blocked
415 * by a failure to pass this function.
416 *
417 * @param string $name
418 * @return bool
419 */
420 static function isUsableName( $name ) {
421 global $wgReservedUsernames;
422 return
423 // Must be a usable username, obviously ;)
424 self::isValidUserName( $name ) &&
425
426 // Certain names may be reserved for batch processes.
427 !in_array( $name, $wgReservedUsernames );
428 }
429
430 /**
431 * Usernames which fail to pass this function will be blocked
432 * from new account registrations, but may be used internally
433 * either by batch processes or by user accounts which have
434 * already been created.
435 *
436 * Additional character blacklisting may be added here
437 * rather than in isValidUserName() to avoid disrupting
438 * existing accounts.
439 *
440 * @param string $name
441 * @return bool
442 */
443 static function isCreatableName( $name ) {
444 return
445 self::isUsableName( $name ) &&
446
447 // Registration-time character blacklisting...
448 strpos( $name, '@' ) === false;
449 }
450
451 /**
452 * Is the input a valid password?
453 *
454 * @param string $password
455 * @return bool
456 * @static
457 */
458 static function isValidPassword( $password ) {
459 global $wgMinimalPasswordLength;
460 return strlen( $password ) >= $wgMinimalPasswordLength;
461 }
462
463 /**
464 * Does the string match roughly an email address ?
465 *
466 * There used to be a regular expression here, it got removed because it
467 * rejected valid addresses. Actually just check if there is '@' somewhere
468 * in the given address.
469 *
470 * @todo Check for RFC 2822 compilance
471 * @bug 959
472 *
473 * @param string $addr email address
474 * @static
475 * @return bool
476 */
477 static function isValidEmailAddr ( $addr ) {
478 return ( trim( $addr ) != '' ) &&
479 (false !== strpos( $addr, '@' ) );
480 }
481
482 /**
483 * Given unvalidated user input, return a canonical username, or false if
484 * the username is invalid.
485 * @param string $name
486 * @param mixed $validate Type of validation to use:
487 * false No validation
488 * 'valid' Valid for batch processes
489 * 'usable' Valid for batch processes and login
490 * 'creatable' Valid for batch processes, login and account creation
491 */
492 static function getCanonicalName( $name, $validate = 'valid' ) {
493 # Force usernames to capital
494 global $wgContLang;
495 $name = $wgContLang->ucfirst( $name );
496
497 # Clean up name according to title rules
498 $t = Title::newFromText( $name );
499 if( is_null( $t ) ) {
500 return false;
501 }
502
503 # Reject various classes of invalid names
504 $name = $t->getText();
505 global $wgAuth;
506 $name = $wgAuth->getCanonicalName( $t->getText() );
507
508 switch ( $validate ) {
509 case false:
510 break;
511 case 'valid':
512 if ( !User::isValidUserName( $name ) ) {
513 $name = false;
514 }
515 break;
516 case 'usable':
517 if ( !User::isUsableName( $name ) ) {
518 $name = false;
519 }
520 break;
521 case 'creatable':
522 if ( !User::isCreatableName( $name ) ) {
523 $name = false;
524 }
525 break;
526 default:
527 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__ );
528 }
529 return $name;
530 }
531
532 /**
533 * Count the number of edits of a user
534 *
535 * @param int $uid The user ID to check
536 * @return int
537 * @static
538 */
539 static function edits( $uid ) {
540 $dbr =& wfGetDB( DB_SLAVE );
541 return $dbr->selectField(
542 'revision', 'count(*)',
543 array( 'rev_user' => $uid ),
544 __METHOD__
545 );
546 }
547
548 /**
549 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
550 * @todo: hash random numbers to improve security, like generateToken()
551 *
552 * @return string
553 * @static
554 */
555 static function randomPassword() {
556 global $wgMinimalPasswordLength;
557 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
558 $l = strlen( $pwchars ) - 1;
559
560 $pwlength = max( 7, $wgMinimalPasswordLength );
561 $digit = mt_rand(0, $pwlength - 1);
562 $np = '';
563 for ( $i = 0; $i < $pwlength; $i++ ) {
564 $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
565 }
566 return $np;
567 }
568
569 /**
570 * Set cached properties to default. Note: this no longer clears
571 * uncached lazy-initialised properties. The constructor does that instead.
572 *
573 * @private
574 */
575 function loadDefaults( $name = false ) {
576 wfProfileIn( __METHOD__ );
577
578 global $wgCookiePrefix;
579
580 $this->mId = 0;
581 $this->mName = $name;
582 $this->mRealName = '';
583 $this->mPassword = $this->mNewpassword = '';
584 $this->mNewpassTime = null;
585 $this->mEmail = '';
586 $this->mOptions = null; # Defer init
587
588 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
589 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
590 } else {
591 $this->mTouched = '0'; # Allow any pages to be cached
592 }
593
594 $this->setToken(); # Random
595 $this->mEmailAuthenticated = null;
596 $this->mEmailToken = '';
597 $this->mEmailTokenExpires = null;
598 $this->mRegistration = wfTimestamp( TS_MW );
599 $this->mGroups = array();
600
601 wfProfileOut( __METHOD__ );
602 }
603
604 /**
605 * Initialise php session
606 * @deprecated use wfSetupSession()
607 */
608 function SetupSession() {
609 wfSetupSession();
610 }
611
612 /**
613 * Load user data from the session or login cookie. If there are no valid
614 * credentials, initialises the user as an anon.
615 * @return true if the user is logged in, false otherwise
616 *
617 * @private
618 */
619 function loadFromSession() {
620 global $wgMemc, $wgCookiePrefix;
621
622 if ( isset( $_SESSION['wsUserID'] ) ) {
623 if ( 0 != $_SESSION['wsUserID'] ) {
624 $sId = $_SESSION['wsUserID'];
625 } else {
626 $this->loadDefaults();
627 return false;
628 }
629 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
630 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
631 $_SESSION['wsUserID'] = $sId;
632 } else {
633 $this->loadDefaults();
634 return false;
635 }
636 if ( isset( $_SESSION['wsUserName'] ) ) {
637 $sName = $_SESSION['wsUserName'];
638 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
639 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
640 $_SESSION['wsUserName'] = $sName;
641 } else {
642 $this->loadDefaults();
643 return false;
644 }
645
646 $passwordCorrect = FALSE;
647 $this->mId = $sId;
648 if ( !$this->loadFromId() ) {
649 # Not a valid ID, loadFromId has switched the object to anon for us
650 return false;
651 }
652
653 if ( isset( $_SESSION['wsToken'] ) ) {
654 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
655 $from = 'session';
656 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
657 $passwordCorrect = $this->mToken == $_COOKIE["{$wgCookiePrefix}Token"];
658 $from = 'cookie';
659 } else {
660 # No session or persistent login cookie
661 $this->loadDefaults();
662 return false;
663 }
664
665 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
666 wfDebug( "Logged in from $from\n" );
667 return true;
668 } else {
669 # Invalid credentials
670 wfDebug( "Can't log in from $from, invalid credentials\n" );
671 $this->loadDefaults();
672 return false;
673 }
674 }
675
676 /**
677 * Load user and user_group data from the database
678 * $this->mId must be set, this is how the user is identified.
679 *
680 * @return true if the user exists, false if the user is anonymous
681 * @private
682 */
683 function loadFromDatabase() {
684 # Paranoia
685 $this->mId = intval( $this->mId );
686
687 /** Anonymous user */
688 if( !$this->mId ) {
689 $this->loadDefaults();
690 return false;
691 }
692
693 $dbr =& wfGetDB( DB_SLAVE );
694 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
695
696 if ( $s !== false ) {
697 # Initialise user table data
698 $this->mName = $s->user_name;
699 $this->mRealName = $s->user_real_name;
700 $this->mPassword = $s->user_password;
701 $this->mNewpassword = $s->user_newpassword;
702 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $s->user_newpass_time );
703 $this->mEmail = $s->user_email;
704 $this->decodeOptions( $s->user_options );
705 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
706 $this->mToken = $s->user_token;
707 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
708 $this->mEmailToken = $s->user_email_token;
709 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $s->user_email_token_expires );
710 $this->mRegistration = wfTimestampOrNull( TS_MW, $s->user_registration );
711
712 # Load group data
713 $res = $dbr->select( 'user_groups',
714 array( 'ug_group' ),
715 array( 'ug_user' => $this->mId ),
716 __METHOD__ );
717 $this->mGroups = array();
718 while( $row = $dbr->fetchObject( $res ) ) {
719 $this->mGroups[] = $row->ug_group;
720 }
721 return true;
722 } else {
723 # Invalid user_id
724 $this->mId = 0;
725 $this->loadDefaults();
726 return false;
727 }
728 }
729
730 /**
731 * Clear various cached data stored in this object.
732 * @param string $reloadFrom Reload user and user_groups table data from a
733 * given source. May be "name", "id", "defaults", "session" or false for
734 * no reload.
735 */
736 function clearInstanceCache( $reloadFrom = false ) {
737 $this->mNewtalk = -1;
738 $this->mDatePreference = null;
739 $this->mBlockedby = -1; # Unset
740 $this->mHash = false;
741 $this->mSkin = null;
742 $this->mRights = null;
743 $this->mEffectiveGroups = null;
744
745 if ( $reloadFrom ) {
746 $this->mDataLoaded = false;
747 $this->mFrom = $reloadFrom;
748 }
749 }
750
751 /**
752 * Combine the language default options with any site-specific options
753 * and add the default language variants.
754 *
755 * @return array
756 * @static
757 * @private
758 */
759 function getDefaultOptions() {
760 global $wgNamespacesToBeSearchedDefault;
761 /**
762 * Site defaults will override the global/language defaults
763 */
764 global $wgDefaultUserOptions, $wgContLang;
765 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
766
767 /**
768 * default language setting
769 */
770 $variant = $wgContLang->getPreferredVariant( false );
771 $defOpt['variant'] = $variant;
772 $defOpt['language'] = $variant;
773
774 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
775 $defOpt['searchNs'.$nsnum] = $val;
776 }
777 return $defOpt;
778 }
779
780 /**
781 * Get a given default option value.
782 *
783 * @param string $opt
784 * @return string
785 * @static
786 * @public
787 */
788 function getDefaultOption( $opt ) {
789 $defOpts = User::getDefaultOptions();
790 if( isset( $defOpts[$opt] ) ) {
791 return $defOpts[$opt];
792 } else {
793 return '';
794 }
795 }
796
797 /**
798 * Get a list of user toggle names
799 * @return array
800 */
801 static function getToggles() {
802 global $wgContLang;
803 $extraToggles = array();
804 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
805 return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
806 }
807
808
809 /**
810 * Get blocking information
811 * @private
812 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
813 * non-critical checks are done against slaves. Check when actually saving should be done against
814 * master.
815 */
816 function getBlockedStatus( $bFromSlave = true ) {
817 global $wgEnableSorbs, $wgProxyWhitelist;
818
819 if ( -1 != $this->mBlockedby ) {
820 wfDebug( "User::getBlockedStatus: already loaded.\n" );
821 return;
822 }
823
824 wfProfileIn( __METHOD__ );
825 wfDebug( __METHOD__.": checking...\n" );
826
827 $this->mBlockedby = 0;
828 $ip = wfGetIP();
829
830 # User/IP blocking
831 $this->mBlock = new Block();
832 $this->mBlock->fromMaster( !$bFromSlave );
833 if ( $this->mBlock->load( $ip , $this->mId ) ) {
834 wfDebug( __METHOD__.": Found block.\n" );
835 $this->mBlockedby = $this->mBlock->mBy;
836 $this->mBlockreason = $this->mBlock->mReason;
837 if ( $this->isLoggedIn() ) {
838 $this->spreadBlock();
839 }
840 } else {
841 $this->mBlock = null;
842 wfDebug( __METHOD__.": No block.\n" );
843 }
844
845 # Proxy blocking
846 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
847
848 # Local list
849 if ( wfIsLocallyBlockedProxy( $ip ) ) {
850 $this->mBlockedby = wfMsg( 'proxyblocker' );
851 $this->mBlockreason = wfMsg( 'proxyblockreason' );
852 }
853
854 # DNSBL
855 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
856 if ( $this->inSorbsBlacklist( $ip ) ) {
857 $this->mBlockedby = wfMsg( 'sorbs' );
858 $this->mBlockreason = wfMsg( 'sorbsreason' );
859 }
860 }
861 }
862
863 # Extensions
864 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
865
866 wfProfileOut( __METHOD__ );
867 }
868
869 function inSorbsBlacklist( $ip ) {
870 global $wgEnableSorbs, $wgSorbsUrl;
871
872 return $wgEnableSorbs &&
873 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
874 }
875
876 function inDnsBlacklist( $ip, $base ) {
877 wfProfileIn( __METHOD__ );
878
879 $found = false;
880 $host = '';
881
882 $m = array();
883 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
884 # Make hostname
885 for ( $i=4; $i>=1; $i-- ) {
886 $host .= $m[$i] . '.';
887 }
888 $host .= $base;
889
890 # Send query
891 $ipList = gethostbynamel( $host );
892
893 if ( $ipList ) {
894 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
895 $found = true;
896 } else {
897 wfDebug( "Requested $host, not found in $base.\n" );
898 }
899 }
900
901 wfProfileOut( __METHOD__ );
902 return $found;
903 }
904
905 /**
906 * Primitive rate limits: enforce maximum actions per time period
907 * to put a brake on flooding.
908 *
909 * Note: when using a shared cache like memcached, IP-address
910 * last-hit counters will be shared across wikis.
911 *
912 * @return bool true if a rate limiter was tripped
913 * @public
914 */
915 function pingLimiter( $action='edit' ) {
916 global $wgRateLimits, $wgRateLimitsExcludedGroups;
917 if( !isset( $wgRateLimits[$action] ) ) {
918 return false;
919 }
920
921 # Some groups shouldn't trigger the ping limiter, ever
922 foreach( $this->getGroups() as $group ) {
923 if( array_search( $group, $wgRateLimitsExcludedGroups ) !== false )
924 return false;
925 }
926
927 global $wgMemc, $wgRateLimitLog;
928 wfProfileIn( __METHOD__ );
929
930 $limits = $wgRateLimits[$action];
931 $keys = array();
932 $id = $this->getId();
933 $ip = wfGetIP();
934
935 if( isset( $limits['anon'] ) && $id == 0 ) {
936 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
937 }
938
939 if( isset( $limits['user'] ) && $id != 0 ) {
940 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
941 }
942 if( $this->isNewbie() ) {
943 if( isset( $limits['newbie'] ) && $id != 0 ) {
944 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
945 }
946 if( isset( $limits['ip'] ) ) {
947 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
948 }
949 $matches = array();
950 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
951 $subnet = $matches[1];
952 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
953 }
954 }
955
956 $triggered = false;
957 foreach( $keys as $key => $limit ) {
958 list( $max, $period ) = $limit;
959 $summary = "(limit $max in {$period}s)";
960 $count = $wgMemc->get( $key );
961 if( $count ) {
962 if( $count > $max ) {
963 wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
964 if( $wgRateLimitLog ) {
965 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
966 }
967 $triggered = true;
968 } else {
969 wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
970 }
971 } else {
972 wfDebug( __METHOD__.": adding record for $key $summary\n" );
973 $wgMemc->add( $key, 1, intval( $period ) );
974 }
975 $wgMemc->incr( $key );
976 }
977
978 wfProfileOut( __METHOD__ );
979 return $triggered;
980 }
981
982 /**
983 * Check if user is blocked
984 * @return bool True if blocked, false otherwise
985 */
986 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
987 wfDebug( "User::isBlocked: enter\n" );
988 $this->getBlockedStatus( $bFromSlave );
989 return $this->mBlockedby !== 0;
990 }
991
992 /**
993 * Check if user is blocked from editing a particular article
994 */
995 function isBlockedFrom( $title, $bFromSlave = false ) {
996 global $wgBlockAllowsUTEdit;
997 wfProfileIn( __METHOD__ );
998 wfDebug( __METHOD__.": enter\n" );
999
1000 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1001 $title->getNamespace() == NS_USER_TALK )
1002 {
1003 $blocked = false;
1004 wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1005 } else {
1006 wfDebug( __METHOD__.": asking isBlocked()\n" );
1007 $blocked = $this->isBlocked( $bFromSlave );
1008 }
1009 wfProfileOut( __METHOD__ );
1010 return $blocked;
1011 }
1012
1013 /**
1014 * Get name of blocker
1015 * @return string name of blocker
1016 */
1017 function blockedBy() {
1018 $this->getBlockedStatus();
1019 return $this->mBlockedby;
1020 }
1021
1022 /**
1023 * Get blocking reason
1024 * @return string Blocking reason
1025 */
1026 function blockedFor() {
1027 $this->getBlockedStatus();
1028 return $this->mBlockreason;
1029 }
1030
1031 /**
1032 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1033 */
1034 function getID() {
1035 $this->load();
1036 return $this->mId;
1037 }
1038
1039 /**
1040 * Set the user and reload all fields according to that ID
1041 * @deprecated use User::newFromId()
1042 */
1043 function setID( $v ) {
1044 $this->mId = $v;
1045 $this->clearInstanceCache( 'id' );
1046 }
1047
1048 /**
1049 * Get the user name, or the IP for anons
1050 */
1051 function getName() {
1052 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1053 # Special case optimisation
1054 return $this->mName;
1055 } else {
1056 $this->load();
1057 if ( $this->mName === false ) {
1058 $this->mName = wfGetIP();
1059 }
1060 return $this->mName;
1061 }
1062 }
1063
1064 /**
1065 * Set the user name.
1066 *
1067 * This does not reload fields from the database according to the given
1068 * name. Rather, it is used to create a temporary "nonexistent user" for
1069 * later addition to the database. It can also be used to set the IP
1070 * address for an anonymous user to something other than the current
1071 * remote IP.
1072 *
1073 * User::newFromName() has rougly the same function, when the named user
1074 * does not exist.
1075 */
1076 function setName( $str ) {
1077 $this->load();
1078 $this->mName = $str;
1079 }
1080
1081 /**
1082 * Return the title dbkey form of the name, for eg user pages.
1083 * @return string
1084 * @public
1085 */
1086 function getTitleKey() {
1087 return str_replace( ' ', '_', $this->getName() );
1088 }
1089
1090 function getNewtalk() {
1091 $this->load();
1092
1093 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1094 if( $this->mNewtalk === -1 ) {
1095 $this->mNewtalk = false; # reset talk page status
1096
1097 # Check memcached separately for anons, who have no
1098 # entire User object stored in there.
1099 if( !$this->mId ) {
1100 global $wgMemc;
1101 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1102 $newtalk = $wgMemc->get( $key );
1103 if( is_integer( $newtalk ) ) {
1104 $this->mNewtalk = (bool)$newtalk;
1105 } else {
1106 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
1107 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
1108 }
1109 } else {
1110 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1111 }
1112 }
1113
1114 return (bool)$this->mNewtalk;
1115 }
1116
1117 /**
1118 * Return the talk page(s) this user has new messages on.
1119 */
1120 function getNewMessageLinks() {
1121 $talks = array();
1122 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1123 return $talks;
1124
1125 if (!$this->getNewtalk())
1126 return array();
1127 $up = $this->getUserPage();
1128 $utp = $up->getTalkPage();
1129 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1130 }
1131
1132
1133 /**
1134 * Perform a user_newtalk check on current slaves; if the memcached data
1135 * is funky we don't want newtalk state to get stuck on save, as that's
1136 * damn annoying.
1137 *
1138 * @param string $field
1139 * @param mixed $id
1140 * @return bool
1141 * @private
1142 */
1143 function checkNewtalk( $field, $id ) {
1144 $dbr =& wfGetDB( DB_SLAVE );
1145 $ok = $dbr->selectField( 'user_newtalk', $field,
1146 array( $field => $id ), __METHOD__ );
1147 return $ok !== false;
1148 }
1149
1150 /**
1151 * Add or update the
1152 * @param string $field
1153 * @param mixed $id
1154 * @private
1155 */
1156 function updateNewtalk( $field, $id ) {
1157 if( $this->checkNewtalk( $field, $id ) ) {
1158 wfDebug( __METHOD__." already set ($field, $id), ignoring\n" );
1159 return false;
1160 }
1161 $dbw =& wfGetDB( DB_MASTER );
1162 $dbw->insert( 'user_newtalk',
1163 array( $field => $id ),
1164 __METHOD__,
1165 'IGNORE' );
1166 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1167 return true;
1168 }
1169
1170 /**
1171 * Clear the new messages flag for the given user
1172 * @param string $field
1173 * @param mixed $id
1174 * @private
1175 */
1176 function deleteNewtalk( $field, $id ) {
1177 if( !$this->checkNewtalk( $field, $id ) ) {
1178 wfDebug( __METHOD__.": already gone ($field, $id), ignoring\n" );
1179 return false;
1180 }
1181 $dbw =& wfGetDB( DB_MASTER );
1182 $dbw->delete( 'user_newtalk',
1183 array( $field => $id ),
1184 __METHOD__ );
1185 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1186 return true;
1187 }
1188
1189 /**
1190 * Update the 'You have new messages!' status.
1191 * @param bool $val
1192 */
1193 function setNewtalk( $val ) {
1194 if( wfReadOnly() ) {
1195 return;
1196 }
1197
1198 $this->load();
1199 $this->mNewtalk = $val;
1200
1201 if( $this->isAnon() ) {
1202 $field = 'user_ip';
1203 $id = $this->getName();
1204 } else {
1205 $field = 'user_id';
1206 $id = $this->getId();
1207 }
1208
1209 if( $val ) {
1210 $changed = $this->updateNewtalk( $field, $id );
1211 } else {
1212 $changed = $this->deleteNewtalk( $field, $id );
1213 }
1214
1215 if( $changed ) {
1216 if( $this->isAnon() ) {
1217 // Anons have a separate memcached space, since
1218 // user records aren't kept for them.
1219 global $wgMemc;
1220 $key = wfMemcKey( 'newtalk', 'ip', $val );
1221 $wgMemc->set( $key, $val ? 1 : 0 );
1222 } else {
1223 if( $val ) {
1224 // Make sure the user page is watched, so a notification
1225 // will be sent out if enabled.
1226 $this->addWatch( $this->getTalkPage() );
1227 }
1228 }
1229 $this->invalidateCache();
1230 }
1231 }
1232
1233 /**
1234 * Generate a current or new-future timestamp to be stored in the
1235 * user_touched field when we update things.
1236 */
1237 private static function newTouchedTimestamp() {
1238 global $wgClockSkewFudge;
1239 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1240 }
1241
1242 /**
1243 * Clear user data from memcached.
1244 * Use after applying fun updates to the database; caller's
1245 * responsibility to update user_touched if appropriate.
1246 *
1247 * Called implicitly from invalidateCache() and saveSettings().
1248 */
1249 private function clearSharedCache() {
1250 if( $this->mId ) {
1251 global $wgMemc;
1252 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1253 }
1254 }
1255
1256 /**
1257 * Immediately touch the user data cache for this account.
1258 * Updates user_touched field, and removes account data from memcached
1259 * for reload on the next hit.
1260 */
1261 function invalidateCache() {
1262 $this->load();
1263 if( $this->mId ) {
1264 $this->mTouched = self::newTouchedTimestamp();
1265
1266 $dbw =& wfGetDB( DB_MASTER );
1267 $dbw->update( 'user',
1268 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1269 array( 'user_id' => $this->mId ),
1270 __METHOD__ );
1271
1272 $this->clearSharedCache();
1273 }
1274 }
1275
1276 function validateCache( $timestamp ) {
1277 $this->load();
1278 return ($timestamp >= $this->mTouched);
1279 }
1280
1281 /**
1282 * Encrypt a password.
1283 * It can eventuall salt a password @see User::addSalt()
1284 * @param string $p clear Password.
1285 * @return string Encrypted password.
1286 */
1287 function encryptPassword( $p ) {
1288 $this->load();
1289 return wfEncryptPassword( $this->mId, $p );
1290 }
1291
1292 /**
1293 * Set the password and reset the random token
1294 */
1295 function setPassword( $str ) {
1296 $this->load();
1297 $this->setToken();
1298 $this->mPassword = $this->encryptPassword( $str );
1299 $this->mNewpassword = '';
1300 $this->mNewpassTime = NULL;
1301 }
1302
1303 /**
1304 * Set the random token (used for persistent authentication)
1305 * Called from loadDefaults() among other places.
1306 * @private
1307 */
1308 function setToken( $token = false ) {
1309 global $wgSecretKey, $wgProxyKey;
1310 $this->load();
1311 if ( !$token ) {
1312 if ( $wgSecretKey ) {
1313 $key = $wgSecretKey;
1314 } elseif ( $wgProxyKey ) {
1315 $key = $wgProxyKey;
1316 } else {
1317 $key = microtime();
1318 }
1319 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1320 } else {
1321 $this->mToken = $token;
1322 }
1323 }
1324
1325 function setCookiePassword( $str ) {
1326 $this->load();
1327 $this->mCookiePassword = md5( $str );
1328 }
1329
1330 /**
1331 * Set the password for a password reminder or new account email
1332 * Sets the user_newpass_time field if $throttle is true
1333 */
1334 function setNewpassword( $str, $throttle = true ) {
1335 $this->load();
1336 $this->mNewpassword = $this->encryptPassword( $str );
1337 if ( $throttle ) {
1338 $this->mNewpassTime = wfTimestampNow();
1339 }
1340 }
1341
1342 /**
1343 * Returns true if a password reminder email has already been sent within
1344 * the last $wgPasswordReminderResendTime hours
1345 */
1346 function isPasswordReminderThrottled() {
1347 global $wgPasswordReminderResendTime;
1348 $this->load();
1349 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1350 return false;
1351 }
1352 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1353 return time() < $expiry;
1354 }
1355
1356 function getEmail() {
1357 $this->load();
1358 return $this->mEmail;
1359 }
1360
1361 function getEmailAuthenticationTimestamp() {
1362 $this->load();
1363 return $this->mEmailAuthenticated;
1364 }
1365
1366 function setEmail( $str ) {
1367 $this->load();
1368 $this->mEmail = $str;
1369 }
1370
1371 function getRealName() {
1372 $this->load();
1373 return $this->mRealName;
1374 }
1375
1376 function setRealName( $str ) {
1377 $this->load();
1378 $this->mRealName = $str;
1379 }
1380
1381 /**
1382 * @param string $oname The option to check
1383 * @return string
1384 */
1385 function getOption( $oname ) {
1386 $this->load();
1387 if ( is_null( $this->mOptions ) ) {
1388 $this->mOptions = User::getDefaultOptions();
1389 }
1390 if ( array_key_exists( $oname, $this->mOptions ) ) {
1391 return trim( $this->mOptions[$oname] );
1392 } else {
1393 return '';
1394 }
1395 }
1396
1397 /**
1398 * Get the user's date preference, including some important migration for
1399 * old user rows.
1400 */
1401 function getDatePreference() {
1402 if ( is_null( $this->mDatePreference ) ) {
1403 global $wgLang;
1404 $value = $this->getOption( 'date' );
1405 $map = $wgLang->getDatePreferenceMigrationMap();
1406 if ( isset( $map[$value] ) ) {
1407 $value = $map[$value];
1408 }
1409 $this->mDatePreference = $value;
1410 }
1411 return $this->mDatePreference;
1412 }
1413
1414 /**
1415 * @param string $oname The option to check
1416 * @return bool False if the option is not selected, true if it is
1417 */
1418 function getBoolOption( $oname ) {
1419 return (bool)$this->getOption( $oname );
1420 }
1421
1422 /**
1423 * Get an option as an integer value from the source string.
1424 * @param string $oname The option to check
1425 * @param int $default Optional value to return if option is unset/blank.
1426 * @return int
1427 */
1428 function getIntOption( $oname, $default=0 ) {
1429 $val = $this->getOption( $oname );
1430 if( $val == '' ) {
1431 $val = $default;
1432 }
1433 return intval( $val );
1434 }
1435
1436 function setOption( $oname, $val ) {
1437 $this->load();
1438 if ( is_null( $this->mOptions ) ) {
1439 $this->mOptions = User::getDefaultOptions();
1440 }
1441 if ( $oname == 'skin' ) {
1442 # Clear cached skin, so the new one displays immediately in Special:Preferences
1443 unset( $this->mSkin );
1444 }
1445 // Filter out any newlines that may have passed through input validation.
1446 // Newlines are used to separate items in the options blob.
1447 $val = str_replace( "\r\n", "\n", $val );
1448 $val = str_replace( "\r", "\n", $val );
1449 $val = str_replace( "\n", " ", $val );
1450 $this->mOptions[$oname] = $val;
1451 }
1452
1453 function getRights() {
1454 if ( is_null( $this->mRights ) ) {
1455 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1456 }
1457 return $this->mRights;
1458 }
1459
1460 /**
1461 * Get the list of explicit group memberships this user has.
1462 * The implicit * and user groups are not included.
1463 * @return array of strings
1464 */
1465 function getGroups() {
1466 $this->load();
1467 return $this->mGroups;
1468 }
1469
1470 /**
1471 * Get the list of implicit group memberships this user has.
1472 * This includes all explicit groups, plus 'user' if logged in
1473 * and '*' for all accounts.
1474 * @param boolean $recache Don't use the cache
1475 * @return array of strings
1476 */
1477 function getEffectiveGroups( $recache = false ) {
1478 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1479 $this->load();
1480 $this->mEffectiveGroups = $this->mGroups;
1481 $this->mEffectiveGroups[] = '*';
1482 if( $this->mId ) {
1483 $this->mEffectiveGroups[] = 'user';
1484
1485 global $wgAutoConfirmAge;
1486 $accountAge = time() - wfTimestampOrNull( TS_UNIX, $this->mRegistration );
1487 if( $accountAge >= $wgAutoConfirmAge ) {
1488 $this->mEffectiveGroups[] = 'autoconfirmed';
1489 }
1490
1491 # Implicit group for users whose email addresses are confirmed
1492 global $wgEmailAuthentication;
1493 if( self::isValidEmailAddr( $this->mEmail ) ) {
1494 if( $wgEmailAuthentication ) {
1495 if( $this->mEmailAuthenticated )
1496 $this->mEffectiveGroups[] = 'emailconfirmed';
1497 } else {
1498 $this->mEffectiveGroups[] = 'emailconfirmed';
1499 }
1500 }
1501 }
1502 }
1503 return $this->mEffectiveGroups;
1504 }
1505
1506 /**
1507 * Add the user to the given group.
1508 * This takes immediate effect.
1509 * @string $group
1510 */
1511 function addGroup( $group ) {
1512 $this->load();
1513 $dbw =& wfGetDB( DB_MASTER );
1514 $dbw->insert( 'user_groups',
1515 array(
1516 'ug_user' => $this->getID(),
1517 'ug_group' => $group,
1518 ),
1519 'User::addGroup',
1520 array( 'IGNORE' ) );
1521
1522 $this->mGroups[] = $group;
1523 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1524
1525 $this->invalidateCache();
1526 }
1527
1528 /**
1529 * Remove the user from the given group.
1530 * This takes immediate effect.
1531 * @string $group
1532 */
1533 function removeGroup( $group ) {
1534 $this->load();
1535 $dbw =& wfGetDB( DB_MASTER );
1536 $dbw->delete( 'user_groups',
1537 array(
1538 'ug_user' => $this->getID(),
1539 'ug_group' => $group,
1540 ),
1541 'User::removeGroup' );
1542
1543 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
1544 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1545
1546 $this->invalidateCache();
1547 }
1548
1549
1550 /**
1551 * A more legible check for non-anonymousness.
1552 * Returns true if the user is not an anonymous visitor.
1553 *
1554 * @return bool
1555 */
1556 function isLoggedIn() {
1557 return( $this->getID() != 0 );
1558 }
1559
1560 /**
1561 * A more legible check for anonymousness.
1562 * Returns true if the user is an anonymous visitor.
1563 *
1564 * @return bool
1565 */
1566 function isAnon() {
1567 return !$this->isLoggedIn();
1568 }
1569
1570 /**
1571 * Whether the user is a bot
1572 * @deprecated
1573 */
1574 function isBot() {
1575 return $this->isAllowed( 'bot' );
1576 }
1577
1578 /**
1579 * Check if user is allowed to access a feature / make an action
1580 * @param string $action Action to be checked
1581 * @return boolean True: action is allowed, False: action should not be allowed
1582 */
1583 function isAllowed($action='') {
1584 if ( $action === '' )
1585 // In the spirit of DWIM
1586 return true;
1587
1588 return in_array( $action, $this->getRights() );
1589 }
1590
1591 /**
1592 * Load a skin if it doesn't exist or return it
1593 * @todo FIXME : need to check the old failback system [AV]
1594 */
1595 function &getSkin() {
1596 global $wgRequest;
1597 if ( ! isset( $this->mSkin ) ) {
1598 wfProfileIn( __METHOD__ );
1599
1600 # get the user skin
1601 $userSkin = $this->getOption( 'skin' );
1602 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1603
1604 $this->mSkin =& Skin::newFromKey( $userSkin );
1605 wfProfileOut( __METHOD__ );
1606 }
1607 return $this->mSkin;
1608 }
1609
1610 /**#@+
1611 * @param string $title Article title to look at
1612 */
1613
1614 /**
1615 * Check watched status of an article
1616 * @return bool True if article is watched
1617 */
1618 function isWatched( $title ) {
1619 $wl = WatchedItem::fromUserTitle( $this, $title );
1620 return $wl->isWatched();
1621 }
1622
1623 /**
1624 * Watch an article
1625 */
1626 function addWatch( $title ) {
1627 $wl = WatchedItem::fromUserTitle( $this, $title );
1628 $wl->addWatch();
1629 $this->invalidateCache();
1630 }
1631
1632 /**
1633 * Stop watching an article
1634 */
1635 function removeWatch( $title ) {
1636 $wl = WatchedItem::fromUserTitle( $this, $title );
1637 $wl->removeWatch();
1638 $this->invalidateCache();
1639 }
1640
1641 /**
1642 * Clear the user's notification timestamp for the given title.
1643 * If e-notif e-mails are on, they will receive notification mails on
1644 * the next change of the page if it's watched etc.
1645 */
1646 function clearNotification( &$title ) {
1647 global $wgUser, $wgUseEnotif;
1648
1649 if ($title->getNamespace() == NS_USER_TALK &&
1650 $title->getText() == $this->getName() ) {
1651 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1652 return;
1653 $this->setNewtalk( false );
1654 }
1655
1656 if( !$wgUseEnotif ) {
1657 return;
1658 }
1659
1660 if( $this->isAnon() ) {
1661 // Nothing else to do...
1662 return;
1663 }
1664
1665 // Only update the timestamp if the page is being watched.
1666 // The query to find out if it is watched is cached both in memcached and per-invocation,
1667 // and when it does have to be executed, it can be on a slave
1668 // If this is the user's newtalk page, we always update the timestamp
1669 if ($title->getNamespace() == NS_USER_TALK &&
1670 $title->getText() == $wgUser->getName())
1671 {
1672 $watched = true;
1673 } elseif ( $this->getID() == $wgUser->getID() ) {
1674 $watched = $title->userIsWatching();
1675 } else {
1676 $watched = true;
1677 }
1678
1679 // If the page is watched by the user (or may be watched), update the timestamp on any
1680 // any matching rows
1681 if ( $watched ) {
1682 $dbw =& wfGetDB( DB_MASTER );
1683 $dbw->update( 'watchlist',
1684 array( /* SET */
1685 'wl_notificationtimestamp' => NULL
1686 ), array( /* WHERE */
1687 'wl_title' => $title->getDBkey(),
1688 'wl_namespace' => $title->getNamespace(),
1689 'wl_user' => $this->getID()
1690 ), 'User::clearLastVisited'
1691 );
1692 }
1693 }
1694
1695 /**#@-*/
1696
1697 /**
1698 * Resets all of the given user's page-change notification timestamps.
1699 * If e-notif e-mails are on, they will receive notification mails on
1700 * the next change of any watched page.
1701 *
1702 * @param int $currentUser user ID number
1703 * @public
1704 */
1705 function clearAllNotifications( $currentUser ) {
1706 global $wgUseEnotif;
1707 if ( !$wgUseEnotif ) {
1708 $this->setNewtalk( false );
1709 return;
1710 }
1711 if( $currentUser != 0 ) {
1712
1713 $dbw =& wfGetDB( DB_MASTER );
1714 $dbw->update( 'watchlist',
1715 array( /* SET */
1716 'wl_notificationtimestamp' => NULL
1717 ), array( /* WHERE */
1718 'wl_user' => $currentUser
1719 ), 'UserMailer::clearAll'
1720 );
1721
1722 # we also need to clear here the "you have new message" notification for the own user_talk page
1723 # This is cleared one page view later in Article::viewUpdates();
1724 }
1725 }
1726
1727 /**
1728 * @private
1729 * @return string Encoding options
1730 */
1731 function encodeOptions() {
1732 $this->load();
1733 if ( is_null( $this->mOptions ) ) {
1734 $this->mOptions = User::getDefaultOptions();
1735 }
1736 $a = array();
1737 foreach ( $this->mOptions as $oname => $oval ) {
1738 array_push( $a, $oname.'='.$oval );
1739 }
1740 $s = implode( "\n", $a );
1741 return $s;
1742 }
1743
1744 /**
1745 * @private
1746 */
1747 function decodeOptions( $str ) {
1748 $this->mOptions = array();
1749 $a = explode( "\n", $str );
1750 foreach ( $a as $s ) {
1751 $m = array();
1752 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1753 $this->mOptions[$m[1]] = $m[2];
1754 }
1755 }
1756 }
1757
1758 function setCookies() {
1759 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1760 $this->load();
1761 if ( 0 == $this->mId ) return;
1762 $exp = time() + $wgCookieExpiration;
1763
1764 $_SESSION['wsUserID'] = $this->mId;
1765 setcookie( $wgCookiePrefix.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1766
1767 $_SESSION['wsUserName'] = $this->getName();
1768 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1769
1770 $_SESSION['wsToken'] = $this->mToken;
1771 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1772 setcookie( $wgCookiePrefix.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1773 } else {
1774 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1775 }
1776 }
1777
1778 /**
1779 * Logout user
1780 * Clears the cookies and session, resets the instance cache
1781 */
1782 function logout() {
1783 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1784 $this->clearInstanceCache( 'defaults' );
1785
1786 $_SESSION['wsUserID'] = 0;
1787
1788 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1789 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1790
1791 # Remember when user logged out, to prevent seeing cached pages
1792 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1793 }
1794
1795 /**
1796 * Save object settings into database
1797 * @fixme Only rarely do all these fields need to be set!
1798 */
1799 function saveSettings() {
1800 $this->load();
1801 if ( wfReadOnly() ) { return; }
1802 if ( 0 == $this->mId ) { return; }
1803
1804 $this->mTouched = self::newTouchedTimestamp();
1805
1806 $dbw =& wfGetDB( DB_MASTER );
1807 $dbw->update( 'user',
1808 array( /* SET */
1809 'user_name' => $this->mName,
1810 'user_password' => $this->mPassword,
1811 'user_newpassword' => $this->mNewpassword,
1812 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
1813 'user_real_name' => $this->mRealName,
1814 'user_email' => $this->mEmail,
1815 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1816 'user_options' => $this->encodeOptions(),
1817 'user_touched' => $dbw->timestamp($this->mTouched),
1818 'user_token' => $this->mToken
1819 ), array( /* WHERE */
1820 'user_id' => $this->mId
1821 ), __METHOD__
1822 );
1823 $this->clearSharedCache();
1824 }
1825
1826
1827 /**
1828 * Checks if a user with the given name exists, returns the ID
1829 */
1830 function idForName() {
1831 $s = trim( $this->getName() );
1832 if ( 0 == strcmp( '', $s ) ) return 0;
1833
1834 $dbr =& wfGetDB( DB_SLAVE );
1835 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
1836 if ( $id === false ) {
1837 $id = 0;
1838 }
1839 return $id;
1840 }
1841
1842 /**
1843 * Add a user to the database, return the user object
1844 *
1845 * @param string $name The user's name
1846 * @param array $params Associative array of non-default parameters to save to the database:
1847 * password The user's password. Password logins will be disabled if this is omitted.
1848 * newpassword A temporary password mailed to the user
1849 * email The user's email address
1850 * email_authenticated The email authentication timestamp
1851 * real_name The user's real name
1852 * options An associative array of non-default options
1853 * token Random authentication token. Do not set.
1854 * registration Registration timestamp. Do not set.
1855 *
1856 * @return User object, or null if the username already exists
1857 */
1858 static function createNew( $name, $params = array() ) {
1859 $user = new User;
1860 $user->load();
1861 if ( isset( $params['options'] ) ) {
1862 $user->mOptions = $params['options'] + $user->mOptions;
1863 unset( $params['options'] );
1864 }
1865 $dbw =& wfGetDB( DB_MASTER );
1866 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1867 $fields = array(
1868 'user_id' => $seqVal,
1869 'user_name' => $name,
1870 'user_password' => $user->mPassword,
1871 'user_newpassword' => $user->mNewpassword,
1872 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
1873 'user_email' => $user->mEmail,
1874 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
1875 'user_real_name' => $user->mRealName,
1876 'user_options' => $user->encodeOptions(),
1877 'user_token' => $user->mToken,
1878 'user_registration' => $dbw->timestamp( $user->mRegistration ),
1879 );
1880 foreach ( $params as $name => $value ) {
1881 $fields["user_$name"] = $value;
1882 }
1883 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
1884 if ( $dbw->affectedRows() ) {
1885 $newUser = User::newFromId( $dbw->insertId() );
1886 } else {
1887 $newUser = null;
1888 }
1889 return $newUser;
1890 }
1891
1892 /**
1893 * Add an existing user object to the database
1894 */
1895 function addToDatabase() {
1896 $this->load();
1897 $dbw =& wfGetDB( DB_MASTER );
1898 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1899 $dbw->insert( 'user',
1900 array(
1901 'user_id' => $seqVal,
1902 'user_name' => $this->mName,
1903 'user_password' => $this->mPassword,
1904 'user_newpassword' => $this->mNewpassword,
1905 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
1906 'user_email' => $this->mEmail,
1907 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1908 'user_real_name' => $this->mRealName,
1909 'user_options' => $this->encodeOptions(),
1910 'user_token' => $this->mToken,
1911 'user_registration' => $dbw->timestamp( $this->mRegistration ),
1912 ), __METHOD__
1913 );
1914 $this->mId = $dbw->insertId();
1915
1916 # Clear instance cache other than user table data, which is already accurate
1917 $this->clearInstanceCache();
1918 }
1919
1920 /**
1921 * If the (non-anonymous) user is blocked, this function will block any IP address
1922 * that they successfully log on from.
1923 */
1924 function spreadBlock() {
1925 wfDebug( __METHOD__."()\n" );
1926 $this->load();
1927 if ( $this->mId == 0 ) {
1928 return;
1929 }
1930
1931 $userblock = Block::newFromDB( '', $this->mId );
1932 if ( !$userblock ) {
1933 return;
1934 }
1935
1936 $userblock->doAutoblock( wfGetIp() );
1937
1938 }
1939
1940 /**
1941 * Generate a string which will be different for any combination of
1942 * user options which would produce different parser output.
1943 * This will be used as part of the hash key for the parser cache,
1944 * so users will the same options can share the same cached data
1945 * safely.
1946 *
1947 * Extensions which require it should install 'PageRenderingHash' hook,
1948 * which will give them a chance to modify this key based on their own
1949 * settings.
1950 *
1951 * @return string
1952 */
1953 function getPageRenderingHash() {
1954 global $wgContLang, $wgUseDynamicDates;
1955 if( $this->mHash ){
1956 return $this->mHash;
1957 }
1958
1959 // stubthreshold is only included below for completeness,
1960 // it will always be 0 when this function is called by parsercache.
1961
1962 $confstr = $this->getOption( 'math' );
1963 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1964 if ( $wgUseDynamicDates ) {
1965 $confstr .= '!' . $this->getDatePreference();
1966 }
1967 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
1968 $confstr .= '!' . $this->getOption( 'language' );
1969 $confstr .= '!' . $this->getOption( 'thumbsize' );
1970 // add in language specific options, if any
1971 $extra = $wgContLang->getExtraHashOptions();
1972 $confstr .= $extra;
1973
1974 // Give a chance for extensions to modify the hash, if they have
1975 // extra options or other effects on the parser cache.
1976 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
1977
1978 $this->mHash = $confstr;
1979 return $confstr;
1980 }
1981
1982 function isBlockedFromCreateAccount() {
1983 $this->getBlockedStatus();
1984 return $this->mBlock && $this->mBlock->mCreateAccount;
1985 }
1986
1987 function isAllowedToCreateAccount() {
1988 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
1989 }
1990
1991 /**
1992 * @deprecated
1993 */
1994 function setLoaded( $loaded ) {}
1995
1996 /**
1997 * Get this user's personal page title.
1998 *
1999 * @return Title
2000 * @public
2001 */
2002 function getUserPage() {
2003 return Title::makeTitle( NS_USER, $this->getName() );
2004 }
2005
2006 /**
2007 * Get this user's talk page title.
2008 *
2009 * @return Title
2010 * @public
2011 */
2012 function getTalkPage() {
2013 $title = $this->getUserPage();
2014 return $title->getTalkPage();
2015 }
2016
2017 /**
2018 * @static
2019 */
2020 function getMaxID() {
2021 static $res; // cache
2022
2023 if ( isset( $res ) )
2024 return $res;
2025 else {
2026 $dbr =& wfGetDB( DB_SLAVE );
2027 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2028 }
2029 }
2030
2031 /**
2032 * Determine whether the user is a newbie. Newbies are either
2033 * anonymous IPs, or the most recently created accounts.
2034 * @return bool True if it is a newbie.
2035 */
2036 function isNewbie() {
2037 return !$this->isAllowed( 'autoconfirmed' );
2038 }
2039
2040 /**
2041 * Check to see if the given clear-text password is one of the accepted passwords
2042 * @param string $password User password.
2043 * @return bool True if the given password is correct otherwise False.
2044 */
2045 function checkPassword( $password ) {
2046 global $wgAuth, $wgMinimalPasswordLength;
2047 $this->load();
2048
2049 // Even though we stop people from creating passwords that
2050 // are shorter than this, doesn't mean people wont be able
2051 // to. Certain authentication plugins do NOT want to save
2052 // domain passwords in a mysql database, so we should
2053 // check this (incase $wgAuth->strict() is false).
2054 if( strlen( $password ) < $wgMinimalPasswordLength ) {
2055 return false;
2056 }
2057
2058 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2059 return true;
2060 } elseif( $wgAuth->strict() ) {
2061 /* Auth plugin doesn't allow local authentication */
2062 return false;
2063 }
2064 $ep = $this->encryptPassword( $password );
2065 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
2066 return true;
2067 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
2068 return true;
2069 } elseif ( function_exists( 'iconv' ) ) {
2070 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2071 # Check for this with iconv
2072 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2073 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
2074 return true;
2075 }
2076 }
2077 return false;
2078 }
2079
2080 /**
2081 * Initialize (if necessary) and return a session token value
2082 * which can be used in edit forms to show that the user's
2083 * login credentials aren't being hijacked with a foreign form
2084 * submission.
2085 *
2086 * @param mixed $salt - Optional function-specific data for hash.
2087 * Use a string or an array of strings.
2088 * @return string
2089 * @public
2090 */
2091 function editToken( $salt = '' ) {
2092 if( !isset( $_SESSION['wsEditToken'] ) ) {
2093 $token = $this->generateToken();
2094 $_SESSION['wsEditToken'] = $token;
2095 } else {
2096 $token = $_SESSION['wsEditToken'];
2097 }
2098 if( is_array( $salt ) ) {
2099 $salt = implode( '|', $salt );
2100 }
2101 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2102 }
2103
2104 /**
2105 * Generate a hex-y looking random token for various uses.
2106 * Could be made more cryptographically sure if someone cares.
2107 * @return string
2108 */
2109 function generateToken( $salt = '' ) {
2110 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2111 return md5( $token . $salt );
2112 }
2113
2114 /**
2115 * Check given value against the token value stored in the session.
2116 * A match should confirm that the form was submitted from the
2117 * user's own login session, not a form submission from a third-party
2118 * site.
2119 *
2120 * @param string $val - the input value to compare
2121 * @param string $salt - Optional function-specific data for hash
2122 * @return bool
2123 * @public
2124 */
2125 function matchEditToken( $val, $salt = '' ) {
2126 global $wgMemc;
2127 $sessionToken = $this->editToken( $salt );
2128 if ( $val != $sessionToken ) {
2129 wfDebug( "User::matchEditToken: broken session data\n" );
2130 }
2131 return $val == $sessionToken;
2132 }
2133
2134 /**
2135 * Generate a new e-mail confirmation token and send a confirmation
2136 * mail to the user's given address.
2137 *
2138 * @return mixed True on success, a WikiError object on failure.
2139 */
2140 function sendConfirmationMail() {
2141 global $wgContLang;
2142 $expiration = null; // gets passed-by-ref and defined in next line.
2143 $url = $this->confirmationTokenUrl( $expiration );
2144 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2145 wfMsg( 'confirmemail_body',
2146 wfGetIP(),
2147 $this->getName(),
2148 $url,
2149 $wgContLang->timeanddate( $expiration, false ) ) );
2150 }
2151
2152 /**
2153 * Send an e-mail to this user's account. Does not check for
2154 * confirmed status or validity.
2155 *
2156 * @param string $subject
2157 * @param string $body
2158 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2159 * @return mixed True on success, a WikiError object on failure.
2160 */
2161 function sendMail( $subject, $body, $from = null ) {
2162 if( is_null( $from ) ) {
2163 global $wgPasswordSender;
2164 $from = $wgPasswordSender;
2165 }
2166
2167 require_once( 'UserMailer.php' );
2168 $to = new MailAddress( $this );
2169 $sender = new MailAddress( $from );
2170 $error = userMailer( $to, $sender, $subject, $body );
2171
2172 if( $error == '' ) {
2173 return true;
2174 } else {
2175 return new WikiError( $error );
2176 }
2177 }
2178
2179 /**
2180 * Generate, store, and return a new e-mail confirmation code.
2181 * A hash (unsalted since it's used as a key) is stored.
2182 * @param &$expiration mixed output: accepts the expiration time
2183 * @return string
2184 * @private
2185 */
2186 function confirmationToken( &$expiration ) {
2187 $now = time();
2188 $expires = $now + 7 * 24 * 60 * 60;
2189 $expiration = wfTimestamp( TS_MW, $expires );
2190
2191 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2192 $hash = md5( $token );
2193
2194 $dbw =& wfGetDB( DB_MASTER );
2195 $dbw->update( 'user',
2196 array( 'user_email_token' => $hash,
2197 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2198 array( 'user_id' => $this->mId ),
2199 __METHOD__ );
2200
2201 return $token;
2202 }
2203
2204 /**
2205 * Generate and store a new e-mail confirmation token, and return
2206 * the URL the user can use to confirm.
2207 * @param &$expiration mixed output: accepts the expiration time
2208 * @return string
2209 * @private
2210 */
2211 function confirmationTokenUrl( &$expiration ) {
2212 $token = $this->confirmationToken( $expiration );
2213 $title = SpecialPage::getTitleFor( 'Confirmemail', $token );
2214 return $title->getFullUrl();
2215 }
2216
2217 /**
2218 * Mark the e-mail address confirmed and save.
2219 */
2220 function confirmEmail() {
2221 $this->load();
2222 $this->mEmailAuthenticated = wfTimestampNow();
2223 $this->saveSettings();
2224 return true;
2225 }
2226
2227 /**
2228 * Is this user allowed to send e-mails within limits of current
2229 * site configuration?
2230 * @return bool
2231 */
2232 function canSendEmail() {
2233 return $this->isEmailConfirmed();
2234 }
2235
2236 /**
2237 * Is this user allowed to receive e-mails within limits of current
2238 * site configuration?
2239 * @return bool
2240 */
2241 function canReceiveEmail() {
2242 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2243 }
2244
2245 /**
2246 * Is this user's e-mail address valid-looking and confirmed within
2247 * limits of the current site configuration?
2248 *
2249 * If $wgEmailAuthentication is on, this may require the user to have
2250 * confirmed their address by returning a code or using a password
2251 * sent to the address from the wiki.
2252 *
2253 * @return bool
2254 */
2255 function isEmailConfirmed() {
2256 global $wgEmailAuthentication;
2257 $this->load();
2258 $confirmed = true;
2259 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2260 if( $this->isAnon() )
2261 return false;
2262 if( !self::isValidEmailAddr( $this->mEmail ) )
2263 return false;
2264 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2265 return false;
2266 return true;
2267 } else {
2268 return $confirmed;
2269 }
2270 }
2271
2272 /**
2273 * @param array $groups list of groups
2274 * @return array list of permission key names for given groups combined
2275 * @static
2276 */
2277 static function getGroupPermissions( $groups ) {
2278 global $wgGroupPermissions;
2279 $rights = array();
2280 foreach( $groups as $group ) {
2281 if( isset( $wgGroupPermissions[$group] ) ) {
2282 $rights = array_merge( $rights,
2283 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2284 }
2285 }
2286 return $rights;
2287 }
2288
2289 /**
2290 * @param string $group key name
2291 * @return string localized descriptive name for group, if provided
2292 * @static
2293 */
2294 static function getGroupName( $group ) {
2295 $key = "group-$group";
2296 $name = wfMsg( $key );
2297 if( $name == '' || wfEmptyMsg( $key, $name ) ) {
2298 return $group;
2299 } else {
2300 return $name;
2301 }
2302 }
2303
2304 /**
2305 * @param string $group key name
2306 * @return string localized descriptive name for member of a group, if provided
2307 * @static
2308 */
2309 static function getGroupMember( $group ) {
2310 $key = "group-$group-member";
2311 $name = wfMsg( $key );
2312 if( $name == '' || wfEmptyMsg( $key, $name ) ) {
2313 return $group;
2314 } else {
2315 return $name;
2316 }
2317 }
2318
2319 /**
2320 * Return the set of defined explicit groups.
2321 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2322 * groups are not included, as they are defined
2323 * automatically, not in the database.
2324 * @return array
2325 * @static
2326 */
2327 static function getAllGroups() {
2328 global $wgGroupPermissions;
2329 return array_diff(
2330 array_keys( $wgGroupPermissions ),
2331 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2332 }
2333
2334 /**
2335 * Get the title of a page describing a particular group
2336 *
2337 * @param $group Name of the group
2338 * @return mixed
2339 */
2340 static function getGroupPage( $group ) {
2341 $page = wfMsgForContent( 'grouppage-' . $group );
2342 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2343 $title = Title::newFromText( $page );
2344 if( is_object( $title ) )
2345 return $title;
2346 }
2347 return false;
2348 }
2349
2350 /**
2351 * Create a link to the group in HTML, if available
2352 *
2353 * @param $group Name of the group
2354 * @param $text The text of the link
2355 * @return mixed
2356 */
2357 static function makeGroupLinkHTML( $group, $text = '' ) {
2358 if( $text == '' ) {
2359 $text = self::getGroupName( $group );
2360 }
2361 $title = self::getGroupPage( $group );
2362 if( $title ) {
2363 global $wgUser;
2364 $sk = $wgUser->getSkin();
2365 return $sk->makeLinkObj( $title, $text );
2366 } else {
2367 return $text;
2368 }
2369 }
2370
2371 /**
2372 * Create a link to the group in Wikitext, if available
2373 *
2374 * @param $group Name of the group
2375 * @param $text The text of the link (by default, the name of the group)
2376 * @return mixed
2377 */
2378 static function makeGroupLinkWiki( $group, $text = '' ) {
2379 if( $text == '' ) {
2380 $text = self::getGroupName( $group );
2381 }
2382 $title = self::getGroupPage( $group );
2383 if( $title ) {
2384 $page = $title->getPrefixedText();
2385 return "[[$page|$text]]";
2386 } else {
2387 return $text;
2388 }
2389 }
2390 }
2391
2392 ?>