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