Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.99% covered (danger)
0.99%
2 / 203
12.50% covered (danger)
12.50%
1 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
AbuseFilterViewRevert
0.99% covered (danger)
0.99%
2 / 203
12.50% covered (danger)
12.50%
1 / 8
903.66
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 show
0.00% covered (danger)
0.00%
0 / 49
0.00% covered (danger)
0.00%
0 / 1
30
 showRevertableActions
0.00% covered (danger)
0.00%
0 / 57
0.00% covered (danger)
0.00%
0 / 1
20
 doLookup
0.00% covered (danger)
0.00%
0 / 55
0.00% covered (danger)
0.00%
0 / 1
56
 loadParameters
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 attemptRevert
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 getConsequence
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
30
 revertAction
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace MediaWiki\Extension\AbuseFilter\View;
4
5use MediaWiki\Context\IContextSource;
6use MediaWiki\Exception\PermissionsError;
7use MediaWiki\Exception\UserBlockedError;
8use MediaWiki\Extension\AbuseFilter\AbuseFilterPermissionManager;
9use MediaWiki\Extension\AbuseFilter\ActionSpecifier;
10use MediaWiki\Extension\AbuseFilter\Consequences\Consequence\ReversibleConsequence;
11use MediaWiki\Extension\AbuseFilter\Consequences\ConsequencesFactory;
12use MediaWiki\Extension\AbuseFilter\Consequences\Parameters;
13use MediaWiki\Extension\AbuseFilter\FilterLookup;
14use MediaWiki\Extension\AbuseFilter\SpecsFormatter;
15use MediaWiki\Extension\AbuseFilter\Variables\UnsetVariableException;
16use MediaWiki\Extension\AbuseFilter\Variables\VariablesBlobStore;
17use MediaWiki\Html\Html;
18use MediaWiki\HTMLForm\HTMLForm;
19use MediaWiki\Linker\Linker;
20use MediaWiki\Linker\LinkRenderer;
21use MediaWiki\Message\Message;
22use MediaWiki\SpecialPage\SpecialPage;
23use MediaWiki\Title\TitleValue;
24use MediaWiki\User\UserFactory;
25use UnexpectedValueException;
26use Wikimedia\IPUtils;
27use Wikimedia\Rdbms\LBFactory;
28use Wikimedia\Rdbms\SelectQueryBuilder;
29
30class AbuseFilterViewRevert extends AbuseFilterView {
31    /** @var int */
32    private $filter;
33    /**
34     * @var string|null The start time of the lookup period
35     */
36    private $periodStart;
37    /**
38     * @var string|null The end time of the lookup period
39     */
40    private $periodEnd;
41    /**
42     * @var string|null The reason provided for the revert
43     */
44    private $reason;
45
46    public function __construct(
47        private readonly LBFactory $lbFactory,
48        private readonly UserFactory $userFactory,
49        AbuseFilterPermissionManager $afPermManager,
50        private readonly FilterLookup $filterLookup,
51        private readonly ConsequencesFactory $consequencesFactory,
52        private readonly VariablesBlobStore $varBlobStore,
53        private readonly SpecsFormatter $specsFormatter,
54        IContextSource $context,
55        LinkRenderer $linkRenderer,
56        string $basePageName,
57        array $params
58    ) {
59        parent::__construct( $afPermManager, $context, $linkRenderer, $basePageName, $params );
60        $this->specsFormatter->setMessageLocalizer( $this->getContext() );
61    }
62
63    /**
64     * Shows the page
65     */
66    public function show() {
67        $lang = $this->getLanguage();
68
69        $performer = $this->getAuthority();
70        $out = $this->getOutput();
71
72        if ( !$this->afPermManager->canRevertFilterActions( $performer ) ) {
73            throw new PermissionsError( 'abusefilter-revert' );
74        }
75
76        $block = $performer->getBlock();
77        if ( $block && $block->isSitewide() ) {
78            throw new UserBlockedError( $block );
79        }
80
81        $this->loadParameters();
82
83        if ( $this->attemptRevert() ) {
84            return;
85        }
86
87        $filter = $this->filter;
88
89        $out->addWikiMsg( 'abusefilter-revert-intro', Message::numParam( $filter ) );
90        // Parse wikitext in this message to allow formatting of numero signs (T343994#9209383)
91        $out->setPageTitle( $this->msg( 'abusefilter-revert-title' )->numParams( $filter )->parse() );
92
93        // First, the search form. Limit dates to avoid huge queries
94        $RCMaxAge = $this->getConfig()->get( 'RCMaxAge' );
95        $min = wfTimestamp( TS_ISO_8601, time() - $RCMaxAge );
96        $max = wfTimestampNow();
97        $filterLink = $this->linkRenderer->makeLink(
98            $this->getTitle( $filter ),
99            $lang->formatNum( $filter )
100        );
101        $searchFields = [
102            'filterid' => [
103                'type' => 'info',
104                'default' => $filterLink,
105                'raw' => true,
106                'label-message' => 'abusefilter-revert-filter',
107            ],
108            'PeriodStart' => [
109                'type' => 'datetime',
110                'label-message' => 'abusefilter-revert-periodstart',
111                'min' => $min,
112                'max' => $max,
113            ],
114            'PeriodEnd' => [
115                'type' => 'datetime',
116                'label-message' => 'abusefilter-revert-periodend',
117                'min' => $min,
118                'max' => $max,
119            ],
120        ];
121
122        HTMLForm::factory( 'ooui', $searchFields, $this->getContext() )
123            ->setTitle( $this->getTitle( "revert/$filter" ) )
124            ->setWrapperLegendMsg( 'abusefilter-revert-search-legend' )
125            ->setSubmitTextMsg( 'abusefilter-revert-search' )
126            ->setMethod( 'get' )
127            ->setFormIdentifier( 'revert-select-date' )
128            ->setSubmitCallback( [ $this, 'showRevertableActions' ] )
129            ->showAlways();
130    }
131
132    /**
133     * Show revertable actions, called as submit callback by HTMLForm
134     * @param array $formData
135     * @param HTMLForm $dateForm
136     * @return bool
137     */
138    public function showRevertableActions( array $formData, HTMLForm $dateForm ): bool {
139        $lang = $this->getLanguage();
140        $user = $this->getUser();
141        $filter = $this->filter;
142
143        // Look up all of them.
144        $results = $this->doLookup();
145        if ( $results === [] ) {
146            $dateForm->addPostHtml( $this->msg( 'abusefilter-revert-preview-no-results' )->escaped() );
147            return true;
148        }
149
150        // Add a summary of everything that will be reversed.
151        $dateForm->addPostHtml( $this->msg( 'abusefilter-revert-preview-intro' )->parseAsBlock() );
152        $list = [];
153
154        foreach ( $results as $result ) {
155            $displayActions = [];
156            foreach ( $result['actions'] as $action ) {
157                $displayActions[] = $this->specsFormatter->getActionDisplay( $action );
158            }
159
160            /** @var ActionSpecifier $spec */
161            $spec = $result['spec'];
162            $msg = $this->msg( 'abusefilter-revert-preview-item' )
163                ->params(
164                    $lang->userTimeAndDate( $result['timestamp'], $user )
165                )->rawParams(
166                    Linker::userLink( $spec->getUser()->getId(), $spec->getUser()->getName() )
167                )->params(
168                    $spec->getAction()
169                )->rawParams(
170                    $this->linkRenderer->makeLink( $spec->getTitle() )
171                )->params(
172                    $lang->commaList( $displayActions )
173                )->rawParams(
174                    $this->linkRenderer->makeLink(
175                        SpecialPage::getTitleFor( 'AbuseLog', $result['id'] ),
176                        $this->msg( 'abusefilter-log-detailslink' )->text()
177                    )
178                )->params(
179                    $spec->getUser()->getName()
180                )->parse();
181            $list[] = Html::rawElement( 'li', [], $msg );
182        }
183
184        $dateForm->addPostHtml( Html::rawElement( 'ul', [], implode( "\n", $list ) ) );
185
186        // Add a button down the bottom.
187        $confirmForm = [
188            'PeriodStart' => [
189                'type' => 'hidden',
190            ],
191            'PeriodEnd' => [
192                'type' => 'hidden',
193            ],
194            'Reason' => [
195                'type' => 'text',
196                'label-message' => 'abusefilter-revert-reasonfield',
197                'id' => 'wpReason',
198            ],
199        ];
200
201        $revertForm = HTMLForm::factory( 'ooui', $confirmForm, $this->getContext() )
202            ->setTitle( $this->getTitle( "revert/$filter" ) )
203            ->setTokenSalt( "abusefilter-revert-$filter" )
204            ->setWrapperLegendMsg( 'abusefilter-revert-confirm-legend' )
205            ->setSubmitTextMsg( 'abusefilter-revert-confirm' )
206            ->prepareForm()
207            ->getHTML( true );
208        $dateForm->addPostHtml( $revertForm );
209
210        return true;
211    }
212
213    /**
214     * @return array[]
215     */
216    public function doLookup() {
217        $periodStart = $this->periodStart;
218        $periodEnd = $this->periodEnd;
219        $filter = $this->filter;
220        $dbr = $this->lbFactory->getReplicaDatabase();
221
222        // Only hits from local filters can be reverted
223        $conds = [ 'afl_filter_id' => $filter, 'afl_global' => 0 ];
224
225        if ( $periodStart !== null ) {
226            $conds[] = $dbr->expr( 'afl_timestamp', '>=', $dbr->timestamp( $periodStart ) );
227        }
228        if ( $periodEnd !== null ) {
229            $conds[] = $dbr->expr( 'afl_timestamp', '<=', $dbr->timestamp( $periodEnd ) );
230        }
231
232        // Don't revert if there was no action, or the action was global
233        $conds[] = $dbr->expr( 'afl_actions', '!=', '' );
234        $conds['afl_wiki'] = null;
235
236        $selectFields = [
237            'afl_id',
238            'afl_user',
239            'afl_user_text',
240            'afl_ip_hex',
241            'afl_action',
242            'afl_actions',
243            'afl_var_dump',
244            'afl_timestamp',
245            'afl_namespace',
246            'afl_title',
247        ];
248        $res = $dbr->newSelectQueryBuilder()
249            ->select( $selectFields )
250            ->from( 'abuse_filter_log' )
251            ->where( $conds )
252            ->caller( __METHOD__ )
253            ->orderBy( 'afl_timestamp', SelectQueryBuilder::SORT_DESC )
254            ->fetchResultSet();
255
256        // TODO: get the following from ConsequencesRegistry or sth else
257        static $reversibleActions = [ 'block', 'blockautopromote', 'degroup' ];
258
259        $results = [];
260        foreach ( $res as $row ) {
261            $actions = explode( ',', $row->afl_actions );
262            $currentReversibleActions = array_intersect( $actions, $reversibleActions );
263            if ( count( $currentReversibleActions ) ) {
264                $vars = $this->varBlobStore->loadVarDump( $row );
265                try {
266                    // The variable is not lazy-loaded
267                    $accountName = $vars->getComputedVariable( 'account_name' )->toNative();
268                } catch ( UnsetVariableException ) {
269                    $accountName = null;
270                }
271
272                $formattedIP = $row->afl_ip_hex ? IPUtils::formatHex( $row->afl_ip_hex ) : '';
273                $results[] = [
274                    'id' => $row->afl_id,
275                    'actions' => $currentReversibleActions,
276                    'vars' => $vars,
277                    'spec' => new ActionSpecifier(
278                        $row->afl_action,
279                        new TitleValue( (int)$row->afl_namespace, $row->afl_title ),
280                        $this->userFactory->newFromAnyId( (int)$row->afl_user, $row->afl_user_text ),
281                        $formattedIP,
282                        $accountName
283                    ),
284                    'timestamp' => $row->afl_timestamp
285                ];
286            }
287        }
288
289        return $results;
290    }
291
292    /**
293     * Loads parameters from request
294     */
295    public function loadParameters() {
296        $request = $this->getRequest();
297
298        $this->filter = (int)$this->mParams[1];
299        $this->periodStart = strtotime( $request->getText( 'wpPeriodStart' ) ) ?: null;
300        $this->periodEnd = strtotime( $request->getText( 'wpPeriodEnd' ) ) ?: null;
301        $this->reason = $request->getVal( 'wpReason' );
302    }
303
304    /**
305     * @return bool
306     */
307    public function attemptRevert() {
308        $filter = $this->filter;
309        $token = $this->getRequest()->getVal( 'wpEditToken' );
310        if ( !$this->getCsrfTokenSet()->matchToken( $token, "abusefilter-revert-$filter" ) ) {
311            return false;
312        }
313
314        $results = $this->doLookup();
315        foreach ( $results as $result ) {
316            foreach ( $result['actions'] as $action ) {
317                $this->revertAction( $action, $result );
318            }
319        }
320        $this->getOutput()->addModuleStyles( 'mediawiki.codex.messagebox.styles' );
321        $this->getOutput()->addHTML( Html::successBox(
322            $this->msg(
323                'abusefilter-revert-success',
324                $filter,
325                $this->getLanguage()->formatNum( $filter )
326            )->parse()
327        ) );
328
329        return true;
330    }
331
332    /**
333     * Helper method for typing
334     * @param string $action
335     * @param array $result
336     * @return ReversibleConsequence
337     */
338    private function getConsequence( string $action, array $result ): ReversibleConsequence {
339        $params = new Parameters(
340            $this->filterLookup->getFilter( $this->filter, false ),
341            false,
342            $result['spec']
343        );
344
345        switch ( $action ) {
346            case 'block':
347                return $this->consequencesFactory->newBlock( $params, '', false );
348            case 'blockautopromote':
349                $duration = $this->getConfig()->get( 'AbuseFilterBlockAutopromoteDuration' ) * 86400;
350                return $this->consequencesFactory->newBlockAutopromote( $params, $duration );
351            case 'degroup':
352                return $this->consequencesFactory->newDegroup( $params, $result['vars'] );
353            default:
354                throw new UnexpectedValueException( "Invalid action $action" );
355        }
356    }
357
358    /**
359     * @param string $action
360     * @param array $result
361     * @return bool
362     */
363    public function revertAction( string $action, array $result ): bool {
364        $message = $this->msg(
365            'abusefilter-revert-reason', $this->filter, $this->reason
366        )->inContentLanguage()->text();
367
368        $consequence = $this->getConsequence( $action, $result );
369        return $consequence->revert( $this->getAuthority(), $message );
370    }
371}