Introduce EditBoxBuilderFactory service and EditBoxBuilder

It makes sense to look at this and Iedd7a5dca24 together,
as this patch itself doesn't really fix anything.

Change-Id: Ifef5266b1803d1a96489789b08d9beed044d908f
This commit is contained in:
Matěj Suchánek 2020-11-24 13:16:41 +01:00
parent b33da096ba
commit 1ad77dc9fb
11 changed files with 375 additions and 183 deletions

View file

@ -180,6 +180,8 @@
"MediaWiki\\Extension\\AbuseFilter\\FilterValidator": "includes/FilterValidator.php",
"MediaWiki\\Extension\\AbuseFilter\\FilterCompare": "includes/FilterCompare.php",
"MediaWiki\\Extension\\AbuseFilter\\FilterImporter": "includes/FilterImporter.php",
"MediaWiki\\Extension\\AbuseFilter\\EditBoxBuilder": "includes/EditBoxBuilder.php",
"MediaWiki\\Extension\\AbuseFilter\\EditBoxBuilderFactory": "includes/EditBoxBuilderFactory.php",
"MediaWiki\\Extension\\AbuseFilter\\InvalidImportDataException": "includes/InvalidImportDataException.php",
"MediaWiki\\Extension\\AbuseFilter\\FilterStore": "includes/FilterStore.php",
"MediaWiki\\Extension\\AbuseFilter\\ConsequencesFactory": "includes/ConsequencesFactory.php",

View file

@ -119,4 +119,11 @@ class AbuseFilterServices {
public static function getConsequencesFactory() : ConsequencesFactory {
return MediaWikiServices::getInstance()->getService( ConsequencesFactory::SERVICE_NAME );
}
/**
* @return EditBoxBuilderFactory
*/
public static function getEditBoxBuilderFactory() : EditBoxBuilderFactory {
return MediaWikiServices::getInstance()->getService( EditBoxBuilderFactory::SERVICE_NAME );
}
}

236
includes/EditBoxBuilder.php Normal file
View file

