Move remaining LoadBalancer classes to Rdbms
[mediawiki.git] / includes / page / ImagePage.php
blobc75cfdd26d58202fa025ac45c219bdbcdedcd008
1 <?php
2 /**
3 * Special handling for file description pages.
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.
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.
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
20 * @file
23 /**
24 * Class for viewing MediaWiki file description pages
26 * @ingroup Media
28 class ImagePage extends Article {
29 /** @var File */
30 private $displayImg;
32 /** @var FileRepo */
33 private $repo;
35 /** @var bool */
36 private $fileLoaded;
38 /** @var bool */
39 protected $mExtraDescription = false;
41 /**
42 * @var WikiFilePage
44 protected $mPage;
46 /**
47 * @param Title $title
48 * @return WikiFilePage
50 protected function newPage( Title $title ) {
51 // Overload mPage with a file-specific page
52 return new WikiFilePage( $title );
55 /**
56 * @param File $file
57 * @return void
59 public function setFile( $file ) {
60 $this->mPage->setFile( $file );
61 $this->displayImg = $file;
62 $this->fileLoaded = true;
65 protected function loadFile() {
66 if ( $this->fileLoaded ) {
67 return;
69 $this->fileLoaded = true;
71 $this->displayImg = $img = false;
73 Hooks::run( 'ImagePageFindFile', [ $this, &$img, &$this->displayImg ] );
74 if ( !$img ) { // not set by hook?
75 $img = wfFindFile( $this->getTitle() );
76 if ( !$img ) {
77 $img = wfLocalFile( $this->getTitle() );
80 $this->mPage->setFile( $img );
81 if ( !$this->displayImg ) { // not set by hook?
82 $this->displayImg = $img;
84 $this->repo = $img->getRepo();
87 /**
88 * Handler for action=render
89 * Include body text only; none of the image extras
91 public function render() {
92 $this->getContext()->getOutput()->setArticleBodyOnly( true );
93 parent::view();
96 public function view() {
97 global $wgShowEXIF;
99 $out = $this->getContext()->getOutput();
100 $request = $this->getContext()->getRequest();
101 $diff = $request->getVal( 'diff' );
102 $diffOnly = $request->getBool(
103 'diffonly',
104 $this->getContext()->getUser()->getOption( 'diffonly' )
107 if ( $this->getTitle()->getNamespace() != NS_FILE || ( $diff !== null && $diffOnly ) ) {
108 parent::view();
109 return;
112 $this->loadFile();
114 if ( $this->getTitle()->getNamespace() == NS_FILE && $this->mPage->getFile()->getRedirected() ) {
115 if ( $this->getTitle()->getDBkey() == $this->mPage->getFile()->getName() || $diff !== null ) {
116 // mTitle is the same as the redirect target so ask Article
117 // to perform the redirect for us.
118 $request->setVal( 'diffonly', 'true' );
119 parent::view();
120 return;
121 } else {
122 // mTitle is not the same as the redirect target so it is
123 // probably the redirect page itself. Fake the redirect symbol
124 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
125 $out->addHTML( $this->viewRedirect(
126 Title::makeTitle( NS_FILE, $this->mPage->getFile()->getName() ),
127 /* $appendSubtitle */ true,
128 /* $forceKnown */ true )
130 $this->mPage->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
131 return;
135 if ( $wgShowEXIF && $this->displayImg->exists() ) {
136 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
137 $formattedMetadata = $this->displayImg->formatMetadata( $this->getContext() );
138 $showmeta = $formattedMetadata !== false;
139 } else {
140 $showmeta = false;
143 if ( !$diff && $this->displayImg->exists() ) {
144 $out->addHTML( $this->showTOC( $showmeta ) );
147 if ( !$diff ) {
148 $this->openShowImage();
151 # No need to display noarticletext, we use our own message, output in openShowImage()
152 if ( $this->mPage->getId() ) {
153 # NS_FILE is in the user language, but this section (the actual wikitext)
154 # should be in page content language
155 $pageLang = $this->getTitle()->getPageViewLanguage();
156 $out->addHTML( Xml::openElement( 'div', [ 'id' => 'mw-imagepage-content',
157 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
158 'class' => 'mw-content-' . $pageLang->getDir() ] ) );
160 parent::view();
162 $out->addHTML( Xml::closeElement( 'div' ) );
163 } else {
164 # Just need to set the right headers
165 $out->setArticleFlag( true );
166 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
167 $this->mPage->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
170 # Show shared description, if needed
171 if ( $this->mExtraDescription ) {
172 $fol = $this->getContext()->msg( 'shareddescriptionfollows' );
173 if ( !$fol->isDisabled() ) {
174 $out->addWikiText( $fol->plain() );
176 $out->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
179 $this->closeShowImage();
180 $this->imageHistory();
181 // TODO: Cleanup the following
183 $out->addHTML( Xml::element( 'h2',
184 [ 'id' => 'filelinks' ],
185 $this->getContext()->msg( 'imagelinks' )->text() ) . "\n" );
186 $this->imageDupes();
187 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
188 # Yet we return metadata about the target. Definitely an issue in the FileRepo
189 $this->imageLinks();
191 # Allow extensions to add something after the image links
192 $html = '';
193 Hooks::run( 'ImagePageAfterImageLinks', [ $this, &$html ] );
194 if ( $html ) {
195 $out->addHTML( $html );
198 if ( $showmeta ) {
199 $out->addHTML( Xml::element(
200 'h2',
201 [ 'id' => 'metadata' ],
202 $this->getContext()->msg( 'metadata' )->text() ) . "\n" );
203 $out->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
204 $out->addModules( [ 'mediawiki.action.view.metadata' ] );
207 // Add remote Filepage.css
208 if ( !$this->repo->isLocal() ) {
209 $css = $this->repo->getDescriptionStylesheetUrl();
210 if ( $css ) {
211 $out->addStyle( $css );
215 $out->addModuleStyles( [
216 'filepage', // always show the local local Filepage.css, bug 29277
217 'mediawiki.action.view.filepage', // Add MediaWiki styles for a file page
218 ] );
222 * @return File
224 public function getDisplayedFile() {
225 $this->loadFile();
226 return $this->displayImg;
230 * Create the TOC
232 * @param bool $metadata Whether or not to show the metadata link
233 * @return string
235 protected function showTOC( $metadata ) {
236 $r = [
237 '<li><a href="#file">' . $this->getContext()->msg( 'file-anchor-link' )->escaped() . '</a></li>',
238 '<li><a href="#filehistory">' . $this->getContext()->msg( 'filehist' )->escaped() . '</a></li>',
239 '<li><a href="#filelinks">' . $this->getContext()->msg( 'imagelinks' )->escaped() . '</a></li>',
242 Hooks::run( 'ImagePageShowTOC', [ $this, &$r ] );
244 if ( $metadata ) {
245 $r[] = '<li><a href="#metadata">' .
246 $this->getContext()->msg( 'metadata' )->escaped() .
247 '</a></li>';
250 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
254 * Make a table with metadata to be shown in the output page.
256 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
258 * @param array $metadata The array containing the Exif data
259 * @return string The metadata table. This is treated as Wikitext (!)
261 protected function makeMetadataTable( $metadata ) {
262 $r = "<div class=\"mw-imagepage-section-metadata\">";
263 $r .= $this->getContext()->msg( 'metadata-help' )->plain();
264 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
265 foreach ( $metadata as $type => $stuff ) {
266 foreach ( $stuff as $v ) {
267 # @todo FIXME: Why is this using escapeId for a class?!
268 $class = Sanitizer::escapeId( $v['id'] );
269 if ( $type == 'collapsed' ) {
270 // Handled by mediawiki.action.view.metadata module.
271 $class .= ' collapsable';
273 $r .= "<tr class=\"$class\">\n";
274 $r .= "<th>{$v['name']}</th>\n";
275 $r .= "<td>{$v['value']}</td>\n</tr>";
278 $r .= "</table>\n</div>\n";
279 return $r;
283 * Overloading Article's getContentObject method.
285 * Omit noarticletext if sharedupload; text will be fetched from the
286 * shared upload server if possible.
287 * @return string
289 public function getContentObject() {
290 $this->loadFile();
291 if ( $this->mPage->getFile() && !$this->mPage->getFile()->isLocal() && 0 == $this->getId() ) {
292 return null;
294 return parent::getContentObject();
297 protected function openShowImage() {
298 global $wgEnableUploads, $wgSend404Code, $wgSVGMaxSize;
300 $this->loadFile();
301 $out = $this->getContext()->getOutput();
302 $user = $this->getContext()->getUser();
303 $lang = $this->getContext()->getLanguage();
304 $dirmark = $lang->getDirMarkEntity();
305 $request = $this->getContext()->getRequest();
307 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
308 $maxWidth = $max[0];
309 $maxHeight = $max[1];
311 if ( $this->displayImg->exists() ) {
312 # image
313 $page = $request->getIntOrNull( 'page' );
314 if ( is_null( $page ) ) {
315 $params = [];
316 $page = 1;
317 } else {
318 $params = [ 'page' => $page ];
321 $renderLang = $request->getVal( 'lang' );
322 if ( !is_null( $renderLang ) ) {
323 $handler = $this->displayImg->getHandler();
324 if ( $handler && $handler->validateParam( 'lang', $renderLang ) ) {
325 $params['lang'] = $renderLang;
326 } else {
327 $renderLang = null;
331 $width_orig = $this->displayImg->getWidth( $page );
332 $width = $width_orig;
333 $height_orig = $this->displayImg->getHeight( $page );
334 $height = $height_orig;
336 $filename = wfEscapeWikiText( $this->displayImg->getName() );
337 $linktext = $filename;
339 // Avoid PHP 7.1 warning from passing $this by reference
340 $imagePage = $this;
342 Hooks::run( 'ImageOpenShowImageInlineBefore', [ &$imagePage, &$out ] );
344 if ( $this->displayImg->allowInlineDisplay() ) {
345 # image
346 # "Download high res version" link below the image
347 # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
348 # Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
349 # We'll show a thumbnail of this image
350 if ( $width > $maxWidth || $height > $maxHeight || $this->displayImg->isVectorized() ) {
351 list( $width, $height ) = $this->getDisplayWidthHeight(
352 $maxWidth, $maxHeight, $width, $height
354 $linktext = $this->getContext()->msg( 'show-big-image' )->escaped();
356 $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
357 # Generate thumbnails or thumbnail links as needed...
358 $otherSizes = [];
359 foreach ( $thumbSizes as $size ) {
360 // We include a thumbnail size in the list, if it is
361 // less than or equal to the original size of the image
362 // asset ($width_orig/$height_orig). We also exclude
363 // the current thumbnail's size ($width/$height)
364 // since that is added to the message separately, so
365 // it can be denoted as the current size being shown.
366 // Vectorized images are limited by $wgSVGMaxSize big,
367 // so all thumbs less than or equal that are shown.
368 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
369 || ( $this->displayImg->isVectorized()
370 && max( $size[0], $size[1] ) <= $wgSVGMaxSize )
372 && $size[0] != $width && $size[1] != $height
374 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
375 if ( $sizeLink ) {
376 $otherSizes[] = $sizeLink;
380 $otherSizes = array_unique( $otherSizes );
382 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
383 $msgsmall = $this->getThumbPrevText( $params, $sizeLinkBigImagePreview );
384 if ( count( $otherSizes ) ) {
385 $msgsmall .= ' ' .
386 Html::rawElement(
387 'span',
388 [ 'class' => 'mw-filepage-other-resolutions' ],
389 $this->getContext()->msg( 'show-big-image-other' )
390 ->rawParams( $lang->pipeList( $otherSizes ) )
391 ->params( count( $otherSizes ) )
392 ->parse()
395 } elseif ( $width == 0 && $height == 0 ) {
396 # Some sort of audio file that doesn't have dimensions
397 # Don't output a no hi res message for such a file
398 $msgsmall = '';
399 } else {
400 # Image is small enough to show full size on image page
401 $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
404 $params['width'] = $width;
405 $params['height'] = $height;
406 $thumbnail = $this->displayImg->transform( $params );
407 Linker::processResponsiveImages( $this->displayImg, $thumbnail, $params );
409 $anchorclose = Html::rawElement(
410 'div',
411 [ 'class' => 'mw-filepage-resolutioninfo' ],
412 $msgsmall
415 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
416 if ( $isMulti ) {
417 $out->addModules( 'mediawiki.page.image.pagination' );
418 $out->addHTML( '<table class="multipageimage"><tr><td>' );
421 if ( $thumbnail ) {
422 $options = [
423 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
424 'file-link' => true,
426 $out->addHTML( '<div class="fullImageLink" id="file">' .
427 $thumbnail->toHtml( $options ) .
428 $anchorclose . "</div>\n" );
431 if ( $isMulti ) {
432 $count = $this->displayImg->pageCount();
434 if ( $page > 1 ) {
435 $label = $out->parse( $this->getContext()->msg( 'imgmultipageprev' )->text(), false );
436 // on the client side, this link is generated in ajaxifyPageNavigation()
437 // in the mediawiki.page.image.pagination module
438 $link = Linker::linkKnown(
439 $this->getTitle(),
440 $label,
442 [ 'page' => $page - 1 ]
444 $thumb1 = Linker::makeThumbLinkObj(
445 $this->getTitle(),
446 $this->displayImg,
447 $link,
448 $label,
449 'none',
450 [ 'page' => $page - 1 ]
452 } else {
453 $thumb1 = '';
456 if ( $page < $count ) {
457 $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
458 $link = Linker::linkKnown(
459 $this->getTitle(),
460 $label,
462 [ 'page' => $page + 1 ]
464 $thumb2 = Linker::makeThumbLinkObj(
465 $this->getTitle(),
466 $this->displayImg,
467 $link,
468 $label,
469 'none',
470 [ 'page' => $page + 1 ]
472 } else {
473 $thumb2 = '';
476 global $wgScript;
478 $formParams = [
479 'name' => 'pageselector',
480 'action' => $wgScript,
482 $options = [];
483 for ( $i = 1; $i <= $count; $i++ ) {
484 $options[] = Xml::option( $lang->formatNum( $i ), $i, $i == $page );
486 $select = Xml::tags( 'select',
487 [ 'id' => 'pageselector', 'name' => 'page' ],
488 implode( "\n", $options ) );
490 $out->addHTML(
491 '</td><td><div class="multipageimagenavbox">' .
492 Xml::openElement( 'form', $formParams ) .
493 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
494 $this->getContext()->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
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>"
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();
504 $out->addHTML( '<div class="fullImageLink" id="file">' .
505 $icon->toHtml( [ 'file-link' => true ] ) .
506 "</div>\n" );
509 $longDesc = $this->getContext()->msg( 'parentheses', $this->displayImg->getLongDesc() )->text();
511 $handler = $this->displayImg->getHandler();
513 // If this is a filetype with potential issues, warn the user.
514 if ( $handler ) {
515 $warningConfig = $handler->getWarningConfig( $this->displayImg );
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' );
527 $medialink = "[[Media:$filename|$linktext]]";
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 bug 25277.
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>
544 // @codingStandardsIgnoreEnd
545 } else {
546 $out->addWikiText( <<<EOT
547 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
548 </div>
553 $renderLangOptions = $this->displayImg->getAvailableLanguages();
554 if ( count( $renderLangOptions ) >= 1 ) {
555 $currentLanguage = $renderLang;
556 $defaultLang = $this->displayImg->getDefaultRenderLanguage();
557 if ( is_null( $currentLanguage ) ) {
558 $currentLanguage = $defaultLang;
560 $out->addHTML( $this->doRenderLangOpt( $renderLangOptions, $currentLanguage, $defaultLang ) );
563 // Add cannot animate thumbnail warning
564 if ( !$this->displayImg->canAnimateThumbIfAppropriate() ) {
565 // Include the extension so wiki admins can
566 // customize it on a per file-type basis
567 // (aka say things like use format X instead).
568 // additionally have a specific message for
569 // file-no-thumb-animation-gif
570 $ext = $this->displayImg->getExtension();
571 $noAnimMesg = wfMessageFallback(
572 'file-no-thumb-animation-' . $ext,
573 'file-no-thumb-animation'
574 )->plain();
576 $out->addWikiText( <<<EOT
577 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
582 if ( !$this->displayImg->isLocal() ) {
583 $this->printSharedImageText();
585 } else {
586 # Image does not exist
587 if ( !$this->getId() ) {
588 # No article exists either
589 # Show deletion log to be consistent with normal articles
590 LogEventsList::showLogExtract(
591 $out,
592 [ 'delete', 'move' ],
593 $this->getTitle()->getPrefixedText(),
595 [ 'lim' => 10,
596 'conds' => [ "log_action != 'revision'" ],
597 'showIfEmpty' => false,
598 'msgKey' => [ 'moveddeleted-notice' ]
603 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
604 // Only show an upload link if the user can upload
605 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
606 $nofile = [
607 'filepage-nofile-link',
608 $uploadTitle->getFullURL( [ 'wpDestFile' => $this->mPage->getFile()->getName() ] )
610 } else {
611 $nofile = 'filepage-nofile';
613 // Note, if there is an image description page, but
614 // no image, then this setRobotPolicy is overridden
615 // by Article::View().
616 $out->setRobotPolicy( 'noindex,nofollow' );
617 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
618 if ( !$this->getId() && $wgSend404Code ) {
619 // If there is no image, no shared image, and no description page,
620 // output a 404, to be consistent with Article::showMissingArticle.
621 $request->response()->statusHeader( 404 );
624 $out->setFileVersion( $this->displayImg );
628 * Make the text under the image to say what size preview
630 * @param $params array parameters for thumbnail
631 * @param $sizeLinkBigImagePreview HTML for the current size
632 * @return string HTML output
634 private function getThumbPrevText( $params, $sizeLinkBigImagePreview ) {
635 if ( $sizeLinkBigImagePreview ) {
636 // Show a different message of preview is different format from original.
637 $previewTypeDiffers = false;
638 $origExt = $thumbExt = $this->displayImg->getExtension();
639 if ( $this->displayImg->getHandler() ) {
640 $origMime = $this->displayImg->getMimeType();
641 $typeParams = $params;
642 $this->displayImg->getHandler()->normaliseParams( $this->displayImg, $typeParams );
643 list( $thumbExt, $thumbMime ) = $this->displayImg->getHandler()->getThumbType(
644 $origExt, $origMime, $typeParams );
645 if ( $thumbMime !== $origMime ) {
646 $previewTypeDiffers = true;
649 if ( $previewTypeDiffers ) {
650 return $this->getContext()->msg( 'show-big-image-preview-differ' )->
651 rawParams( $sizeLinkBigImagePreview )->
652 params( strtoupper( $origExt ) )->
653 params( strtoupper( $thumbExt ) )->
654 parse();
655 } else {
656 return $this->getContext()->msg( 'show-big-image-preview' )->
657 rawParams( $sizeLinkBigImagePreview )->
658 parse();
660 } else {
661 return '';
666 * Creates an thumbnail of specified size and returns an HTML link to it
667 * @param array $params Scaler parameters
668 * @param int $width
669 * @param int $height
670 * @return string
672 private function makeSizeLink( $params, $width, $height ) {
673 $params['width'] = $width;
674 $params['height'] = $height;
675 $thumbnail = $this->displayImg->transform( $params );
676 if ( $thumbnail && !$thumbnail->isError() ) {
677 return Html::rawElement( 'a', [
678 'href' => $thumbnail->getUrl(),
679 'class' => 'mw-thumbnail-link'
680 ], $this->getContext()->msg( 'show-big-image-size' )->numParams(
681 $thumbnail->getWidth(), $thumbnail->getHeight()
682 )->parse() );
683 } else {
684 return '';
689 * Show a notice that the file is from a shared repository
691 protected function printSharedImageText() {
692 $out = $this->getContext()->getOutput();
693 $this->loadFile();
695 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
696 $descText = $this->mPage->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
698 /* Add canonical to head if there is no local page for this shared file */
699 if ( $descUrl && $this->mPage->getId() == 0 ) {
700 $out->setCanonicalUrl( $descUrl );
703 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
704 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
706 if ( $descUrl &&
707 $descText &&
708 $this->getContext()->msg( 'sharedupload-desc-here' )->plain() !== '-'
710 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-here', $repo, $descUrl ] );
711 } elseif ( $descUrl &&
712 $this->getContext()->msg( 'sharedupload-desc-there' )->plain() !== '-'
714 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-there', $repo, $descUrl ] );
715 } else {
716 $out->wrapWikiMsg( $wrap, [ 'sharedupload', $repo ], ''/*BACKCOMPAT*/ );
719 if ( $descText ) {
720 $this->mExtraDescription = $descText;
724 public function getUploadUrl() {
725 $this->loadFile();
726 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
727 return $uploadTitle->getFullURL( [
728 'wpDestFile' => $this->mPage->getFile()->getName(),
729 'wpForReUpload' => 1
730 ] );
734 * Print out the various links at the bottom of the image page, e.g. reupload,
735 * external editing (and instructions link) etc.
737 protected function uploadLinksBox() {
738 global $wgEnableUploads;
740 if ( !$wgEnableUploads ) {
741 return;
744 $this->loadFile();
745 if ( !$this->mPage->getFile()->isLocal() ) {
746 return;
749 $out = $this->getContext()->getOutput();
750 $out->addHTML( "<ul>\n" );
752 # "Upload a new version of this file" link
753 $canUpload = $this->getTitle()->quickUserCan( 'upload', $this->getContext()->getUser() );
754 if ( $canUpload && UploadBase::userCanReUpload(
755 $this->getContext()->getUser(),
756 $this->mPage->getFile() )
758 $ulink = Linker::makeExternalLink(
759 $this->getUploadUrl(),
760 $this->getContext()->msg( 'uploadnewversion-linktext' )->text()
762 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\">"
763 . "<div class=\"plainlinks\">{$ulink}</div></li>\n" );
764 } else {
765 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">"
766 . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
769 $out->addHTML( "</ul>\n" );
773 * For overloading
775 protected function closeShowImage() {
779 * If the page we've just displayed is in the "Image" namespace,
780 * we follow it with an upload history of the image and its usage.
782 protected function imageHistory() {
783 $this->loadFile();
784 $out = $this->getContext()->getOutput();
785 $pager = new ImageHistoryPseudoPager( $this );
786 $out->addHTML( $pager->getBody() );
787 $out->preventClickjacking( $pager->getPreventClickjacking() );
789 $this->mPage->getFile()->resetHistory(); // free db resources
791 # Exist check because we don't want to show this on pages where an image
792 # doesn't exist along with the noimage message, that would suck. -ævar
793 if ( $this->mPage->getFile()->exists() ) {
794 $this->uploadLinksBox();
799 * @param string $target
800 * @param int $limit
801 * @return ResultWrapper
803 protected function queryImageLinks( $target, $limit ) {
804 $dbr = wfGetDB( DB_REPLICA );
806 return $dbr->select(
807 [ 'imagelinks', 'page' ],
808 [ 'page_namespace', 'page_title', 'il_to' ],
809 [ 'il_to' => $target, 'il_from = page_id' ],
810 __METHOD__,
811 [ 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', ]
815 protected function imageLinks() {
816 $limit = 100;
818 $out = $this->getContext()->getOutput();
820 $rows = [];
821 $redirects = [];
822 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE ) as $redir ) {
823 $redirects[$redir->getDBkey()] = [];
824 $rows[] = (object)[
825 'page_namespace' => NS_FILE,
826 'page_title' => $redir->getDBkey(),
830 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit + 1 );
831 foreach ( $res as $row ) {
832 $rows[] = $row;
834 $count = count( $rows );
836 $hasMore = $count > $limit;
837 if ( !$hasMore && count( $redirects ) ) {
838 $res = $this->queryImageLinks( array_keys( $redirects ),
839 $limit - count( $rows ) + 1 );
840 foreach ( $res as $row ) {
841 $redirects[$row->il_to][] = $row;
842 $count++;
844 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
847 if ( $count == 0 ) {
848 $out->wrapWikiMsg(
849 Html::rawElement( 'div',
850 [ 'id' => 'mw-imagepage-nolinkstoimage' ], "\n$1\n" ),
851 'nolinkstoimage'
853 return;
856 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
857 if ( !$hasMore ) {
858 $out->addWikiMsg( 'linkstoimage', $count );
859 } else {
860 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
861 $out->addWikiMsg( 'linkstoimage-more',
862 $this->getContext()->getLanguage()->formatNum( $limit ),
863 $this->getTitle()->getPrefixedDBkey()
867 $out->addHTML(
868 Html::openElement( 'ul',
869 [ 'class' => 'mw-imagepage-linkstoimage' ] ) . "\n"
871 $count = 0;
873 // Sort the list by namespace:title
874 usort( $rows, [ $this, 'compare' ] );
876 // Create links for every element
877 $currentCount = 0;
878 foreach ( $rows as $element ) {
879 $currentCount++;
880 if ( $currentCount > $limit ) {
881 break;
884 $query = [];
885 # Add a redirect=no to make redirect pages reachable
886 if ( isset( $redirects[$element->page_title] ) ) {
887 $query['redirect'] = 'no';
889 $link = Linker::linkKnown(
890 Title::makeTitle( $element->page_namespace, $element->page_title ),
891 null, [], $query
893 if ( !isset( $redirects[$element->page_title] ) ) {
894 # No redirects
895 $liContents = $link;
896 } elseif ( count( $redirects[$element->page_title] ) === 0 ) {
897 # Redirect without usages
898 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )
899 ->rawParams( $link, '' )
900 ->parse();
901 } else {
902 # Redirect with usages
903 $li = '';
904 foreach ( $redirects[$element->page_title] as $row ) {
905 $currentCount++;
906 if ( $currentCount > $limit ) {
907 break;
910 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
911 $li .= Html::rawElement(
912 'li',
913 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
914 $link2
915 ) . "\n";
918 $ul = Html::rawElement(
919 'ul',
920 [ 'class' => 'mw-imagepage-redirectstofile' ],
922 ) . "\n";
923 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
924 $link, $ul )->parse();
926 $out->addHTML( Html::rawElement(
927 'li',
928 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
929 $liContents
930 ) . "\n"
934 $out->addHTML( Html::closeElement( 'ul' ) . "\n" );
935 $res->free();
937 // Add a links to [[Special:Whatlinkshere]]
938 if ( $count > $limit ) {
939 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
941 $out->addHTML( Html::closeElement( 'div' ) . "\n" );
944 protected function imageDupes() {
945 $this->loadFile();
946 $out = $this->getContext()->getOutput();
948 $dupes = $this->mPage->getDuplicates();
949 if ( count( $dupes ) == 0 ) {
950 return;
953 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
954 $out->addWikiMsg( 'duplicatesoffile',
955 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
957 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
960 * @var $file File
962 foreach ( $dupes as $file ) {
963 $fromSrc = '';
964 if ( $file->isLocal() ) {
965 $link = Linker::linkKnown( $file->getTitle() );
966 } else {
967 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
968 $file->getTitle()->getPrefixedText() );
969 $fromSrc = $this->getContext()->msg(
970 'shared-repo-from',
971 $file->getRepo()->getDisplayName()
972 )->text();
974 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
976 $out->addHTML( "</ul></div>\n" );
980 * Delete the file, or an earlier version of it
982 public function delete() {
983 $file = $this->mPage->getFile();
984 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
985 // Standard article deletion
986 parent::delete();
987 return;
990 $deleter = new FileDeleteForm( $file );
991 $deleter->execute();
995 * Display an error with a wikitext description
997 * @param string $description
999 function showError( $description ) {
1000 $out = $this->getContext()->getOutput();
1001 $out->setPageTitle( $this->getContext()->msg( 'internalerror' ) );
1002 $out->setRobotPolicy( 'noindex,nofollow' );
1003 $out->setArticleRelated( false );
1004 $out->enableClientCache( false );
1005 $out->addWikiText( $description );
1009 * Callback for usort() to do link sorts by (namespace, title)
1010 * Function copied from Title::compare()
1012 * @param object $a Object page to compare with
1013 * @param object $b Object page to compare with
1014 * @return int Result of string comparison, or namespace comparison
1016 protected function compare( $a, $b ) {
1017 if ( $a->page_namespace == $b->page_namespace ) {
1018 return strcmp( $a->page_title, $b->page_title );
1019 } else {
1020 return $a->page_namespace - $b->page_namespace;
1025 * Returns the corresponding $wgImageLimits entry for the selected user option
1027 * @param User $user
1028 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
1029 * @return array
1030 * @since 1.21
1032 public function getImageLimitsFromOption( $user, $optionName ) {
1033 global $wgImageLimits;
1035 $option = $user->getIntOption( $optionName );
1036 if ( !isset( $wgImageLimits[$option] ) ) {
1037 $option = User::getDefaultOption( $optionName );
1040 // The user offset might still be incorrect, specially if
1041 // $wgImageLimits got changed (see bug #8858).
1042 if ( !isset( $wgImageLimits[$option] ) ) {
1043 // Default to the first offset in $wgImageLimits
1044 $option = 0;
1047 return isset( $wgImageLimits[$option] )
1048 ? $wgImageLimits[$option]
1049 : [ 800, 600 ]; // if nothing is set, fallback to a hardcoded default
1053 * Output a drop-down box for language options for the file
1055 * @param array $langChoices Array of string language codes
1056 * @param string $curLang Language code file is being viewed in.
1057 * @param string $defaultLang Language code that image is rendered in by default
1058 * @return string HTML to insert underneath image.
1060 protected function doRenderLangOpt( array $langChoices, $curLang, $defaultLang ) {
1061 global $wgScript;
1062 sort( $langChoices );
1063 $curLang = wfBCP47( $curLang );
1064 $defaultLang = wfBCP47( $defaultLang );
1065 $opts = '';
1066 $haveCurrentLang = false;
1067 $haveDefaultLang = false;
1069 // We make a list of all the language choices in the file.
1070 // Additionally if the default language to render this file
1071 // is not included as being in this file (for example, in svgs
1072 // usually the fallback content is the english content) also
1073 // include a choice for that. Last of all, if we're viewing
1074 // the file in a language not on the list, add it as a choice.
1075 foreach ( $langChoices as $lang ) {
1076 $code = wfBCP47( $lang );
1077 $name = Language::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1078 if ( $name !== '' ) {
1079 $display = $this->getContext()->msg( 'img-lang-opt', $code, $name )->text();
1080 } else {
1081 $display = $code;
1083 $opts .= "\n" . Xml::option( $display, $code, $curLang === $code );
1084 if ( $curLang === $code ) {
1085 $haveCurrentLang = true;
1087 if ( $defaultLang === $code ) {
1088 $haveDefaultLang = true;
1091 if ( !$haveDefaultLang ) {
1092 // Its hard to know if the content is really in the default language, or
1093 // if its just unmarked content that could be in any language.
1094 $opts = Xml::option(
1095 $this->getContext()->msg( 'img-lang-default' )->text(),
1096 $defaultLang,
1097 $defaultLang === $curLang
1098 ) . $opts;
1100 if ( !$haveCurrentLang && $defaultLang !== $curLang ) {
1101 $name = Language::fetchLanguageName( $curLang, $this->getContext()->getLanguage()->getCode() );
1102 if ( $name !== '' ) {
1103 $display = $this->getContext()->msg( 'img-lang-opt', $curLang, $name )->text();
1104 } else {
1105 $display = $curLang;
1107 $opts = Xml::option( $display, $curLang, true ) . $opts;
1110 $select = Html::rawElement(
1111 'select',
1112 [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1113 $opts
1115 $submit = Xml::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1117 $formContents = $this->getContext()->msg( 'img-lang-info' )
1118 ->rawParams( $select, $submit )
1119 ->parse();
1120 $formContents .= Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1122 $langSelectLine = Html::rawElement( 'div', [ 'id' => 'mw-imglangselector-line' ],
1123 Html::rawElement( 'form', [ 'action' => $wgScript ], $formContents )
1125 return $langSelectLine;
1129 * Get the width and height to display image at.
1131 * @note This method assumes that it is only called if one
1132 * of the dimensions are bigger than the max, or if the
1133 * image is vectorized.
1135 * @param int $maxWidth Max width to display at
1136 * @param int $maxHeight Max height to display at
1137 * @param int $width Actual width of the image
1138 * @param int $height Actual height of the image
1139 * @throws MWException
1140 * @return array Array (width, height)
1142 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1143 if ( !$maxWidth || !$maxHeight ) {
1144 // should never happen
1145 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1148 if ( !$width || !$height ) {
1149 return [ 0, 0 ];
1152 # Calculate the thumbnail size.
1153 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1154 // Vectorized image, do nothing.
1155 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1156 # The limiting factor is the width, not the height.
1157 $height = round( $height * $maxWidth / $width );
1158 $width = $maxWidth;
1159 # Note that $height <= $maxHeight now.
1160 } else {
1161 $newwidth = floor( $width * $maxHeight / $height );
1162 $height = round( $height * $newwidth / $width );
1163 $width = $newwidth;
1164 # Note that $height <= $maxHeight now, but might not be identical
1165 # because of rounding.
1167 return [ $width, $height ];
1171 * Get alternative thumbnail sizes.
1173 * @note This will only list several alternatives if thumbnails are rendered on 404
1174 * @param int $origWidth Actual width of image
1175 * @param int $origHeight Actual height of image
1176 * @return array An array of [width, height] pairs.
1178 protected function getThumbSizes( $origWidth, $origHeight ) {
1179 global $wgImageLimits;
1180 if ( $this->displayImg->getRepo()->canTransformVia404() ) {
1181 $thumbSizes = $wgImageLimits;
1182 // Also include the full sized resolution in the list, so
1183 // that users know they can get it. This will link to the
1184 // original file asset if mustRender() === false. In the case
1185 // that we mustRender, some users have indicated that they would
1186 // find it useful to have the full size image in the rendered
1187 // image format.
1188 $thumbSizes[] = [ $origWidth, $origHeight ];
1189 } else {
1190 # Creating thumb links triggers thumbnail generation.
1191 # Just generate the thumb for the current users prefs.
1192 $thumbSizes = [
1193 $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' )
1195 if ( !$this->displayImg->mustRender() ) {
1196 // We can safely include a link to the "full-size" preview,
1197 // without actually rendering.
1198 $thumbSizes[] = [ $origWidth, $origHeight ];
1201 return $thumbSizes;
1205 * @see WikiFilePage::getFile
1206 * @return bool|File
1208 public function getFile() {
1209 return $this->mPage->getFile();
1213 * @see WikiFilePage::isLocal
1214 * @return bool
1216 public function isLocal() {
1217 return $this->mPage->isLocal();
1221 * @see WikiFilePage::getDuplicates
1222 * @return array|null
1224 public function getDuplicates() {
1225 return $this->mPage->getDuplicates();
1229 * @see WikiFilePage::getForeignCategories
1230 * @return TitleArray|Title[]
1232 public function getForeignCategories() {
1233 $this->mPage->getForeignCategories();