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