@ -0,0 +1,236 @@
<?php
namespace MediaWiki\Extension\AbuseFilter;
use AbuseFilterParser;
use AbuseFilterTokenizer;
use MessageLocalizer;
use OOUI;
use OutputPage;
use User;
use Xml;
/**
* Class responsible for building filter edit boxes
* @todo Consider splitting to different classes for each editor (plain, Ace, etc.)
*/
class EditBoxBuilder {
/** @var AbuseFilterPermissionManager */
private $afPermManager;
/** @var KeywordsManager */
private $keywordsManager;
/** @var bool */
private $isCodeEditorLoaded;
/** @var MessageLocalizer */
private $localizer;
/** @var User */
private $user;
/** @var OutputPage */
private $output;
/**
* @param AbuseFilterPermissionManager $afPermManager
* @param KeywordsManager $keywordsManager
* @param bool $isCodeEditorLoaded
* @param MessageLocalizer $messageLocalizer
* @param User $user
* @param OutputPage $output
*/
public function __construct(
AbuseFilterPermissionManager $afPermManager,
KeywordsManager $keywordsManager,
bool $isCodeEditorLoaded,
MessageLocalizer $messageLocalizer,
User $user,
OutputPage $output
) {
$this->afPermManager = $afPermManager;
$this->keywordsManager = $keywordsManager;
$this->isCodeEditorLoaded = $isCodeEditorLoaded;
$this->localizer = $messageLocalizer;
$this->user = $user;
$this->output = $output;
}
/**
* @param string $rules
* @param bool $addResultDiv
* @param bool $externalForm
* @param bool $needsModifyRights
* @param-taint $rules none
* @return string
*/
public function buildEditBox(
string $rules,
bool $addResultDiv = true,
bool $externalForm = false,
bool $needsModifyRights = true
) : string {
$this->output->enableOOUI();
// Rules are in English
$editorAttribs = [ 'dir' => 'ltr' ];
$noTestAttrib = [];
$isUserAllowed = $needsModifyRights ?
$this->afPermManager->canEdit( $this->user ) :
$this->afPermManager->canViewPrivateFilters( $this->user );
if ( !$isUserAllowed ) {
$noTestAttrib['disabled'] = 'disabled';
$addResultDiv = false;
}
$rules = rtrim( $rules ) . "\n";
$switchEditor = null;
$rulesContainer = '';
if ( $this->isCodeEditorLoaded ) {
$aceAttribs = [
'name' => 'wpAceFilterEditor',
'id' => 'wpAceFilterEditor',
'class' => 'mw-abusefilter-editor'
];
$attribs = array_merge( $editorAttribs, $aceAttribs );
$switchEditor =
new OOUI\ButtonWidget(
[
'label' => $this->localizer->msg( 'abusefilter-edit-switch-editor' )->text(),
'id' => 'mw-abusefilter-switcheditor'
] + $noTestAttrib
);
$rulesContainer .= Xml::element( 'div', $attribs, $rules );
// Add Ace configuration variable
$editorConfig = $this->getAceConfig( $isUserAllowed );
$this->output->addJsConfigVars( 'aceConfig', $editorConfig );
}
// Build a dummy textarea to be used: for submitting form if CodeEditor isn't installed,
// and in case JS is disabled (with or without CodeEditor)
if ( !$isUserAllowed ) {
$editorAttribs['readonly'] = 'readonly';
}
if ( $externalForm ) {
$editorAttribs['form'] = 'wpFilterForm';
}
$rulesContainer .= Xml::textarea( 'wpFilterRules', $rules, 40, 15, $editorAttribs );
if ( $isUserAllowed ) {
// Generate builder drop-down
$rawDropDown = $this->keywordsManager->getBuilderValues();
// The array needs to be rearranged to be understood by OOUI. It comes with the format
// [ group-msg-key => [ text-to-add => text-msg-key ] ] and we need it as
// [ group-msg => [ text-msg => text-to-add ] ]
// Also, the 'other' element must be the first one.
$dropDownOptions = [ $this->localizer->msg( 'abusefilter-edit-builder-select' )->text() => 'other' ];
foreach ( $rawDropDown as $group => $values ) {
// Give grep a chance to find the usages:
// abusefilter-edit-builder-group-op-arithmetic, abusefilter-edit-builder-group-op-comparison,
// abusefilter-edit-builder-group-op-bool, abusefilter-edit-builder-group-misc,
// abusefilter-edit-builder-group-funcs, abusefilter-edit-builder-group-vars
$localisedGroup = $this->localizer->msg( "abusefilter-edit-builder-group-$group" )->text();
$dropDownOptions[ $localisedGroup ] = array_flip( $values );
$newKeys = array_map(
function ( $key ) use ( $group ) {
return $this->localizer->msg( "abusefilter-edit-builder-$group-$key" )->text();
},
array_keys( $dropDownOptions[ $localisedGroup ] )
);
$dropDownOptions[ $localisedGroup ] = array_combine(
$newKeys, $dropDownOptions[ $localisedGroup ] );
}
$dropDownList = Xml::listDropDownOptionsOoui( $dropDownOptions );
$dropDown = new OOUI\DropdownInputWidget( [
'name' => 'wpFilterBuilder',
'inputId' => 'wpFilterBuilder',
'options' => $dropDownList
] );
$formElements = [ new OOUI\FieldLayout( $dropDown ) ];
// Button for syntax check
$syntaxCheck =
new OOUI\ButtonWidget(
[
'label' => $this->localizer->msg( 'abusefilter-edit-check' )->text(),
'id' => 'mw-abusefilter-syntaxcheck'
] + $noTestAttrib
);
// Button for switching editor (if Ace is used)
if ( $switchEditor !== null ) {
$formElements[] = new OOUI\FieldLayout(
new OOUI\Widget( [
'content' => new OOUI\HorizontalLayout( [
'items' => [ $switchEditor, $syntaxCheck ]
] )
] )
);
} else {
$formElements[] = new OOUI\FieldLayout( $syntaxCheck );
}
$fieldSet = new OOUI\FieldsetLayout( [
'items' => $formElements,
'classes' => [ 'mw-abusefilter-edit-buttons', 'mw-abusefilter-javascript-tools' ]
] );
$rulesContainer .= $fieldSet;
}
if ( $addResultDiv ) {
$rulesContainer .= Xml::element( 'div',
[ 'id' => 'mw-abusefilter-syntaxresult', 'style' => 'display: none;' ],
'&#160;' );
}
// Add script
$this->output->addModules( 'ext.abuseFilter.edit' );
return $rulesContainer;
}
/**
* Extract values for syntax highlight
*
* @param bool $canEdit
* @return array
*/
private function getAceConfig( bool $canEdit ): array {
$values = $this->keywordsManager->getBuilderValues();
$deprecatedVars = $this->keywordsManager->getDeprecatedVariables();
$builderVariables = implode( '|', array_keys( $values['vars'] ) );
$builderFunctions = implode( '|', array_keys( AbuseFilterParser::FUNCTIONS ) );
// AbuseFilterTokenizer::KEYWORDS also includes constants (true, false and null),
// but Ace redefines these constants afterwards so this will not be an issue
$builderKeywords = implode( '|', AbuseFilterTokenizer::KEYWORDS );
// Extract operators from tokenizer like we do in AbuseFilterParserTest
$operators = implode( '|', array_map( function ( $op ) {
return preg_quote( $op, '/' );
}, AbuseFilterTokenizer::OPERATORS ) );
$deprecatedVariables = implode( '|', array_keys( $deprecatedVars ) );
$disabledVariables = implode( '|', array_keys( $this->keywordsManager->getDisabledVariables() ) );
return [
'variables' => $builderVariables,
'functions' => $builderFunctions,
'keywords' => $builderKeywords,
'operators' => $operators,
'deprecated' => $deprecatedVariables,
'disabled' => $disabledVariables,
'aceReadOnly' => !$canEdit
];
}
}

