Debian Codegraph @

extensions/AbuseFilter/includes/View/AbuseFilterViewEdit.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\AbuseFilter\View;
4
5 use HtmlArmor;
6 use LogicException;
7 use MediaWiki\Context\IContextSource;
8 use MediaWiki\Extension\AbuseFilter\AbuseFilterPermissionManager;
9 use MediaWiki\Extension\AbuseFilter\Consequences\ConsequencesRegistry;
10 use MediaWiki\Extension\AbuseFilter\EditBox\EditBoxBuilderFactory;
11 use MediaWiki\Extension\AbuseFilter\Filter\Filter;
12 use MediaWiki\Extension\AbuseFilter\Filter\FilterNotFoundException;
13 use MediaWiki\Extension\AbuseFilter\Filter\FilterVersionNotFoundException;
14 use MediaWiki\Extension\AbuseFilter\Filter\MutableFilter;
15 use MediaWiki\Extension\AbuseFilter\FilterImporter;
16 use MediaWiki\Extension\AbuseFilter\FilterLookup;
17 use MediaWiki\Extension\AbuseFilter\FilterProfiler;
18 use MediaWiki\Extension\AbuseFilter\FilterStore;
19 use MediaWiki\Extension\AbuseFilter\InvalidImportDataException;
20 use MediaWiki\Extension\AbuseFilter\SpecsFormatter;
21 use MediaWiki\Html\Html;
22 use MediaWiki\Linker\Linker;
23 use MediaWiki\Linker\LinkRenderer;
24 use MediaWiki\MainConfigNames;
25 use MediaWiki\Permissions\PermissionManager;
26 use MediaWiki\SpecialPage\SpecialPage;
27 use MediaWiki\Xml\Xml;
28 use OOUI;
29 use UnexpectedValueException;
30 use Wikimedia\Rdbms\IDBAccessObject;
31 use Wikimedia\Rdbms\IExpression;
32 use Wikimedia\Rdbms\LBFactory;
33 use Wikimedia\Rdbms\LikeValue;
34 use Wikimedia\Rdbms\SelectQueryBuilder;
35
36 class AbuseFilterViewEdit extends AbuseFilterView {
37 /**
38 * @var int|null The history ID of the current filter
39 */
40 private $historyID;
41 /** @var int|string */
42 private $filter;
43
44 /** @var LBFactory */
45 private $lbFactory;
46
47 /** @var PermissionManager */
48 private $permissionManager;
49
50 /** @var FilterProfiler */
51 private $filterProfiler;
52
53 /** @var FilterLookup */
54 private $filterLookup;
55
56 /** @var FilterImporter */
57 private $filterImporter;
58
59 /** @var FilterStore */
60 private $filterStore;
61
62 /** @var EditBoxBuilderFactory */
63 private $boxBuilderFactory;
64
65 /** @var ConsequencesRegistry */
66 private $consequencesRegistry;
67
68 /** @var SpecsFormatter */
69 private $specsFormatter;
70
71 /**
72 * @param LBFactory $lbFactory
73 * @param PermissionManager $permissionManager
74 * @param AbuseFilterPermissionManager $afPermManager
75 * @param FilterProfiler $filterProfiler
76 * @param FilterLookup $filterLookup
77 * @param FilterImporter $filterImporter
78 * @param FilterStore $filterStore
79 * @param EditBoxBuilderFactory $boxBuilderFactory
80 * @param ConsequencesRegistry $consequencesRegistry
81 * @param SpecsFormatter $specsFormatter
82 * @param IContextSource $context
83 * @param LinkRenderer $linkRenderer
84 * @param string $basePageName
85 * @param array $params
86 */
87 public function __construct(
88 LBFactory $lbFactory,
89 PermissionManager $permissionManager,
90 AbuseFilterPermissionManager $afPermManager,
91 FilterProfiler $filterProfiler,
92 FilterLookup $filterLookup,
93 FilterImporter $filterImporter,
94 FilterStore $filterStore,
95 EditBoxBuilderFactory $boxBuilderFactory,
96 ConsequencesRegistry $consequencesRegistry,
97 SpecsFormatter $specsFormatter,
98 IContextSource $context,
99 LinkRenderer $linkRenderer,
100 string $basePageName,
101 array $params
102 ) {
103 parent::__construct( $afPermManager, $context, $linkRenderer, $basePageName, $params );
104 $this->lbFactory = $lbFactory;
105 $this->permissionManager = $permissionManager;
106 $this->filterProfiler = $filterProfiler;
107 $this->filterLookup = $filterLookup;
108 $this->filterImporter = $filterImporter;
109 $this->filterStore = $filterStore;
110 $this->boxBuilderFactory = $boxBuilderFactory;
111 $this->consequencesRegistry = $consequencesRegistry;
112 $this->specsFormatter = $specsFormatter;
113 $this->specsFormatter->setMessageLocalizer( $this->getContext() );
114 $this->filter = $this->mParams['filter'];
115 $this->historyID = $this->mParams['history'] ?? null;
116 }
117
118 /**
119 * Shows the page
120 */
121 public function show() {
122 $out = $this->getOutput();
123 $out->enableOOUI();
124 $request = $this->getRequest();
125 $out->setPageTitleMsg( $this->msg( 'abusefilter-edit' ) );
126 $out->addHelpLink( 'Extension:AbuseFilter/Rules format' );
127
128 if ( !is_numeric( $this->filter ) && $this->filter !== null ) {
129 $this->showUnrecoverableError( 'abusefilter-edit-badfilter' );
130 return;
131 }
132 $filter = $this->filter ? (int)$this->filter : null;
133 $history_id = $this->historyID;
134 if ( $this->historyID ) {
135 $dbr = $this->lbFactory->getReplicaDatabase();
136 $lastID = (int)$dbr->newSelectQueryBuilder()
137 ->select( 'afh_id' )
138 ->from( 'abuse_filter_history' )
139 ->where( [
140 'afh_filter' => $filter,
141 ] )
142 ->orderBy( 'afh_id', SelectQueryBuilder::SORT_DESC )
143 ->caller( __METHOD__ )
144 ->fetchField();
145 // change $history_id to null if it's current version id
146 if ( $lastID === $this->historyID ) {
147 $history_id = null;
148 }
149 }
150
151 // Add the default warning and disallow messages in a JS variable
152 $this->exposeMessages();
153
154 $canEdit = $this->afPermManager->canEdit( $this->getAuthority() );
155
156 if ( $filter === null && !$canEdit ) {
157 // Special case: Special:AbuseFilter/new is certainly not usable if the user cannot edit
158 $this->showUnrecoverableError( 'abusefilter-edit-notallowed' );
159 return;
160 }
161
162 $isImport = $request->wasPosted() && $request->getRawVal( 'wpImportText' ) !== null;
163
164 if ( !$isImport && $request->wasPosted() && $canEdit ) {
165 $this->attemptSave( $filter, $history_id );
166 return;
167 }
168
169 if ( $isImport ) {
170 $filterObj = $this->loadImportRequest();
171 if ( $filterObj === null ) {
172 $this->showUnrecoverableError( 'abusefilter-import-invalid-data' );
173 return;
174 }
175 } else {
176 // The request wasn't posted (i.e. just viewing the filter) or the user cannot edit
177 try {
178 $filterObj = $this->loadFromDatabase( $filter, $history_id );
179 } catch ( FilterNotFoundException $_ ) {
180 $filterObj = null;
181 }
182 if ( $filterObj === null || ( $history_id && (int)$filterObj->getID() !== $filter ) ) {
183 $this->showUnrecoverableError( 'abusefilter-edit-badfilter' );
184 return;
185 }
186 }
187
188 $this->buildFilterEditor( null, $filterObj, $filter, $history_id );
189 }
190
191 /**
192 * @param int|null $filter The filter ID or null for a new filter
193 * @param int|null $history_id The history ID of the filter, if applicable. Otherwise null
194 */
195 private function attemptSave( ?int $filter, $history_id ): void {
196 $out = $this->getOutput();
197 $request = $this->getRequest();
198 $user = $this->getUser();
199
200 [ $newFilter, $origFilter ] = $this->loadRequest( $filter );
201
202 $tokenFilter = $filter === null ? 'new' : (string)$filter;
203 $editToken = $request->getVal( 'wpEditToken' );
204 $tokenMatches = $this->getCsrfTokenSet()->matchToken( $editToken, [ 'abusefilter', $tokenFilter ] );
205
206 if ( !$tokenMatches ) {
207 // Token invalid or expired while the page was open, warn to retry
208 $error = Html::warningBox( $this->msg( 'abusefilter-edit-token-not-match' )->parseAsBlock() );
209 $this->buildFilterEditor( $error, $newFilter, $filter, $history_id );
210 return;
211 }
212
213 $status = $this->filterStore->saveFilter( $user, $filter, $newFilter, $origFilter );
214
215 if ( !$status->isGood() ) {
216 $msg = $status->getMessages()[0];
217 if ( $status->isOK() ) {
218 // Fixable error, show the editing interface
219 $error = Html::errorBox( $this->msg( $msg )->parseAsBlock() );
220 $this->buildFilterEditor( $error, $newFilter, $filter, $history_id );
221 } else {
222 $this->showUnrecoverableError( $msg );
223 }
224 } elseif ( $status->getValue() === false ) {
225 // No change
226 $out->redirect( $this->getTitle()->getLocalURL() );
227 } else {
228 // Everything went fine!
229 [ $new_id, $history_id ] = $status->getValue();
230 $out->redirect(
231 $this->getTitle()->getLocalURL(
232 [
233 'result' => 'success',
234 'changedfilter' => $new_id,
235 'changeid' => $history_id,
236 ]
237 )
238 );
239 }
240 }
241
242 /**
243 * @param string|\Wikimedia\Message\MessageSpecifier $msg
244 */
245 private function showUnrecoverableError( $msg ): void {
246 $out = $this->getOutput();
247
248 $out->addHTML( Html::errorBox( $this->msg( $msg )->parseAsBlock() ) );
249 $href = $this->getTitle()->getFullURL();
250 $btn = new OOUI\ButtonWidget( [
251 'label' => $this->msg( 'abusefilter-return' )->text(),
252 'href' => $href
253 ] );
254 $out->addHTML( $btn );
255 }
256
257 /**
258 * Builds the full form for edit filters, adding it to the OutputPage. This method can be called in 5 different
259 * situations, for a total of 5 different data sources for $filterObj and $actions:
260 * 1 - View the result of importing a filter
261 * 2 - Create a new filter
262 * 3 - Load the current version of an existing filter
263 * 4 - Load an old version of an existing filter
264 * 5 - Show the user input again if saving fails after one of the steps above
265 *
266 * @param string|null $error An error message to show above the filter box (HTML).
267 * @param Filter $filterObj
268 * @param int|null $filter The filter ID, or null for a new filter
269 * @param int|null $history_id The history ID of the filter, if applicable. Otherwise null
270 */
271 private function buildFilterEditor(
272 $error,
273 Filter $filterObj,
274 ?int $filter,
275 $history_id
276 ) {
277 $out = $this->getOutput();
278 $out->addJsConfigVars( 'isFilterEditor', true );
279 $lang = $this->getLanguage();
280 $user = $this->getUser();
281 $actions = $filterObj->getActions();
282
283 $isCreatingNewFilter = $filter === null;
284 $out->addSubtitle( $this->msg(
285 $isCreatingNewFilter ? 'abusefilter-edit-subtitle-new' : 'abusefilter-edit-subtitle',
286 $isCreatingNewFilter ? $filter : $this->getLanguage()->formatNum( $filter ),
287 $history_id
288 )->parse() );
289
290 // Grab the current hidden flag from the DB, in case we're editing an older, public revision of a filter that is
291 // currently hidden, so that we can also hide that public revision.
292 if (
293 ( $filterObj->isHidden() || (
294 $filter !== null && $this->filterLookup->getFilter( $filter, false )->isHidden() )
295 ) && !$this->afPermManager->canViewPrivateFilters( $user )
296 ) {
297 $out->addHTML( $this->msg( 'abusefilter-edit-denied' )->escaped() );
298 return;
299 }
300
301 // Filters that use protected variables should always be hidden from public view
302 if (
303 (
304 $filterObj->isProtected() ||
305 ( $filter !== null && $this->filterLookup->getFilter( $filter, false )->isProtected() )
306 ) &&
307 !$this->afPermManager->canViewProtectedVariables( $user )
308 ) {
309 $out->addHTML( $this->msg( 'abusefilter-edit-denied-protected-vars' )->escaped() );
310 return;
311 }
312
313 if ( $isCreatingNewFilter ) {
314 $title = $this->msg( 'abusefilter-add' );
315 } elseif ( $this->afPermManager->canEditFilter( $user, $filterObj ) ) {
316 $title = $this->msg( 'abusefilter-edit-specific' )
317 ->numParams( $this->filter )
318 ->params( $filterObj->getName() );
319 } else {
320 $title = $this->msg( 'abusefilter-view-specific' )
321 ->numParams( $this->filter )
322 ->params( $filterObj->getName() );
323 }
324 $out->setPageTitleMsg( $title );
325
326 $readOnly = !$this->afPermManager->canEditFilter( $user, $filterObj );
327
328 if ( $history_id ) {
329 $oldWarningMessage = $readOnly
330 ? 'abusefilter-edit-oldwarning-view'
331 : 'abusefilter-edit-oldwarning';
332 $out->addWikiMsg( $oldWarningMessage, $history_id, $filter );
333 }
334
335 if ( $error !== null ) {
336 $out->addHTML( $error );
337 }
338
339 $fields = [];
340
341 $fields['abusefilter-edit-id'] =
342 $isCreatingNewFilter ?
343 $this->msg( 'abusefilter-edit-new' )->escaped() :
344 htmlspecialchars( $lang->formatNum( (string)$filter ) );
345 $fields['abusefilter-edit-description'] =
346 new OOUI\TextInputWidget( [
347 'name' => 'wpFilterDescription',
348 'id' => 'mw-abusefilter-edit-description-input',
349 'value' => $filterObj->getName(),
350 'readOnly' => $readOnly
351 ]
352 );
353
354 $validGroups = $this->getConfig()->get( 'AbuseFilterValidGroups' );
355 if ( count( $validGroups ) > 1 ) {
356 $groupSelector =
357 new OOUI\DropdownInputWidget( [
358 'name' => 'wpFilterGroup',
359 'id' => 'mw-abusefilter-edit-group-input',
360 'value' => $filterObj->getGroup(),
361 'disabled' => $readOnly
362 ] );
363
364 $options = [];
365 foreach ( $validGroups as $group ) {
366 $options += [ $this->specsFormatter->nameGroup( $group ) => $group ];
367 }
368
369 $options = Html::listDropdownOptionsOoui( $options );
370 $groupSelector->setOptions( $options );
371
372 $fields['abusefilter-edit-group'] = $groupSelector;
373 }
374
375 // Hit count display
376 if ( $filterObj->getHitCount() !== null && $this->afPermManager->canSeeLogDetails( $user ) ) {
377 $count_display = $this->msg( 'abusefilter-hitcount' )
378 ->numParams( $filterObj->getHitCount() )->text();
379 $hitCount = $this->linkRenderer->makeKnownLink(
380 SpecialPage::getTitleFor( 'AbuseLog' ),
381 $count_display,
382 [],
383 [ 'wpSearchFilter' => $filterObj->getID() ]
384 );
385
386 $fields['abusefilter-edit-hitcount'] = $hitCount;
387 }
388
389 if ( $filter !== null && $filterObj->isEnabled() ) {
390 // Statistics
391 [
392 'count' => $totalCount,
393 'matches' => $matchesCount,
394 'total-time' => $curTotalTime,
395 'total-cond' => $curTotalConds,
396 ] = $this->filterProfiler->getFilterProfile( $filter );
397
398 if ( $totalCount > 0 ) {
399 $matchesPercent = round( 100 * $matchesCount / $totalCount, 2 );
400 $avgTime = round( $curTotalTime / $totalCount, 2 );
401 $avgCond = round( $curTotalConds / $totalCount, 1 );
402
403 $fields['abusefilter-edit-status-label'] = $this->msg( 'abusefilter-edit-status' )
404 ->numParams( $totalCount, $matchesCount, $matchesPercent, $avgTime, $avgCond )
405 ->parse();
406 }
407 }
408
409 $boxBuilder = $this->boxBuilderFactory->newEditBoxBuilder( $this, $user, $out );
410
411 $fields['abusefilter-edit-rules'] = $boxBuilder->buildEditBox(
412 $filterObj->getRules(),
413 true
414 );
415 $fields['abusefilter-edit-notes'] =
416 new OOUI\MultilineTextInputWidget( [
417 'name' => 'wpFilterNotes',
418 'value' => $filterObj->getComments() . "\n",
419 'rows' => 15,
420 'readOnly' => $readOnly,
421 'id' => 'mw-abusefilter-notes-editor'
422 ] );
423
424 // Build checkboxes
425 $checkboxes = [ 'hidden', 'enabled', 'protected', 'deleted' ];
426 $flags = '';
427
428 if ( $this->getConfig()->get( 'AbuseFilterIsCentral' ) ) {
429 $checkboxes[] = 'global';
430 }
431
432 if ( $filterObj->isThrottled() ) {
433 $throttledActionNames = array_intersect(
434 $filterObj->getActionsNames(),
435 $this->consequencesRegistry->getDangerousActionNames()
436 );
437
438 if ( $throttledActionNames ) {
439 $throttledActionsLocalized = [];
440 foreach ( $throttledActionNames as $actionName ) {
441 $throttledActionsLocalized[] = $this->specsFormatter->getActionMessage( $actionName )->text();
442 }
443
444 $throttledMsg = $this->msg( 'abusefilter-edit-throttled-warning' )
445 ->plaintextParams( $lang->commaList( $throttledActionsLocalized ) )
446 ->params( count( $throttledActionsLocalized ) )
447 ->parseAsBlock();
448 } else {
449 $throttledMsg = $this->msg( 'abusefilter-edit-throttled-warning-no-actions' )
450 ->parseAsBlock();
451 }
452 $flags .= Html::warningBox( $throttledMsg );
453 }
454
455 foreach ( $checkboxes as $checkboxId ) {
456 // Messages that can be used here:
457 // * abusefilter-edit-enabled
458 // * abusefilter-edit-deleted
459 // * abusefilter-edit-hidden
460 // * abusefilter-edit-protected
461 // * abusefilter-edit-global
462 $message = "abusefilter-edit-$checkboxId";
463 // isEnabled(), isDeleted(), isHidden(), isProtected(), isGlobal()
464 $method = 'is' . ucfirst( $checkboxId );
465 $postVar = 'wpFilter' . ucfirst( $checkboxId );
466
467 $checkboxAttribs = [
468 'name' => $postVar,
469 'id' => $postVar,
470 'selected' => $filterObj->$method(),
471 'disabled' => $readOnly
472 ];
473 $labelAttribs = [
474 'label' => $this->msg( $message )->text(),
475 'align' => 'inline',
476 ];
477
478 if ( $checkboxId === 'global' && !$this->afPermManager->canEditGlobal( $user ) ) {
479 $checkboxAttribs['disabled'] = 'disabled';
480 }
481
482 if ( $checkboxId == 'protected' ) {
483 if ( !$this->afPermManager->canViewProtectedVariables( $user ) ) {
484 $checkboxAttribs['classes'] = [ 'oo-ui-element-hidden' ];
485 $labelAttribs['classes'] = [ 'oo-ui-element-hidden' ];
486 } elseif ( $filterObj->isProtected() ) {
487 $checkboxAttribs['disabled'] = true;
488 $labelAttribs['label'] = $this->msg(
489 'abusefilter-edit-protected-variable-already-protected'
490 )->text();
491 } else {
492 $labelAttribs['label'] = new OOUI\HtmlSnippet(
493 $this->msg( $message )->parse()
494 );
495 $labelAttribs['help'] = $this->msg( 'abusefilter-edit-protected-help-message' )->text();
496 $labelAttribs['helpInline'] = true;
497 }
498 }
499
500 // Set readonly on deleted if the filter isn't disabled
501 if ( $checkboxId === 'deleted' && $filterObj->isEnabled() ) {
502 $checkboxAttribs['disabled'] = 'disabled';
503 }
504
505 // Add infusable where needed
506 if ( $checkboxId === 'deleted' || $checkboxId === 'enabled' ) {
507 $checkboxAttribs['infusable'] = true;
508 if ( $checkboxId === 'deleted' ) {
509 $labelAttribs['id'] = $postVar . 'Label';
510 $labelAttribs['infusable'] = true;
511 }
512 }
513
514 $checkbox =
515 new OOUI\FieldLayout(
516 new OOUI\CheckboxInputWidget( $checkboxAttribs ),
517 $labelAttribs
518 );
519 $flags .= $checkbox;
520 }
521
522 $fields['abusefilter-edit-flags'] = $flags;
523
524 if ( $filter !== null ) {
525 $tools = '';
526 if ( $this->afPermManager->canRevertFilterActions( $user ) ) {
527 $tools .= Html::rawElement(
528 'p', [],
529 $this->linkRenderer->makeLink(
530 $this->getTitle( "revert/$filter" ),
531 new HtmlArmor( $this->msg( 'abusefilter-edit-revert' )->parse() )
532 )
533 );
534 }
535
536 if ( $this->afPermManager->canUseTestTools( $user ) ) {
537 // Test link
538 $tools .= Html::rawElement(
539 'p', [],
540 $this->linkRenderer->makeLink(
541 $this->getTitle( "test/$filter" ),
542 new HtmlArmor( $this->msg( 'abusefilter-edit-test-link' )->parse() )
543 )
544 );
545 }
546 // Last modification details
547 $userLink =
548 Linker::userLink( $filterObj->getUserID(), $filterObj->getUserName() ) .
549 Linker::userToolLinks( $filterObj->getUserID(), $filterObj->getUserName() );
550 $fields['abusefilter-edit-lastmod'] =
551 $this->msg( 'abusefilter-edit-lastmod-text' )
552 ->rawParams(
553 $this->getLinkToLatestDiff(
554 $filter,
555 $lang->userTimeAndDate( $filterObj->getTimestamp(), $user )
556 ),
557 $userLink,
558 $this->getLinkToLatestDiff(
559 $filter,
560 $lang->userDate( $filterObj->getTimestamp(), $user )
561 ),
562 $this->getLinkToLatestDiff(
563 $filter,
564 $lang->userTime( $filterObj->getTimestamp(), $user )
565 )
566 )->params(
567 wfEscapeWikiText( $filterObj->getUserName() )
568 )->parse();
569 $history_display = new HtmlArmor( $this->msg( 'abusefilter-edit-viewhistory' )->parse() );
570 $fields['abusefilter-edit-history'] =
571 $this->linkRenderer->makeKnownLink( $this->getTitle( 'history/' . $filter ), $history_display );
572
573 $exportText = $this->filterImporter->encodeData( $filterObj, $actions );
574 $tools .= Html::rawElement( 'a', [ 'href' => '#', 'id' => 'mw-abusefilter-export-link' ],
575 $this->msg( 'abusefilter-edit-export' )->parse() );
576 $tools .=
577 new OOUI\MultilineTextInputWidget( [
578 'id' => 'mw-abusefilter-export',
579 'readOnly' => true,
580 'value' => $exportText,
581 'rows' => 10
582 ] );
583
584 $fields['abusefilter-edit-tools'] = $tools;
585 }
586
587 $form = Xml::fieldset(
588 $this->msg( 'abusefilter-edit-main' )->text(),
589 // TODO: deprecated, use OOUI or Codex widgets instead
590 Xml::buildForm( $fields )
591 );
592 $form .= Xml::fieldset(
593 $this->msg( 'abusefilter-edit-consequences' )->text(),
594 $this->buildConsequenceEditor( $filterObj, $actions )
595 );
596
597 $urlFilter = $filter === null ? 'new' : (string)$filter;
598 if ( !$readOnly ) {
599 $form .=
600 new OOUI\ButtonInputWidget( [
601 'type' => 'submit',
602 'label' => $this->msg( 'abusefilter-edit-save' )->text(),
603 'useInputTag' => true,
604 'accesskey' => 's',
605 'flags' => [ 'progressive', 'primary' ]
606 ] );
607 $form .= Html::hidden(
608 'wpEditToken',
609 $this->getCsrfTokenSet()->getToken( [ 'abusefilter', $urlFilter ] )->toString()
610 );
611 }
612
613 $form = Html::rawElement( 'form',
614 [
615 'action' => $this->getTitle( $urlFilter )->getFullURL(),
616 'method' => 'post',
617 'id' => 'mw-abusefilter-editing-form'
618 ],
619 $form
620 );
621
622 $out->addHTML( $form );
623
624 if ( $history_id ) {
625 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable,PhanTypeMismatchArgumentNullable
626 $out->addWikiMsg( $oldWarningMessage, $history_id, $filter );
627 }
628 }
629
630 /**
631 * Builds the "actions" editor for a given filter.
632 * @param Filter $filterObj
633 * @param array[] $actions Array of rows from the abuse_filter_action table
634 * corresponding to the filter object
635 * @return string HTML text for an action editor.
636 */
637 private function buildConsequenceEditor( Filter $filterObj, array $actions ) {
638 $enabledActions = $this->consequencesRegistry->getAllEnabledActionNames();
639
640 $setActions = [];
641 foreach ( $enabledActions as $action ) {
642 $setActions[$action] = array_key_exists( $action, $actions );
643 }
644
645 $output = '';
646
647 foreach ( $enabledActions as $action ) {
648 $params = $actions[$action] ?? null;
649 $output .= $this->buildConsequenceSelector(
650 $action, $setActions[$action], $filterObj, $params );
651 }
652
653 return $output;
654 }
655
656 /**
657 * @param string $action The action to build an editor for
658 * @param bool $set Whether or not the action is activated
659 * @param Filter $filterObj
660 * @param string[]|null $parameters Action parameters. Null iff $set is false.
661 * @return string|\OOUI\FieldLayout
662 */
663 private function buildConsequenceSelector( $action, $set, $filterObj, ?array $parameters ) {
664 $config = $this->getConfig();
665 $user = $this->getUser();
666 $actions = $this->consequencesRegistry->getAllEnabledActionNames();
667 if ( !in_array( $action, $actions, true ) ) {
668 return '';
669 }
670
671 $readOnly = !$this->afPermManager->canEditFilter( $user, $filterObj );
672
673 switch ( $action ) {
674 case 'throttle':
675 // Throttling is only available via object caching
676 if ( $config->get( MainConfigNames::MainCacheType ) === CACHE_NONE ) {
677 return '';
678 }
679 $throttleSettings =
680 new OOUI\FieldLayout(
681 new OOUI\CheckboxInputWidget( [
682 'name' => 'wpFilterActionThrottle',
683 'id' => 'mw-abusefilter-action-checkbox-throttle',
684 'selected' => $set,
685 'classes' => [ 'mw-abusefilter-action-checkbox' ],
686 'disabled' => $readOnly
687 ]
688 ),
689 [
690 'label' => $this->msg( 'abusefilter-edit-action-throttle' )->text(),
691 'align' => 'inline'
692 ]
693 );
694 $throttleFields = [];
695
696 if ( $set ) {
697 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable $parameters is array here
698 [ $throttleCount, $throttlePeriod ] = explode( ',', $parameters[1], 2 );
699
700 $throttleGroups = array_slice( $parameters, 2 );
701 } else {
702 $throttleCount = 3;
703 $throttlePeriod = 60;
704
705 $throttleGroups = [ 'user' ];
706 }
707
708 $throttleFields[] =
709 new OOUI\FieldLayout(
710 new OOUI\TextInputWidget( [
711 'type' => 'number',
712 'name' => 'wpFilterThrottleCount',
713 'value' => $throttleCount,
714 'readOnly' => $readOnly
715 ]
716 ),
717 [
718 'label' => $this->msg( 'abusefilter-edit-throttle-count' )->text()
719 ]
720 );
721 $throttleFields[] =
722 new OOUI\FieldLayout(
723 new OOUI\TextInputWidget( [
724 'type' => 'number',
725 'name' => 'wpFilterThrottlePeriod',
726 'value' => $throttlePeriod,
727 'readOnly' => $readOnly
728 ]
729 ),
730 [
731 'label' => $this->msg( 'abusefilter-edit-throttle-period' )->text()
732 ]
733 );
734
735 $groupsHelpLink = Html::element(
736 'a',
737 [
738 'href' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/' .
739 'Extension:AbuseFilter/Actions#Throttling',
740 'target' => '_blank'
741 ],
742 $this->msg( 'abusefilter-edit-throttle-groups-help-text' )->text()
743 );
744 $groupsHelp = $this->msg( 'abusefilter-edit-throttle-groups-help' )
745 ->rawParams( $groupsHelpLink )->escaped();
746 $hiddenGroups =
747 new OOUI\FieldLayout(
748 new OOUI\MultilineTextInputWidget( [
749 'name' => 'wpFilterThrottleGroups',
750 'value' => implode( "\n", $throttleGroups ),
751 'rows' => 5,
752 'placeholder' => $this->msg( 'abusefilter-edit-throttle-hidden-placeholder' )->text(),
753 'infusable' => true,
754 'id' => 'mw-abusefilter-hidden-throttle-field',
755 'readOnly' => $readOnly
756 ]
757 ),
758 [
759 'label' => new OOUI\HtmlSnippet(
760 $this->msg( 'abusefilter-edit-throttle-groups' )->parse()
761 ),
762 'align' => 'top',
763 'id' => 'mw-abusefilter-hidden-throttle',
764 'help' => new OOUI\HtmlSnippet( $groupsHelp ),
765 'helpInline' => true
766 ]
767 );
768
769 $throttleFields[] = $hiddenGroups;
770
771 $throttleConfig = [
772 'values' => $throttleGroups,
773 'label' => $this->msg( 'abusefilter-edit-throttle-groups' )->parse(),
774 'disabled' => $readOnly,
775 'help' => $groupsHelp
776 ];
777 $this->getOutput()->addJsConfigVars( 'throttleConfig', $throttleConfig );
778
779 $throttleSettings .=
780 Html::rawElement(
781 'div',
782 [ 'id' => 'mw-abusefilter-throttle-parameters' ],
783 new OOUI\FieldsetLayout( [ 'items' => $throttleFields ] )
784 );
785 return $throttleSettings;
786 case 'disallow':
787 case 'warn':
788 $output = '';
789 $formName = $action === 'warn' ? 'wpFilterActionWarn' : 'wpFilterActionDisallow';
790 $checkbox =
791 new OOUI\FieldLayout(
792 new OOUI\CheckboxInputWidget( [
793 'name' => $formName,
794 // mw-abusefilter-action-checkbox-warn, mw-abusefilter-action-checkbox-disallow
795 'id' => "mw-abusefilter-action-checkbox-$action",
796 'selected' => $set,
797 'classes' => [ 'mw-abusefilter-action-checkbox' ],
798 'disabled' => $readOnly
799 ]
800 ),
801 [
802 // abusefilter-edit-action-warn, abusefilter-edit-action-disallow
803 'label' => $this->msg( "abusefilter-edit-action-$action" )->text(),
804 'align' => 'inline'
805 ]
806 );
807 $output .= $checkbox;
808 $defaultWarnMsg = $config->get( 'AbuseFilterDefaultWarningMessage' );
809 $defaultDisallowMsg = $config->get( 'AbuseFilterDefaultDisallowMessage' );
810
811 if ( $set && isset( $parameters[0] ) ) {
812 $msg = $parameters[0];
813 } elseif (
814 ( $action === 'warn' && isset( $defaultWarnMsg[$filterObj->getGroup()] ) ) ||
815 ( $action === 'disallow' && isset( $defaultDisallowMsg[$filterObj->getGroup()] ) )
816 ) {
817 $msg = $action === 'warn' ? $defaultWarnMsg[$filterObj->getGroup()] :
818 $defaultDisallowMsg[$filterObj->getGroup()];
819 } else {
820 $msg = $action === 'warn' ? 'abusefilter-warning' : 'abusefilter-disallowed';
821 }
822
823 $fields = [];
824 $fields[] =
825 $this->getExistingSelector( $msg, $readOnly, $action );
826 $otherFieldName = $action === 'warn' ? 'wpFilterWarnMessageOther'
827 : 'wpFilterDisallowMessageOther';
828
829 $fields[] =
830 new OOUI\FieldLayout(
831 new OOUI\TextInputWidget( [
832 'name' => $otherFieldName,
833 'value' => $msg,
834 // mw-abusefilter-warn-message-other, mw-abusefilter-disallow-message-other
835 'id' => "mw-abusefilter-$action-message-other",
836 'infusable' => true,
837 'readOnly' => $readOnly
838 ]
839 ),
840 [
841 'label' => new OOUI\HtmlSnippet(
842 // abusefilter-edit-warn-other-label, abusefilter-edit-disallow-other-label
843 $this->msg( "abusefilter-edit-$action-other-label" )->parse()
844 )
845 ]
846 );
847
848 $previewButton =
849 new OOUI\ButtonInputWidget( [
850 // abusefilter-edit-warn-preview, abusefilter-edit-disallow-preview
851 'label' => $this->msg( "abusefilter-edit-$action-preview" )->text(),
852 // mw-abusefilter-warn-preview-button, mw-abusefilter-disallow-preview-button
853 'id' => "mw-abusefilter-$action-preview-button",
854 'infusable' => true,
855 'flags' => 'progressive'
856 ]
857 );
858
859 $buttonGroup = $previewButton;
860 if ( $this->permissionManager->userHasRight( $user, 'editinterface' ) ) {
861 $editButton =
862 new OOUI\ButtonInputWidget( [
863 // abusefilter-edit-warn-edit, abusefilter-edit-disallow-edit
864 'label' => $this->msg( "abusefilter-edit-$action-edit" )->text(),
865 // mw-abusefilter-warn-edit-button, mw-abusefilter-disallow-edit-button
866 'id' => "mw-abusefilter-$action-edit-button"
867 ]
868 );
869 $buttonGroup =
870 new OOUI\Widget( [
871 'content' =>
872 new OOUI\HorizontalLayout( [
873 'items' => [ $previewButton, $editButton ],
874 'classes' => [
875 'mw-abusefilter-preview-buttons',
876 'mw-abusefilter-javascript-tools'
877 ]
878 ] )
879 ] );
880 }
881 $previewHolder = Html::rawElement(
882 'div',
883 [
884 // mw-abusefilter-warn-preview, mw-abusefilter-disallow-preview
885 'id' => "mw-abusefilter-$action-preview",
886 'style' => 'display:none'
887 ],
888 ''
889 );
890 $fields[] = $buttonGroup;
891 $output .=
892 Html::rawElement(
893 'div',
894 // mw-abusefilter-warn-parameters, mw-abusefilter-disallow-parameters
895 [ 'id' => "mw-abusefilter-$action-parameters" ],
896 new OOUI\FieldsetLayout( [ 'items' => $fields ] )
897 ) . $previewHolder;
898
899 return $output;
900 case 'tag':
901 $tags = $set ? $parameters : [];
902 '@phan-var string[] $parameters';
903 $output = '';
904
905 $checkbox =
906 new OOUI\FieldLayout(
907 new OOUI\CheckboxInputWidget( [
908 'name' => 'wpFilterActionTag',
909 'id' => 'mw-abusefilter-action-checkbox-tag',
910 'selected' => $set,
911 'classes' => [ 'mw-abusefilter-action-checkbox' ],
912 'disabled' => $readOnly
913 ]
914 ),
915 [
916 'label' => $this->msg( 'abusefilter-edit-action-tag' )->text(),
917 'align' => 'inline'
918 ]
919 );
920 $output .= $checkbox;
921
922 $tagConfig = [
923 'values' => $tags,
924 'label' => $this->msg( 'abusefilter-edit-tag-tag' )->parse(),
925 'disabled' => $readOnly
926 ];
927 $this->getOutput()->addJsConfigVars( 'tagConfig', $tagConfig );
928
929 $hiddenTags =
930 new OOUI\FieldLayout(
931 new OOUI\MultilineTextInputWidget( [
932 'name' => 'wpFilterTags',
933 'value' => implode( ',', $tags ),
934 'rows' => 5,
935 'placeholder' => $this->msg( 'abusefilter-edit-tag-hidden-placeholder' )->text(),
936 'infusable' => true,
937 'id' => 'mw-abusefilter-hidden-tag-field',
938 'readOnly' => $readOnly
939 ]
940 ),
941 [
942 'label' => new OOUI\HtmlSnippet(
943 $this->msg( 'abusefilter-edit-tag-tag' )->parse()
944 ),
945 'align' => 'top',
946 'id' => 'mw-abusefilter-hidden-tag'
947 ]
948 );
949 $output .=
950 Html::rawElement( 'div',
951 [ 'id' => 'mw-abusefilter-tag-parameters' ],
952 $hiddenTags
953 );
954 return $output;
955 case 'block':
956 if ( $set && count( $parameters ) === 3 ) {
957 // Both blocktalk and custom block durations available
958 [ $blockTalk, $defaultAnonDuration, $defaultUserDuration ] = $parameters;
959 } else {
960 if ( $set && count( $parameters ) === 1 ) {
961 // Only blocktalk available
962 $blockTalk = $parameters[0];
963 }
964 $defaultAnonDuration = $config->get( 'AbuseFilterAnonBlockDuration' ) ??
965 $config->get( 'AbuseFilterBlockDuration' );
966 $defaultUserDuration = $config->get( 'AbuseFilterBlockDuration' );
967 }
968 $suggestedBlocks = $this->getLanguage()->getBlockDurations( false );
969 $suggestedBlocks = self::normalizeBlocks( $suggestedBlocks );
970
971 $output = '';
972 $checkbox =
973 new OOUI\FieldLayout(
974 new OOUI\CheckboxInputWidget( [
975 'name' => 'wpFilterActionBlock',
976 'id' => 'mw-abusefilter-action-checkbox-block',
977 'selected' => $set,
978 'classes' => [ 'mw-abusefilter-action-checkbox' ],
979 'disabled' => $readOnly
980 ]
981 ),
982 [
983 'label' => $this->msg( 'abusefilter-edit-action-block' )->text(),
984 'align' => 'inline'
985 ]
986 );
987 $output .= $checkbox;
988
989 $suggestedBlocks = Html::listDropdownOptionsOoui( $suggestedBlocks );
990
991 $anonDuration =
992 new OOUI\DropdownInputWidget( [
993 'name' => 'wpBlockAnonDuration',
994 'options' => $suggestedBlocks,
995 'value' => $defaultAnonDuration,
996 'disabled' => $readOnly
997 ] );
998
999 $userDuration =
1000 new OOUI\DropdownInputWidget( [
1001 'name' => 'wpBlockUserDuration',
1002 'options' => $suggestedBlocks,
1003 'value' => $defaultUserDuration,
1004 'disabled' => $readOnly
1005 ] );
1006
1007 $blockOptions = [];
1008 if ( $config->get( MainConfigNames::BlockAllowsUTEdit ) === true ) {
1009 $talkCheckbox =
1010 new OOUI\FieldLayout(
1011 new OOUI\CheckboxInputWidget( [
1012 'name' => 'wpFilterBlockTalk',
1013 'id' => 'mw-abusefilter-action-checkbox-blocktalk',
1014 'selected' => isset( $blockTalk ) && $blockTalk === 'blocktalk',
1015 'classes' => [ 'mw-abusefilter-action-checkbox' ],
1016 'disabled' => $readOnly
1017 ]
1018 ),
1019 [
1020 'label' => $this->msg( 'abusefilter-edit-action-blocktalk' )->text(),
1021 'align' => 'left'
1022 ]
1023 );
1024
1025 $blockOptions[] = $talkCheckbox;
1026 }
1027 $blockOptions[] =
1028 new OOUI\FieldLayout(
1029 $anonDuration,
1030 [
1031 'label' => $this->msg( 'abusefilter-edit-block-anon-durations' )->text()
1032 ]
1033 );
1034 $blockOptions[] =
1035 new OOUI\FieldLayout(
1036 $userDuration,
1037 [
1038 'label' => $this->msg( 'abusefilter-edit-block-user-durations' )->text()
1039 ]
1040 );
1041
1042 $output .= Html::rawElement(
1043 'div',
1044 [ 'id' => 'mw-abusefilter-block-parameters' ],
1045 new OOUI\FieldsetLayout( [ 'items' => $blockOptions ] )
1046 );
1047
1048 return $output;
1049
1050 default:
1051 // Give grep a chance to find the usages:
1052 // abusefilter-edit-action-disallow,
1053 // abusefilter-edit-action-blockautopromote,
1054 // abusefilter-edit-action-degroup,
1055 // abusefilter-edit-action-rangeblock,
1056 $message = 'abusefilter-edit-action-' . $action;
1057 $form_field = 'wpFilterAction' . ucfirst( $action );
1058 $status = $set;
1059
1060 $thisAction =
1061 new OOUI\FieldLayout(
1062 new OOUI\CheckboxInputWidget( [
1063 'name' => $form_field,
1064 'id' => "mw-abusefilter-action-checkbox-$action",
1065 'selected' => $status,
1066 'classes' => [ 'mw-abusefilter-action-checkbox' ],
1067 'disabled' => $readOnly
1068 ]
1069 ),
1070 [
1071 'label' => $this->msg( $message )->text(),
1072 'align' => 'inline'
1073 ]
1074 );
1075 return $thisAction;
1076 }
1077 }
1078
1079 /**
1080 * @param string $warnMsg
1081 * @param bool $readOnly
1082 * @param string $action
1083 * @return \OOUI\FieldLayout
1084 */
1085 public function getExistingSelector( $warnMsg, $readOnly = false, $action = 'warn' ) {
1086 if ( $action === 'warn' ) {
1087 $action = 'warning';
1088 $formId = 'warn';
1089 $inputName = 'wpFilterWarnMessage';
1090 } elseif ( $action === 'disallow' ) {
1091 $action = 'disallowed';
1092 $formId = 'disallow';
1093 $inputName = 'wpFilterDisallowMessage';
1094 } else {
1095 throw new UnexpectedValueException( "Unexpected action value $action" );
1096 }
1097
1098 $existingSelector =
1099 new OOUI\DropdownInputWidget( [
1100 'name' => $inputName,
1101 // mw-abusefilter-warn-message-existing, mw-abusefilter-disallow-message-existing
1102 'id' => "mw-abusefilter-$formId-message-existing",
1103 // abusefilter-warning, abusefilter-disallowed
1104 'value' => $warnMsg === "abusefilter-$action" ? "abusefilter-$action" : 'other',
1105 'infusable' => true
1106 ] );
1107
1108 // abusefilter-warning, abusefilter-disallowed
1109 $options = [ "abusefilter-$action" => "abusefilter-$action" ];
1110
1111 if ( $readOnly ) {
1112 $existingSelector->setDisabled( true );
1113 } else {
1114 // Find other messages.
1115 $dbr = $this->lbFactory->getReplicaDatabase();
1116 $pageTitlePrefix = "Abusefilter-$action";
1117 $titles = $dbr->newSelectQueryBuilder()
1118 ->select( 'page_title' )
1119 ->from( 'page' )
1120 ->where( [
1121 'page_namespace' => 8,
1122 $dbr->expr( 'page_title', IExpression::LIKE, new LikeValue( $pageTitlePrefix, $dbr->anyString() ) )
1123 ] )
1124 ->caller( __METHOD__ )
1125 ->fetchFieldValues();
1126
1127 $lang = $this->getLanguage();
1128 foreach ( $titles as $title ) {
1129 if ( $lang->lcfirst( $title ) === $lang->lcfirst( $warnMsg ) ) {
1130 $existingSelector->setValue( $lang->lcfirst( $warnMsg ) );
1131 }
1132
1133 if ( $title !== "Abusefilter-$action" ) {
1134 $options[ $lang->lcfirst( $title ) ] = $lang->lcfirst( $title );
1135 }
1136 }
1137 }
1138
1139 // abusefilter-edit-warn-other, abusefilter-edit-disallow-other
1140 $options[ $this->msg( "abusefilter-edit-$formId-other" )->text() ] = 'other';
1141
1142 $options = Html::listDropdownOptionsOoui( $options );
1143 $existingSelector->setOptions( $options );
1144
1145 $existingSelector =
1146 new OOUI\FieldLayout(
1147 $existingSelector,
1148 [
1149 // abusefilter-edit-warn-message, abusefilter-edit-disallow-message
1150 'label' => $this->msg( "abusefilter-edit-$formId-message" )->text()
1151 ]
1152 );
1153
1154 return $existingSelector;
1155 }
1156
1157 /**
1158 * @todo Maybe we should also check if global values belong to $durations
1159 * and determine the right point to add them if missing.
1160 *
1161 * @param string[] $durations
1162 * @return string[]
1163 */
1164 private static function normalizeBlocks( array $durations ) {
1165 global $wgAbuseFilterBlockDuration, $wgAbuseFilterAnonBlockDuration;
1166 // We need to have same values since it may happen that ipblocklist
1167 // and one (or both) of the global variables use different wording
1168 // for the same duration. In such case, when setting the default of
1169 // the dropdowns it would fail.
1170 $anonDuration = self::getAbsoluteBlockDuration( $wgAbuseFilterAnonBlockDuration ??
1171 $wgAbuseFilterBlockDuration );
1172 $userDuration = self::getAbsoluteBlockDuration( $wgAbuseFilterBlockDuration );
1173 foreach ( $durations as &$duration ) {
1174 $currentDuration = self::getAbsoluteBlockDuration( $duration );
1175
1176 if ( $duration !== $wgAbuseFilterBlockDuration &&
1177 $currentDuration === $userDuration ) {
1178 $duration = $wgAbuseFilterBlockDuration;
1179
1180 } elseif ( $duration !== $wgAbuseFilterAnonBlockDuration &&
1181 $currentDuration === $anonDuration ) {
1182 $duration = $wgAbuseFilterAnonBlockDuration;
1183 }
1184 }
1185
1186 return $durations;
1187 }
1188
1189 /**
1190 * Converts a string duration to an absolute timestamp, i.e. unrelated to the current
1191 * time, taking into account infinity durations as well. The second parameter of
1192 * strtotime is set to 0 in order to convert the duration in seconds (instead of
1193 * a timestamp), thus making it unaffected by the execution time of the code.
1194 *
1195 * @param string $duration
1196 * @return string|int
1197 */
1198 private static function getAbsoluteBlockDuration( $duration ) {
1199 if ( wfIsInfinity( $duration ) ) {
1200 return 'infinity';
1201 }
1202 return strtotime( $duration, 0 );
1203 }
1204
1205 /**
1206 * Loads filter data from the database by ID.
1207 * @param int|null $id The filter's ID number, or null for a new filter
1208 * @return Filter
1209 * @throws FilterNotFoundException
1210 */
1211 private function loadFilterData( ?int $id ): Filter {
1212 if ( $id === null ) {
1213 return MutableFilter::newDefault();
1214 }
1215
1216 $flags = $this->getRequest()->wasPosted()
1217 // Load from primary database to avoid unintended reversions where there's replication lag.
1218 ? IDBAccessObject::READ_LATEST
1219 : IDBAccessObject::READ_NORMAL;
1220
1221 return $this->filterLookup->getFilter( $id, false, $flags );
1222 }
1223
1224 /**
1225 * Load filter data to show in the edit view from the DB.
1226 * @param int|null $filter The filter ID being requested or null for a new filter
1227 * @param int|null $history_id If any, the history ID being requested.
1228 * @return Filter|null Null if the filter does not exist.
1229 */
1230 private function loadFromDatabase( ?int $filter, $history_id = null ): ?Filter {
1231 if ( $history_id ) {
1232 try {
1233 return $this->filterLookup->getFilterVersion( $history_id );
1234 } catch ( FilterVersionNotFoundException $_ ) {
1235 return null;
1236 }
1237 } else {
1238 return $this->loadFilterData( $filter );
1239 }
1240 }
1241
1242 /**
1243 * Load data from the HTTP request. Used for saving the filter, and when the token doesn't match
1244 * @param int|null $filter
1245 * @return Filter[]
1246 */
1247 private function loadRequest( ?int $filter ): array {
1248 $request = $this->getRequest();
1249 if ( !$request->wasPosted() ) {
1250 // Sanity
1251 throw new LogicException( __METHOD__ . ' called without the request being POSTed.' );
1252 }
1253
1254 $origFilter = $this->loadFilterData( $filter );
1255
1256 /** @var MutableFilter $newFilter */
1257 $newFilter = $origFilter instanceof MutableFilter
1258 ? clone $origFilter
1259 : MutableFilter::newFromParentFilter( $origFilter );
1260
1261 if ( $filter !== null ) {
1262 // Unchangeable values
1263 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
1264 $newFilter->setThrottled( $origFilter->isThrottled() );
1265 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
1266 $newFilter->setHitCount( $origFilter->getHitCount() );
1267 // These are needed if the save fails and the filter is not new
1268 $newFilter->setID( $origFilter->getID() );
1269 $newFilter->setUserID( $origFilter->getUserID() );
1270 $newFilter->setUserName( $origFilter->getUserName() );
1271 $newFilter->setTimestamp( $origFilter->getTimestamp() );
1272 }
1273
1274 $newFilter->setName( trim( $request->getVal( 'wpFilterDescription' ) ?? '' ) );
1275 $newFilter->setRules( trim( $request->getVal( 'wpFilterRules' ) ?? '' ) );
1276 $newFilter->setComments( trim( $request->getVal( 'wpFilterNotes' ) ?? '' ) );
1277
1278 $newFilter->setGroup( $request->getVal( 'wpFilterGroup', 'default' ) );
1279
1280 $newFilter->setDeleted( $request->getCheck( 'wpFilterDeleted' ) );
1281 $newFilter->setEnabled( $request->getCheck( 'wpFilterEnabled' ) );
1282 $newFilter->setHidden( $request->getCheck( 'wpFilterHidden' ) );
1283 $newFilter->setProtected( $request->getCheck( 'wpFilterProtected' ) );
1284 $newFilter->setGlobal( $request->getCheck( 'wpFilterGlobal' )
1285 && $this->getConfig()->get( 'AbuseFilterIsCentral' ) );
1286
1287 $actions = $this->loadActions();
1288
1289 $newFilter->setActions( $actions );
1290
1291 return [ $newFilter, $origFilter ];
1292 }
1293
1294 /**
1295 * @return Filter|null
1296 */
1297 private function loadImportRequest(): ?Filter {
1298 $request = $this->getRequest();
1299 if ( !$request->wasPosted() ) {
1300 // Sanity
1301 throw new LogicException( __METHOD__ . ' called without the request being POSTed.' );
1302 }
1303
1304 try {
1305 $filter = $this->filterImporter->decodeData( $request->getVal( 'wpImportText' ) );
1306 } catch ( InvalidImportDataException $_ ) {
1307 return null;
1308 }
1309
1310 return $filter;
1311 }
1312
1313 /**
1314 * @return array[]
1315 */
1316 private function loadActions(): array {
1317 $request = $this->getRequest();
1318 $allActions = $this->consequencesRegistry->getAllEnabledActionNames();
1319 $actions = [];
1320 foreach ( $allActions as $action ) {
1321 // Check if it's set
1322 $enabled = $request->getCheck( 'wpFilterAction' . ucfirst( $action ) );
1323
1324 if ( $enabled ) {
1325 $parameters = [];
1326
1327 if ( $action === 'throttle' ) {
1328 // We need to load the parameters
1329 $throttleCount = $request->getIntOrNull( 'wpFilterThrottleCount' );
1330 $throttlePeriod = $request->getIntOrNull( 'wpFilterThrottlePeriod' );
1331 // First explode with \n, which is the delimiter used in the textarea
1332 $rawGroups = explode( "\n", $request->getText( 'wpFilterThrottleGroups' ) );
1333 // Trim any space, both as an actual group and inside subgroups
1334 $throttleGroups = [];
1335 foreach ( $rawGroups as $group ) {
1336 if ( strpos( $group, ',' ) !== false ) {
1337 $subGroups = explode( ',', $group );
1338 $throttleGroups[] = implode( ',', array_map( 'trim', $subGroups ) );
1339 } elseif ( trim( $group ) !== '' ) {
1340 $throttleGroups[] = trim( $group );
1341 }
1342 }
1343
1344 $parameters[0] = $this->filter;
1345 $parameters[1] = "$throttleCount,$throttlePeriod";
1346 $parameters = array_merge( $parameters, $throttleGroups );
1347 } elseif ( $action === 'warn' ) {
1348 $specMsg = $request->getVal( 'wpFilterWarnMessage' );
1349
1350 if ( $specMsg === 'other' ) {
1351 $specMsg = $request->getVal( 'wpFilterWarnMessageOther' );
1352 }
1353
1354 $parameters[0] = $specMsg;
1355 } elseif ( $action === 'block' ) {
1356 // TODO: Should save a boolean
1357 $parameters[0] = $request->getCheck( 'wpFilterBlockTalk' ) ?
1358 'blocktalk' : 'noTalkBlockSet';
1359 $parameters[1] = $request->getVal( 'wpBlockAnonDuration' );
1360 $parameters[2] = $request->getVal( 'wpBlockUserDuration' );
1361 } elseif ( $action === 'disallow' ) {
1362 $specMsg = $request->getVal( 'wpFilterDisallowMessage' );
1363
1364 if ( $specMsg === 'other' ) {
1365 $specMsg = $request->getVal( 'wpFilterDisallowMessageOther' );
1366 }
1367
1368 $parameters[0] = $specMsg;
1369 } elseif ( $action === 'tag' ) {
1370 $parameters = explode( ',', trim( $request->getText( 'wpFilterTags' ) ) );
1371 if ( $parameters === [ '' ] ) {
1372 // Since it's not possible to manually add an empty tag, this only happens
1373 // if the form is submitted without touching the tag input field.
1374 // We pass an empty array so that the widget won't show an empty tag in the topbar
1375 $parameters = [];
1376 }
1377 }
1378
1379 $actions[$action] = $parameters;
1380 }
1381 }
1382 return $actions;
1383 }
1384
1385 /**
1386 * Exports the default warning and disallow messages to a JS variable
1387 */
1388 private function exposeMessages() {
1389 $this->getOutput()->addJsConfigVars(
1390 'wgAbuseFilterDefaultWarningMessage',
1391 $this->getConfig()->get( 'AbuseFilterDefaultWarningMessage' )
1392 );
1393 $this->getOutput()->addJsConfigVars(
1394 'wgAbuseFilterDefaultDisallowMessage',
1395 $this->getConfig()->get( 'AbuseFilterDefaultDisallowMessage' )
1396 );
1397 }
1398 }