aboutsummaryrefslogtreecommitdiffstats
path: root/resources/src/mediawiki.special.block/stores/block.js
blob: 15324052a89f1d2b35f36869882aee67a1daae85 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
const { defineStore } = require( 'pinia' );
const { computed, ComputedRef, ref, Ref, watch } = require( 'vue' );
const api = new mw.Api();
const util = require( '../util.js' );

/**
 * Pinia store for the SpecialBlock application.
 */
module.exports = exports = defineStore( 'block', () => {
	/**
	 * Whether the multiblocks feature is enabled with $wgEnableMultiBlocks.
	 *
	 * @type {boolean}
	 */
	const enableMultiblocks = mw.config.get( 'blockEnableMultiblocks' ) || false;

	// ** State properties (refs) **

	// Form fields.

	/**
	 * The target user to block. Beyond the initial value,
	 * this is set only by the UserLookup component.
	 *
	 * @type {Ref<string>}
	 */
	const targetUser = ref( mw.config.get( 'blockTargetUser' ) || '' );
	/**
	 * The block ID of the block to modify.
	 *
	 * @type {Ref<number|null>}
	 */
	const blockId = ref( mw.config.get( 'blockId' ) || null );
	/**
	 * The block type, either `sitewide` or `partial`. This is set by the BlockTypeField component.
	 *
	 * @type {Ref<string>}
	 */
	const type = ref( mw.config.get( 'blockTypePreset' ) || 'sitewide' );
	/**
	 * The pages to restrict the partial block to.
	 *
	 * @type {Ref<string[]>}
	 */
	const pages = ref( ( mw.config.get( 'blockPageRestrictions' ) || '' )
		.split( '\n' )
		.filter( Boolean )
	);
	/**
	 * The namespaces to restrict the partial block to.
	 *
	 * @type {Ref<number[]>}
	 */
	const namespaces = ref( ( mw.config.get( 'blockNamespaceRestrictions' ) || '' )
		.split( '\n' )
		.filter( Boolean )
		.map( Number )
	);
	/**
	 * Actions to apply the partial block to,
	 * i.e. `ipb-action-create`, `ipb-action-move`, `ipb-action-upload`.
	 *
	 * @type {Ref<string[]>}
	 */
	const partialOptions = ref( [] );
	/**
	 * The expiry of the block.
	 *
	 * @type {Ref<string>}
	 */
	const expiry = ref(
		// From URL, ?wpExpiry=...
		mw.config.get( 'blockExpiryPreset' ) ||
		// From [[MediaWiki:ipb-default-expiry]] or [[MediaWiki:ipb-default-expiry-ip]].
		mw.config.get( 'blockExpiryDefault' ) ||
		''
	);
	/**
	 * The block summary, as selected from via the dropdown in the ReasonField component.
	 * These options are ultimately defined by [[MediaWiki:Ipbreason-dropdown]].
	 *
	 * @type {Ref<string>}
	 * @todo Combine with `reasonOther` here within the store.
	 */
	const reason = ref( 'other' );
	/**
	 * The free-form text for the block summary.
	 *
	 * @type {Ref<string>}
	 * @todo Combine with `reason` here within the store.
	 */
	const reasonOther = ref( mw.config.get( 'blockReasonOtherPreset' ) || '' );
	const details = mw.config.get( 'blockDetailsPreset' ) || [];
	/**
	 * Whether to block an IP or IP range from creating accounts.
	 *
	 * @type {Ref<boolean>}
	 */
	const createAccount = ref( details.includes( 'wpCreateAccount' ) );
	/**
	 * Whether to disable the target's ability to send email via Special:EmailUser.
	 *
	 * @type {Ref<boolean>}
	 */
	const disableEmail = ref( details.includes( 'wpDisableEmail' ) );
	/**
	 * Whether to disable the target's ability to edit their own user talk page.
	 *
	 * @type {Ref<boolean>}
	 */
	const disableUTEdit = ref( details.includes( 'wpDisableUTEdit' ) );
	const additionalDetails = mw.config.get( 'blockAdditionalDetailsPreset' ) || [];
	/**
	 * Whether to autoblock IP addresses used by the target.
	 *
	 * @type {Ref<boolean>}
	 * @see https://www.mediawiki.org/wiki/Autoblock
	 */
	const autoBlock = ref( additionalDetails.includes( 'wpAutoBlock' ) );
	/**
	 * Whether to impose a "suppressed" block, hiding the target's username
	 * from block log, the active block list, and the user list.
	 *
	 * @type {Ref<boolean>}
	 */
	const hideUser = ref( additionalDetails.includes( 'wpHideUser' ) );
	/**
	 * Whether to watch the target's user page and talk page.
	 *
	 * @type {Ref<boolean>}
	 */
	const watchUser = ref( additionalDetails.includes( 'wpWatch' ) );
	/**
	 * Whether to apply a hard block, blocking accounts using the same IP address.
	 *
	 * @type {Ref<boolean>}
	 */
	const hardBlock = ref( additionalDetails.includes( 'wpHardBlock' ) );
	/*
	 * The removal reason, used in the remove-block confirmation dialog.
	 * Note that the target and watchuser values in that form are shared with the main form.
	 *
	 * @type {Ref<string>}
	 */
	const removalReason = ref( '' );

	// Other refs that don't have corresponding form fields.

	/**
	 * Errors pertaining the form as a whole, shown at the top.
	 *
	 * @type {Ref<string[]>}
	 */
	const formErrors = ref( mw.config.get( 'blockPreErrors' ) || [] );
	/**
	 * Whether the form has been submitted. This is watched by UserLookup
	 * and ExpiryField to trigger validation on form submission.
	 *
	 * @type {Ref<boolean>}
	 */
	const formSubmitted = ref( false );
	/**
	 * Whether the form is visible. This is set by the SpecialBlock component,
	 * and unset by a watcher when the target user changes.
	 *
	 * @type {Ref<boolean>}
	 */
	const formVisible = ref( false );
	/**
	 * Whether the block was added successfully.
	 *
	 * @type {Ref<boolean>}
	 */
	const blockAdded = ref( false );
	/**
	 * Whether the block was removed successfully.
	 *
	 * @type {Ref<boolean>}
	 */
	const blockRemoved = ref( false );
	/**
	 * Whether the target user is already blocked. This is set
	 * after fetching block log data from the API.
	 *
	 * @type {Ref<boolean>}
	 */
	const alreadyBlocked = ref( mw.config.get( 'blockAlreadyBlocked' ) || false );
	/**
	 * Keep track of all UI-blocking API requests that are currently in flight.
	 *
	 * @type {Ref<Set<Promise|jQuery.Promise>>}
	 */
	const promises = ref( new Set() );
	/**
	 * Confirmation dialog message. When not null, the confirmation dialog will be
	 * shown on submission. This is set automatically by a watcher in the store.
	 *
	 * @type {Ref<string>}
	 */
	const confirmationMessage = ref( '' );
	/**
	 * Whether the target user exists. This is set by the UserLookup component.
	 *
	 * @type {Ref<boolean>}
	 */
	const targetExists = ref( !!mw.config.get( 'blockTargetExists' ) );

	// ** Getters (computed properties) **

	/**
	 * Whether the form is disabled due to an in-flight API request.
	 *
	 * @type {ComputedRef<boolean>}
	 */
	const formDisabled = computed( () => !!promises.value.size );
	/**
	 * Controls visibility of the 'Hide username' checkbox. True when the user has the
	 * hideuser right (this is passed from PHP), and the block is sitewide and infinite.
	 *
	 * @type {ComputedRef<boolean>}
	 */
	const hideUserVisible = computed( () => {
		const typeVal = type.value;
		return mw.config.get( 'blockHideUser' ) &&
			typeVal === 'sitewide' &&
			mw.util.isInfinity( expiry.value );
	} );
	/**
	 * Whether the 'Editing own talk page' checkbox is visible.
	 */
	const disableUTEditVisible = computed( () => {
		const isVisibleByConfig = mw.config.get( 'blockDisableUTEditVisible' ) || false;
		const isPartial = type.value === 'partial';
		const blocksUT = namespaces.value.includes( mw.config.get( 'wgNamespaceIds' ).user_talk );
		return isVisibleByConfig && ( !isPartial || ( isPartial && blocksUT ) );
	} );
	/**
	 * Convenience computed prop indicating if confirmation is needed on submission.
	 *
	 * @type {ComputedRef<boolean>}
	 */
	const confirmationNeeded = computed( () => !!confirmationMessage.value );

	// ** Watchers **

	// Show confirmation dialog if 'Hide username' is visible and selected,
	// or if the target user is the current user.
	watch(
		computed( () => [ targetUser.value, hideUser.value, hideUserVisible.value ] ),
		( [ newTargetUser, newHideUser, newHideUserVisible ] ) => {
			if ( newHideUserVisible && newHideUser ) {
				confirmationMessage.value = mw.message( 'ipb-confirmhideuser' ).parse();
			} else if ( newTargetUser === mw.config.get( 'wgUserName' ) ) {
				confirmationMessage.value = mw.msg( 'ipb-blockingself' );
			} else {
				confirmationMessage.value = '';
			}
		},
		// Ensure confirmationMessage is set on initial load.
		{ immediate: true }
	);

	// Hide the form and clear form-related refs when the target user changes.
	watch( targetUser, resetFormInternal );

	/**
	 * The current in-flight API request for block log data. This is used to
	 * avoid redundant API queries when rendering multiple BlockLog components.
	 *
	 * @type {Promise|null}
	 */
	let blockLogPromise = null;
	// Reset the blockLogPromise when the target user changes or the form is submitted.
	watch( [ targetUser, formSubmitted ], () => {
		blockLogPromise = null;
	} );

	// ** Actions (exported functions) **

	/**
	 * Load block data from an action=blocks API response.
	 *
	 * @param {Object} blockData The block's item from the API.
	 * @param {boolean} [setTarget=false] Whether to set the `targetUser`, thereby firing
	 *   off associated watchers.
	 */
	function loadFromData( blockData, setTarget = false ) {
		if ( setTarget ) {
			targetUser.value = blockData.user;
		}
		blockId.value = blockData.id;
		type.value = blockData.partial ? 'partial' : 'sitewide';
		pages.value = ( blockData.restrictions.pages || [] ).map( ( i ) => i.title );
		namespaces.value = blockData.restrictions.namespaces || [];
		expiry.value = blockData.expiry;
		partialOptions.value = ( blockData.restrictions.actions || [] ).map( ( i ) => 'ipb-action-' + i );
		// The reason is a single string that possibly starts with one of the predefined reasons,
		// and can have an 'other' value separated by a colon.
		// Here we replicate what's done in PHP in HTMLSelectAndOtherField at https://w.wiki/CPMs
		reason.value = 'other';
		reasonOther.value = blockData.reason;
		for ( const opt of mw.config.get( 'blockReasonOptions' ) ) {
			const possPrefix = opt.value + mw.msg( 'colon-separator' );
			if ( reasonOther.value.startsWith( possPrefix ) ) {
				reason.value = opt.value;
				reasonOther.value = reasonOther.value.slice( possPrefix.length );
				break;
			}
		}
		createAccount.value = blockData.nocreate;
		disableEmail.value = blockData.noemail;
		disableUTEdit.value = !blockData.allowusertalk;
		hardBlock.value = !blockData.anononly;
		hideUser.value = blockData.hidden;
		autoBlock.value = blockData.autoblock;
		// We do not need to set watchUser as its state is never loaded from a block.
	}

	/**
	 * Reset the form to default values, optionally clearing the target user and behavioural refs.
	 * The values here should be the defaults set on the elements in SpecialBlock.php.
	 * These are not the same as the *preset* values fetched from URL parameters.
	 *
	 * @param {boolean} [user=false] Whether to clear the target user.
	 * @param {boolean} [internal=true] Whether to also reset internal refs not tied to a specific
	 *   form field, such as `formErrors`, `formVisible` and `alreadyBlocked`.
	 * @todo Infuse default values once we have Codex PHP (T377529).
	 *   Until then this needs to be manually kept in sync with the PHP defaults.
	 */
	function resetForm( user = false, internal = true ) {
		// Form fields
		if ( user ) {
			targetUser.value = '';
			targetExists.value = false;
		}
		blockId.value = null;
		type.value = 'sitewide';
		pages.value = [];
		namespaces.value = [];
		partialOptions.value = [];
		expiry.value = '';
		reason.value = 'other';
		reasonOther.value = '';
		createAccount.value = true;
		disableEmail.value = false;
		disableUTEdit.value = false;
		autoBlock.value = true;
		hideUser.value = false;
		watchUser.value = false;
		hardBlock.value = false;
		// Other refs
		if ( internal ) {
			resetFormInternal();
		}
	}

	/**
	 * Clear form behavioural refs.
	 *
	 * @internal
	 */
	function resetFormInternal() {
		blockId.value = null;
		formErrors.value = [];
		formSubmitted.value = false;
		formVisible.value = false;
		blockAdded.value = false;
		blockRemoved.value = false;
		promises.value.clear();
	}

	/**
	 * Execute the block.
	 *
	 * @return {jQuery.Promise}
	 */
	function doBlock() {
		const params = {
			action: 'block',
			format: 'json',
			formatversion: 2,
			user: targetUser.value,
			expiry: expiry.value,
			// Localize errors
			errorformat: 'html',
			uselang: mw.config.get( 'wgUserLanguage' ),
			errorlang: mw.config.get( 'wgUserLanguage' ),
			errorsuselocal: true
		};

		if ( !enableMultiblocks && alreadyBlocked.value ) {
			params.reblock = 1;
		}

		if ( enableMultiblocks ) {
			if ( blockId.value ) {
				params.id = blockId.value;
				delete params.user;
			} else {
				params.newblock = 1;
			}
		}

		// Reason selected concatenated with 'Other' field
		if ( reason.value === 'other' ) {
			params.reason = reasonOther.value;
		} else {
			params.reason = reason.value + (
				reasonOther.value ? mw.msg( 'colon-separator' ) + reasonOther.value : ''
			);
		}

		if ( type.value === 'partial' ) {
			params.partial = 1;
			params.actionrestrictions = Object.keys( partialOptions.value )
				.map( ( i ) => partialOptions.value[ i ].replace( 'ipb-action-', '' ) )
				.join( '|' );
			if ( pages.value.length ) {
				params.pagerestrictions = pages.value.join( '|' );
			}
			if ( namespaces.value.length ) {
				params.namespacerestrictions = namespaces.value.join( '|' );
			}
		}

		if ( createAccount.value ) {
			params.nocreate = 1;
		}

		if ( disableEmail.value ) {
			params.noemail = 1;
		}

		if ( !disableUTEditVisible.value || !disableUTEdit.value ) {
			params.allowusertalk = 1;
		}

		if ( autoBlock.value ) {
			params.autoblock = 1;
		}

		if ( hideUserVisible.value && hideUser.value ) {
			params.hidename = 1;
		}

		if ( watchUser.value ) {
			params.watchuser = 1;
		}

		if ( !hardBlock.value && mw.util.isIPAddress( targetUser.value, true ) ) {
			params.anononly = 1;
		}

		// Clear any previous errors.
		formErrors.value = [];

		return pushPromise( api.postWithEditToken( params ) );
	}

	/**
	 * Send the API request to remove a single block.
	 *
	 * @return {Promise|jQuery.Promise}
	 */
	function doRemoveBlock() {
		const params = {
			action: 'unblock',
			reason: removalReason.value
		};
		if ( blockId.value ) {
			params.id = blockId.value;
		} else {
			params.user = targetUser.value;
		}
		if ( watchUser.value ) {
			params.watchuser = 1;
		}
		// Reset the blockLogPromise so the log will be re-requested after the removal.
		blockLogPromise = null;
		return pushPromise( api.postWithEditToken( params ) );
	}

	/**
	 * Query the API for data needed by the BlockLog component. This method caches the response
	 * by target user to consolidate API requests across multiple BlockLog components.
	 * The cache is cleared when the target user changes by a watcher in the store.
	 *
	 * @param {string} blockLogType Which data to fetch. One of 'recent', 'active', or 'suppress'.
	 * @return {Promise|jQuery.Promise}
	 */
	function getBlockLogData( blockLogType ) {
		if ( blockLogPromise && blockLogType !== 'suppress' ) {
			// Serve block log data from cache if available.
			return blockLogPromise;
		}

		let target = targetUser.value;
		const isValidIpOrRange = mw.util.isIPAddress( target, true );
		const isIpRange = isValidIpOrRange && !mw.util.isIPAddress( target, false );

		// Sanitize IP ranges for block log queries.
		if ( isIpRange ) {
			target = util.sanitizeRange( target );
		}

		const params = {
			action: 'query',
			format: 'json',
			leprop: 'ids|title|type|user|timestamp|parsedcomment|details',
			letitle: `User:${ target }`,
			list: 'logevents',
			formatversion: 2
		};

		if ( blockLogType === 'suppress' ) {
			const localPromises = [];
			// Query both the block and reblock actions of the suppression log.
			params.leaction = 'suppress/block';
			localPromises.push( pushPromise( api.get( params ) ) );
			params.leaction = 'suppress/reblock';
			localPromises.push( pushPromise( api.get( params ) ) );
			return Promise.all( localPromises );
		}

		// Cache miss for block log data.
		// Add params needed to fetch block log and active blocks in one request.
		params.list = 'logevents|blocks';
		params.letype = 'block';
		params.bkprop = 'id|user|by|timestamp|expiry|reason|parsedreason|range|flags|restrictions';
		if ( isValidIpOrRange ) {
			params.bkip = target;
		} else {
			params.bkusers = target;
		}

		const actualPromise = api.get( params );
		actualPromise.then( ( data ) => {
			alreadyBlocked.value = data.query.blocks.length > 0;
			// form should be visible if target is not blocked
			if ( !alreadyBlocked.value ) {
				formVisible.value = true;
			}
		} );
		blockLogPromise = Promise.all( [ actualPromise ] );
		return pushPromise( blockLogPromise );
	}

	/**
	 * Add a promise to the `Set` of pending promises.
	 * This is used solely to disable the form while waiting for a response,
	 * and should only be used for requests that need to block UI interaction.
	 * The promise will be removed from the Set when it resolves, and
	 * once the Set is empty, the form will be re-enabled.
	 *
	 * @param {Promise|jQuery.Promise} promise
	 * @return {Promise|jQuery.Promise} The same unresolved promise that was passed in.
	 */
	function pushPromise( promise ) {
		promises.value.add( promise );
		// Can't use .finally() because it's not supported in jQuery.
		promise.then(
			() => promises.value.delete( promise ),
			() => promises.value.delete( promise )
		);
		return promise;
	}

	return {
		enableMultiblocks,
		formDisabled,
		formErrors,
		formSubmitted,
		formVisible,
		targetUser,
		blockAdded,
		blockRemoved,
		blockId,
		alreadyBlocked,
		type,
		expiry,
		partialOptions,
		pages,
		namespaces,
		reason,
		reasonOther,
		createAccount,
		disableEmail,
		disableUTEdit,
		disableUTEditVisible,
		autoBlock,
		hideUser,
		hideUserVisible,
		watchUser,
		hardBlock,
		confirmationMessage,
		confirmationNeeded,
		removalReason,
		loadFromData,
		resetForm,
		doBlock,
		doRemoveBlock,
		getBlockLogData,
		targetExists
	};
} );