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
24 * Class for viewing MediaWiki file description pages
28 class ImagePage
extends Article
{
39 protected $mExtraDescription = false;
48 * @return WikiFilePage
50 protected function newPage( Title
$title ) {
51 // Overload mPage with a file-specific page
52 return new WikiFilePage( $title );
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
) {
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() );
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();
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 );
96 public function view() {
99 $out = $this->getContext()->getOutput();
100 $request = $this->getContext()->getRequest();
101 $diff = $request->getVal( 'diff' );
102 $diffOnly = $request->getBool(
104 $this->getContext()->getUser()->getOption( 'diffonly' )
107 if ( $this->getTitle()->getNamespace() != NS_FILE ||
( $diff !== null && $diffOnly ) ) {
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' );
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() );
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;
143 if ( !$diff && $this->displayImg
->exists() ) {
144 $out->addHTML( $this->showTOC( $showmeta ) );
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() ] ) );
162 $out->addHTML( Xml
::closeElement( 'div' ) );
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" );
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
191 # Allow extensions to add something after the image links
193 Hooks
::run( 'ImagePageAfterImageLinks', [ $this, &$html ] );
195 $out->addHTML( $html );
199 $out->addHTML( Xml
::element(
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();
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
224 public function getDisplayedFile() {
226 return $this->displayImg
;
232 * @param bool $metadata Whether or not to show the metadata link
235 protected function showTOC( $metadata ) {
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 ] );
245 $r[] = '<li><a href="#metadata">' .
246 $this->getContext()->msg( 'metadata' )->escaped() .
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";
283 * Overloading Article's getContentObject method.
285 * Omit noarticletext if sharedupload; text will be fetched from the
286 * shared upload server if possible.
289 public function getContentObject() {
291 if ( $this->mPage
->getFile() && !$this->mPage
->getFile()->isLocal() && 0 == $this->getId() ) {
294 return parent
::getContentObject();
297 protected function openShowImage() {
298 global $wgEnableUploads, $wgSend404Code, $wgSVGMaxSize;
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' );
309 $maxHeight = $max[1];
311 if ( $this->displayImg
->exists() ) {
313 $page = $request->getIntOrNull( 'page' );
314 if ( is_null( $page ) ) {
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;
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 // Use of &$this in hooks triggers warnings in PHP 7.1
342 Hooks
::run( 'ImageOpenShowImageInlineBefore', [ &$imagePage, &$out ] );
344 if ( $this->displayImg
->allowInlineDisplay() ) {
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...
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] );
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 ) ) {
388 [ 'class' => 'mw-filepage-other-resolutions' ],
389 $this->getContext()->msg( 'show-big-image-other' )
390 ->rawParams( $lang->pipeList( $otherSizes ) )
391 ->params( count( $otherSizes ) )
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
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(
411 [ 'class' => 'mw-filepage-resolutioninfo' ],
415 $isMulti = $this->displayImg
->isMultipage() && $this->displayImg
->pageCount() > 1;
417 $out->addModules( 'mediawiki.page.image.pagination' );
418 $out->addHTML( '<table class="multipageimage"><tr><td>' );
423 'alt' => $this->displayImg
->getTitle()->getPrefixedText(),
426 $out->addHTML( '<div class="fullImageLink" id="file">' .
427 $thumbnail->toHtml( $options ) .
428 $anchorclose . "</div>\n" );
432 $count = $this->displayImg
->pageCount();
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(
442 [ 'page' => $page - 1 ]
444 $thumb1 = Linker
::makeThumbLinkObj(
450 [ 'page' => $page - 1 ]
456 if ( $page < $count ) {
457 $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
458 $link = Linker
::linkKnown(
462 [ 'page' => $page +
1 ]
464 $thumb2 = Linker
::makeThumbLinkObj(
470 [ 'page' => $page +
1 ]
479 'name' => 'pageselector',
480 'action' => $wgScript,
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 ) );
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 ] ) .
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.
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.
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
546 $out->addWikiText( <<<EOT
547 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
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'
576 $out->addWikiText( <<<EOT
577 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
582 if ( !$this->displayImg
->isLocal() ) {
583 $this->printSharedImageText();
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(
592 [ 'delete', 'move' ],
593 $this->getTitle()->getPrefixedText(),
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' );
607 'filepage-nofile-link',
608 $uploadTitle->getFullURL( [ 'wpDestFile' => $this->mPage
->getFile()->getName() ] )
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 ) )->
656 return $this->getContext()->msg( 'show-big-image-preview' )->
657 rawParams( $sizeLinkBigImagePreview )->
666 * Creates an thumbnail of specified size and returns an HTML link to it
667 * @param array $params Scaler parameters
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()
689 * Show a notice that the file is from a shared repository
691 protected function printSharedImageText() {
692 $out = $this->getContext()->getOutput();
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();
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 ] );
716 $out->wrapWikiMsg( $wrap, [ 'sharedupload', $repo ], ''/*BACKCOMPAT*/ );
720 $this->mExtraDescription
= $descText;
724 public function getUploadUrl() {
726 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
727 return $uploadTitle->getFullURL( [
728 'wpDestFile' => $this->mPage
->getFile()->getName(),
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 ) {
745 if ( !$this->mPage
->getFile()->isLocal() ) {
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" );
765 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">"
766 . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
769 $out->addHTML( "</ul>\n" );
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() {
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
801 * @return ResultWrapper
803 protected function queryImageLinks( $target, $limit ) {
804 $dbr = wfGetDB( DB_REPLICA
);
807 [ 'imagelinks', 'page' ],
808 [ 'page_namespace', 'page_title', 'il_to' ],
809 [ 'il_to' => $target, 'il_from = page_id' ],
811 [ 'LIMIT' => $limit +
1, 'ORDER BY' => 'il_from', ]
815 protected function imageLinks() {
818 $out = $this->getContext()->getOutput();
822 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE
) as $redir ) {
823 $redirects[$redir->getDBkey()] = [];
825 'page_namespace' => NS_FILE
,
826 'page_title' => $redir->getDBkey(),
830 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit +
1 );
831 foreach ( $res as $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;
844 $hasMore = ( $res->numRows() +
count( $rows ) ) > $limit;
849 Html
::rawElement( 'div',
850 [ 'id' => 'mw-imagepage-nolinkstoimage' ], "\n$1\n" ),
856 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
858 $out->addWikiMsg( 'linkstoimage', $count );
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()
868 Html
::openElement( 'ul',
869 [ 'class' => 'mw-imagepage-linkstoimage' ] ) . "\n"
873 // Sort the list by namespace:title
874 usort( $rows, [ $this, 'compare' ] );
876 // Create links for every element
878 foreach ( $rows as $element ) {
880 if ( $currentCount > $limit ) {
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
),
893 if ( !isset( $redirects[$element->page_title
] ) ) {
896 } elseif ( count( $redirects[$element->page_title
] ) === 0 ) {
897 # Redirect without usages
898 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )
899 ->rawParams( $link, '' )
902 # Redirect with usages
904 foreach ( $redirects[$element->page_title
] as $row ) {
906 if ( $currentCount > $limit ) {
910 $link2 = Linker
::linkKnown( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
911 $li .= Html
::rawElement(
913 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
],
918 $ul = Html
::rawElement(
920 [ 'class' => 'mw-imagepage-redirectstofile' ],
923 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
924 $link, $ul )->parse();
926 $out->addHTML( Html
::rawElement(
928 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
],
934 $out->addHTML( Html
::closeElement( 'ul' ) . "\n" );
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() {
946 $out = $this->getContext()->getOutput();
948 $dupes = $this->mPage
->getDuplicates();
949 if ( count( $dupes ) == 0 ) {
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" );
962 foreach ( $dupes as $file ) {
964 if ( $file->isLocal() ) {
965 $link = Linker
::linkKnown( $file->getTitle() );
967 $link = Linker
::makeExternalLink( $file->getDescriptionUrl(),
968 $file->getTitle()->getPrefixedText() );
969 $fromSrc = $this->getContext()->msg(
971 $file->getRepo()->getDisplayName()
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
990 $deleter = new FileDeleteForm( $file );
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
);
1020 return $a->page_namespace
- $b->page_namespace
;
1025 * Returns the corresponding $wgImageLimits entry for the selected user option
1028 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
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
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 ) {
1062 sort( $langChoices );
1063 $curLang = wfBCP47( $curLang );
1064 $defaultLang = wfBCP47( $defaultLang );
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();
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(),
1097 $defaultLang === $curLang
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();
1105 $display = $curLang;
1107 $opts = Xml
::option( $display, $curLang, true ) . $opts;
1110 $select = Html
::rawElement(
1112 [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1115 $submit = Xml
::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1117 $formContents = $this->getContext()->msg( 'img-lang-info' )
1118 ->rawParams( $select, $submit )
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 ) {
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 );
1159 # Note that $height <= $maxHeight now.
1161 $newwidth = floor( $width * $maxHeight / $height );
1162 $height = round( $height * $newwidth / $width );
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
1188 $thumbSizes[] = [ $origWidth, $origHeight ];
1190 # Creating thumb links triggers thumbnail generation.
1191 # Just generate the thumb for the current users prefs.
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 ];
1205 * @see WikiFilePage::getFile
1208 public function getFile() {
1209 return $this->mPage
->getFile();
1213 * @see WikiFilePage::isLocal
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();