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