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