Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.17% covered (success)
98.17%
107 / 109
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
QueryAbuseFilters
98.17% covered (success)
98.17%
107 / 109
50.00% covered (danger)
50.00%
1 / 2
42
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 execute
98.15% covered (success)
98.15%
106 / 108
0.00% covered (danger)
0.00%
0 / 1
39
 getAllowedParams
n/a
0 / 0
n/a
0 / 0
1
 getExamplesMessages
n/a
0 / 0
n/a
0 / 0
1
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
19namespace MediaWiki\Extension\AbuseFilter\Api;
20
21use MediaWiki\Api\ApiBase;
22use MediaWiki\Api\ApiQuery;
23use MediaWiki\Api\ApiQueryBase;
24use MediaWiki\Extension\AbuseFilter\AbuseFilterPermissionManager;
25use MediaWiki\Extension\AbuseFilter\Filter\Flags;
26use MediaWiki\Extension\AbuseFilter\FilterLookup;
27use Wikimedia\ParamValidator\ParamValidator;
28use Wikimedia\ParamValidator\TypeDef\IntegerDef;
29use Wikimedia\Timestamp\ConvertibleTimestamp;
30use Wikimedia\Timestamp\TimestampFormat as TS;
31
32/**
33 * Query module to list abuse filter details.
34 *
35 * @copyright 2009 Alex Z. <mrzmanwiki AT gmail DOT com>
36 * Based mostly on code by Bryan Tong Minh and Roan Kattouw
37 *
38 * @ingroup API
39 * @ingroup Extensions
40 */
41class QueryAbuseFilters extends ApiQueryBase {
42
43    public function __construct(
44        ApiQuery $query,
45        string $moduleName,
46        private readonly AbuseFilterPermissionManager $afPermManager,
47        private readonly FilterLookup $filterLookup
48    ) {
49        parent::__construct( $query, $moduleName, 'abf' );
50    }
51
52    /**
53     * @inheritDoc
54     */
55    public function execute() {
56        $this->checkUserRightsAny( 'abusefilter-view' );
57
58        $params = $this->extractRequestParams();
59
60        $prop = array_fill_keys( $params['prop'], true );
61        $fld_id = isset( $prop['id'] );
62        $fld_desc = isset( $prop['description'] );
63        $fld_pattern = isset( $prop['pattern'] );
64        $fld_actions = isset( $prop['actions'] );
65        $fld_hits = isset( $prop['hits'] );
66        $fld_comments = isset( $prop['comments'] );
67        $fld_user = isset( $prop['lasteditor'] );
68        $fld_time = isset( $prop['lastedittime'] );
69        $fld_status = isset( $prop['status'] );
70        $fld_suppressed = isset( $prop['suppressed'] );
71        $fld_private = isset( $prop['private'] );
72        $fld_protected = isset( $prop['protected'] );
73
74        $result = $this->getResult();
75
76        // Use the SelectQueryBuilder from the FilterLookup service as a base so that we can construct
77        // Filter objects from the rows got in the query.
78        $this->getQueryBuilder()->queryInfo(
79            $this->filterLookup->getAbuseFilterQueryBuilder( $this->getDB() )->getQueryInfo()
80        );
81
82        $this->addOption( 'LIMIT', $params['limit'] + 1 );
83
84        $this->addWhereRange( 'af_id', $params['dir'], $params['startid'], $params['endid'] );
85
86        if ( $params['show'] !== null ) {
87            $show = array_fill_keys( $params['show'], true );
88
89            /* Check for conflicting parameters. */
90            if ( ( isset( $show['enabled'] ) && isset( $show['!enabled'] ) )
91                || ( isset( $show['deleted'] ) && isset( $show['!deleted'] ) )
92                || ( isset( $show['private'] ) && isset( $show['!private'] ) )
93                || ( isset( $show['protected'] ) && isset( $show['!protected'] ) )
94            ) {
95                $this->dieWithError( 'apierror-show' );
96            }
97
98            $dbr = $this->getDb();
99            $this->addWhereIf( $dbr->expr( 'af_enabled', '=', 0 ), isset( $show['!enabled'] ) );
100            $this->addWhereIf( $dbr->expr( 'af_enabled', '!=', 0 ), isset( $show['enabled'] ) );
101            $this->addWhereIf( $dbr->expr( 'af_deleted', '=', 0 ), isset( $show['!deleted'] ) );
102            $this->addWhereIf( $dbr->expr( 'af_deleted', '!=', 0 ), isset( $show['deleted'] ) );
103            $this->addWhereIf(
104                $dbr->bitAnd( 'af_hidden', Flags::FILTER_HIDDEN ) . ' = 0',
105                isset( $show['!private'] )
106            );
107            $this->addWhereIf(
108                $dbr->bitAnd( 'af_hidden', Flags::FILTER_HIDDEN ) . ' != 0',
109                isset( $show['private'] )
110            );
111            $this->addWhereIf(
112                $dbr->bitAnd( 'af_hidden', Flags::FILTER_USES_PROTECTED_VARS ) . ' = 0',
113                isset( $show['!protected'] )
114            );
115            $this->addWhereIf(
116                $dbr->bitAnd( 'af_hidden', Flags::FILTER_USES_PROTECTED_VARS ) . ' != 0',
117                isset( $show['protected'] )
118            );
119        }
120
121        $res = $this->select( __METHOD__ );
122
123        $showhidden = $this->afPermManager->canViewPrivateFilters( $this->getAuthority() );
124        $showSuppressed = $this->afPermManager->canViewSuppressed( $this->getAuthority() );
125
126        $count = 0;
127        foreach ( $res as $row ) {
128            // FilterLookup::filterFromRow will override af_actions, so we need to define the callback to generate
129            // the data. We do not need to define anything other than the names because we only call
130            // AbstractFilter::getActionNames.
131            $actions = array_flip( explode( ',', $row->af_actions ) );
132            $filter = $this->filterLookup->filterFromRow( $row, $actions );
133            if ( ++$count > $params['limit'] ) {
134                // We've had enough
135                $this->setContinueEnumParameter( 'startid', $filter->getID() );
136                break;
137            }
138
139            // Hide the pattern and non-public comments from the API response if the user would not
140            // be able to open the editor for the filter.
141            $canViewExtendedDetailsAboutFilter =
142                ( !$filter->isHidden() || $showhidden )
143                && ( !$filter->isSuppressed() || $showSuppressed );
144
145            if ( $filter->isProtected() && $canViewExtendedDetailsAboutFilter ) {
146                $canViewExtendedDetailsAboutFilter = $this->afPermManager
147                    ->canViewProtectedVariablesInFilter( $this->getAuthority(), $filter )
148                    ->isGood();
149            }
150
151            $entry = [];
152            if ( $fld_id ) {
153                $entry['id'] = $filter->getID();
154            }
155            if ( $fld_desc ) {
156                $entry['description'] = $filter->getName();
157            }
158            if ( $fld_pattern ) {
159                if ( $canViewExtendedDetailsAboutFilter ) {
160                    $entry['pattern'] = $filter->getRules();
161                } else {
162                    $entry['patternredacted'] = '';
163                }
164            }
165            if ( $fld_actions ) {
166                $entry['actions'] = implode( ',', $filter->getActionsNames() );
167            }
168            if ( $fld_hits ) {
169                if ( $this->afPermManager->canSeeLogDetailsForFilter( $this->getAuthority(), $filter ) ) {
170                    $entry['hits'] = $filter->getHitCount();
171                } else {
172                    $entry['hitsredacted'] = '';
173                }
174            }
175            if ( $fld_comments ) {
176                if ( $canViewExtendedDetailsAboutFilter ) {
177                    $entry['comments'] = $filter->getComments();
178                } else {
179                    $entry['commentsredacted'] = '';
180                }
181            }
182            if ( $fld_user ) {
183                $entry['lasteditor'] = $filter->getLastEditInfo()->getUserName();
184            }
185            if ( $fld_time ) {
186                $entry['lastedittime'] = ConvertibleTimestamp::convert(
187                    TS::ISO_8601, $filter->getLastEditInfo()->getTimestamp()
188                );
189            }
190            if ( $fld_suppressed && $filter->isSuppressed() ) {
191                $entry['suppressed'] = '';
192            }
193
194            if ( $fld_private && $filter->isHidden() ) {
195                $entry['private'] = '';
196            }
197            if ( $fld_protected && $filter->isProtected() ) {
198                $entry['protected'] = '';
199            }
200            if ( $fld_status ) {
201                if ( $filter->isEnabled() ) {
202                    $entry['enabled'] = '';
203                }
204                if ( $filter->isDeleted() ) {
205                    $entry['deleted'] = '';
206                }
207            }
208            if ( $entry ) {
209                $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $entry );
210                if ( !$fit ) {
211                    $this->setContinueEnumParameter( 'startid', $filter->getID() );
212                    break;
213                }
214            }
215        }
216        $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'filter' );
217    }
218
219    /**
220     * @codeCoverageIgnore Merely declarative
221     * @inheritDoc
222     */
223    public function getAllowedParams() {
224        return [
225            'startid' => [
226                ParamValidator::PARAM_TYPE => 'integer'
227            ],
228            'endid' => [
229                ParamValidator::PARAM_TYPE => 'integer',
230            ],
231            'dir' => [
232                ParamValidator::PARAM_TYPE => [
233                    'older',
234                    'newer'
235                ],
236                ParamValidator::PARAM_DEFAULT => 'newer',
237                ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
238            ],
239            'show' => [
240                ParamValidator::PARAM_ISMULTI => true,
241                ParamValidator::PARAM_TYPE => [
242                    'enabled',
243                    '!enabled',
244                    'deleted',
245                    '!deleted',
246                    'private',
247                    '!private',
248                    'protected',
249                    '!protected',
250                ],
251            ],
252            'limit' => [
253                ParamValidator::PARAM_DEFAULT => 10,
254                ParamValidator::PARAM_TYPE => 'limit',
255                IntegerDef::PARAM_MIN => 1,
256                IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
257                IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
258            ],
259            'prop' => [
260                ParamValidator::PARAM_DEFAULT => 'id|description|actions|status',
261                ParamValidator::PARAM_TYPE => [
262                    'id',
263                    'description',
264                    'pattern',
265                    'actions',
266                    'hits',
267                    'comments',
268                    'lasteditor',
269                    'lastedittime',
270                    'status',
271                    'suppressed',
272                    'private',
273                    'protected',
274                ],
275                ParamValidator::PARAM_ISMULTI => true
276            ]
277        ];
278    }
279
280    /**
281     * @codeCoverageIgnore Merely declarative
282     * @inheritDoc
283     */
284    protected function getExamplesMessages() {
285        return [
286            'action=query&list=abusefilters&abfshow=enabled|!private'
287                => 'apihelp-query+abusefilters-example-1',
288            'action=query&list=abusefilters&abfprop=id|description|pattern'
289                => 'apihelp-query+abusefilters-example-2',
290        ];
291    }
292}