View file

@ -0,0 +1,61 @@
<?php
namespace MediaWiki\Extension\AbuseFilter;
use MessageLocalizer;
use OutputPage;
use User;
/**
* Factory for EditBoxBuilder objects
*/
class EditBoxBuilderFactory {
public const SERVICE_NAME = 'AbuseFilterEditBoxBuilderFactory';
/** @var AbuseFilterPermissionManager */
private $afPermManager;
/** @var KeywordsManager */
private $keywordsManager;
/** @var bool */
private $isCodeEditorLoaded;
/**
* @param AbuseFilterPermissionManager $afPermManager
* @param KeywordsManager $keywordsManager
* @param bool $isCodeEditorLoaded
*/
public function __construct(
AbuseFilterPermissionManager $afPermManager,
KeywordsManager $keywordsManager,
bool $isCodeEditorLoaded
) {
$this->afPermManager = $afPermManager;
$this->keywordsManager = $keywordsManager;
$this->isCodeEditorLoaded = $isCodeEditorLoaded;
}
/**
* @param MessageLocalizer $messageLocalizer
* @param User $user
* @param OutputPage $output
* @return EditBoxBuilder
*/
public function newEditBoxBuilder(
MessageLocalizer $messageLocalizer,
User $user,
OutputPage $output
) : EditBoxBuilder {
return new EditBoxBuilder(
$this->afPermManager,
$this->keywordsManager,
$this->isCodeEditorLoaded,
$messageLocalizer,
$user,
$output
);
}
}

View file

