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