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