@ -7,6 +7,7 @@ use MediaWiki\Extension\AbuseFilter\CentralDBManager;
use MediaWiki\Extension\AbuseFilter\ChangeTagger;
use MediaWiki\Extension\AbuseFilter\ChangeTagsManager;
use MediaWiki\Extension\AbuseFilter\ConsequencesFactory;
use MediaWiki\Extension\AbuseFilter\EditBoxBuilderFactory;
use MediaWiki\Extension\AbuseFilter\FilterCompare;
use MediaWiki\Extension\AbuseFilter\FilterImporter;
use MediaWiki\Extension\AbuseFilter\FilterLookup;
@ -159,6 +160,13 @@ return [
RequestContext::getMain()->getRequest()->getIP()
);
},
EditBoxBuilderFactory::SERVICE_NAME => function ( MediaWikiServices $services ): EditBoxBuilderFactory {
return new EditBoxBuilderFactory(
$services->get( PermManager::SERVICE_NAME ),
$services->get( KeywordsManager::SERVICE_NAME ),
ExtensionRegistry::getInstance()->isLoaded( 'CodeEditor' )
);
},
];
// @codeCoverageIgnoreEnd

View file

@ -1,6 +1,5 @@
<?php
use MediaWiki\Extension\AbuseFilter\AbuseFilterServices;
use MediaWiki\Linker\LinkRenderer;
use Wikimedia\Rdbms\IDatabase;
@ -48,151 +47,6 @@ abstract class AbuseFilterView extends ContextSource {
*/
abstract public function show();
/**
* @param string $rules
* @param bool $addResultDiv
* @param bool $externalForm
* @param bool $needsModifyRights
* @param-taint $rules none
* @return string
*/
protected function buildEditBox(
$rules,
$addResultDiv = true,
$externalForm = false,
$needsModifyRights = true
) {
$this->getOutput()->enableOOUI();
$user = $this->getUser();
$afPermManager = AbuseFilterServices::getPermissionManager();
// Rules are in English
$editorAttribs = [ 'dir' => 'ltr' ];
$noTestAttrib = [];
$isUserAllowed = $needsModifyRights ?
$afPermManager->canEdit( $user ) :
$afPermManager->canViewPrivateFilters( $user );
if ( !$isUserAllowed ) {
$noTestAttrib['disabled'] = 'disabled';
$addResultDiv = false;
}
$rules = rtrim( $rules ) . "\n";
$switchEditor = null;
$rulesContainer = '';
if ( ExtensionRegistry::getInstance()->isLoaded( 'CodeEditor' ) ) {
$aceAttribs = [
'name' => 'wpAceFilterEditor',
'id' => 'wpAceFilterEditor',
'class' => 'mw-abusefilter-editor'
];
$attribs = array_merge( $editorAttribs, $aceAttribs );
$switchEditor =
new OOUI\ButtonWidget(
[
'label' => $this->msg( 'abusefilter-edit-switch-editor' )->text(),
'id' => 'mw-abusefilter-switcheditor'
] + $noTestAttrib
);
$rulesContainer .= Xml::element( 'div', $attribs, $rules );
// Add Ace configuration variable
$editorConfig = $this->getAceConfig( $isUserAllowed );
$this->getOutput()->addJsConfigVars( 'aceConfig', $editorConfig );
}
// Build a dummy textarea to be used: for submitting form if CodeEditor isn't installed,
// and in case JS is disabled (with or without CodeEditor)
if ( !$isUserAllowed ) {
$editorAttribs['readonly'] = 'readonly';
}
if ( $externalForm ) {
$editorAttribs['form'] = 'wpFilterForm';
}
$rulesContainer .= Xml::textarea( 'wpFilterRules', $rules, 40, 15, $editorAttribs );
if ( $isUserAllowed ) {
$keywordsManager = AbuseFilterServices::getKeywordsManager();
// Generate builder drop-down
$rawDropDown = $keywordsManager->getBuilderValues();
// The array needs to be rearranged to be understood by OOUI. It comes with the format
// [ group-msg-key => [ text-to-add => text-msg-key ] ] and we need it as
// [ group-msg => [ text-msg => text-to-add ] ]
// Also, the 'other' element must be the first one.
$dropDownOptions = [ $this->msg( 'abusefilter-edit-builder-select' )->text() => 'other' ];
foreach ( $rawDropDown as $group => $values ) {
// Give grep a chance to find the usages:
// abusefilter-edit-builder-group-op-arithmetic, abusefilter-edit-builder-group-op-comparison,
// abusefilter-edit-builder-group-op-bool, abusefilter-edit-builder-group-misc,
// abusefilter-edit-builder-group-funcs, abusefilter-edit-builder-group-vars
$localisedGroup = $this->msg( "abusefilter-edit-builder-group-$group" )->text();
$dropDownOptions[ $localisedGroup ] = array_flip( $values );
$newKeys = array_map(
function ( $key ) use ( $group ) {
return $this->msg( "abusefilter-edit-builder-$group-$key" )->text();
},
array_keys( $dropDownOptions[ $localisedGroup ] )
);
$dropDownOptions[ $localisedGroup ] = array_combine(
$newKeys, $dropDownOptions[ $localisedGroup ] );
}
$dropDownList = Xml::listDropDownOptionsOoui( $dropDownOptions );
$dropDown = new OOUI\DropdownInputWidget( [
'name' => 'wpFilterBuilder',
'inputId' => 'wpFilterBuilder',
'options' => $dropDownList
] );
$formElements = [ new OOUI\FieldLayout( $dropDown ) ];
// Button for syntax check
$syntaxCheck =
new OOUI\ButtonWidget(
[
'label' => $this->msg( 'abusefilter-edit-check' )->text(),
'id' => 'mw-abusefilter-syntaxcheck'
] + $noTestAttrib
);
// Button for switching editor (if Ace is used)
if ( $switchEditor !== null ) {
$formElements[] = new OOUI\FieldLayout(
new OOUI\Widget( [
'content' => new OOUI\HorizontalLayout( [
'items' => [ $switchEditor, $syntaxCheck ]
] )
] )
);
} else {
$formElements[] = new OOUI\FieldLayout( $syntaxCheck );
}
$fieldSet = new OOUI\FieldsetLayout( [
'items' => $formElements,
'classes' => [ 'mw-abusefilter-edit-buttons', 'mw-abusefilter-javascript-tools' ]
] );
$rulesContainer .= $fieldSet;
}
if ( $addResultDiv ) {
$rulesContainer .= Xml::element( 'div',
[ 'id' => 'mw-abusefilter-syntaxresult', 'style' => 'display: none;' ],
'&#160;' );
}
// Add script
$this->getOutput()->addModules( 'ext.abuseFilter.edit' );
return $rulesContainer;
}
/**
* Build input and button for loading a filter
*
@ -320,37 +174,4 @@ abstract class AbuseFilterView extends ContextSource {
);
}
/**
* Extract values for syntax highlight
*
* @param bool $canEdit
* @return array
*/
private function getAceConfig( bool $canEdit ): array {
$keywordsManager = AbuseFilterServices::getKeywordsManager();
$values = $keywordsManager->getBuilderValues();
$deprecatedVars = $keywordsManager->getDeprecatedVariables();
$builderVariables = implode( '|', array_keys( $values['vars'] ) );
$builderFunctions = implode( '|', array_keys( AbuseFilterParser::FUNCTIONS ) );
// AbuseFilterTokenizer::KEYWORDS also includes constants (true, false and null),
// but Ace redefines these constants afterwards so this will not be an issue
$builderKeywords = implode( '|', AbuseFilterTokenizer::KEYWORDS );
// Extract operators from tokenizer like we do in AbuseFilterParserTest
$operators = implode( '|', array_map( function ( $op ) {
return preg_quote( $op, '/' );
}, AbuseFilterTokenizer::OPERATORS ) );
$deprecatedVariables = implode( '|', array_keys( $deprecatedVars ) );
$disabledVariables = implode( '|', array_keys( $keywordsManager->getDisabledVariables() ) );
return [
'variables' => $builderVariables,
'functions' => $builderFunctions,
'keywords' => $builderKeywords,
'operators' => $operators,
'deprecated' => $deprecatedVariables,
'disabled' => $disabledVariables,
'aceReadOnly' => !$canEdit
];
}
}

