Completed
Branch master (d1effa)
by
unknown
26:14
created

User::changeAuthenticationData()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 6
eloc 17
c 1
b 0
f 1
nc 9
nop 1
dl 0
loc 26
rs 8.439
1
<?php
2
/**
3
 * Implements the User class for the %MediaWiki software.
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 2 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License along
16
 * with this program; if not, write to the Free Software Foundation, Inc.,
17
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18
 * http://www.gnu.org/copyleft/gpl.html
19
 *
20
 * @file
21
 */
22
23
use MediaWiki\MediaWikiServices;
24
use MediaWiki\Session\SessionManager;
25
use MediaWiki\Session\Token;
26
use MediaWiki\Auth\AuthManager;
27
use MediaWiki\Auth\AuthenticationResponse;
28
use MediaWiki\Auth\AuthenticationRequest;
29
30
/**
31
 * String Some punctuation to prevent editing from broken text-mangling proxies.
32
 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
33
 * @ingroup Constants
34
 */
35
define( 'EDIT_TOKEN_SUFFIX', Token::SUFFIX );
36
37
/**
38
 * The User object encapsulates all of the user-specific settings (user_id,
39
 * name, rights, email address, options, last login time). Client
40
 * classes use the getXXX() functions to access these fields. These functions
41
 * do all the work of determining whether the user is logged in,
42
 * whether the requested option can be satisfied from cookies or
43
 * whether a database query is needed. Most of the settings needed
44
 * for rendering normal pages are set in the cookie to minimize use
45
 * of the database.
46
 */
47
class User implements IDBAccessObject {
48
	/**
49
	 * @const int Number of characters in user_token field.
50
	 */
51
	const TOKEN_LENGTH = 32;
52
53
	/**
54
	 * @const string An invalid value for user_token
55
	 */
56
	const INVALID_TOKEN = '*** INVALID ***';
57
58
	/**
59
	 * Global constant made accessible as class constants so that autoloader
60
	 * magic can be used.
61
	 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
62
	 */
63
	const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
0 ignored issues
show
Deprecated Code introduced by
The constant EDIT_TOKEN_SUFFIX has been deprecated with message: since 1.27, use \MediaWiki\Session\Token::SUFFIX

This class constant has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the constant will be removed from the class and what other constant to use instead.

Loading history...
64
65
	/**
66
	 * @const int Serialized record version.
67
	 */
68
	const VERSION = 10;
69
70
	/**
71
	 * Exclude user options that are set to their default value.
72
	 * @since 1.25
73
	 */
74
	const GETOPTIONS_EXCLUDE_DEFAULTS = 1;
75
76
	/**
77
	 * @since 1.27
78
	 */
79
	const CHECK_USER_RIGHTS = true;
80
81
	/**
82
	 * @since 1.27
83
	 */
84
	const IGNORE_USER_RIGHTS = false;
85
86
	/**
87
	 * Array of Strings List of member variables which are saved to the
88
	 * shared cache (memcached). Any operation which changes the
89
	 * corresponding database fields must call a cache-clearing function.
90
	 * @showinitializer
91
	 */
92
	protected static $mCacheVars = [
93
		// user table
94
		'mId',
95
		'mName',
96
		'mRealName',
97
		'mEmail',
98
		'mTouched',
99
		'mToken',
100
		'mEmailAuthenticated',
101
		'mEmailToken',
102
		'mEmailTokenExpires',
103
		'mRegistration',
104
		'mEditCount',
105
		// user_groups table
106
		'mGroups',
107
		// user_properties table
108
		'mOptionOverrides',
109
	];
110
111
	/**
112
	 * Array of Strings Core rights.
113
	 * Each of these should have a corresponding message of the form
114
	 * "right-$right".
115
	 * @showinitializer
116
	 */
117
	protected static $mCoreRights = [
118
		'apihighlimits',
119
		'applychangetags',
120
		'autoconfirmed',
121
		'autocreateaccount',
122
		'autopatrol',
123
		'bigdelete',
124
		'block',
125
		'blockemail',
126
		'bot',
127
		'browsearchive',
128
		'changetags',
129
		'createaccount',
130
		'createpage',
131
		'createtalk',
132
		'delete',
133
		'deletechangetags',
134
		'deletedhistory',
135
		'deletedtext',
136
		'deletelogentry',
137
		'deleterevision',
138
		'edit',
139
		'editcontentmodel',
140
		'editinterface',
141
		'editprotected',
142
		'editmyoptions',
143
		'editmyprivateinfo',
144
		'editmyusercss',
145
		'editmyuserjs',
146
		'editmywatchlist',
147
		'editsemiprotected',
148
		'editusercssjs', # deprecated
149
		'editusercss',
150
		'edituserjs',
151
		'hideuser',
152
		'import',
153
		'importupload',
154
		'ipblock-exempt',
155
		'managechangetags',
156
		'markbotedits',
157
		'mergehistory',
158
		'minoredit',
159
		'move',
160
		'movefile',
161
		'move-categorypages',
162
		'move-rootuserpages',
163
		'move-subpages',
164
		'nominornewtalk',
165
		'noratelimit',
166
		'override-export-depth',
167
		'pagelang',
168
		'passwordreset',
169
		'patrol',
170
		'patrolmarks',
171
		'protect',
172
		'purge',
173
		'read',
174
		'reupload',
175
		'reupload-own',
176
		'reupload-shared',
177
		'rollback',
178
		'sendemail',
179
		'siteadmin',
180
		'suppressionlog',
181
		'suppressredirect',
182
		'suppressrevision',
183
		'unblockself',
184
		'undelete',
185
		'unwatchedpages',
186
		'upload',
187
		'upload_by_url',
188
		'userrights',
189
		'userrights-interwiki',
190
		'viewmyprivateinfo',
191
		'viewmywatchlist',
192
		'viewsuppressed',
193
		'writeapi',
194
	];
195
196
	/**
197
	 * String Cached results of getAllRights()
198
	 */
199
	protected static $mAllRights = false;
200
201
	/** Cache variables */
202
	// @{
203
	/** @var int */
204
	public $mId;
205
	/** @var string */
206
	public $mName;
207
	/** @var string */
208
	public $mRealName;
209
210
	/** @var string */
211
	public $mEmail;
212
	/** @var string TS_MW timestamp from the DB */
213
	public $mTouched;
214
	/** @var string TS_MW timestamp from cache */
215
	protected $mQuickTouched;
216
	/** @var string */
217
	protected $mToken;
218
	/** @var string */
219
	public $mEmailAuthenticated;
220
	/** @var string */
221
	protected $mEmailToken;
222
	/** @var string */
223
	protected $mEmailTokenExpires;
224
	/** @var string */
225
	protected $mRegistration;
226
	/** @var int */
227
	protected $mEditCount;
228
	/** @var array */
229
	public $mGroups;
230
	/** @var array */
231
	protected $mOptionOverrides;
232
	// @}
233
234
	/**
235
	 * Bool Whether the cache variables have been loaded.
236
	 */
237
	// @{
238
	public $mOptionsLoaded;
239
240
	/**
241
	 * Array with already loaded items or true if all items have been loaded.
242
	 */
243
	protected $mLoadedItems = [];
244
	// @}
245
246
	/**
247
	 * String Initialization data source if mLoadedItems!==true. May be one of:
248
	 *  - 'defaults'   anonymous user initialised from class defaults
249
	 *  - 'name'       initialise from mName
250
	 *  - 'id'         initialise from mId
251
	 *  - 'session'    log in from session if possible
252
	 *
253
	 * Use the User::newFrom*() family of functions to set this.
254
	 */
255
	public $mFrom;
256
257
	/**
258
	 * Lazy-initialized variables, invalidated with clearInstanceCache
259
	 */
260
	protected $mNewtalk;
261
	/** @var string */
262
	protected $mDatePreference;
263
	/** @var string */
264
	public $mBlockedby;
265
	/** @var string */
266
	protected $mHash;
267
	/** @var array */
268
	public $mRights;
269
	/** @var string */
270
	protected $mBlockreason;
271
	/** @var array */
272
	protected $mEffectiveGroups;
273
	/** @var array */
274
	protected $mImplicitGroups;
275
	/** @var array */
276
	protected $mFormerGroups;
277
	/** @var Block */
278
	protected $mGlobalBlock;
279
	/** @var bool */
280
	protected $mLocked;
281
	/** @var bool */
282
	public $mHideName;
283
	/** @var array */
284
	public $mOptions;
285
286
	/**
287
	 * @var WebRequest
288
	 */
289
	private $mRequest;
290
291
	/** @var Block */
292
	public $mBlock;
293
294
	/** @var bool */
295
	protected $mAllowUsertalk;
296
297
	/** @var Block */
298
	private $mBlockedFromCreateAccount = false;
299
300
	/** @var integer User::READ_* constant bitfield used to load data */
301
	protected $queryFlagsUsed = self::READ_NORMAL;
302
303
	public static $idCacheByName = [];
304
305
	/**
306
	 * Lightweight constructor for an anonymous user.
307
	 * Use the User::newFrom* factory functions for other kinds of users.
308
	 *
309
	 * @see newFromName()
310
	 * @see newFromId()
311
	 * @see newFromConfirmationCode()
312
	 * @see newFromSession()
313
	 * @see newFromRow()
314
	 */
315
	public function __construct() {
316
		$this->clearInstanceCache( 'defaults' );
317
	}
318
319
	/**
320
	 * @return string
321
	 */
322
	public function __toString() {
323
		return $this->getName();
324
	}
325
326
	/**
327
	 * Test if it's safe to load this User object.
328
	 *
329
	 * You should typically check this before using $wgUser or
330
	 * RequestContext::getUser in a method that might be called before the
331
	 * system has been fully initialized. If the object is unsafe, you should
332
	 * use an anonymous user:
333
	 * \code
334
	 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
335
	 * \endcode
336
	 *
337
	 * @since 1.27
338
	 * @return bool
339
	 */
340
	public function isSafeToLoad() {
341
		global $wgFullyInitialised;
342
343
		// The user is safe to load if:
344
		// * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
345
		// * mLoadedItems === true (already loaded)
346
		// * mFrom !== 'session' (sessions not involved at all)
347
348
		return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
349
			$this->mLoadedItems === true || $this->mFrom !== 'session';
350
	}
351
352
	/**
353
	 * Load the user table data for this object from the source given by mFrom.
354
	 *
355
	 * @param integer $flags User::READ_* constant bitfield
356
	 */
357
	public function load( $flags = self::READ_NORMAL ) {
358
		global $wgFullyInitialised;
359
360
		if ( $this->mLoadedItems === true ) {
361
			return;
362
		}
363
364
		// Set it now to avoid infinite recursion in accessors
365
		$oldLoadedItems = $this->mLoadedItems;
366
		$this->mLoadedItems = true;
0 ignored issues
show
Documentation Bug introduced by
It seems like true of type boolean is incompatible with the declared type array of property $mLoadedItems.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
367
		$this->queryFlagsUsed = $flags;
368
369
		// If this is called too early, things are likely to break.
370
		if ( !$wgFullyInitialised && $this->mFrom === 'session' ) {
371
			\MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
372
				->warning( 'User::loadFromSession called before the end of Setup.php', [
373
					'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
374
				] );
375
			$this->loadDefaults();
376
			$this->mLoadedItems = $oldLoadedItems;
377
			return;
378
		}
379
380
		switch ( $this->mFrom ) {
381
			case 'defaults':
382
				$this->loadDefaults();
383
				break;
384
			case 'name':
385
				// Make sure this thread sees its own changes
386
				if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
0 ignored issues
show
Deprecated Code introduced by
The function wfGetLB() has been deprecated with message: since 1.27, use MediaWikiServices::getDBLoadBalancer() or MediaWikiServices::getDBLoadBalancerFactory() instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
387
					$flags |= self::READ_LATEST;
388
					$this->queryFlagsUsed = $flags;
389
				}
390
391
				$this->mId = self::idFromName( $this->mName, $flags );
392
				if ( !$this->mId ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->mId of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
393
					// Nonexistent user placeholder object
394
					$this->loadDefaults( $this->mName );
395
				} else {
396
					$this->loadFromId( $flags );
397
				}
398
				break;
399
			case 'id':
400
				$this->loadFromId( $flags );
401
				break;
402
			case 'session':
403
				if ( !$this->loadFromSession() ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->loadFromSession() of type null|boolean is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
404
					// Loading from session failed. Load defaults.
405
					$this->loadDefaults();
406
				}
407
				Hooks::run( 'UserLoadAfterLoadFromSession', [ $this ] );
408
				break;
409
			default:
410
				throw new UnexpectedValueException(
411
					"Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
412
		}
413
	}
414
415
	/**
416
	 * Load user table data, given mId has already been set.
417
	 * @param integer $flags User::READ_* constant bitfield
418
	 * @return bool False if the ID does not exist, true otherwise
419
	 */
420
	public function loadFromId( $flags = self::READ_NORMAL ) {
421
		if ( $this->mId == 0 ) {
422
			// Anonymous users are not in the database (don't need cache)
423
			$this->loadDefaults();
424
			return false;
425
		}
426
427
		// Try cache (unless this needs data from the master DB).
428
		// NOTE: if this thread called saveSettings(), the cache was cleared.
429
		$latest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
430
		if ( $latest ) {
431
			if ( !$this->loadFromDatabase( $flags ) ) {
432
				// Can't load from ID
433
				return false;
434
			}
435
		} else {
436
			$this->loadFromCache();
437
		}
438
439
		$this->mLoadedItems = true;
0 ignored issues
show
Documentation Bug introduced by
It seems like true of type boolean is incompatible with the declared type array of property $mLoadedItems.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
440
		$this->queryFlagsUsed = $flags;
441
442
		return true;
443
	}
444
445
	/**
446
	 * @since 1.27
447
	 * @param string $wikiId
448
	 * @param integer $userId
449
	 */
450
	public static function purge( $wikiId, $userId ) {
451
		$cache = ObjectCache::getMainWANInstance();
452
		$key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
453
		$cache->delete( $key );
454
	}
455
456
	/**
457
	 * @since 1.27
458
	 * @param WANObjectCache $cache
459
	 * @return string
460
	 */
461
	protected function getCacheKey( WANObjectCache $cache ) {
462
		return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId );
463
	}
464
465
	/**
466
	 * Load user data from shared cache, given mId has already been set.
467
	 *
468
	 * @return bool True
469
	 * @since 1.25
470
	 */
471
	protected function loadFromCache() {
472
		$cache = ObjectCache::getMainWANInstance();
473
		$data = $cache->getWithSetCallback(
474
			$this->getCacheKey( $cache ),
475
			$cache::TTL_HOUR,
476
			function ( $oldValue, &$ttl, array &$setOpts ) {
477
				$setOpts += Database::getCacheSetOptions( wfGetDB( DB_SLAVE ) );
478
				wfDebug( "User: cache miss for user {$this->mId}\n" );
479
480
				$this->loadFromDatabase();
481
				$this->loadGroups();
482
				$this->loadOptions();
483
484
				$data = [];
485
				foreach ( self::$mCacheVars as $name ) {
486
					$data[$name] = $this->$name;
487
				}
488
489
				return $data;
490
491
			},
492
			[ 'pcTTL' => $cache::TTL_PROC_LONG, 'version' => self::VERSION ]
493
		);
494
495
		// Restore from cache
496
		foreach ( self::$mCacheVars as $name ) {
497
			$this->$name = $data[$name];
498
		}
499
500
		return true;
501
	}
502
503
	/** @name newFrom*() static factory methods */
504
	// @{
505
506
	/**
507
	 * Static factory method for creation from username.
508
	 *
509
	 * This is slightly less efficient than newFromId(), so use newFromId() if
510
	 * you have both an ID and a name handy.
511
	 *
512
	 * @param string $name Username, validated by Title::newFromText()
513
	 * @param string|bool $validate Validate username. Takes the same parameters as
514
	 *  User::getCanonicalName(), except that true is accepted as an alias
515
	 *  for 'valid', for BC.
516
	 *
517
	 * @return User|bool User object, or false if the username is invalid
518
	 *  (e.g. if it contains illegal characters or is an IP address). If the
519
	 *  username is not present in the database, the result will be a user object
520
	 *  with a name, zero user ID and default settings.
521
	 */
522
	public static function newFromName( $name, $validate = 'valid' ) {
523
		if ( $validate === true ) {
524
			$validate = 'valid';
525
		}
526
		$name = self::getCanonicalName( $name, $validate );
527
		if ( $name === false ) {
528
			return false;
529
		} else {
530
			// Create unloaded user object
531
			$u = new User;
532
			$u->mName = $name;
0 ignored issues
show
Documentation Bug introduced by
It seems like $name can also be of type boolean. However, the property $mName is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
533
			$u->mFrom = 'name';
534
			$u->setItemLoaded( 'name' );
535
			return $u;
536
		}
537
	}
538
539
	/**
540
	 * Static factory method for creation from a given user ID.
541
	 *
542
	 * @param int $id Valid user ID
543
	 * @return User The corresponding User object
544
	 */
545
	public static function newFromId( $id ) {
546
		$u = new User;
547
		$u->mId = $id;
548
		$u->mFrom = 'id';
549
		$u->setItemLoaded( 'id' );
550
		return $u;
551
	}
552
553
	/**
554
	 * Factory method to fetch whichever user has a given email confirmation code.
555
	 * This code is generated when an account is created or its e-mail address
556
	 * has changed.
557
	 *
558
	 * If the code is invalid or has expired, returns NULL.
559
	 *
560
	 * @param string $code Confirmation code
561
	 * @param int $flags User::READ_* bitfield
562
	 * @return User|null
563
	 */
564
	public static function newFromConfirmationCode( $code, $flags = 0 ) {
565
		$db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
566
			? wfGetDB( DB_MASTER )
567
			: wfGetDB( DB_SLAVE );
568
569
		$id = $db->selectField(
570
			'user',
571
			'user_id',
572
			[
573
				'user_email_token' => md5( $code ),
574
				'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
0 ignored issues
show
Security Bug introduced by
It seems like $db->timestamp() targeting DatabaseBase::timestamp() can also be of type false; however, DatabaseBase::addQuotes() does only seem to accept string|object<Blob>, did you maybe forget to handle an error condition?
Loading history...
575
			]
576
		);
577
578
		return $id ? User::newFromId( $id ) : null;
579
	}
580
581
	/**
582
	 * Create a new user object using data from session. If the login
583
	 * credentials are invalid, the result is an anonymous user.
584
	 *
585
	 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
586
	 * @return User
587
	 */
588
	public static function newFromSession( WebRequest $request = null ) {
589
		$user = new User;
590
		$user->mFrom = 'session';
591
		$user->mRequest = $request;
592
		return $user;
593
	}
594
595
	/**
596
	 * Create a new user object from a user row.
597
	 * The row should have the following fields from the user table in it:
598
	 * - either user_name or user_id to load further data if needed (or both)
599
	 * - user_real_name
600
	 * - all other fields (email, etc.)
601
	 * It is useless to provide the remaining fields if either user_id,
602
	 * user_name and user_real_name are not provided because the whole row
603
	 * will be loaded once more from the database when accessing them.
604
	 *
605
	 * @param stdClass $row A row from the user table
606
	 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
607
	 * @return User
608
	 */
609
	public static function newFromRow( $row, $data = null ) {
610
		$user = new User;
611
		$user->loadFromRow( $row, $data );
612
		return $user;
613
	}
614
615
	/**
616
	 * Static factory method for creation of a "system" user from username.
617
	 *
618
	 * A "system" user is an account that's used to attribute logged actions
619
	 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
620
	 * might include the 'Maintenance script' or 'Conversion script' accounts
621
	 * used by various scripts in the maintenance/ directory or accounts such
622
	 * as 'MediaWiki message delivery' used by the MassMessage extension.
623
	 *
624
	 * This can optionally create the user if it doesn't exist, and "steal" the
625
	 * account if it does exist.
626
	 *
627
	 * "Stealing" an existing user is intended to make it impossible for normal
628
	 * authentication processes to use the account, effectively disabling the
629
	 * account for normal use:
630
	 * - Email is invalidated, to prevent account recovery by emailing a
631
	 *   temporary password and to disassociate the account from the existing
632
	 *   human.
633
	 * - The token is set to a magic invalid value, to kill existing sessions
634
	 *   and to prevent $this->setToken() calls from resetting the token to a
635
	 *   valid value.
636
	 * - SessionManager is instructed to prevent new sessions for the user, to
637
	 *   do things like deauthorizing OAuth consumers.
638
	 * - AuthManager is instructed to revoke access, to invalidate or remove
639
	 *   passwords and other credentials.
640
	 *
641
	 * @param string $name Username
642
	 * @param array $options Options are:
643
	 *  - validate: As for User::getCanonicalName(), default 'valid'
644
	 *  - create: Whether to create the user if it doesn't already exist, default true
645
	 *  - steal: Whether to "disable" the account for normal use if it already
646
	 *    exists, default false
647
	 * @return User|null
648
	 * @since 1.27
649
	 */
650
	public static function newSystemUser( $name, $options = [] ) {
651
		global $wgDisableAuthManager;
652
653
		$options += [
654
			'validate' => 'valid',
655
			'create' => true,
656
			'steal' => false,
657
		];
658
659
		$name = self::getCanonicalName( $name, $options['validate'] );
660
		if ( $name === false ) {
661
			return null;
662
		}
663
664
		$fields = self::selectFields();
665
		if ( $wgDisableAuthManager ) {
666
			$fields = array_merge( $fields, [ 'user_password', 'user_newpassword' ] );
667
		}
668
669
		$dbw = wfGetDB( DB_MASTER );
670
		$row = $dbw->selectRow(
671
			'user',
672
			$fields,
673
			[ 'user_name' => $name ],
674
			__METHOD__
675
		);
676
		if ( !$row ) {
677
			// No user. Create it?
678
			return $options['create'] ? self::createNew( $name ) : null;
0 ignored issues
show
Bug introduced by
It seems like $name defined by self::getCanonicalName($..., $options['validate']) on line 659 can also be of type boolean; however, User::createNew() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
679
		}
680
		$user = self::newFromRow( $row );
0 ignored issues
show
Bug introduced by
It seems like $row defined by $dbw->selectRow('user', ... => $name), __METHOD__) on line 670 can also be of type boolean; however, User::newFromRow() does only seem to accept object<stdClass>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
681
682
		// A user is considered to exist as a non-system user if it can
683
		// authenticate, or has an email set, or has a non-invalid token.
684
		if ( !$user->mEmail && $user->mToken === self::INVALID_TOKEN ) {
685
			if ( $wgDisableAuthManager ) {
686
				$passwordFactory = new PasswordFactory();
687
				$passwordFactory->init( RequestContext::getMain()->getConfig() );
688
				try {
689
					$password = $passwordFactory->newFromCiphertext( $row->user_password );
690
				} catch ( PasswordError $e ) {
691
					wfDebug( 'Invalid password hash found in database.' );
692
					$password = PasswordFactory::newInvalidPassword();
693
				}
694
				try {
695
					$newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
696
				} catch ( PasswordError $e ) {
697
					wfDebug( 'Invalid password hash found in database.' );
698
					$newpassword = PasswordFactory::newInvalidPassword();
699
				}
700
				$canAuthenticate = !$password instanceof InvalidPassword ||
701
					!$newpassword instanceof InvalidPassword;
702
			} else {
703
				$canAuthenticate = AuthManager::singleton()->userCanAuthenticate( $name );
0 ignored issues
show
Bug introduced by
It seems like $name defined by self::getCanonicalName($..., $options['validate']) on line 659 can also be of type boolean; however, MediaWiki\Auth\AuthManager::userCanAuthenticate() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
704
			}
705
		}
706
		if ( $user->mEmail || $user->mToken !== self::INVALID_TOKEN || $canAuthenticate ) {
0 ignored issues
show
Bug introduced by
The variable $canAuthenticate does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
707
			// User exists. Steal it?
708
			if ( !$options['steal'] ) {
709
				return null;
710
			}
711
712
			if ( $wgDisableAuthManager ) {
713
				$nopass = PasswordFactory::newInvalidPassword()->toString();
714
				$dbw->update(
715
					'user',
716
					[
717
						'user_password' => $nopass,
718
						'user_newpassword' => $nopass,
719
						'user_newpass_time' => null,
720
					],
721
					[ 'user_id' => $user->getId() ],
722
					__METHOD__
723
				);
724
			} else {
725
				AuthManager::singleton()->revokeAccessForUser( $name );
0 ignored issues
show
Bug introduced by
It seems like $name defined by self::getCanonicalName($..., $options['validate']) on line 659 can also be of type boolean; however, MediaWiki\Auth\AuthManager::revokeAccessForUser() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
726
			}
727
728
			$user->invalidateEmail();
729
			$user->mToken = self::INVALID_TOKEN;
730
			$user->saveSettings();
731
			SessionManager::singleton()->preventSessionsForUser( $user->getName() );
732
		}
