Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
3.32% covered (danger)
3.32%
22 / 662
3.57% covered (danger)
3.57%
1 / 28
CRAP
0.00% covered (danger)
0.00%
0 / 1
ImagePage
3.32% covered (danger)
3.32%
22 / 662
3.57% covered (danger)
3.57%
1 / 28
18620.28
0.00% covered (danger)
0.00%
0 / 1
 newPage
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setFile
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 loadFile
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
30
 view
0.00% covered (danger)
0.00%
0 / 75
0.00% covered (danger)
0.00%
0 / 1
462
 getDisplayedFile
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 showTOC
0.00% covered (danger)
0.00%
0 / 44
0.00% covered (danger)
0.00%
0 / 1
6
 makeMetadataTable
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
20
 getLanguageForRendering
84.62% covered (warning)
84.62%
11 / 13
0.00% covered (danger)
0.00%
0 / 1
4.06
 openShowImage
0.00% covered (danger)
0.00%
0 / 222
0.00% covered (danger)
0.00%
0 / 1
1722
 getThumbPrevText
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
30
 makeSizeLink
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 printSharedImageText
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
90
 getUploadUrl
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 uploadLinksBox
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
30
 closeShowImage
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 imageHistory
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 queryImageLinks
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 imageLinks
0.00% covered (danger)
0.00%
0 / 88
0.00% covered (danger)
0.00%
0 / 1
272
 imageDupes
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
20
 showError
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 compare
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 doRenderLangOpt
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
20
 createXmlOptionStringForLanguage
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 getThumbSizes
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 getFile
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isLocal
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getDuplicates
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getForeignCategories
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 */
20
21use MediaWiki\Html\Html;
22use MediaWiki\Linker\Linker;
23use MediaWiki\MainConfigNames;
24use MediaWiki\MediaWikiServices;
25use MediaWiki\Request\WebRequest;
26use MediaWiki\SpecialPage\SpecialPage;
27use MediaWiki\Title\Title;
28use MediaWiki\Title\TitleArrayFromResult;
29use MediaWiki\Xml\Xml;
30use Wikimedia\Rdbms\IResultWrapper;
31
32/**
33 * Rendering of file description pages.
34 *
35 * @ingroup Media
36 * @method WikiFilePage getPage()
37 */
38class ImagePage extends Article {
39    use MediaFileTrait;
40
41    /** @var File|false Only temporary false, most code can assume this is a File */
42    private $displayImg;
43
44    /** @var FileRepo */
45    private $repo;
46
47    /** @var bool */
48    private $fileLoaded;
49
50    /** @var string|false Guaranteed to be HTML, {@see File::getDescriptionText} */
51    protected $mExtraDescription = false;
52
53    /**
54     * @param Title $title
55     * @return WikiFilePage
56     */
57    protected function newPage( Title $title ) {
58        // Overload mPage with a file-specific page
59        return new WikiFilePage( $title );
60    }
61
62    /**
63     * @param File $file
64     * @return void
65     */
66    public function setFile( $file ) {
67        $this->getPage()->setFile( $file );
68        $this->displayImg = $file;
69        $this->fileLoaded = true;
70    }
71
72    protected function loadFile() {
73        if ( $this->fileLoaded ) {
74            return;
75        }
76        $this->fileLoaded = true;
77
78        $this->displayImg = $img = false;
79
80        $this->getHookRunner()->onImagePageFindFile( $this, $img, $this->displayImg );
81        if ( !$img ) { // not set by hook?
82            $services = MediaWikiServices::getInstance();
83            $img = $services->getRepoGroup()->findFile( $this->getTitle() );
84            if ( !$img ) {
85                $img = $services->getRepoGroup()->getLocalRepo()->newFile( $this->getTitle() );
86            }
87        }
88        // @phan-suppress-next-line PhanTypeMismatchArgumentNullable should be set
89        $this->getPage()->setFile( $img );
90        if ( !$this->displayImg ) { // not set by hook?
91            // @phan-suppress-next-line PhanPossiblyNullTypeMismatchProperty should be set
92            $this->displayImg = $img;
93        }
94        $this->repo = $img->getRepo();
95    }
96
97    public function view() {
98        $context = $this->getContext();
99        $showEXIF = $context->getConfig()->get( MainConfigNames::ShowEXIF );
100
101        // For action=render, include body text only; none of the image extras
102        if ( $this->viewIsRenderAction ) {
103            parent::view();
104            return;
105        }
106
107        $out = $context->getOutput();
108        $request = $context->getRequest();
109        $diff = $request->getVal( 'diff' );
110
111        if ( $this->getTitle()->getNamespace() !== NS_FILE || ( $diff !== null && $this->isDiffOnlyView() ) ) {
112            parent::view();
113            return;
114        }
115
116        $this->loadFile();
117
118        if (
119            $this->getTitle()->getNamespace() === NS_FILE
120            && $this->getFile()->getRedirected()
121        ) {
122            if (
123                $this->getTitle()->getDBkey() == $this->getFile()->getName()
124                || $diff !== null
125            ) {
126                $request->setVal( 'diffonly', 'true' );
127            }
128
129            parent::view();
130            return;
131        }
132
133        if ( $showEXIF && $this->displayImg->exists() ) {
134            // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
135            $formattedMetadata = $this->displayImg->formatMetadata( $this->getContext() );
136        } else {
137            $formattedMetadata = false;
138        }
139
140        if ( !$diff && $this->displayImg->exists() ) {
141            $out->addHTML( $this->showTOC( (bool)$formattedMetadata ) );
142        }
143
144        if ( !$diff ) {
145            $this->openShowImage();
146        }
147
148        # No need to display noarticletext, we use our own message, output in openShowImage()
149        if ( $this->getPage()->getId() ) {
150            $out->addHTML( Html::openElement( 'div', [ 'id' => 'mw-imagepage-content' ] ) );
151            // NS_FILE pages render mostly in the user language (like special pages),
152            // except the editable wikitext content, which is rendered in the page content
153            // language by the parent class.
154            parent::view();
155            $out->addHTML( Html::closeElement( 'div' ) );
156        } else {
157            # Just need to set the right headers
158            $out->setArticleFlag( true );
159            $out->setPageTitle( $this->getTitle()->getPrefixedText() );
160            $this->getPage()->doViewUpdates(
161                $context->getAuthority(),
162                $this->getOldID()
163            );
164        }
165
166        # Show shared description, if needed
167        if ( $this->mExtraDescription ) {
168            $fol = $context->msg( 'shareddescriptionfollows' );
169            if ( !$fol->isDisabled() ) {
170                $out->addWikiTextAsInterface( $fol->plain() );
171            }
172            $out->addHTML(
173                Html::rawElement(
174                    'div',
175                    [ 'id' => 'shared-image-desc' ],
176                    $this->mExtraDescription
177                ) . "\n"
178            );
179        }
180
181        $this->closeShowImage();
182        $this->imageHistory();
183        // TODO: Cleanup the following
184
185        $out->addHTML( Xml::element( 'h2',
186            [ 'id' => 'filelinks' ],
187                $context->msg( 'imagelinks' )->text() ) . "\n" );
188        $this->imageDupes();
189        # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
190        # Yet we return metadata about the target. Definitely an issue in the FileRepo
191        $this->imageLinks();
192
193        # Allow extensions to add something after the image links
194        $html = '';
195        $this->getHookRunner()->onImagePageAfterImageLinks( $this, $html );
196        if ( $html ) {
197            $out->addHTML( $html );
198        }
199
200        if ( $formattedMetadata ) {
201            $out->addHTML( Xml::element(
202                'h2',
203                [ 'id' => 'metadata' ],
204                    $context->msg( 'metadata' )->text() ) . "\n" );
205            $out->wrapWikiTextAsInterface(
206                'mw-imagepage-section-metadata',
207                $this->makeMetadataTable( $formattedMetadata )
208            );
209            $out->addModules( [ 'mediawiki.action.view.metadata' ] );
210        }
211
212        // Add remote Filepage.css
213        if ( !$this->repo->isLocal() ) {
214            $css = $this->repo->getDescriptionStylesheetUrl();
215            if ( $css ) {
216                $out->addStyle( $css );
217            }
218        }
219
220        $out->addModuleStyles( [
221            'mediawiki.action.view.filepage', // Add MediaWiki styles for a file page
222        ] );
223    }
224
225    /**
226     * @return File
227     */
228    public function getDisplayedFile() {
229        $this->loadFile();
230        return $this->displayImg;
231    }
232
233    /**
234     * Create the TOC
235     *
236     * @param bool $metadata Whether or not to show the metadata link
237     * @return string
238     */
239    protected function showTOC( $metadata ) {
240        $r = [
241            Html::rawElement(
242                'li',
243                [],
244                Html::rawElement(
245                    'a',
246                    [ 'href' => '#file' ],
247                    $this->getContext()->msg( 'file-anchor-link' )->escaped()
248                )
249            ),
250            Html::rawElement(
251                'li',
252                [],
253                Html::rawElement(
254                    'a',
255                    [ 'href' => '#filehistory' ],
256                    $this->getContext()->msg( 'filehist' )->escaped()
257                )
258            ),
259            Html::rawElement(
260                'li',
261                [],
262                Html::rawElement(
263                    'a',
264                    [ 'href' => '#filelinks' ],
265                    $this->getContext()->msg( 'imagelinks' )->escaped()
266                )
267            ),
268        ];
269
270        $this->getHookRunner()->onImagePageShowTOC( $this, $r );
271
272        if ( $metadata ) {
273            $r[] = Html::rawElement(
274                'li',
275                [],
276                Html::rawElement(
277                    'a',
278                    [ 'href' => '#metadata' ],
279                    $this->getContext()->msg( 'metadata' )->escaped()
280                )
281            );
282        }
283
284        return Html::rawElement( 'ul', [
285            'id' => 'filetoc',
286            'role' => 'navigation'
287        ], implode( "\n", $r ) );
288    }
289
290    /**
291     * Make a table with metadata to be shown in the output page.
292     *
293     * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
294     *
295     * @param array $metadata The array containing the Exif data
296     * @return string The metadata table. This is treated as Wikitext (!)
297     */
298    protected function makeMetadataTable( $metadata ) {
299        $r = $this->getContext()->msg( 'metadata-help' )->plain();
300        // Initial state of collapsible rows is collapsed
301        // see mediawiki.action.view.filepage.less and mediawiki.action.view.metadata module.
302        $r .= "<table id=\"mw_metadata\" class=\"mw_metadata collapsed\">\n";
303        foreach ( $metadata as $type => $stuff ) {
304            foreach ( $stuff as $v ) {
305                $class = str_replace( ' ', '_', $v['id'] );
306                if ( $type === 'collapsed' ) {
307                    $class .= ' mw-metadata-collapsible';
308                }
309                $r .= Html::rawElement( 'tr',
310                    [ 'class' => $class ],
311                    Html::rawElement( 'th', [], $v['name'] )
312                        . Html::rawElement( 'td', [], $v['value'] )
313                );
314            }
315        }
316        $r .= "</table>\n";
317        return $r;
318    }
319
320    /**
321     * Returns language code to be used for displaying the image, based on request context and
322     * languages available in the file.
323     *
324     * @param WebRequest $request
325     * @param File $file
326     * @return string|null a valid IETF language tag
327     */
328    private function getLanguageForRendering( WebRequest $request, File $file ) {
329        $handler = $file->getHandler();
330        if ( !$handler ) {
331            return null;
332        }
333
334        $requestLanguage = $request->getVal( 'lang' );
335        if ( $requestLanguage === null ) {
336            // For on File pages about a translatable SVG, decide which
337            // language to render the large thumbnail in (T310445)
338            $services = MediaWikiServices::getInstance();
339            $variantLangCode = $services->getLanguageConverterFactory()
340                ->getLanguageConverter( $services->getContentLanguage() )
341                ->getPreferredVariant();
342            $requestLanguage = LanguageCode::bcp47( $variantLangCode );
343        }
344        if ( $handler->validateParam( 'lang', $requestLanguage ) ) {
345            return $file->getMatchedLanguage( $requestLanguage );
346        }
347
348        return $handler->getDefaultRenderLanguage( $file );
349    }
350
351    protected function openShowImage() {
352        $context = $this->getContext();
353        $mainConfig = $context->getConfig();
354        $enableUploads = $mainConfig->get( MainConfigNames::EnableUploads );
355        $send404Code = $mainConfig->get( MainConfigNames::Send404Code );
356        $svgMaxSize = $mainConfig->get( MainConfigNames::SVGMaxSize );
357        $enableLegacyMediaDOM = $mainConfig->get( MainConfigNames::ParserEnableLegacyMediaDOM );
358        $this->loadFile();
359        $out = $context->getOutput();
360        $user = $context->getUser();
361        $lang = $context->getLanguage();
362        $dirmark = $lang->getDirMarkEntity();
363        $request = $context->getRequest();
364
365        if ( $this->displayImg->exists() ) {
366            [ $maxWidth, $maxHeight ] = $this->getImageLimitsFromOption( $user, 'imagesize' );
367
368            # image
369            $page = $request->getIntOrNull( 'page' );
370            if ( $page === null ) {
371                $params = [];
372                $page = 1;
373            } else {
374                $params = [ 'page' => $page ];
375            }
376
377            $renderLang = $this->getLanguageForRendering( $request, $this->displayImg );
378            if ( $renderLang !== null ) {
379                $params['lang'] = $renderLang;
380            }
381
382            $width_orig = $this->displayImg->getWidth( $page );
383            $width = $width_orig;
384            $height_orig = $this->displayImg->getHeight( $page );
385            $height = $height_orig;
386
387            $filename = wfEscapeWikiText( $this->displayImg->getName() );
388            $linktext = $filename;
389
390            $this->getHookRunner()->onImageOpenShowImageInlineBefore( $this, $out );
391
392            if ( $this->displayImg->allowInlineDisplay() ) {
393                # image
394                # "Download high res version" link below the image
395                # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
396                #   Language::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
397                # We'll show a thumbnail of this image
398                if ( $width > $maxWidth ||
399                    $height > $maxHeight ||
400                    $this->displayImg->isVectorized()
401                ) {
402                    [ $width, $height ] = $this->displayImg->getDisplayWidthHeight(
403                        $maxWidth, $maxHeight, $page
404                    );
405                    $linktext = $context->msg( 'show-big-image' )->escaped();
406
407                    $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
408                    # Generate thumbnails or thumbnail links as needed...
409                    $otherSizes = [];
410                    foreach ( $thumbSizes as $size ) {
411                        // We include a thumbnail size in the list, if it is
412                        // less than or equal to the original size of the image
413                        // asset ($width_orig/$height_orig). We also exclude
414                        // the current thumbnail's size ($width/$height)
415                        // since that is added to the message separately, so
416                        // it can be denoted as the current size being shown.
417                        // Vectorized images are limited by $wgSVGMaxSize big,
418                        // so all thumbs less than or equal that are shown.
419                        if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
420                                || ( $this->displayImg->isVectorized()
421                                    && max( $size[0], $size[1] ) <= $svgMaxSize )
422                            )
423                            && $size[0] != $width && $size[1] != $height
424                            && $size[0] != $maxWidth && $size[1] != $maxHeight
425                        ) {
426                            $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
427                            if ( $sizeLink ) {
428                                $otherSizes[] = $sizeLink;
429                            }
430                        }
431                    }
432                    $otherSizes = array_unique( $otherSizes );
433
434                    $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
435                    $msgsmall = $this->getThumbPrevText( $params, $sizeLinkBigImagePreview );
436                    if ( count( $otherSizes ) ) {
437                        $msgsmall .= ' ' .
438                        Html::rawElement(
439                            'span',
440                            [ 'class' => 'mw-filepage-other-resolutions' ],
441                            $context->msg( 'show-big-image-other' )
442                                ->rawParams( $lang->pipeList( $otherSizes ) )
443                                ->params( count( $otherSizes ) )
444                                ->parse()
445                        );
446                    }
447                } elseif ( $width == 0 && $height == 0 ) {
448                    # Some sort of audio file that doesn't have dimensions
449                    # Don't output a no hi res message for such a file
450                    $msgsmall = '';
451                } else {
452                    # Image is small enough to show full size on image page
453                    $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
454                }
455
456                $params['width'] = $width;
457                $params['height'] = $height;
458                $params['isFilePageThumb'] = true;
459                // Allow the MediaHandler to handle query string parameters on the file page,
460                // e.g. start time for videos (T203994)
461                $params['imagePageParams'] = $request->getQueryValuesOnly();
462                $thumbnail = $this->displayImg->transform( $params );
463                Linker::processResponsiveImages( $this->displayImg, $thumbnail, $params );
464
465                $anchorclose = Html::rawElement(
466                    'div',
467                    [ 'class' => 'mw-filepage-resolutioninfo' ],
468                    $msgsmall
469                );
470
471                $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
472                if ( $isMulti ) {
473                    $out->addModules( 'mediawiki.page.image.pagination' );
474                    /* TODO: multipageimage class is deprecated since Jan 2023 */
475                    $out->addHTML( '<div class="mw-filepage-multipage multipageimage">' );
476                }
477
478                if ( $thumbnail ) {
479                    $options = [
480                        'alt' => $this->displayImg->getTitle()->getPrefixedText(),
481                        'file-link' => true,
482                    ];
483                    $out->addHTML(
484                        Html::rawElement(
485                            'div',
486                            [ 'class' => 'fullImageLink', 'id' => 'file' ],
487                            $thumbnail->toHtml( $options ) . $anchorclose
488                        ) . "\n"
489                    );
490                }
491
492                if ( $isMulti ) {
493                    $linkPrev = $linkNext = '';
494                    $count = $this->displayImg->pageCount();
495                    if ( !$enableLegacyMediaDOM ) {
496                        $out->addModules( 'mediawiki.page.media' );
497                    }
498
499                    if ( $page > 1 ) {
500                        $label = $context->msg( 'imgmultipageprev' )->text();
501                        // on the client side, this link is generated in ajaxifyPageNavigation()
502                        // in the mediawiki.page.image.pagination module
503                        $linkPrev = $this->linkRenderer->makeKnownLink(
504                            $this->getTitle(),
505                            $label,
506                            [],
507                            [ 'page' => $page - 1 ]
508                        );
509                        $thumbPrevPage = Linker::makeThumbLinkObj(
510                            $this->getTitle(),
511                            $this->displayImg,
512                            $linkPrev,
513                            $label,
514                            'none',
515                            [ 'page' => $page - 1, 'isFilePageThumb' => true ]
516                        );
517                    } else {
518                        $thumbPrevPage = '';
519                    }
520
521                    if ( $page < $count ) {
522                        $label = $context->msg( 'imgmultipagenext' )->text();
523                        $linkNext = $this->linkRenderer->makeKnownLink(
524                            $this->getTitle(),
525                            $label,
526                            [],
527                            [ 'page' => $page + 1 ]
528                        );
529                        $thumbNextPage = Linker::makeThumbLinkObj(
530                            $this->getTitle(),
531                            $this->displayImg,
532                            $linkNext,
533                            $label,
534                            'none',
535                            [ 'page' => $page + 1, 'isFilePageThumb' => true ]
536                        );
537                    } else {
538                        $thumbNextPage = '';
539                    }
540
541                    $script = $mainConfig->get( MainConfigNames::Script );
542
543                    $formParams = [
544                        'name' => 'pageselector',
545                        'action' => $script,
546                    ];
547                    $options = [];
548                    for ( $i = 1; $i <= $count; $i++ ) {
549                        $options[] = Xml::option( $lang->formatNum( $i ), (string)$i, $i == $page );
550                    }
551                    $select = Xml::tags( 'select',
552                        [ 'id' => 'pageselector', 'name' => 'page' ],
553                        implode( "\n", $options ) );
554
555                    /* TODO: multipageimagenavbox class is deprecated since Jan 2023 */
556                    $out->addHTML(
557                        '<div class="mw-filepage-multipage-navigation multipageimagenavbox">' .
558                        $linkPrev .
559                        Html::rawElement( 'form', $formParams,
560                            Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
561                            $context->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
562                            $context->msg( 'word-separator' )->escaped() .
563                            Xml::submitButton( $context->msg( 'imgmultigo' )->text() )
564                        ) .
565                        "$thumbPrevPage\n$thumbNextPage\n$linkNext</div></div>"
566                    );
567                }
568            } elseif ( $this->displayImg->isSafeFile() ) {
569                # if direct link is allowed but it's not a renderable image, show an icon.
570                $icon = $this->displayImg->iconThumb();
571
572                $out->addHTML(
573                    Html::rawElement(
574                        'div',
575                        [ 'class' => 'fullImageLink', 'id' => 'file' ],
576                        $icon->toHtml( [ 'file-link' => true ] )
577                    ) . "\n"
578                );
579            }
580
581            $longDesc = $context->msg( 'parentheses', $this->displayImg->getLongDesc() )->text();
582
583            $handler = $this->displayImg->getHandler();
584
585            // If this is a filetype with potential issues, warn the user.
586            if ( $handler ) {
587                $warningConfig = $handler->getWarningConfig( $this->displayImg );
588
589                if ( $warningConfig !== null ) {
590                    // The warning will be displayed via CSS and JavaScript.
591                    // We just need to tell the client side what message to use.
592                    $output = $context->getOutput();
593                    $output->addJsConfigVars( 'wgFileWarning', $warningConfig );
594                    $output->addModules( $warningConfig['module'] );
595                    $output->addModules( 'mediawiki.filewarning' );
596                }
597            }
598
599            $medialink = "[[Media:$filename|$linktext]]";
600
601            if ( !$this->displayImg->isSafeFile() ) {
602                $warning = $context->msg( 'mediawarning' )->plain();
603                // dirmark is needed here to separate the file name, which
604                // most likely ends in Latin characters, from the description,
605                // which may begin with the file type. In RTL environment
606                // this will get messy.
607                // The dirmark, however, must not be immediately adjacent
608                // to the filename, because it can get copied with it.
609                // See T27277.
610                // phpcs:disable Generic.Files.LineLength
611                $out->wrapWikiTextAsInterface( 'fullMedia', <<<EOT
612<span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span>
613EOT
614                );
615                // phpcs:enable
616                $out->wrapWikiTextAsInterface( 'mediaWarning', $warning );
617            } else {
618                $out->wrapWikiTextAsInterface( 'fullMedia', <<<EOT
619{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
620EOT
621                );
622            }
623
624            $renderLangOptions = $this->displayImg->getAvailableLanguages();
625            if ( count( $renderLangOptions ) >= 1 ) {
626                $out->addHTML( $this->doRenderLangOpt( $renderLangOptions, $renderLang ) );
627            }
628
629            // Add cannot animate thumbnail warning
630            if ( !$this->displayImg->canAnimateThumbIfAppropriate() ) {
631                // Include the extension so wiki admins can
632                // customize it on a per file-type basis
633                // (aka say things like use format X instead).
634                // additionally have a specific message for
635                // file-no-thumb-animation-gif
636                $ext = $this->displayImg->getExtension();
637                $noAnimMesg = wfMessageFallback(
638                    'file-no-thumb-animation-' . $ext,
639                    'file-no-thumb-animation'
640                )->setContext( $context )->plain();
641
642                $out->wrapWikiTextAsInterface( 'mw-noanimatethumb', $noAnimMesg );
643            }
644
645            if ( !$this->displayImg->isLocal() ) {
646                $this->printSharedImageText();
647            }
648        } else {
649            # Image does not exist
650            if ( !$this->getPage()->getId() ) {
651                $dbr = $this->dbProvider->getReplicaDatabase();
652
653                # No article exists either
654                # Show deletion log to be consistent with normal articles
655                LogEventsList::showLogExtract(
656                    $out,
657                    [ 'delete', 'move', 'protect' ],
658                    $this->getTitle()->getPrefixedText(),
659                    '',
660                    [ 'lim' => 10,
661                        'conds' => [ $dbr->expr( 'log_action', '!=', 'revision' ) ],
662                        'showIfEmpty' => false,
663                        'msgKey' => [ 'moveddeleted-notice' ]
664                    ]
665                );
666            }
667
668            if ( $enableUploads &&
669                $context->getAuthority()->isAllowed( 'upload' )
670            ) {
671                // Only show an upload link if the user can upload
672                $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
673                $nofile = [
674                    'filepage-nofile-link',
675                    $uploadTitle->getFullURL( [
676                        'wpDestFile' => $this->getFile()->getName()
677                    ] )
678                ];
679            } else {
680                $nofile = 'filepage-nofile';
681            }
682            // Note, if there is an image description page, but
683            // no image, then this setRobotPolicy is overridden
684            // by Article::View().
685            $out->setRobotPolicy( 'noindex,nofollow' );
686            $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
687            if ( !$this->getPage()->getId() && $send404Code ) {
688                // If there is no image, no shared image, and no description page,
689                // output a 404, to be consistent with Article::showMissingArticle.
690                $request->response()->statusHeader( 404 );
691            }
692        }
693        $out->setFileVersion( $this->displayImg );
694    }
695
696    /**
697     * Make the text under the image to say what size preview
698     *
699     * @param array $params parameters for thumbnail
700     * @param string $sizeLinkBigImagePreview HTML for the current size
701     * @return string HTML output
702     */
703    protected function getThumbPrevText( $params, $sizeLinkBigImagePreview ) {
704        if ( $sizeLinkBigImagePreview ) {
705            // Show a different message of preview is different format from original.
706            $previewTypeDiffers = false;
707            $origExt = $thumbExt = $this->displayImg->getExtension();
708            if ( $this->displayImg->getHandler() ) {
709                $origMime = $this->displayImg->getMimeType();
710                $typeParams = $params;
711                $this->displayImg->getHandler()->normaliseParams( $this->displayImg, $typeParams );
712                [ $thumbExt, $thumbMime ] = $this->displayImg->getHandler()->getThumbType(
713                    $origExt, $origMime, $typeParams );
714                if ( $thumbMime !== $origMime ) {
715                    $previewTypeDiffers = true;
716                }
717            }
718            if ( $previewTypeDiffers ) {
719                return $this->getContext()->msg( 'show-big-image-preview-differ' )->
720                    rawParams( $sizeLinkBigImagePreview )->
721                    params( strtoupper( $origExt ) )->
722                    params( strtoupper( $thumbExt ) )->
723                    parse();
724            } else {
725                return $this->getContext()->msg( 'show-big-image-preview' )->
726                    rawParams( $sizeLinkBigImagePreview )->
727                parse();
728            }
729        } else {
730            return '';
731        }
732    }
733
734    /**
735     * Creates a thumbnail of specified size and returns an HTML link to it
736     * @param array $params Scaler parameters
737     * @param int $width
738     * @param int $height
739     * @return string
740     */
741    protected function makeSizeLink( $params, $width, $height ) {
742        $params['width'] = $width;
743        $params['height'] = $height;
744        $thumbnail = $this->displayImg->transform( $params );
745        if ( $thumbnail && !$thumbnail->isError() ) {
746            return Html::rawElement( 'a', [
747                'href' => $thumbnail->getUrl(),
748                'class' => 'mw-thumbnail-link'
749                ], $this->getContext()->msg( 'show-big-image-size' )->numParams(
750                    $thumbnail->getWidth(), $thumbnail->getHeight()
751                )->parse() );
752        } else {
753            return '';
754        }
755    }
756
757    /**
758     * Show a notice that the file is from a shared repository
759     */
760    protected function printSharedImageText() {
761        $out = $this->getContext()->getOutput();
762        $this->loadFile();
763
764        $descUrl = $this->getFile()->getDescriptionUrl();
765        $descText = $this->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
766
767        /* Add canonical to head if there is no local page for this shared file */
768        if ( $descUrl && !$this->getPage()->getId() ) {
769            $out->setCanonicalUrl( $descUrl );
770        }
771
772        $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
773        $repo = $this->getFile()->getRepo()->getDisplayName();
774
775        if ( $descUrl &&
776            $descText &&
777            !$this->getContext()->msg( 'sharedupload-desc-here' )->isDisabled()
778        ) {
779            $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-here', $repo, $descUrl ] );
780        } elseif ( $descUrl &&
781            !$this->getContext()->msg( 'sharedupload-desc-there' )->isDisabled()
782        ) {
783            $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-there', $repo, $descUrl ] );
784        } else {
785            $out->wrapWikiMsg( $wrap, [ 'sharedupload', $repo ], ''/*BACKCOMPAT*/ );
786        }
787
788        if ( $descText ) {
789            $this->mExtraDescription = $descText;
790        }
791    }
792
793    public function getUploadUrl() {
794        $this->loadFile();
795        $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
796        return $uploadTitle->getFullURL( [
797            'wpDestFile' => $this->getFile()->getName(),
798            'wpForReUpload' => 1
799        ] );
800    }
801
802    /**
803     * Add the re-upload link (or message about not being able to re-upload) to the output.
804     */
805    protected function uploadLinksBox() {
806        if ( !$this->getContext()->getConfig()->get( MainConfigNames::EnableUploads ) ) {
807            return;
808        }
809
810        $this->loadFile();
811        if ( !$this->getFile()->isLocal() ) {
812            return;
813        }
814
815        $canUpload = $this->getContext()->getAuthority()
816            ->probablyCan( 'upload', $this->getTitle() );
817        if ( $canUpload && UploadBase::userCanReUpload(
818                $this->getContext()->getAuthority(),
819                $this->getFile() )
820        ) {
821            // "Upload a new version of this file" link
822            $ulink = $this->linkRenderer->makeExternalLink(
823                $this->getUploadUrl(),
824                $this->getContext()->msg( 'uploadnewversion-linktext' ),
825                $this->getTitle()
826            );
827            $attrs = [ 'class' => 'plainlinks', 'id' => 'mw-imagepage-reupload-link' ];
828            $linkPara = Html::rawElement( 'p', $attrs, $ulink );
829        } else {
830            // "You cannot overwrite this file." message
831            $attrs = [ 'id' => 'mw-imagepage-upload-disallowed' ];
832            $msg = $this->getContext()->msg( 'upload-disallowed-here' )->text();
833            $linkPara = Html::element( 'p', $attrs, $msg );
834        }
835
836        $uploadLinks = Html::rawElement( 'div', [ 'class' => 'mw-imagepage-upload-links' ], $linkPara );
837        $this->getContext()->getOutput()->addHTML( $uploadLinks );
838    }
839
840    /**
841     * For overloading
842     */
843    protected function closeShowImage() {
844    }
845
846    /**
847     * If the page we've just displayed is in the "Image" namespace,
848     * we follow it with an upload history of the image and its usage.
849     */
850    protected function imageHistory() {
851        $this->loadFile();
852        $out = $this->getContext()->getOutput();
853        $pager = new ImageHistoryPseudoPager(
854            $this,
855            MediaWikiServices::getInstance()->getLinkBatchFactory()
856        );
857        $out->addHTML( $pager->getBody() );
858        $out->setPreventClickjacking( $pager->getPreventClickjacking() );
859
860        $this->getFile()->resetHistory(); // free db resources
861
862        # Exist check because we don't want to show this on pages where an image
863        # doesn't exist along with the noimage message, that would suck. -√¶var
864        if ( $this->getFile()->exists() ) {
865            $this->uploadLinksBox();
866        }
867    }
868
869    /**
870     * @param string|string[] $target
871     * @param int $limit
872     * @return IResultWrapper
873     */
874    protected function queryImageLinks( $target, $limit ) {
875        return $this->dbProvider->getReplicaDatabase()->newSelectQueryBuilder()
876            ->select( [ 'page_namespace', 'page_title', 'il_to' ] )
877            ->from( 'imagelinks' )
878            ->join( 'page', null, 'il_from = page_id' )
879            ->where( [ 'il_to' => $target ] )
880            ->orderBy( 'il_from' )
881            ->limit( $limit + 1 )
882            ->caller( __METHOD__ )->fetchResultSet();
883    }
884
885    protected function imageLinks() {
886        $limit = 100;
887
888        $out = $this->getContext()->getOutput();
889
890        $rows = [];
891        $redirects = [];
892        foreach ( $this->getTitle()->getRedirectsHere( NS_FILE ) as $redir ) {
893            $redirects[$redir->getDBkey()] = [];
894            $rows[] = (object)[
895                'page_namespace' => NS_FILE,
896                'page_title' => $redir->getDBkey(),
897            ];
898        }
899
900        $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit + 1 );
901        foreach ( $res as $row ) {
902            $rows[] = $row;
903        }
904        $count = count( $rows );
905
906        $hasMore = $count > $limit;
907        if ( !$hasMore && count( $redirects ) ) {
908            $res = $this->queryImageLinks( array_keys( $redirects ),
909                $limit - count( $rows ) + 1 );
910            foreach ( $res as $row ) {
911                $redirects[$row->il_to][] = $row;
912                $count++;
913            }
914            $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
915        }
916
917        if ( $count == 0 ) {
918            $out->wrapWikiMsg(
919                Html::rawElement( 'div',
920                    [ 'id' => 'mw-imagepage-nolinkstoimage' ], "\n$1\n" ),
921                'nolinkstoimage'
922            );
923            return;
924        }
925
926        $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
927        if ( !$hasMore ) {
928            $out->addWikiMsg( 'linkstoimage', $count );
929        } else {
930            // More links than the limit. Add a link to [[Special:Whatlinkshere]]
931            $out->addWikiMsg( 'linkstoimage-more',
932                $this->getContext()->getLanguage()->formatNum( $limit ),
933                $this->getTitle()->getPrefixedDBkey()
934            );
935        }
936
937        $out->addHTML(
938            Html::openElement( 'ul',
939                [ 'class' => 'mw-imagepage-linkstoimage' ] ) . "\n"
940        );
941        // Sort the list by namespace:title
942        usort( $rows, [ $this, 'compare' ] );
943
944        // Create links for every element
945        $currentCount = 0;
946        foreach ( $rows as $element ) {
947            $currentCount++;
948            if ( $currentCount > $limit ) {
949                break;
950            }
951
952            $link = $this->linkRenderer->makeKnownLink(
953                Title::makeTitle( $element->page_namespace, $element->page_title ),
954                null,
955                [],
956                // Add a redirect=no to make redirect pages reachable
957                [ 'redirect' => isset( $redirects[$element->page_title] ) ? 'no' : null ]
958            );
959            if ( !isset( $redirects[$element->page_title] ) ) {
960                # No redirects
961                $liContents = $link;
962            } elseif ( count( $redirects[$element->page_title] ) === 0 ) {
963                # Redirect without usages
964                $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )
965                    ->rawParams( $link, '' )
966                    ->parse();
967            } else {
968                # Redirect with usages
969                $li = '';
970                foreach ( $redirects[$element->page_title] as $row ) {
971                    $currentCount++;
972                    if ( $currentCount > $limit ) {
973                        break;
974                    }
975
976                    $link2 = $this->linkRenderer->makeKnownLink(
977                        Title::makeTitle( $row->page_namespace, $row->page_title ) );
978                    $li .= Html::rawElement(
979                        'li',
980                        [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
981                        $link2
982                        ) . "\n";
983                }
984
985                $ul = Html::rawElement(
986                    'ul',
987                    [ 'class' => 'mw-imagepage-redirectstofile' ],
988                    $li
989                    ) . "\n";
990                $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
991                    $link, $ul )->parse();
992            }
993            $out->addHTML( Html::rawElement(
994                    'li',
995                    [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
996                    $liContents
997                ) . "\n"
998            );
999
1000        }
1001        $out->addHTML( Html::closeElement( 'ul' ) . "\n" );
1002        $res->free();
1003
1004        // Add a links to [[Special:Whatlinkshere]]
1005        if ( $currentCount > $limit ) {
1006            $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
1007        }
1008        $out->addHTML( Html::closeElement( 'div' ) . "\n" );
1009    }
1010
1011    protected function imageDupes() {
1012        $this->loadFile();
1013        $out = $this->getContext()->getOutput();
1014
1015        $dupes = $this->getPage()->getDuplicates();
1016        if ( count( $dupes ) == 0 ) {
1017            return;
1018        }
1019
1020        $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
1021        $out->addWikiMsg( 'duplicatesoffile',
1022            $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
1023        );
1024        $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
1025
1026        /**
1027         * @var File $file
1028         */
1029        foreach ( $dupes as $file ) {
1030            $fromSrc = '';
1031            if ( $file->isLocal() ) {
1032                $link = $this->linkRenderer->makeKnownLink( $file->getTitle() );
1033            } else {
1034                $link = $this->linkRenderer->makeExternalLink(
1035                    $file->getDescriptionUrl(),
1036                    $file->getTitle()->getPrefixedText(),
1037                    $this->getTitle()
1038                );
1039                $fromSrc = $this->getContext()->msg(
1040                    'shared-repo-from',
1041                    $file->getRepo()->getDisplayName()
1042                )->escaped();
1043            }
1044            $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
1045        }
1046        $out->addHTML( "</ul></div>\n" );
1047    }
1048
1049    /**
1050     * Display an error with a wikitext description
1051     *
1052     * @param string $description
1053     */
1054    public function showError( $description ) {
1055        $out = $this->getContext()->getOutput();
1056        $out->setPageTitleMsg( $this->getContext()->msg( 'internalerror' ) );
1057        $out->setRobotPolicy( 'noindex,nofollow' );
1058        $out->setArticleRelated( false );
1059        $out->disableClientCache();
1060        $out->addWikiTextAsInterface( $description );
1061    }
1062
1063    /**
1064     * Callback for usort() to do link sorts by (namespace, title)
1065     * Function copied from Title::compare()
1066     *
1067     * @param stdClass $a Object page to compare with
1068     * @param stdClass $b Object page to compare with
1069     * @return int Result of string comparison, or namespace comparison
1070     */
1071    protected function compare( $a, $b ) {
1072        return $a->page_namespace <=> $b->page_namespace
1073            ?: strcmp( $a->page_title, $b->page_title );
1074    }
1075
1076    /**
1077     * Output a drop-down box for language options for the file
1078     *
1079     * @param array $langChoices Array of string language codes
1080     * @param string|null $renderLang Language code for the language we want the file to rendered in,
1081     *  it is pre-selected in the drop down box, use null to select the default case in the option list
1082     * @return string HTML to insert underneath image.
1083     */
1084    protected function doRenderLangOpt( array $langChoices, $renderLang ) {
1085        $context = $this->getContext();
1086        $script = $context->getConfig()->get( MainConfigNames::Script );
1087        $opts = '';
1088
1089        $matchedRenderLang = $renderLang === null ? null : $this->displayImg->getMatchedLanguage( $renderLang );
1090
1091        foreach ( $langChoices as $lang ) {
1092            $opts .= $this->createXmlOptionStringForLanguage(
1093                $lang,
1094                $matchedRenderLang === $lang
1095            );
1096        }
1097
1098        // Allow for the default case in an svg <switch> that is displayed if no
1099        // systemLanguage attribute matches
1100        $opts .= "\n" .
1101            Xml::option(
1102                $context->msg( 'img-lang-default' )->text(),
1103                'und',
1104                $matchedRenderLang === null || $matchedRenderLang === 'und'
1105            );
1106
1107        $select = Html::rawElement(
1108            'select',
1109            [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1110            $opts
1111        );
1112        $submit = Xml::submitButton( $context->msg( 'img-lang-go' )->text() );
1113
1114        $formContents = $context->msg( 'img-lang-info' )
1115            ->rawParams( $select, $submit )
1116            ->parse();
1117        $formContents .= Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1118
1119        $langSelectLine = Html::rawElement( 'div', [ 'id' => 'mw-imglangselector-line' ],
1120            Html::rawElement( 'form', [ 'action' => $script ], $formContents )
1121        );
1122        return $langSelectLine;
1123    }
1124
1125    /**
1126     * @param string $lang
1127     * @param bool $selected
1128     * @return string
1129     */
1130    private function createXmlOptionStringForLanguage( $lang, $selected ) {
1131        // TODO: There is no good way to get the language name of a BCP code,
1132        // as MW language codes take precedence
1133        $name = MediaWikiServices::getInstance()
1134            ->getLanguageNameUtils()
1135            ->getLanguageName( $lang, $this->getContext()->getLanguage()->getCode() );
1136        if ( $name !== '' ) {
1137            $display = $this->getContext()->msg( 'img-lang-opt', $lang, $name )->text();
1138        } else {
1139            $display = $lang;
1140        }
1141        return "\n" .
1142            Xml::option(
1143                $display,
1144                $lang,
1145                $selected
1146            );
1147    }
1148
1149    /**
1150     * Get alternative thumbnail sizes.
1151     *
1152     * @note This will only list several alternatives if thumbnails are rendered on 404
1153     * @param int $origWidth Actual width of image
1154     * @param int $origHeight Actual height of image
1155     * @return int[][] An array of [width, height] pairs.
1156     * @phan-return array<int,array{0:int,1:int}>
1157     */
1158    protected function getThumbSizes( $origWidth, $origHeight ) {
1159        $context = $this->getContext();
1160        $imageLimits = $context->getConfig()->get( MainConfigNames::ImageLimits );
1161        if ( $this->displayImg->getRepo()->canTransformVia404() ) {
1162            $thumbSizes = $imageLimits;
1163            // Also include the full sized resolution in the list, so
1164            // that users know they can get it. This will link to the
1165            // original file asset if mustRender() === false. In the case
1166            // that we mustRender, some users have indicated that they would
1167            // find it useful to have the full size image in the rendered
1168            // image format.
1169            $thumbSizes[] = [ $origWidth, $origHeight ];
1170        } else {
1171            # Creating thumb links triggers thumbnail generation.
1172            # Just generate the thumb for the current users prefs.
1173            $thumbSizes = [
1174                $this->getImageLimitsFromOption( $context->getUser(), 'thumbsize' )
1175            ];
1176            if ( !$this->displayImg->mustRender() ) {
1177                // We can safely include a link to the "full-size" preview,
1178                // without actually rendering.
1179                $thumbSizes[] = [ $origWidth, $origHeight ];
1180            }
1181        }
1182        return $thumbSizes;
1183    }
1184
1185    /**
1186     * @see WikiFilePage::getFile
1187     * @return File
1188     */
1189    public function getFile(): File {
1190        return $this->getPage()->getFile();
1191    }
1192
1193    /**
1194     * @see WikiFilePage::isLocal
1195     * @return bool
1196     */
1197    public function isLocal() {
1198        return $this->getPage()->isLocal();
1199    }
1200
1201    /**
1202     * @see WikiFilePage::getDuplicates
1203     * @return File[]|null
1204     */
1205    public function getDuplicates() {
1206        return $this->getPage()->getDuplicates();
1207    }
1208
1209    /**
1210     * @see WikiFilePage::getForeignCategories
1211     * @return TitleArrayFromResult
1212     */
1213    public function getForeignCategories() {
1214        return $this->getPage()->getForeignCategories();
1215    }
1216
1217}