View file

@ -305,7 +305,10 @@ class AbuseFilterViewEdit extends AbuseFilterView {
}
}
$fields['abusefilter-edit-rules'] = $this->buildEditBox(
$boxBuilderFactory = AbuseFilterServices::getEditBoxBuilderFactory();
$boxBuilder = $boxBuilderFactory->newEditBoxBuilder( $this, $user, $out );
$fields['abusefilter-edit-rules'] = $boxBuilder->buildEditBox(
$filterObj->getRules(),
true
);

View file

@ -211,8 +211,15 @@ class AbuseFilterViewExamine extends AbuseFilterView {
// Add test bit
if ( $afPermManager->canViewPrivateFilters( $this->getUser() ) ) {
$boxBuilderFactory = AbuseFilterServices::getEditBoxBuilderFactory();
$boxBuilder = $boxBuilderFactory->newEditBoxBuilder(
$this,
$this->getUser(),
$output
);
$tester = Xml::tags( 'h2', null, $this->msg( 'abusefilter-examine-test' )->parse() );
$tester .= $this->buildEditBox( $this->mTestFilter, false, false, false );
$tester .= $boxBuilder->buildEditBox( $this->mTestFilter, false, false, false );
$tester .= $this->buildFilterLoader();
$html .= Xml::tags( 'div', [ 'id' => 'mw-abusefilter-examine-editor' ], $tester );
$html .= Xml::tags( 'p',

View file

@ -61,9 +61,12 @@ class AbuseFilterViewTestBatch extends AbuseFilterView {
$out->addWikiMsg( 'abusefilter-test-intro', self::$mChangeLimit );
$out->enableOOUI();
$boxBuilderFactory = AbuseFilterServices::getEditBoxBuilderFactory();
$boxBuilder = $boxBuilderFactory->newEditBoxBuilder( $this, $this->getUser(), $out );
$output = '';
$output .=
$this->buildEditBox(
$boxBuilder->buildEditBox(
$this->testPattern,
true,
true,

View file

@ -21,9 +21,12 @@ class AbuseFilterViewTools extends AbuseFilterView {
// Header
$out->addWikiMsg( 'abusefilter-tools-text' );
$boxBuilderFactory = AbuseFilterServices::getEditBoxBuilderFactory();
$boxBuilder = $boxBuilderFactory->newEditBoxBuilder( $this, $this->getUser(), $out );
// Expression evaluator
$eval = '';
$eval .= $this->buildEditBox(
$eval .= $boxBuilder->buildEditBox(
$request->getText( 'wpFilterRules' ),
true,
false,

View file

@ -0,0 +1,41 @@
<?php
use MediaWiki\Extension\AbuseFilter\AbuseFilterPermissionManager;
use MediaWiki\Extension\AbuseFilter\EditBoxBuilder;
use MediaWiki\Extension\AbuseFilter\EditBoxBuilderFactory;
use MediaWiki\Extension\AbuseFilter\KeywordsManager;
/**
* @coversDefaultClass \MediaWiki\Extension\AbuseFilter\EditBoxBuilderFactory
*/
class EditBoxBuilderFactoryTest extends MediaWikiUnitTestCase {
/**
* @covers ::__construct
* @covers ::newEditBoxBuilder
* @covers \MediaWiki\Extension\AbuseFilter\EditBoxBuilder::__construct
* @dataProvider provideNewEditBoxBuilder
* @param bool $isCodeEditorLoaded
*/
public function testNewEditBoxBuilder( bool $isCodeEditorLoaded ) {
$factory = new EditBoxBuilderFactory(
$this->createMock( AbuseFilterPermissionManager::class ),
$this->createMock( KeywordsManager::class ),
$isCodeEditorLoaded
);
$builder = $factory->newEditBoxBuilder(
$this->createMock( MessageLocalizer::class ),
$this->createMock( User::class ),
$this->createMock( OutputPage::class )
);
$this->assertInstanceOf( EditBoxBuilder::class, $builder );
}
public function provideNewEditBoxBuilder() : array {
return [
[ true ],
[ false ]
];
}
}