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
23 use Wikimedia\Rdbms\ResultWrapper
;
26 * Class for viewing MediaWiki file description pages
30 class ImagePage
extends Article
{
41 protected $mExtraDescription = false;
50 * @return WikiFilePage
52 protected function newPage( Title
$title ) {
53 // Overload mPage with a file-specific page
54 return new WikiFilePage( $title );
61 public function setFile( $file ) {
62 $this->mPage
->setFile( $file );
63 $this->displayImg
= $file;
64 $this->fileLoaded
= true;
67 protected function loadFile() {
68 if ( $this->fileLoaded
) {
71 $this->fileLoaded
= true;
73 $this->displayImg
= $img = false;
75 Hooks
::run( 'ImagePageFindFile', [ $this, &$img, &$this->displayImg
] );
76 if ( !$img ) { // not set by hook?
77 $img = wfFindFile( $this->getTitle() );
79 $img = wfLocalFile( $this->getTitle() );
82 $this->mPage
->setFile( $img );
83 if ( !$this->displayImg
) { // not set by hook?
84 $this->displayImg
= $img;
86 $this->repo
= $img->getRepo();
89 public function view() {
92 // For action=render, include body text only; none of the image extras
93 if ( $this->viewIsRenderAction
) {
98 $out = $this->getContext()->getOutput();
99 $request = $this->getContext()->getRequest();
100 $diff = $request->getVal( 'diff' );
101 $diffOnly = $request->getBool(
103 $this->getContext()->getUser()->getOption( 'diffonly' )
106 if ( $this->getTitle()->getNamespace() != NS_FILE ||
( $diff !== null && $diffOnly ) ) {
113 if ( $this->getTitle()->getNamespace() == NS_FILE
&& $this->mPage
->getFile()->getRedirected() ) {
114 if ( $this->getTitle()->getDBkey() == $this->mPage
->getFile()->getName() ||
$diff !== null ) {
115 $request->setVal( 'diffonly', 'true' );
122 if ( $wgShowEXIF && $this->displayImg
->exists() ) {
123 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
124 $formattedMetadata = $this->displayImg
->formatMetadata( $this->getContext() );
125 $showmeta = $formattedMetadata !== false;
130 if ( !$diff && $this->displayImg
->exists() ) {
131 $out->addHTML( $this->showTOC( $showmeta ) );
135 $this->openShowImage();
138 # No need to display noarticletext, we use our own message, output in openShowImage()
139 if ( $this->mPage
->getId() ) {
140 # NS_FILE is in the user language, but this section (the actual wikitext)
141 # should be in page content language
142 $pageLang = $this->getTitle()->getPageViewLanguage();
143 $out->addHTML( Xml
::openElement( 'div', [ 'id' => 'mw-imagepage-content',
144 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
145 'class' => 'mw-content-' . $pageLang->getDir() ] ) );
149 $out->addHTML( Xml
::closeElement( 'div' ) );
151 # Just need to set the right headers
152 $out->setArticleFlag( true );
153 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
154 $this->mPage
->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
157 # Show shared description, if needed
158 if ( $this->mExtraDescription
) {
159 $fol = $this->getContext()->msg( 'shareddescriptionfollows' );
160 if ( !$fol->isDisabled() ) {
161 $out->addWikiText( $fol->plain() );
163 $out->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription
. "</div>\n" );
166 $this->closeShowImage();
167 $this->imageHistory();
168 // TODO: Cleanup the following
170 $out->addHTML( Xml
::element( 'h2',
171 [ 'id' => 'filelinks' ],
172 $this->getContext()->msg( 'imagelinks' )->text() ) . "\n" );
174 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
175 # Yet we return metadata about the target. Definitely an issue in the FileRepo
178 # Allow extensions to add something after the image links
180 Hooks
::run( 'ImagePageAfterImageLinks', [ $this, &$html ] );
182 $out->addHTML( $html );
186 $out->addHTML( Xml
::element(
188 [ 'id' => 'metadata' ],
189 $this->getContext()->msg( 'metadata' )->text() ) . "\n" );
190 $out->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
191 $out->addModules( [ 'mediawiki.action.view.metadata' ] );
194 // Add remote Filepage.css
195 if ( !$this->repo
->isLocal() ) {
196 $css = $this->repo
->getDescriptionStylesheetUrl();
198 $out->addStyle( $css );
202 $out->addModuleStyles( [
203 'filepage', // always show the local local Filepage.css, T31277
204 'mediawiki.action.view.filepage', // Add MediaWiki styles for a file page
211 public function getDisplayedFile() {
213 return $this->displayImg
;
219 * @param bool $metadata Whether or not to show the metadata link
222 protected function showTOC( $metadata ) {
224 '<li><a href="#file">' . $this->getContext()->msg( 'file-anchor-link' )->escaped() . '</a></li>',
225 '<li><a href="#filehistory">' . $this->getContext()->msg( 'filehist' )->escaped() . '</a></li>',
226 '<li><a href="#filelinks">' . $this->getContext()->msg( 'imagelinks' )->escaped() . '</a></li>',
229 Hooks
::run( 'ImagePageShowTOC', [ $this, &$r ] );
232 $r[] = '<li><a href="#metadata">' .
233 $this->getContext()->msg( 'metadata' )->escaped() .
237 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
241 * Make a table with metadata to be shown in the output page.
243 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
245 * @param array $metadata The array containing the Exif data
246 * @return string The metadata table. This is treated as Wikitext (!)
248 protected function makeMetadataTable( $metadata ) {
249 $r = "<div class=\"mw-imagepage-section-metadata\">";
250 $r .= $this->getContext()->msg( 'metadata-help' )->plain();
251 // Intial state is collapsed
252 // see filepage.css and mediawiki.action.view.metadata module.
253 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata collapsed\">\n";
254 foreach ( $metadata as $type => $stuff ) {
255 foreach ( $stuff as $v ) {
256 $class = str_replace( ' ', '_', $v['id'] );
257 if ( $type == 'collapsed' ) {
258 $class .= ' mw-metadata-collapsible';
260 $r .= Html
::rawElement( 'tr',
261 [ 'class' => $class ],
262 Html
::rawElement( 'th', [], $v['name'] )
263 . Html
::rawElement( 'td', [], $v['value'] )
267 $r .= "</table>\n</div>\n";
272 * Overloading Article's getEmptyPageParserOutput method.
274 * Omit noarticletext if sharedupload; text will be fetched from the
275 * shared upload server if possible.
277 * @param ParserOptions $options
278 * @return ParserOutput
280 public function getEmptyPageParserOutput( ParserOptions
$options ) {
282 if ( $this->mPage
->getFile() && !$this->mPage
->getFile()->isLocal() && 0 == $this->getId() ) {
283 return new ParserOutput();
285 return parent
::getEmptyPageParserOutput( $options );
288 private function getLanguageForRendering( WebRequest
$request, File
$file ) {
289 $handler = $this->displayImg
->getHandler();
294 $requestLanguage = $request->getVal( 'lang' );
295 if ( !is_null( $requestLanguage ) ) {
296 if ( $handler->validateParam( 'lang', $requestLanguage ) ) {
297 return $requestLanguage;
301 return $handler->getDefaultRenderLanguage( $this->displayImg
);
304 protected function openShowImage() {
305 global $wgEnableUploads, $wgSend404Code, $wgSVGMaxSize;
308 $out = $this->getContext()->getOutput();
309 $user = $this->getContext()->getUser();
310 $lang = $this->getContext()->getLanguage();
311 $dirmark = $lang->getDirMarkEntity();
312 $request = $this->getContext()->getRequest();
314 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
316 $maxHeight = $max[1];
318 if ( $this->displayImg
->exists() ) {
320 $page = $request->getIntOrNull( 'page' );
321 if ( is_null( $page ) ) {
325 $params = [ 'page' => $page ];
328 $renderLang = $this->getLanguageForRendering( $request, $this->displayImg
);
329 if ( !is_null( $renderLang ) ) {
330 $params['lang'] = $renderLang;
333 $width_orig = $this->displayImg
->getWidth( $page );
334 $width = $width_orig;
335 $height_orig = $this->displayImg
->getHeight( $page );
336 $height = $height_orig;
338 $filename = wfEscapeWikiText( $this->displayImg
->getName() );
339 $linktext = $filename;
341 // Avoid PHP 7.1 warning from passing $this by reference
344 Hooks
::run( 'ImageOpenShowImageInlineBefore', [ &$imagePage, &$out ] );
346 if ( $this->displayImg
->allowInlineDisplay() ) {
348 # "Download high res version" link below the image
349 # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
350 # Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
351 # We'll show a thumbnail of this image
352 if ( $width > $maxWidth ||
$height > $maxHeight ||
$this->displayImg
->isVectorized() ) {
353 list( $width, $height ) = $this->getDisplayWidthHeight(
354 $maxWidth, $maxHeight, $width, $height
356 $linktext = $this->getContext()->msg( 'show-big-image' )->escaped();
358 $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
359 # Generate thumbnails or thumbnail links as needed...
361 foreach ( $thumbSizes as $size ) {
362 // We include a thumbnail size in the list, if it is
363 // less than or equal to the original size of the image
364 // asset ($width_orig/$height_orig). We also exclude
365 // the current thumbnail's size ($width/$height)
366 // since that is added to the message separately, so
367 // it can be denoted as the current size being shown.
368 // Vectorized images are limited by $wgSVGMaxSize big,
369 // so all thumbs less than or equal that are shown.
370 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
371 ||
( $this->displayImg
->isVectorized()
372 && max( $size[0], $size[1] ) <= $wgSVGMaxSize )
374 && $size[0] != $width && $size[1] != $height
376 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
378 $otherSizes[] = $sizeLink;
382 $otherSizes = array_unique( $otherSizes );
384 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
385 $msgsmall = $this->getThumbPrevText( $params, $sizeLinkBigImagePreview );
386 if ( count( $otherSizes ) ) {
390 [ 'class' => 'mw-filepage-other-resolutions' ],
391 $this->getContext()->msg( 'show-big-image-other' )
392 ->rawParams( $lang->pipeList( $otherSizes ) )
393 ->params( count( $otherSizes ) )
397 } elseif ( $width == 0 && $height == 0 ) {
398 # Some sort of audio file that doesn't have dimensions
399 # Don't output a no hi res message for such a file
402 # Image is small enough to show full size on image page
403 $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
406 $params['width'] = $width;
407 $params['height'] = $height;
408 $thumbnail = $this->displayImg
->transform( $params );
409 Linker
::processResponsiveImages( $this->displayImg
, $thumbnail, $params );
411 $anchorclose = Html
::rawElement(
413 [ 'class' => 'mw-filepage-resolutioninfo' ],
417 $isMulti = $this->displayImg
->isMultipage() && $this->displayImg
->pageCount() > 1;
419 $out->addModules( 'mediawiki.page.image.pagination' );
420 $out->addHTML( '<table class="multipageimage"><tr><td>' );
425 'alt' => $this->displayImg
->getTitle()->getPrefixedText(),
428 $out->addHTML( '<div class="fullImageLink" id="file">' .
429 $thumbnail->toHtml( $options ) .
430 $anchorclose . "</div>\n" );
434 $count = $this->displayImg
->pageCount();
437 $label = $this->getContext()->msg( 'imgmultipageprev' )->text();
438 // on the client side, this link is generated in ajaxifyPageNavigation()
439 // in the mediawiki.page.image.pagination module
440 $link = Linker
::linkKnown(
442 htmlspecialchars( $label ),
444 [ 'page' => $page - 1 ]
446 $thumb1 = Linker
::makeThumbLinkObj(
452 [ 'page' => $page - 1 ]
458 if ( $page < $count ) {
459 $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
460 $link = Linker
::linkKnown(
462 htmlspecialchars( $label ),
464 [ 'page' => $page +
1 ]
466 $thumb2 = Linker
::makeThumbLinkObj(
472 [ 'page' => $page +
1 ]
481 'name' => 'pageselector',
482 'action' => $wgScript,
485 for ( $i = 1; $i <= $count; $i++
) {
486 $options[] = Xml
::option( $lang->formatNum( $i ), $i, $i == $page );
488 $select = Xml
::tags( 'select',
489 [ 'id' => 'pageselector', 'name' => 'page' ],
490 implode( "\n", $options ) );
493 '</td><td><div class="multipageimagenavbox">' .
494 Xml
::openElement( 'form', $formParams ) .
495 Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
496 $this->getContext()->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
497 $this->getContext()->msg( 'word-separator' )->escaped() .
498 Xml
::submitButton( $this->getContext()->msg( 'imgmultigo' )->text() ) .
499 Xml
::closeElement( 'form' ) .
500 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
503 } elseif ( $this->displayImg
->isSafeFile() ) {
504 # if direct link is allowed but it's not a renderable image, show an icon.
505 $icon = $this->displayImg
->iconThumb();
507 $out->addHTML( '<div class="fullImageLink" id="file">' .
508 $icon->toHtml( [ 'file-link' => true ] ) .
512 $longDesc = $this->getContext()->msg( 'parentheses', $this->displayImg
->getLongDesc() )->text();
514 $handler = $this->displayImg
->getHandler();
516 // If this is a filetype with potential issues, warn the user.
518 $warningConfig = $handler->getWarningConfig( $this->displayImg
);
520 if ( $warningConfig !== null ) {
521 // The warning will be displayed via CSS and JavaScript.
522 // We just need to tell the client side what message to use.
523 $output = $this->getContext()->getOutput();
524 $output->addJsConfigVars( 'wgFileWarning', $warningConfig );
525 $output->addModules( $warningConfig['module'] );
526 $output->addModules( 'mediawiki.filewarning' );
530 $medialink = "[[Media:$filename|$linktext]]";
532 if ( !$this->displayImg
->isSafeFile() ) {
533 $warning = $this->getContext()->msg( 'mediawarning' )->plain();
534 // dirmark is needed here to separate the file name, which
535 // most likely ends in Latin characters, from the description,
536 // which may begin with the file type. In RTL environment
537 // this will get messy.
538 // The dirmark, however, must not be immediately adjacent
539 // to the filename, because it can get copied with it.
541 // phpcs:disable Generic.Files.LineLength
542 $out->addWikiText( <<<EOT
543 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
544 <div class="mediaWarning">$warning</div>
549 $out->addWikiText( <<<EOT
550 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
556 $renderLangOptions = $this->displayImg
->getAvailableLanguages();
557 if ( count( $renderLangOptions ) >= 1 ) {
558 $out->addHTML( $this->doRenderLangOpt( $renderLangOptions, $renderLang ) );
561 // Add cannot animate thumbnail warning
562 if ( !$this->displayImg
->canAnimateThumbIfAppropriate() ) {
563 // Include the extension so wiki admins can
564 // customize it on a per file-type basis
565 // (aka say things like use format X instead).
566 // additionally have a specific message for
567 // file-no-thumb-animation-gif
568 $ext = $this->displayImg
->getExtension();
569 $noAnimMesg = wfMessageFallback(
570 'file-no-thumb-animation-' . $ext,
571 'file-no-thumb-animation'
574 $out->addWikiText( <<<EOT
575 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
580 if ( !$this->displayImg
->isLocal() ) {
581 $this->printSharedImageText();
584 # Image does not exist
585 if ( !$this->getId() ) {
586 $dbr = wfGetDB( DB_REPLICA
);
588 # No article exists either
589 # Show deletion log to be consistent with normal articles
590 LogEventsList
::showLogExtract(
592 [ 'delete', 'move', 'protect' ],
593 $this->getTitle()->getPrefixedText(),
596 'conds' => [ 'log_action != ' . $dbr->addQuotes( '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 array $params parameters for thumbnail
631 * @param string $sizeLinkBigImagePreview HTML for the current size
632 * @return string HTML output
634 protected 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 protected 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 return $a->page_namespace
<=> $b->page_namespace
1018 ?
: strcmp( $a->page_title
, $b->page_title
);
1022 * Returns the corresponding $wgImageLimits entry for the selected user option
1025 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
1029 public function getImageLimitsFromOption( $user, $optionName ) {
1030 global $wgImageLimits;
1032 $option = $user->getIntOption( $optionName );
1033 if ( !isset( $wgImageLimits[$option] ) ) {
1034 $option = User
::getDefaultOption( $optionName );
1037 // The user offset might still be incorrect, specially if
1038 // $wgImageLimits got changed (see T10858).
1039 if ( !isset( $wgImageLimits[$option] ) ) {
1040 // Default to the first offset in $wgImageLimits
1044 // if nothing is set, fallback to a hardcoded default
1045 return $wgImageLimits[$option] ??
[ 800, 600 ];
1049 * Output a drop-down box for language options for the file
1051 * @param array $langChoices Array of string language codes
1052 * @param string $renderLang Language code for the language we want the file to rendered in.
1053 * @return string HTML to insert underneath image.
1055 protected function doRenderLangOpt( array $langChoices, $renderLang ) {
1059 $matchedRenderLang = $this->displayImg
->getMatchedLanguage( $renderLang );
1061 foreach ( $langChoices as $lang ) {
1062 $opts .= $this->createXmlOptionStringForLanguage(
1064 $matchedRenderLang === $lang
1068 // Allow for the default case in an svg <switch> that is displayed if no
1069 // systemLanguage attribute matches
1072 $this->getContext()->msg( 'img-lang-default' )->text(),
1074 is_null( $matchedRenderLang )
1077 $select = Html
::rawElement(
1079 [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1082 $submit = Xml
::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1084 $formContents = $this->getContext()->msg( 'img-lang-info' )
1085 ->rawParams( $select, $submit )
1087 $formContents .= Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1089 $langSelectLine = Html
::rawElement( 'div', [ 'id' => 'mw-imglangselector-line' ],
1090 Html
::rawElement( 'form', [ 'action' => $wgScript ], $formContents )
1092 return $langSelectLine;
1096 * @param $lang string
1097 * @param $selected bool
1100 private function createXmlOptionStringForLanguage( $lang, $selected ) {
1101 $code = LanguageCode
::bcp47( $lang );
1102 $name = Language
::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1103 if ( $name !== '' ) {
1104 $display = $this->getContext()->msg( 'img-lang-opt', $code, $name )->text();
1117 * Get the width and height to display image at.
1119 * @note This method assumes that it is only called if one
1120 * of the dimensions are bigger than the max, or if the
1121 * image is vectorized.
1123 * @param int $maxWidth Max width to display at
1124 * @param int $maxHeight Max height to display at
1125 * @param int $width Actual width of the image
1126 * @param int $height Actual height of the image
1127 * @throws MWException
1128 * @return array Array (width, height)
1130 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1131 if ( !$maxWidth ||
!$maxHeight ) {
1132 // should never happen
1133 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1136 if ( !$width ||
!$height ) {
1140 # Calculate the thumbnail size.
1141 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1142 // Vectorized image, do nothing.
1143 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1144 # The limiting factor is the width, not the height.
1145 $height = round( $height * $maxWidth / $width );
1147 # Note that $height <= $maxHeight now.
1149 $newwidth = floor( $width * $maxHeight / $height );
1150 $height = round( $height * $newwidth / $width );
1152 # Note that $height <= $maxHeight now, but might not be identical
1153 # because of rounding.
1155 return [ $width, $height ];
1159 * Get alternative thumbnail sizes.
1161 * @note This will only list several alternatives if thumbnails are rendered on 404
1162 * @param int $origWidth Actual width of image
1163 * @param int $origHeight Actual height of image
1164 * @return array An array of [width, height] pairs.
1166 protected function getThumbSizes( $origWidth, $origHeight ) {
1167 global $wgImageLimits;
1168 if ( $this->displayImg
->getRepo()->canTransformVia404() ) {
1169 $thumbSizes = $wgImageLimits;
1170 // Also include the full sized resolution in the list, so
1171 // that users know they can get it. This will link to the
1172 // original file asset if mustRender() === false. In the case
1173 // that we mustRender, some users have indicated that they would
1174 // find it useful to have the full size image in the rendered
1176 $thumbSizes[] = [ $origWidth, $origHeight ];
1178 # Creating thumb links triggers thumbnail generation.
1179 # Just generate the thumb for the current users prefs.
1181 $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' )
1183 if ( !$this->displayImg
->mustRender() ) {
1184 // We can safely include a link to the "full-size" preview,
1185 // without actually rendering.
1186 $thumbSizes[] = [ $origWidth, $origHeight ];
1193 * @see WikiFilePage::getFile
1196 public function getFile() {
1197 return $this->mPage
->getFile();
1201 * @see WikiFilePage::isLocal
1204 public function isLocal() {
1205 return $this->mPage
->isLocal();
1209 * @see WikiFilePage::getDuplicates
1210 * @return array|null
1212 public function getDuplicates() {
1213 return $this->mPage
->getDuplicates();
1217 * @see WikiFilePage::getForeignCategories
1218 * @return TitleArray|Title[]
1220 public function getForeignCategories() {
1221 $this->mPage
->getForeignCategories();