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