Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 177
0.00% covered (danger)
0.00%
0 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
BlockedExternalDomains
0.00% covered (danger)
0.00%
0 / 177
0.00% covered (danger)
0.00%
0 / 10
702
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
30
 showList
0.00% covered (danger)
0.00%
0 / 60
0.00% covered (danger)
0.00%
0 / 1
42
 doDomainRow
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 showRemoveForm
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
6
 processRemoveForm
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 showAddForm
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
6
 processAddForm
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 getGroupName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isListed
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20namespace MediaWiki\Extension\AbuseFilter\Special;
21
22use ErrorPageError;
23use Html;
24use HTMLForm;
25use IDBAccessObject;
26use MediaWiki\Extension\AbuseFilter\BlockedDomainStorage;
27use PermissionsError;
28use SpecialPage;
29use WANObjectCache;
30
31/**
32 * List and manage blocked external domains
33 *
34 * @ingroup SpecialPage
35 */
36class BlockedExternalDomains extends SpecialPage {
37    private BlockedDomainStorage $blockedDomainStorage;
38    private WANObjectCache $wanCache;
39
40    public function __construct(
41        BlockedDomainStorage $blockedDomainStorage,
42        WANObjectCache $wanCache
43    ) {
44        parent::__construct( 'BlockedExternalDomains' );
45        $this->blockedDomainStorage = $blockedDomainStorage;
46        $this->wanCache = $wanCache;
47    }
48
49    /** @inheritDoc */
50    public function execute( $par ) {
51        if ( !$this->getConfig()->get( 'AbuseFilterEnableBlockedExternalDomain' ) ) {
52            throw new ErrorPageError( 'abusefilter-disabled', 'disabledspecialpage-disabled' );
53        }
54        $this->setHeaders();
55        $this->outputHeader();
56        $this->addHelpLink( 'Manual:BlockedExternalDomains' );
57
58        $request = $this->getRequest();
59        switch ( $par ) {
60            case 'remove':
61                $this->showRemoveForm( $request->getVal( 'domain' ) );
62                break;
63            case 'add':
64                $this->showAddForm( $request->getVal( 'domain' ) );
65                break;
66            default:
67                $this->showList();
68                break;
69        }
70    }
71
72    private function showList() {
73        $out = $this->getOutput();
74        $out->setPageTitleMsg( $this->msg( 'abusefilter-blocked-domains-title' ) );
75        $out->wrapWikiMsg( "$1", 'abusefilter-blocked-domains-intro' );
76
77        // Direct editing of this page is blocked via EditPermissionHandler
78        $userCanManage = $this->getAuthority()->isAllowed( 'abusefilter-modify-blocked-external-domains' );
79
80        // Show form to add a blocked domain
81        if ( $userCanManage ) {
82            $fields = [
83                'Domain' => [
84                    'type' => 'text',
85                    'label' => $this->msg( 'abusefilter-blocked-domains-domain' )->plain(),
86                    'required' => true,
87                ],
88                'Notes' => [
89                    'type' => 'text',
90                    'maxlength' => 255,
91                    'label' => $this->msg( 'abusefilter-blocked-domains-notes' )->plain(),
92                    'size' => 250,
93                ],
94            ];
95
96            HTMLForm::factory( 'ooui', $fields, $this->getContext() )
97                ->setAction( $this->getPageTitle( 'add' )->getLocalURL() )
98                ->setWrapperLegendMsg( 'abusefilter-blocked-domains-add-heading' )
99                ->setHeaderHtml( $this->msg( 'abusefilter-blocked-domains-add-explanation' )->parseAsBlock() )
100                ->setSubmitCallback( [ $this, 'processAddForm' ] )
101                ->setSubmitTextMsg( 'abusefilter-blocked-domains-add-submit' )
102                ->show();
103
104            if ( $out->getRedirect() !== '' ) {
105                return;
106            }
107        }
108
109        $res = $this->blockedDomainStorage->loadConfig( IDBAccessObject::READ_LATEST );
110        if ( !$res->isGood() ) {
111            return;
112        }
113
114        $content = Html::element( 'th', [], $this->msg( 'abusefilter-blocked-domains-domain-header' )->text() ) .
115            Html::element( 'th', [], $this->msg( 'abusefilter-blocked-domains-notes-header' )->text() ) .
116            ( $userCanManage ?
117                Html::element( 'th', [ 'class' => 'unsortable' ],
118                           $this->msg( 'abusefilter-blocked-domains-actions-header' )->text() ) :
119                '' );
120        $thead = Html::rawElement( 'tr', [], $content );
121
122        // Parsing each row is expensive, put it behind WAN cache
123        // with md5 checksum, we make sure changes to the domain list
124        // invalidate the cache
125        $cacheKey = $this->wanCache->makeKey(
126            'abuse-filter-special-blocked-external-domains-rows',
127            md5( json_encode( $res->getValue() ) ),
128            (int)$userCanManage
129        );
130        $tbody = $this->wanCache->getWithSetCallback(
131            $cacheKey,
132            WANObjectCache::TTL_DAY,
133            function () use ( $res, $userCanManage ) {
134                $tbody = '';
135                foreach ( $res->getValue() as $domain ) {
136                    $tbody .= $this->doDomainRow( $domain, $userCanManage );
137                }
138                return $tbody;
139            }
140        );
141
142        $out->addModuleStyles( [ 'jquery.tablesorter.styles', 'mediawiki.pager.styles' ] );
143        $out->addModules( 'jquery.tablesorter' );
144        $out->addHTML( Html::rawElement(
145            'table',
146            [ 'class' => 'mw-datatable sortable' ],
147            Html::rawElement( 'thead', [], $thead ) .
148            Html::rawElement( 'tbody', [], $tbody )
149        ) );
150    }
151
152    /**
153     * Show the row in the table
154     *
155     * @param array $domain domain data
156     * @param bool $showManageActions whether to add manage actions
157     * @return string HTML for the row
158     */
159    private function doDomainRow( $domain, $showManageActions ) {
160        $newRow = '';
161        $newRow .= Html::rawElement( 'td', [], Html::element( 'code', [], $domain['domain'] ) );
162
163        $newRow .= Html::rawElement( 'td', [], $this->getOutput()->parseInlineAsInterface( $domain['notes'] ) );
164
165        if ( $showManageActions ) {
166            $actionLink = $this->getLinkRenderer()->makeKnownLink(
167                $this->getPageTitle( 'remove' ),
168                $this->msg( 'abusefilter-blocked-domains-remove' )->text(),
169                [],
170                [ 'domain' => $domain['domain'] ] );
171            $newRow .= Html::rawElement( 'td', [], $actionLink );
172        }
173
174        return Html::rawElement( 'tr', [], $newRow ) . "\n";
175    }
176
177    /**
178     * Show form for removing a domain from the blocked list
179     *
180     * @param string $domain
181     * @return void
182     */
183    private function showRemoveForm( $domain ) {
184        if ( !$this->getAuthority()->isAllowed( 'editsitejson' ) ) {
185            throw new PermissionsError( 'editsitejson' );
186        }
187
188        $out = $this->getOutput();
189        $out->setPageTitleMsg( $this->msg( 'abusefilter-blocked-domains-remove-title' ) );
190        $out->addBacklinkSubtitle( $this->getPageTitle() );
191
192        $preText = $this->msg( 'abusefilter-blocked-domains-remove-explanation-initial', $domain )->parseAsBlock();
193
194        $fields = [
195            'Domain' => [
196                'type' => 'text',
197                'label' => $this->msg( 'abusefilter-blocked-domains-domain' )->plain(),
198                'required' => true,
199                'default' => $domain,
200            ],
201            'Notes' => [
202                'type' => 'text',
203                'maxlength' => 255,
204                'label' => $this->msg( 'abusefilter-blocked-domains-notes' )->plain(),
205                'size' => 250,
206            ],
207        ];
208
209        HTMLForm::factory( 'ooui', $fields, $this->getContext() )
210            ->setAction( $this->getPageTitle( 'remove' )->getLocalURL() )
211            ->setSubmitCallback( function ( $data, $form ) {
212                return $this->processRemoveForm( $data, $form );
213            } )
214            ->setSubmitTextMsg( 'abusefilter-blocked-domains-remove-submit' )
215            ->setSubmitDestructive()
216            ->addPreHtml( $preText )
217            ->show();
218    }
219
220    /**
221     * Process the form for removing a domain from the blocked list
222     *
223     * @param array $data request data
224     * @param HTMLForm $form
225     * @return bool whether the action was successful or not
226     */
227    public function processRemoveForm( array $data, HTMLForm $form ) {
228        $out = $form->getContext()->getOutput();
229        $domain = $this->blockedDomainStorage->validateDomain( $data['Domain'] );
230        if ( $domain === false ) {
231            $out->wrapWikiTextAsInterface( 'error', 'Invalid URL' );
232            return false;
233        }
234
235        $rev = $this->blockedDomainStorage->removeDomain(
236            $domain,
237            $data['Notes'] ?? '',
238            $this->getUser()
239        );
240
241        if ( !$rev ) {
242            $out->wrapWikiTextAsInterface( 'error', 'Save failed' );
243            return false;
244        }
245
246        $out->redirect( $this->getPageTitle()->getLocalURL() );
247        return true;
248    }
249
250    /**
251     * Show form for adding a domain to the blocked list
252     *
253     * @param string $domain
254     * @return void
255     */
256    private function showAddForm( $domain ) {
257        if ( !$this->getAuthority()->isAllowed( 'editsitejson' ) ) {
258            throw new PermissionsError( 'editsitejson' );
259        }
260
261        $out = $this->getOutput();
262        $out->setPageTitleMsg( $this->msg( "abusefilter-blocked-domains-add-heading" ) );
263        $out->addBacklinkSubtitle( $this->getPageTitle() );
264
265        $preText = $this->msg( "abusefilter-blocked-domains-add-explanation", $domain )->parseAsBlock();
266
267        $fields = [
268            'Domain' => [
269                'type' => 'text',
270                'label' => $this->msg( 'abusefilter-blocked-domains-domain' )->plain(),
271                'required' => true,
272                'default' => $domain,
273            ],
274            'Notes' => [
275                'type' => 'text',
276                'maxlength' => 255,
277                'label' => $this->msg( 'abusefilter-blocked-domains-notes' )->plain(),
278                'size' => 250,
279            ],
280        ];
281
282        HTMLForm::factory( 'ooui', $fields, $this->getContext() )
283            ->setAction( $this->getPageTitle( 'add' )->getLocalURL() )
284            ->setSubmitCallback( function ( $data, $form ) {
285                return $this->processAddForm( $data, $form );
286            } )
287            ->setSubmitTextMsg( "abusefilter-blocked-domains-add-submit" )
288            ->addPreHtml( $preText )
289            ->show();
290    }
291
292    /**
293     * Process the form for adding a domain to the blocked list
294     *
295     * @param array $data request data
296     * @param HTMLForm $form
297     * @return bool whether the action was successful or not
298     */
299    private function processAddForm( array $data, HTMLForm $form ) {
300        $out = $form->getContext()->getOutput();
301
302        $domain = $this->blockedDomainStorage->validateDomain( $data['Domain'] );
303        if ( $domain === false ) {
304            $out->wrapWikiTextAsInterface( 'error', 'Invalid URL' );
305            return false;
306        }
307        $rev = $this->blockedDomainStorage->addDomain(
308            $domain,
309            $data['Notes'] ?? '',
310            $this->getUser()
311        );
312
313        if ( !$rev ) {
314            $out->wrapWikiTextAsInterface( 'error', 'Save failed' );
315            return false;
316        }
317
318        $out->redirect( $this->getPageTitle()->getLocalURL() );
319        return true;
320    }
321
322    /** @inheritDoc */
323    protected function getGroupName() {
324        return 'spam';
325    }
326
327    public function isListed() {
328        return $this->getConfig()->get( 'AbuseFilterEnableBlockedExternalDomain' );
329    }
330}