733
734
		return $user;
735
	}
736
737
	// @}
738
739
	/**
740
	 * Get the username corresponding to a given user ID
741
	 * @param int $id User ID
742
	 * @return string|bool The corresponding username
743
	 */
744
	public static function whoIs( $id ) {
745
		return UserCache::singleton()->getProp( $id, 'name' );
746
	}
747
748
	/**
749
	 * Get the real name of a user given their user ID
750
	 *
751
	 * @param int $id User ID
752
	 * @return string|bool The corresponding user's real name
753
	 */
754
	public static function whoIsReal( $id ) {
755
		return UserCache::singleton()->getProp( $id, 'real_name' );
756
	}
757
758
	/**
759
	 * Get database id given a user name
760
	 * @param string $name Username
761
	 * @param integer $flags User::READ_* constant bitfield
762
	 * @return int|null The corresponding user's ID, or null if user is nonexistent
763
	 */
764
	public static function idFromName( $name, $flags = self::READ_NORMAL ) {
765
		$nt = Title::makeTitleSafe( NS_USER, $name );
766
		if ( is_null( $nt ) ) {
767
			// Illegal name
768
			return null;
769
		}
770
771
		if ( !( $flags & self::READ_LATEST ) && isset( self::$idCacheByName[$name] ) ) {
772
			return self::$idCacheByName[$name];
773
		}
774
775
		$db = ( $flags & self::READ_LATEST )
776
			? wfGetDB( DB_MASTER )
777
			: wfGetDB( DB_SLAVE );
778
779
		$s = $db->selectRow(
780
			'user',
781
			[ 'user_id' ],
782
			[ 'user_name' => $nt->getText() ],
783
			__METHOD__
784
		);
785
786
		if ( $s === false ) {
787
			$result = null;
788
		} else {
789
			$result = $s->user_id;
790
		}
791
792
		self::$idCacheByName[$name] = $result;
793
794
		if ( count( self::$idCacheByName ) > 1000 ) {
795
			self::$idCacheByName = [];
796
		}
797
798
		return $result;
799
	}
800
801
	/**
802
	 * Reset the cache used in idFromName(). For use in tests.
803
	 */
804
	public static function resetIdByNameCache() {
805
		self::$idCacheByName = [];
806
	}
807
808
	/**
809
	 * Does the string match an anonymous IPv4 address?
810
	 *
811
	 * This function exists for username validation, in order to reject
812
	 * usernames which are similar in form to IP addresses. Strings such
813
	 * as 300.300.300.300 will return true because it looks like an IP
814
	 * address, despite not being strictly valid.
815
	 *
816
	 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
817
	 * address because the usemod software would "cloak" anonymous IP
818
	 * addresses like this, if we allowed accounts like this to be created
819
	 * new users could get the old edits of these anonymous users.
820
	 *
821
	 * @param string $name Name to match
822
	 * @return bool
823
	 */
824
	public static function isIP( $name ) {
825
		return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
826
			|| IP::isIPv6( $name );
827
	}
828
829
	/**
830
	 * Is the input a valid username?
831
	 *
832
	 * Checks if the input is a valid username, we don't want an empty string,
833
	 * an IP address, anything that contains slashes (would mess up subpages),
834
	 * is longer than the maximum allowed username size or doesn't begin with
835
	 * a capital letter.
836
	 *
837
	 * @param string $name Name to match
838
	 * @return bool
839
	 */
840
	public static function isValidUserName( $name ) {
841
		global $wgContLang, $wgMaxNameChars;
842
843
		if ( $name == ''
844
			|| User::isIP( $name )
845
			|| strpos( $name, '/' ) !== false
846
			|| strlen( $name ) > $wgMaxNameChars
847
			|| $name != $wgContLang->ucfirst( $name )
848
		) {
849
			return false;
850
		}
851
852
		// Ensure that the name can't be misresolved as a different title,
853
		// such as with extra namespace keys at the start.
854
		$parsed = Title::newFromText( $name );
855
		if ( is_null( $parsed )
856
			|| $parsed->getNamespace()
857
			|| strcmp( $name, $parsed->getPrefixedText() ) ) {
858
			return false;
859
		}
860
861
		// Check an additional blacklist of troublemaker characters.
862
		// Should these be merged into the title char list?
863
		$unicodeBlacklist = '/[' .
864
			'\x{0080}-\x{009f}' . # iso-8859-1 control chars
865
			'\x{00a0}' .          # non-breaking space
866
			'\x{2000}-\x{200f}' . # various whitespace
867
			'\x{2028}-\x{202f}' . # breaks and control chars
868
			'\x{3000}' .          # ideographic space
869
			'\x{e000}-\x{f8ff}' . # private use
870
			']/u';
871
		if ( preg_match( $unicodeBlacklist, $name ) ) {
872
			return false;
873
		}
874
875
		return true;
876
	}
877
878
	/**
879
	 * Usernames which fail to pass this function will be blocked
880
	 * from user login and new account registrations, but may be used
881
	 * internally by batch processes.
882
	 *
883
	 * If an account already exists in this form, login will be blocked
884
	 * by a failure to pass this function.
885
	 *
886
	 * @param string $name Name to match
887
	 * @return bool
888
	 */
889
	public static function isUsableName( $name ) {
890
		global $wgReservedUsernames;
891
		// Must be a valid username, obviously ;)
892
		if ( !self::isValidUserName( $name ) ) {
893
			return false;
894
		}
895
896
		static $reservedUsernames = false;
897
		if ( !$reservedUsernames ) {
898
			$reservedUsernames = $wgReservedUsernames;
899
			Hooks::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
900
		}
901
902
		// Certain names may be reserved for batch processes.
903
		foreach ( $reservedUsernames as $reserved ) {
904
			if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
905
				$reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
906
			}
907
			if ( $reserved == $name ) {
908
				return false;
909
			}
910
		}
911
		return true;
912
	}
913
914
	/**
915
	 * Usernames which fail to pass this function will be blocked
916
	 * from new account registrations, but may be used internally
917
	 * either by batch processes or by user accounts which have
918
	 * already been created.
919
	 *
920
	 * Additional blacklisting may be added here rather than in
921
	 * isValidUserName() to avoid disrupting existing accounts.
922
	 *
923
	 * @param string $name String to match
924
	 * @return bool
925
	 */
926
	public static function isCreatableName( $name ) {
927
		global $wgInvalidUsernameCharacters;
928
929
		// Ensure that the username isn't longer than 235 bytes, so that
930
		// (at least for the builtin skins) user javascript and css files
931
		// will work. (bug 23080)
932
		if ( strlen( $name ) > 235 ) {
933
			wfDebugLog( 'username', __METHOD__ .
934
				": '$name' invalid due to length" );
935
			return false;
936
		}
937
938
		// Preg yells if you try to give it an empty string
939
		if ( $wgInvalidUsernameCharacters !== '' ) {
940
			if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
941
				wfDebugLog( 'username', __METHOD__ .
942
					": '$name' invalid due to wgInvalidUsernameCharacters" );
943
				return false;
944
			}
945
		}
946
947
		return self::isUsableName( $name );
948
	}
949
950
	/**
951
	 * Is the input a valid password for this user?
952
	 *
953
	 * @param string $password Desired password
954
	 * @return bool
955
	 */
956
	public function isValidPassword( $password ) {
957
		// simple boolean wrapper for getPasswordValidity
958
		return $this->getPasswordValidity( $password ) === true;
959
	}
960
961
	/**
962
	 * Given unvalidated password input, return error message on failure.
963
	 *
964
	 * @param string $password Desired password
965
	 * @return bool|string|array True on success, string or array of error message on failure
966
	 */
967
	public function getPasswordValidity( $password ) {
968
		$result = $this->checkPasswordValidity( $password );
969
		if ( $result->isGood() ) {
970
			return true;
971
		} else {
972
			$messages = [];
973
			foreach ( $result->getErrorsByType( 'error' ) as $error ) {
974
				$messages[] = $error['message'];
975
			}
976
			foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
977
				$messages[] = $warning['message'];
978
			}
979
			if ( count( $messages ) === 1 ) {
980
				return $messages[0];
981
			}
982
			return $messages;
983
		}
984
	}
985
986
	/**
987
	 * Check if this is a valid password for this user
988
	 *
989
	 * Create a Status object based on the password's validity.
990
	 * The Status should be set to fatal if the user should not
991
	 * be allowed to log in, and should have any errors that
992
	 * would block changing the password.
993
	 *
994
	 * If the return value of this is not OK, the password
995
	 * should not be checked. If the return value is not Good,
996
	 * the password can be checked, but the user should not be
997
	 * able to set their password to this.
998
	 *
999
	 * @param string $password Desired password
1000
	 * @param string $purpose one of 'login', 'create', 'reset'
1001
	 * @return Status
1002
	 * @since 1.23
1003
	 */
1004
	public function checkPasswordValidity( $password, $purpose = 'login' ) {
1005
		global $wgPasswordPolicy;
1006
1007
		$upp = new UserPasswordPolicy(
1008
			$wgPasswordPolicy['policies'],
1009
			$wgPasswordPolicy['checks']
1010
		);
1011
1012
		$status = Status::newGood();
1013
		$result = false; // init $result to false for the internal checks
1014
1015
		if ( !Hooks::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1016
			$status->error( $result );
1017
			return $status;
1018
		}
1019
1020
		if ( $result === false ) {
1021
			$status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1022
			return $status;
1023
		} elseif ( $result === true ) {
1024
			return $status;
1025
		} else {
1026
			$status->error( $result );
1027
			return $status; // the isValidPassword hook set a string $result and returned true
1028
		}
1029
	}
1030
1031
	/**
1032
	 * Given unvalidated user input, return a canonical username, or false if
1033
	 * the username is invalid.
1034
	 * @param string $name User input
1035
	 * @param string|bool $validate Type of validation to use:
1036
	 *   - false        No validation
1037
	 *   - 'valid'      Valid for batch processes
1038
	 *   - 'usable'     Valid for batch processes and login
1039
	 *   - 'creatable'  Valid for batch processes, login and account creation
1040
	 *
1041
	 * @throws InvalidArgumentException
1042
	 * @return bool|string
1043
	 */
1044
	public static function getCanonicalName( $name, $validate = 'valid' ) {
1045
		// Force usernames to capital
1046
		global $wgContLang;
1047
		$name = $wgContLang->ucfirst( $name );
1048
1049
		# Reject names containing '#'; these will be cleaned up
1050
		# with title normalisation, but then it's too late to
1051
		# check elsewhere
1052
		if ( strpos( $name, '#' ) !== false ) {
1053
			return false;
1054
		}
1055
1056
		// Clean up name according to title rules,
1057
		// but only when validation is requested (bug 12654)
1058
		$t = ( $validate !== false ) ?
1059
			Title::newFromText( $name, NS_USER ) : Title::makeTitle( NS_USER, $name );
1060
		// Check for invalid titles
1061
		if ( is_null( $t ) || $t->getNamespace() !== NS_USER || $t->isExternal() ) {
1062
			return false;
1063
		}
1064
1065
		// Reject various classes of invalid names
1066
		$name = AuthManager::callLegacyAuthPlugin(
0 ignored issues
show
Deprecated Code introduced by
The method MediaWiki\Auth\AuthManager::callLegacyAuthPlugin() has been deprecated with message: For backwards compatibility only, should be avoided in new code

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1067
			'getCanonicalName', [ $t->getText() ], $t->getText()
1068
		);
1069
1070
		switch ( $validate ) {
1071
			case false:
1072
				break;
1073
			case 'valid':
1074
				if ( !User::isValidUserName( $name ) ) {
1075
					$name = false;
1076
				}
1077
				break;
1078
			case 'usable':
1079
				if ( !User::isUsableName( $name ) ) {
1080
					$name = false;
1081
				}
1082
				break;
1083
			case 'creatable':
1084
				if ( !User::isCreatableName( $name ) ) {
1085
					$name = false;
1086
				}
1087
				break;
1088
			default:
1089
				throw new InvalidArgumentException(
1090
					'Invalid parameter value for $validate in ' . __METHOD__ );
1091
		}
1092
		return $name;
1093
	}
1094
1095
	/**
1096
	 * Count the number of edits of a user
1097
	 *
1098
	 * @param int $uid User ID to check
1099
	 * @return int The user's edit count
1100
	 *
1101
	 * @deprecated since 1.21 in favour of User::getEditCount
1102
	 */
1103
	public static function edits( $uid ) {
1104
		wfDeprecated( __METHOD__, '1.21' );
1105
		$user = self::newFromId( $uid );
1106
		return $user->getEditCount();
1107
	}
1108
1109
	/**
1110
	 * Return a random password.
1111
	 *
1112
	 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1113
	 * @return string New random password
1114
	 */
1115
	public static function randomPassword() {
1116
		global $wgMinimalPasswordLength;
1117
		return PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
1118
	}
1119
1120
	/**
1121
	 * Set cached properties to default.
1122
	 *
1123
	 * @note This no longer clears uncached lazy-initialised properties;
1124
	 *       the constructor does that instead.
1125
	 *
1126
	 * @param string|bool $name
1127
	 */
1128
	public function loadDefaults( $name = false ) {
1129
		$this->mId = 0;
1130
		$this->mName = $name;
0 ignored issues
show
Documentation Bug introduced by
It seems like $name can also be of type boolean. However, the property $mName is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1131
		$this->mRealName = '';
1132
		$this->mEmail = '';
1133
		$this->mOptionOverrides = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $mOptionOverrides.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1134
		$this->mOptionsLoaded = false;
1135
1136
		$loggedOut = $this->mRequest && !defined( 'MW_NO_SESSION' )
1137
			? $this->mRequest->getSession()->getLoggedOutTimestamp() : 0;
1138
		if ( $loggedOut !== 0 ) {
1139
			$this->mTouched = wfTimestamp( TS_MW, $loggedOut );
0 ignored issues
show
Documentation Bug introduced by
It seems like wfTimestamp(TS_MW, $loggedOut) can also be of type false. However, the property $mTouched is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1140
		} else {
1141
			$this->mTouched = '1'; # Allow any pages to be cached
1142
		}
1143
1144
		$this->mToken = null; // Don't run cryptographic functions till we need a token
1145
		$this->mEmailAuthenticated = null;
1146
		$this->mEmailToken = '';
1147
		$this->mEmailTokenExpires = null;
1148
		$this->mRegistration = wfTimestamp( TS_MW );
0 ignored issues
show
Documentation Bug introduced by
It seems like wfTimestamp(TS_MW) can also be of type false. However, the property $mRegistration is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1149
		$this->mGroups = [];
1150
1151
		Hooks::run( 'UserLoadDefaults', [ $this, $name ] );
1152
	}
1153
1154
	/**
1155
	 * Return whether an item has been loaded.
1156
	 *
1157
	 * @param string $item Item to check. Current possibilities:
1158
	 *   - id
1159
	 *   - name
1160
	 *   - realname
1161
	 * @param string $all 'all' to check if the whole object has been loaded
1162
	 *   or any other string to check if only the item is available (e.g.
1163
	 *   for optimisation)
1164
	 * @return bool
1165
	 */
1166
	public function isItemLoaded( $item, $all = 'all' ) {
1167
		return ( $this->mLoadedItems === true && $all === 'all' ) ||
1168
			( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1169
	}
1170
1171
	/**
1172
	 * Set that an item has been loaded
1173
	 *
1174
	 * @param string $item
1175
	 */
1176
	protected function setItemLoaded( $item ) {
1177
		if ( is_array( $this->mLoadedItems ) ) {
1178
			$this->mLoadedItems[$item] = true;
1179
		}
1180
	}
1181
1182
	/**
1183
	 * Load user data from the session.
1184
	 *
1185
	 * @return bool True if the user is logged in, false otherwise.
1186
	 */
1187
	private function loadFromSession() {
1188
		// Deprecated hook
1189
		$result = null;
1190
		Hooks::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1191
		if ( $result !== null ) {
1192
			return $result;
1193
		}
1194
1195
		// MediaWiki\Session\Session already did the necessary authentication of the user
1196
		// returned here, so just use it if applicable.
1197
		$session = $this->getRequest()->getSession();
1198
		$user = $session->getUser();
1199
		if ( $user->isLoggedIn() ) {
1200
			$this->loadFromUserObject( $user );
1201
			// Other code expects these to be set in the session, so set them.
1202
			$session->set( 'wsUserID', $this->getId() );
1203
			$session->set( 'wsUserName', $this->getName() );
1204
			$session->set( 'wsToken', $this->getToken() );
1205
			return true;
1206
		}
1207
1208
		return false;
1209
	}
1210
1211
	/**
1212
	 * Load user and user_group data from the database.
1213
	 * $this->mId must be set, this is how the user is identified.
1214
	 *
1215
	 * @param integer $flags User::READ_* constant bitfield
1216
	 * @return bool True if the user exists, false if the user is anonymous
1217
	 */
1218
	public function loadFromDatabase( $flags = self::READ_LATEST ) {
1219
		// Paranoia
1220
		$this->mId = intval( $this->mId );
1221
1222
		if ( !$this->mId ) {
1223
			// Anonymous users are not in the database
1224
			$this->loadDefaults();
1225
			return false;
1226
		}
1227
1228
		list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
1229
		$db = wfGetDB( $index );
1230
1231
		$s = $db->selectRow(
1232
			'user',
1233
			self::selectFields(),
1234
			[ 'user_id' => $this->mId ],
1235
			__METHOD__,
1236
			$options
1237
		);
1238
1239
		$this->queryFlagsUsed = $flags;
1240
		Hooks::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1241
1242
		if ( $s !== false ) {
1243
			// Initialise user table data
1244
			$this->loadFromRow( $s );
0 ignored issues
show
Bug introduced by
It seems like $s defined by $db->selectRow('user', s..., __METHOD__, $options) on line 1231 can also be of type boolean; however, User::loadFromRow() does only seem to accept object<stdClass>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1245
			$this->mGroups = null; // deferred
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $mGroups.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1246
			$this->getEditCount(); // revalidation for nulls
1247
			return true;
1248
		} else {
1249
			// Invalid user_id
1250
			$this->mId = 0;
1251
			$this->loadDefaults();
1252
			return false;
1253
		}
1254
	}
1255
1256
	/**
1257
	 * Initialize this object from a row from the user table.
1258
	 *
1259
	 * @param stdClass $row Row from the user table to load.
1260
	 * @param array $data Further user data to load into the object
1261
	 *
1262
	 *	user_groups		Array with groups out of the user_groups table
1263
	 *	user_properties		Array with properties out of the user_properties table
1264
	 */
1265
	protected function loadFromRow( $row, $data = null ) {
1266
		$all = true;
1267
1268
		$this->mGroups = null; // deferred
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $mGroups.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1269
1270 View Code Duplication
		if ( isset( $row->user_name ) ) {
1271
			$this->mName = $row->user_name;
1272
			$this->mFrom = 'name';
1273
			$this->setItemLoaded( 'name' );
1274
		} else {
1275
			$all = false;
1276
		}
1277
1278
		if ( isset( $row->user_real_name ) ) {
1279
			$this->mRealName = $row->user_real_name;
1280
			$this->setItemLoaded( 'realname' );
1281
		} else {
1282
			$all = false;
1283
		}
1284
1285 View Code Duplication
		if ( isset( $row->user_id ) ) {
1286
			$this->mId = intval( $row->user_id );
1287
			$this->mFrom = 'id';
1288
			$this->setItemLoaded( 'id' );
1289
		} else {
1290
			$all = false;
1291
		}
1292
1293
		if ( isset( $row->user_id ) && isset( $row->user_name ) ) {
1294
			self::$idCacheByName[$row->user_name] = $row->user_id;
1295
		}
1296
1297
		if ( isset( $row->user_editcount ) ) {
1298
			$this->mEditCount = $row->user_editcount;
1299
		} else {
1300
			$all = false;
1301
		}
1302
1303
		if ( isset( $row->user_touched ) ) {
1304
			$this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
0 ignored issues
show
Documentation Bug introduced by
It seems like wfTimestamp(TS_MW, $row->user_touched) can also be of type false. However, the property $mTouched is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1305
		} else {
1306
			$all = false;
1307
		}
1308
1309
		if ( isset( $row->user_token ) ) {
1310
			// The definition for the column is binary(32), so trim the NULs
1311
			// that appends. The previous definition was char(32), so trim
1312
			// spaces too.
1313
			$this->mToken = rtrim( $row->user_token, " \0" );
1314
			if ( $this->mToken === '' ) {
1315
				$this->mToken = null;
1316
			}
1317
		} else {
1318
			$all = false;
1319
		}
1320
1321
		if ( isset( $row->user_email ) ) {
1322
			$this->mEmail = $row->user_email;
1323
			$this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
0 ignored issues
show
Documentation Bug introduced by
It seems like wfTimestampOrNull(TS_MW,...er_email_authenticated) can also be of type false. However, the property $mEmailAuthenticated is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1324
			$this->mEmailToken = $row->user_email_token;
1325
			$this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
0 ignored issues
show
Documentation Bug introduced by
It seems like wfTimestampOrNull(TS_MW,...er_email_token_expires) can also be of type false. However, the property $mEmailTokenExpires is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1326
			$this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
0 ignored issues
show
Documentation Bug introduced by
It seems like wfTimestampOrNull(TS_MW, $row->user_registration) can also be of type false. However, the property $mRegistration is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1327
		} else {
1328
			$all = false;
1329
		}
1330
1331
		if ( $all ) {
1332
			$this->mLoadedItems = true;
0 ignored issues
show
Documentation Bug introduced by
It seems like true of type boolean is incompatible with the declared type array of property $mLoadedItems.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1333
		}
1334
1335
		if ( is_array( $data ) ) {
1336
			if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1337
				$this->mGroups = $data['user_groups'];
1338
			}
1339
			if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1340
				$this->loadOptions( $data['user_properties'] );
1341
			}
1342
		}
1343
	}
1344
1345
	/**
1346
	 * Load the data for this user object from another user object.
1347
	 *
1348
	 * @param User $user
1349
	 */
1350
	protected function loadFromUserObject( $user ) {
1351
		$user->load();
1352
		$user->loadGroups();
1353
		$user->loadOptions();
1354
		foreach ( self::$mCacheVars as $var ) {
1355
			$this->$var = $user->$var;
1356
		}
1357
	}
1358
1359
	/**
1360
	 * Load the groups from the database if they aren't already loaded.
1361
	 */
1362 View Code Duplication
	private function loadGroups() {
1363
		if ( is_null( $this->mGroups ) ) {
1364
			$db = ( $this->queryFlagsUsed & self::READ_LATEST )
1365
				? wfGetDB( DB_MASTER )
1366
				: wfGetDB( DB_SLAVE );
1367
			$res = $db->select( 'user_groups',
1368
				[ 'ug_group' ],
1369
				[ 'ug_user' => $this->mId ],
1370
				__METHOD__ );
1371
			$this->mGroups = [];
1372
			foreach ( $res as $row ) {
0 ignored issues
show
Bug introduced by
The expression $res of type boolean|object<ResultWrapper> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1373
				$this->mGroups[] = $row->ug_group;
1374
			}
1375
		}
1376
	}
1377
1378
	/**
1379
	 * Add the user to the group if he/she meets given criteria.
1380
	 *
1381
	 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1382
	 *   possible to remove manually via Special:UserRights. In such case it
1383
	 *   will not be re-added automatically. The user will also not lose the
1384
	 *   group if they no longer meet the criteria.
1385
	 *
1386
	 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1387
	 *
1388
	 * @return array Array of groups the user has been promoted to.
1389
	 *
1390
	 * @see $wgAutopromoteOnce
1391
	 */
1392
	public function addAutopromoteOnceGroups( $event ) {
1393
		global $wgAutopromoteOnceLogInRC;
1394
1395
		if ( wfReadOnly() || !$this->getId() ) {
1396
			return [];
1397
		}
1398
1399
		$toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1400
		if ( !count( $toPromote ) ) {
1401
			return [];
1402
		}
1403
1404
		if ( !$this->checkAndSetTouched() ) {
1405
			return []; // raced out (bug T48834)
1406
		}
1407
1408
		$oldGroups = $this->getGroups(); // previous groups
1409
		foreach ( $toPromote as $group ) {
1410
			$this->addGroup( $group );
1411
		}
1412
		// update groups in external authentication database
1413
		Hooks::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1414
		AuthManager::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
0 ignored issues
show
Deprecated Code introduced by
The method MediaWiki\Auth\AuthManager::callLegacyAuthPlugin() has been deprecated with message: For backwards compatibility only, should be avoided in new code

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1415
1416
		$newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1417
1418
		$logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1419
		$logEntry->setPerformer( $this );
1420
		$logEntry->setTarget( $this->getUserPage() );
1421
		$logEntry->setParameters( [
1422
			'4::oldgroups' => $oldGroups,
1423
			'5::newgroups' => $newGroups,
1424
		] );
1425
		$logid = $logEntry->insert();
1426
		if ( $wgAutopromoteOnceLogInRC ) {
1427
			$logEntry->publish( $logid );
1428
		}
1429
1430
		return $toPromote;
1431
	}
