Merge "Removed 'Remember my login' preference"
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * Int Number of characters in user_token field.
25 * @ingroup Constants
26 */
27 define( 'USER_TOKEN_LENGTH', 32 );
28
29 /**
30 * Int Serialized record version.
31 * @ingroup Constants
32 */
33 define( 'MW_USER_VERSION', 9 );
34
35 /**
36 * String Some punctuation to prevent editing from broken text-mangling proxies.
37 * @ingroup Constants
38 */
39 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
40
41 /**
42 * Thrown by User::setPassword() on error.
43 * @ingroup Exception
44 */
45 class PasswordError extends MWException {
46 // NOP
47 }
48
49 /**
50 * The User object encapsulates all of the user-specific settings (user_id,
51 * name, rights, password, email address, options, last login time). Client
52 * classes use the getXXX() functions to access these fields. These functions
53 * do all the work of determining whether the user is logged in,
54 * whether the requested option can be satisfied from cookies or
55 * whether a database query is needed. Most of the settings needed
56 * for rendering normal pages are set in the cookie to minimize use
57 * of the database.
58 */
59 class User {
60 /**
61 * Global constants made accessible as class constants so that autoloader
62 * magic can be used.
63 */
64 const USER_TOKEN_LENGTH = USER_TOKEN_LENGTH;
65 const MW_USER_VERSION = MW_USER_VERSION;
66 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
67
68 /**
69 * Maximum items in $mWatchedItems
70 */
71 const MAX_WATCHED_ITEMS_CACHE = 100;
72
73 /**
74 * Array of Strings List of member variables which are saved to the
75 * shared cache (memcached). Any operation which changes the
76 * corresponding database fields must call a cache-clearing function.
77 * @showinitializer
78 */
79 static $mCacheVars = array(
80 // user table
81 'mId',
82 'mName',
83 'mRealName',
84 'mPassword',
85 'mNewpassword',
86 'mNewpassTime',
87 'mEmail',
88 'mTouched',
89 'mToken',
90 'mEmailAuthenticated',
91 'mEmailToken',
92 'mEmailTokenExpires',
93 'mPasswordExpires',
94 'mRegistration',
95 'mEditCount',
96 // user_groups table
97 'mGroups',
98 // user_properties table
99 'mOptionOverrides',
100 );
101
102 /**
103 * Array of Strings Core rights.
104 * Each of these should have a corresponding message of the form
105 * "right-$right".
106 * @showinitializer
107 */
108 static $mCoreRights = array(
109 'apihighlimits',
110 'autoconfirmed',
111 'autopatrol',
112 'bigdelete',
113 'block',
114 'blockemail',
115 'bot',
116 'browsearchive',
117 'createaccount',
118 'createpage',
119 'createtalk',
120 'delete',
121 'deletedhistory',
122 'deletedtext',
123 'deletelogentry',
124 'deleterevision',
125 'edit',
126 'editinterface',
127 'editprotected',
128 'editmyoptions',
129 'editmyprivateinfo',
130 'editmyusercss',
131 'editmyuserjs',
132 'editmywatchlist',
133 'editsemiprotected',
134 'editusercssjs', #deprecated
135 'editusercss',
136 'edituserjs',
137 'hideuser',
138 'import',
139 'importupload',
140 'ipblock-exempt',
141 'markbotedits',
142 'mergehistory',
143 'minoredit',
144 'move',
145 'movefile',
146 'move-rootuserpages',
147 'move-subpages',
148 'nominornewtalk',
149 'noratelimit',
150 'override-export-depth',
151 'passwordreset',
152 'patrol',
153 'patrolmarks',
154 'protect',
155 'proxyunbannable',
156 'purge',
157 'read',
158 'reupload',
159 'reupload-own',
160 'reupload-shared',
161 'rollback',
162 'sendemail',
163 'siteadmin',
164 'suppressionlog',
165 'suppressredirect',
166 'suppressrevision',
167 'unblockself',
168 'undelete',
169 'unwatchedpages',
170 'upload',
171 'upload_by_url',
172 'userrights',
173 'userrights-interwiki',
174 'viewmyprivateinfo',
175 'viewmywatchlist',
176 'writeapi',
177 );
178 /**
179 * String Cached results of getAllRights()
180 */
181 static $mAllRights = false;
182
183 /** @name Cache variables */
184 //@{
185 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
186 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
187 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
188 $mGroups, $mOptionOverrides;
189
190 protected $mPasswordExpires;
191 //@}
192
193 /**
194 * Bool Whether the cache variables have been loaded.
195 */
196 //@{
197 var $mOptionsLoaded;
198
199 /**
200 * Array with already loaded items or true if all items have been loaded.
201 */
202 private $mLoadedItems = array();
203 //@}
204
205 /**
206 * String Initialization data source if mLoadedItems!==true. May be one of:
207 * - 'defaults' anonymous user initialised from class defaults
208 * - 'name' initialise from mName
209 * - 'id' initialise from mId
210 * - 'session' log in from cookies or session if possible
211 *
212 * Use the User::newFrom*() family of functions to set this.
213 */
214 var $mFrom;
215
216 /**
217 * Lazy-initialized variables, invalidated with clearInstanceCache
218 */
219 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
220 $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
221 $mLocked, $mHideName, $mOptions;
222
223 /**
224 * @var WebRequest
225 */
226 private $mRequest;
227
228 /**
229 * @var Block
230 */
231 var $mBlock;
232
233 /**
234 * @var bool
235 */
236 var $mAllowUsertalk;
237
238 /**
239 * @var Block
240 */
241 private $mBlockedFromCreateAccount = false;
242
243 /**
244 * @var Array
245 */
246 private $mWatchedItems = array();
247
248 static $idCacheByName = array();
249
250 /**
251 * Lightweight constructor for an anonymous user.
252 * Use the User::newFrom* factory functions for other kinds of users.
253 *
254 * @see newFromName()
255 * @see newFromId()
256 * @see newFromConfirmationCode()
257 * @see newFromSession()
258 * @see newFromRow()
259 */
260 public function __construct() {
261 $this->clearInstanceCache( 'defaults' );
262 }
263
264 /**
265 * @return string
266 */
267 public function __toString() {
268 return $this->getName();
269 }
270
271 /**
272 * Load the user table data for this object from the source given by mFrom.
273 */
274 public function load() {
275 if ( $this->mLoadedItems === true ) {
276 return;
277 }
278 wfProfileIn( __METHOD__ );
279
280 // Set it now to avoid infinite recursion in accessors
281 $this->mLoadedItems = true;
282
283 switch ( $this->mFrom ) {
284 case 'defaults':
285 $this->loadDefaults();
286 break;
287 case 'name':
288 $this->mId = self::idFromName( $this->mName );
289 if ( !$this->mId ) {
290 // Nonexistent user placeholder object
291 $this->loadDefaults( $this->mName );
292 } else {
293 $this->loadFromId();
294 }
295 break;
296 case 'id':
297 $this->loadFromId();
298 break;
299 case 'session':
300 if ( !$this->loadFromSession() ) {
301 // Loading from session failed. Load defaults.
302 $this->loadDefaults();
303 }
304 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
305 break;
306 default:
307 wfProfileOut( __METHOD__ );
308 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
309 }
310 wfProfileOut( __METHOD__ );
311 }
312
313 /**
314 * Load user table data, given mId has already been set.
315 * @return bool false if the ID does not exist, true otherwise
316 */
317 public function loadFromId() {
318 global $wgMemc;
319 if ( $this->mId == 0 ) {
320 $this->loadDefaults();
321 return false;
322 }
323
324 // Try cache
325 $key = wfMemcKey( 'user', 'id', $this->mId );
326 $data = $wgMemc->get( $key );
327 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
328 // Object is expired, load from DB
329 $data = false;
330 }
331
332 if ( !$data ) {
333 wfDebug( "User: cache miss for user {$this->mId}\n" );
334 // Load from DB
335 if ( !$this->loadFromDatabase() ) {
336 // Can't load from ID, user is anonymous
337 return false;
338 }
339 $this->saveToCache();
340 } else {
341 wfDebug( "User: got user {$this->mId} from cache\n" );
342 // Restore from cache
343 foreach ( self::$mCacheVars as $name ) {
344 $this->$name = $data[$name];
345 }
346 }
347
348 $this->mLoadedItems = true;
349
350 return true;
351 }
352
353 /**
354 * Save user data to the shared cache
355 */
356 public function saveToCache() {
357 $this->load();
358 $this->loadGroups();
359 $this->loadOptions();
360 if ( $this->isAnon() ) {
361 // Anonymous users are uncached
362 return;
363 }
364 $data = array();
365 foreach ( self::$mCacheVars as $name ) {
366 $data[$name] = $this->$name;
367 }
368 $data['mVersion'] = MW_USER_VERSION;
369 $key = wfMemcKey( 'user', 'id', $this->mId );
370 global $wgMemc;
371 $wgMemc->set( $key, $data );
372 }
373
374 /** @name newFrom*() static factory methods */
375 //@{
376
377 /**
378 * Static factory method for creation from username.
379 *
380 * This is slightly less efficient than newFromId(), so use newFromId() if
381 * you have both an ID and a name handy.
382 *
383 * @param string $name Username, validated by Title::newFromText()
384 * @param string|bool $validate Validate username. Takes the same parameters as
385 * User::getCanonicalName(), except that true is accepted as an alias
386 * for 'valid', for BC.
387 *
388 * @return User|bool User object, or false if the username is invalid
389 * (e.g. if it contains illegal characters or is an IP address). If the
390 * username is not present in the database, the result will be a user object
391 * with a name, zero user ID and default settings.
392 */
393 public static function newFromName( $name, $validate = 'valid' ) {
394 if ( $validate === true ) {
395 $validate = 'valid';
396 }
397 $name = self::getCanonicalName( $name, $validate );
398 if ( $name === false ) {
399 return false;
400 } else {
401 // Create unloaded user object
402 $u = new User;
403 $u->mName = $name;
404 $u->mFrom = 'name';
405 $u->setItemLoaded( 'name' );
406 return $u;
407 }
408 }
409
410 /**
411 * Static factory method for creation from a given user ID.
412 *
413 * @param int $id Valid user ID
414 * @return User The corresponding User object
415 */
416 public static function newFromId( $id ) {
417 $u = new User;
418 $u->mId = $id;
419 $u->mFrom = 'id';
420 $u->setItemLoaded( 'id' );
421 return $u;
422 }
423
424 /**
425 * Factory method to fetch whichever user has a given email confirmation code.
426 * This code is generated when an account is created or its e-mail address
427 * has changed.
428 *
429 * If the code is invalid or has expired, returns NULL.
430 *
431 * @param string $code Confirmation code
432 * @return User|null
433 */
434 public static function newFromConfirmationCode( $code ) {
435 $dbr = wfGetDB( DB_SLAVE );
436 $id = $dbr->selectField( 'user', 'user_id', array(
437 'user_email_token' => md5( $code ),
438 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
439 ) );
440 if ( $id !== false ) {
441 return User::newFromId( $id );
442 } else {
443 return null;
444 }
445 }
446
447 /**
448 * Create a new user object using data from session or cookies. If the
449 * login credentials are invalid, the result is an anonymous user.
450 *
451 * @param WebRequest $request Object to use; $wgRequest will be used if omitted.
452 * @return User object
453 */
454 public static function newFromSession( WebRequest $request = null ) {
455 $user = new User;
456 $user->mFrom = 'session';
457 $user->mRequest = $request;
458 return $user;
459 }
460
461 /**
462 * Create a new user object from a user row.
463 * The row should have the following fields from the user table in it:
464 * - either user_name or user_id to load further data if needed (or both)
465 * - user_real_name
466 * - all other fields (email, password, etc.)
467 * It is useless to provide the remaining fields if either user_id,
468 * user_name and user_real_name are not provided because the whole row
469 * will be loaded once more from the database when accessing them.
470 *
471 * @param stdClass $row A row from the user table
472 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
473 * @return User
474 */
475 public static function newFromRow( $row, $data = null ) {
476 $user = new User;
477 $user->loadFromRow( $row, $data );
478 return $user;
479 }
480
481 //@}
482
483 /**
484 * Get the username corresponding to a given user ID
485 * @param int $id User ID
486 * @return string|bool The corresponding username
487 */
488 public static function whoIs( $id ) {
489 return UserCache::singleton()->getProp( $id, 'name' );
490 }
491
492 /**
493 * Get the real name of a user given their user ID
494 *
495 * @param int $id User ID
496 * @return string|bool The corresponding user's real name
497 */
498 public static function whoIsReal( $id ) {
499 return UserCache::singleton()->getProp( $id, 'real_name' );
500 }
501
502 /**
503 * Get database id given a user name
504 * @param string $name Username
505 * @return int|null The corresponding user's ID, or null if user is nonexistent
506 */
507 public static function idFromName( $name ) {
508 $nt = Title::makeTitleSafe( NS_USER, $name );
509 if ( is_null( $nt ) ) {
510 // Illegal name
511 return null;
512 }
513
514 if ( isset( self::$idCacheByName[$name] ) ) {
515 return self::$idCacheByName[$name];
516 }
517
518 $dbr = wfGetDB( DB_SLAVE );
519 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
520
521 if ( $s === false ) {
522 $result = null;
523 } else {
524 $result = $s->user_id;
525 }
526
527 self::$idCacheByName[$name] = $result;
528
529 if ( count( self::$idCacheByName ) > 1000 ) {
530 self::$idCacheByName = array();
531 }
532
533 return $result;
534 }
535
536 /**
537 * Reset the cache used in idFromName(). For use in tests.
538 */
539 public static function resetIdByNameCache() {
540 self::$idCacheByName = array();
541 }
542
543 /**
544 * Does the string match an anonymous IPv4 address?
545 *
546 * This function exists for username validation, in order to reject
547 * usernames which are similar in form to IP addresses. Strings such
548 * as 300.300.300.300 will return true because it looks like an IP
549 * address, despite not being strictly valid.
550 *
551 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
552 * address because the usemod software would "cloak" anonymous IP
553 * addresses like this, if we allowed accounts like this to be created
554 * new users could get the old edits of these anonymous users.
555 *
556 * @param string $name Name to match
557 * @return bool
558 */
559 public static function isIP( $name ) {
560 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name ) || IP::isIPv6( $name );
561 }
562
563 /**
564 * Is the input a valid username?
565 *
566 * Checks if the input is a valid username, we don't want an empty string,
567 * an IP address, anything that contains slashes (would mess up subpages),
568 * is longer than the maximum allowed username size or doesn't begin with
569 * a capital letter.
570 *
571 * @param string $name Name to match
572 * @return bool
573 */
574 public static function isValidUserName( $name ) {
575 global $wgContLang, $wgMaxNameChars;
576
577 if ( $name == ''
578 || User::isIP( $name )
579 || strpos( $name, '/' ) !== false
580 || strlen( $name ) > $wgMaxNameChars
581 || $name != $wgContLang->ucfirst( $name ) ) {
582 wfDebugLog( 'username', __METHOD__ .
583 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
584 return false;
585 }
586
587 // Ensure that the name can't be misresolved as a different title,
588 // such as with extra namespace keys at the start.
589 $parsed = Title::newFromText( $name );
590 if ( is_null( $parsed )
591 || $parsed->getNamespace()
592 || strcmp( $name, $parsed->getPrefixedText() ) ) {
593 wfDebugLog( 'username', __METHOD__ .
594 ": '$name' invalid due to ambiguous prefixes" );
595 return false;
596 }
597
598 // Check an additional blacklist of troublemaker characters.
599 // Should these be merged into the title char list?
600 $unicodeBlacklist = '/[' .
601 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
602 '\x{00a0}' . # non-breaking space
603 '\x{2000}-\x{200f}' . # various whitespace
604 '\x{2028}-\x{202f}' . # breaks and control chars
605 '\x{3000}' . # ideographic space
606 '\x{e000}-\x{f8ff}' . # private use
607 ']/u';
608 if ( preg_match( $unicodeBlacklist, $name ) ) {
609 wfDebugLog( 'username', __METHOD__ .
610 ": '$name' invalid due to blacklisted characters" );
611 return false;
612 }
613
614 return true;
615 }
616
617 /**
618 * Usernames which fail to pass this function will be blocked
619 * from user login and new account registrations, but may be used
620 * internally by batch processes.
621 *
622 * If an account already exists in this form, login will be blocked
623 * by a failure to pass this function.
624 *
625 * @param string $name Name to match
626 * @return bool
627 */
628 public static function isUsableName( $name ) {
629 global $wgReservedUsernames;
630 // Must be a valid username, obviously ;)
631 if ( !self::isValidUserName( $name ) ) {
632 return false;
633 }
634
635 static $reservedUsernames = false;
636 if ( !$reservedUsernames ) {
637 $reservedUsernames = $wgReservedUsernames;
638 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
639 }
640
641 // Certain names may be reserved for batch processes.
642 foreach ( $reservedUsernames as $reserved ) {
643 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
644 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
645 }
646 if ( $reserved == $name ) {
647 return false;
648 }
649 }
650 return true;
651 }
652
653 /**
654 * Usernames which fail to pass this function will be blocked
655 * from new account registrations, but may be used internally
656 * either by batch processes or by user accounts which have
657 * already been created.
658 *
659 * Additional blacklisting may be added here rather than in
660 * isValidUserName() to avoid disrupting existing accounts.
661 *
662 * @param string $name to match
663 * @return bool
664 */
665 public static function isCreatableName( $name ) {
666 global $wgInvalidUsernameCharacters;
667
668 // Ensure that the username isn't longer than 235 bytes, so that
669 // (at least for the builtin skins) user javascript and css files
670 // will work. (bug 23080)
671 if ( strlen( $name ) > 235 ) {
672 wfDebugLog( 'username', __METHOD__ .
673 ": '$name' invalid due to length" );
674 return false;
675 }
676
677 // Preg yells if you try to give it an empty string
678 if ( $wgInvalidUsernameCharacters !== '' ) {
679 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
680 wfDebugLog( 'username', __METHOD__ .
681 ": '$name' invalid due to wgInvalidUsernameCharacters" );
682 return false;
683 }
684 }
685
686 return self::isUsableName( $name );
687 }
688
689 /**
690 * Is the input a valid password for this user?
691 *
692 * @param string $password Desired password
693 * @return bool
694 */
695 public function isValidPassword( $password ) {
696 //simple boolean wrapper for getPasswordValidity
697 return $this->getPasswordValidity( $password ) === true;
698 }
699
700
701 /**
702 * Given unvalidated password input, return error message on failure.
703 *
704 * @param string $password Desired password
705 * @return mixed: true on success, string or array of error message on failure
706 */
707 public function getPasswordValidity( $password ) {
708 $result = $this->checkPasswordValidity( $password );
709 if ( $result->isGood() ) {
710 return true;
711 } else {
712 $messages = array();
713 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
714 $messages[] = $error['message'];
715 }
716 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
717 $messages[] = $warning['message'];
718 }
719 if ( count( $messages ) === 1 ) {
720 return $messages[0];
721 }
722 return $messages;
723 }
724 }
725
726 /**
727 * Check if this is a valid password for this user. Status will be good if
728 * the password is valid, or have an array of error messages if not.
729 *
730 * @param string $password Desired password
731 * @return Status
732 * @since 1.23
733 */
734 public function checkPasswordValidity( $password ) {
735 global $wgMinimalPasswordLength, $wgContLang;
736
737 static $blockedLogins = array(
738 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
739 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
740 );
741
742 $status = Status::newGood();
743
744 $result = false; //init $result to false for the internal checks
745
746 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
747 $status->error( $result );
748 return $status;
749 }
750
751 if ( $result === false ) {
752 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
753 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
754 return $status;
755 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
756 $status->error( 'password-name-match' );
757 return $status;
758 } elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) {
759 $status->error( 'password-login-forbidden' );
760 return $status;
761 } else {
762 //it seems weird returning a Good status here, but this is because of the
763 //initialization of $result to false above. If the hook is never run or it
764 //doesn't modify $result, then we will likely get down into this if with
765 //a valid password.
766 return $status;
767 }
768 } elseif ( $result === true ) {
769 return $status;
770 } else {
771 $status->error( $result );
772 return $status; //the isValidPassword hook set a string $result and returned true
773 }
774 }
775
776 /**
777 * Expire a user's password
778 * @since 1.23
779 * @param $ts Mixed: optional timestamp to convert, default 0 for the current time
780 */
781 public function expirePassword( $ts = 0 ) {
782 $this->load();
783 $timestamp = wfTimestamp( TS_MW, $ts );
784 $this->mPasswordExpires = $timestamp;
785 $this->saveSettings();
786 }
787
788 /**
789 * Clear the password expiration for a user
790 * @since 1.23
791 * @param bool $load ensure user object is loaded first
792 */
793 public function resetPasswordExpiration( $load = true ) {
794 global $wgPasswordExpirationDays;
795 if ( $load ) {
796 $this->load();
797 }
798 $newExpire = null;
799 if ( $wgPasswordExpirationDays ) {
800 $newExpire = wfTimestamp(
801 TS_MW,
802 time() + ( $wgPasswordExpirationDays * 24 * 3600 )
803 );
804 }
805 // Give extensions a chance to force an expiration
806 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
807 $this->mPasswordExpires = $newExpire;
808 }
809
810 /**
811 * Check if the user's password is expired.
812 * TODO: Put this and password length into a PasswordPolicy object
813 * @since 1.23
814 * @return string|bool The expiration type, or false if not expired
815 * hard: A password change is required to login
816 * soft: Allow login, but encourage password change
817 * false: Password is not expired
818 */
819 public function getPasswordExpired() {
820 global $wgPasswordExpireGrace;
821 $expired = false;
822 $now = wfTimestamp();
823 $expiration = $this->getPasswordExpireDate();
824 $expUnix = wfTimestamp( TS_UNIX, $expiration );
825 if ( $expiration !== null && $expUnix < $now ) {
826 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
827 }
828 return $expired;
829 }
830
831 /**
832 * Get this user's password expiration date. Since this may be using
833 * the cached User object, we assume that whatever mechanism is setting
834 * the expiration date is also expiring the User cache.
835 * @since 1.23
836 * @return string|false the datestamp of the expiration, or null if not set
837 */
838 public function getPasswordExpireDate() {
839 $this->load();
840 return $this->mPasswordExpires;
841 }
842
843 /**
844 * Does a string look like an e-mail address?
845 *
846 * This validates an email address using an HTML5 specification found at:
847 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
848 * Which as of 2011-01-24 says:
849 *
850 * A valid e-mail address is a string that matches the ABNF production
851 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
852 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
853 * 3.5.
854 *
855 * This function is an implementation of the specification as requested in
856 * bug 22449.
857 *
858 * Client-side forms will use the same standard validation rules via JS or
859 * HTML 5 validation; additional restrictions can be enforced server-side
860 * by extensions via the 'isValidEmailAddr' hook.
861 *
862 * Note that this validation doesn't 100% match RFC 2822, but is believed
863 * to be liberal enough for wide use. Some invalid addresses will still
864 * pass validation here.
865 *
866 * @param string $addr E-mail address
867 * @return bool
868 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
869 */
870 public static function isValidEmailAddr( $addr ) {
871 wfDeprecated( __METHOD__, '1.18' );
872 return Sanitizer::validateEmail( $addr );
873 }
874
875 /**
876 * Given unvalidated user input, return a canonical username, or false if
877 * the username is invalid.
878 * @param string $name User input
879 * @param string|bool $validate type of validation to use:
880 * - false No validation
881 * - 'valid' Valid for batch processes
882 * - 'usable' Valid for batch processes and login
883 * - 'creatable' Valid for batch processes, login and account creation
884 *
885 * @throws MWException
886 * @return bool|string
887 */
888 public static function getCanonicalName( $name, $validate = 'valid' ) {
889 // Force usernames to capital
890 global $wgContLang;
891 $name = $wgContLang->ucfirst( $name );
892
893 # Reject names containing '#'; these will be cleaned up
894 # with title normalisation, but then it's too late to
895 # check elsewhere
896 if ( strpos( $name, '#' ) !== false ) {
897 return false;
898 }
899
900 // Clean up name according to title rules
901 $t = ( $validate === 'valid' ) ?
902 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
903 // Check for invalid titles
904 if ( is_null( $t ) ) {
905 return false;
906 }
907
908 // Reject various classes of invalid names
909 global $wgAuth;
910 $name = $wgAuth->getCanonicalName( $t->getText() );
911
912 switch ( $validate ) {
913 case false:
914 break;
915 case 'valid':
916 if ( !User::isValidUserName( $name ) ) {
917 $name = false;
918 }
919 break;
920 case 'usable':
921 if ( !User::isUsableName( $name ) ) {
922 $name = false;
923 }
924 break;
925 case 'creatable':
926 if ( !User::isCreatableName( $name ) ) {
927 $name = false;
928 }
929 break;
930 default:
931 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
932 }
933 return $name;
934 }
935
936 /**
937 * Count the number of edits of a user
938 *
939 * @param int $uid User ID to check
940 * @return int The user's edit count
941 *
942 * @deprecated since 1.21 in favour of User::getEditCount
943 */
944 public static function edits( $uid ) {
945 wfDeprecated( __METHOD__, '1.21' );
946 $user = self::newFromId( $uid );
947 return $user->getEditCount();
948 }
949
950 /**
951 * Return a random password.
952 *
953 * @return string New random password
954 */
955 public static function randomPassword() {
956 global $wgMinimalPasswordLength;
957 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
958 $length = max( 10, $wgMinimalPasswordLength );
959 // Multiply by 1.25 to get the number of hex characters we need
960 $length = $length * 1.25;
961 // Generate random hex chars
962 $hex = MWCryptRand::generateHex( $length );
963 // Convert from base 16 to base 32 to get a proper password like string
964 return wfBaseConvert( $hex, 16, 32 );
965 }
966
967 /**
968 * Set cached properties to default.
969 *
970 * @note This no longer clears uncached lazy-initialised properties;
971 * the constructor does that instead.
972 *
973 * @param $name string|bool
974 */
975 public function loadDefaults( $name = false ) {
976 wfProfileIn( __METHOD__ );
977
978 $this->mId = 0;
979 $this->mName = $name;
980 $this->mRealName = '';
981 $this->mPassword = $this->mNewpassword = '';
982 $this->mNewpassTime = null;
983 $this->mEmail = '';
984 $this->mOptionOverrides = null;
985 $this->mOptionsLoaded = false;
986
987 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
988 if ( $loggedOut !== null ) {
989 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
990 } else {
991 $this->mTouched = '1'; # Allow any pages to be cached
992 }
993
994 $this->mToken = null; // Don't run cryptographic functions till we need a token
995 $this->mEmailAuthenticated = null;
996 $this->mEmailToken = '';
997 $this->mEmailTokenExpires = null;
998 $this->mPasswordExpires = null;
999 $this->resetPasswordExpiration( false );
1000 $this->mRegistration = wfTimestamp( TS_MW );
1001 $this->mGroups = array();
1002
1003 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1004
1005 wfProfileOut( __METHOD__ );
1006 }
1007
1008 /**
1009 * Return whether an item has been loaded.
1010 *
1011 * @param string $item item to check. Current possibilities:
1012 * - id
1013 * - name
1014 * - realname
1015 * @param string $all 'all' to check if the whole object has been loaded
1016 * or any other string to check if only the item is available (e.g.
1017 * for optimisation)
1018 * @return boolean
1019 */
1020 public function isItemLoaded( $item, $all = 'all' ) {
1021 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1022 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1023 }
1024
1025 /**
1026 * Set that an item has been loaded
1027 *
1028 * @param string $item
1029 */
1030 protected function setItemLoaded( $item ) {
1031 if ( is_array( $this->mLoadedItems ) ) {
1032 $this->mLoadedItems[$item] = true;
1033 }
1034 }
1035
1036 /**
1037 * Load user data from the session or login cookie.
1038 * @return bool True if the user is logged in, false otherwise.
1039 */
1040 private function loadFromSession() {
1041 $result = null;
1042 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1043 if ( $result !== null ) {
1044 return $result;
1045 }
1046
1047 $request = $this->getRequest();
1048
1049 $cookieId = $request->getCookie( 'UserID' );
1050 $sessId = $request->getSessionData( 'wsUserID' );
1051
1052 if ( $cookieId !== null ) {
1053 $sId = intval( $cookieId );
1054 if ( $sessId !== null && $cookieId != $sessId ) {
1055 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1056 cookie user ID ($sId) don't match!" );
1057 return false;
1058 }
1059 $request->setSessionData( 'wsUserID', $sId );
1060 } elseif ( $sessId !== null && $sessId != 0 ) {
1061 $sId = $sessId;
1062 } else {
1063 return false;
1064 }
1065
1066 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1067 $sName = $request->getSessionData( 'wsUserName' );
1068 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1069 $sName = $request->getCookie( 'UserName' );
1070 $request->setSessionData( 'wsUserName', $sName );
1071 } else {
1072 return false;
1073 }
1074
1075 $proposedUser = User::newFromId( $sId );
1076 if ( !$proposedUser->isLoggedIn() ) {
1077 // Not a valid ID
1078 return false;
1079 }
1080
1081 global $wgBlockDisablesLogin;
1082 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1083 // User blocked and we've disabled blocked user logins
1084 return false;
1085 }
1086
1087 if ( $request->getSessionData( 'wsToken' ) ) {
1088 $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1089 $from = 'session';
1090 } elseif ( $request->getCookie( 'Token' ) ) {
1091 # Get the token from DB/cache and clean it up to remove garbage padding.
1092 # This deals with historical problems with bugs and the default column value.
1093 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1094 // Make comparison in constant time (bug 61346)
1095 $passwordCorrect = strlen( $token ) && $this->compareSecrets( $token, $request->getCookie( 'Token' ) );
1096 $from = 'cookie';
1097 } else {
1098 // No session or persistent login cookie
1099 return false;
1100 }
1101
1102 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1103 $this->loadFromUserObject( $proposedUser );
1104 $request->setSessionData( 'wsToken', $this->mToken );
1105 wfDebug( "User: logged in from $from\n" );
1106 return true;
1107 } else {
1108 // Invalid credentials
1109 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1110 return false;
1111 }
1112 }
1113
1114 /**
1115 * A comparison of two strings, not vulnerable to timing attacks
1116 * @param string $answer the secret string that you are comparing against.
1117 * @param string $test compare this string to the $answer.
1118 * @return bool True if the strings are the same, false otherwise
1119 */
1120 protected function compareSecrets( $answer, $test ) {
1121 if ( strlen( $answer ) !== strlen( $test ) ) {
1122 $passwordCorrect = false;
1123 } else {
1124 $result = 0;
1125 for ( $i = 0; $i < strlen( $answer ); $i++ ) {
1126 $result |= ord( $answer[$i] ) ^ ord( $test[$i] );
1127 }
1128 $passwordCorrect = ( $result == 0 );
1129 }
1130 return $passwordCorrect;
1131 }
1132
1133 /**
1134 * Load user and user_group data from the database.
1135 * $this->mId must be set, this is how the user is identified.
1136 *
1137 * @return bool True if the user exists, false if the user is anonymous
1138 */
1139 public function loadFromDatabase() {
1140 // Paranoia
1141 $this->mId = intval( $this->mId );
1142
1143 // Anonymous user
1144 if ( !$this->mId ) {
1145 $this->loadDefaults();
1146 return false;
1147 }
1148
1149 $dbr = wfGetDB( DB_MASTER );
1150 $s = $dbr->selectRow( 'user', self::selectFields(), array( 'user_id' => $this->mId ), __METHOD__ );
1151
1152 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1153
1154 if ( $s !== false ) {
1155 // Initialise user table data
1156 $this->loadFromRow( $s );
1157 $this->mGroups = null; // deferred
1158 $this->getEditCount(); // revalidation for nulls
1159 return true;
1160 } else {
1161 // Invalid user_id
1162 $this->mId = 0;
1163 $this->loadDefaults();
1164 return false;
1165 }
1166 }
1167
1168 /**
1169 * Initialize this object from a row from the user table.
1170 *
1171 * @param stdClass $row Row from the user table to load.
1172 * @param array $data Further user data to load into the object
1173 *
1174 * user_groups Array with groups out of the user_groups table
1175 * user_properties Array with properties out of the user_properties table
1176 */
1177 public function loadFromRow( $row, $data = null ) {
1178 $all = true;
1179
1180 $this->mGroups = null; // deferred
1181
1182 if ( isset( $row->user_name ) ) {
1183 $this->mName = $row->user_name;
1184 $this->mFrom = 'name';
1185 $this->setItemLoaded( 'name' );
1186 } else {
1187 $all = false;
1188 }
1189
1190 if ( isset( $row->user_real_name ) ) {
1191 $this->mRealName = $row->user_real_name;
1192 $this->setItemLoaded( 'realname' );
1193 } else {
1194 $all = false;
1195 }
1196
1197 if ( isset( $row->user_id ) ) {
1198 $this->mId = intval( $row->user_id );
1199 $this->mFrom = 'id';
1200 $this->setItemLoaded( 'id' );
1201 } else {
1202 $all = false;
1203 }
1204
1205 if ( isset( $row->user_editcount ) ) {
1206 $this->mEditCount = $row->user_editcount;
1207 } else {
1208 $all = false;
1209 }
1210
1211 if ( isset( $row->user_password ) ) {
1212 $this->mPassword = $row->user_password;
1213 $this->mNewpassword = $row->user_newpassword;
1214 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1215 $this->mEmail = $row->user_email;
1216 if ( isset( $row->user_options ) ) {
1217 $this->decodeOptions( $row->user_options );
1218 }
1219 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1220 $this->mToken = $row->user_token;
1221 if ( $this->mToken == '' ) {
1222 $this->mToken = null;
1223 }
1224 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1225 $this->mEmailToken = $row->user_email_token;
1226 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1227 $this->mPasswordExpires = wfTimestampOrNull( TS_MW, $row->user_password_expires );
1228 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1229 } else {
1230 $all = false;
1231 }
1232
1233 if ( $all ) {
1234 $this->mLoadedItems = true;
1235 }
1236
1237 if ( is_array( $data ) ) {
1238 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1239 $this->mGroups = $data['user_groups'];
1240 }
1241 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1242 $this->loadOptions( $data['user_properties'] );
1243 }
1244 }
1245 }
1246
1247 /**
1248 * Load the data for this user object from another user object.
1249 *
1250 * @param $user User
1251 */
1252 protected function loadFromUserObject( $user ) {
1253 $user->load();
1254 $user->loadGroups();
1255 $user->loadOptions();
1256 foreach ( self::$mCacheVars as $var ) {
1257 $this->$var = $user->$var;
1258 }
1259 }
1260
1261 /**
1262 * Load the groups from the database if they aren't already loaded.
1263 */
1264 private function loadGroups() {
1265 if ( is_null( $this->mGroups ) ) {
1266 $dbr = wfGetDB( DB_MASTER );
1267 $res = $dbr->select( 'user_groups',
1268 array( 'ug_group' ),
1269 array( 'ug_user' => $this->mId ),
1270 __METHOD__ );
1271 $this->mGroups = array();
1272 foreach ( $res as $row ) {
1273 $this->mGroups[] = $row->ug_group;
1274 }
1275 }
1276 }
1277
1278 /**
1279 * Add the user to the group if he/she meets given criteria.
1280 *
1281 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1282 * possible to remove manually via Special:UserRights. In such case it
1283 * will not be re-added automatically. The user will also not lose the
1284 * group if they no longer meet the criteria.
1285 *
1286 * @param string $event key in $wgAutopromoteOnce (each one has groups/criteria)
1287 *
1288 * @return array Array of groups the user has been promoted to.
1289 *
1290 * @see $wgAutopromoteOnce
1291 */
1292 public function addAutopromoteOnceGroups( $event ) {
1293 global $wgAutopromoteOnceLogInRC, $wgAuth;
1294
1295 $toPromote = array();
1296 if ( $this->getId() ) {
1297 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1298 if ( count( $toPromote ) ) {
1299 $oldGroups = $this->getGroups(); // previous groups
1300
1301 foreach ( $toPromote as $group ) {
1302 $this->addGroup( $group );
1303 }
1304 // update groups in external authentication database
1305 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1306
1307 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1308
1309 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1310 $logEntry->setPerformer( $this );
1311 $logEntry->setTarget( $this->getUserPage() );
1312 $logEntry->setParameters( array(
1313 '4::oldgroups' => $oldGroups,
1314 '5::newgroups' => $newGroups,
1315 ) );
1316 $logid = $logEntry->insert();
1317 if ( $wgAutopromoteOnceLogInRC ) {
1318 $logEntry->publish( $logid );
1319 }
1320 }
1321 }
1322 return $toPromote;
1323 }
1324
1325 /**
1326 * Clear various cached data stored in this object. The cache of the user table
1327 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1328 *
1329 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1330 * given source. May be "name", "id", "defaults", "session", or false for
1331 * no reload.
1332 */
1333 public function clearInstanceCache( $reloadFrom = false ) {
1334 $this->mNewtalk = -1;
1335 $this->mDatePreference = null;
1336 $this->mBlockedby = -1; # Unset
1337 $this->mHash = false;
1338 $this->mRights = null;
1339 $this->mEffectiveGroups = null;
1340 $this->mImplicitGroups = null;
1341 $this->mGroups = null;
1342 $this->mOptions = null;
1343 $this->mOptionsLoaded = false;
1344 $this->mEditCount = null;
1345
1346 if ( $reloadFrom ) {
1347 $this->mLoadedItems = array();
1348 $this->mFrom = $reloadFrom;
1349 }
1350 }
1351
1352 /**
1353 * Combine the language default options with any site-specific options
1354 * and add the default language variants.
1355 *
1356 * @return Array of String options
1357 */
1358 public static function getDefaultOptions() {
1359 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1360
1361 static $defOpt = null;
1362 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1363 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1364 // mid-request and see that change reflected in the return value of this function.
1365 // Which is insane and would never happen during normal MW operation
1366 return $defOpt;
1367 }
1368
1369 $defOpt = $wgDefaultUserOptions;
1370 // Default language setting
1371 $defOpt['language'] = $wgContLang->getCode();
1372 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1373 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1374 }
1375 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1376 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1377 }
1378 $defOpt['skin'] = $wgDefaultSkin;
1379
1380 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1381
1382 return $defOpt;
1383 }
1384
1385 /**
1386 * Get a given default option value.
1387 *
1388 * @param string $opt Name of option to retrieve
1389 * @return string Default option value
1390 */
1391 public static function getDefaultOption( $opt ) {
1392 $defOpts = self::getDefaultOptions();
1393 if ( isset( $defOpts[$opt] ) ) {
1394 return $defOpts[$opt];
1395 } else {
1396 return null;
1397 }
1398 }
1399
1400 /**
1401 * Get blocking information
1402 * @param bool $bFromSlave Whether to check the slave database first. To
1403 * improve performance, non-critical checks are done
1404 * against slaves. Check when actually saving should be
1405 * done against master.
1406 */
1407 private function getBlockedStatus( $bFromSlave = true ) {
1408 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1409
1410 if ( -1 != $this->mBlockedby ) {
1411 return;
1412 }
1413
1414 wfProfileIn( __METHOD__ );
1415 wfDebug( __METHOD__ . ": checking...\n" );
1416
1417 // Initialize data...
1418 // Otherwise something ends up stomping on $this->mBlockedby when
1419 // things get lazy-loaded later, causing false positive block hits
1420 // due to -1 !== 0. Probably session-related... Nothing should be
1421 // overwriting mBlockedby, surely?
1422 $this->load();
1423
1424 # We only need to worry about passing the IP address to the Block generator if the
1425 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1426 # know which IP address they're actually coming from
1427 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1428 $ip = $this->getRequest()->getIP();
1429 } else {
1430 $ip = null;
1431 }
1432
1433 // User/IP blocking
1434 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1435
1436 // Proxy blocking
1437 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1438 && !in_array( $ip, $wgProxyWhitelist )
1439 ) {
1440 // Local list
1441 if ( self::isLocallyBlockedProxy( $ip ) ) {
1442 $block = new Block;
1443 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1444 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1445 $block->setTarget( $ip );
1446 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1447 $block = new Block;
1448 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1449 $block->mReason = wfMessage( 'sorbsreason' )->text();
1450 $block->setTarget( $ip );
1451 }
1452 }
1453
1454 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1455 if ( !$block instanceof Block
1456 && $wgApplyIpBlocksToXff
1457 && $ip !== null
1458 && !$this->isAllowed( 'proxyunbannable' )
1459 && !in_array( $ip, $wgProxyWhitelist )
1460 ) {
1461 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1462 $xff = array_map( 'trim', explode( ',', $xff ) );
1463 $xff = array_diff( $xff, array( $ip ) );
1464 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1465 $block = Block::chooseBlock( $xffblocks, $xff );
1466 if ( $block instanceof Block ) {
1467 # Mangle the reason to alert the user that the block
1468 # originated from matching the X-Forwarded-For header.
1469 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1470 }
1471 }
1472
1473 if ( $block instanceof Block ) {
1474 wfDebug( __METHOD__ . ": Found block.\n" );
1475 $this->mBlock = $block;
1476 $this->mBlockedby = $block->getByName();
1477 $this->mBlockreason = $block->mReason;
1478 $this->mHideName = $block->mHideName;
1479 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1480 } else {
1481 $this->mBlockedby = '';
1482 $this->mHideName = 0;
1483 $this->mAllowUsertalk = false;
1484 }
1485
1486 // Extensions
1487 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1488
1489 wfProfileOut( __METHOD__ );
1490 }
1491
1492 /**
1493 * Whether the given IP is in a DNS blacklist.
1494 *
1495 * @param string $ip IP to check
1496 * @param bool $checkWhitelist whether to check the whitelist first
1497 * @return bool True if blacklisted.
1498 */
1499 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1500 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1501 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1502
1503 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1504 return false;
1505 }
1506
1507 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1508 return false;
1509 }
1510
1511 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1512 return $this->inDnsBlacklist( $ip, $urls );
1513 }
1514
1515 /**
1516 * Whether the given IP is in a given DNS blacklist.
1517 *
1518 * @param string $ip IP to check
1519 * @param string|array $bases of Strings: URL of the DNS blacklist
1520 * @return bool True if blacklisted.
1521 */
1522 public function inDnsBlacklist( $ip, $bases ) {
1523 wfProfileIn( __METHOD__ );
1524
1525 $found = false;
1526 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1527 if ( IP::isIPv4( $ip ) ) {
1528 // Reverse IP, bug 21255
1529 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1530
1531 foreach ( (array)$bases as $base ) {
1532 // Make hostname
1533 // If we have an access key, use that too (ProjectHoneypot, etc.)
1534 if ( is_array( $base ) ) {
1535 if ( count( $base ) >= 2 ) {
1536 // Access key is 1, base URL is 0
1537 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1538 } else {
1539 $host = "$ipReversed.{$base[0]}";
1540 }
1541 } else {
1542 $host = "$ipReversed.$base";
1543 }
1544
1545 // Send query
1546 $ipList = gethostbynamel( $host );
1547
1548 if ( $ipList ) {
1549 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1550 $found = true;
1551 break;
1552 } else {
1553 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1554 }
1555 }
1556 }
1557
1558 wfProfileOut( __METHOD__ );
1559 return $found;
1560 }
1561
1562 /**
1563 * Check if an IP address is in the local proxy list
1564 *
1565 * @param $ip string
1566 *
1567 * @return bool
1568 */
1569 public static function isLocallyBlockedProxy( $ip ) {
1570 global $wgProxyList;
1571
1572 if ( !$wgProxyList ) {
1573 return false;
1574 }
1575 wfProfileIn( __METHOD__ );
1576
1577 if ( !is_array( $wgProxyList ) ) {
1578 // Load from the specified file
1579 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1580 }
1581
1582 if ( !is_array( $wgProxyList ) ) {
1583 $ret = false;
1584 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1585 $ret = true;
1586 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1587 // Old-style flipped proxy list
1588 $ret = true;
1589 } else {
1590 $ret = false;
1591 }
1592 wfProfileOut( __METHOD__ );
1593 return $ret;
1594 }
1595
1596 /**
1597 * Is this user subject to rate limiting?
1598 *
1599 * @return bool True if rate limited
1600 */
1601 public function isPingLimitable() {
1602 global $wgRateLimitsExcludedIPs;
1603 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1604 // No other good way currently to disable rate limits
1605 // for specific IPs. :P
1606 // But this is a crappy hack and should die.
1607 return false;
1608 }
1609 return !$this->isAllowed( 'noratelimit' );
1610 }
1611
1612 /**
1613 * Primitive rate limits: enforce maximum actions per time period
1614 * to put a brake on flooding.
1615 *
1616 * @note When using a shared cache like memcached, IP-address
1617 * last-hit counters will be shared across wikis.
1618 *
1619 * @param string $action Action to enforce; 'edit' if unspecified
1620 * @param integer $incrBy Positive amount to increment counter by [defaults to 1]
1621 * @return bool True if a rate limiter was tripped
1622 */
1623 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1624 // Call the 'PingLimiter' hook
1625 $result = false;
1626 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1627 return $result;
1628 }
1629
1630 global $wgRateLimits;
1631 if ( !isset( $wgRateLimits[$action] ) ) {
1632 return false;
1633 }
1634
1635 // Some groups shouldn't trigger the ping limiter, ever
1636 if ( !$this->isPingLimitable() ) {
1637 return false;
1638 }
1639
1640 global $wgMemc;
1641 wfProfileIn( __METHOD__ );
1642
1643 $limits = $wgRateLimits[$action];
1644 $keys = array();
1645 $id = $this->getId();
1646 $userLimit = false;
1647
1648 if ( isset( $limits['anon'] ) && $id == 0 ) {
1649 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1650 }
1651
1652 if ( isset( $limits['user'] ) && $id != 0 ) {
1653 $userLimit = $limits['user'];
1654 }
1655 if ( $this->isNewbie() ) {
1656 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1657 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1658 }
1659 if ( isset( $limits['ip'] ) ) {
1660 $ip = $this->getRequest()->getIP();
1661 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1662 }
1663 if ( isset( $limits['subnet'] ) ) {
1664 $ip = $this->getRequest()->getIP();
1665 $matches = array();
1666 $subnet = false;
1667 if ( IP::isIPv6( $ip ) ) {
1668 $parts = IP::parseRange( "$ip/64" );
1669 $subnet = $parts[0];
1670 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1671 // IPv4
1672 $subnet = $matches[1];
1673 }
1674 if ( $subnet !== false ) {
1675 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1676 }
1677 }
1678 }
1679 // Check for group-specific permissions
1680 // If more than one group applies, use the group with the highest limit
1681 foreach ( $this->getGroups() as $group ) {
1682 if ( isset( $limits[$group] ) ) {
1683 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1684 $userLimit = $limits[$group];
1685 }
1686 }
1687 }
1688 // Set the user limit key
1689 if ( $userLimit !== false ) {
1690 list( $max, $period ) = $userLimit;
1691 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1692 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1693 }
1694
1695 $triggered = false;
1696 foreach ( $keys as $key => $limit ) {
1697 list( $max, $period ) = $limit;
1698 $summary = "(limit $max in {$period}s)";
1699 $count = $wgMemc->get( $key );
1700 // Already pinged?
1701 if ( $count ) {
1702 if ( $count >= $max ) {
1703 wfDebugLog( 'ratelimit', $this->getName() . " tripped! $key at $count $summary" );
1704 $triggered = true;
1705 } else {
1706 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1707 }
1708 } else {
1709 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1710 if ( $incrBy > 0 ) {
1711 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1712 }
1713 }
1714 if ( $incrBy > 0 ) {
1715 $wgMemc->incr( $key, $incrBy );
1716 }
1717 }
1718
1719 wfProfileOut( __METHOD__ );
1720 return $triggered;
1721 }
1722
1723 /**
1724 * Check if user is blocked
1725 *
1726 * @param bool $bFromSlave Whether to check the slave database instead of the master
1727 * @return bool True if blocked, false otherwise
1728 */
1729 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1730 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1731 }
1732
1733 /**
1734 * Get the block affecting the user, or null if the user is not blocked
1735 *
1736 * @param bool $bFromSlave Whether to check the slave database instead of the master
1737 * @return Block|null
1738 */
1739 public function getBlock( $bFromSlave = true ) {
1740 $this->getBlockedStatus( $bFromSlave );
1741 return $this->mBlock instanceof Block ? $this->mBlock : null;
1742 }
1743
1744 /**
1745 * Check if user is blocked from editing a particular article
1746 *
1747 * @param Title $title Title to check
1748 * @param bool $bFromSlave whether to check the slave database instead of the master
1749 * @return bool
1750 */
1751 public function isBlockedFrom( $title, $bFromSlave = false ) {
1752 global $wgBlockAllowsUTEdit;
1753 wfProfileIn( __METHOD__ );
1754
1755 $blocked = $this->isBlocked( $bFromSlave );
1756 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1757 // If a user's name is suppressed, they cannot make edits anywhere
1758 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1759 && $title->getNamespace() == NS_USER_TALK ) {
1760 $blocked = false;
1761 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1762 }
1763
1764 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1765
1766 wfProfileOut( __METHOD__ );
1767 return $blocked;
1768 }
1769
1770 /**
1771 * If user is blocked, return the name of the user who placed the block
1772 * @return string Name of blocker
1773 */
1774 public function blockedBy() {
1775 $this->getBlockedStatus();
1776 return $this->mBlockedby;
1777 }
1778
1779 /**
1780 * If user is blocked, return the specified reason for the block
1781 * @return string Blocking reason
1782 */
1783 public function blockedFor() {
1784 $this->getBlockedStatus();
1785 return $this->mBlockreason;
1786 }
1787
1788 /**
1789 * If user is blocked, return the ID for the block
1790 * @return int Block ID
1791 */
1792 public function getBlockId() {
1793 $this->getBlockedStatus();
1794 return ( $this->mBlock ? $this->mBlock->getId() : false );
1795 }
1796
1797 /**
1798 * Check if user is blocked on all wikis.
1799 * Do not use for actual edit permission checks!
1800 * This is intended for quick UI checks.
1801 *
1802 * @param string $ip IP address, uses current client if none given
1803 * @return bool True if blocked, false otherwise
1804 */
1805 public function isBlockedGlobally( $ip = '' ) {
1806 if ( $this->mBlockedGlobally !== null ) {
1807 return $this->mBlockedGlobally;
1808 }
1809 // User is already an IP?
1810 if ( IP::isIPAddress( $this->getName() ) ) {
1811 $ip = $this->getName();
1812 } elseif ( !$ip ) {
1813 $ip = $this->getRequest()->getIP();
1814 }
1815 $blocked = false;
1816 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1817 $this->mBlockedGlobally = (bool)$blocked;
1818 return $this->mBlockedGlobally;
1819 }
1820
1821 /**
1822 * Check if user account is locked
1823 *
1824 * @return bool True if locked, false otherwise
1825 */
1826 public function isLocked() {
1827 if ( $this->mLocked !== null ) {
1828 return $this->mLocked;
1829 }
1830 global $wgAuth;
1831 StubObject::unstub( $wgAuth );
1832 $authUser = $wgAuth->getUserInstance( $this );
1833 $this->mLocked = (bool)$authUser->isLocked();
1834 return $this->mLocked;
1835 }
1836
1837 /**
1838 * Check if user account is hidden
1839 *
1840 * @return bool True if hidden, false otherwise
1841 */
1842 public function isHidden() {
1843 if ( $this->mHideName !== null ) {
1844 return $this->mHideName;
1845 }
1846 $this->getBlockedStatus();
1847 if ( !$this->mHideName ) {
1848 global $wgAuth;
1849 StubObject::unstub( $wgAuth );
1850 $authUser = $wgAuth->getUserInstance( $this );
1851 $this->mHideName = (bool)$authUser->isHidden();
1852 }
1853 return $this->mHideName;
1854 }
1855
1856 /**
1857 * Get the user's ID.
1858 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1859 */
1860 public function getId() {
1861 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1862 // Special case, we know the user is anonymous
1863 return 0;
1864 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1865 // Don't load if this was initialized from an ID
1866 $this->load();
1867 }
1868 return $this->mId;
1869 }
1870
1871 /**
1872 * Set the user and reload all fields according to a given ID
1873 * @param int $v User ID to reload
1874 */
1875 public function setId( $v ) {
1876 $this->mId = $v;
1877 $this->clearInstanceCache( 'id' );
1878 }
1879
1880 /**
1881 * Get the user name, or the IP of an anonymous user
1882 * @return string User's name or IP address
1883 */
1884 public function getName() {
1885 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1886 // Special case optimisation
1887 return $this->mName;
1888 } else {
1889 $this->load();
1890 if ( $this->mName === false ) {
1891 // Clean up IPs
1892 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1893 }
1894 return $this->mName;
1895 }
1896 }
1897
1898 /**
1899 * Set the user name.
1900 *
1901 * This does not reload fields from the database according to the given
1902 * name. Rather, it is used to create a temporary "nonexistent user" for
1903 * later addition to the database. It can also be used to set the IP
1904 * address for an anonymous user to something other than the current
1905 * remote IP.
1906 *
1907 * @note User::newFromName() has roughly the same function, when the named user
1908 * does not exist.
1909 * @param string $str New user name to set
1910 */
1911 public function setName( $str ) {
1912 $this->load();
1913 $this->mName = $str;
1914 }
1915
1916 /**
1917 * Get the user's name escaped by underscores.
1918 * @return string Username escaped by underscores.
1919 */
1920 public function getTitleKey() {
1921 return str_replace( ' ', '_', $this->getName() );
1922 }
1923
1924 /**
1925 * Check if the user has new messages.
1926 * @return bool True if the user has new messages
1927 */
1928 public function getNewtalk() {
1929 $this->load();
1930
1931 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1932 if ( $this->mNewtalk === -1 ) {
1933 $this->mNewtalk = false; # reset talk page status
1934
1935 // Check memcached separately for anons, who have no
1936 // entire User object stored in there.
1937 if ( !$this->mId ) {
1938 global $wgDisableAnonTalk;
1939 if ( $wgDisableAnonTalk ) {
1940 // Anon newtalk disabled by configuration.
1941 $this->mNewtalk = false;
1942 } else {
1943 global $wgMemc;
1944 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1945 $newtalk = $wgMemc->get( $key );
1946 if ( strval( $newtalk ) !== '' ) {
1947 $this->mNewtalk = (bool)$newtalk;
1948 } else {
1949 // Since we are caching this, make sure it is up to date by getting it
1950 // from the master
1951 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1952 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1953 }
1954 }
1955 } else {
1956 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1957 }
1958 }
1959
1960 return (bool)$this->mNewtalk;
1961 }
1962
1963 /**
1964 * Return the data needed to construct links for new talk page message
1965 * alerts. If there are new messages, this will return an associative array
1966 * with the following data:
1967 * wiki: The database name of the wiki
1968 * link: Root-relative link to the user's talk page
1969 * rev: The last talk page revision that the user has seen or null. This
1970 * is useful for building diff links.
1971 * If there are no new messages, it returns an empty array.
1972 * @note This function was designed to accomodate multiple talk pages, but
1973 * currently only returns a single link and revision.
1974 * @return Array
1975 */
1976 public function getNewMessageLinks() {
1977 $talks = array();
1978 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1979 return $talks;
1980 } elseif ( !$this->getNewtalk() ) {
1981 return array();
1982 }
1983 $utp = $this->getTalkPage();
1984 $dbr = wfGetDB( DB_SLAVE );
1985 // Get the "last viewed rev" timestamp from the oldest message notification
1986 $timestamp = $dbr->selectField( 'user_newtalk',
1987 'MIN(user_last_timestamp)',
1988 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1989 __METHOD__ );
1990 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1991 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1992 }
1993
1994 /**
1995 * Get the revision ID for the last talk page revision viewed by the talk
1996 * page owner.
1997 * @return int|null Revision ID or null
1998 */
1999 public function getNewMessageRevisionId() {
2000 $newMessageRevisionId = null;
2001 $newMessageLinks = $this->getNewMessageLinks();
2002 if ( $newMessageLinks ) {
2003 // Note: getNewMessageLinks() never returns more than a single link
2004 // and it is always for the same wiki, but we double-check here in
2005 // case that changes some time in the future.
2006 if ( count( $newMessageLinks ) === 1
2007 && $newMessageLinks[0]['wiki'] === wfWikiID()
2008 && $newMessageLinks[0]['rev']
2009 ) {
2010 $newMessageRevision = $newMessageLinks[0]['rev'];
2011 $newMessageRevisionId = $newMessageRevision->getId();
2012 }
2013 }
2014 return $newMessageRevisionId;
2015 }
2016
2017 /**
2018 * Internal uncached check for new messages
2019 *
2020 * @see getNewtalk()
2021 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2022 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2023 * @param bool $fromMaster true to fetch from the master, false for a slave
2024 * @return bool True if the user has new messages
2025 */
2026 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2027 if ( $fromMaster ) {
2028 $db = wfGetDB( DB_MASTER );
2029 } else {
2030 $db = wfGetDB( DB_SLAVE );
2031 }
2032 $ok = $db->selectField( 'user_newtalk', $field,
2033 array( $field => $id ), __METHOD__ );
2034 return $ok !== false;
2035 }
2036
2037 /**
2038 * Add or update the new messages flag
2039 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2040 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2041 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
2042 * @return bool True if successful, false otherwise
2043 */
2044 protected function updateNewtalk( $field, $id, $curRev = null ) {
2045 // Get timestamp of the talk page revision prior to the current one
2046 $prevRev = $curRev ? $curRev->getPrevious() : false;
2047 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2048 // Mark the user as having new messages since this revision
2049 $dbw = wfGetDB( DB_MASTER );
2050 $dbw->insert( 'user_newtalk',
2051 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2052 __METHOD__,
2053 'IGNORE' );
2054 if ( $dbw->affectedRows() ) {
2055 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2056 return true;
2057 } else {
2058 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2059 return false;
2060 }
2061 }
2062
2063 /**
2064 * Clear the new messages flag for the given user
2065 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2066 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2067 * @return bool True if successful, false otherwise
2068 */
2069 protected function deleteNewtalk( $field, $id ) {
2070 $dbw = wfGetDB( DB_MASTER );
2071 $dbw->delete( 'user_newtalk',
2072 array( $field => $id ),
2073 __METHOD__ );
2074 if ( $dbw->affectedRows() ) {
2075 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2076 return true;
2077 } else {
2078 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2079 return false;
2080 }
2081 }
2082
2083 /**
2084 * Update the 'You have new messages!' status.
2085 * @param bool $val Whether the user has new messages
2086 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
2087 */
2088 public function setNewtalk( $val, $curRev = null ) {
2089 if ( wfReadOnly() ) {
2090 return;
2091 }
2092
2093 $this->load();
2094 $this->mNewtalk = $val;
2095
2096 if ( $this->isAnon() ) {
2097 $field = 'user_ip';
2098 $id = $this->getName();
2099 } else {
2100 $field = 'user_id';
2101 $id = $this->getId();
2102 }
2103 global $wgMemc;
2104
2105 if ( $val ) {
2106 $changed = $this->updateNewtalk( $field, $id, $curRev );
2107 } else {
2108 $changed = $this->deleteNewtalk( $field, $id );
2109 }
2110
2111 if ( $this->isAnon() ) {
2112 // Anons have a separate memcached space, since
2113 // user records aren't kept for them.
2114 $key = wfMemcKey( 'newtalk', 'ip', $id );
2115 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
2116 }
2117 if ( $changed ) {
2118 $this->invalidateCache();
2119 }
2120 }
2121
2122 /**
2123 * Generate a current or new-future timestamp to be stored in the
2124 * user_touched field when we update things.
2125 * @return string Timestamp in TS_MW format
2126 */
2127 private static function newTouchedTimestamp() {
2128 global $wgClockSkewFudge;
2129 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2130 }
2131
2132 /**
2133 * Clear user data from memcached.
2134 * Use after applying fun updates to the database; caller's
2135 * responsibility to update user_touched if appropriate.
2136 *
2137 * Called implicitly from invalidateCache() and saveSettings().
2138 */
2139 private function clearSharedCache() {
2140 $this->load();
2141 if ( $this->mId ) {
2142 global $wgMemc;
2143 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2144 }
2145 }
2146
2147 /**
2148 * Immediately touch the user data cache for this account.
2149 * Updates user_touched field, and removes account data from memcached
2150 * for reload on the next hit.
2151 */
2152 public function invalidateCache() {
2153 if ( wfReadOnly() ) {
2154 return;
2155 }
2156 $this->load();
2157 if ( $this->mId ) {
2158 $this->mTouched = self::newTouchedTimestamp();
2159
2160 $dbw = wfGetDB( DB_MASTER );
2161 $userid = $this->mId;
2162 $touched = $this->mTouched;
2163 $method = __METHOD__;
2164 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2165 // Prevent contention slams by checking user_touched first
2166 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2167 $needsPurge = $dbw->selectField( 'user', '1',
2168 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2169 if ( $needsPurge ) {
2170 $dbw->update( 'user',
2171 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2172 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2173 $method
2174 );
2175 }
2176 } );
2177 $this->clearSharedCache();
2178 }
2179 }
2180
2181 /**
2182 * Validate the cache for this account.
2183 * @param string $timestamp A timestamp in TS_MW format
2184 * @return bool
2185 */
2186 public function validateCache( $timestamp ) {
2187 $this->load();
2188 return ( $timestamp >= $this->mTouched );
2189 }
2190
2191 /**
2192 * Get the user touched timestamp
2193 * @return string timestamp
2194 */
2195 public function getTouched() {
2196 $this->load();
2197 return $this->mTouched;
2198 }
2199
2200 /**
2201 * Set the password and reset the random token.
2202 * Calls through to authentication plugin if necessary;
2203 * will have no effect if the auth plugin refuses to
2204 * pass the change through or if the legal password
2205 * checks fail.
2206 *
2207 * As a special case, setting the password to null
2208 * wipes it, so the account cannot be logged in until
2209 * a new password is set, for instance via e-mail.
2210 *
2211 * @param string $str New password to set
2212 * @throws PasswordError on failure
2213 *
2214 * @return bool
2215 */
2216 public function setPassword( $str ) {
2217 global $wgAuth;
2218
2219 if ( $str !== null ) {
2220 if ( !$wgAuth->allowPasswordChange() ) {
2221 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2222 }
2223
2224 if ( !$this->isValidPassword( $str ) ) {
2225 global $wgMinimalPasswordLength;
2226 $valid = $this->getPasswordValidity( $str );
2227 if ( is_array( $valid ) ) {
2228 $message = array_shift( $valid );
2229 $params = $valid;
2230 } else {
2231 $message = $valid;
2232 $params = array( $wgMinimalPasswordLength );
2233 }
2234 throw new PasswordError( wfMessage( $message, $params )->text() );
2235 }
2236 }
2237
2238 if ( !$wgAuth->setPassword( $this, $str ) ) {
2239 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2240 }
2241
2242 $this->setInternalPassword( $str );
2243
2244 return true;
2245 }
2246
2247 /**
2248 * Set the password and reset the random token unconditionally.
2249 *
2250 * @param string|null $str New password to set or null to set an invalid
2251 * password hash meaning that the user will not be able to log in
2252 * through the web interface.
2253 */
2254 public function setInternalPassword( $str ) {
2255 $this->load();
2256 $this->setToken();
2257
2258 if ( $str === null ) {
2259 // Save an invalid hash...
2260 $this->mPassword = '';
2261 } else {
2262 $this->mPassword = self::crypt( $str );
2263 }
2264 $this->mNewpassword = '';
2265 $this->mNewpassTime = null;
2266 }
2267
2268 /**
2269 * Get the user's current token.
2270 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2271 * @return string Token
2272 */
2273 public function getToken( $forceCreation = true ) {
2274 $this->load();
2275 if ( !$this->mToken && $forceCreation ) {
2276 $this->setToken();
2277 }
2278 return $this->mToken;
2279 }
2280
2281 /**
2282 * Set the random token (used for persistent authentication)
2283 * Called from loadDefaults() among other places.
2284 *
2285 * @param string|bool $token If specified, set the token to this value
2286 */
2287 public function setToken( $token = false ) {
2288 $this->load();
2289 if ( !$token ) {
2290 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
2291 } else {
2292 $this->mToken = $token;
2293 }
2294 }
2295
2296 /**
2297 * Set the password for a password reminder or new account email
2298 *
2299 * @param $str New password to set or null to set an invalid
2300 * password hash meaning that the user will not be able to use it
2301 * @param bool $throttle If true, reset the throttle timestamp to the present
2302 */
2303 public function setNewpassword( $str, $throttle = true ) {
2304 $this->load();
2305
2306 if ( $str === null ) {
2307 $this->mNewpassword = '';
2308 $this->mNewpassTime = null;
2309 } else {
2310 $this->mNewpassword = self::crypt( $str );
2311 if ( $throttle ) {
2312 $this->mNewpassTime = wfTimestampNow();
2313 }
2314 }
2315 }
2316
2317 /**
2318 * Has password reminder email been sent within the last
2319 * $wgPasswordReminderResendTime hours?
2320 * @return bool
2321 */
2322 public function isPasswordReminderThrottled() {
2323 global $wgPasswordReminderResendTime;
2324 $this->load();
2325 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2326 return false;
2327 }
2328 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2329 return time() < $expiry;
2330 }
2331
2332 /**
2333 * Get the user's e-mail address
2334 * @return string User's email address
2335 */
2336 public function getEmail() {
2337 $this->load();
2338 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2339 return $this->mEmail;
2340 }
2341
2342 /**
2343 * Get the timestamp of the user's e-mail authentication
2344 * @return string TS_MW timestamp
2345 */
2346 public function getEmailAuthenticationTimestamp() {
2347 $this->load();
2348 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2349 return $this->mEmailAuthenticated;
2350 }
2351
2352 /**
2353 * Set the user's e-mail address
2354 * @param string $str New e-mail address
2355 */
2356 public function setEmail( $str ) {
2357 $this->load();
2358 if ( $str == $this->mEmail ) {
2359 return;
2360 }
2361 $this->mEmail = $str;
2362 $this->invalidateEmail();
2363 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2364 }
2365
2366 /**
2367 * Set the user's e-mail address and a confirmation mail if needed.
2368 *
2369 * @since 1.20
2370 * @param string $str New e-mail address
2371 * @return Status
2372 */
2373 public function setEmailWithConfirmation( $str ) {
2374 global $wgEnableEmail, $wgEmailAuthentication;
2375
2376 if ( !$wgEnableEmail ) {
2377 return Status::newFatal( 'emaildisabled' );
2378 }
2379
2380 $oldaddr = $this->getEmail();
2381 if ( $str === $oldaddr ) {
2382 return Status::newGood( true );
2383 }
2384
2385 $this->setEmail( $str );
2386
2387 if ( $str !== '' && $wgEmailAuthentication ) {
2388 // Send a confirmation request to the new address if needed
2389 $type = $oldaddr != '' ? 'changed' : 'set';
2390 $result = $this->sendConfirmationMail( $type );
2391 if ( $result->isGood() ) {
2392 // Say the the caller that a confirmation mail has been sent
2393 $result->value = 'eauth';
2394 }
2395 } else {
2396 $result = Status::newGood( true );
2397 }
2398
2399 return $result;
2400 }
2401
2402 /**
2403 * Get the user's real name
2404 * @return string User's real name
2405 */
2406 public function getRealName() {
2407 if ( !$this->isItemLoaded( 'realname' ) ) {
2408 $this->load();
2409 }
2410
2411 return $this->mRealName;
2412 }
2413
2414 /**
2415 * Set the user's real name
2416 * @param string $str New real name
2417 */
2418 public function setRealName( $str ) {
2419 $this->load();
2420 $this->mRealName = $str;
2421 }
2422
2423 /**
2424 * Get the user's current setting for a given option.
2425 *
2426 * @param string $oname The option to check
2427 * @param string $defaultOverride A default value returned if the option does not exist
2428 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2429 * @return string User's current value for the option
2430 * @see getBoolOption()
2431 * @see getIntOption()
2432 */
2433 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2434 global $wgHiddenPrefs;
2435 $this->loadOptions();
2436
2437 # We want 'disabled' preferences to always behave as the default value for
2438 # users, even if they have set the option explicitly in their settings (ie they
2439 # set it, and then it was disabled removing their ability to change it). But
2440 # we don't want to erase the preferences in the database in case the preference
2441 # is re-enabled again. So don't touch $mOptions, just override the returned value
2442 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2443 return self::getDefaultOption( $oname );
2444 }
2445
2446 if ( array_key_exists( $oname, $this->mOptions ) ) {
2447 return $this->mOptions[$oname];
2448 } else {
2449 return $defaultOverride;
2450 }
2451 }
2452
2453 /**
2454 * Get all user's options
2455 *
2456 * @return array
2457 */
2458 public function getOptions() {
2459 global $wgHiddenPrefs;
2460 $this->loadOptions();
2461 $options = $this->mOptions;
2462
2463 # We want 'disabled' preferences to always behave as the default value for
2464 # users, even if they have set the option explicitly in their settings (ie they
2465 # set it, and then it was disabled removing their ability to change it). But
2466 # we don't want to erase the preferences in the database in case the preference
2467 # is re-enabled again. So don't touch $mOptions, just override the returned value
2468 foreach ( $wgHiddenPrefs as $pref ) {
2469 $default = self::getDefaultOption( $pref );
2470 if ( $default !== null ) {
2471 $options[$pref] = $default;
2472 }
2473 }
2474
2475 return $options;
2476 }
2477
2478 /**
2479 * Get the user's current setting for a given option, as a boolean value.
2480 *
2481 * @param string $oname The option to check
2482 * @return bool User's current value for the option
2483 * @see getOption()
2484 */
2485 public function getBoolOption( $oname ) {
2486 return (bool)$this->getOption( $oname );
2487 }
2488
2489 /**
2490 * Get the user's current setting for a given option, as an integer value.
2491 *
2492 * @param string $oname The option to check
2493 * @param int $defaultOverride A default value returned if the option does not exist
2494 * @return int User's current value for the option
2495 * @see getOption()
2496 */
2497 public function getIntOption( $oname, $defaultOverride = 0 ) {
2498 $val = $this->getOption( $oname );
2499 if ( $val == '' ) {
2500 $val = $defaultOverride;
2501 }
2502 return intval( $val );
2503 }
2504
2505 /**
2506 * Set the given option for a user.
2507 *
2508 * @param string $oname The option to set
2509 * @param mixed $val New value to set
2510 */
2511 public function setOption( $oname, $val ) {
2512 $this->loadOptions();
2513
2514 // Explicitly NULL values should refer to defaults
2515 if ( is_null( $val ) ) {
2516 $val = self::getDefaultOption( $oname );
2517 }
2518
2519 $this->mOptions[$oname] = $val;
2520 }
2521
2522 /**
2523 * Get a token stored in the preferences (like the watchlist one),
2524 * resetting it if it's empty (and saving changes).
2525 *
2526 * @param string $oname The option name to retrieve the token from
2527 * @return string|bool User's current value for the option, or false if this option is disabled.
2528 * @see resetTokenFromOption()
2529 * @see getOption()
2530 */
2531 public function getTokenFromOption( $oname ) {
2532 global $wgHiddenPrefs;
2533 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2534 return false;
2535 }
2536
2537 $token = $this->getOption( $oname );
2538 if ( !$token ) {
2539 $token = $this->resetTokenFromOption( $oname );
2540 $this->saveSettings();
2541 }
2542 return $token;
2543 }
2544
2545 /**
2546 * Reset a token stored in the preferences (like the watchlist one).
2547 * *Does not* save user's preferences (similarly to setOption()).
2548 *
2549 * @param string $oname The option name to reset the token in
2550 * @return string|bool New token value, or false if this option is disabled.
2551 * @see getTokenFromOption()
2552 * @see setOption()
2553 */
2554 public function resetTokenFromOption( $oname ) {
2555 global $wgHiddenPrefs;
2556 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2557 return false;
2558 }
2559
2560 $token = MWCryptRand::generateHex( 40 );
2561 $this->setOption( $oname, $token );
2562 return $token;
2563 }
2564
2565 /**
2566 * Return a list of the types of user options currently returned by
2567 * User::getOptionKinds().
2568 *
2569 * Currently, the option kinds are:
2570 * - 'registered' - preferences which are registered in core MediaWiki or
2571 * by extensions using the UserGetDefaultOptions hook.
2572 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2573 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2574 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2575 * be used by user scripts.
2576 * - 'special' - "preferences" that are not accessible via User::getOptions
2577 * or User::setOptions.
2578 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2579 * These are usually legacy options, removed in newer versions.
2580 *
2581 * The API (and possibly others) use this function to determine the possible
2582 * option types for validation purposes, so make sure to update this when a
2583 * new option kind is added.
2584 *
2585 * @see User::getOptionKinds
2586 * @return array Option kinds
2587 */
2588 public static function listOptionKinds() {
2589 return array(
2590 'registered',
2591 'registered-multiselect',
2592 'registered-checkmatrix',
2593 'userjs',
2594 'special',
2595 'unused'
2596 );
2597 }
2598
2599 /**
2600 * Return an associative array mapping preferences keys to the kind of a preference they're
2601 * used for. Different kinds are handled differently when setting or reading preferences.
2602 *
2603 * See User::listOptionKinds for the list of valid option types that can be provided.
2604 *
2605 * @see User::listOptionKinds
2606 * @param $context IContextSource
2607 * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2608 * @return array the key => kind mapping data
2609 */
2610 public function getOptionKinds( IContextSource $context, $options = null ) {
2611 $this->loadOptions();
2612 if ( $options === null ) {
2613 $options = $this->mOptions;
2614 }
2615
2616 $prefs = Preferences::getPreferences( $this, $context );
2617 $mapping = array();
2618
2619 // Pull out the "special" options, so they don't get converted as
2620 // multiselect or checkmatrix.
2621 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2622 foreach ( $specialOptions as $name => $value ) {
2623 unset( $prefs[$name] );
2624 }
2625
2626 // Multiselect and checkmatrix options are stored in the database with
2627 // one key per option, each having a boolean value. Extract those keys.
2628 $multiselectOptions = array();
2629 foreach ( $prefs as $name => $info ) {
2630 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2631 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2632 $opts = HTMLFormField::flattenOptions( $info['options'] );
2633 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2634
2635 foreach ( $opts as $value ) {
2636 $multiselectOptions["$prefix$value"] = true;
2637 }
2638
2639 unset( $prefs[$name] );
2640 }
2641 }
2642 $checkmatrixOptions = array();
2643 foreach ( $prefs as $name => $info ) {
2644 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2645 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2646 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2647 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2648 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2649
2650 foreach ( $columns as $column ) {
2651 foreach ( $rows as $row ) {
2652 $checkmatrixOptions["$prefix-$column-$row"] = true;
2653 }
2654 }
2655
2656 unset( $prefs[$name] );
2657 }
2658 }
2659
2660 // $value is ignored
2661 foreach ( $options as $key => $value ) {
2662 if ( isset( $prefs[$key] ) ) {
2663 $mapping[$key] = 'registered';
2664 } elseif ( isset( $multiselectOptions[$key] ) ) {
2665 $mapping[$key] = 'registered-multiselect';
2666 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2667 $mapping[$key] = 'registered-checkmatrix';
2668 } elseif ( isset( $specialOptions[$key] ) ) {
2669 $mapping[$key] = 'special';
2670 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2671 $mapping[$key] = 'userjs';
2672 } else {
2673 $mapping[$key] = 'unused';
2674 }
2675 }
2676
2677 return $mapping;
2678 }
2679
2680 /**
2681 * Reset certain (or all) options to the site defaults
2682 *
2683 * The optional parameter determines which kinds of preferences will be reset.
2684 * Supported values are everything that can be reported by getOptionKinds()
2685 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2686 *
2687 * @param array|string $resetKinds which kinds of preferences to reset. Defaults to
2688 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2689 * for backwards-compatibility.
2690 * @param $context IContextSource|null context source used when $resetKinds
2691 * does not contain 'all', passed to getOptionKinds().
2692 * Defaults to RequestContext::getMain() when null.
2693 */
2694 public function resetOptions(
2695 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2696 IContextSource $context = null
2697 ) {
2698 $this->load();
2699 $defaultOptions = self::getDefaultOptions();
2700
2701 if ( !is_array( $resetKinds ) ) {
2702 $resetKinds = array( $resetKinds );
2703 }
2704
2705 if ( in_array( 'all', $resetKinds ) ) {
2706 $newOptions = $defaultOptions;
2707 } else {
2708 if ( $context === null ) {
2709 $context = RequestContext::getMain();
2710 }
2711
2712 $optionKinds = $this->getOptionKinds( $context );
2713 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2714 $newOptions = array();
2715
2716 // Use default values for the options that should be deleted, and
2717 // copy old values for the ones that shouldn't.
2718 foreach ( $this->mOptions as $key => $value ) {
2719 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2720 if ( array_key_exists( $key, $defaultOptions ) ) {
2721 $newOptions[$key] = $defaultOptions[$key];
2722 }
2723 } else {
2724 $newOptions[$key] = $value;
2725 }
2726 }
2727 }
2728
2729 $this->mOptions = $newOptions;
2730 $this->mOptionsLoaded = true;
2731 }
2732
2733 /**
2734 * Get the user's preferred date format.
2735 * @return string User's preferred date format
2736 */
2737 public function getDatePreference() {
2738 // Important migration for old data rows
2739 if ( is_null( $this->mDatePreference ) ) {
2740 global $wgLang;
2741 $value = $this->getOption( 'date' );
2742 $map = $wgLang->getDatePreferenceMigrationMap();
2743 if ( isset( $map[$value] ) ) {
2744 $value = $map[$value];
2745 }
2746 $this->mDatePreference = $value;
2747 }
2748 return $this->mDatePreference;
2749 }
2750
2751 /**
2752 * Determine based on the wiki configuration and the user's options,
2753 * whether this user must be over HTTPS no matter what.
2754 *
2755 * @return bool
2756 */
2757 public function requiresHTTPS() {
2758 global $wgSecureLogin;
2759 if ( !$wgSecureLogin ) {
2760 return false;
2761 } else {
2762 $https = $this->getBoolOption( 'prefershttps' );
2763 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2764 if ( $https ) {
2765 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2766 }
2767 return $https;
2768 }
2769 }
2770
2771 /**
2772 * Get the user preferred stub threshold
2773 *
2774 * @return int
2775 */
2776 public function getStubThreshold() {
2777 global $wgMaxArticleSize; # Maximum article size, in Kb
2778 $threshold = $this->getIntOption( 'stubthreshold' );
2779 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2780 // If they have set an impossible value, disable the preference
2781 // so we can use the parser cache again.
2782 $threshold = 0;
2783 }
2784 return $threshold;
2785 }
2786
2787 /**
2788 * Get the permissions this user has.
2789 * @return Array of String permission names
2790 */
2791 public function getRights() {
2792 if ( is_null( $this->mRights ) ) {
2793 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2794 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2795 // Force reindexation of rights when a hook has unset one of them
2796 $this->mRights = array_values( array_unique( $this->mRights ) );
2797 }
2798 return $this->mRights;
2799 }
2800
2801 /**
2802 * Get the list of explicit group memberships this user has.
2803 * The implicit * and user groups are not included.
2804 * @return Array of String internal group names
2805 */
2806 public function getGroups() {
2807 $this->load();
2808 $this->loadGroups();
2809 return $this->mGroups;
2810 }
2811
2812 /**
2813 * Get the list of implicit group memberships this user has.
2814 * This includes all explicit groups, plus 'user' if logged in,
2815 * '*' for all accounts, and autopromoted groups
2816 * @param bool $recache Whether to avoid the cache
2817 * @return Array of String internal group names
2818 */
2819 public function getEffectiveGroups( $recache = false ) {
2820 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2821 wfProfileIn( __METHOD__ );
2822 $this->mEffectiveGroups = array_unique( array_merge(
2823 $this->getGroups(), // explicit groups
2824 $this->getAutomaticGroups( $recache ) // implicit groups
2825 ) );
2826 // Hook for additional groups
2827 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2828 // Force reindexation of groups when a hook has unset one of them
2829 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2830 wfProfileOut( __METHOD__ );
2831 }
2832 return $this->mEffectiveGroups;
2833 }
2834
2835 /**
2836 * Get the list of implicit group memberships this user has.
2837 * This includes 'user' if logged in, '*' for all accounts,
2838 * and autopromoted groups
2839 * @param bool $recache Whether to avoid the cache
2840 * @return Array of String internal group names
2841 */
2842 public function getAutomaticGroups( $recache = false ) {
2843 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2844 wfProfileIn( __METHOD__ );
2845 $this->mImplicitGroups = array( '*' );
2846 if ( $this->getId() ) {
2847 $this->mImplicitGroups[] = 'user';
2848
2849 $this->mImplicitGroups = array_unique( array_merge(
2850 $this->mImplicitGroups,
2851 Autopromote::getAutopromoteGroups( $this )
2852 ) );
2853 }
2854 if ( $recache ) {
2855 // Assure data consistency with rights/groups,
2856 // as getEffectiveGroups() depends on this function
2857 $this->mEffectiveGroups = null;
2858 }
2859 wfProfileOut( __METHOD__ );
2860 }
2861 return $this->mImplicitGroups;
2862 }
2863
2864 /**
2865 * Returns the groups the user has belonged to.
2866 *
2867 * The user may still belong to the returned groups. Compare with getGroups().
2868 *
2869 * The function will not return groups the user had belonged to before MW 1.17
2870 *
2871 * @return array Names of the groups the user has belonged to.
2872 */
2873 public function getFormerGroups() {
2874 if ( is_null( $this->mFormerGroups ) ) {
2875 $dbr = wfGetDB( DB_MASTER );
2876 $res = $dbr->select( 'user_former_groups',
2877 array( 'ufg_group' ),
2878 array( 'ufg_user' => $this->mId ),
2879 __METHOD__ );
2880 $this->mFormerGroups = array();
2881 foreach ( $res as $row ) {
2882 $this->mFormerGroups[] = $row->ufg_group;
2883 }
2884 }
2885 return $this->mFormerGroups;
2886 }
2887
2888 /**
2889 * Get the user's edit count.
2890 * @return int, null for anonymous users
2891 */
2892 public function getEditCount() {
2893 if ( !$this->getId() ) {
2894 return null;
2895 }
2896
2897 if ( !isset( $this->mEditCount ) ) {
2898 /* Populate the count, if it has not been populated yet */
2899 wfProfileIn( __METHOD__ );
2900 $dbr = wfGetDB( DB_SLAVE );
2901 // check if the user_editcount field has been initialized
2902 $count = $dbr->selectField(
2903 'user', 'user_editcount',
2904 array( 'user_id' => $this->mId ),
2905 __METHOD__
2906 );
2907
2908 if ( $count === null ) {
2909 // it has not been initialized. do so.
2910 $count = $this->initEditCount();
2911 }
2912 $this->mEditCount = $count;
2913 wfProfileOut( __METHOD__ );
2914 }
2915 return (int)$this->mEditCount;
2916 }
2917
2918 /**
2919 * Add the user to the given group.
2920 * This takes immediate effect.
2921 * @param string $group Name of the group to add
2922 */
2923 public function addGroup( $group ) {
2924 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2925 $dbw = wfGetDB( DB_MASTER );
2926 if ( $this->getId() ) {
2927 $dbw->insert( 'user_groups',
2928 array(
2929 'ug_user' => $this->getID(),
2930 'ug_group' => $group,
2931 ),
2932 __METHOD__,
2933 array( 'IGNORE' ) );
2934 }
2935 }
2936 $this->loadGroups();
2937 $this->mGroups[] = $group;
2938 // In case loadGroups was not called before, we now have the right twice.
2939 // Get rid of the duplicate.
2940 $this->mGroups = array_unique( $this->mGroups );
2941
2942 // Refresh the groups caches, and clear the rights cache so it will be
2943 // refreshed on the next call to $this->getRights().
2944 $this->getEffectiveGroups( true );
2945 $this->mRights = null;
2946
2947 $this->invalidateCache();
2948 }
2949
2950 /**
2951 * Remove the user from the given group.
2952 * This takes immediate effect.
2953 * @param string $group Name of the group to remove
2954 */
2955 public function removeGroup( $group ) {
2956 $this->load();
2957 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2958 $dbw = wfGetDB( DB_MASTER );
2959 $dbw->delete( 'user_groups',
2960 array(
2961 'ug_user' => $this->getID(),
2962 'ug_group' => $group,
2963 ), __METHOD__ );
2964 // Remember that the user was in this group
2965 $dbw->insert( 'user_former_groups',
2966 array(
2967 'ufg_user' => $this->getID(),
2968 'ufg_group' => $group,
2969 ),
2970 __METHOD__,
2971 array( 'IGNORE' ) );
2972 }
2973 $this->loadGroups();
2974 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2975
2976 // Refresh the groups caches, and clear the rights cache so it will be
2977 // refreshed on the next call to $this->getRights().
2978 $this->getEffectiveGroups( true );
2979 $this->mRights = null;
2980
2981 $this->invalidateCache();
2982 }
2983
2984 /**
2985 * Get whether the user is logged in
2986 * @return bool
2987 */
2988 public function isLoggedIn() {
2989 return $this->getID() != 0;
2990 }
2991
2992 /**
2993 * Get whether the user is anonymous
2994 * @return bool
2995 */
2996 public function isAnon() {
2997 return !$this->isLoggedIn();
2998 }
2999
3000 /**
3001 * Check if user is allowed to access a feature / make an action
3002 *
3003 * @internal param \String $varargs permissions to test
3004 * @return boolean: True if user is allowed to perform *any* of the given actions
3005 *
3006 * @return bool
3007 */
3008 public function isAllowedAny( /*...*/ ) {
3009 $permissions = func_get_args();
3010 foreach ( $permissions as $permission ) {
3011 if ( $this->isAllowed( $permission ) ) {
3012 return true;
3013 }
3014 }
3015 return false;
3016 }
3017
3018 /**
3019 *
3020 * @internal param $varargs string
3021 * @return bool True if the user is allowed to perform *all* of the given actions
3022 */
3023 public function isAllowedAll( /*...*/ ) {
3024 $permissions = func_get_args();
3025 foreach ( $permissions as $permission ) {
3026 if ( !$this->isAllowed( $permission ) ) {
3027 return false;
3028 }
3029 }
3030 return true;
3031 }
3032
3033 /**
3034 * Internal mechanics of testing a permission
3035 * @param string $action
3036 * @return bool
3037 */
3038 public function isAllowed( $action = '' ) {
3039 if ( $action === '' ) {
3040 return true; // In the spirit of DWIM
3041 }
3042 // Patrolling may not be enabled
3043 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3044 global $wgUseRCPatrol, $wgUseNPPatrol;
3045 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3046 return false;
3047 }
3048 }
3049 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3050 // by misconfiguration: 0 == 'foo'
3051 return in_array( $action, $this->getRights(), true );
3052 }
3053
3054 /**
3055 * Check whether to enable recent changes patrol features for this user
3056 * @return boolean: True or false
3057 */
3058 public function useRCPatrol() {
3059 global $wgUseRCPatrol;
3060 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3061 }
3062
3063 /**
3064 * Check whether to enable new pages patrol features for this user
3065 * @return bool True or false
3066 */
3067 public function useNPPatrol() {
3068 global $wgUseRCPatrol, $wgUseNPPatrol;
3069 return (
3070 ( $wgUseRCPatrol || $wgUseNPPatrol )
3071 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3072 );
3073 }
3074
3075 /**
3076 * Get the WebRequest object to use with this object
3077 *
3078 * @return WebRequest
3079 */
3080 public function getRequest() {
3081 if ( $this->mRequest ) {
3082 return $this->mRequest;
3083 } else {
3084 global $wgRequest;
3085 return $wgRequest;
3086 }
3087 }
3088
3089 /**
3090 * Get the current skin, loading it if required
3091 * @return Skin The current skin
3092 * @todo FIXME: Need to check the old failback system [AV]
3093 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3094 */
3095 public function getSkin() {
3096 wfDeprecated( __METHOD__, '1.18' );
3097 return RequestContext::getMain()->getSkin();
3098 }
3099
3100 /**
3101 * Get a WatchedItem for this user and $title.
3102 *
3103 * @since 1.22 $checkRights parameter added
3104 * @param $title Title
3105 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3106 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3107 * @return WatchedItem
3108 */
3109 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3110 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3111
3112 if ( isset( $this->mWatchedItems[$key] ) ) {
3113 return $this->mWatchedItems[$key];
3114 }
3115
3116 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3117 $this->mWatchedItems = array();
3118 }
3119
3120 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3121 return $this->mWatchedItems[$key];
3122 }
3123
3124 /**
3125 * Check the watched status of an article.
3126 * @since 1.22 $checkRights parameter added
3127 * @param $title Title of the article to look at
3128 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3129 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3130 * @return bool
3131 */
3132 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3133 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3134 }
3135
3136 /**
3137 * Watch an article.
3138 * @since 1.22 $checkRights parameter added
3139 * @param $title Title of the article to look at
3140 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3141 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3142 */
3143 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3144 $this->getWatchedItem( $title, $checkRights )->addWatch();
3145 $this->invalidateCache();
3146 }
3147
3148 /**
3149 * Stop watching an article.
3150 * @since 1.22 $checkRights parameter added
3151 * @param $title Title of the article to look at
3152 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3153 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3154 */
3155 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3156 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3157 $this->invalidateCache();
3158 }
3159
3160 /**
3161 * Clear the user's notification timestamp for the given title.
3162 * If e-notif e-mails are on, they will receive notification mails on
3163 * the next change of the page if it's watched etc.
3164 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3165 * @param $title Title of the article to look at
3166 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3167 */
3168 public function clearNotification( &$title, $oldid = 0 ) {
3169 global $wgUseEnotif, $wgShowUpdatedMarker;
3170
3171 // Do nothing if the database is locked to writes
3172 if ( wfReadOnly() ) {
3173 return;
3174 }
3175
3176 // Do nothing if not allowed to edit the watchlist
3177 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3178 return;
3179 }
3180
3181 // If we're working on user's talk page, we should update the talk page message indicator
3182 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3183 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3184 return;
3185 }
3186
3187 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3188
3189 if ( !$oldid || !$nextid ) {
3190 // If we're looking at the latest revision, we should definitely clear it
3191 $this->setNewtalk( false );
3192 } else {
3193 // Otherwise we should update its revision, if it's present
3194 if ( $this->getNewtalk() ) {
3195 // Naturally the other one won't clear by itself
3196 $this->setNewtalk( false );
3197 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3198 }
3199 }
3200 }
3201
3202 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3203 return;
3204 }
3205
3206 if ( $this->isAnon() ) {
3207 // Nothing else to do...
3208 return;
3209 }
3210
3211 // Only update the timestamp if the page is being watched.
3212 // The query to find out if it is watched is cached both in memcached and per-invocation,
3213 // and when it does have to be executed, it can be on a slave
3214 // If this is the user's newtalk page, we always update the timestamp
3215 $force = '';
3216 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3217 $force = 'force';
3218 }
3219
3220 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3221 }
3222
3223 /**
3224 * Resets all of the given user's page-change notification timestamps.
3225 * If e-notif e-mails are on, they will receive notification mails on
3226 * the next change of any watched page.
3227 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3228 */
3229 public function clearAllNotifications() {
3230 if ( wfReadOnly() ) {
3231 return;
3232 }
3233
3234 // Do nothing if not allowed to edit the watchlist
3235 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3236 return;
3237 }
3238
3239 global $wgUseEnotif, $wgShowUpdatedMarker;
3240 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3241 $this->setNewtalk( false );
3242 return;
3243 }
3244 $id = $this->getId();
3245 if ( $id != 0 ) {
3246 $dbw = wfGetDB( DB_MASTER );
3247 $dbw->update( 'watchlist',
3248 array( /* SET */ 'wl_notificationtimestamp' => null ),
3249 array( /* WHERE */ 'wl_user' => $id ),
3250 __METHOD__
3251 );
3252 // We also need to clear here the "you have new message" notification for the own user_talk page;
3253 // it's cleared one page view later in WikiPage::doViewUpdates().
3254 }
3255 }
3256
3257 /**
3258 * Set this user's options from an encoded string
3259 * @param string $str Encoded options to import
3260 *
3261 * @deprecated since 1.19 due to removal of user_options from the user table
3262 */
3263 private function decodeOptions( $str ) {
3264 wfDeprecated( __METHOD__, '1.19' );
3265 if ( !$str ) {
3266 return;
3267 }
3268
3269 $this->mOptionsLoaded = true;
3270 $this->mOptionOverrides = array();
3271
3272 // If an option is not set in $str, use the default value
3273 $this->mOptions = self::getDefaultOptions();
3274
3275 $a = explode( "\n", $str );
3276 foreach ( $a as $s ) {
3277 $m = array();
3278 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3279 $this->mOptions[$m[1]] = $m[2];
3280 $this->mOptionOverrides[$m[1]] = $m[2];
3281 }
3282 }
3283 }
3284
3285 /**
3286 * Set a cookie on the user's client. Wrapper for
3287 * WebResponse::setCookie
3288 * @param string $name Name of the cookie to set
3289 * @param string $value Value to set
3290 * @param int $exp Expiration time, as a UNIX time value;
3291 * if 0 or not specified, use the default $wgCookieExpiration
3292 * @param bool $secure
3293 * true: Force setting the secure attribute when setting the cookie
3294 * false: Force NOT setting the secure attribute when setting the cookie
3295 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3296 * @param array $params Array of options sent passed to WebResponse::setcookie()
3297 */
3298 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3299 $params['secure'] = $secure;
3300 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3301 }
3302
3303 /**
3304 * Clear a cookie on the user's client
3305 * @param string $name Name of the cookie to clear
3306 * @param bool $secure
3307 * true: Force setting the secure attribute when setting the cookie
3308 * false: Force NOT setting the secure attribute when setting the cookie
3309 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3310 * @param array $params Array of options sent passed to WebResponse::setcookie()
3311 */
3312 protected function clearCookie( $name, $secure = null, $params = array() ) {
3313 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3314 }
3315
3316 /**
3317 * Set the default cookies for this session on the user's client.
3318 *
3319 * @param $request WebRequest object to use; $wgRequest will be used if null
3320 * is passed.
3321 * @param bool $secure Whether to force secure/insecure cookies or use default
3322 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3323 */
3324 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3325 if ( $request === null ) {
3326 $request = $this->getRequest();
3327 }
3328
3329 $this->load();
3330 if ( 0 == $this->mId ) {
3331 return;
3332 }
3333 if ( !$this->mToken ) {
3334 // When token is empty or NULL generate a new one and then save it to the database
3335 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3336 // Simply by setting every cell in the user_token column to NULL and letting them be
3337 // regenerated as users log back into the wiki.
3338 $this->setToken();
3339 $this->saveSettings();
3340 }
3341 $session = array(
3342 'wsUserID' => $this->mId,
3343 'wsToken' => $this->mToken,
3344 'wsUserName' => $this->getName()
3345 );
3346 $cookies = array(
3347 'UserID' => $this->mId,
3348 'UserName' => $this->getName(),
3349 );
3350 if ( $rememberMe ) {
3351 $cookies['Token'] = $this->mToken;
3352 } else {
3353 $cookies['Token'] = false;
3354 }
3355
3356 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3357
3358 foreach ( $session as $name => $value ) {
3359 $request->setSessionData( $name, $value );
3360 }
3361 foreach ( $cookies as $name => $value ) {
3362 if ( $value === false ) {
3363 $this->clearCookie( $name );
3364 } else {
3365 $this->setCookie( $name, $value, 0, $secure );
3366 }
3367 }
3368
3369 /**
3370 * If wpStickHTTPS was selected, also set an insecure cookie that
3371 * will cause the site to redirect the user to HTTPS, if they access
3372 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3373 * as the one set by centralauth (bug 53538). Also set it to session, or
3374 * standard time setting, based on if rememberme was set.
3375 */
3376 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3377 $this->setCookie(
3378 'forceHTTPS',
3379 'true',
3380 $rememberMe ? 0 : null,
3381 false,
3382 array( 'prefix' => '' ) // no prefix
3383 );
3384 }
3385 }
3386
3387 /**
3388 * Log this user out.
3389 */
3390 public function logout() {
3391 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3392 $this->doLogout();
3393 }
3394 }
3395
3396 /**
3397 * Clear the user's cookies and session, and reset the instance cache.
3398 * @see logout()
3399 */
3400 public function doLogout() {
3401 $this->clearInstanceCache( 'defaults' );
3402
3403 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3404
3405 $this->clearCookie( 'UserID' );
3406 $this->clearCookie( 'Token' );
3407 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3408
3409 // Remember when user logged out, to prevent seeing cached pages
3410 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3411 }
3412
3413 /**
3414 * Save this user's settings into the database.
3415 * @todo Only rarely do all these fields need to be set!
3416 */
3417 public function saveSettings() {
3418 global $wgAuth;
3419
3420 $this->load();
3421 if ( wfReadOnly() ) {
3422 return;
3423 }
3424 if ( 0 == $this->mId ) {
3425 return;
3426 }
3427
3428 $this->mTouched = self::newTouchedTimestamp();
3429 if ( !$wgAuth->allowSetLocalPassword() ) {
3430 $this->mPassword = '';
3431 }
3432
3433 $dbw = wfGetDB( DB_MASTER );
3434 $dbw->update( 'user',
3435 array( /* SET */
3436 'user_name' => $this->mName,
3437 'user_password' => $this->mPassword,
3438 'user_newpassword' => $this->mNewpassword,
3439 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3440 'user_real_name' => $this->mRealName,
3441 'user_email' => $this->mEmail,
3442 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3443 'user_touched' => $dbw->timestamp( $this->mTouched ),
3444 'user_token' => strval( $this->mToken ),
3445 'user_email_token' => $this->mEmailToken,
3446 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3447 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3448 ), array( /* WHERE */
3449 'user_id' => $this->mId
3450 ), __METHOD__
3451 );
3452
3453 $this->saveOptions();
3454
3455 wfRunHooks( 'UserSaveSettings', array( $this ) );
3456 $this->clearSharedCache();
3457 $this->getUserPage()->invalidateCache();
3458 }
3459
3460 /**
3461 * If only this user's username is known, and it exists, return the user ID.
3462 * @return int
3463 */
3464 public function idForName() {
3465 $s = trim( $this->getName() );
3466 if ( $s === '' ) {
3467 return 0;
3468 }
3469
3470 $dbr = wfGetDB( DB_SLAVE );
3471 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3472 if ( $id === false ) {
3473 $id = 0;
3474 }
3475 return $id;
3476 }
3477
3478 /**
3479 * Add a user to the database, return the user object
3480 *
3481 * @param string $name Username to add
3482 * @param array $params of Strings Non-default parameters to save to the database as user_* fields:
3483 * - password The user's password hash. Password logins will be disabled if this is omitted.
3484 * - newpassword Hash for a temporary password that has been mailed to the user
3485 * - email The user's email address
3486 * - email_authenticated The email authentication timestamp
3487 * - real_name The user's real name
3488 * - options An associative array of non-default options
3489 * - token Random authentication token. Do not set.
3490 * - registration Registration timestamp. Do not set.
3491 *
3492 * @return User object, or null if the username already exists
3493 */
3494 public static function createNew( $name, $params = array() ) {
3495 $user = new User;
3496 $user->load();
3497 $user->setToken(); // init token
3498 if ( isset( $params['options'] ) ) {
3499 $user->mOptions = $params['options'] + (array)$user->mOptions;
3500 unset( $params['options'] );
3501 }
3502 $dbw = wfGetDB( DB_MASTER );
3503 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3504
3505 $fields = array(
3506 'user_id' => $seqVal,
3507 'user_name' => $name,
3508 'user_password' => $user->mPassword,
3509 'user_newpassword' => $user->mNewpassword,
3510 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3511 'user_email' => $user->mEmail,
3512 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3513 'user_real_name' => $user->mRealName,
3514 'user_token' => strval( $user->mToken ),
3515 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3516 'user_editcount' => 0,
3517 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3518 );
3519 foreach ( $params as $name => $value ) {
3520 $fields["user_$name"] = $value;
3521 }
3522 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3523 if ( $dbw->affectedRows() ) {
3524 $newUser = User::newFromId( $dbw->insertId() );
3525 } else {
3526 $newUser = null;
3527 }
3528 return $newUser;
3529 }
3530
3531 /**
3532 * Add this existing user object to the database. If the user already
3533 * exists, a fatal status object is returned, and the user object is
3534 * initialised with the data from the database.
3535 *
3536 * Previously, this function generated a DB error due to a key conflict
3537 * if the user already existed. Many extension callers use this function
3538 * in code along the lines of:
3539 *
3540 * $user = User::newFromName( $name );
3541 * if ( !$user->isLoggedIn() ) {
3542 * $user->addToDatabase();
3543 * }
3544 * // do something with $user...
3545 *
3546 * However, this was vulnerable to a race condition (bug 16020). By
3547 * initialising the user object if the user exists, we aim to support this
3548 * calling sequence as far as possible.
3549 *
3550 * Note that if the user exists, this function will acquire a write lock,
3551 * so it is still advisable to make the call conditional on isLoggedIn(),
3552 * and to commit the transaction after calling.
3553 *
3554 * @throws MWException
3555 * @return Status
3556 */
3557 public function addToDatabase() {
3558 $this->load();
3559 if ( !$this->mToken ) {
3560 $this->setToken(); // init token
3561 }
3562
3563 $this->mTouched = self::newTouchedTimestamp();
3564
3565 $dbw = wfGetDB( DB_MASTER );
3566 $inWrite = $dbw->writesOrCallbacksPending();
3567 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3568 $dbw->insert( 'user',
3569 array(
3570 'user_id' => $seqVal,
3571 'user_name' => $this->mName,
3572 'user_password' => $this->mPassword,
3573 'user_newpassword' => $this->mNewpassword,
3574 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3575 'user_email' => $this->mEmail,
3576 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3577 'user_real_name' => $this->mRealName,
3578 'user_token' => strval( $this->mToken ),
3579 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3580 'user_editcount' => 0,
3581 'user_touched' => $dbw->timestamp( $this->mTouched ),
3582 ), __METHOD__,
3583 array( 'IGNORE' )
3584 );
3585 if ( !$dbw->affectedRows() ) {
3586 if ( !$inWrite ) {
3587 // XXX: Get out of REPEATABLE-READ so the SELECT below works.
3588 // Often this case happens early in views before any writes.
3589 // This shows up at least with CentralAuth.
3590 $dbw->commit( __METHOD__, 'flush' );
3591 }
3592 $this->mId = $dbw->selectField( 'user', 'user_id',
3593 array( 'user_name' => $this->mName ), __METHOD__ );
3594 $loaded = false;
3595 if ( $this->mId ) {
3596 if ( $this->loadFromDatabase() ) {
3597 $loaded = true;
3598 }
3599 }
3600 if ( !$loaded ) {
3601 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3602 "to insert user '{$this->mName}' row, but it was not present in select!" );
3603 }
3604 return Status::newFatal( 'userexists' );
3605 }
3606 $this->mId = $dbw->insertId();
3607
3608 // Clear instance cache other than user table data, which is already accurate
3609 $this->clearInstanceCache();
3610
3611 $this->saveOptions();
3612 return Status::newGood();
3613 }
3614
3615 /**
3616 * If this user is logged-in and blocked,
3617 * block any IP address they've successfully logged in from.
3618 * @return bool A block was spread
3619 */
3620 public function spreadAnyEditBlock() {
3621 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3622 return $this->spreadBlock();
3623 }
3624 return false;
3625 }
3626
3627 /**
3628 * If this (non-anonymous) user is blocked,
3629 * block the IP address they've successfully logged in from.
3630 * @return bool A block was spread
3631 */
3632 protected function spreadBlock() {
3633 wfDebug( __METHOD__ . "()\n" );
3634 $this->load();
3635 if ( $this->mId == 0 ) {
3636 return false;
3637 }
3638
3639 $userblock = Block::newFromTarget( $this->getName() );
3640 if ( !$userblock ) {
3641 return false;
3642 }
3643
3644 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3645 }
3646
3647 /**
3648 * Get whether the user is explicitly blocked from account creation.
3649 * @return bool|Block
3650 */
3651 public function isBlockedFromCreateAccount() {
3652 $this->getBlockedStatus();
3653 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3654 return $this->mBlock;
3655 }
3656
3657 # bug 13611: if the IP address the user is trying to create an account from is
3658 # blocked with createaccount disabled, prevent new account creation there even
3659 # when the user is logged in
3660 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3661 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3662 }
3663 return $this->mBlockedFromCreateAccount instanceof Block && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3664 ? $this->mBlockedFromCreateAccount
3665 : false;
3666 }
3667
3668 /**
3669 * Get whether the user is blocked from using Special:Emailuser.
3670 * @return bool
3671 */
3672 public function isBlockedFromEmailuser() {
3673 $this->getBlockedStatus();
3674 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3675 }
3676
3677 /**
3678 * Get whether the user is allowed to create an account.
3679 * @return bool
3680 */
3681 public function isAllowedToCreateAccount() {
3682 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3683 }
3684
3685 /**
3686 * Get this user's personal page title.
3687 *
3688 * @return Title: User's personal page title
3689 */
3690 public function getUserPage() {
3691 return Title::makeTitle( NS_USER, $this->getName() );
3692 }
3693
3694 /**
3695 * Get this user's talk page title.
3696 *
3697 * @return Title: User's talk page title
3698 */
3699 public function getTalkPage() {
3700 $title = $this->getUserPage();
3701 return $title->getTalkPage();
3702 }
3703
3704 /**
3705 * Determine whether the user is a newbie. Newbies are either
3706 * anonymous IPs, or the most recently created accounts.
3707 * @return bool
3708 */
3709 public function isNewbie() {
3710 return !$this->isAllowed( 'autoconfirmed' );
3711 }
3712
3713 /**
3714 * Check to see if the given clear-text password is one of the accepted passwords
3715 * @param string $password user password.
3716 * @return boolean: True if the given password is correct, otherwise False.
3717 */
3718 public function checkPassword( $password ) {
3719 global $wgAuth, $wgLegacyEncoding;
3720 $this->load();
3721
3722 // Certain authentication plugins do NOT want to save
3723 // domain passwords in a mysql database, so we should
3724 // check this (in case $wgAuth->strict() is false).
3725
3726 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3727 return true;
3728 } elseif ( $wgAuth->strict() ) {
3729 // Auth plugin doesn't allow local authentication
3730 return false;
3731 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3732 // Auth plugin doesn't allow local authentication for this user name
3733 return false;
3734 }
3735 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
3736 return true;
3737 } elseif ( $wgLegacyEncoding ) {
3738 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3739 // Check for this with iconv
3740 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3741 if ( $cp1252Password != $password
3742 && self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId )
3743 ) {
3744 return true;
3745 }
3746 }
3747 return false;
3748 }
3749
3750 /**
3751 * Check if the given clear-text password matches the temporary password
3752 * sent by e-mail for password reset operations.
3753 *
3754 * @param $plaintext string
3755 *
3756 * @return boolean: True if matches, false otherwise
3757 */
3758 public function checkTemporaryPassword( $plaintext ) {
3759 global $wgNewPasswordExpiry;
3760
3761 $this->load();
3762 if ( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
3763 if ( is_null( $this->mNewpassTime ) ) {
3764 return true;
3765 }
3766 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3767 return ( time() < $expiry );
3768 } else {
3769 return false;
3770 }
3771 }
3772
3773 /**
3774 * Alias for getEditToken.
3775 * @deprecated since 1.19, use getEditToken instead.
3776 *
3777 * @param string|array $salt of Strings Optional function-specific data for hashing
3778 * @param $request WebRequest object to use or null to use $wgRequest
3779 * @return string The new edit token
3780 */
3781 public function editToken( $salt = '', $request = null ) {
3782 wfDeprecated( __METHOD__, '1.19' );
3783 return $this->getEditToken( $salt, $request );
3784 }
3785
3786 /**
3787 * Initialize (if necessary) and return a session token value
3788 * which can be used in edit forms to show that the user's
3789 * login credentials aren't being hijacked with a foreign form
3790 * submission.
3791 *
3792 * @since 1.19
3793 *
3794 * @param string|array $salt of Strings Optional function-specific data for hashing
3795 * @param $request WebRequest object to use or null to use $wgRequest
3796 * @return string The new edit token
3797 */
3798 public function getEditToken( $salt = '', $request = null ) {
3799 if ( $request == null ) {
3800 $request = $this->getRequest();
3801 }
3802
3803 if ( $this->isAnon() ) {
3804 return EDIT_TOKEN_SUFFIX;
3805 } else {
3806 $token = $request->getSessionData( 'wsEditToken' );
3807 if ( $token === null ) {
3808 $token = MWCryptRand::generateHex( 32 );
3809 $request->setSessionData( 'wsEditToken', $token );
3810 }
3811 if ( is_array( $salt ) ) {
3812 $salt = implode( '|', $salt );
3813 }
3814 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
3815 }
3816 }
3817
3818 /**
3819 * Generate a looking random token for various uses.
3820 *
3821 * @return string The new random token
3822 * @deprecated since 1.20: Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3823 */
3824 public static function generateToken() {
3825 return MWCryptRand::generateHex( 32 );
3826 }
3827
3828 /**
3829 * Check given value against the token value stored in the session.
3830 * A match should confirm that the form was submitted from the
3831 * user's own login session, not a form submission from a third-party
3832 * site.
3833 *
3834 * @param string $val Input value to compare
3835 * @param string $salt Optional function-specific data for hashing
3836 * @param WebRequest $request Object to use or null to use $wgRequest
3837 * @return boolean: Whether the token matches
3838 */
3839 public function matchEditToken( $val, $salt = '', $request = null ) {
3840 $sessionToken = $this->getEditToken( $salt, $request );
3841 if ( $val != $sessionToken ) {
3842 wfDebug( "User::matchEditToken: broken session data\n" );
3843 }
3844 return $val == $sessionToken;
3845 }
3846
3847 /**
3848 * Check given value against the token value stored in the session,
3849 * ignoring the suffix.
3850 *
3851 * @param string $val Input value to compare
3852 * @param string $salt Optional function-specific data for hashing
3853 * @param WebRequest $request object to use or null to use $wgRequest
3854 * @return boolean: Whether the token matches
3855 */
3856 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3857 $sessionToken = $this->getEditToken( $salt, $request );
3858 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3859 }
3860
3861 /**
3862 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3863 * mail to the user's given address.
3864 *
3865 * @param string $type message to send, either "created", "changed" or "set"
3866 * @return Status object
3867 */
3868 public function sendConfirmationMail( $type = 'created' ) {
3869 global $wgLang;
3870 $expiration = null; // gets passed-by-ref and defined in next line.
3871 $token = $this->confirmationToken( $expiration );
3872 $url = $this->confirmationTokenUrl( $token );
3873 $invalidateURL = $this->invalidationTokenUrl( $token );
3874 $this->saveSettings();
3875
3876 if ( $type == 'created' || $type === false ) {
3877 $message = 'confirmemail_body';
3878 } elseif ( $type === true ) {
3879 $message = 'confirmemail_body_changed';
3880 } else {
3881 // Messages: confirmemail_body_changed, confirmemail_body_set
3882 $message = 'confirmemail_body_' . $type;
3883 }
3884
3885 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3886 wfMessage( $message,
3887 $this->getRequest()->getIP(),
3888 $this->getName(),
3889 $url,
3890 $wgLang->timeanddate( $expiration, false ),
3891 $invalidateURL,
3892 $wgLang->date( $expiration, false ),
3893 $wgLang->time( $expiration, false ) )->text() );
3894 }
3895
3896 /**
3897 * Send an e-mail to this user's account. Does not check for
3898 * confirmed status or validity.
3899 *
3900 * @param string $subject Message subject
3901 * @param string $body Message body
3902 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3903 * @param string $replyto Reply-To address
3904 * @return Status
3905 */
3906 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3907 if ( is_null( $from ) ) {
3908 global $wgPasswordSender;
3909 $sender = new MailAddress( $wgPasswordSender,
3910 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3911 } else {
3912 $sender = new MailAddress( $from );
3913 }
3914
3915 $to = new MailAddress( $this );
3916 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3917 }
3918
3919 /**
3920 * Generate, store, and return a new e-mail confirmation code.
3921 * A hash (unsalted, since it's used as a key) is stored.
3922 *
3923 * @note Call saveSettings() after calling this function to commit
3924 * this change to the database.
3925 *
3926 * @param &$expiration \mixed Accepts the expiration time
3927 * @return string New token
3928 */
3929 protected function confirmationToken( &$expiration ) {
3930 global $wgUserEmailConfirmationTokenExpiry;
3931 $now = time();
3932 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3933 $expiration = wfTimestamp( TS_MW, $expires );
3934 $this->load();
3935 $token = MWCryptRand::generateHex( 32 );
3936 $hash = md5( $token );
3937 $this->mEmailToken = $hash;
3938 $this->mEmailTokenExpires = $expiration;
3939 return $token;
3940 }
3941
3942 /**
3943 * Return a URL the user can use to confirm their email address.
3944 * @param string $token Accepts the email confirmation token
3945 * @return string New token URL
3946 */
3947 protected function confirmationTokenUrl( $token ) {
3948 return $this->getTokenUrl( 'ConfirmEmail', $token );
3949 }
3950
3951 /**
3952 * Return a URL the user can use to invalidate their email address.
3953 * @param string $token Accepts the email confirmation token
3954 * @return string New token URL
3955 */
3956 protected function invalidationTokenUrl( $token ) {
3957 return $this->getTokenUrl( 'InvalidateEmail', $token );
3958 }
3959
3960 /**
3961 * Internal function to format the e-mail validation/invalidation URLs.
3962 * This uses a quickie hack to use the
3963 * hardcoded English names of the Special: pages, for ASCII safety.
3964 *
3965 * @note Since these URLs get dropped directly into emails, using the
3966 * short English names avoids insanely long URL-encoded links, which
3967 * also sometimes can get corrupted in some browsers/mailers
3968 * (bug 6957 with Gmail and Internet Explorer).
3969 *
3970 * @param string $page Special page
3971 * @param string $token Token
3972 * @return string Formatted URL
3973 */
3974 protected function getTokenUrl( $page, $token ) {
3975 // Hack to bypass localization of 'Special:'
3976 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
3977 return $title->getCanonicalURL();
3978 }
3979
3980 /**
3981 * Mark the e-mail address confirmed.
3982 *
3983 * @note Call saveSettings() after calling this function to commit the change.
3984 *
3985 * @return bool
3986 */
3987 public function confirmEmail() {
3988 // Check if it's already confirmed, so we don't touch the database
3989 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3990 if ( !$this->isEmailConfirmed() ) {
3991 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3992 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3993 }
3994 return true;
3995 }
3996
3997 /**
3998 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3999 * address if it was already confirmed.
4000 *
4001 * @note Call saveSettings() after calling this function to commit the change.
4002 * @return bool Returns true
4003 */
4004 public function invalidateEmail() {
4005 $this->load();
4006 $this->mEmailToken = null;
4007 $this->mEmailTokenExpires = null;
4008 $this->setEmailAuthenticationTimestamp( null );
4009 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4010 return true;
4011 }
4012
4013 /**
4014 * Set the e-mail authentication timestamp.
4015 * @param string $timestamp TS_MW timestamp
4016 */
4017 public function setEmailAuthenticationTimestamp( $timestamp ) {
4018 $this->load();
4019 $this->mEmailAuthenticated = $timestamp;
4020 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4021 }
4022
4023 /**
4024 * Is this user allowed to send e-mails within limits of current
4025 * site configuration?
4026 * @return bool
4027 */
4028 public function canSendEmail() {
4029 global $wgEnableEmail, $wgEnableUserEmail;
4030 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4031 return false;
4032 }
4033 $canSend = $this->isEmailConfirmed();
4034 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4035 return $canSend;
4036 }
4037
4038 /**
4039 * Is this user allowed to receive e-mails within limits of current
4040 * site configuration?
4041 * @return bool
4042 */
4043 public function canReceiveEmail() {
4044 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4045 }
4046
4047 /**
4048 * Is this user's e-mail address valid-looking and confirmed within
4049 * limits of the current site configuration?
4050 *
4051 * @note If $wgEmailAuthentication is on, this may require the user to have
4052 * confirmed their address by returning a code or using a password
4053 * sent to the address from the wiki.
4054 *
4055 * @return bool
4056 */
4057 public function isEmailConfirmed() {
4058 global $wgEmailAuthentication;
4059 $this->load();
4060 $confirmed = true;
4061 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4062 if ( $this->isAnon() ) {
4063 return false;
4064 }
4065 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4066 return false;
4067 }
4068 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4069 return false;
4070 }
4071 return true;
4072 } else {
4073 return $confirmed;
4074 }
4075 }
4076
4077 /**
4078 * Check whether there is an outstanding request for e-mail confirmation.
4079 * @return bool
4080 */
4081 public function isEmailConfirmationPending() {
4082 global $wgEmailAuthentication;
4083 return $wgEmailAuthentication &&
4084 !$this->isEmailConfirmed() &&
4085 $this->mEmailToken &&
4086 $this->mEmailTokenExpires > wfTimestamp();
4087 }
4088
4089 /**
4090 * Get the timestamp of account creation.
4091 *
4092 * @return string|bool|null Timestamp of account creation, false for
4093 * non-existent/anonymous user accounts, or null if existing account
4094 * but information is not in database.
4095 */
4096 public function getRegistration() {
4097 if ( $this->isAnon() ) {
4098 return false;
4099 }
4100 $this->load();
4101 return $this->mRegistration;
4102 }
4103
4104 /**
4105 * Get the timestamp of the first edit
4106 *
4107 * @return string|bool Timestamp of first edit, or false for
4108 * non-existent/anonymous user accounts.
4109 */
4110 public function getFirstEditTimestamp() {
4111 if ( $this->getId() == 0 ) {
4112 return false; // anons
4113 }
4114 $dbr = wfGetDB( DB_SLAVE );
4115 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4116 array( 'rev_user' => $this->getId() ),
4117 __METHOD__,
4118 array( 'ORDER BY' => 'rev_timestamp ASC' )
4119 );
4120 if ( !$time ) {
4121 return false; // no edits
4122 }
4123 return wfTimestamp( TS_MW, $time );
4124 }
4125
4126 /**
4127 * Get the permissions associated with a given list of groups
4128 *
4129 * @param array $groups of Strings List of internal group names
4130 * @return Array of Strings List of permission key names for given groups combined
4131 */
4132 public static function getGroupPermissions( $groups ) {
4133 global $wgGroupPermissions, $wgRevokePermissions;
4134 $rights = array();
4135 // grant every granted permission first
4136 foreach ( $groups as $group ) {
4137 if ( isset( $wgGroupPermissions[$group] ) ) {
4138 $rights = array_merge( $rights,
4139 // array_filter removes empty items
4140 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4141 }
4142 }
4143 // now revoke the revoked permissions
4144 foreach ( $groups as $group ) {
4145 if ( isset( $wgRevokePermissions[$group] ) ) {
4146 $rights = array_diff( $rights,
4147 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4148 }
4149 }
4150 return array_unique( $rights );
4151 }
4152
4153 /**
4154 * Get all the groups who have a given permission
4155 *
4156 * @param string $role Role to check
4157 * @return Array of Strings List of internal group names with the given permission
4158 */
4159 public static function getGroupsWithPermission( $role ) {
4160 global $wgGroupPermissions;
4161 $allowedGroups = array();
4162 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4163 if ( self::groupHasPermission( $group, $role ) ) {
4164 $allowedGroups[] = $group;
4165 }
4166 }
4167 return $allowedGroups;
4168 }
4169
4170 /**
4171 * Check, if the given group has the given permission
4172 *
4173 * If you're wanting to check whether all users have a permission, use
4174 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4175 * from anyone.
4176 *
4177 * @since 1.21
4178 * @param string $group Group to check
4179 * @param string $role Role to check
4180 * @return bool
4181 */
4182 public static function groupHasPermission( $group, $role ) {
4183 global $wgGroupPermissions, $wgRevokePermissions;
4184 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4185 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4186 }
4187
4188 /**
4189 * Check if all users have the given permission
4190 *
4191 * @since 1.22
4192 * @param string $right Right to check
4193 * @return bool
4194 */
4195 public static function isEveryoneAllowed( $right ) {
4196 global $wgGroupPermissions, $wgRevokePermissions;
4197 static $cache = array();
4198
4199 // Use the cached results, except in unit tests which rely on
4200 // being able change the permission mid-request
4201 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4202 return $cache[$right];
4203 }
4204
4205 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4206 $cache[$right] = false;
4207 return false;
4208 }
4209
4210 // If it's revoked anywhere, then everyone doesn't have it
4211 foreach ( $wgRevokePermissions as $rights ) {
4212 if ( isset( $rights[$right] ) && $rights[$right] ) {
4213 $cache[$right] = false;
4214 return false;
4215 }
4216 }
4217
4218 // Allow extensions (e.g. OAuth) to say false
4219 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4220 $cache[$right] = false;
4221 return false;
4222 }
4223
4224 $cache[$right] = true;
4225 return true;
4226 }
4227
4228 /**
4229 * Get the localized descriptive name for a group, if it exists
4230 *
4231 * @param string $group Internal group name
4232 * @return string Localized descriptive group name
4233 */
4234 public static function getGroupName( $group ) {
4235 $msg = wfMessage( "group-$group" );
4236 return $msg->isBlank() ? $group : $msg->text();
4237 }
4238
4239 /**
4240 * Get the localized descriptive name for a member of a group, if it exists
4241 *
4242 * @param string $group Internal group name
4243 * @param string $username Username for gender (since 1.19)
4244 * @return string Localized name for group member
4245 */
4246 public static function getGroupMember( $group, $username = '#' ) {
4247 $msg = wfMessage( "group-$group-member", $username );
4248 return $msg->isBlank() ? $group : $msg->text();
4249 }
4250
4251 /**
4252 * Return the set of defined explicit groups.
4253 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4254 * are not included, as they are defined automatically, not in the database.
4255 * @return Array of internal group names
4256 */
4257 public static function getAllGroups() {
4258 global $wgGroupPermissions, $wgRevokePermissions;
4259 return array_diff(
4260 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4261 self::getImplicitGroups()
4262 );
4263 }
4264
4265 /**
4266 * Get a list of all available permissions.
4267 * @return Array of permission names
4268 */
4269 public static function getAllRights() {
4270 if ( self::$mAllRights === false ) {
4271 global $wgAvailableRights;
4272 if ( count( $wgAvailableRights ) ) {
4273 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4274 } else {
4275 self::$mAllRights = self::$mCoreRights;
4276 }
4277 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4278 }
4279 return self::$mAllRights;
4280 }
4281
4282 /**
4283 * Get a list of implicit groups
4284 * @return Array of Strings Array of internal group names
4285 */
4286 public static function getImplicitGroups() {
4287 global $wgImplicitGroups;
4288 $groups = $wgImplicitGroups;
4289 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
4290 return $groups;
4291 }
4292
4293 /**
4294 * Get the title of a page describing a particular group
4295 *
4296 * @param string $group Internal group name
4297 * @return Title|bool Title of the page if it exists, false otherwise
4298 */
4299 public static function getGroupPage( $group ) {
4300 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4301 if ( $msg->exists() ) {
4302 $title = Title::newFromText( $msg->text() );
4303 if ( is_object( $title ) ) {
4304 return $title;
4305 }
4306 }
4307 return false;
4308 }
4309
4310 /**
4311 * Create a link to the group in HTML, if available;
4312 * else return the group name.
4313 *
4314 * @param string $group Internal name of the group
4315 * @param string $text The text of the link
4316 * @return string HTML link to the group
4317 */
4318 public static function makeGroupLinkHTML( $group, $text = '' ) {
4319 if ( $text == '' ) {
4320 $text = self::getGroupName( $group );
4321 }
4322 $title = self::getGroupPage( $group );
4323 if ( $title ) {
4324 return Linker::link( $title, htmlspecialchars( $text ) );
4325 } else {
4326 return $text;
4327 }
4328 }
4329
4330 /**
4331 * Create a link to the group in Wikitext, if available;
4332 * else return the group name.
4333 *
4334 * @param string $group Internal name of the group
4335 * @param string $text The text of the link
4336 * @return string Wikilink to the group
4337 */
4338 public static function makeGroupLinkWiki( $group, $text = '' ) {
4339 if ( $text == '' ) {
4340 $text = self::getGroupName( $group );
4341 }
4342 $title = self::getGroupPage( $group );
4343 if ( $title ) {
4344 $page = $title->getPrefixedText();
4345 return "[[$page|$text]]";
4346 } else {
4347 return $text;
4348 }
4349 }
4350
4351 /**
4352 * Returns an array of the groups that a particular group can add/remove.
4353 *
4354 * @param string $group the group to check for whether it can add/remove
4355 * @return Array array( 'add' => array( addablegroups ),
4356 * 'remove' => array( removablegroups ),
4357 * 'add-self' => array( addablegroups to self),
4358 * 'remove-self' => array( removable groups from self) )
4359 */
4360 public static function changeableByGroup( $group ) {
4361 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4362
4363 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4364 if ( empty( $wgAddGroups[$group] ) ) {
4365 // Don't add anything to $groups
4366 } elseif ( $wgAddGroups[$group] === true ) {
4367 // You get everything
4368 $groups['add'] = self::getAllGroups();
4369 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4370 $groups['add'] = $wgAddGroups[$group];
4371 }
4372
4373 // Same thing for remove
4374 if ( empty( $wgRemoveGroups[$group] ) ) {
4375 } elseif ( $wgRemoveGroups[$group] === true ) {
4376 $groups['remove'] = self::getAllGroups();
4377 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4378 $groups['remove'] = $wgRemoveGroups[$group];
4379 }
4380
4381 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4382 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4383 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4384 if ( is_int( $key ) ) {
4385 $wgGroupsAddToSelf['user'][] = $value;
4386 }
4387 }
4388 }
4389
4390 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4391 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4392 if ( is_int( $key ) ) {
4393 $wgGroupsRemoveFromSelf['user'][] = $value;
4394 }
4395 }
4396 }
4397
4398 // Now figure out what groups the user can add to him/herself
4399 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4400 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4401 // No idea WHY this would be used, but it's there
4402 $groups['add-self'] = User::getAllGroups();
4403 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4404 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4405 }
4406
4407 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4408 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4409 $groups['remove-self'] = User::getAllGroups();
4410 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4411 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4412 }
4413
4414 return $groups;
4415 }
4416
4417 /**
4418 * Returns an array of groups that this user can add and remove
4419 * @return Array array( 'add' => array( addablegroups ),
4420 * 'remove' => array( removablegroups ),
4421 * 'add-self' => array( addablegroups to self),
4422 * 'remove-self' => array( removable groups from self) )
4423 */
4424 public function changeableGroups() {
4425 if ( $this->isAllowed( 'userrights' ) ) {
4426 // This group gives the right to modify everything (reverse-
4427 // compatibility with old "userrights lets you change
4428 // everything")
4429 // Using array_merge to make the groups reindexed
4430 $all = array_merge( User::getAllGroups() );
4431 return array(
4432 'add' => $all,
4433 'remove' => $all,
4434 'add-self' => array(),
4435 'remove-self' => array()
4436 );
4437 }
4438
4439 // Okay, it's not so simple, we will have to go through the arrays
4440 $groups = array(
4441 'add' => array(),
4442 'remove' => array(),
4443 'add-self' => array(),
4444 'remove-self' => array()
4445 );
4446 $addergroups = $this->getEffectiveGroups();
4447
4448 foreach ( $addergroups as $addergroup ) {
4449 $groups = array_merge_recursive(
4450 $groups, $this->changeableByGroup( $addergroup )
4451 );
4452 $groups['add'] = array_unique( $groups['add'] );
4453 $groups['remove'] = array_unique( $groups['remove'] );
4454 $groups['add-self'] = array_unique( $groups['add-self'] );
4455 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4456 }
4457 return $groups;
4458 }
4459
4460 /**
4461 * Increment the user's edit-count field.
4462 * Will have no effect for anonymous users.
4463 */
4464 public function incEditCount() {
4465 if ( !$this->isAnon() ) {
4466 $dbw = wfGetDB( DB_MASTER );
4467 $dbw->update(
4468 'user',
4469 array( 'user_editcount=user_editcount+1' ),
4470 array( 'user_id' => $this->getId() ),
4471 __METHOD__
4472 );
4473
4474 // Lazy initialization check...
4475 if ( $dbw->affectedRows() == 0 ) {
4476 // Now here's a goddamn hack...
4477 $dbr = wfGetDB( DB_SLAVE );
4478 if ( $dbr !== $dbw ) {
4479 // If we actually have a slave server, the count is
4480 // at least one behind because the current transaction
4481 // has not been committed and replicated.
4482 $this->initEditCount( 1 );
4483 } else {
4484 // But if DB_SLAVE is selecting the master, then the
4485 // count we just read includes the revision that was
4486 // just added in the working transaction.
4487 $this->initEditCount();
4488 }
4489 }
4490 }
4491 // edit count in user cache too
4492 $this->invalidateCache();
4493 }
4494
4495 /**
4496 * Initialize user_editcount from data out of the revision table
4497 *
4498 * @param $add Integer Edits to add to the count from the revision table
4499 * @return integer Number of edits
4500 */
4501 protected function initEditCount( $add = 0 ) {
4502 // Pull from a slave to be less cruel to servers
4503 // Accuracy isn't the point anyway here
4504 $dbr = wfGetDB( DB_SLAVE );
4505 $count = (int)$dbr->selectField(
4506 'revision',
4507 'COUNT(rev_user)',
4508 array( 'rev_user' => $this->getId() ),
4509 __METHOD__
4510 );
4511 $count = $count + $add;
4512
4513 $dbw = wfGetDB( DB_MASTER );
4514 $dbw->update(
4515 'user',
4516 array( 'user_editcount' => $count ),
4517 array( 'user_id' => $this->getId() ),
4518 __METHOD__
4519 );
4520
4521 return $count;
4522 }
4523
4524 /**
4525 * Get the description of a given right
4526 *
4527 * @param string $right Right to query
4528 * @return string Localized description of the right
4529 */
4530 public static function getRightDescription( $right ) {
4531 $key = "right-$right";
4532 $msg = wfMessage( $key );
4533 return $msg->isBlank() ? $right : $msg->text();
4534 }
4535
4536 /**
4537 * Make an old-style password hash
4538 *
4539 * @param string $password Plain-text password
4540 * @param string $userId User ID
4541 * @return string Password hash
4542 */
4543 public static function oldCrypt( $password, $userId ) {
4544 global $wgPasswordSalt;
4545 if ( $wgPasswordSalt ) {
4546 return md5( $userId . '-' . md5( $password ) );
4547 } else {
4548 return md5( $password );
4549 }
4550 }
4551
4552 /**
4553 * Make a new-style password hash
4554 *
4555 * @param string $password Plain-text password
4556 * @param bool|string $salt Optional salt, may be random or the user ID.
4557 * If unspecified or false, will generate one automatically
4558 * @return string Password hash
4559 */
4560 public static function crypt( $password, $salt = false ) {
4561 global $wgPasswordSalt;
4562
4563 $hash = '';
4564 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4565 return $hash;
4566 }
4567
4568 if ( $wgPasswordSalt ) {
4569 if ( $salt === false ) {
4570 $salt = MWCryptRand::generateHex( 8 );
4571 }
4572 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4573 } else {
4574 return ':A:' . md5( $password );
4575 }
4576 }
4577
4578 /**
4579 * Compare a password hash with a plain-text password. Requires the user
4580 * ID if there's a chance that the hash is an old-style hash.
4581 *
4582 * @param string $hash Password hash
4583 * @param string $password Plain-text password to compare
4584 * @param string|bool $userId User ID for old-style password salt
4585 *
4586 * @return boolean
4587 */
4588 public static function comparePasswords( $hash, $password, $userId = false ) {
4589 $type = substr( $hash, 0, 3 );
4590
4591 $result = false;
4592 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4593 return $result;
4594 }
4595
4596 if ( $type == ':A:' ) {
4597 // Unsalted
4598 return md5( $password ) === substr( $hash, 3 );
4599 } elseif ( $type == ':B:' ) {
4600 // Salted
4601 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4602 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4603 } else {
4604 // Old-style
4605 return self::oldCrypt( $password, $userId ) === $hash;
4606 }
4607 }
4608
4609 /**
4610 * Add a newuser log entry for this user.
4611 * Before 1.19 the return value was always true.
4612 *
4613 * @param string|bool $action account creation type.
4614 * - String, one of the following values:
4615 * - 'create' for an anonymous user creating an account for himself.
4616 * This will force the action's performer to be the created user itself,
4617 * no matter the value of $wgUser
4618 * - 'create2' for a logged in user creating an account for someone else
4619 * - 'byemail' when the created user will receive its password by e-mail
4620 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4621 * - Boolean means whether the account was created by e-mail (deprecated):
4622 * - true will be converted to 'byemail'
4623 * - false will be converted to 'create' if this object is the same as
4624 * $wgUser and to 'create2' otherwise
4625 *
4626 * @param string $reason user supplied reason
4627 *
4628 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4629 */
4630 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4631 global $wgUser, $wgNewUserLog;
4632 if ( empty( $wgNewUserLog ) ) {
4633 return true; // disabled
4634 }
4635
4636 if ( $action === true ) {
4637 $action = 'byemail';
4638 } elseif ( $action === false ) {
4639 if ( $this->getName() == $wgUser->getName() ) {
4640 $action = 'create';
4641 } else {
4642 $action = 'create2';
4643 }
4644 }
4645
4646 if ( $action === 'create' || $action === 'autocreate' ) {
4647 $performer = $this;
4648 } else {
4649 $performer = $wgUser;
4650 }
4651
4652 $logEntry = new ManualLogEntry( 'newusers', $action );
4653 $logEntry->setPerformer( $performer );
4654 $logEntry->setTarget( $this->getUserPage() );
4655 $logEntry->setComment( $reason );
4656 $logEntry->setParameters( array(
4657 '4::userid' => $this->getId(),
4658 ) );
4659 $logid = $logEntry->insert();
4660
4661 if ( $action !== 'autocreate' ) {
4662 $logEntry->publish( $logid );
4663 }
4664
4665 return (int)$logid;
4666 }
4667
4668 /**
4669 * Add an autocreate newuser log entry for this user
4670 * Used by things like CentralAuth and perhaps other authplugins.
4671 * Consider calling addNewUserLogEntry() directly instead.
4672 *
4673 * @return bool
4674 */
4675 public function addNewUserLogEntryAutoCreate() {
4676 $this->addNewUserLogEntry( 'autocreate' );
4677
4678 return true;
4679 }
4680
4681 /**
4682 * Load the user options either from cache, the database or an array
4683 *
4684 * @param array $data Rows for the current user out of the user_properties table
4685 */
4686 protected function loadOptions( $data = null ) {
4687 global $wgContLang;
4688
4689 $this->load();
4690
4691 if ( $this->mOptionsLoaded ) {
4692 return;
4693 }
4694
4695 $this->mOptions = self::getDefaultOptions();
4696
4697 if ( !$this->getId() ) {
4698 // For unlogged-in users, load language/variant options from request.
4699 // There's no need to do it for logged-in users: they can set preferences,
4700 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4701 // so don't override user's choice (especially when the user chooses site default).
4702 $variant = $wgContLang->getDefaultVariant();
4703 $this->mOptions['variant'] = $variant;
4704 $this->mOptions['language'] = $variant;
4705 $this->mOptionsLoaded = true;
4706 return;
4707 }
4708
4709 // Maybe load from the object
4710 if ( !is_null( $this->mOptionOverrides ) ) {
4711 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4712 foreach ( $this->mOptionOverrides as $key => $value ) {
4713 $this->mOptions[$key] = $value;
4714 }
4715 } else {
4716 if ( !is_array( $data ) ) {
4717 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4718 // Load from database
4719 $dbr = wfGetDB( DB_SLAVE );
4720
4721 $res = $dbr->select(
4722 'user_properties',
4723 array( 'up_property', 'up_value' ),
4724 array( 'up_user' => $this->getId() ),
4725 __METHOD__
4726 );
4727
4728 $this->mOptionOverrides = array();
4729 $data = array();
4730 foreach ( $res as $row ) {
4731 $data[$row->up_property] = $row->up_value;
4732 }
4733 }
4734 foreach ( $data as $property => $value ) {
4735 $this->mOptionOverrides[$property] = $value;
4736 $this->mOptions[$property] = $value;
4737 }
4738 }
4739
4740 $this->mOptionsLoaded = true;
4741
4742 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4743 }
4744
4745 /**
4746 * @todo document
4747 */
4748 protected function saveOptions() {
4749 $this->loadOptions();
4750
4751 // Not using getOptions(), to keep hidden preferences in database
4752 $saveOptions = $this->mOptions;
4753
4754 // Allow hooks to abort, for instance to save to a global profile.
4755 // Reset options to default state before saving.
4756 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4757 return;
4758 }
4759
4760 $userId = $this->getId();
4761 $insert_rows = array();
4762 foreach ( $saveOptions as $key => $value ) {
4763 // Don't bother storing default values
4764 $defaultOption = self::getDefaultOption( $key );
4765 if ( ( is_null( $defaultOption ) &&
4766 !( $value === false || is_null( $value ) ) ) ||
4767 $value != $defaultOption
4768 ) {
4769 $insert_rows[] = array(
4770 'up_user' => $userId,
4771 'up_property' => $key,
4772 'up_value' => $value,
4773 );
4774 }
4775 }
4776
4777 $dbw = wfGetDB( DB_MASTER );
4778 // Find and delete any prior preference rows...
4779 $res = $dbw->select( 'user_properties',
4780 array( 'up_property' ), array( 'up_user' => $userId ), __METHOD__ );
4781 $priorKeys = array();
4782 foreach ( $res as $row ) {
4783 $priorKeys[] = $row->up_property;
4784 }
4785 if ( count( $priorKeys ) ) {
4786 // Do the DELETE by PRIMARY KEY for prior rows.
4787 // In the past a very large portion of calls to this function are for setting
4788 // 'rememberpassword' for new accounts (a preference that has since been removed).
4789 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4790 // caused gap locks on [max user ID,+infinity) which caused high contention since
4791 // updates would pile up on each other as they are for higher (newer) user IDs.
4792 // It might not be necessary these days, but it shouldn't hurt either.
4793 $dbw->delete( 'user_properties',
4794 array( 'up_user' => $userId, 'up_property' => $priorKeys ), __METHOD__ );
4795 }
4796 // Insert the new preference rows
4797 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4798 }
4799
4800 /**
4801 * Provide an array of HTML5 attributes to put on an input element
4802 * intended for the user to enter a new password. This may include
4803 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4804 *
4805 * Do *not* use this when asking the user to enter his current password!
4806 * Regardless of configuration, users may have invalid passwords for whatever
4807 * reason (e.g., they were set before requirements were tightened up).
4808 * Only use it when asking for a new password, like on account creation or
4809 * ResetPass.
4810 *
4811 * Obviously, you still need to do server-side checking.
4812 *
4813 * NOTE: A combination of bugs in various browsers means that this function
4814 * actually just returns array() unconditionally at the moment. May as
4815 * well keep it around for when the browser bugs get fixed, though.
4816 *
4817 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4818 *
4819 * @return array Array of HTML attributes suitable for feeding to
4820 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4821 * That will get confused by the boolean attribute syntax used.)
4822 */
4823 public static function passwordChangeInputAttribs() {
4824 global $wgMinimalPasswordLength;
4825
4826 if ( $wgMinimalPasswordLength == 0 ) {
4827 return array();
4828 }
4829
4830 # Note that the pattern requirement will always be satisfied if the
4831 # input is empty, so we need required in all cases.
4832 #
4833 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4834 # if e-mail confirmation is being used. Since HTML5 input validation
4835 # is b0rked anyway in some browsers, just return nothing. When it's
4836 # re-enabled, fix this code to not output required for e-mail
4837 # registration.
4838 #$ret = array( 'required' );
4839 $ret = array();
4840
4841 # We can't actually do this right now, because Opera 9.6 will print out
4842 # the entered password visibly in its error message! When other
4843 # browsers add support for this attribute, or Opera fixes its support,
4844 # we can add support with a version check to avoid doing this on Opera
4845 # versions where it will be a problem. Reported to Opera as
4846 # DSK-262266, but they don't have a public bug tracker for us to follow.
4847 /*
4848 if ( $wgMinimalPasswordLength > 1 ) {
4849 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4850 $ret['title'] = wfMessage( 'passwordtooshort' )
4851 ->numParams( $wgMinimalPasswordLength )->text();
4852 }
4853 */
4854
4855 return $ret;
4856 }
4857
4858 /**
4859 * Return the list of user fields that should be selected to create
4860 * a new user object.
4861 * @return array
4862 */
4863 public static function selectFields() {
4864 return array(
4865 'user_id',
4866 'user_name',
4867 'user_real_name',
4868 'user_password',
4869 'user_newpassword',
4870 'user_newpass_time',
4871 'user_email',
4872 'user_touched',
4873 'user_token',
4874 'user_email_authenticated',
4875 'user_email_token',
4876 'user_email_token_expires',
4877 'user_password_expires',
4878 'user_registration',
4879 'user_editcount',
4880 );
4881 }
4882
4883 /**
4884 * Factory function for fatal permission-denied errors
4885 *
4886 * @since 1.22
4887 * @param string $permission User right required
4888 * @return Status
4889 */
4890 static function newFatalPermissionDeniedStatus( $permission ) {
4891 global $wgLang;
4892
4893 $groups = array_map(
4894 array( 'User', 'makeGroupLinkWiki' ),
4895 User::getGroupsWithPermission( $permission )
4896 );
4897
4898 if ( $groups ) {
4899 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4900 } else {
4901 return Status::newFatal( 'badaccess-group0' );
4902 }
4903 }
4904 }