Completed
Branch master (d7c4e6)
by
unknown
29:20
created

User::getRights()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 35
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

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

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
5064
5065
		return true;
5066
	}
5067
5068
	/**
5069
	 * Load the user options either from cache, the database or an array
5070
	 *
5071
	 * @param array $data Rows for the current user out of the user_properties table
5072
	 */
5073
	protected function loadOptions( $data = null ) {
5074
		global $wgContLang;
5075
5076
		$this->load();
5077
5078
		if ( $this->mOptionsLoaded ) {
5079
			return;
5080
		}
5081
5082
		$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...
5083
5084
		if ( !$this->getId() ) {
5085
			// For unlogged-in users, load language/variant options from request.
5086
			// There's no need to do it for logged-in users: they can set preferences,
5087
			// and handling of page content is done by $pageLang->getPreferredVariant() and such,
5088
			// so don't override user's choice (especially when the user chooses site default).
5089
			$variant = $wgContLang->getDefaultVariant();
5090
			$this->mOptions['variant'] = $variant;
5091
			$this->mOptions['language'] = $variant;
5092
			$this->mOptionsLoaded = true;
5093
			return;
5094
		}
5095
5096
		// Maybe load from the object
5097
		if ( !is_null( $this->mOptionOverrides ) ) {
5098
			wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5099
			foreach ( $this->mOptionOverrides as $key => $value ) {
5100
				$this->mOptions[$key] = $value;
5101
			}
5102
		} else {
5103
			if ( !is_array( $data ) ) {
5104
				wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5105
				// Load from database
5106
				$dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5107
					? wfGetDB( DB_MASTER )
5108
					: wfGetDB( DB_SLAVE );
5109
5110
				$res = $dbr->select(
5111
					'user_properties',
5112
					[ 'up_property', 'up_value' ],
5113
					[ 'up_user' => $this->getId() ],
5114
					__METHOD__
5115
				);
5116
5117
				$this->mOptionOverrides = [];
5118
				$data = [];
5119
				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...
5120
					$data[$row->up_property] = $row->up_value;
5121
				}
5122
			}
5123
			foreach ( $data as $property => $value ) {
5124
				$this->mOptionOverrides[$property] = $value;
5125
				$this->mOptions[$property] = $value;
5126
			}
5127
		}
5128
5129
		$this->mOptionsLoaded = true;
5130
5131
		Hooks::run( 'UserLoadOptions', [ $this, &$this->mOptions ] );
5132
	}
5133
5134
	/**
5135
	 * Saves the non-default options for this user, as previously set e.g. via
5136
	 * setOption(), in the database's "user_properties" (preferences) table.
5137
	 * Usually used via saveSettings().
5138
	 */