1432
1433
	/**
1434
	 * Builds update conditions. Additional conditions may be added to $conditions to
1435
	 * protected against race conditions using a compare-and-set (CAS) mechanism
1436
	 * based on comparing $this->mTouched with the user_touched field.
1437
	 *
1438
	 * @param DatabaseBase $db
1439
	 * @param array $conditions WHERE conditions for use with DatabaseBase::update
1440
	 * @return array WHERE conditions for use with DatabaseBase::update
1441
	 */
1442
	protected function makeUpdateConditions( DatabaseBase $db, array $conditions ) {
1443
		if ( $this->mTouched ) {
1444
			// CAS check: only update if the row wasn't changed sicne it was loaded.
1445
			$conditions['user_touched'] = $db->timestamp( $this->mTouched );
1446
		}
1447
1448
		return $conditions;
1449
	}
1450
1451
	/**
1452
	 * Bump user_touched if it didn't change since this object was loaded
1453
	 *
1454
	 * On success, the mTouched field is updated.
1455
	 * The user serialization cache is always cleared.
1456
	 *
1457
	 * @return bool Whether user_touched was actually updated
1458
	 * @since 1.26
1459
	 */
1460
	protected function checkAndSetTouched() {
1461
		$this->load();
1462
1463
		if ( !$this->mId ) {
1464
			return false; // anon
1465
		}
1466
1467
		// Get a new user_touched that is higher than the old one
1468
		$newTouched = $this->newTouchedTimestamp();
1469
1470
		$dbw = wfGetDB( DB_MASTER );
1471
		$dbw->update( 'user',
1472
			[ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1473
			$this->makeUpdateConditions( $dbw, [
1474
				'user_id' => $this->mId,
1475
			] ),
1476
			__METHOD__
1477
		);
1478
		$success = ( $dbw->affectedRows() > 0 );
1479
1480
		if ( $success ) {
1481
			$this->mTouched = $newTouched;
0 ignored issues
show
Documentation Bug introduced by
It seems like $newTouched can also be of type false. However, the property $mTouched is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1482
			$this->clearSharedCache();
1483
		} else {
1484
			// Clears on failure too since that is desired if the cache is stale
1485
			$this->clearSharedCache( 'refresh' );
1486
		}
1487
1488
		return $success;
1489
	}
1490
1491
	/**
1492
	 * Clear various cached data stored in this object. The cache of the user table
1493
	 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1494
	 *
1495
	 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1496
	 *   given source. May be "name", "id", "defaults", "session", or false for no reload.
1497
	 */
1498
	public function clearInstanceCache( $reloadFrom = false ) {
1499
		$this->mNewtalk = -1;
1500
		$this->mDatePreference = null;
1501
		$this->mBlockedby = -1; # Unset
0 ignored issues
show
Documentation Bug introduced by
The property $mBlockedby was declared of type string, but -1 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
1502
		$this->mHash = false;
0 ignored issues
show
Documentation Bug introduced by
The property $mHash was declared of type string, but false is of type false. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
1503
		$this->mRights = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $mRights.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1504
		$this->mEffectiveGroups = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $mEffectiveGroups.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1505
		$this->mImplicitGroups = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $mImplicitGroups.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1506
		$this->mGroups = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $mGroups.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1507
		$this->mOptions = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $mOptions.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1508
		$this->mOptionsLoaded = false;
1509
		$this->mEditCount = null;
1510
1511
		if ( $reloadFrom ) {
1512
			$this->mLoadedItems = [];
1513
			$this->mFrom = $reloadFrom;
1514
		}
1515
	}
1516
1517
	/**
1518
	 * Combine the language default options with any site-specific options
1519
	 * and add the default language variants.
1520
	 *
1521
	 * @return array Array of String options
1522
	 */
1523
	public static function getDefaultOptions() {
1524
		global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1525
1526
		static $defOpt = null;
1527
		if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1528
			// Disabling this for the unit tests, as they rely on being able to change $wgContLang
1529
			// mid-request and see that change reflected in the return value of this function.
1530
			// Which is insane and would never happen during normal MW operation
1531
			return $defOpt;
1532
		}
1533
1534
		$defOpt = $wgDefaultUserOptions;
1535
		// Default language setting
1536
		$defOpt['language'] = $wgContLang->getCode();
1537
		foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1538
			$defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1539
		}
1540
		$namespaces = MediaWikiServices::getInstance()->getSearchEngineConfig()->searchableNamespaces();
1541
		foreach ( $namespaces as $nsnum => $nsname ) {
1542
			$defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1543
		}
1544
		$defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1545
1546
		Hooks::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1547
1548
		return $defOpt;
1549
	}
1550
1551
	/**
1552
	 * Get a given default option value.
1553
	 *
1554
	 * @param string $opt Name of option to retrieve
1555
	 * @return string Default option value
1556
	 */
1557
	public static function getDefaultOption( $opt ) {
1558
		$defOpts = self::getDefaultOptions();
1559
		if ( isset( $defOpts[$opt] ) ) {
1560
			return $defOpts[$opt];
1561
		} else {
1562
			return null;
1563
		}
1564
	}
1565
1566
	/**
1567
	 * Get blocking information
1568
	 * @param bool $bFromSlave Whether to check the slave database first.
1569
	 *   To improve performance, non-critical checks are done against slaves.
1570
	 *   Check when actually saving should be done against master.
1571
	 */
1572
	private function getBlockedStatus( $bFromSlave = true ) {
1573
		global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1574
1575
		if ( -1 != $this->mBlockedby ) {
1576
			return;
1577
		}
1578
1579
		wfDebug( __METHOD__ . ": checking...\n" );
1580
1581
		// Initialize data...
1582
		// Otherwise something ends up stomping on $this->mBlockedby when
1583
		// things get lazy-loaded later, causing false positive block hits
1584
		// due to -1 !== 0. Probably session-related... Nothing should be
1585
		// overwriting mBlockedby, surely?
1586
		$this->load();
1587
1588
		# We only need to worry about passing the IP address to the Block generator if the
1589
		# user is not immune to autoblocks/hardblocks, and they are the current user so we
1590
		# know which IP address they're actually coming from
1591
		$ip = null;
1592
		if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1593
			// $wgUser->getName() only works after the end of Setup.php. Until
1594
			// then, assume it's a logged-out user.
1595
			$globalUserName = $wgUser->isSafeToLoad()
1596
				? $wgUser->getName()
1597
				: IP::sanitizeIP( $wgUser->getRequest()->getIP() );
1598
			if ( $this->getName() === $globalUserName ) {
1599
				$ip = $this->getRequest()->getIP();
1600
			}
1601
		}
1602
1603
		// User/IP blocking
1604
		$block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1605
1606
		// Proxy blocking
1607
		if ( !$block instanceof Block && $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1608
			// Local list
1609
			if ( self::isLocallyBlockedProxy( $ip ) ) {
1610
				$block = new Block;
1611
				$block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1612
				$block->mReason = wfMessage( 'proxyblockreason' )->text();
1613
				$block->setTarget( $ip );
1614
			} elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1615
				$block = new Block;
1616
				$block->setBlocker( wfMessage( 'sorbs' )->text() );
1617
				$block->mReason = wfMessage( 'sorbsreason' )->text();
1618
				$block->setTarget( $ip );
1619
			}
1620
		}
1621
1622
		// (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1623
		if ( !$block instanceof Block
1624
			&& $wgApplyIpBlocksToXff
1625
			&& $ip !== null
1626
			&& !in_array( $ip, $wgProxyWhitelist )
1627
		) {
1628
			$xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1629
			$xff = array_map( 'trim', explode( ',', $xff ) );
1630
			$xff = array_diff( $xff, [ $ip ] );
1631
			$xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1632
			$block = Block::chooseBlock( $xffblocks, $xff );
1633
			if ( $block instanceof Block ) {
1634
				# Mangle the reason to alert the user that the block
1635
				# originated from matching the X-Forwarded-For header.
1636
				$block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1637
			}
1638
		}
1639
1640
		if ( $block instanceof Block ) {
1641
			wfDebug( __METHOD__ . ": Found block.\n" );
1642
			$this->mBlock = $block;
1643
			$this->mBlockedby = $block->getByName();
1644
			$this->mBlockreason = $block->mReason;
1645
			$this->mHideName = $block->mHideName;
1646
			$this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1647
		} else {
1648
			$this->mBlockedby = '';
1649
			$this->mHideName = 0;
0 ignored issues
show
Documentation Bug introduced by
The property $mHideName was declared of type boolean, but 0 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
1650
			$this->mAllowUsertalk = false;
1651
		}
1652
1653
		// Extensions
1654
		Hooks::run( 'GetBlockedStatus', [ &$this ] );
1655
1656
	}
1657
1658
	/**
1659
	 * Whether the given IP is in a DNS blacklist.
1660
	 *
1661
	 * @param string $ip IP to check
1662
	 * @param bool $checkWhitelist Whether to check the whitelist first
1663
	 * @return bool True if blacklisted.
1664
	 */
1665
	public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1666
		global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1667
1668
		if ( !$wgEnableDnsBlacklist ) {
1669
			return false;
1670
		}
1671
1672
		if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1673
			return false;
1674
		}
1675
1676
		return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1677
	}
1678
1679
	/**
1680
	 * Whether the given IP is in a given DNS blacklist.
1681
	 *
1682
	 * @param string $ip IP to check
1683
	 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1684
	 * @return bool True if blacklisted.
1685
	 */
1686
	public function inDnsBlacklist( $ip, $bases ) {
1687
1688
		$found = false;
1689
		// @todo FIXME: IPv6 ???  (http://bugs.php.net/bug.php?id=33170)
1690
		if ( IP::isIPv4( $ip ) ) {
1691
			// Reverse IP, bug 21255
1692
			$ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1693
1694
			foreach ( (array)$bases as $base ) {
1695
				// Make hostname
1696
				// If we have an access key, use that too (ProjectHoneypot, etc.)
1697
				$basename = $base;
1698
				if ( is_array( $base ) ) {
1699
					if ( count( $base ) >= 2 ) {
1700
						// Access key is 1, base URL is 0
1701
						$host = "{$base[1]}.$ipReversed.{$base[0]}";
1702
					} else {
1703
						$host = "$ipReversed.{$base[0]}";
1704
					}
1705
					$basename = $base[0];
1706
				} else {
1707
					$host = "$ipReversed.$base";
1708
				}
1709
1710
				// Send query
1711
				$ipList = gethostbynamel( $host );
1712
1713
				if ( $ipList ) {
1714
					wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1715
					$found = true;
1716
					break;
1717
				} else {
1718
					wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1719
				}
1720
			}
1721
		}
1722
1723
		return $found;
1724
	}
1725
1726
	/**
1727
	 * Check if an IP address is in the local proxy list
1728
	 *
1729
	 * @param string $ip
1730
	 *
1731
	 * @return bool
1732
	 */
1733
	public static function isLocallyBlockedProxy( $ip ) {
1734
		global $wgProxyList;
1735
1736
		if ( !$wgProxyList ) {
1737
			return false;
1738
		}
1739
1740
		if ( !is_array( $wgProxyList ) ) {
1741
			// Load from the specified file
1742
			$wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1743
		}
1744
1745
		if ( !is_array( $wgProxyList ) ) {
1746
			$ret = false;
1747
		} elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1748
			$ret = true;
1749
		} elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1750
			// Old-style flipped proxy list
1751
			$ret = true;
1752
		} else {
1753
			$ret = false;
1754
		}
1755
		return $ret;
1756
	}
1757
1758
	/**
1759
	 * Is this user subject to rate limiting?
1760
	 *
1761
	 * @return bool True if rate limited
1762
	 */
1763
	public function isPingLimitable() {
1764
		global $wgRateLimitsExcludedIPs;
1765
		if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1766
			// No other good way currently to disable rate limits
1767
			// for specific IPs. :P
1768
			// But this is a crappy hack and should die.
1769
			return false;
1770
		}
1771
		return !$this->isAllowed( 'noratelimit' );
1772
	}
1773
1774
	/**
1775
	 * Primitive rate limits: enforce maximum actions per time period
1776
	 * to put a brake on flooding.
1777
	 *
1778
	 * The method generates both a generic profiling point and a per action one
1779
	 * (suffix being "-$action".
1780
	 *
1781
	 * @note When using a shared cache like memcached, IP-address
1782
	 * last-hit counters will be shared across wikis.
1783
	 *
1784
	 * @param string $action Action to enforce; 'edit' if unspecified
1785
	 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1786
	 * @return bool True if a rate limiter was tripped
1787
	 */
1788
	public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1789
		// Call the 'PingLimiter' hook
1790
		$result = false;
1791
		if ( !Hooks::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1792
			return $result;
1793
		}
1794
1795
		global $wgRateLimits;
1796
		if ( !isset( $wgRateLimits[$action] ) ) {
1797
			return false;
1798
		}
1799
1800
		// Some groups shouldn't trigger the ping limiter, ever
1801
		if ( !$this->isPingLimitable() ) {
1802
			return false;
1803
		}
1804
1805
		$limits = $wgRateLimits[$action];
1806
		$keys = [];
1807
		$id = $this->getId();
1808
		$userLimit = false;
1809
		$isNewbie = $this->isNewbie();
1810
1811
		if ( $id == 0 ) {
1812
			// limits for anons
1813 View Code Duplication
			if ( isset( $limits['anon'] ) ) {
1814
				$keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1815
			}
1816
		} else {
1817
			// limits for logged-in users
1818
			if ( isset( $limits['user'] ) ) {
1819
				$userLimit = $limits['user'];
1820
			}
1821
			// limits for newbie logged-in users
1822 View Code Duplication
			if ( $isNewbie && isset( $limits['newbie'] ) ) {
1823
				$keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1824
			}
1825
		}
1826
1827
		// limits for anons and for newbie logged-in users
1828
		if ( $isNewbie ) {
1829
			// ip-based limits
1830
			if ( isset( $limits['ip'] ) ) {
1831
				$ip = $this->getRequest()->getIP();
1832
				$keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1833
			}
1834
			// subnet-based limits
1835
			if ( isset( $limits['subnet'] ) ) {
1836
				$ip = $this->getRequest()->getIP();
1837
				$subnet = IP::getSubnet( $ip );
1838
				if ( $subnet !== false ) {
1839
					$keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1840
				}
1841
			}
1842
		}
1843
1844
		// Check for group-specific permissions
1845
		// If more than one group applies, use the group with the highest limit ratio (max/period)
1846
		foreach ( $this->getGroups() as $group ) {
1847
			if ( isset( $limits[$group] ) ) {
1848
				if ( $userLimit === false
1849
					|| $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1850
				) {
1851
					$userLimit = $limits[$group];
1852
				}
1853
			}
1854
		}
1855
1856
		// Set the user limit key
1857
		if ( $userLimit !== false ) {
1858
			list( $max, $period ) = $userLimit;
1859
			wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1860
			$keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1861
		}
1862
1863
		// ip-based limits for all ping-limitable users
1864
		if ( isset( $limits['ip-all'] ) ) {
1865
			$ip = $this->getRequest()->getIP();
1866
			// ignore if user limit is more permissive
1867 View Code Duplication
			if ( $isNewbie || $userLimit === false
1868
				|| $limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1869
				$keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1870
			}
1871
		}
1872
1873
		// subnet-based limits for all ping-limitable users
1874
		if ( isset( $limits['subnet-all'] ) ) {
1875
			$ip = $this->getRequest()->getIP();
1876
			$subnet = IP::getSubnet( $ip );
1877 View Code Duplication
			if ( $subnet !== false ) {
1878
				// ignore if user limit is more permissive
1879
				if ( $isNewbie || $userLimit === false
1880
					|| $limits['ip-all'][0] / $limits['ip-all'][1]
1881
					> $userLimit[0] / $userLimit[1] ) {
1882
					$keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1883
				}
1884
			}
1885
		}
1886
1887
		$cache = ObjectCache::getLocalClusterInstance();
1888
1889
		$triggered = false;
1890
		foreach ( $keys as $key => $limit ) {
1891
			list( $max, $period ) = $limit;
1892
			$summary = "(limit $max in {$period}s)";
1893
			$count = $cache->get( $key );
1894
			// Already pinged?
1895
			if ( $count ) {
1896
				if ( $count >= $max ) {
1897
					wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1898
						"(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1899
					$triggered = true;
1900
				} else {
1901
					wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1902
				}
1903
			} else {
1904
				wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1905
				if ( $incrBy > 0 ) {
1906
					$cache->add( $key, 0, intval( $period ) ); // first ping
1907
				}
1908
			}
1909
			if ( $incrBy > 0 ) {
1910
				$cache->incr( $key, $incrBy );
1911
			}
1912
		}
1913
1914
		return $triggered;
1915
	}
1916
1917
	/**
1918
	 * Check if user is blocked
1919
	 *
1920
	 * @param bool $bFromSlave Whether to check the slave database instead of
1921
	 *   the master. Hacked from false due to horrible probs on site.
1922
	 * @return bool True if blocked, false otherwise
1923
	 */
1924
	public function isBlocked( $bFromSlave = true ) {
1925
		return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1926
	}
1927
1928
	/**
1929
	 * Get the block affecting the user, or null if the user is not blocked
1930
	 *
1931
	 * @param bool $bFromSlave Whether to check the slave database instead of the master
1932
	 * @return Block|null
1933
	 */
1934
	public function getBlock( $bFromSlave = true ) {
1935
		$this->getBlockedStatus( $bFromSlave );
1936
		return $this->mBlock instanceof Block ? $this->mBlock : null;
1937
	}
1938
1939
	/**
1940
	 * Check if user is blocked from editing a particular article
1941
	 *
1942
	 * @param Title $title Title to check
1943
	 * @param bool $bFromSlave Whether to check the slave database instead of the master
1944
	 * @return bool
1945
	 */
1946
	public function isBlockedFrom( $title, $bFromSlave = false ) {
1947
		global $wgBlockAllowsUTEdit;
1948
1949
		$blocked = $this->isBlocked( $bFromSlave );
1950
		$allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1951
		// If a user's name is suppressed, they cannot make edits anywhere
1952
		if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1953
			&& $title->getNamespace() == NS_USER_TALK ) {
1954
			$blocked = false;
1955
			wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1956
		}
1957
1958
		Hooks::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1959
1960
		return $blocked;
1961
	}
1962
1963
	/**
1964
	 * If user is blocked, return the name of the user who placed the block
1965
	 * @return string Name of blocker
1966
	 */
1967
	public function blockedBy() {
1968
		$this->getBlockedStatus();
1969
		return $this->mBlockedby;
1970
	}
1971
1972
	/**
1973
	 * If user is blocked, return the specified reason for the block
1974
	 * @return string Blocking reason
1975
	 */
1976
	public function blockedFor() {
1977
		$this->getBlockedStatus();
1978
		return $this->mBlockreason;
1979
	}
1980
1981
	/**
1982
	 * If user is blocked, return the ID for the block
1983
	 * @return int Block ID
1984
	 */
1985
	public function getBlockId() {
1986
		$this->getBlockedStatus();
1987
		return ( $this->mBlock ? $this->mBlock->getId() : false );
1988
	}
1989
1990
	/**
1991
	 * Check if user is blocked on all wikis.
1992
	 * Do not use for actual edit permission checks!
1993
	 * This is intended for quick UI checks.
1994
	 *
1995
	 * @param string $ip IP address, uses current client if none given
1996
	 * @return bool True if blocked, false otherwise
1997
	 */
1998
	public function isBlockedGlobally( $ip = '' ) {
1999
		return $this->getGlobalBlock( $ip ) instanceof Block;
2000
	}
2001
2002
	/**
2003
	 * Check if user is blocked on all wikis.
2004
	 * Do not use for actual edit permission checks!
2005
	 * This is intended for quick UI checks.
2006
	 *
2007
	 * @param string $ip IP address, uses current client if none given
2008
	 * @return Block|null Block object if blocked, null otherwise
2009
	 * @throws FatalError
2010
	 * @throws MWException
2011
	 */
2012
	public function getGlobalBlock( $ip = '' ) {
2013
		if ( $this->mGlobalBlock !== null ) {
2014
			return $this->mGlobalBlock ?: null;
2015
		}
2016
		// User is already an IP?
2017
		if ( IP::isIPAddress( $this->getName() ) ) {
2018
			$ip = $this->getName();
2019
		} elseif ( !$ip ) {
2020
			$ip = $this->getRequest()->getIP();
2021
		}
2022
		$blocked = false;
2023
		$block = null;
2024
		Hooks::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked, &$block ] );
2025
2026
		if ( $blocked && $block === null ) {
2027
			// back-compat: UserIsBlockedGlobally didn't have $block param first
2028
			$block = new Block;
2029
			$block->setTarget( $ip );
2030
		}
2031
2032
		$this->mGlobalBlock = $blocked ? $block : false;
0 ignored issues
show
Documentation Bug introduced by
It seems like $blocked ? $block : false can also be of type false. However, the property $mGlobalBlock is declared as type object<Block>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
2033
		return $this->mGlobalBlock ?: null;
2034
	}
2035
2036
	/**
2037
	 * Check if user account is locked
2038
	 *
2039
	 * @return bool True if locked, false otherwise
2040
	 */
2041 View Code Duplication
	public function isLocked() {
2042
		if ( $this->mLocked !== null ) {
2043
			return $this->mLocked;
2044
		}
2045
		$authUser = AuthManager::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
0 ignored issues
show
Deprecated Code introduced by
The method MediaWiki\Auth\AuthManager::callLegacyAuthPlugin() has been deprecated with message: For backwards compatibility only, should be avoided in new code

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
2046
		$this->mLocked = $authUser && $authUser->isLocked();
2047
		Hooks::run( 'UserIsLocked', [ $this, &$this->mLocked ] );
2048
		return $this->mLocked;
2049
	}
2050
2051
	/**
2052
	 * Check if user account is hidden
2053
	 *
2054
	 * @return bool True if hidden, false otherwise
2055
	 */
2056 View Code Duplication
	public function isHidden() {
2057
		if ( $this->mHideName !== null ) {
2058
			return $this->mHideName;
2059
		}
2060
		$this->getBlockedStatus();
2061
		if ( !$this->mHideName ) {
2062
			$authUser = AuthManager::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
0 ignored issues
show
Deprecated Code introduced by
The method MediaWiki\Auth\AuthManager::callLegacyAuthPlugin() has been deprecated with message: For backwards compatibility only, should be avoided in new code

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
2063
			$this->mHideName = $authUser && $authUser->isHidden();
2064
			Hooks::run( 'UserIsHidden', [ $this, &$this->mHideName ] );
2065
		}
2066
		return $this->mHideName;
2067
	}
2068
2069
	/**
2070
	 * Get the user's ID.
2071
	 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2072
	 */
2073
	public function getId() {
2074
		if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
2075
			// Special case, we know the user is anonymous
2076
			return 0;
2077
		} elseif ( !$this->isItemLoaded( 'id' ) ) {
2078
			// Don't load if this was initialized from an ID
2079
			$this->load();
2080
		}
2081
2082
		return (int)$this->mId;
2083
	}
2084
2085
	/**
2086
	 * Set the user and reload all fields according to a given ID
2087
	 * @param int $v User ID to reload
2088
	 */
2089
	public function setId( $v ) {
2090
		$this->mId = $v;
2091
		$this->clearInstanceCache( 'id' );
2092
	}
2093
2094
	/**
2095
	 * Get the user name, or the IP of an anonymous user
2096
	 * @return string User's name or IP address
2097
	 */
2098
	public function getName() {
2099
		if ( $this->isItemLoaded( 'name', 'only' ) ) {
2100
			// Special case optimisation
2101
			return $this->mName;
2102
		} else {
2103
			$this->load();
2104
			if ( $this->mName === false ) {
2105
				// Clean up IPs
2106
				$this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
2107
			}
2108
			return $this->mName;
2109
		}
2110
	}
2111
2112
	/**
2113
	 * Set the user name.
2114
	 *
2115
	 * This does not reload fields from the database according to the given
2116
	 * name. Rather, it is used to create a temporary "nonexistent user" for
2117
	 * later addition to the database. It can also be used to set the IP
2118
	 * address for an anonymous user to something other than the current
2119
	 * remote IP.
2120
	 *
2121
	 * @note User::newFromName() has roughly the same function, when the named user
2122
	 * does not exist.
2123
	 * @param string $str New user name to set
2124
	 */
