Debian Codegraph @

includes/page/ImagePage.php

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