Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 204
0.00% covered (danger)
0.00%
0 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiQueryFilearchive
0.00% covered (danger)
0.00%
0 / 204
0.00% covered (danger)
0.00%
0 / 5
4422
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 / 153
0.00% covered (danger)
0.00%
0 / 1
3906
 getAllowedParams
0.00% covered (danger)
0.00%
0 / 43
0.00% covered (danger)
0.00%
0 / 1
2
 getExamplesMessages
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 getHelpUrls
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * API for MediaWiki 1.12+
4 *
5 * Copyright © 2010 Sam Reed
6 * Copyright © 2008 Vasiliev Victor vasilvv@gmail.com,
7 * based on ApiQueryAllPages.php
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27use MediaWiki\CommentFormatter\CommentFormatter;
28use MediaWiki\CommentFormatter\CommentItem;
29use MediaWiki\CommentStore\CommentStore;
30use MediaWiki\Revision\RevisionRecord;
31use MediaWiki\Title\Title;
32use MediaWiki\Title\TitleValue;
33use Wikimedia\ParamValidator\ParamValidator;
34use Wikimedia\ParamValidator\TypeDef\IntegerDef;
35use Wikimedia\Rdbms\IExpression;
36use Wikimedia\Rdbms\LikeValue;
37
38/**
39 * Query module to enumerate all deleted files.
40 *
41 * @ingroup API
42 */
43class ApiQueryFilearchive extends ApiQueryBase {
44
45    private CommentStore $commentStore;
46    private CommentFormatter $commentFormatter;
47
48    /**
49     * @param ApiQuery $query
50     * @param string $moduleName
51     * @param CommentStore $commentStore
52     * @param CommentFormatter $commentFormatter
53     */
54    public function __construct(
55        ApiQuery $query,
56        $moduleName,
57        CommentStore $commentStore,
58        CommentFormatter $commentFormatter
59    ) {
60        parent::__construct( $query, $moduleName, 'fa' );
61        $this->commentStore = $commentStore;
62        $this->commentFormatter = $commentFormatter;
63    }
64
65    public function execute() {
66        $user = $this->getUser();
67        $db = $this->getDB();
68
69        $params = $this->extractRequestParams();
70
71        $prop = array_fill_keys( $params['prop'], true );
72        $fld_sha1 = isset( $prop['sha1'] );
73        $fld_timestamp = isset( $prop['timestamp'] );
74        $fld_user = isset( $prop['user'] );
75        $fld_size = isset( $prop['size'] );
76        $fld_dimensions = isset( $prop['dimensions'] );
77        $fld_description = isset( $prop['description'] ) || isset( $prop['parseddescription'] );
78        $fld_parseddescription = isset( $prop['parseddescription'] );
79        $fld_mime = isset( $prop['mime'] );
80        $fld_mediatype = isset( $prop['mediatype'] );
81        $fld_metadata = isset( $prop['metadata'] );
82        $fld_bitdepth = isset( $prop['bitdepth'] );
83        $fld_archivename = isset( $prop['archivename'] );
84
85        if ( $fld_description && !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
86            $this->dieWithError( 'apierror-cantview-deleted-description', 'permissiondenied' );
87        }
88        if ( $fld_metadata && !$this->getAuthority()->isAllowedAny( 'deletedtext', 'undelete' ) ) {
89            $this->dieWithError( 'apierror-cantview-deleted-metadata', 'permissiondenied' );
90        }
91
92        $fileQuery = ArchivedFile::getQueryInfo();
93        $this->addTables( $fileQuery['tables'] );
94        $this->addFields( $fileQuery['fields'] );
95        $this->addJoinConds( $fileQuery['joins'] );
96
97        if ( $params['continue'] !== null ) {
98            $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'string', 'timestamp', 'int' ] );
99            $op = $params['dir'] == 'descending' ? '<=' : '>=';
100            $this->addWhere( $db->buildComparison( $op, [
101                'fa_name' => $cont[0],
102                'fa_timestamp' => $db->timestamp( $cont[1] ),
103                'fa_id' => $cont[2],
104            ] ) );
105        }
106
107        // Image filters
108        $dir = ( $params['dir'] == 'descending' ? 'older' : 'newer' );
109        $from = ( $params['from'] === null ? null : $this->titlePartToKey( $params['from'], NS_FILE ) );
110        $to = ( $params['to'] === null ? null : $this->titlePartToKey( $params['to'], NS_FILE ) );
111        $this->addWhereRange( 'fa_name', $dir, $from, $to );
112        if ( isset( $params['prefix'] ) ) {
113            $this->addWhere(
114                $db->expr(
115                    'fa_name',
116                    IExpression::LIKE,
117                    new LikeValue( $this->titlePartToKey( $params['prefix'], NS_FILE ), $db->anyString() )
118                )
119            );
120        }
121
122        $sha1Set = isset( $params['sha1'] );
123        $sha1base36Set = isset( $params['sha1base36'] );
124        if ( $sha1Set || $sha1base36Set ) {
125            $sha1 = false;
126            if ( $sha1Set ) {
127                $sha1 = strtolower( $params['sha1'] );
128                if ( !$this->validateSha1Hash( $sha1 ) ) {
129                    $this->dieWithError( 'apierror-invalidsha1hash' );
130                }
131                $sha1 = Wikimedia\base_convert( $sha1, 16, 36, 31 );
132            } elseif ( $sha1base36Set ) {
133                $sha1 = strtolower( $params['sha1base36'] );
134                if ( !$this->validateSha1Base36Hash( $sha1 ) ) {
135                    $this->dieWithError( 'apierror-invalidsha1base36hash' );
136                }
137            }
138            if ( $sha1 ) {
139                $this->addWhereFld( 'fa_sha1', $sha1 );
140                // Paranoia: avoid brute force searches (T19342)
141                if ( !$this->getAuthority()->isAllowed( 'deletedtext' ) ) {
142                    $bitmask = File::DELETED_FILE;
143                } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
144                    $bitmask = File::DELETED_FILE | File::DELETED_RESTRICTED;
145                } else {
146                    $bitmask = 0;
147                }
148                if ( $bitmask ) {
149                    $this->addWhere( $this->getDB()->bitAnd( 'fa_deleted', $bitmask ) . " != $bitmask" );
150                }
151            }
152        }
153
154        $limit = $params['limit'];
155        $this->addOption( 'LIMIT', $limit + 1 );
156        $sort = ( $params['dir'] == 'descending' ? ' DESC' : '' );
157        $this->addOption( 'ORDER BY', [
158            'fa_name' . $sort,
159            'fa_timestamp' . $sort,
160            'fa_id' . $sort,
161        ] );
162
163        $res = $this->select( __METHOD__ );
164
165        // Format descriptions in a batch
166        $formattedDescriptions = [];
167        $descriptions = [];
168        if ( $fld_parseddescription ) {
169            $commentItems = [];
170            foreach ( $res as $row ) {
171                $desc = $this->commentStore->getComment( 'fa_description', $row )->text;
172                $descriptions[$row->fa_id] = $desc;
173                $commentItems[$row->fa_id] = ( new CommentItem( $desc ) )
174                    ->selfLinkTarget( new TitleValue( NS_FILE, $row->fa_name ) );
175            }
176            $formattedDescriptions = $this->commentFormatter->createBatch()
177                ->comments( $commentItems )
178                ->execute();
179        }
180
181        $count = 0;
182        $result = $this->getResult();
183        foreach ( $res as $row ) {
184            if ( ++$count > $limit ) {
185                // We've reached the one extra which shows that there are
186                // additional pages to be had. Stop here...
187                $this->setContinueEnumParameter(
188                    'continue', "$row->fa_name|$row->fa_timestamp|$row->fa_id"
189                );
190                break;
191            }
192
193            $exists = $row->fa_archive_name !== '';
194            $canViewFile = RevisionRecord::userCanBitfield( $row->fa_deleted, File::DELETED_FILE, $user );
195
196            $file = [];
197            $file['id'] = (int)$row->fa_id;
198            $file['name'] = $row->fa_name;
199            $title = Title::makeTitle( NS_FILE, $row->fa_name );
200            self::addTitleInfo( $file, $title );
201
202            if ( $fld_description &&
203                RevisionRecord::userCanBitfield( $row->fa_deleted, File::DELETED_COMMENT, $user )
204            ) {
205                if ( isset( $prop['parseddescription'] ) ) {
206                    $file['parseddescription'] = $formattedDescriptions[$row->fa_id];
207                    $file['description'] = $descriptions[$row->fa_id];
208                } else {
209                    $file['description'] = $this->commentStore->getComment( 'fa_description', $row )->text;
210                }
211            }
212            if ( $fld_user &&
213                RevisionRecord::userCanBitfield( $row->fa_deleted, File::DELETED_USER, $user )
214            ) {
215                $file['userid'] = (int)$row->fa_user;
216                $file['user'] = $row->fa_user_text;
217            }
218            if ( !$exists ) {
219                $file['filemissing'] = true;
220            }
221            if ( $fld_sha1 && $canViewFile && $exists ) {
222                $file['sha1'] = Wikimedia\base_convert( $row->fa_sha1, 36, 16, 40 );
223            }
224            if ( $fld_timestamp ) {
225                $file['timestamp'] = wfTimestamp( TS_ISO_8601, $row->fa_timestamp );
226            }
227            if ( ( $fld_size || $fld_dimensions ) && $canViewFile && $exists ) {
228                $file['size'] = $row->fa_size;
229
230                $pageCount = ArchivedFile::newFromRow( $row )->pageCount();
231                if ( $pageCount !== false ) {
232                    $file['pagecount'] = $pageCount;
233                }
234
235                $file['height'] = $row->fa_height;
236                $file['width'] = $row->fa_width;
237            }
238            if ( $fld_mediatype && $canViewFile && $exists ) {
239                $file['mediatype'] = $row->fa_media_type;
240            }
241            if ( $fld_metadata && $canViewFile && $exists ) {
242                $metadataArray = ArchivedFile::newFromRow( $row )->getMetadataArray();
243                $file['metadata'] = $row->fa_metadata
244                    ? ApiQueryImageInfo::processMetaData( $metadataArray, $result )
245                    : null;
246            }
247            if ( $fld_bitdepth && $canViewFile && $exists ) {
248                $file['bitdepth'] = $row->fa_bits;
249            }
250            if ( $fld_mime && $canViewFile && $exists ) {
251                $file['mime'] = "$row->fa_major_mime/$row->fa_minor_mime";
252            }
253            if ( $fld_archivename && $row->fa_archive_name !== null ) {
254                $file['archivename'] = $row->fa_archive_name;
255            }
256
257            if ( $row->fa_deleted & File::DELETED_FILE ) {
258                $file['filehidden'] = true;
259            }
260            if ( $row->fa_deleted & File::DELETED_COMMENT ) {
261                $file['commenthidden'] = true;
262            }
263            if ( $row->fa_deleted & File::DELETED_USER ) {
264                $file['userhidden'] = true;
265            }
266            if ( $row->fa_deleted & File::DELETED_RESTRICTED ) {
267                // This file is deleted for normal admins
268                $file['suppressed'] = true;
269            }
270
271            $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $file );
272            if ( !$fit ) {
273                $this->setContinueEnumParameter(
274                    'continue', "$row->fa_name|$row->fa_timestamp|$row->fa_id"
275                );
276                break;
277            }
278        }
279
280        $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'fa' );
281    }
282
283    public function getAllowedParams() {
284        return [
285            'from' => null,
286            'to' => null,
287            'prefix' => null,
288            'dir' => [
289                ParamValidator::PARAM_DEFAULT => 'ascending',
290                ParamValidator::PARAM_TYPE => [
291                    'ascending',
292                    'descending'
293                ]
294            ],
295            'sha1' => null,
296            'sha1base36' => null,
297            'prop' => [
298                ParamValidator::PARAM_DEFAULT => 'timestamp',
299                ParamValidator::PARAM_ISMULTI => true,
300                ParamValidator::PARAM_TYPE => [
301                    'sha1',
302                    'timestamp',
303                    'user',
304                    'size',
305                    'dimensions',
306                    'description',
307                    'parseddescription',
308                    'mime',
309                    'mediatype',
310                    'metadata',
311                    'bitdepth',
312                    'archivename',
313                ],
314                ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
315            ],
316            'limit' => [
317                ParamValidator::PARAM_DEFAULT => 10,
318                ParamValidator::PARAM_TYPE => 'limit',
319                IntegerDef::PARAM_MIN => 1,
320                IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
321                IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
322            ],
323            'continue' => [
324                ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
325            ],
326        ];
327    }
328
329    protected function getExamplesMessages() {
330        return [
331            'action=query&list=filearchive'
332                => 'apihelp-query+filearchive-example-simple',
333        ];
334    }
335
336    public function getHelpUrls() {
337        return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Filearchive';
338    }
339}