2125
	public function setName( $str ) {
2126
		$this->load();
2127
		$this->mName = $str;
2128
	}
2129
2130
	/**
2131
	 * Get the user's name escaped by underscores.
2132
	 * @return string Username escaped by underscores.
2133
	 */
2134
	public function getTitleKey() {
2135
		return str_replace( ' ', '_', $this->getName() );
2136
	}
2137
2138
	/**
2139
	 * Check if the user has new messages.
2140
	 * @return bool True if the user has new messages
2141
	 */
2142
	public function getNewtalk() {
2143
		$this->load();
2144
2145
		// Load the newtalk status if it is unloaded (mNewtalk=-1)
2146
		if ( $this->mNewtalk === -1 ) {
2147
			$this->mNewtalk = false; # reset talk page status
2148
2149
			// Check memcached separately for anons, who have no
2150
			// entire User object stored in there.
2151
			if ( !$this->mId ) {
2152
				global $wgDisableAnonTalk;
2153
				if ( $wgDisableAnonTalk ) {
2154
					// Anon newtalk disabled by configuration.
2155
					$this->mNewtalk = false;
2156
				} else {
2157
					$this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
2158
				}
2159
			} else {
2160
				$this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2161
			}
2162
		}
2163
2164
		return (bool)$this->mNewtalk;
2165
	}
2166
2167
	/**
2168
	 * Return the data needed to construct links for new talk page message
2169
	 * alerts. If there are new messages, this will return an associative array
2170
	 * with the following data:
2171
	 *     wiki: The database name of the wiki
2172
	 *     link: Root-relative link to the user's talk page
2173
	 *     rev: The last talk page revision that the user has seen or null. This
2174
	 *         is useful for building diff links.
2175
	 * If there are no new messages, it returns an empty array.
2176
	 * @note This function was designed to accomodate multiple talk pages, but
2177
	 * currently only returns a single link and revision.
2178
	 * @return array
2179
	 */
2180
	public function getNewMessageLinks() {
2181
		$talks = [];
2182
		if ( !Hooks::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2183
			return $talks;
2184
		} elseif ( !$this->getNewtalk() ) {
2185
			return [];
2186
		}
2187
		$utp = $this->getTalkPage();
2188
		$dbr = wfGetDB( DB_SLAVE );
2189
		// Get the "last viewed rev" timestamp from the oldest message notification
2190
		$timestamp = $dbr->selectField( 'user_newtalk',
2191
			'MIN(user_last_timestamp)',
2192
			$this->isAnon() ? [ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2193
			__METHOD__ );
2194
		$rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2195
		return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2196
	}
2197
2198
	/**
2199
	 * Get the revision ID for the last talk page revision viewed by the talk
2200
	 * page owner.
2201
	 * @return int|null Revision ID or null
2202
	 */
2203
	public function getNewMessageRevisionId() {
2204
		$newMessageRevisionId = null;
2205
		$newMessageLinks = $this->getNewMessageLinks();
2206
		if ( $newMessageLinks ) {
2207
			// Note: getNewMessageLinks() never returns more than a single link
2208
			// and it is always for the same wiki, but we double-check here in
2209
			// case that changes some time in the future.
2210
			if ( count( $newMessageLinks ) === 1
2211
				&& $newMessageLinks[0]['wiki'] === wfWikiID()
2212
				&& $newMessageLinks[0]['rev']
2213
			) {
2214
				/** @var Revision $newMessageRevision */
2215
				$newMessageRevision = $newMessageLinks[0]['rev'];
2216
				$newMessageRevisionId = $newMessageRevision->getId();
2217
			}
2218
		}
2219
		return $newMessageRevisionId;
2220
	}
2221
2222
	/**
2223
	 * Internal uncached check for new messages
2224
	 *
2225
	 * @see getNewtalk()
2226
	 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2227
	 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2228
	 * @return bool True if the user has new messages
2229
	 */
2230
	protected function checkNewtalk( $field, $id ) {
2231
		$dbr = wfGetDB( DB_SLAVE );
2232
2233
		$ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__ );
2234
2235
		return $ok !== false;
2236
	}
2237
2238
	/**
2239
	 * Add or update the new messages flag
2240
	 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2241
	 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2242
	 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2243
	 * @return bool True if successful, false otherwise
2244
	 */
2245
	protected function updateNewtalk( $field, $id, $curRev = null ) {
2246
		// Get timestamp of the talk page revision prior to the current one
2247
		$prevRev = $curRev ? $curRev->getPrevious() : false;
2248
		$ts = $prevRev ? $prevRev->getTimestamp() : null;
2249
		// Mark the user as having new messages since this revision
2250
		$dbw = wfGetDB( DB_MASTER );
2251
		$dbw->insert( 'user_newtalk',
2252
			[ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2253
			__METHOD__,
2254
			'IGNORE' );
2255 View Code Duplication
		if ( $dbw->affectedRows() ) {
2256
			wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2257
			return true;
2258
		} else {
2259
			wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2260
			return false;
2261
		}
2262
	}
2263
2264
	/**
2265
	 * Clear the new messages flag for the given user
2266
	 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2267
	 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2268
	 * @return bool True if successful, false otherwise
2269
	 */
2270
	protected function deleteNewtalk( $field, $id ) {
2271
		$dbw = wfGetDB( DB_MASTER );
2272
		$dbw->delete( 'user_newtalk',
2273
			[ $field => $id ],
2274
			__METHOD__ );
2275 View Code Duplication
		if ( $dbw->affectedRows() ) {
2276
			wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2277
			return true;
2278
		} else {
2279
			wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2280
			return false;
2281
		}
2282
	}
2283
2284
	/**
2285
	 * Update the 'You have new messages!' status.
2286
	 * @param bool $val Whether the user has new messages
2287
	 * @param Revision $curRev New, as yet unseen revision of the user talk
2288
	 *   page. Ignored if null or !$val.
2289
	 */
2290
	public function setNewtalk( $val, $curRev = null ) {
2291
		if ( wfReadOnly() ) {
2292
			return;
2293
		}
2294
2295
		$this->load();
2296
		$this->mNewtalk = $val;
2297
2298
		if ( $this->isAnon() ) {
2299
			$field = 'user_ip';
2300
			$id = $this->getName();
2301
		} else {
2302
			$field = 'user_id';
2303
			$id = $this->getId();
2304
		}
2305
2306
		if ( $val ) {
2307
			$changed = $this->updateNewtalk( $field, $id, $curRev );
2308
		} else {
2309
			$changed = $this->deleteNewtalk( $field, $id );
2310
		}
2311
2312
		if ( $changed ) {
2313
			$this->invalidateCache();
2314
		}
2315
	}
2316
2317
	/**
2318
	 * Generate a current or new-future timestamp to be stored in the
2319
	 * user_touched field when we update things.
2320
	 * @return string Timestamp in TS_MW format
2321
	 */
2322
	private function newTouchedTimestamp() {
2323
		global $wgClockSkewFudge;
2324
2325
		$time = wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2326
		if ( $this->mTouched && $time <= $this->mTouched ) {
2327
			$time = wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2328
		}
2329
2330
		return $time;
2331
	}
2332
2333
	/**
2334
	 * Clear user data from memcached
2335
	 *
2336
	 * Use after applying updates to the database; caller's
2337
	 * responsibility to update user_touched if appropriate.
2338
	 *
2339
	 * Called implicitly from invalidateCache() and saveSettings().
2340
	 *
2341
	 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2342
	 */
2343
	public function clearSharedCache( $mode = 'changed' ) {
2344
		if ( !$this->getId() ) {
2345
			return;
2346
		}
2347
2348
		$cache = ObjectCache::getMainWANInstance();
2349
		$key = $this->getCacheKey( $cache );
2350
		if ( $mode === 'refresh' ) {
2351
			$cache->delete( $key, 1 );
2352
		} else {
2353
			wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle(
2354
				function() use ( $cache, $key ) {
2355
					$cache->delete( $key );
2356
				}
2357
			);
2358
		}
2359
	}
2360
2361
	/**
2362
	 * Immediately touch the user data cache for this account
2363
	 *
2364
	 * Calls touch() and removes account data from memcached
2365
	 */
2366
	public function invalidateCache() {
2367
		$this->touch();
2368
		$this->clearSharedCache();
2369
	}
2370
2371
	/**
2372
	 * Update the "touched" timestamp for the user
2373
	 *
2374
	 * This is useful on various login/logout events when making sure that
2375
	 * a browser or proxy that has multiple tenants does not suffer cache
2376
	 * pollution where the new user sees the old users content. The value
2377
	 * of getTouched() is checked when determining 304 vs 200 responses.
2378
	 * Unlike invalidateCache(), this preserves the User object cache and
2379
	 * avoids database writes.
2380
	 *
2381
	 * @since 1.25
2382
	 */
2383
	public function touch() {
2384
		$id = $this->getId();
2385
		if ( $id ) {
2386
			$key = wfMemcKey( 'user-quicktouched', 'id', $id );
2387
			ObjectCache::getMainWANInstance()->touchCheckKey( $key );
2388
			$this->mQuickTouched = null;
2389
		}
2390
	}
2391
2392
	/**
2393
	 * Validate the cache for this account.
2394
	 * @param string $timestamp A timestamp in TS_MW format
2395
	 * @return bool
2396
	 */
2397
	public function validateCache( $timestamp ) {
2398
		return ( $timestamp >= $this->getTouched() );
2399
	}
2400
2401
	/**
2402
	 * Get the user touched timestamp
2403
	 *
2404
	 * Use this value only to validate caches via inequalities
2405
	 * such as in the case of HTTP If-Modified-Since response logic
2406
	 *
2407
	 * @return string TS_MW Timestamp
2408
	 */
2409
	public function getTouched() {
2410
		$this->load();
2411
2412
		if ( $this->mId ) {
2413
			if ( $this->mQuickTouched === null ) {
2414
				$key = wfMemcKey( 'user-quicktouched', 'id', $this->mId );
2415
				$cache = ObjectCache::getMainWANInstance();
2416
2417
				$this->mQuickTouched = wfTimestamp( TS_MW, $cache->getCheckKeyTime( $key ) );
0 ignored issues
show
Documentation Bug introduced by
It seems like wfTimestamp(TS_MW, $cache->getCheckKeyTime($key)) can also be of type false. However, the property $mQuickTouched is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
2418
			}
2419
2420
			return max( $this->mTouched, $this->mQuickTouched );
2421
		}
2422
2423
		return $this->mTouched;
2424
	}
2425
2426
	/**
2427
	 * Get the user_touched timestamp field (time of last DB updates)
2428
	 * @return string TS_MW Timestamp
2429
	 * @since 1.26
2430
	 */
2431
	public function getDBTouched() {
2432
		$this->load();
2433
2434
		return $this->mTouched;
2435
	}
2436
2437
	/**
2438
	 * @deprecated Removed in 1.27.
2439
	 * @return Password
2440
	 * @since 1.24
2441
	 */
2442
	public function getPassword() {
2443
		throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2444
	}
2445
2446
	/**
2447
	 * @deprecated Removed in 1.27.
2448
	 * @return Password
2449
	 * @since 1.24
2450
	 */
2451
	public function getTemporaryPassword() {
2452
		throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2453
	}
2454
2455
	/**
2456
	 * Set the password and reset the random token.
2457
	 * Calls through to authentication plugin if necessary;
2458
	 * will have no effect if the auth plugin refuses to
2459
	 * pass the change through or if the legal password
2460
	 * checks fail.
2461
	 *
2462
	 * As a special case, setting the password to null
2463
	 * wipes it, so the account cannot be logged in until
2464
	 * a new password is set, for instance via e-mail.
2465
	 *
2466
	 * @deprecated since 1.27, use AuthManager instead
2467
	 * @param string $str New password to set
2468
	 * @throws PasswordError On failure
2469
	 * @return bool
2470
	 */
2471
	public function setPassword( $str ) {
2472
		global $wgAuth, $wgDisableAuthManager;
2473
2474
		if ( !$wgDisableAuthManager ) {
2475
			return $this->setPasswordInternal( $str );
2476
		}
2477
2478
		if ( $str !== null ) {
2479
			if ( !$wgAuth->allowPasswordChange() ) {
2480
				throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2481
			}
2482
2483
			$status = $this->checkPasswordValidity( $str );
2484
			if ( !$status->isGood() ) {
2485
				throw new PasswordError( $status->getMessage()->text() );
2486
			}
2487
		}
2488
2489
		if ( !$wgAuth->setPassword( $this, $str ) ) {
2490
			throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2491
		}
2492
2493
		$this->setOption( 'watchlisttoken', false );
2494
		$this->setPasswordInternal( $str );
2495
2496
		return true;
2497
	}
2498
2499
	/**
2500
	 * Set the password and reset the random token unconditionally.
2501
	 *
2502
	 * @deprecated since 1.27, use AuthManager instead
2503
	 * @param string|null $str New password to set or null to set an invalid
2504
	 *  password hash meaning that the user will not be able to log in
2505
	 *  through the web interface.
2506
	 */
2507
	public function setInternalPassword( $str ) {
2508
		global $wgAuth, $wgDisableAuthManager;
2509
2510
		if ( !$wgDisableAuthManager ) {
2511
			$this->setPasswordInternal( $str );
2512
		}
2513
2514
		if ( $wgAuth->allowSetLocalPassword() ) {
2515
			$this->setOption( 'watchlisttoken', false );
2516
			$this->setPasswordInternal( $str );
2517
		}
2518
	}
2519
2520
	/**
2521
	 * Actually set the password and such
2522
	 * @since 1.27 cannot set a password for a user not in the database
2523
	 * @param string|null $str New password to set or null to set an invalid
2524
	 *  password hash meaning that the user will not be able to log in
2525
	 *  through the web interface.
2526
	 * @return bool Success
2527
	 */
2528
	private function setPasswordInternal( $str ) {
2529
		global $wgDisableAuthManager;
2530
2531
		if ( $wgDisableAuthManager ) {
2532
			$id = self::idFromName( $this->getName(), self::READ_LATEST );
2533
			if ( $id == 0 ) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $id of type integer|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
2534
				throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2535
			}
2536
2537
			$passwordFactory = new PasswordFactory();
2538
			$passwordFactory->init( RequestContext::getMain()->getConfig() );
2539
			$dbw = wfGetDB( DB_MASTER );
2540
			$dbw->update(
2541
				'user',
2542
				[
2543
					'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2544
					'user_newpassword' => PasswordFactory::newInvalidPassword()->toString(),
2545
					'user_newpass_time' => $dbw->timestampOrNull( null ),
2546
				],
2547
				[
2548
					'user_id' => $id,
2549
				],
2550
				__METHOD__
2551
			);
2552
2553
			// When the main password is changed, invalidate all bot passwords too
2554
			BotPassword::invalidateAllPasswordsForUser( $this->getName() );
2555
		} else {
2556
			$manager = AuthManager::singleton();
2557
2558
			// If the user doesn't exist yet, fail
2559
			if ( !$manager->userExists( $this->getName() ) ) {
2560
				throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2561
			}
2562
2563
			$status = $this->changeAuthenticationData( [
2564
				'username' => $this->getName(),
2565
				'password' => $str,
2566
				'retype' => $str,
2567
			] );
2568
			if ( !$status->isGood() ) {
2569
				\MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
2570
					->info( __METHOD__ . ': Password change rejected: '
2571
						. $status->getWikiText( null, null, 'en' ) );
2572
				return false;
2573
			}
2574
2575
			$this->setOption( 'watchlisttoken', false );
2576
		}
2577
2578
		SessionManager::singleton()->invalidateSessionsForUser( $this );
2579
2580
		return true;
2581
	}
2582
2583
	/**
2584
	 * Changes credentials of the user.
2585
	 *
2586
	 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2587
	 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2588
	 * e.g. when no provider handled the change.
2589
	 *
2590
	 * @param array $data A set of authentication data in fieldname => value format. This is the
2591
	 *   same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2592
	 * @return Status
2593
	 * @since 1.27
2594
	 */
2595
	public function changeAuthenticationData( array $data ) {
2596
		global $wgDisableAuthManager;
2597
		if ( $wgDisableAuthManager ) {
2598
			throw new LogicException( __METHOD__ . ' cannot be called when $wgDisableAuthManager '
2599
				. 'is true' );
2600
		}
2601
2602
		$manager = AuthManager::singleton();
2603
		$reqs = $manager->getAuthenticationRequests( AuthManager::ACTION_CHANGE, $this );
2604
		$reqs = AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
2605
2606
		$status = Status::newGood( 'ignored' );
2607
		foreach ( $reqs as $req ) {
2608
			$status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2609
		}
2610
		if ( $status->getValue() === 'ignored' ) {
2611
			$status->warning( 'authenticationdatachange-ignored' );
2612
		}
2613
2614
		if ( $status->isGood() ) {
2615
			foreach ( $reqs as $req ) {
2616
				$manager->changeAuthenticationData( $req );
2617
			}
2618
		}
2619
		return $status;
2620
	}
2621
2622
	/**
2623
	 * Get the user's current token.
2624
	 * @param bool $forceCreation Force the generation of a new token if the
2625
	 *   user doesn't have one (default=true for backwards compatibility).
2626
	 * @return string|null Token
2627
	 */
2628
	public function getToken( $forceCreation = true ) {
2629
		global $wgAuthenticationTokenVersion;
2630
2631
		$this->load();
2632
		if ( !$this->mToken && $forceCreation ) {
2633
			$this->setToken();
2634
		}
2635
2636
		if ( !$this->mToken ) {
2637
			// The user doesn't have a token, return null to indicate that.
2638
			return null;
2639
		} elseif ( $this->mToken === self::INVALID_TOKEN ) {
2640
			// We return a random value here so existing token checks are very
2641
			// likely to fail.
2642
			return MWCryptRand::generateHex( self::TOKEN_LENGTH );
2643
		} elseif ( $wgAuthenticationTokenVersion === null ) {
2644
			// $wgAuthenticationTokenVersion not in use, so return the raw secret
2645
			return $this->mToken;
2646
		} else {
2647
			// $wgAuthenticationTokenVersion in use, so hmac it.
2648
			$ret = MWCryptHash::hmac( $wgAuthenticationTokenVersion, $this->mToken, false );
2649
2650
			// The raw hash can be overly long. Shorten it up.
2651
			$len = max( 32, self::TOKEN_LENGTH );
2652
			if ( strlen( $ret ) < $len ) {
2653
				// Should never happen, even md5 is 128 bits
2654
				throw new \UnexpectedValueException( 'Hmac returned less than 128 bits' );
2655
			}
2656
			return substr( $ret, -$len );
2657
		}
2658
	}
2659
2660
	/**
2661
	 * Set the random token (used for persistent authentication)
2662
	 * Called from loadDefaults() among other places.
2663
	 *
2664
	 * @param string|bool $token If specified, set the token to this value
2665
	 */
2666
	public function setToken( $token = false ) {
2667
		$this->load();
2668
		if ( $this->mToken === self::INVALID_TOKEN ) {
2669
			\MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
2670
				->debug( __METHOD__ . ": Ignoring attempt to set token for system user \"$this\"" );
2671
		} elseif ( !$token ) {
2672
			$this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2673
		} else {
2674
			$this->mToken = $token;
0 ignored issues
show
Documentation Bug introduced by
It seems like $token can also be of type boolean. However, the property $mToken is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
2675
		}
2676
	}
2677
2678
	/**
2679
	 * Set the password for a password reminder or new account email
2680
	 *
2681
	 * @deprecated Removed in 1.27. Use PasswordReset instead.
2682
	 * @param string $str New password to set or null to set an invalid
2683
	 *  password hash meaning that the user will not be able to use it
2684
	 * @param bool $throttle If true, reset the throttle timestamp to the present
2685
	 */
2686
	public function setNewpassword( $str, $throttle = true ) {
2687
		global $wgDisableAuthManager;
2688
2689
		if ( $wgDisableAuthManager ) {
2690
			$id = $this->getId();
2691
			if ( $id == 0 ) {
2692
				throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2693
			}
2694
2695
			$dbw = wfGetDB( DB_MASTER );
2696
2697
			$passwordFactory = new PasswordFactory();
2698
			$passwordFactory->init( RequestContext::getMain()->getConfig() );
2699
			$update = [
2700
				'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2701
			];
2702
2703
			if ( $str === null ) {
2704
				$update['user_newpass_time'] = null;
2705
			} elseif ( $throttle ) {
2706
				$update['user_newpass_time'] = $dbw->timestamp();
2707
			}
2708
2709
			$dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__ );
2710
		} else {
2711
			throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2712
		}
2713
	}
2714
2715
	/**
2716
	 * Has password reminder email been sent within the last
2717
	 * $wgPasswordReminderResendTime hours?
2718
	 * @deprecated Removed in 1.27. See above.
2719
	 * @return bool
2720
	 */
2721
	public function isPasswordReminderThrottled() {
2722
		global $wgPasswordReminderResendTime, $wgDisableAuthManager;
2723
2724
		if ( $wgDisableAuthManager ) {
2725
			if ( !$wgPasswordReminderResendTime ) {
2726
				return false;
2727
			}
2728
2729
			$this->load();
2730
2731
			$db = ( $this->queryFlagsUsed & self::READ_LATEST )
2732
				? wfGetDB( DB_MASTER )
2733
				: wfGetDB( DB_SLAVE );
2734
			$newpassTime = $db->selectField(
2735
				'user',
2736
				'user_newpass_time',
2737
				[ 'user_id' => $this->getId() ],
2738
				__METHOD__
2739
			);
2740
2741
			if ( $newpassTime === null ) {
2742
				return false;
2743
			}
2744
			$expiry = wfTimestamp( TS_UNIX, $newpassTime ) + $wgPasswordReminderResendTime * 3600;
2745
			return time() < $expiry;
2746
		} else {
2747
			throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2748
		}
2749
	}
2750
2751
	/**
2752
	 * Get the user's e-mail address
2753
	 * @return string User's email address
2754
	 */
2755
	public function getEmail() {
2756
		$this->load();
2757
		Hooks::run( 'UserGetEmail', [ $this, &$this->mEmail ] );
2758
		return $this->mEmail;
2759
	}
2760
2761
	/**
2762
	 * Get the timestamp of the user's e-mail authentication
2763
	 * @return string TS_MW timestamp
2764
	 */
2765
	public function getEmailAuthenticationTimestamp() {
2766
		$this->load();
2767
		Hooks::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
2768
		return $this->mEmailAuthenticated;
2769
	}
2770
2771
	/**
2772
	 * Set the user's e-mail address
2773
	 * @param string $str New e-mail address
2774
	 */
2775
	public function setEmail( $str ) {
2776
		$this->load();
2777
		if ( $str == $this->mEmail ) {
2778
			return;
2779
		}
2780
		$this->invalidateEmail();
2781
		$this->mEmail = $str;
2782
		Hooks::run( 'UserSetEmail', [ $this, &$this->mEmail ] );
2783
	}
2784
2785
	/**
2786
	 * Set the user's e-mail address and a confirmation mail if needed.
2787
	 *
2788
	 * @since 1.20
2789
	 * @param string $str New e-mail address
2790
	 * @return Status
2791
	 */
2792
	public function setEmailWithConfirmation( $str ) {
2793
		global $wgEnableEmail, $wgEmailAuthentication;
2794
2795
		if ( !$wgEnableEmail ) {
2796
			return Status::newFatal( 'emaildisabled' );
2797
		}
2798
2799
		$oldaddr = $this->getEmail();
2800
		if ( $str === $oldaddr ) {
2801
			return Status::newGood( true );
2802
		}
2803
2804
		$type = $oldaddr != '' ? 'changed' : 'set';
2805
		$notificationResult = null;
2806
2807
		if ( $wgEmailAuthentication ) {
2808
			// Send the user an email notifying the user of the change in registered
2809
			// email address on their previous email address
2810
			if ( $type == 'changed' ) {
2811
				$change = $str != '' ? 'changed' : 'removed';
2812
				$notificationResult = $this->sendMail(
2813
					wfMessage( 'notificationemail_subject_' . $change )->text(),
2814
					wfMessage( 'notificationemail_body_' . $change,
2815
						$this->getRequest()->getIP(),
2816
						$this->getName(),
2817
						$str )->text()
2818
				);
2819
			}
2820
		}
2821
2822
		$this->setEmail( $str );
2823
2824
		if ( $str !== '' && $wgEmailAuthentication ) {
2825
			// Send a confirmation request to the new address if needed
2826
			$result = $this->sendConfirmationMail( $type );
2827
2828
			if ( $notificationResult !== null ) {
2829
				$result->merge( $notificationResult );
2830
			}
2831
2832
			if ( $result->isGood() ) {
2833
				// Say to the caller that a confirmation and notification mail has been sent
2834
				$result->value = 'eauth';
2835
			}
2836
		} else {
2837
			$result = Status::newGood( true );
2838
		}
2839
2840
		return $result;
2841
	}
