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