Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 109
0.00% covered (danger)
0.00%
0 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
SpecialFileDuplicateSearch
0.00% covered (danger)
0.00%
0 / 108
0.00% covered (danger)
0.00%
0 / 8
702
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getDupes
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 showList
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 execute
0.00% covered (danger)
0.00%
0 / 59
0.00% covered (danger)
0.00%
0 / 1
110
 doBatchLookups
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 formatResult
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
20
 prefixSearchSubpages
0.00% covered (danger)
0.00%
0 / 10
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
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace MediaWiki\Specials;
8
9use MediaWiki\FileRepo\File\File;
10use MediaWiki\FileRepo\RepoGroup;
11use MediaWiki\HTMLForm\HTMLForm;
12use MediaWiki\Language\ILanguageConverter;
13use MediaWiki\Language\LanguageConverterFactory;
14use MediaWiki\Linker\Linker;
15use MediaWiki\Page\LinkBatchFactory;
16use MediaWiki\Search\SearchEngineFactory;
17use MediaWiki\SpecialPage\SpecialPage;
18use MediaWiki\Title\Title;
19
20/**
21 * Search the database for files of the requested hash, comparing this with the
22 * 'img_sha1' field in the image table.
23 *
24 * @ingroup SpecialPage
25 * @author Raimond Spekking, based on Special:MIMESearch by Ævar Arnfjörð Bjarmason
26 */
27class SpecialFileDuplicateSearch extends SpecialPage {
28    /**
29     * @var string The form input hash
30     */
31    private $hash = '';
32
33    /**
34     * @var string The form input filename
35     */
36    private $filename = '';
37
38    /**
39     * @var File|null selected reference file, if present
40     */
41    private $file = null;
42
43    private readonly ILanguageConverter $languageConverter;
44
45    public function __construct(
46        private readonly LinkBatchFactory $linkBatchFactory,
47        private readonly RepoGroup $repoGroup,
48        private readonly SearchEngineFactory $searchEngineFactory,
49        LanguageConverterFactory $languageConverterFactory,
50    ) {
51        parent::__construct( 'FileDuplicateSearch' );
52        $this->languageConverter = $languageConverterFactory->getLanguageConverter( $this->getContentLanguage() );
53    }
54
55    /**
56     * Fetch dupes from all connected file repositories.
57     *
58     * @return File[]
59     */
60    private function getDupes() {
61        return $this->repoGroup->findBySha1( $this->hash );
62    }
63
64    /**
65     * @param File[] $dupes
66     */
67    private function showList( $dupes ) {
68        $html = [];
69        $html[] = "<ol class='special'>";
70
71        foreach ( $dupes as $dupe ) {
72            $line = $this->formatResult( $dupe );
73            $html[] = "<li>" . $line . "</li>";
74        }
75        $html[] = '</ol>';
76
77        $this->getOutput()->addHTML( implode( "\n", $html ) );
78    }
79
80    /** @inheritDoc */
81    public function execute( $par ) {
82        $this->setHeaders();
83        $this->outputHeader();
84
85        $this->filename = $par ?? $this->getRequest()->getText( 'filename' );
86        $this->file = null;
87        $this->hash = '';
88        $title = Title::newFromText( $this->filename, NS_FILE );
89        if ( $title && $title->getText() != '' ) {
90            $this->file = $this->repoGroup->findFile( $title );
91        }
92
93        $out = $this->getOutput();
94
95        # Create the input form
96        $formFields = [
97            'filename' => [
98                'type' => 'text',
99                'name' => 'filename',
100                'label-message' => 'fileduplicatesearch-filename',
101                'id' => 'filename',
102                'size' => 50,
103                'default' => $this->filename,
104            ],
105        ];
106        $htmlForm = HTMLForm::factory( 'ooui', $formFields, $this->getContext() );
107        $htmlForm->setTitle( $this->getPageTitle() );
108        $htmlForm->setMethod( 'get' );
109        $htmlForm->setSubmitTextMsg( $this->msg( 'fileduplicatesearch-submit' ) );
110
111        // The form should be visible always, even if it was submitted (e.g. to perform another action).
112        // To bypass the callback validation of HTMLForm, use prepareForm() and displayForm().
113        $htmlForm->prepareForm()->displayForm( false );
114
115        if ( $this->file ) {
116            $this->hash = $this->file->getSha1();
117        } elseif ( $this->filename !== '' ) {
118            $out->wrapWikiMsg(
119                "<p class='mw-fileduplicatesearch-noresults'>\n$1\n</p>",
120                [ 'fileduplicatesearch-noresults', wfEscapeWikiText( $this->filename ) ]
121            );
122        }
123
124        if ( $this->hash != '' ) {
125            # Show a thumbnail of the file
126            $img = $this->file;
127            if ( $img ) {
128                $thumb = $img->transform( [ 'width' => 120, 'height' => 120 ] );
129                if ( $thumb ) {
130                    $out->addModuleStyles( 'mediawiki.special' );
131                    $out->addHTML( '<div id="mw-fileduplicatesearch-icon">' .
132                        $thumb->toHtml( [ 'desc-link' => false ] ) . '<br />' .
133                        $this->msg( 'fileduplicatesearch-info' )
134                            ->numParams( $img->getWidth(), $img->getHeight() )
135                            ->sizeParams( $img->getSize() )
136                            ->params( $img->getMimeType() )->parseAsBlock() .
137                        '</div>' );
138                }
139            }
140
141            $dupes = $this->getDupes();
142            $numRows = count( $dupes );
143
144            # Show a short summary
145            if ( $numRows == 1 ) {
146                $out->wrapWikiMsg(
147                    "<p class='mw-fileduplicatesearch-result-1'>\n$1\n</p>",
148                    [ 'fileduplicatesearch-result-1', wfEscapeWikiText( $this->filename ) ]
149                );
150            } elseif ( $numRows ) {
151                $out->wrapWikiMsg(
152                    "<p class='mw-fileduplicatesearch-result-n'>\n$1\n</p>",
153                    [ 'fileduplicatesearch-result-n', wfEscapeWikiText( $this->filename ),
154                        $this->getLanguage()->formatNum( $numRows - 1 ) ]
155                );
156            }
157
158            $this->doBatchLookups( $dupes );
159            $this->showList( $dupes );
160        }
161    }
162
163    /**
164     * @param File[] $list
165     */
166    private function doBatchLookups( $list ) {
167        $batch = $this->linkBatchFactory->newLinkBatch()->setCaller( __METHOD__ );
168        foreach ( $list as $file ) {
169            $batch->addObj( $file->getTitle() );
170            if ( $file->isLocal() ) {
171                $uploader = $file->getUploader( File::FOR_THIS_USER, $this->getAuthority() );
172                if ( $uploader ) {
173                    $batch->addUser( $uploader );
174                }
175            }
176        }
177
178        $batch->execute();
179    }
180
181    /**
182     * @param File $result
183     * @return string HTML
184     */
185    private function formatResult( $result ) {
186        $linkRenderer = $this->getLinkRenderer();
187        $nt = $result->getTitle();
188        $text = $this->languageConverter->convert( $nt->getText() );
189        $plink = $linkRenderer->makeLink(
190            $nt,
191            $text
192        );
193
194        $uploader = $result->getUploader( File::FOR_THIS_USER, $this->getAuthority() );
195        if ( $result->isLocal() && $uploader ) {
196            $user = Linker::userLink( $uploader->getId(), $uploader->getName() );
197            $user .= '<span style="white-space: nowrap;">';
198            $user .= Linker::userToolLinks( $uploader->getId(), $uploader->getName() );
199            $user .= '</span>';
200        } elseif ( $uploader ) {
201            $user = htmlspecialchars( $uploader->getName() );
202        } else {
203            $user = '<span class="history-deleted">'
204                . $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
205        }
206
207        $time = htmlspecialchars( $this->getLanguage()->userTimeAndDate(
208            $result->getTimestamp(), $this->getUser() ) );
209
210        return "$plink . . $user . . $time";
211    }
212
213    /**
214     * Return an array of subpages beginning with $search that this special page will accept.
215     *
216     * @param string $search Prefix to search for
217     * @param int $limit Maximum number of results to return (usually 10)
218     * @param int $offset Number of results to skip (usually 0)
219     * @return string[] Matching subpages
220     */
221    public function prefixSearchSubpages( $search, $limit, $offset ) {
222        $title = Title::newFromText( $search, NS_FILE );
223        if ( !$title || $title->getNamespace() !== NS_FILE ) {
224            // No prefix suggestion outside of file namespace
225            return [];
226        }
227        $searchEngine = $this->searchEngineFactory->create();
228        $searchEngine->setLimitOffset( $limit, $offset );
229        // Autocomplete subpage the same as a normal search, but just for files
230        $searchEngine->setNamespaces( [ NS_FILE ] );
231        $result = $searchEngine->defaultPrefixSearch( $search );
232
233        return array_map( static function ( Title $t ) {
234            // Remove namespace in search suggestion
235            return $t->getText();
236        }, $result );
237    }
238
239    /** @inheritDoc */
240    protected function getGroupName() {
241        return 'media';
242    }
243}
244
245/** @deprecated class alias since 1.41 */
246class_alias( SpecialFileDuplicateSearch::class, 'SpecialFileDuplicateSearch' );