2842
2843
	/**
2844
	 * Get the user's real name
2845
	 * @return string User's real name
2846
	 */
2847
	public function getRealName() {
2848
		if ( !$this->isItemLoaded( 'realname' ) ) {
2849
			$this->load();
2850
		}
2851
2852
		return $this->mRealName;
2853
	}
2854
2855
	/**
2856
	 * Set the user's real name
2857
	 * @param string $str New real name
2858
	 */
2859
	public function setRealName( $str ) {
2860
		$this->load();
2861
		$this->mRealName = $str;
2862
	}
2863
2864
	/**
2865
	 * Get the user's current setting for a given option.
2866
	 *
2867
	 * @param string $oname The option to check
2868
	 * @param string $defaultOverride A default value returned if the option does not exist
2869
	 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2870
	 * @return string User's current value for the option
2871
	 * @see getBoolOption()
2872
	 * @see getIntOption()
2873
	 */
2874
	public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2875
		global $wgHiddenPrefs;
2876
		$this->loadOptions();
2877
2878
		# We want 'disabled' preferences to always behave as the default value for
2879
		# users, even if they have set the option explicitly in their settings (ie they
2880
		# set it, and then it was disabled removing their ability to change it).  But
2881
		# we don't want to erase the preferences in the database in case the preference
2882
		# is re-enabled again.  So don't touch $mOptions, just override the returned value
2883
		if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2884
			return self::getDefaultOption( $oname );
2885
		}
2886
2887
		if ( array_key_exists( $oname, $this->mOptions ) ) {
2888
			return $this->mOptions[$oname];
2889
		} else {
2890
			return $defaultOverride;
2891
		}
2892
	}
2893
2894
	/**
2895
	 * Get all user's options
2896
	 *
2897
	 * @param int $flags Bitwise combination of:
2898
	 *   User::GETOPTIONS_EXCLUDE_DEFAULTS  Exclude user options that are set
2899
	 *                                      to the default value. (Since 1.25)
2900
	 * @return array
2901
	 */
2902
	public function getOptions( $flags = 0 ) {
2903
		global $wgHiddenPrefs;
2904
		$this->loadOptions();
2905
		$options = $this->mOptions;
2906
2907
		# We want 'disabled' preferences to always behave as the default value for
2908
		# users, even if they have set the option explicitly in their settings (ie they
2909
		# set it, and then it was disabled removing their ability to change it).  But
2910
		# we don't want to erase the preferences in the database in case the preference
2911
		# is re-enabled again.  So don't touch $mOptions, just override the returned value
2912
		foreach ( $wgHiddenPrefs as $pref ) {
2913
			$default = self::getDefaultOption( $pref );
2914
			if ( $default !== null ) {
2915
				$options[$pref] = $default;
2916
			}
2917
		}
2918
2919
		if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
2920
			$options = array_diff_assoc( $options, self::getDefaultOptions() );
2921
		}
2922
2923
		return $options;
2924
	}
2925
2926
	/**
2927
	 * Get the user's current setting for a given option, as a boolean value.
2928
	 *
2929
	 * @param string $oname The option to check
2930
	 * @return bool User's current value for the option
2931
	 * @see getOption()
2932
	 */
2933
	public function getBoolOption( $oname ) {
2934
		return (bool)$this->getOption( $oname );
2935
	}
2936
2937
	/**
2938
	 * Get the user's current setting for a given option, as an integer value.
2939
	 *
2940
	 * @param string $oname The option to check
2941
	 * @param int $defaultOverride A default value returned if the option does not exist
2942
	 * @return int User's current value for the option
2943
	 * @see getOption()
2944
	 */
2945
	public function getIntOption( $oname, $defaultOverride = 0 ) {
2946
		$val = $this->getOption( $oname );
2947
		if ( $val == '' ) {
2948
			$val = $defaultOverride;
2949
		}
2950
		return intval( $val );
2951
	}
2952
2953
	/**
2954
	 * Set the given option for a user.
2955
	 *
2956
	 * You need to call saveSettings() to actually write to the database.
2957
	 *
2958
	 * @param string $oname The option to set
2959
	 * @param mixed $val New value to set
2960
	 */
2961
	public function setOption( $oname, $val ) {
2962
		$this->loadOptions();
2963
2964
		// Explicitly NULL values should refer to defaults
2965
		if ( is_null( $val ) ) {
2966
			$val = self::getDefaultOption( $oname );
2967
		}
2968
2969
		$this->mOptions[$oname] = $val;
2970
	}
2971
2972
	/**
2973
	 * Get a token stored in the preferences (like the watchlist one),
2974
	 * resetting it if it's empty (and saving changes).
2975
	 *
2976
	 * @param string $oname The option name to retrieve the token from
2977
	 * @return string|bool User's current value for the option, or false if this option is disabled.
2978
	 * @see resetTokenFromOption()
2979
	 * @see getOption()
2980
	 * @deprecated 1.26 Applications should use the OAuth extension
2981
	 */
2982
	public function getTokenFromOption( $oname ) {
2983
		global $wgHiddenPrefs;
2984
2985
		$id = $this->getId();
2986
		if ( !$id || in_array( $oname, $wgHiddenPrefs ) ) {
2987
			return false;
2988
		}
2989
2990
		$token = $this->getOption( $oname );
2991
		if ( !$token ) {
2992
			// Default to a value based on the user token to avoid space
2993
			// wasted on storing tokens for all users. When this option
2994
			// is set manually by the user, only then is it stored.
2995
			$token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2996
		}
2997
2998
		return $token;
2999
	}
3000
3001
	/**
3002
	 * Reset a token stored in the preferences (like the watchlist one).
3003
	 * *Does not* save user's preferences (similarly to setOption()).
3004
	 *
3005
	 * @param string $oname The option name to reset the token in
3006
	 * @return string|bool New token value, or false if this option is disabled.
3007
	 * @see getTokenFromOption()
3008
	 * @see setOption()
3009
	 */
3010
	public function resetTokenFromOption( $oname ) {
3011
		global $wgHiddenPrefs;
3012
		if ( in_array( $oname, $wgHiddenPrefs ) ) {
3013
			return false;
3014
		}
3015
3016
		$token = MWCryptRand::generateHex( 40 );
3017
		$this->setOption( $oname, $token );
3018
		return $token;
3019
	}
3020
3021
	/**
3022
	 * Return a list of the types of user options currently returned by
3023
	 * User::getOptionKinds().
3024
	 *
3025
	 * Currently, the option kinds are:
3026
	 * - 'registered' - preferences which are registered in core MediaWiki or
3027
	 *                  by extensions using the UserGetDefaultOptions hook.
3028
	 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3029
	 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3030
	 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3031
	 *              be used by user scripts.
3032
	 * - 'special' - "preferences" that are not accessible via User::getOptions
3033
	 *               or User::setOptions.
3034
	 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3035
	 *              These are usually legacy options, removed in newer versions.
3036
	 *
3037
	 * The API (and possibly others) use this function to determine the possible
3038
	 * option types for validation purposes, so make sure to update this when a
3039
	 * new option kind is added.
3040
	 *
3041
	 * @see User::getOptionKinds
3042
	 * @return array Option kinds
3043
	 */
3044
	public static function listOptionKinds() {
3045
		return [
3046
			'registered',
3047
			'registered-multiselect',
3048
			'registered-checkmatrix',
3049
			'userjs',
3050
			'special',
3051
			'unused'
3052
		];
3053
	}
3054
3055
	/**
3056
	 * Return an associative array mapping preferences keys to the kind of a preference they're
3057
	 * used for. Different kinds are handled differently when setting or reading preferences.
3058
	 *
3059
	 * See User::listOptionKinds for the list of valid option types that can be provided.
3060
	 *
3061
	 * @see User::listOptionKinds
3062
	 * @param IContextSource $context
3063
	 * @param array $options Assoc. array with options keys to check as keys.
3064
	 *   Defaults to $this->mOptions.
3065
	 * @return array The key => kind mapping data
3066
	 */
3067
	public function getOptionKinds( IContextSource $context, $options = null ) {
3068
		$this->loadOptions();
3069
		if ( $options === null ) {
3070
			$options = $this->mOptions;
3071
		}
3072
3073
		$prefs = Preferences::getPreferences( $this, $context );
3074
		$mapping = [];
3075
3076
		// Pull out the "special" options, so they don't get converted as
3077
		// multiselect or checkmatrix.
3078
		$specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
3079
		foreach ( $specialOptions as $name => $value ) {
3080
			unset( $prefs[$name] );
3081
		}
3082
3083
		// Multiselect and checkmatrix options are stored in the database with
3084
		// one key per option, each having a boolean value. Extract those keys.
3085
		$multiselectOptions = [];
3086
		foreach ( $prefs as $name => $info ) {
3087 View Code Duplication
			if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3088
					( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3089
				$opts = HTMLFormField::flattenOptions( $info['options'] );
3090
				$prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
3091
3092
				foreach ( $opts as $value ) {
3093
					$multiselectOptions["$prefix$value"] = true;
3094
				}
3095
3096
				unset( $prefs[$name] );
3097
			}
3098
		}
3099
		$checkmatrixOptions = [];
3100
		foreach ( $prefs as $name => $info ) {
3101
			if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3102
					( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3103
				$columns = HTMLFormField::flattenOptions( $info['columns'] );
3104
				$rows = HTMLFormField::flattenOptions( $info['rows'] );
3105
				$prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
3106
3107
				foreach ( $columns as $column ) {
3108
					foreach ( $rows as $row ) {
3109
						$checkmatrixOptions["$prefix$column-$row"] = true;
3110
					}
3111
				}
3112
3113
				unset( $prefs[$name] );
3114
			}
3115
		}
3116
3117
		// $value is ignored
3118
		foreach ( $options as $key => $value ) {
3119
			if ( isset( $prefs[$key] ) ) {
3120
				$mapping[$key] = 'registered';
3121
			} elseif ( isset( $multiselectOptions[$key] ) ) {
3122
				$mapping[$key] = 'registered-multiselect';
3123
			} elseif ( isset( $checkmatrixOptions[$key] ) ) {
3124
				$mapping[$key] = 'registered-checkmatrix';
3125
			} elseif ( isset( $specialOptions[$key] ) ) {
3126
				$mapping[$key] = 'special';
3127
			} elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3128
				$mapping[$key] = 'userjs';
3129
			} else {
3130
				$mapping[$key] = 'unused';
3131
			}
3132
		}
3133
3134
		return $mapping;
3135
	}
3136
3137
	/**
3138
	 * Reset certain (or all) options to the site defaults
3139
	 *
3140
	 * The optional parameter determines which kinds of preferences will be reset.
3141
	 * Supported values are everything that can be reported by getOptionKinds()
3142
	 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3143
	 *
3144
	 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3145
	 *  array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3146
	 *  for backwards-compatibility.
3147
	 * @param IContextSource|null $context Context source used when $resetKinds
3148
	 *  does not contain 'all', passed to getOptionKinds().
3149
	 *  Defaults to RequestContext::getMain() when null.
3150
	 */
3151
	public function resetOptions(
3152
		$resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3153
		IContextSource $context = null
3154
	) {
3155
		$this->load();
3156
		$defaultOptions = self::getDefaultOptions();
3157
3158
		if ( !is_array( $resetKinds ) ) {
3159
			$resetKinds = [ $resetKinds ];
3160
		}
3161
3162
		if ( in_array( 'all', $resetKinds ) ) {
3163
			$newOptions = $defaultOptions;
3164
		} else {
3165
			if ( $context === null ) {
3166
				$context = RequestContext::getMain();
3167
			}
3168
3169
			$optionKinds = $this->getOptionKinds( $context );
3170
			$resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
3171
			$newOptions = [];
3172
3173
			// Use default values for the options that should be deleted, and
3174
			// copy old values for the ones that shouldn't.
3175
			foreach ( $this->mOptions as $key => $value ) {
3176
				if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3177
					if ( array_key_exists( $key, $defaultOptions ) ) {
3178
						$newOptions[$key] = $defaultOptions[$key];
3179
					}
3180
				} else {
3181
					$newOptions[$key] = $value;
3182
				}
3183
			}
3184
		}
3185
3186
		Hooks::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions, $resetKinds ] );
3187
3188
		$this->mOptions = $newOptions;
0 ignored issues
show
Documentation Bug introduced by
It seems like $newOptions can be null. However, the property $mOptions is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property.

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
3189
		$this->mOptionsLoaded = true;
3190
	}
3191
3192
	/**
3193
	 * Get the user's preferred date format.
3194
	 * @return string User's preferred date format
3195
	 */
3196
	public function getDatePreference() {
3197
		// Important migration for old data rows
3198
		if ( is_null( $this->mDatePreference ) ) {
3199
			global $wgLang;
3200
			$value = $this->getOption( 'date' );
3201
			$map = $wgLang->getDatePreferenceMigrationMap();
3202
			if ( isset( $map[$value] ) ) {
3203
				$value = $map[$value];
3204
			}
3205
			$this->mDatePreference = $value;
3206
		}
3207
		return $this->mDatePreference;
3208
	}
3209
3210
	/**
3211
	 * Determine based on the wiki configuration and the user's options,
3212
	 * whether this user must be over HTTPS no matter what.
3213
	 *
3214
	 * @return bool
3215
	 */
3216
	public function requiresHTTPS() {
3217
		global $wgSecureLogin;
3218
		if ( !$wgSecureLogin ) {
3219
			return false;
3220
		} else {
3221
			$https = $this->getBoolOption( 'prefershttps' );
3222
			Hooks::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3223
			if ( $https ) {
3224
				$https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3225
			}
3226
			return $https;
3227
		}
3228
	}
3229
3230
	/**
3231
	 * Get the user preferred stub threshold
3232
	 *
3233
	 * @return int
3234
	 */
3235
	public function getStubThreshold() {
3236
		global $wgMaxArticleSize; # Maximum article size, in Kb
3237
		$threshold = $this->getIntOption( 'stubthreshold' );
3238
		if ( $threshold > $wgMaxArticleSize * 1024 ) {
3239
			// If they have set an impossible value, disable the preference
3240
			// so we can use the parser cache again.
3241
			$threshold = 0;
3242
		}
3243
		return $threshold;
3244
	}
3245
3246
	/**
3247
	 * Get the permissions this user has.
3248
	 * @return array Array of String permission names
3249
	 */
3250
	public function getRights() {
3251
		if ( is_null( $this->mRights ) ) {
3252
			$this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
3253
3254
			// Deny any rights denied by the user's session, unless this
3255
			// endpoint has no sessions.
3256
			if ( !defined( 'MW_NO_SESSION' ) ) {
3257
				$allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3258
				if ( $allowedRights !== null ) {
3259
					$this->mRights = array_intersect( $this->mRights, $allowedRights );
3260
				}
3261
			}
3262
3263
			Hooks::run( 'UserGetRights', [ $this, &$this->mRights ] );
3264
			// Force reindexation of rights when a hook has unset one of them
3265
			$this->mRights = array_values( array_unique( $this->mRights ) );
3266
		}
3267
		return $this->mRights;
3268
	}
3269
3270
	/**
3271
	 * Get the list of explicit group memberships this user has.
3272
	 * The implicit * and user groups are not included.
3273
	 * @return array Array of String internal group names
3274
	 */
3275
	public function getGroups() {
3276
		$this->load();
3277
		$this->loadGroups();
3278
		return $this->mGroups;
3279
	}
3280
3281
	/**
3282
	 * Get the list of implicit group memberships this user has.
3283
	 * This includes all explicit groups, plus 'user' if logged in,
3284
	 * '*' for all accounts, and autopromoted groups
3285
	 * @param bool $recache Whether to avoid the cache
3286
	 * @return array Array of String internal group names
3287
	 */
3288
	public function getEffectiveGroups( $recache = false ) {
3289
		if ( $recache || is_null( $this->mEffectiveGroups ) ) {
3290
			$this->mEffectiveGroups = array_unique( array_merge(
3291
				$this->getGroups(), // explicit groups
3292
				$this->getAutomaticGroups( $recache ) // implicit groups
3293
			) );
3294
			// Hook for additional groups
3295
			Hooks::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups ] );
3296
			// Force reindexation of groups when a hook has unset one of them
3297
			$this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
3298
		}
3299
		return $this->mEffectiveGroups;
3300
	}
3301
3302
	/**
3303
	 * Get the list of implicit group memberships this user has.
3304
	 * This includes 'user' if logged in, '*' for all accounts,
3305
	 * and autopromoted groups
3306
	 * @param bool $recache Whether to avoid the cache
3307
	 * @return array Array of String internal group names
3308
	 */
3309
	public function getAutomaticGroups( $recache = false ) {
3310
		if ( $recache || is_null( $this->mImplicitGroups ) ) {
3311
			$this->mImplicitGroups = [ '*' ];
3312
			if ( $this->getId() ) {
3313
				$this->mImplicitGroups[] = 'user';
3314
3315
				$this->mImplicitGroups = array_unique( array_merge(
3316
					$this->mImplicitGroups,
3317
					Autopromote::getAutopromoteGroups( $this )
3318
				) );
3319
			}
3320
			if ( $recache ) {
3321
				// Assure data consistency with rights/groups,
3322
				// as getEffectiveGroups() depends on this function
3323
				$this->mEffectiveGroups = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $mEffectiveGroups.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
3324
			}
3325
		}
3326
		return $this->mImplicitGroups;
3327
	}
3328
3329
	/**
3330
	 * Returns the groups the user has belonged to.
3331
	 *
3332
	 * The user may still belong to the returned groups. Compare with getGroups().
3333
	 *
3334
	 * The function will not return groups the user had belonged to before MW 1.17
3335
	 *
3336
	 * @return array Names of the groups the user has belonged to.
3337
	 */
3338 View Code Duplication
	public function getFormerGroups() {
3339
		$this->load();
3340
3341
		if ( is_null( $this->mFormerGroups ) ) {
3342
			$db = ( $this->queryFlagsUsed & self::READ_LATEST )
3343
				? wfGetDB( DB_MASTER )
3344
				: wfGetDB( DB_SLAVE );
3345
			$res = $db->select( 'user_former_groups',
3346
				[ 'ufg_group' ],
3347
				[ 'ufg_user' => $this->mId ],
3348
				__METHOD__ );
3349
			$this->mFormerGroups = [];
3350
			foreach ( $res as $row ) {
0 ignored issues
show
Bug introduced by
The expression $res of type boolean|object<ResultWrapper> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
3351
				$this->mFormerGroups[] = $row->ufg_group;
3352
			}
3353
		}
3354
3355
		return $this->mFormerGroups;
3356
	}
3357
3358
	/**
3359
	 * Get the user's edit count.
3360
	 * @return int|null Null for anonymous users
3361
	 */
3362
	public function getEditCount() {
3363
		if ( !$this->getId() ) {
3364
			return null;
3365
		}
3366
3367
		if ( $this->mEditCount === null ) {
3368
			/* Populate the count, if it has not been populated yet */
3369
			$dbr = wfGetDB( DB_SLAVE );
3370
			// check if the user_editcount field has been initialized
3371
			$count = $dbr->selectField(
3372
				'user', 'user_editcount',
3373
				[ 'user_id' => $this->mId ],
3374
				__METHOD__
3375
			);
3376
3377
			if ( $count === null ) {
3378
				// it has not been initialized. do so.
3379
				$count = $this->initEditCount();
3380
			}
3381
			$this->mEditCount = $count;
3382
		}
3383
		return (int)$this->mEditCount;
3384
	}
3385
3386
	/**
3387
	 * Add the user to the given group.
3388
	 * This takes immediate effect.
3389
	 * @param string $group Name of the group to add
3390
	 * @return bool
3391
	 */
3392
	public function addGroup( $group ) {
3393
		$this->load();
3394
3395
		if ( !Hooks::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3396
			return false;
3397
		}
3398
3399
		$dbw = wfGetDB( DB_MASTER );
3400
		if ( $this->getId() ) {
3401
			$dbw->insert( 'user_groups',
3402
				[
3403
					'ug_user' => $this->getId(),
3404
					'ug_group' => $group,
3405
				],
3406
				__METHOD__,
3407
				[ 'IGNORE' ] );
3408
		}
3409
3410
		$this->loadGroups();
3411
		$this->mGroups[] = $group;
3412
		// In case loadGroups was not called before, we now have the right twice.
3413
		// Get rid of the duplicate.
3414
		$this->mGroups = array_unique( $this->mGroups );
3415
3416
		// Refresh the groups caches, and clear the rights cache so it will be
3417
		// refreshed on the next call to $this->getRights().
3418
		$this->getEffectiveGroups( true );
3419
		$this->mRights = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $mRights.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
3420
3421
		$this->invalidateCache();
3422
3423
		return true;
3424
	}
3425
3426
	/**
3427
	 * Remove the user from the given group.
3428
	 * This takes immediate effect.
3429
	 * @param string $group Name of the group to remove
3430
	 * @return bool
3431
	 */
3432
	public function removeGroup( $group ) {
3433
		$this->load();
3434
		if ( !Hooks::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3435
			return false;
3436
		}
3437
3438
		$dbw = wfGetDB( DB_MASTER );
3439
		$dbw->delete( 'user_groups',
3440
			[
3441
				'ug_user' => $this->getId(),
3442
				'ug_group' => $group,
3443
			], __METHOD__
3444
		);
3445
		// Remember that the user was in this group
3446
		$dbw->insert( 'user_former_groups',
3447
			[
3448
				'ufg_user' => $this->getId(),
3449
				'ufg_group' => $group,
3450
			],
3451
			__METHOD__,
3452
			[ 'IGNORE' ]
3453
		);
3454
3455
		$this->loadGroups();
3456
		$this->mGroups = array_diff( $this->mGroups, [ $group ] );
3457
3458
		// Refresh the groups caches, and clear the rights cache so it will be
3459
		// refreshed on the next call to $this->getRights().
3460
		$this->getEffectiveGroups( true );
3461
		$this->mRights = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $mRights.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
3462
3463
		$this->invalidateCache();
3464
3465
		return true;
3466
	}
3467
3468
	/**
3469
	 * Get whether the user is logged in
3470
	 * @return bool
3471
	 */
3472
	public function isLoggedIn() {
3473
		return $this->getId() != 0;
3474
	}
3475
3476
	/**
3477
	 * Get whether the user is anonymous
3478
	 * @return bool
3479
	 */
3480
	public function isAnon() {
3481
		return !$this->isLoggedIn();
3482
	}
3483
3484
	/**
3485
	 * @return bool Whether this user is flagged as being a bot role account
3486
	 * @since 1.28
3487
	 */
3488
	public function isBot() {
3489
		if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3490
			return true;
3491
		}
3492
3493
		$isBot = false;
3494
		Hooks::run( "UserIsBot", [ $this, &$isBot ] );
3495
3496
		return $isBot;
3497
	}
3498
3499
	/**
3500
	 * Check if user is allowed to access a feature / make an action
3501
	 *
3502
	 * @param string ... Permissions to test
3503
	 * @return bool True if user is allowed to perform *any* of the given actions
3504
	 */
3505 View Code Duplication
	public function isAllowedAny() {
3506
		$permissions = func_get_args();
3507
		foreach ( $permissions as $permission ) {
3508
			if ( $this->isAllowed( $permission ) ) {
3509
				return true;
3510
			}
3511
		}
3512
		return false;
3513
	}
3514
3515
	/**
3516
	 *
3517
	 * @param string ... Permissions to test
3518
	 * @return bool True if the user is allowed to perform *all* of the given actions
3519
	 */
3520 View Code Duplication
	public function isAllowedAll() {
3521
		$permissions = func_get_args();
3522
		foreach ( $permissions as $permission ) {
3523
			if ( !$this->isAllowed( $permission ) ) {
3524
				return false;
3525
			}
3526
		}
3527
		return true;
3528
	}
3529
3530
	/**
3531
	 * Internal mechanics of testing a permission
3532
	 * @param string $action
3533
	 * @return bool
3534
	 */
3535
	public function isAllowed( $action = '' ) {
3536
		if ( $action === '' ) {
3537
			return true; // In the spirit of DWIM
3538
		}
3539
		// Use strict parameter to avoid matching numeric 0 accidentally inserted
3540
		// by misconfiguration: 0 == 'foo'
3541
		return in_array( $action, $this->getRights(), true );
3542
	}
3543
3544
	/**
3545
	 * Check whether to enable recent changes patrol features for this user
3546
	 * @return bool True or false
3547
	 */
3548
	public function useRCPatrol() {
3549
		global $wgUseRCPatrol;
3550
		return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3551
	}
3552
3553
	/**
3554
	 * Check whether to enable new pages patrol features for this user
3555
	 * @return bool True or false
3556
	 */
