Debian Codegraph @

extensions/AbuseFilter/modules/ext.abuseFilter.edit.js

raw symbols SCIP
1 /**
2 * AbuseFilter editing JavaScript
3 *
4 * @author John Du Hart
5 * @author Marius Hoch <[email protected]>
6 */
7 /* global ace */
8
9 ( function () {
10 'use strict';
11
12 // @var {jQuery} Filter editor for JS and jQuery handling
13 var $filterBox,
14 // Filter editor for Ace specific functions
15 filterEditor,
16 // @var {jQuery} Hidden textarea for submitting form
17 $plainTextBox,
18 // @var {boolean} To determine what editor to use
19 useAce = false,
20 // Infused OOUI elements
21 toggleWarnPreviewButton, warnMessageExisting, warnMessageOther,
22 toggleDisallowPreviewButton, disallowMessageExisting, disallowMessageOther;
23
24 /**
25 * Returns the currently selected warning or disallow message.
26 *
27 * @param {string} action The action to get the message for
28 * @return {string} current warning message
29 */
30 function getCurrentMessage( action ) {
31 var existing = action === 'warn' ? warnMessageExisting : disallowMessageExisting,
32 other = action === 'warn' ? warnMessageOther : disallowMessageOther,
33 message = existing.getValue();
34
35 if ( message === 'other' ) {
36 message = other.getValue();
37 }
38
39 return message;
40 }
41
42 /**
43 * Things always needed after syntax checks
44 *
45 * @param {string} resultText The message to show, telling if the syntax is valid
46 * @param {string} className Class to add
47 * @param {boolean} syntaxOk Is the syntax ok?
48 */
49 function processSyntaxResultAlways( resultText, className, syntaxOk ) {
50 $.removeSpinner( 'abusefilter-syntaxcheck' );
51 $( '#mw-abusefilter-syntaxcheck' ).prop( 'disabled', false );
52
53 $( '#mw-abusefilter-syntaxresult' )
54 .show()
55 .attr( 'class', className )
56 .text( resultText )
57 .data( 'syntaxOk', syntaxOk );
58 }
59
60 /**
61 * Switch between Ace Editor and classic textarea
62 */
63 function switchEditor() {
64 if ( useAce ) {
65 useAce = false;
66 $filterBox.hide();
67 $plainTextBox.show();
68 } else {
69 useAce = true;
70 filterEditor.session.setValue( $plainTextBox.val() );
71 $filterBox.show();
72 $plainTextBox.hide();
73 }
74 }
75
76 /**
77 * Takes the data retrieved in doSyntaxCheck and processes it.
78 *
79 * @param {Object} response Data returned from the AJAX request
80 */
81 function processSyntaxResult( response ) {
82 var data = response.abusefilterchecksyntax;
83
84 if ( data.status === 'ok' ) {
85 // Successful
86 processSyntaxResultAlways(
87 mw.msg( 'abusefilter-edit-syntaxok' ),
88 'mw-abusefilter-syntaxresult-ok',
89 true
90 );
91 } else {
92 // Set a custom error message as we're aware of the actual problem
93 processSyntaxResultAlways(
94 mw.message( 'abusefilter-edit-syntaxerr', data.message ).toString(),
95 'mw-abusefilter-syntaxresult-error',
96 false
97 );
98
99 if ( useAce ) {
100 filterEditor.focus();
101 // Convert index (used in textareas) in position {row, column} for ace
102 var position = filterEditor.session.getDocument().indexToPosition( data.character );
103 filterEditor.navigateTo( position.row, position.column );
104 filterEditor.scrollToRow( position.row );
105 } else {
106 $plainTextBox
107 .trigger( 'focus' )
108 .textSelection( 'setSelection', { start: data.character } );
109 }
110 }
111 }
112
113 /**
114 * Acts on errors after doSyntaxCheck.
115 *
116 * @param {string} error Error code returned from the AJAX request
117 * @param {Object} details Details about the error
118 */
119 function processSyntaxResultFailure( error, details ) {
120 processSyntaxResultAlways(
121 mw.msg(
122 error === 'http' ? 'abusefilter-http-error' : 'unknown-error',
123 details && details.exception
124 ),
125 'mw-abusefilter-syntaxresult-error',
126 false
127 );
128 }
129
130 /**
131 * Sends the current filter text to be checked for syntax issues.
132 *
133 * @this HTMLElement
134 * @param {jQuery.Event} e The event fired when the function is called
135 */
136 function doSyntaxCheck() {
137 var filter = $plainTextBox.val();
138
139 $( this )
140 .prop( 'disabled', true )
141 .injectSpinner( { id: 'abusefilter-syntaxcheck', size: 'large' } );
142
143 new mw.Api().post( {
144 action: 'abusefilterchecksyntax',
145 filter: filter
146 } )
147 .done( processSyntaxResult )
148 .fail( processSyntaxResultFailure );
149 }
150
151 /**
152 * Adds text to the filter textarea.
153 * Fired by a change event from the #wpFilterBuilder dropdown
154 */
155 function addText() {
156 var $filterBuilder = $( '#wpFilterBuilder' );
157
158 if ( $filterBuilder.prop( 'selectedIndex' ) === 0 ) {
159 return;
160 }
161
162 if ( useAce ) {
163 filterEditor.insert( $filterBuilder.val() + ' ' );
164 $plainTextBox.val( filterEditor.getSession().getValue() );
165 filterEditor.focus();
166 } else {
167 $plainTextBox.textSelection(
168 'encapsulateSelection', { pre: $filterBuilder.val() + ' ' }
169 );
170 }
171 $filterBuilder.prop( 'selectedIndex', 0 );
172 }
173
174 /**
175 * Fetches a filter from the API and inserts it into the filter box.
176 *
177 * @this HTMLElement
178 * @param {jQuery.Event} e The event fired when the function is called
179 */
180 function fetchFilter() {
181 var filterId = $( '#mw-abusefilter-load-filter input' ).val().trim();
182
183 if ( filterId === '' ) {
184 return;
185 }
186
187 $( this ).injectSpinner( { id: 'fetch-spinner', size: 'large' } );
188
189 // We just ignore errors or unexisting filters over here
190 new mw.Api().get( {
191 action: 'query',
192 list: 'abusefilters',
193 abfprop: 'pattern',
194 abfstartid: filterId,
195 abfendid: filterId,
196 abflimit: 1
197 } )
198 .always( function removeSpinner() {
199 $.removeSpinner( 'fetch-spinner' );
200 } )
201 .done( function insertFilter( data ) {
202 if ( data.query.abusefilters[ 0 ] !== undefined ) {
203 if ( useAce ) {
204 filterEditor.setValue( data.query.abusefilters[ 0 ].pattern );
205 }
206 $plainTextBox.val( data.query.abusefilters[ 0 ].pattern );
207 }
208 } );
209 }
210
211 /**
212 * Cycles through all action checkboxes and hides parameter divs.
213 * that don't have checked boxes
214 */
215 function hideDeselectedActions() {
216 $( '.mw-abusefilter-action-checkbox input' ).each( function showHideParams() {
217 // mw-abusefilter-action-checkbox-{$action}
218 var action = this.parentNode.id.slice( 31 ),
219 $params = $( '#mw-abusefilter-' + action + '-parameters' );
220
221 if ( $params.length ) {
222 if ( this.checked ) {
223 $params.show();
224 } else {
225 $params.hide();
226 }
227 }
228 } );
229 }
230
231 /**
232 * Fetches the selected warning message for previewing.
233 *
234 * @param {string} action The action the message refers to
235 */
236 function previewMessage( action ) {
237 // The following messages are generated here:
238 // * mw-abusefilter-warn-preview
239 // * mw-abusefilter-disallow-preview
240 var $element = $( '#mw-abusefilter-' + action + '-preview' ),
241 previewButton = action === 'warn' ? toggleWarnPreviewButton : toggleDisallowPreviewButton;
242
243 if ( $element.css( 'display' ) !== 'none' ) {
244 $element.hide();
245 previewButton.setFlags( { destructive: false, progressive: true } );
246 } else {
247 var api = new mw.Api();
248 var args = [
249 '<nowiki>' + $( 'input[name=wpFilterDescription]' ).val() + '</nowiki>',
250 $( '#mw-abusefilter-edit-id' ).children().last().text()
251 ];
252 var message = getCurrentMessage( action );
253
254 api.get( {
255 action: 'query',
256 meta: 'allmessages',
257 ammessages: message,
258 amargs: args.join( '|' )
259 } )
260 .done( function parseMessage( data ) {
261 api.parse( data.query.allmessages[ 0 ][ '*' ], {
262 disablelimitreport: '',
263 preview: '',
264 prop: 'text',
265 title: 'MediaWiki:' + message
266 } )
267 .done( function showMessage( html ) {
268 $element.show().html( html );
269 previewButton.setFlags(
270 { destructive: true, progressive: false }
271 );
272 } );
273 } );
274 }
275 }
276
277 /**
278 * Redirects the browser to the message for editing.
279 *
280 * @param {string} action The action for which the message is used
281 */
282 function editMessage( action ) {
283 var message = getCurrentMessage( action ),
284 defaultMsg = action === 'warn' ? 'warning' : 'disallowed',
285 url = mw.util.getUrl( 'MediaWiki:' + message, {
286 action: 'edit',
287 preload: 'MediaWiki:abusefilter-' + defaultMsg
288 } );
289
290 window.open( url, '_blank' );
291 }
292
293 /**
294 * Called if the filter group (#mw-abusefilter-edit-group-input select) is changed. Allows
295 * using different default messages for 'warn' and 'disallow', based on the group.
296 *
297 * @this HTMLELement
298 * @param {jQuery.Event} e The event fired when the function is called
299 */
300 function onFilterGroupChange() {
301 var newVal;
302
303 if (
304 !$( '#mw-abusefilter-action-checkbox-warn input' ).is( ':checked' ) &&
305 $( this ).val() in mw.config.get( 'wgAbuseFilterDefaultWarningMessage' )
306 ) {
307 var $afWarnMessageExisting = $( '#mw-abusefilter-warn-message-existing select' );
308 newVal = mw.config.get( 'wgAbuseFilterDefaultWarningMessage' )[ $( this ).val() ];
309
310 if ( $afWarnMessageExisting.find( 'option[value=\'' + newVal + '\']' ).length ) {
311 $afWarnMessageExisting.val( newVal );
312 warnMessageOther.setValue( '' );
313 } else {
314 $afWarnMessageExisting.val( 'other' );
315 warnMessageOther.setValue( newVal );
316 }
317 }
318
319 if (
320 !$( '#mw-abusefilter-action-checkbox-disallow input' ).is( ':checked' ) &&
321 $( this ).val() in mw.config.get( 'wgAbuseFilterDefaultDisallowMessage' )
322 ) {
323 var $afDisallowMessageExisting = $( '#mw-abusefilter-disallow-message-existing select' );
324 newVal = mw.config.get( 'wgAbuseFilterDefaultDisallowMessage' )[ $( this ).val() ];
325
326 if ( $afDisallowMessageExisting.find( 'option[value=\'' + newVal + '\']' ).length ) {
327 $afDisallowMessageExisting.val( newVal );
328 disallowMessageOther.setValue( '' );
329 } else {
330 $afDisallowMessageExisting.val( 'other' );
331 disallowMessageOther.setValue( newVal );
332 }
333 }
334 }
335
336 /**
337 * Remove the options for warning and disallow messages if the filter is set to global.
338 */
339 function toggleCustomMessages() {
340 // Use the table over here as hideDeselectedActions might alter the visibility of the div
341 var $warnOptions = $( '#mw-abusefilter-warn-parameters > table' ),
342 $disallowOptions = $( '#mw-abusefilter-disallow-parameters > table' );
343
344 if ( $( '#wpFilterGlobal' ).is( ':checked' ) ) {
345 // It's a global filter, so use the default message and hide the option from the user
346 warnMessageExisting.setValue( 'abusefilter-warning' );
347 disallowMessageExisting.setValue( 'abusefilter-disallowed' );
348
349 $warnOptions.hide();
350 $disallowOptions.hide();
351 } else {
352 $warnOptions.show();
353 $disallowOptions.show();
354 }
355 }
356
357 /**
358 * Called if the user presses a key in the load filter field.
359 *
360 * @this HTMLELement
361 * @param {jQuery.Event} e The event fired when the function is called
362 */
363 function onFilterKeypress( e ) {
364 if ( e.type === 'keypress' && e.which === 13 ) {
365 e.preventDefault();
366 $( '#mw-abusefilter-load' ).trigger( 'click' );
367 }
368 }
369
370 /**
371 * Warn if the user changed anything and tries to leave the window
372 */
373 function setWarnOnLeave() {
374 var $form = $( '#mw-abusefilter-editing-form' ),
375 origValues = $form.serialize();
376
377 var warnOnLeave = mw.confirmCloseWindow( {
378 test: function () {
379 return $form.serialize() !== origValues;
380 },
381 message: mw.msg( 'abusefilter-edit-warn-leave' )
382 } );
383
384 $form.on( 'submit', function () {
385 warnOnLeave.release();
386 } );
387 }
388
389 /**
390 * Builds a TagMultiselectWidget, to be used both for throttle groups and change tags
391 *
392 * @param {string} action Either 'throttle' or 'tag', will be used to build element IDs
393 * @param {Array} config The array with configuration passed from PHP code
394 */
395 function buildSelector( action, config ) {
396 // mw-abusefilter-throttle-parameters, mw-abusefilter-tag-parameters
397 var $container = $( '#mw-abusefilter-' + action + '-parameters' ),
398 // Character used to separate elements in the textarea.
399 separator = action === 'throttle' ? '\n' : ',';
400
401 var selector = new OO.ui.TagMultiselectWidget( {
402 inputPosition: 'outline',
403 allowArbitrary: true,
404 allowEditTags: true,
405
406 selected: config.values,
407 // The following messages are used here:
408 // * abusefilter-edit-throttle-placeholder
409 // * abusefilter-edit-tag-placeholder
410 placeholder: OO.ui.msg( 'abusefilter-edit-' + action + '-placeholder' ),
411 disabled: config.disabled
412 } );
413
414 var fieldOpts = {
415 label: $( $.parseHTML( config.label ) ),
416 align: 'top'
417 };
418 if ( action === 'throttle' ) {
419 fieldOpts.help = new OO.ui.HtmlSnippet( config.help );
420 }
421
422 var field = new OO.ui.FieldLayout( selector, fieldOpts );
423
424 // mw-abusefilter-hidden-throttle-field, mw-abusefilter-hidden-tag-field
425 var hiddenField = OO.ui.infuse( $( '#mw-abusefilter-hidden-' + action + '-field' ) );
426 selector.on( 'change', function () {
427 hiddenField.setValue( selector.getValue().join( separator ) );
428 } );
429
430 // mw-abusefilter-hidden-throttle, mw-abusefilter-hidden-tag
431 $( '#mw-abusefilter-hidden-' + action ).hide();
432 $container.append( field.$element );
433 }
434
435 // On ready initialization
436 $( function () {
437 var $exportBox = $( '#mw-abusefilter-export' ),
438 isFilterEditor = mw.config.get( 'isFilterEditor' ),
439 tagConfig = mw.config.get( 'tagConfig' ),
440 throttleConfig = mw.config.get( 'throttleConfig' ),
441 $switchEditorBtn = $( '#mw-abusefilter-switcheditor' );
442
443 if ( isFilterEditor ) {
444 // Configure the actual editing interface
445 if ( tagConfig ) {
446 // Build the tag selector
447 buildSelector( 'tag', tagConfig );
448 }
449 if ( throttleConfig ) {
450 // Build the throttle groups selector
451 buildSelector( 'throttle', throttleConfig );
452 }
453
454 toggleWarnPreviewButton = OO.ui.infuse( $( '#mw-abusefilter-warn-preview-button' ) );
455 warnMessageExisting = OO.ui.infuse( $( '#mw-abusefilter-warn-message-existing' ) );
456 warnMessageOther = OO.ui.infuse( $( '#mw-abusefilter-warn-message-other' ) );
457 toggleDisallowPreviewButton = OO.ui.infuse( $( '#mw-abusefilter-disallow-preview-button' ) );
458 disallowMessageExisting = OO.ui.infuse( $( '#mw-abusefilter-disallow-message-existing' ) );
459 disallowMessageOther = OO.ui.infuse( $( '#mw-abusefilter-disallow-message-other' ) );
460 setWarnOnLeave();
461 }
462
463 $plainTextBox = $( '#wpFilterRules' );
464
465 if ( $( '#wpAceFilterEditor' ).length ) {
466 // CodeEditor is installed.
467 mw.loader.using( [ 'ext.abuseFilter.ace' ] ).then( function () {
468 $filterBox = $( '#wpAceFilterEditor' );
469
470 filterEditor = ace.edit( 'wpAceFilterEditor' );
471 filterEditor.session.setMode( 'ace/mode/abusefilter' );
472
473 // Ace setup from codeEditor extension
474 var basePath = mw.config.get( 'wgExtensionAssetsPath', '' );
475 if ( basePath.slice( 0, 2 ) === '//' ) {
476 // ACE uses web workers, which have importScripts, which don't like
477 // relative links. This is a problem only when the assets are on another
478 // server, so this rewrite should suffice.
479 basePath = window.location.protocol + basePath;
480 }
481 ace.config.set( 'basePath', basePath + '/CodeEditor/modules/lib/ace' );
482
483 // Settings for Ace editor box
484 var readOnly = mw.config.get( 'aceConfig' ).aceReadOnly;
485
486 filterEditor.setTheme( 'ace/theme/textmate' );
487 filterEditor.setReadOnly( readOnly );
488 filterEditor.$blockScrolling = Infinity;
489
490 // Display Ace editor
491 switchEditor();
492
493 // Hide the syntax ok message when the text changes and sync dummy box
494 filterEditor.on( 'change', function () {
495 var $el = $( '#mw-abusefilter-syntaxresult' );
496
497 if ( $el.data( 'syntaxOk' ) ) {
498 $el.hide();
499 }
500
501 $plainTextBox.val( filterEditor.getSession().getValue() );
502 } );
503
504 // Make Ace editor resizable
505 // (uses ResizeObserver, which is not implemented in IE 11)
506 if ( typeof ResizeObserver !== 'undefined' ) {
507 // Make the container resizable
508 $filterBox.css( 'resize', 'both' );
509 // Refresh Ace editor size (notably its scrollbars) when the container
510 // is resized, otherwise it would be refreshed only on window resize
511 new ResizeObserver( function () {
512
513 filterEditor.resize();
514 } ).observe( $filterBox[ 0 ] );
515 }
516
517 $switchEditorBtn.on( 'click', switchEditor ).show();
518 } );
519 }
520
521 // Hide the syntax ok message when the text changes
522 $plainTextBox.on( 'change', function () {
523 var $el = $( '#mw-abusefilter-syntaxresult' );
524
525 if ( $el.data( 'syntaxOk' ) ) {
526 $el.hide();
527 }
528 } );
529
530 $( '#mw-abusefilter-load' ).on( 'click', fetchFilter );
531 $( '#mw-abusefilter-load-filter' ).on( 'keypress', onFilterKeypress );
532
533 if ( isFilterEditor ) {
534 // Add logic for flags and consequences
535 $( '#mw-abusefilter-warn-preview-button' ).on( 'click',
536 function () {
537 previewMessage( 'warn' );
538 }
539 );
540 $( '#mw-abusefilter-disallow-preview-button' ).on( 'click',
541 function () {
542 previewMessage( 'disallow' );
543 }
544 );
545 $( '#mw-abusefilter-warn-edit-button' ).on( 'click',
546 function () {
547 editMessage( 'warn' );
548 }
549 );
550 $( '#mw-abusefilter-disallow-edit-button' ).on( 'click',
551 function () {
552 editMessage( 'disallow' );
553 }
554 );
555 $( '.mw-abusefilter-action-checkbox input' ).on( 'click', hideDeselectedActions );
556 hideDeselectedActions();
557
558 $( '#wpFilterGlobal' ).on( 'change', toggleCustomMessages );
559 toggleCustomMessages();
560
561 var cbEnabled = OO.ui.infuse( $( '#wpFilterEnabled' ) );
562 var cbDeleted = OO.ui.infuse( $( '#wpFilterDeleted' ) );
563 OO.ui.infuse( $( '#wpFilterDeletedLabel' ) );
564 cbEnabled.on( 'change',
565 function () {
566 cbDeleted.setDisabled( cbEnabled.isSelected() );
567 if ( cbEnabled.isSelected() ) {
568 cbDeleted.setSelected( false );
569 }
570 }
571 );
572
573 cbDeleted.on( 'change',
574 function () {
575 if ( cbDeleted.isSelected() ) {
576 cbEnabled.setSelected( false );
577 }
578 }
579 );
580
581 $( '#mw-abusefilter-edit-group-input select' ).on( 'change', onFilterGroupChange );
582
583 $( '#mw-abusefilter-export-link' ).on( 'click',
584 function ( e ) {
585 e.preventDefault();
586 $exportBox.toggle();
587 }
588 );
589 }
590
591 $( '#mw-abusefilter-syntaxcheck' ).on( 'click', doSyntaxCheck );
592 $( '#wpFilterBuilder' ).on( 'change', addText );
593 } );
594 }() );