5139
	protected function saveOptions() {
5140
		$this->loadOptions();
5141
5142
		// Not using getOptions(), to keep hidden preferences in database
5143
		$saveOptions = $this->mOptions;
5144
5145
		// Allow hooks to abort, for instance to save to a global profile.
5146
		// Reset options to default state before saving.
5147
		if ( !Hooks::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5148
			return;
5149
		}
5150
5151
		$userId = $this->getId();
5152
5153
		$insert_rows = []; // all the new preference rows
5154
		foreach ( $saveOptions as $key => $value ) {
5155
			// Don't bother storing default values
5156
			$defaultOption = self::getDefaultOption( $key );
5157
			if ( ( $defaultOption === null && $value !== false && $value !== null )
5158
				|| $value != $defaultOption
5159
			) {
5160
				$insert_rows[] = [
5161
					'up_user' => $userId,
5162
					'up_property' => $key,
5163
					'up_value' => $value,
5164
				];
5165
			}
5166
		}
5167
5168
		$dbw = wfGetDB( DB_MASTER );
5169
5170
		$res = $dbw->select( 'user_properties',
5171
			[ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__ );
5172
5173
		// Find prior rows that need to be removed or updated. These rows will
5174
		// all be deleted (the later so that INSERT IGNORE applies the new values).
5175
		$keysDelete = [];
5176
		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...
5177
			if ( !isset( $saveOptions[$row->up_property] )
5178
				|| strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5179
			) {
5180
				$keysDelete[] = $row->up_property;
5181
			}
5182
		}
5183
5184
		if ( count( $keysDelete ) ) {
5185
			// Do the DELETE by PRIMARY KEY for prior rows.
5186
			// In the past a very large portion of calls to this function are for setting
5187
			// 'rememberpassword' for new accounts (a preference that has since been removed).
5188
			// Doing a blanket per-user DELETE for new accounts with no rows in the table
5189
			// caused gap locks on [max user ID,+infinity) which caused high contention since
5190
			// updates would pile up on each other as they are for higher (newer) user IDs.
5191
			// It might not be necessary these days, but it shouldn't hurt either.
5192
			$dbw->delete( 'user_properties',
5193
				[ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__ );
5194
		}
5195
		// Insert the new preference rows
5196
		$dbw->insert( 'user_properties', $insert_rows, __METHOD__, [ 'IGNORE' ] );
5197
	}
5198
5199
	/**
5200
	 * Lazily instantiate and return a factory object for making passwords
5201
	 *
5202
	 * @deprecated since 1.27, create a PasswordFactory directly instead
5203
	 * @return PasswordFactory
5204
	 */
5205
	public static function getPasswordFactory() {
5206
		wfDeprecated( __METHOD__, '1.27' );
5207
		$ret = new PasswordFactory();
5208
		$ret->init( RequestContext::getMain()->getConfig() );
5209
		return $ret;
5210
	}
5211
5212
	/**
5213
	 * Provide an array of HTML5 attributes to put on an input element
5214
	 * intended for the user to enter a new password.  This may include
5215
	 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5216
	 *
5217
	 * Do *not* use this when asking the user to enter his current password!
5218
	 * Regardless of configuration, users may have invalid passwords for whatever
5219
	 * reason (e.g., they were set before requirements were tightened up).
5220
	 * Only use it when asking for a new password, like on account creation or
5221
	 * ResetPass.
5222
	 *
5223
	 * Obviously, you still need to do server-side checking.
5224
	 *
5225
	 * NOTE: A combination of bugs in various browsers means that this function
5226
	 * actually just returns array() unconditionally at the moment.  May as
5227
	 * well keep it around for when the browser bugs get fixed, though.
5228
	 *
5229
	 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5230
	 *
5231
	 * @deprecated since 1.27
5232
	 * @return array Array of HTML attributes suitable for feeding to
5233
	 *   Html::element(), directly or indirectly.  (Don't feed to Xml::*()!
5234
	 *   That will get confused by the boolean attribute syntax used.)
5235
	 */
5236
	public static function passwordChangeInputAttribs() {
5237
		global $wgMinimalPasswordLength;
5238
5239
		if ( $wgMinimalPasswordLength == 0 ) {
5240
			return [];
5241
		}
5242
5243
		# Note that the pattern requirement will always be satisfied if the
5244
		# input is empty, so we need required in all cases.
5245
5246
		# @todo FIXME: Bug 23769: This needs to not claim the password is required
5247
		# if e-mail confirmation is being used.  Since HTML5 input validation
5248
		# is b0rked anyway in some browsers, just return nothing.  When it's
5249
		# re-enabled, fix this code to not output required for e-mail
5250
		# registration.
5251
		# $ret = array( 'required' );
5252
		$ret = [];
5253
5254
		# We can't actually do this right now, because Opera 9.6 will print out
5255
		# the entered password visibly in its error message!  When other
5256
		# browsers add support for this attribute, or Opera fixes its support,
5257
		# we can add support with a version check to avoid doing this on Opera
5258
		# versions where it will be a problem.  Reported to Opera as
5259
		# DSK-262266, but they don't have a public bug tracker for us to follow.
5260
		/*
5261
		if ( $wgMinimalPasswordLength > 1 ) {
5262
			$ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5263
			$ret['title'] = wfMessage( 'passwordtooshort' )
5264
				->numParams( $wgMinimalPasswordLength )->text();
5265
		}
5266
		*/
5267
5268
		return $ret;
5269
	}
5270
5271
	/**
5272
	 * Return the list of user fields that should be selected to create
5273
	 * a new user object.
5274
	 * @return array
5275
	 */
5276
	public static function selectFields() {
5277
		return [
5278
			'user_id',
5279
			'user_name',
5280
			'user_real_name',
5281
			'user_email',
5282
			'user_touched',
5283
			'user_token',
5284
			'user_email_authenticated',
5285
			'user_email_token',
5286
			'user_email_token_expires',
5287
			'user_registration',
5288
			'user_editcount',
5289
		];
5290
	}
5291
5292
	/**
5293
	 * Factory function for fatal permission-denied errors
5294
	 *
5295
	 * @since 1.22
5296
	 * @param string $permission User right required
5297
	 * @return Status
5298
	 */
5299
	static function newFatalPermissionDeniedStatus( $permission ) {
5300
		global $wgLang;
5301
5302
		$groups = array_map(
5303
			[ 'User', 'makeGroupLinkWiki' ],
5304
			User::getGroupsWithPermission( $permission )
5305
		);
5306
5307
		if ( $groups ) {
5308
			return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5309
		} else {
5310
			return Status::newFatal( 'badaccess-group0' );
5311
		}
5312
	}
5313
5314
	/**
5315
	 * Get a new instance of this user that was loaded from the master via a locking read
5316
	 *
5317
	 * Use this instead of the main context User when updating that user. This avoids races
5318
	 * where that user was loaded from a slave or even the master but without proper locks.
5319
	 *
5320
	 * @return User|null Returns null if the user was not found in the DB
5321
	 * @since 1.27
5322
	 */
5323
	public function getInstanceForUpdate() {
5324
		if ( !$this->getId() ) {
5325
			return null; // anon
5326
		}
5327
5328
		$user = self::newFromId( $this->getId() );
5329
		if ( !$user->loadFromId( self::READ_EXCLUSIVE ) ) {
5330
			return null;
5331
		}
5332
5333
		return $user;
5334
	}
5335
5336
	/**
5337
	 * Checks if two user objects point to the same user.
5338
	 *
5339
	 * @since 1.25
5340
	 * @param User $user
5341
	 * @return bool
5342
	 */
5343
	public function equals( User $user ) {
5344
		return $this->getName() === $user->getName();
5345
	}
5346
}
5347