3557
	public function useNPPatrol() {
3558
		global $wgUseRCPatrol, $wgUseNPPatrol;
3559
		return (
3560
			( $wgUseRCPatrol || $wgUseNPPatrol )
3561
				&& ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3562
		);
3563
	}
3564
3565
	/**
3566
	 * Check whether to enable new files patrol features for this user
3567
	 * @return bool True or false
3568
	 */
3569
	public function useFilePatrol() {
3570
		global $wgUseRCPatrol, $wgUseFilePatrol;
3571
		return (
3572
			( $wgUseRCPatrol || $wgUseFilePatrol )
3573
				&& ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3574
		);
3575
	}
3576
3577
	/**
3578
	 * Get the WebRequest object to use with this object
3579
	 *
3580
	 * @return WebRequest
3581
	 */
3582
	public function getRequest() {
3583
		if ( $this->mRequest ) {
3584
			return $this->mRequest;
3585
		} else {
3586
			global $wgRequest;
3587
			return $wgRequest;
3588
		}
3589
	}
3590
3591
	/**
3592
	 * Check the watched status of an article.
3593
	 * @since 1.22 $checkRights parameter added
3594
	 * @param Title $title Title of the article to look at
3595
	 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3596
	 *     Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3597
	 * @return bool
3598
	 */
3599
	public function isWatched( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3600
		if ( $title->isWatchable() && ( !$checkRights || $this->isAllowed( 'viewmywatchlist' ) ) ) {
3601
			return MediaWikiServices::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3602
		}
3603
		return false;
3604
	}
3605
3606
	/**
3607
	 * Watch an article.
3608
	 * @since 1.22 $checkRights parameter added
3609
	 * @param Title $title Title of the article to look at
3610
	 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3611
	 *     Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3612
	 */
3613
	public function addWatch( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3614
		if ( !$checkRights || $this->isAllowed( 'editmywatchlist' ) ) {
3615
			MediaWikiServices::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3616
				$this,
3617
				[ $title->getSubjectPage(), $title->getTalkPage() ]
3618
			);
3619
		}
3620
		$this->invalidateCache();
3621
	}
3622
3623
	/**
3624
	 * Stop watching an article.
3625
	 * @since 1.22 $checkRights parameter added
3626
	 * @param Title $title Title of the article to look at
3627
	 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3628
	 *     Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3629
	 */
3630
	public function removeWatch( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3631
		if ( !$checkRights || $this->isAllowed( 'editmywatchlist' ) ) {
3632
			$store = MediaWikiServices::getInstance()->getWatchedItemStore();
3633
			$store->removeWatch( $this, $title->getSubjectPage() );
3634
			$store->removeWatch( $this, $title->getTalkPage() );
3635
		}
3636
		$this->invalidateCache();
3637
	}
3638
3639
	/**
3640
	 * Clear the user's notification timestamp for the given title.
3641
	 * If e-notif e-mails are on, they will receive notification mails on
3642
	 * the next change of the page if it's watched etc.
3643
	 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3644
	 * @param Title $title Title of the article to look at
3645
	 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3646
	 */
3647
	public function clearNotification( &$title, $oldid = 0 ) {
3648
		global $wgUseEnotif, $wgShowUpdatedMarker;
3649
3650
		// Do nothing if the database is locked to writes
3651
		if ( wfReadOnly() ) {
3652
			return;
3653
		}
3654
3655
		// Do nothing if not allowed to edit the watchlist
3656
		if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3657
			return;
3658
		}
3659
3660
		// If we're working on user's talk page, we should update the talk page message indicator
3661
		if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3662
			if ( !Hooks::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3663
				return;
3664
			}
3665
3666
			// Try to update the DB post-send and only if needed...
3667
			DeferredUpdates::addCallableUpdate( function() use ( $title, $oldid ) {
3668
				if ( !$this->getNewtalk() ) {
3669
					return; // no notifications to clear
3670
				}
3671
3672
				// Delete the last notifications (they stack up)
3673
				$this->setNewtalk( false );
3674
3675
				// If there is a new, unseen, revision, use its timestamp
3676
				$nextid = $oldid
3677
					? $title->getNextRevisionID( $oldid, Title::GAID_FOR_UPDATE )
3678
					: null;
3679
				if ( $nextid ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $nextid of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
3680
					$this->setNewtalk( true, Revision::newFromId( $nextid ) );
3681
				}
3682
			} );
3683
		}
3684
3685
		if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3686
			return;
3687
		}
3688
3689
		if ( $this->isAnon() ) {
3690
			// Nothing else to do...
3691
			return;
3692
		}
3693
3694
		// Only update the timestamp if the page is being watched.
3695
		// The query to find out if it is watched is cached both in memcached and per-invocation,
3696
		// and when it does have to be executed, it can be on a slave
3697
		// If this is the user's newtalk page, we always update the timestamp
3698
		$force = '';
3699
		if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3700
			$force = 'force';
3701
		}
3702
3703
		MediaWikiServices::getInstance()->getWatchedItemStore()
3704
			->resetNotificationTimestamp( $this, $title, $force, $oldid );
3705
	}
3706
3707
	/**
3708
	 * Resets all of the given user's page-change notification timestamps.
3709
	 * If e-notif e-mails are on, they will receive notification mails on
3710
	 * the next change of any watched page.
3711
	 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3712
	 */
3713
	public function clearAllNotifications() {
3714
		if ( wfReadOnly() ) {
3715
			return;
3716
		}
3717
3718
		// Do nothing if not allowed to edit the watchlist
3719
		if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3720
			return;
3721
		}
3722
3723
		global $wgUseEnotif, $wgShowUpdatedMarker;
3724
		if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3725
			$this->setNewtalk( false );
3726
			return;
3727
		}
3728
		$id = $this->getId();
3729
		if ( $id != 0 ) {
3730
			$dbw = wfGetDB( DB_MASTER );
3731
			$dbw->update( 'watchlist',
3732
				[ /* SET */ 'wl_notificationtimestamp' => null ],
3733
				[ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3734
				__METHOD__
3735
			);
3736
			// We also need to clear here the "you have new message" notification for the own user_talk page;
3737
			// it's cleared one page view later in WikiPage::doViewUpdates().
3738
		}
3739
	}
3740
3741
	/**
3742
	 * Set a cookie on the user's client. Wrapper for
3743
	 * WebResponse::setCookie
3744
	 * @deprecated since 1.27
3745
	 * @param string $name Name of the cookie to set
3746
	 * @param string $value Value to set
3747
	 * @param int $exp Expiration time, as a UNIX time value;
3748
	 *                   if 0 or not specified, use the default $wgCookieExpiration
3749
	 * @param bool $secure
3750
	 *  true: Force setting the secure attribute when setting the cookie
3751
	 *  false: Force NOT setting the secure attribute when setting the cookie
3752
	 *  null (default): Use the default ($wgCookieSecure) to set the secure attribute
3753
	 * @param array $params Array of options sent passed to WebResponse::setcookie()
3754
	 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3755
	 *        is passed.
3756
	 */
3757
	protected function setCookie(
3758
		$name, $value, $exp = 0, $secure = null, $params = [], $request = null
3759
	) {
3760
		wfDeprecated( __METHOD__, '1.27' );
3761
		if ( $request === null ) {
3762
			$request = $this->getRequest();
3763
		}
3764
		$params['secure'] = $secure;
3765
		$request->response()->setCookie( $name, $value, $exp, $params );
3766
	}
3767
3768
	/**
3769
	 * Clear a cookie on the user's client
3770
	 * @deprecated since 1.27
3771
	 * @param string $name Name of the cookie to clear
3772
	 * @param bool $secure
3773
	 *  true: Force setting the secure attribute when setting the cookie
3774
	 *  false: Force NOT setting the secure attribute when setting the cookie
3775
	 *  null (default): Use the default ($wgCookieSecure) to set the secure attribute
3776
	 * @param array $params Array of options sent passed to WebResponse::setcookie()
3777
	 */
3778
	protected function clearCookie( $name, $secure = null, $params = [] ) {
3779
		wfDeprecated( __METHOD__, '1.27' );
3780
		$this->setCookie( $name, '', time() - 86400, $secure, $params );
0 ignored issues
show
Deprecated Code introduced by
The method User::setCookie() has been deprecated with message: since 1.27

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3781
	}
3782
3783
	/**
3784
	 * Set an extended login cookie on the user's client. The expiry of the cookie
3785
	 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3786
	 * variable.
3787
	 *
3788
	 * @see User::setCookie
3789
	 *
3790
	 * @deprecated since 1.27
3791
	 * @param string $name Name of the cookie to set
3792
	 * @param string $value Value to set
3793
	 * @param bool $secure
3794
	 *  true: Force setting the secure attribute when setting the cookie
3795
	 *  false: Force NOT setting the secure attribute when setting the cookie
3796
	 *  null (default): Use the default ($wgCookieSecure) to set the secure attribute
3797
	 */
3798
	protected function setExtendedLoginCookie( $name, $value, $secure ) {
3799
		global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3800
3801
		wfDeprecated( __METHOD__, '1.27' );
3802
3803
		$exp = time();
3804
		$exp += $wgExtendedLoginCookieExpiration !== null
3805
			? $wgExtendedLoginCookieExpiration
3806
			: $wgCookieExpiration;
3807
3808
		$this->setCookie( $name, $value, $exp, $secure );
0 ignored issues
show
Deprecated Code introduced by
The method User::setCookie() has been deprecated with message: since 1.27

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3809
	}
3810
3811
	/**
3812
	 * Persist this user's session (e.g. set cookies)
3813
	 *
3814
	 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3815
	 *        is passed.
3816
	 * @param bool $secure Whether to force secure/insecure cookies or use default
3817
	 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3818
	 */
3819
	public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3820
		$this->load();
3821
		if ( 0 == $this->mId ) {
3822
			return;
3823
		}
3824
3825
		$session = $this->getRequest()->getSession();
3826
		if ( $request && $session->getRequest() !== $request ) {
3827
			$session = $session->sessionWithRequest( $request );
3828
		}
3829
		$delay = $session->delaySave();
3830
3831
		if ( !$session->getUser()->equals( $this ) ) {
3832
			if ( !$session->canSetUser() ) {
3833
				\MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3834
					->warning( __METHOD__ .
3835
						": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3836
					);
3837
				return;
3838
			}
3839
			$session->setUser( $this );
3840
		}
3841
3842
		$session->setRememberUser( $rememberMe );
3843
		if ( $secure !== null ) {
3844
			$session->setForceHTTPS( $secure );
3845
		}
3846
3847
		$session->persist();
3848
3849
		ScopedCallback::consume( $delay );
3850
	}
3851
3852
	/**
3853
	 * Log this user out.
3854
	 */
3855
	public function logout() {
3856
		if ( Hooks::run( 'UserLogout', [ &$this ] ) ) {
3857
			$this->doLogout();
3858
		}
3859
	}
3860
3861
	/**
3862
	 * Clear the user's session, and reset the instance cache.
3863
	 * @see logout()
3864
	 */
3865
	public function doLogout() {
3866
		$session = $this->getRequest()->getSession();
3867
		if ( !$session->canSetUser() ) {
3868
			\MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3869
				->warning( __METHOD__ . ": Cannot log out of an immutable session" );
3870
			$error = 'immutable';
3871
		} elseif ( !$session->getUser()->equals( $this ) ) {
3872
			\MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3873
				->warning( __METHOD__ .
3874
					": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3875
				);
3876
			// But we still may as well make this user object anon
3877
			$this->clearInstanceCache( 'defaults' );
3878
			$error = 'wronguser';
3879
		} else {
3880
			$this->clearInstanceCache( 'defaults' );
3881
			$delay = $session->delaySave();
3882
			$session->unpersist(); // Clear cookies (T127436)
3883
			$session->setLoggedOutTimestamp( time() );
3884
			$session->setUser( new User );
3885
			$session->set( 'wsUserID', 0 ); // Other code expects this
3886
			$session->resetAllTokens();
3887
			ScopedCallback::consume( $delay );
3888
			$error = false;
3889
		}
3890
		\MediaWiki\Logger\LoggerFactory::getInstance( 'authmanager' )->info( 'Logout', [
3891
			'event' => 'logout',
3892
			'successful' => $error === false,
3893
			'status' => $error ?: 'success',
3894
		] );
3895
	}
3896
3897
	/**
3898
	 * Save this user's settings into the database.
3899
	 * @todo Only rarely do all these fields need to be set!
3900
	 */
3901
	public function saveSettings() {
3902
		if ( wfReadOnly() ) {
3903
			// @TODO: caller should deal with this instead!
3904
			// This should really just be an exception.
3905
			MWExceptionHandler::logException( new DBExpectedError(
3906
				null,
3907
				"Could not update user with ID '{$this->mId}'; DB is read-only."
3908
			) );
3909
			return;
3910
		}
3911
3912
		$this->load();
3913
		if ( 0 == $this->mId ) {
3914
			return; // anon
3915
		}
3916
3917
		// Get a new user_touched that is higher than the old one.
3918
		// This will be used for a CAS check as a last-resort safety
3919
		// check against race conditions and slave lag.
3920
		$newTouched = $this->newTouchedTimestamp();
3921
3922
		$dbw = wfGetDB( DB_MASTER );
3923
		$dbw->update( 'user',
3924
			[ /* SET */
3925
				'user_name' => $this->mName,
3926
				'user_real_name' => $this->mRealName,
3927
				'user_email' => $this->mEmail,
3928
				'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3929
				'user_touched' => $dbw->timestamp( $newTouched ),
3930
				'user_token' => strval( $this->mToken ),
3931
				'user_email_token' => $this->mEmailToken,
3932
				'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3933
			], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3934
				'user_id' => $this->mId,
3935
			] ), __METHOD__
3936
		);
3937
3938
		if ( !$dbw->affectedRows() ) {
3939
			// Maybe the problem was a missed cache update; clear it to be safe
3940
			$this->clearSharedCache( 'refresh' );
3941
			// User was changed in the meantime or loaded with stale data
3942
			$from = ( $this->queryFlagsUsed & self::READ_LATEST ) ? 'master' : 'slave';
3943
			throw new MWException(
3944
				"CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3945
				" the version of the user to be saved is older than the current version."
3946
			);
3947
		}
3948
3949
		$this->mTouched = $newTouched;
0 ignored issues
show
Documentation Bug introduced by
It seems like $newTouched can also be of type false. However, the property $mTouched is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
3950
		$this->saveOptions();
3951
3952
		Hooks::run( 'UserSaveSettings', [ $this ] );
3953
		$this->clearSharedCache();
3954
		$this->getUserPage()->invalidateCache();
3955
	}
3956
3957
	/**
3958
	 * If only this user's username is known, and it exists, return the user ID.
3959
	 *
3960
	 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3961
	 * @return int
3962
	 */
3963
	public function idForName( $flags = 0 ) {
3964
		$s = trim( $this->getName() );
3965
		if ( $s === '' ) {
3966
			return 0;
3967
		}
3968
3969
		$db = ( ( $flags & self::READ_LATEST ) == self::READ_LATEST )
3970
			? wfGetDB( DB_MASTER )
3971
			: wfGetDB( DB_SLAVE );
3972
3973
		$options = ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING )
3974
			? [ 'LOCK IN SHARE MODE' ]
3975
			: [];
3976
3977
		$id = $db->selectField( 'user',
3978
			'user_id', [ 'user_name' => $s ], __METHOD__, $options );
3979
3980
		return (int)$id;
3981
	}
3982
3983
	/**
3984
	 * Add a user to the database, return the user object
3985
	 *
3986
	 * @param string $name Username to add
3987
	 * @param array $params Array of Strings Non-default parameters to save to
3988
	 *   the database as user_* fields:
3989
	 *   - email: The user's email address.
3990
	 *   - email_authenticated: The email authentication timestamp.
3991
	 *   - real_name: The user's real name.
3992
	 *   - options: An associative array of non-default options.
3993
	 *   - token: Random authentication token. Do not set.
3994
	 *   - registration: Registration timestamp. Do not set.
3995
	 *
3996
	 * @return User|null User object, or null if the username already exists.
3997
	 */
3998
	public static function createNew( $name, $params = [] ) {
3999
		foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4000
			if ( isset( $params[$field] ) ) {
4001
				wfDeprecated( __METHOD__ . " with param '$field'", '1.27' );
4002
				unset( $params[$field] );
4003
			}
4004
		}
4005
4006
		$user = new User;
4007
		$user->load();
4008
		$user->setToken(); // init token
4009
		if ( isset( $params['options'] ) ) {
4010
			$user->mOptions = $params['options'] + (array)$user->mOptions;
4011
			unset( $params['options'] );
4012
		}
4013
		$dbw = wfGetDB( DB_MASTER );
4014
		$seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4015
4016
		$noPass = PasswordFactory::newInvalidPassword()->toString();
4017
4018
		$fields = [
4019
			'user_id' => $seqVal,
4020
			'user_name' => $name,
4021
			'user_password' => $noPass,
4022
			'user_newpassword' => $noPass,
4023
			'user_email' => $user->mEmail,
4024
			'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
4025
			'user_real_name' => $user->mRealName,
4026
			'user_token' => strval( $user->mToken ),
4027
			'user_registration' => $dbw->timestamp( $user->mRegistration ),
4028
			'user_editcount' => 0,
4029
			'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4030
		];
4031
		foreach ( $params as $name => $value ) {
4032
			$fields["user_$name"] = $value;
4033
		}
4034
		$dbw->insert( 'user', $fields, __METHOD__, [ 'IGNORE' ] );
4035
		if ( $dbw->affectedRows() ) {
4036
			$newUser = User::newFromId( $dbw->insertId() );
4037
		} else {
4038
			$newUser = null;
4039
		}
4040
		return $newUser;
4041
	}
4042
4043
	/**
4044
	 * Add this existing user object to the database. If the user already
4045
	 * exists, a fatal status object is returned, and the user object is
4046
	 * initialised with the data from the database.
4047
	 *
4048
	 * Previously, this function generated a DB error due to a key conflict
4049
	 * if the user already existed. Many extension callers use this function
4050
	 * in code along the lines of:
4051
	 *
4052
	 *   $user = User::newFromName( $name );
4053
	 *   if ( !$user->isLoggedIn() ) {
4054
	 *       $user->addToDatabase();
4055
	 *   }
4056
	 *   // do something with $user...
4057
	 *
4058
	 * However, this was vulnerable to a race condition (bug 16020). By
4059
	 * initialising the user object if the user exists, we aim to support this
4060
	 * calling sequence as far as possible.
4061
	 *
4062
	 * Note that if the user exists, this function will acquire a write lock,
4063
	 * so it is still advisable to make the call conditional on isLoggedIn(),
4064
	 * and to commit the transaction after calling.
4065
	 *
4066
	 * @throws MWException
4067
	 * @return Status
4068
	 */
4069
	public function addToDatabase() {
4070
		$this->load();
4071
		if ( !$this->mToken ) {
4072
			$this->setToken(); // init token
4073
		}
4074
4075
		$this->mTouched = $this->newTouchedTimestamp();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->newTouchedTimestamp() can also be of type false. However, the property $mTouched is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
4076
4077
		$noPass = PasswordFactory::newInvalidPassword()->toString();
4078
4079
		$dbw = wfGetDB( DB_MASTER );
4080
		$inWrite = $dbw->writesOrCallbacksPending();
4081
		$seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4082
		$dbw->insert( 'user',
4083
			[
4084
				'user_id' => $seqVal,
4085
				'user_name' => $this->mName,
4086
				'user_password' => $noPass,
4087
				'user_newpassword' => $noPass,
4088
				'user_email' => $this->mEmail,
4089
				'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
4090
				'user_real_name' => $this->mRealName,
4091
				'user_token' => strval( $this->mToken ),
4092
				'user_registration' => $dbw->timestamp( $this->mRegistration ),
4093
				'user_editcount' => 0,
4094
				'user_touched' => $dbw->timestamp( $this->mTouched ),
4095
			], __METHOD__,
4096
			[ 'IGNORE' ]
4097
		);
4098
		if ( !$dbw->affectedRows() ) {
4099
			// The queries below cannot happen in the same REPEATABLE-READ snapshot.
4100
			// Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
4101
			if ( $inWrite ) {
4102
				// Can't commit due to pending writes that may need atomicity.
4103
				// This may cause some lock contention unlike the case below.
4104
				$options = [ 'LOCK IN SHARE MODE' ];
4105
				$flags = self::READ_LOCKING;
4106
			} else {
4107
				// Often, this case happens early in views before any writes when
4108
				// using CentralAuth. It's should be OK to commit and break the snapshot.
4109
				$dbw->commit( __METHOD__, 'flush' );
4110
				$options = [];
4111
				$flags = self::READ_LATEST;
4112
			}
4113
			$this->mId = $dbw->selectField( 'user', 'user_id',
4114
				[ 'user_name' => $this->mName ], __METHOD__, $options );
4115
			$loaded = false;
4116
			if ( $this->mId ) {
4117
				if ( $this->loadFromDatabase( $flags ) ) {
4118
					$loaded = true;
4119
				}
4120
			}
4121
			if ( !$loaded ) {
4122
				throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
4123
					"to insert user '{$this->mName}' row, but it was not present in select!" );
4124
			}
4125
			return Status::newFatal( 'userexists' );
4126
		}
4127
		$this->mId = $dbw->insertId();
4128
		self::$idCacheByName[$this->mName] = $this->mId;
4129
4130
		// Clear instance cache other than user table data, which is already accurate
4131
		$this->clearInstanceCache();
4132
4133
		$this->saveOptions();
4134
		return Status::newGood();
4135
	}
4136
4137
	/**
4138
	 * If this user is logged-in and blocked,
4139
	 * block any IP address they've successfully logged in from.
4140
	 * @return bool A block was spread
4141
	 */
4142
	public function spreadAnyEditBlock() {
4143
		if ( $this->isLoggedIn() && $this->isBlocked() ) {
4144
			return $this->spreadBlock();
4145
		}
4146
4147
		return false;
4148
	}
4149
4150
	/**
4151
	 * If this (non-anonymous) user is blocked,
4152
	 * block the IP address they've successfully logged in from.
4153
	 * @return bool A block was spread
4154
	 */
4155
	protected function spreadBlock() {
4156
		wfDebug( __METHOD__ . "()\n" );
4157
		$this->load();
4158
		if ( $this->mId == 0 ) {
4159
			return false;
4160
		}
4161
4162
		$userblock = Block::newFromTarget( $this->getName() );
4163
		if ( !$userblock ) {
4164
			return false;
4165
		}
4166
4167
		return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4168
	}
4169
4170
	/**
4171
	 * Get whether the user is explicitly blocked from account creation.
4172
	 * @return bool|Block
4173
	 */
4174
	public function isBlockedFromCreateAccount() {
4175
		$this->getBlockedStatus();
4176
		if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
4177
			return $this->mBlock;
4178
		}
4179
4180
		# bug 13611: if the IP address the user is trying to create an account from is
4181
		# blocked with createaccount disabled, prevent new account creation there even
4182
		# when the user is logged in
4183
		if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4184
			$this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
4185
		}
4186
		return $this->mBlockedFromCreateAccount instanceof Block
4187
			&& $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
4188
			? $this->mBlockedFromCreateAccount
4189
			: false;
4190
	}
4191
4192
	/**
4193
	 * Get whether the user is blocked from using Special:Emailuser.
4194
	 * @return bool
4195
	 */
4196
	public function isBlockedFromEmailuser() {
4197
		$this->getBlockedStatus();
4198
		return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
4199
	}
4200
4201
	/**
4202
	 * Get whether the user is allowed to create an account.
4203
	 * @return bool
4204
	 */
4205
	public function isAllowedToCreateAccount() {
4206
		return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4207
	}
4208
4209
	/**
4210
	 * Get this user's personal page title.
4211
	 *
4212
	 * @return Title User's personal page title
4213
	 */
4214
	public function getUserPage() {
4215
		return Title::makeTitle( NS_USER, $this->getName() );
4216
	}
4217
4218
	/**
4219
	 * Get this user's talk page title.
4220
	 *
4221
	 * @return Title User's talk page title
4222
	 */
4223
	public function getTalkPage() {
4224
		$title = $this->getUserPage();
4225
		return $title->getTalkPage();
4226
	}
4227
4228
	/**
4229
	 * Determine whether the user is a newbie. Newbies are either
4230
	 * anonymous IPs, or the most recently created accounts.
4231
	 * @return bool
4232
	 */
4233
	public function isNewbie() {
4234
		return !$this->isAllowed( 'autoconfirmed' );
4235
	}
4236
4237
	/**
4238
	 * Check to see if the given clear-text password is one of the accepted passwords
4239
	 * @deprecated since 1.27, use AuthManager instead
4240
	 * @param string $password User password
4241
	 * @return bool True if the given password is correct, otherwise False
4242
	 */
4243
	public function checkPassword( $password ) {
4244
		global $wgAuth, $wgLegacyEncoding, $wgDisableAuthManager;
4245
4246
		if ( $wgDisableAuthManager ) {
4247
			$this->load();
4248
4249
			// Some passwords will give a fatal Status, which means there is
4250
			// some sort of technical or security reason for this password to
4251
			// be completely invalid and should never be checked (e.g., T64685)
4252
			if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4253
				return false;
4254
			}
4255
4256
			// Certain authentication plugins do NOT want to save
4257
			// domain passwords in a mysql database, so we should
4258
			// check this (in case $wgAuth->strict() is false).
4259
			if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4260
				return true;
4261
			} elseif ( $wgAuth->strict() ) {
4262
				// Auth plugin doesn't allow local authentication
4263
				return false;
4264
			} elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4265
				// Auth plugin doesn't allow local authentication for this user name
4266
				return false;
4267
			}
4268
4269
			$passwordFactory = new PasswordFactory();
4270
			$passwordFactory->init( RequestContext::getMain()->getConfig() );
4271
			$db = ( $this->queryFlagsUsed & self::READ_LATEST )
4272
				? wfGetDB( DB_MASTER )
4273
				: wfGetDB( DB_SLAVE );
4274
4275
			try {
4276
				$mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4277
					'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4278
				) );
4279
			} catch ( PasswordError $e ) {
4280
				wfDebug( 'Invalid password hash found in database.' );
4281
				$mPassword = PasswordFactory::newInvalidPassword();
4282
			}
4283
4284
			if ( !$mPassword->equals( $password ) ) {
4285
				if ( $wgLegacyEncoding ) {
4286
					// Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4287
					// Check for this with iconv
4288
					$cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4289
					if ( $cp1252Password === $password || !$mPassword->equals( $cp1252Password ) ) {
4290
						return false;
4291
					}
4292
				} else {
4293
					return false;
4294
				}
4295
			}
4296
4297
			if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
0 ignored issues
show
Bug introduced by
It seems like $mPassword defined by \PasswordFactory::newInvalidPassword() on line 4281 can be null; however, PasswordFactory::needsUpdate() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
4298
				$this->setPasswordInternal( $password );
4299
			}
4300
4301
			return true;
4302
		} else {
4303
			$manager = AuthManager::singleton();
4304
			$reqs = AuthenticationRequest::loadRequestsFromSubmission(
4305
				$manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN ),
4306
				[
4307
					'username' => $this->getName(),
4308
					'password' => $password,
4309
				]
4310
			);
4311
			$res = AuthManager::singleton()->beginAuthentication( $reqs, 'null:' );
4312
			switch ( $res->status ) {
4313
				case AuthenticationResponse::PASS:
4314
					return true;
4315
				case AuthenticationResponse::FAIL:
4316
					// Hope it's not a PreAuthenticationProvider that failed...
4317
					\MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
4318
						->info( __METHOD__ . ': Authentication failed: ' . $res->message->plain() );
4319
					return false;
4320
				default:
4321
					throw new BadMethodCallException(
4322
						'AuthManager returned a response unsupported by ' . __METHOD__
4323
					);
4324
			}
4325
		}
4326
	}
4327
4328
	/**
4329
	 * Check if the given clear-text password matches the temporary password
4330
	 * sent by e-mail for password reset operations.
4331
	 *
4332
	 * @deprecated since 1.27, use AuthManager instead
4333
	 * @param string $plaintext
4334
	 * @return bool True if matches, false otherwise
4335
	 */
4336
	public function checkTemporaryPassword( $plaintext ) {
4337
		global $wgNewPasswordExpiry, $wgDisableAuthManager;
4338
4339
		if ( $wgDisableAuthManager ) {
4340
			$this->load();
4341
4342
			$passwordFactory = new PasswordFactory();
4343
			$passwordFactory->init( RequestContext::getMain()->getConfig() );
4344
			$db = ( $this->queryFlagsUsed & self::READ_LATEST )
4345
				? wfGetDB( DB_MASTER )
4346
				: wfGetDB( DB_SLAVE );
4347
4348
			$row = $db->selectRow(
4349
				'user',
4350
				[ 'user_newpassword', 'user_newpass_time' ],
4351
				[ 'user_id' => $this->getId() ],
4352
				__METHOD__
4353
			);
4354
			try {
4355
				$newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
4356
			} catch ( PasswordError $e ) {
4357
				wfDebug( 'Invalid password hash found in database.' );
4358
				$newPassword = PasswordFactory::newInvalidPassword();
4359
			}
4360
4361
			if ( $newPassword->equals( $plaintext ) ) {
4362
				if ( is_null( $row->user_newpass_time ) ) {
4363
					return true;
4364
				}
4365
				$expiry = wfTimestamp( TS_UNIX, $row->user_newpass_time ) + $wgNewPasswordExpiry;
4366
				return ( time() < $expiry );
4367
			} else {
4368
				return false;
4369
			}
4370
		} else {
4371
			// Can't check the temporary password individually.
4372
			return $this->checkPassword( $plaintext );
0 ignored issues
show
Deprecated Code introduced by
The method User::checkPassword() has been deprecated with message: since 1.27, use AuthManager instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
4373
		}
4374
	}
4375
4376
	/**
4377
	 * Initialize (if necessary) and return a session token value
4378
	 * which can be used in edit forms to show that the user's
4379
	 * login credentials aren't being hijacked with a foreign form
4380
	 * submission.
4381
	 *
4382
	 * @since 1.27
4383
	 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4384
	 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4385
	 * @return MediaWiki\Session\Token The new edit token
4386
	 */
4387
	public function getEditTokenObject( $salt = '', $request = null ) {
4388
		if ( $this->isAnon() ) {
4389
			return new LoggedOutEditToken();
4390
		}
4391
4392
		if ( !$request ) {
4393
			$request = $this->getRequest();
4394
		}
4395
		return $request->getSession()->getToken( $salt );
0 ignored issues
show
Bug introduced by
It seems like $salt defined by parameter $salt on line 4387 can also be of type array; however, MediaWiki\Session\Session::getToken() does only seem to accept string|array<integer,string>, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
4396
	}
4397
4398
	/**
4399
	 * Initialize (if necessary) and return a session token value
4400
	 * which can be used in edit forms to show that the user's
4401
	 * login credentials aren't being hijacked with a foreign form
4402
	 * submission.
4403
	 *
4404
	 * @since 1.19
4405
	 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4406
	 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4407
	 * @return string The new edit token
4408
	 */
4409
	public function getEditToken( $salt = '', $request = null ) {
4410
		return $this->getEditTokenObject( $salt, $request )->toString();
4411
	}
4412
4413
	/**
4414
	 * Get the embedded timestamp from a token.
4415
	 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4416
	 * @param string $val Input token
4417
	 * @return int|null
4418
	 */
4419
	public static function getEditTokenTimestamp( $val ) {
4420
		wfDeprecated( __METHOD__, '1.27' );
4421
		return MediaWiki\Session\Token::getTimestamp( $val );
4422
	}
4423
4424
	/**
4425
	 * Check given value against the token value stored in the session.
4426
	 * A match should confirm that the form was submitted from the
4427
	 * user's own login session, not a form submission from a third-party
4428
	 * site.
4429
	 *
4430
	 * @param string $val Input value to compare
4431
	 * @param string $salt Optional function-specific data for hashing
4432
	 * @param WebRequest|null $request Object to use or null to use $wgRequest
4433
	 * @param int $maxage Fail tokens older than this, in seconds
4434
	 * @return bool Whether the token matches
4435
	 */
4436
	public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4437
		return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4438
	}
4439
4440
	/**
4441
	 * Check given value against the token value stored in the session,
4442
	 * ignoring the suffix.
4443
	 *
4444
	 * @param string $val Input value to compare
4445
	 * @param string $salt Optional function-specific data for hashing
4446
	 * @param WebRequest|null $request Object to use or null to use $wgRequest
4447
	 * @param int $maxage Fail tokens older than this, in seconds
4448
	 * @return bool Whether the token matches
4449
	 */
4450
	public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4451
		$val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token::SUFFIX;
4452
		return $this->matchEditToken( $val, $salt, $request, $maxage );
4453
	}
4454
4455
	/**
4456
	 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4457
	 * mail to the user's given address.
4458
	 *
4459
	 * @param string $type Message to send, either "created", "changed" or "set"
4460
	 * @return Status
4461
	 */
4462
	public function sendConfirmationMail( $type = 'created' ) {
4463
		global $wgLang;
4464
		$expiration = null; // gets passed-by-ref and defined in next line.
4465
		$token = $this->confirmationToken( $expiration );
4466
		$url = $this->confirmationTokenUrl( $token );
4467
		$invalidateURL = $this->invalidationTokenUrl( $token );
4468
		$this->saveSettings();
4469
4470
		if ( $type == 'created' || $type === false ) {
4471
			$message = 'confirmemail_body';
4472
		} elseif ( $type === true ) {
4473
			$message = 'confirmemail_body_changed';
4474
		} else {
4475
			// Messages: confirmemail_body_changed, confirmemail_body_set
4476
			$message = 'confirmemail_body_' . $type;
4477
		}
4478
4479
		return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4480
			wfMessage( $message,
4481
				$this->getRequest()->getIP(),
4482
				$this->getName(),
4483
				$url,
4484
				$wgLang->userTimeAndDate( $expiration, $this ),
4485
				$invalidateURL,
4486
				$wgLang->userDate( $expiration, $this ),
4487
				$wgLang->userTime( $expiration, $this ) )->text() );
4488
	}
4489
4490
	/**
4491
	 * Send an e-mail to this user's account. Does not check for
4492
	 * confirmed status or validity.
4493
	 *
4494
	 * @param string $subject Message subject
4495
	 * @param string $body Message body
4496
	 * @param User|null $from Optional sending user; if unspecified, default
4497
	 *   $wgPasswordSender will be used.
4498
	 * @param string $replyto Reply-To address
4499
	 * @return Status
4500
	 */
4501
	public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4502
		global $wgPasswordSender;
4503
4504
		if ( $from instanceof User ) {
4505
			$sender = MailAddress::newFromUser( $from );
4506
		} else {
4507
			$sender = new MailAddress( $wgPasswordSender,
4508
				wfMessage( 'emailsender' )->inContentLanguage()->text() );
4509
		}
4510
		$to = MailAddress::newFromUser( $this );
4511
4512
		return UserMailer::send( $to, $sender, $subject, $body, [
4513
			'replyTo' => $replyto,
4514
		] );
4515
	}
4516
4517
	/**
4518
	 * Generate, store, and return a new e-mail confirmation code.
4519
	 * A hash (unsalted, since it's used as a key) is stored.
4520
	 *
4521
	 * @note Call saveSettings() after calling this function to commit
4522
	 * this change to the database.
4523
	 *
4524
	 * @param string &$expiration Accepts the expiration time
4525
	 * @return string New token
4526
	 */
4527
	protected function confirmationToken( &$expiration ) {
4528
		global $wgUserEmailConfirmationTokenExpiry;
4529
		$now = time();
4530
		$expires = $now + $wgUserEmailConfirmationTokenExpiry;
4531
		$expiration = wfTimestamp( TS_MW, $expires );
4532
		$this->load();
4533
		$token = MWCryptRand::generateHex( 32 );
4534
		$hash = md5( $token );
4535
		$this->mEmailToken = $hash;
4536
		$this->mEmailTokenExpires = $expiration;
0 ignored issues
show
Documentation Bug introduced by
It seems like $expiration can also be of type false. However, the property $mEmailTokenExpires is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
4537
		return $token;
4538
	}
4539
4540
	/**
4541
	 * Return a URL the user can use to confirm their email address.
4542
	 * @param string $token Accepts the email confirmation token
4543
	 * @return string New token URL
4544
	 */
4545
	protected function confirmationTokenUrl( $token ) {
4546
		return $this->getTokenUrl( 'ConfirmEmail', $token );
4547
	}
4548
4549
	/**
4550
	 * Return a URL the user can use to invalidate their email address.
4551
	 * @param string $token Accepts the email confirmation token
4552
	 * @return string New token URL
4553
	 */
4554
	protected function invalidationTokenUrl( $token ) {
4555
		return $this->getTokenUrl( 'InvalidateEmail', $token );
4556
	}
4557
4558
	/**
4559
	 * Internal function to format the e-mail validation/invalidation URLs.
4560
	 * This uses a quickie hack to use the
4561
	 * hardcoded English names of the Special: pages, for ASCII safety.
4562
	 *
4563
	 * @note Since these URLs get dropped directly into emails, using the
4564
	 * short English names avoids insanely long URL-encoded links, which
4565
	 * also sometimes can get corrupted in some browsers/mailers
4566
	 * (bug 6957 with Gmail and Internet Explorer).
4567
	 *
4568
	 * @param string $page Special page
4569
	 * @param string $token Token
4570
	 * @return string Formatted URL
4571
	 */
4572
	protected function getTokenUrl( $page, $token ) {
4573
		// Hack to bypass localization of 'Special:'
4574
		$title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4575
		return $title->getCanonicalURL();
4576
	}
4577
4578
	/**
4579
	 * Mark the e-mail address confirmed.
4580
	 *
4581
	 * @note Call saveSettings() after calling this function to commit the change.
4582
	 *
4583
	 * @return bool
4584
	 */
4585
	public function confirmEmail() {
4586
		// Check if it's already confirmed, so we don't touch the database
4587
		// and fire the ConfirmEmailComplete hook on redundant confirmations.
4588
		if ( !$this->isEmailConfirmed() ) {
4589
			$this->setEmailAuthenticationTimestamp( wfTimestampNow() );
0 ignored issues
show
Security Bug introduced by
It seems like wfTimestampNow() can also be of type false; however, User::setEmailAuthenticationTimestamp() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
4590
			Hooks::run( 'ConfirmEmailComplete', [ $this ] );
4591
		}
4592
		return true;
4593
	}
4594
4595
	/**
4596
	 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4597
	 * address if it was already confirmed.
4598
	 *
4599
	 * @note Call saveSettings() after calling this function to commit the change.
4600
	 * @return bool Returns true
4601
	 */
4602
	public function invalidateEmail() {
4603
		$this->load();
4604
		$this->mEmailToken = null;
4605
		$this->mEmailTokenExpires = null;
4606
		$this->setEmailAuthenticationTimestamp( null );
4607
		$this->mEmail = '';
4608
		Hooks::run( 'InvalidateEmailComplete', [ $this ] );
4609
		return true;
4610
	}
4611
4612
	/**
4613
	 * Set the e-mail authentication timestamp.
4614
	 * @param string $timestamp TS_MW timestamp
4615
	 */
4616
	public function setEmailAuthenticationTimestamp( $timestamp ) {
4617
		$this->load();
4618
		$this->mEmailAuthenticated = $timestamp;
4619
		Hooks::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
4620
	}
4621
4622
	/**
4623
	 * Is this user allowed to send e-mails within limits of current
4624
	 * site configuration?
4625
	 * @return bool
4626
	 */
4627
	public function canSendEmail() {
4628
		global $wgEnableEmail, $wgEnableUserEmail;
4629
		if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4630
			return false;
4631
		}
4632
		$canSend = $this->isEmailConfirmed();
4633
		Hooks::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4634
		return $canSend;
4635
	}
4636
4637
	/**
4638
	 * Is this user allowed to receive e-mails within limits of current
4639
	 * site configuration?
4640
	 * @return bool
4641
	 */
4642
	public function canReceiveEmail() {
4643
		return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4644
	}
4645
4646
	/**
4647
	 * Is this user's e-mail address valid-looking and confirmed within
4648
	 * limits of the current site configuration?
4649
	 *
4650
	 * @note If $wgEmailAuthentication is on, this may require the user to have
4651
	 * confirmed their address by returning a code or using a password
4652
	 * sent to the address from the wiki.
4653
	 *
4654
	 * @return bool
4655
	 */
4656
	public function isEmailConfirmed() {
4657
		global $wgEmailAuthentication;
4658
		$this->load();
4659
		$confirmed = true;
4660
		if ( Hooks::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4661
			if ( $this->isAnon() ) {
4662
				return false;
4663
			}
4664
			if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression \Sanitizer::validateEmail($this->mEmail) of type null|boolean is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
4665
				return false;
4666
			}
4667
			if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4668
				return false;
4669
			}
4670
			return true;
4671
		} else {
4672
			return $confirmed;
4673
		}
4674
	}
4675
4676
	/**
4677
	 * Check whether there is an outstanding request for e-mail confirmation.
4678
	 * @return bool
4679
	 */
4680
	public function isEmailConfirmationPending() {
4681
		global $wgEmailAuthentication;
4682
		return $wgEmailAuthentication &&
4683
			!$this->isEmailConfirmed() &&
4684
			$this->mEmailToken &&
4685
			$this->mEmailTokenExpires > wfTimestamp();
4686
	}
4687
4688
	/**
4689
	 * Get the timestamp of account creation.
4690
	 *
4691
	 * @return string|bool|null Timestamp of account creation, false for
4692
	 *  non-existent/anonymous user accounts, or null if existing account
4693
	 *  but information is not in database.
4694
	 */
4695
	public function getRegistration() {
4696
		if ( $this->isAnon() ) {
4697
			return false;
4698
		}
4699
		$this->load();
4700
		return $this->mRegistration;
4701
	}
4702
4703
	/**
4704
	 * Get the timestamp of the first edit
4705
	 *
4706
	 * @return string|bool Timestamp of first edit, or false for
4707
	 *  non-existent/anonymous user accounts.
4708
	 */
4709
	public function getFirstEditTimestamp() {
4710
		if ( $this->getId() == 0 ) {
4711
			return false; // anons
4712
		}
4713
		$dbr = wfGetDB( DB_SLAVE );
4714
		$time = $dbr->selectField( 'revision', 'rev_timestamp',
4715
			[ 'rev_user' => $this->getId() ],
4716
			__METHOD__,
4717
			[ 'ORDER BY' => 'rev_timestamp ASC' ]
4718
		);
4719
		if ( !$time ) {
4720
			return false; // no edits
4721
		}
4722
		return wfTimestamp( TS_MW, $time );
4723
	}
4724
4725
	/**
4726
	 * Get the permissions associated with a given list of groups
4727
	 *
4728
	 * @param array $groups Array of Strings List of internal group names
4729
	 * @return array Array of Strings List of permission key names for given groups combined
4730
	 */
4731
	public static function getGroupPermissions( $groups ) {
4732
		global $wgGroupPermissions, $wgRevokePermissions;
4733
		$rights = [];
4734
		// grant every granted permission first
4735
		foreach ( $groups as $group ) {
4736
			if ( isset( $wgGroupPermissions[$group] ) ) {
4737
				$rights = array_merge( $rights,
4738
					// array_filter removes empty items
4739
					array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4740
			}
4741
		}
4742
		// now revoke the revoked permissions
4743
		foreach ( $groups as $group ) {
4744
			if ( isset( $wgRevokePermissions[$group] ) ) {
4745
				$rights = array_diff( $rights,
4746
					array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4747
			}
4748
		}
4749
		return array_unique( $rights );
4750
	}
4751
4752
	/**
4753
	 * Get all the groups who have a given permission
4754
	 *
4755
	 * @param string $role Role to check
4756
	 * @return array Array of Strings List of internal group names with the given permission
4757
	 */
4758
	public static function getGroupsWithPermission( $role ) {
4759
		global $wgGroupPermissions;
4760
		$allowedGroups = [];
4761
		foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4762
			if ( self::groupHasPermission( $group, $role ) ) {
4763
				$allowedGroups[] = $group;
4764
			}
4765
		}
4766
		return $allowedGroups;
4767
	}
4768
4769
	/**
4770
	 * Check, if the given group has the given permission
4771
	 *
4772
	 * If you're wanting to check whether all users have a permission, use
4773
	 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4774
	 * from anyone.
4775
	 *
4776
	 * @since 1.21
4777
	 * @param string $group Group to check
4778
	 * @param string $role Role to check
4779
	 * @return bool
4780
	 */
4781
	public static function groupHasPermission( $group, $role ) {
4782
		global $wgGroupPermissions, $wgRevokePermissions;
4783
		return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4784
			&& !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4785
	}
4786
4787
	/**
4788
	 * Check if all users may be assumed to have the given permission
4789
	 *
4790
	 * We generally assume so if the right is granted to '*' and isn't revoked
4791
	 * on any group. It doesn't attempt to take grants or other extension
4792
	 * limitations on rights into account in the general case, though, as that
4793
	 * would require it to always return false and defeat the purpose.
4794
	 * Specifically, session-based rights restrictions (such as OAuth or bot
4795
	 * passwords) are applied based on the current session.
4796
	 *
4797
	 * @since 1.22
4798
	 * @param string $right Right to check
4799
	 * @return bool
4800
	 */
4801
	public static function isEveryoneAllowed( $right ) {
4802
		global $wgGroupPermissions, $wgRevokePermissions;
4803
		static $cache = [];
4804
4805
		// Use the cached results, except in unit tests which rely on
4806
		// being able change the permission mid-request
4807
		if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4808
			return $cache[$right];
4809
		}
4810
4811
		if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4812
			$cache[$right] = false;
4813
			return false;
4814
		}
4815
4816
		// If it's revoked anywhere, then everyone doesn't have it
4817
		foreach ( $wgRevokePermissions as $rights ) {
4818
			if ( isset( $rights[$right] ) && $rights[$right] ) {
4819
				$cache[$right] = false;
4820
				return false;
4821
			}
4822
		}
4823
4824
		// Remove any rights that aren't allowed to the global-session user,
4825
		// unless there are no sessions for this endpoint.
4826
		if ( !defined( 'MW_NO_SESSION' ) ) {
4827
			$allowedRights = SessionManager::getGlobalSession()->getAllowedUserRights();
4828
			if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4829
				$cache[$right] = false;
4830
				return false;
4831
			}
4832
		}
4833
4834
		// Allow extensions to say false
4835
		if ( !Hooks::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4836
			$cache[$right] = false;
4837
			return false;
4838
		}
4839
4840
		$cache[$right] = true;
4841
		return true;
4842
	}
4843
4844
	/**
4845
	 * Get the localized descriptive name for a group, if it exists
4846
	 *
4847
	 * @param string $group Internal group name
4848
	 * @return string Localized descriptive group name
4849
	 */
4850
	public static function getGroupName( $group ) {
4851
		$msg = wfMessage( "group-$group" );
4852
		return $msg->isBlank() ? $group : $msg->text();
4853
	}
4854
4855
	/**
4856
	 * Get the localized descriptive name for a member of a group, if it exists
4857
	 *
4858
	 * @param string $group Internal group name
4859
	 * @param string $username Username for gender (since 1.19)
4860
	 * @return string Localized name for group member
4861
	 */
4862
	public static function getGroupMember( $group, $username = '#' ) {
4863
		$msg = wfMessage( "group-$group-member", $username );
4864
		return $msg->isBlank() ? $group : $msg->text();
4865
	}
4866
4867
	/**
4868
	 * Return the set of defined explicit groups.
4869
	 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4870
	 * are not included, as they are defined automatically, not in the database.
4871
	 * @return array Array of internal group names
4872
	 */
4873
	public static function getAllGroups() {
4874
		global $wgGroupPermissions, $wgRevokePermissions;
4875
		return array_diff(
4876
			array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4877
			self::getImplicitGroups()
4878
		);
4879
	}
4880
4881
	/**
4882
	 * Get a list of all available permissions.
4883
	 * @return string[] Array of permission names
4884
	 */
4885
	public static function getAllRights() {
4886
		if ( self::$mAllRights === false ) {
4887
			global $wgAvailableRights;
4888
			if ( count( $wgAvailableRights ) ) {
4889
				self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
0 ignored issues
show
Documentation Bug introduced by
It seems like array_unique(array_merge...s, $wgAvailableRights)) of type array is incompatible with the declared type boolean of property $mAllRights.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
4890
			} else {
4891
				self::$mAllRights = self::$mCoreRights;
0 ignored issues
show
Documentation Bug introduced by
It seems like self::$mCoreRights of type array is incompatible with the declared type boolean of property $mAllRights.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
4892
			}
4893
			Hooks::run( 'UserGetAllRights', [ &self::$mAllRights ] );
4894
		}
4895
		return self::$mAllRights;
4896
	}
4897
4898
	/**
4899
	 * Get a list of implicit groups
4900
	 * @return array Array of Strings Array of internal group names
4901
	 */
4902
	public static function getImplicitGroups() {
4903
		global $wgImplicitGroups;
4904
4905
		$groups = $wgImplicitGroups;
4906
		# Deprecated, use $wgImplicitGroups instead
4907
		Hooks::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4908
4909
		return $groups;
4910
	}
4911
4912
	/**
4913
	 * Get the title of a page describing a particular group
4914
	 *
4915
	 * @param string $group Internal group name
4916
	 * @return Title|bool Title of the page if it exists, false otherwise
4917
	 */
4918
	public static function getGroupPage( $group ) {
4919
		$msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4920
		if ( $msg->exists() ) {
4921
			$title = Title::newFromText( $msg->text() );
4922
			if ( is_object( $title ) ) {
4923
				return $title;
4924
			}
4925
		}
4926
		return false;
4927
	}
4928
4929
	/**
4930
	 * Create a link to the group in HTML, if available;
4931
	 * else return the group name.
4932
	 *
4933
	 * @param string $group Internal name of the group
4934
	 * @param string $text The text of the link
4935
	 * @return string HTML link to the group
4936
	 */
4937
	public static function makeGroupLinkHTML( $group, $text = '' ) {
4938
		if ( $text == '' ) {
4939
			$text = self::getGroupName( $group );
4940
		}
4941
		$title = self::getGroupPage( $group );
4942
		if ( $title ) {
4943
			return Linker::link( $title, htmlspecialchars( $text ) );
4944
		} else {
4945
			return htmlspecialchars( $text );
4946
		}
4947
	}
4948
4949
	/**
4950
	 * Create a link to the group in Wikitext, if available;
4951
	 * else return the group name.
4952
	 *
4953
	 * @param string $group Internal name of the group
4954
	 * @param string $text The text of the link
4955
	 * @return string Wikilink to the group
4956
	 */
4957
	public static function makeGroupLinkWiki( $group, $text = '' ) {
4958
		if ( $text == '' ) {
4959
			$text = self::getGroupName( $group );
4960
		}
4961
		$title = self::getGroupPage( $group );
4962
		if ( $title ) {
4963
			$page = $title->getFullText();
4964
			return "[[$page|$text]]";
4965
		} else {
4966
			return $text;
4967
		}
4968
	}
4969
4970
	/**
4971
	 * Returns an array of the groups that a particular group can add/remove.
4972
	 *
4973
	 * @param string $group The group to check for whether it can add/remove
4974
	 * @return array Array( 'add' => array( addablegroups ),
4975
	 *     'remove' => array( removablegroups ),
4976
	 *     'add-self' => array( addablegroups to self),
4977
	 *     'remove-self' => array( removable groups from self) )
4978
	 */
4979
	public static function changeableByGroup( $group ) {
4980
		global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4981
4982
		$groups = [
4983
			'add' => [],
4984
			'remove' => [],
4985
			'add-self' => [],
4986
			'remove-self' => []
4987
		];
4988
4989 View Code Duplication
		if ( empty( $wgAddGroups[$group] ) ) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
4990
			// Don't add anything to $groups
4991
		} elseif ( $wgAddGroups[$group] === true ) {
4992
			// You get everything
4993
			$groups['add'] = self::getAllGroups();
4994
		} elseif ( is_array( $wgAddGroups[$group] ) ) {
4995
			$groups['add'] = $wgAddGroups[$group];
4996
		}
4997
4998
		// Same thing for remove
4999 View Code Duplication
		if ( empty( $wgRemoveGroups[$group] ) ) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
5000
			// Do nothing
5001
		} elseif ( $wgRemoveGroups[$group] === true ) {
5002
			$groups['remove'] = self::getAllGroups();
5003
		} elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5004
			$groups['remove'] = $wgRemoveGroups[$group];
5005
		}
5006
5007
		// Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5008 View Code Duplication
		if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
5009
			foreach ( $wgGroupsAddToSelf as $key => $value ) {
5010
				if ( is_int( $key ) ) {
5011
					$wgGroupsAddToSelf['user'][] = $value;
5012
				}
5013
			}
5014
		}
5015
5016 View Code Duplication
		if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
5017
			foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5018
				if ( is_int( $key ) ) {
5019
					$wgGroupsRemoveFromSelf['user'][] = $value;
5020
				}
5021
			}
5022
		}
5023
5024
		// Now figure out what groups the user can add to him/herself
5025 View Code Duplication
		if ( empty( $wgGroupsAddToSelf[$group] ) ) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
5026
			// Do nothing
5027
		} elseif ( $wgGroupsAddToSelf[$group] === true ) {
5028
			// No idea WHY this would be used, but it's there
5029
			$groups['add-self'] = User::getAllGroups();
5030
		} elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5031
			$groups['add-self'] = $wgGroupsAddToSelf[$group];
5032
		}
5033
5034 View Code Duplication
		if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
5035
			// Do nothing
5036
		} elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5037
			$groups['remove-self'] = User::getAllGroups();
5038
		} elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5039
			$groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5040
		}
5041
5042
		return $groups;
5043
	}
5044
5045
	/**
5046
	 * Returns an array of groups that this user can add and remove
5047
	 * @return array Array( 'add' => array( addablegroups ),
5048
	 *  'remove' => array( removablegroups ),
5049
	 *  'add-self' => array( addablegroups to self),
5050
	 *  'remove-self' => array( removable groups from self) )
5051
	 */
5052
	public function changeableGroups() {
5053
		if ( $this->isAllowed( 'userrights' ) ) {
5054
			// This group gives the right to modify everything (reverse-
5055
			// compatibility with old "userrights lets you change
5056
			// everything")
5057
			// Using array_merge to make the groups reindexed
5058
			$all = array_merge( User::getAllGroups() );
5059
			return [
5060
				'add' => $all,
5061
				'remove' => $all,
5062
				'add-self' => [],
5063
				'remove-self' => []
5064
			];
5065
		}
5066
5067
		// Okay, it's not so simple, we will have to go through the arrays
5068
		$groups = [
5069
			'add' => [],
5070
			'remove' => [],
5071
			'add-self' => [],
5072
			'remove-self' => []
5073
		];
5074
		$addergroups = $this->getEffectiveGroups();
5075
5076
		foreach ( $addergroups as $addergroup ) {
5077
			$groups = array_merge_recursive(
5078
				$groups, $this->changeableByGroup( $addergroup )
5079
			);
5080
			$groups['add'] = array_unique( $groups['add'] );
5081
			$groups['remove'] = array_unique( $groups['remove'] );
5082
			$groups['add-self'] = array_unique( $groups['add-self'] );
5083
			$groups['remove-self'] = array_unique( $groups['remove-self'] );
5084
		}
5085
		return $groups;
5086
	}
5087
5088
	/**
5089
	 * Deferred version of incEditCountImmediate()
5090
	 */
5091
	public function incEditCount() {
5092
		wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle( function() {
5093
			$this->incEditCountImmediate();
5094
		} );
5095
	}
5096
5097
	/**
5098
	 * Increment the user's edit-count field.
5099
	 * Will have no effect for anonymous users.
5100
	 * @since 1.26
5101
	 */
5102
	public function incEditCountImmediate() {
5103
		if ( $this->isAnon() ) {
5104
			return;
5105
		}
5106
5107
		$dbw = wfGetDB( DB_MASTER );
5108
		// No rows will be "affected" if user_editcount is NULL
5109
		$dbw->update(
5110
			'user',
5111
			[ 'user_editcount=user_editcount+1' ],
5112
			[ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5113
			__METHOD__
5114
		);
5115
		// Lazy initialization check...
5116
		if ( $dbw->affectedRows() == 0 ) {
5117
			// Now here's a goddamn hack...
5118
			$dbr = wfGetDB( DB_SLAVE );
5119
			if ( $dbr !== $dbw ) {
5120
				// If we actually have a slave server, the count is
5121
				// at least one behind because the current transaction
5122
				// has not been committed and replicated.
5123
				$this->initEditCount( 1 );
5124
			} else {
5125
				// But if DB_SLAVE is selecting the master, then the
5126
				// count we just read includes the revision that was
5127
				// just added in the working transaction.
5128
				$this->initEditCount();
5129
			}
5130
		}
5131
		// Edit count in user cache too
5132
		$this->invalidateCache();
5133
	}
5134
5135
	/**
5136
	 * Initialize user_editcount from data out of the revision table
5137
	 *
5138
	 * @param int $add Edits to add to the count from the revision table
5139
	 * @return int Number of edits
5140
	 */
5141
	protected function initEditCount( $add = 0 ) {
5142
		// Pull from a slave to be less cruel to servers
5143
		// Accuracy isn't the point anyway here
5144
		$dbr = wfGetDB( DB_SLAVE );
5145
		$count = (int)$dbr->selectField(
5146
			'revision',
5147
			'COUNT(rev_user)',
5148
			[ 'rev_user' => $this->getId() ],
5149
			__METHOD__
5150
		);
5151
		$count = $count + $add;
5152
5153
		$dbw = wfGetDB( DB_MASTER );
5154
		$dbw->update(
5155
			'user',
5156
			[ 'user_editcount' => $count ],
5157
			[ 'user_id' => $this->getId() ],
5158
			__METHOD__
5159
		);
5160
5161
		return $count;
5162
	}
5163
5164
	/**
5165
	 * Get the description of a given right
5166
	 *
5167
	 * @param string $right Right to query
5168
	 * @return string Localized description of the right
5169
	 */
5170
	public static function getRightDescription( $right ) {
5171
		$key = "right-$right";
5172
		$msg = wfMessage( $key );
5173
		return $msg->isBlank() ? $right : $msg->text();
5174
	}
5175
5176
	/**
5177
	 * Make a new-style password hash
5178
	 *
5179
	 * @param string $password Plain-text password
5180
	 * @param bool|string $salt Optional salt, may be random or the user ID.
5181
	 *  If unspecified or false, will generate one automatically
5182
	 * @return string Password hash
5183
	 * @deprecated since 1.24, use Password class
5184
	 */
5185
	public static function crypt( $password, $salt = false ) {
5186
		wfDeprecated( __METHOD__, '1.24' );
5187
		$passwordFactory = new PasswordFactory();
5188
		$passwordFactory->init( RequestContext::getMain()->getConfig() );
5189
		$hash = $passwordFactory->newFromPlaintext( $password );
5190
		return $hash->toString();
5191
	}
5192
5193
	/**
5194
	 * Compare a password hash with a plain-text password. Requires the user
5195
	 * ID if there's a chance that the hash is an old-style hash.
5196
	 *
5197
	 * @param string $hash Password hash
5198
	 * @param string $password Plain-text password to compare
5199
	 * @param string|bool $userId User ID for old-style password salt
5200
	 *
5201
	 * @return bool
5202
	 * @deprecated since 1.24, use Password class
5203
	 */
5204
	public static function comparePasswords( $hash, $password, $userId = false ) {
5205
		wfDeprecated( __METHOD__, '1.24' );
5206
5207
		// Check for *really* old password hashes that don't even have a type
5208
		// The old hash format was just an md5 hex hash, with no type information
5209
		if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5210
			global $wgPasswordSalt;
5211
			if ( $wgPasswordSalt ) {
5212
				$password = ":B:{$userId}:{$hash}";
5213
			} else {
5214
				$password = ":A:{$hash}";
5215
			}
5216
		}
5217
5218
		$passwordFactory = new PasswordFactory();
5219
		$passwordFactory->init( RequestContext::getMain()->getConfig() );
5220
		$hash = $passwordFactory->newFromCiphertext( $hash );
5221
		return $hash->equals( $password );
5222
	}
5223
5224
	/**
5225
	 * Add a newuser log entry for this user.
5226
	 * Before 1.19 the return value was always true.
5227
	 *
5228
	 * @deprecated since 1.27, AuthManager handles logging
5229
	 * @param string|bool $action Account creation type.
5230
	 *   - String, one of the following values:
5231
	 *     - 'create' for an anonymous user creating an account for himself.
5232
	 *       This will force the action's performer to be the created user itself,
5233
	 *       no matter the value of $wgUser
5234
	 *     - 'create2' for a logged in user creating an account for someone else
5235
	 *     - 'byemail' when the created user will receive its password by e-mail
5236
	 *     - 'autocreate' when the user is automatically created (such as by CentralAuth).
5237
	 *   - Boolean means whether the account was created by e-mail (deprecated):
5238
	 *     - true will be converted to 'byemail'
5239
	 *     - false will be converted to 'create' if this object is the same as
5240
	 *       $wgUser and to 'create2' otherwise
5241
	 * @param string $reason User supplied reason
5242
	 * @return int|bool True if not $wgNewUserLog or not $wgDisableAuthManager;
5243
	 *   otherwise ID of log item or 0 on failure
5244
	 */
5245
	public function addNewUserLogEntry( $action = false, $reason = '' ) {
5246
		global $wgUser, $wgNewUserLog, $wgDisableAuthManager;
5247
		if ( !$wgDisableAuthManager || empty( $wgNewUserLog ) ) {
5248
			return true; // disabled
5249
		}
5250
5251
		if ( $action === true ) {
5252
			$action = 'byemail';
5253
		} elseif ( $action === false ) {
5254
			if ( $this->equals( $wgUser ) ) {
5255
				$action = 'create';
5256
			} else {
5257
				$action = 'create2';
5258
			}
5259
		}
5260
5261
		if ( $action === 'create' || $action === 'autocreate' ) {
5262
			$performer = $this;
5263
		} else {
5264
			$performer = $wgUser;
5265
		}
5266
5267
		$logEntry = new ManualLogEntry( 'newusers', $action );
0 ignored issues
show
Bug introduced by
It seems like $action defined by parameter $action on line 5245 can also be of type boolean; however, ManualLogEntry::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
5268
		$logEntry->setPerformer( $performer );
5269
		$logEntry->setTarget( $this->getUserPage() );
5270
		$logEntry->setComment( $reason );
5271
		$logEntry->setParameters( [
5272
			'4::userid' => $this->getId(),
5273
		] );
5274
		$logid = $logEntry->insert();
5275
5276
		if ( $action !== 'autocreate' ) {
5277
			$logEntry->publish( $logid );
5278
		}
5279
5280
		return (int)$logid;
5281
	}
5282
5283
	/**
5284
	 * Add an autocreate newuser log entry for this user
5285
	 * Used by things like CentralAuth and perhaps other authplugins.
5286
	 * Consider calling addNewUserLogEntry() directly instead.
5287
	 *
5288
	 * @deprecated since 1.27, AuthManager handles logging
5289
	 * @return bool
5290
	 */
5291
	public function addNewUserLogEntryAutoCreate() {
5292
		$this->addNewUserLogEntry( 'autocreate' );
0 ignored issues
show
Deprecated Code introduced by
The method User::addNewUserLogEntry() has been deprecated with message: since 1.27, AuthManager handles logging

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
5293
5294
		return true;
5295
	}
5296
5297
	/**
5298
	 * Load the user options either from cache, the database or an array
5299
	 *
5300
	 * @param array $data Rows for the current user out of the user_properties table
5301
	 */
5302
	protected function loadOptions( $data = null ) {
5303
		global $wgContLang;
5304
5305
		$this->load();
5306
5307
		if ( $this->mOptionsLoaded ) {
5308
			return;
5309
		}
5310
5311
		$this->mOptions = self::getDefaultOptions();
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getDefaultOptions() can be null. However, the property $mOptions is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property.

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
5312
5313
		if ( !$this->getId() ) {
5314
			// For unlogged-in users, load language/variant options from request.
5315
			// There's no need to do it for logged-in users: they can set preferences,
5316
			// and handling of page content is done by $pageLang->getPreferredVariant() and such,
5317
			// so don't override user's choice (especially when the user chooses site default).
5318
			$variant = $wgContLang->getDefaultVariant();
5319
			$this->mOptions['variant'] = $variant;
5320
			$this->mOptions['language'] = $variant;
5321
			$this->mOptionsLoaded = true;
5322
			return;
5323
		}
5324
5325
		// Maybe load from the object
5326
		if ( !is_null( $this->mOptionOverrides ) ) {
5327
			wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5328
			foreach ( $this->mOptionOverrides as $key => $value ) {
5329
				$this->mOptions[$key] = $value;
5330
			}
5331
		} else {
5332
			if ( !is_array( $data ) ) {
5333
				wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5334
				// Load from database
5335
				$dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5336
					? wfGetDB( DB_MASTER )
5337
					: wfGetDB( DB_SLAVE );
5338
5339
				$res = $dbr->select(
5340
					'user_properties',
5341
					[ 'up_property', 'up_value' ],
5342
					[ 'up_user' => $this->getId() ],
5343
					__METHOD__
5344
				);
5345
5346
				$this->mOptionOverrides = [];
5347
				$data = [];
5348
				foreach ( $res as $row ) {
0 ignored issues
show
Bug introduced by
The expression $res of type boolean|object<ResultWrapper> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
5349
					$data[$row->up_property] = $row->up_value;
5350
				}
5351
			}
5352
			foreach ( $data as $property => $value ) {
5353
				$this->mOptionOverrides[$property] = $value;
5354
				$this->mOptions[$property] = $value;
5355
			}
5356
		}
5357
5358
		$this->mOptionsLoaded = true;
5359
5360
		Hooks::run( 'UserLoadOptions', [ $this, &$this->mOptions ] );
5361
	}
5362
5363
	/**
5364
	 * Saves the non-default options for this user, as previously set e.g. via
5365
	 * setOption(), in the database's "user_properties" (preferences) table.
5366
	 * Usually used via saveSettings().
5367
	 */
5368
	protected function saveOptions() {
5369
		$this->loadOptions();
5370
5371
		// Not using getOptions(), to keep hidden preferences in database
5372
		$saveOptions = $this->mOptions;
5373
5374
		// Allow hooks to abort, for instance to save to a global profile.
5375
		// Reset options to default state before saving.
5376
		if ( !Hooks::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5377
			return;
5378
		}
5379
5380
		$userId = $this->getId();
5381
5382
		$insert_rows = []; // all the new preference rows
5383
		foreach ( $saveOptions as $key => $value ) {
5384
			// Don't bother storing default values
5385
			$defaultOption = self::getDefaultOption( $key );
5386
			if ( ( $defaultOption === null && $value !== false && $value !== null )
5387
				|| $value != $defaultOption
5388
			) {
5389
				$insert_rows[] = [
5390
					'up_user' => $userId,
5391
					'up_property' => $key,
5392
					'up_value' => $value,
5393
				];
5394
			}
5395
		}
5396
5397
		$dbw = wfGetDB( DB_MASTER );
5398
5399
		$res = $dbw->select( 'user_properties',
5400
			[ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__ );
5401
5402
		// Find prior rows that need to be removed or updated. These rows will
5403
		// all be deleted (the later so that INSERT IGNORE applies the new values).
5404
		$keysDelete = [];
5405
		foreach ( $res as $row ) {
0 ignored issues
show
Bug introduced by
The expression $res of type boolean|object<ResultWrapper> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
5406
			if ( !isset( $saveOptions[$row->up_property] )
5407
				|| strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5408
			) {
5409
				$keysDelete[] = $row->up_property;
5410
			}
5411
		}
5412
5413
		if ( count( $keysDelete ) ) {
5414
			// Do the DELETE by PRIMARY KEY for prior rows.
5415
			// In the past a very large portion of calls to this function are for setting
5416
			// 'rememberpassword' for new accounts (a preference that has since been removed).
5417
			// Doing a blanket per-user DELETE for new accounts with no rows in the table
5418
			// caused gap locks on [max user ID,+infinity) which caused high contention since
5419
			// updates would pile up on each other as they are for higher (newer) user IDs.
5420
			// It might not be necessary these days, but it shouldn't hurt either.
5421
			$dbw->delete( 'user_properties',
5422
				[ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__ );
5423
		}
5424
		// Insert the new preference rows
5425
		$dbw->insert( 'user_properties', $insert_rows, __METHOD__, [ 'IGNORE' ] );
5426
	}
5427
5428
	/**
5429
	 * Lazily instantiate and return a factory object for making passwords
5430
	 *
5431
	 * @deprecated since 1.27, create a PasswordFactory directly instead
5432
	 * @return PasswordFactory
5433
	 */
5434
	public static function getPasswordFactory() {
5435
		wfDeprecated( __METHOD__, '1.27' );
5436
		$ret = new PasswordFactory();
5437
		$ret->init( RequestContext::getMain()->getConfig() );
5438
		return $ret;
5439
	}
5440
5441
	/**
5442
	 * Provide an array of HTML5 attributes to put on an input element
5443
	 * intended for the user to enter a new password.  This may include
5444
	 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5445
	 *
5446
	 * Do *not* use this when asking the user to enter his current password!
5447
	 * Regardless of configuration, users may have invalid passwords for whatever
5448
	 * reason (e.g., they were set before requirements were tightened up).
5449
	 * Only use it when asking for a new password, like on account creation or
5450
	 * ResetPass.
5451
	 *
5452
	 * Obviously, you still need to do server-side checking.
5453
	 *
5454
	 * NOTE: A combination of bugs in various browsers means that this function
5455
	 * actually just returns array() unconditionally at the moment.  May as
5456
	 * well keep it around for when the browser bugs get fixed, though.
5457
	 *
5458
	 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5459
	 *
5460
	 * @deprecated since 1.27
5461
	 * @return array Array of HTML attributes suitable for feeding to
5462
	 *   Html::element(), directly or indirectly.  (Don't feed to Xml::*()!
5463
	 *   That will get confused by the boolean attribute syntax used.)
5464
	 */
5465
	public static function passwordChangeInputAttribs() {
5466
		global $wgMinimalPasswordLength;
5467
5468
		if ( $wgMinimalPasswordLength == 0 ) {
5469
			return [];
5470
		}
5471
5472
		# Note that the pattern requirement will always be satisfied if the
5473
		# input is empty, so we need required in all cases.
5474
5475
		# @todo FIXME: Bug 23769: This needs to not claim the password is required
5476
		# if e-mail confirmation is being used.  Since HTML5 input validation
5477
		# is b0rked anyway in some browsers, just return nothing.  When it's
5478
		# re-enabled, fix this code to not output required for e-mail
5479
		# registration.
5480
		# $ret = array( 'required' );
5481
		$ret = [];
5482
5483
		# We can't actually do this right now, because Opera 9.6 will print out
5484
		# the entered password visibly in its error message!  When other
5485
		# browsers add support for this attribute, or Opera fixes its support,
5486
		# we can add support with a version check to avoid doing this on Opera
5487
		# versions where it will be a problem.  Reported to Opera as
5488
		# DSK-262266, but they don't have a public bug tracker for us to follow.
5489
		/*
5490
		if ( $wgMinimalPasswordLength > 1 ) {
5491
			$ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5492
			$ret['title'] = wfMessage( 'passwordtooshort' )
5493
				->numParams( $wgMinimalPasswordLength )->text();
5494
		}
5495
		*/
5496
5497
		return $ret;
5498
	}
5499
5500
	/**
5501
	 * Return the list of user fields that should be selected to create
5502
	 * a new user object.
5503
	 * @return array
5504
	 */
5505
	public static function selectFields() {
5506
		return [
5507
			'user_id',
5508
			'user_name',
5509
			'user_real_name',
5510
			'user_email',
5511
			'user_touched',
5512
			'user_token',
5513
			'user_email_authenticated',
5514
			'user_email_token',
5515
			'user_email_token_expires',
5516
			'user_registration',
5517
			'user_editcount',
5518
		];
5519
	}
5520
5521
	/**
5522
	 * Factory function for fatal permission-denied errors
5523
	 *
5524
	 * @since 1.22
5525
	 * @param string $permission User right required
5526
	 * @return Status
5527
	 */
5528
	static function newFatalPermissionDeniedStatus( $permission ) {
5529
		global $wgLang;
5530
5531
		$groups = array_map(
5532
			[ 'User', 'makeGroupLinkWiki' ],
5533
			User::getGroupsWithPermission( $permission )
5534
		);
5535
5536
		if ( $groups ) {
5537
			return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5538
		} else {
5539
			return Status::newFatal( 'badaccess-group0' );
5540
		}
5541
	}
5542
5543
	/**
5544
	 * Get a new instance of this user that was loaded from the master via a locking read
5545
	 *
5546
	 * Use this instead of the main context User when updating that user. This avoids races
5547
	 * where that user was loaded from a slave or even the master but without proper locks.
5548
	 *
5549
	 * @return User|null Returns null if the user was not found in the DB
5550
	 * @since 1.27
5551
	 */
5552
	public function getInstanceForUpdate() {
5553
		if ( !$this->getId() ) {
5554
			return null; // anon
5555
		}
5556
5557
		$user = self::newFromId( $this->getId() );
5558
		if ( !$user->loadFromId( self::READ_EXCLUSIVE ) ) {
5559
			return null;
5560
		}
5561
5562
		return $user;
5563
	}
5564
5565
	/**
5566
	 * Checks if two user objects point to the same user.
5567
	 *
5568
	 * @since 1.25
5569
	 * @param User $user
5570
	 * @return bool
5571
	 */
5572
	public function equals( User $user ) {
5573
		return $this->getName() === $user->getName();
5574
	}
5575
}
5576