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 MediaWiki\MediaWikiServices
;
24 use Wikimedia\Rdbms\ResultWrapper
;
27 * Class for viewing MediaWiki file description pages
31 class ImagePage
extends Article
{
42 protected $mExtraDescription = false;
51 * @return WikiFilePage
53 protected function newPage( Title
$title ) {
54 // Overload mPage with a file-specific page
55 return new WikiFilePage( $title );
62 public function setFile( $file ) {
63 $this->mPage
->setFile( $file );
64 $this->displayImg
= $file;
65 $this->fileLoaded
= true;
68 protected function loadFile() {
69 if ( $this->fileLoaded
) {
72 $this->fileLoaded
= true;
74 $this->displayImg
= $img = false;
76 Hooks
::run( 'ImagePageFindFile', [ $this, &$img, &$this->displayImg
] );
77 if ( !$img ) { // not set by hook?
78 $img = wfFindFile( $this->getTitle() );
80 $img = wfLocalFile( $this->getTitle() );
83 $this->mPage
->setFile( $img );
84 if ( !$this->displayImg
) { // not set by hook?
85 $this->displayImg
= $img;
87 $this->repo
= $img->getRepo();
90 public function view() {
93 // For action=render, include body text only; none of the image extras
94 if ( $this->viewIsRenderAction
) {
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 $request->setVal( 'diffonly', 'true' );
123 if ( $wgShowEXIF && $this->displayImg
->exists() ) {
124 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
125 $formattedMetadata = $this->displayImg
->formatMetadata( $this->getContext() );
126 $showmeta = $formattedMetadata !== false;
131 if ( !$diff && $this->displayImg
->exists() ) {
132 $out->addHTML( $this->showTOC( $showmeta ) );
136 $this->openShowImage();
139 # No need to display noarticletext, we use our own message, output in openShowImage()
140 if ( $this->mPage
->getId() ) {
141 # NS_FILE is in the user language, but this section (the actual wikitext)
142 # should be in page content language
143 $pageLang = $this->getTitle()->getPageViewLanguage();
144 $out->addHTML( Xml
::openElement( 'div', [ 'id' => 'mw-imagepage-content',
145 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
146 'class' => 'mw-content-' . $pageLang->getDir() ] ) );
150 $out->addHTML( Xml
::closeElement( 'div' ) );
152 # Just need to set the right headers
153 $out->setArticleFlag( true );
154 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
155 $this->mPage
->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
158 # Show shared description, if needed
159 if ( $this->mExtraDescription
) {
160 $fol = $this->getContext()->msg( 'shareddescriptionfollows' );
161 if ( !$fol->isDisabled() ) {
162 $out->addWikiTextAsInterface( $fol->plain() );
164 $out->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription
. "</div>\n" );
167 $this->closeShowImage();
168 $this->imageHistory();
169 // TODO: Cleanup the following
171 $out->addHTML( Xml
::element( 'h2',
172 [ 'id' => 'filelinks' ],
173 $this->getContext()->msg( 'imagelinks' )->text() ) . "\n" );
175 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
176 # Yet we return metadata about the target. Definitely an issue in the FileRepo
179 # Allow extensions to add something after the image links
181 Hooks
::run( 'ImagePageAfterImageLinks', [ $this, &$html ] );
183 $out->addHTML( $html );
187 $out->addHTML( Xml
::element(
189 [ 'id' => 'metadata' ],
190 $this->getContext()->msg( 'metadata' )->text() ) . "\n" );
191 $out->wrapWikiTextAsInterface(
192 'mw-imagepage-section-metadata',
193 $this->makeMetadataTable( $formattedMetadata )
195 $out->addModules( [ 'mediawiki.action.view.metadata' ] );
198 // Add remote Filepage.css
199 if ( !$this->repo
->isLocal() ) {
200 $css = $this->repo
->getDescriptionStylesheetUrl();
202 $out->addStyle( $css );
206 $out->addModuleStyles( [
207 'filepage', // always show the local local Filepage.css, T31277
208 'mediawiki.action.view.filepage', // Add MediaWiki styles for a file page
215 public function getDisplayedFile() {
217 return $this->displayImg
;
223 * @param bool $metadata Whether or not to show the metadata link
226 protected function showTOC( $metadata ) {
228 '<li><a href="#file">' . $this->getContext()->msg( 'file-anchor-link' )->escaped() . '</a></li>',
229 '<li><a href="#filehistory">' . $this->getContext()->msg( 'filehist' )->escaped() . '</a></li>',
230 '<li><a href="#filelinks">' . $this->getContext()->msg( 'imagelinks' )->escaped() . '</a></li>',
233 Hooks
::run( 'ImagePageShowTOC', [ $this, &$r ] );
236 $r[] = '<li><a href="#metadata">' .
237 $this->getContext()->msg( 'metadata' )->escaped() .
241 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
245 * Make a table with metadata to be shown in the output page.
247 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
249 * @param array $metadata The array containing the Exif data
250 * @return string The metadata table. This is treated as Wikitext (!)
252 protected function makeMetadataTable( $metadata ) {
253 $r = $this->getContext()->msg( 'metadata-help' )->plain();
254 // Intial state is collapsed
255 // see filepage.css and mediawiki.action.view.metadata module.
256 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata collapsed\">\n";
257 foreach ( $metadata as $type => $stuff ) {
258 foreach ( $stuff as $v ) {
259 $class = str_replace( ' ', '_', $v['id'] );
260 if ( $type == 'collapsed' ) {
261 $class .= ' mw-metadata-collapsible';
263 $r .= Html
::rawElement( 'tr',
264 [ 'class' => $class ],
265 Html
::rawElement( 'th', [], $v['name'] )
266 . Html
::rawElement( 'td', [], $v['value'] )
275 * Overloading Article's getEmptyPageParserOutput method.
277 * Omit noarticletext if sharedupload; text will be fetched from the
278 * shared upload server if possible.
280 * @param ParserOptions $options
281 * @return ParserOutput
283 public function getEmptyPageParserOutput( ParserOptions
$options ) {
285 if ( $this->mPage
->getFile() && !$this->mPage
->getFile()->isLocal() && $this->getId() == 0 ) {
286 return new ParserOutput();
288 return parent
::getEmptyPageParserOutput( $options );
292 * Returns language code to be used for dispaying the image, based on request context and
293 * languages available in the file.
295 * @param WebRequest $request
297 * @return string|null
299 private function getLanguageForRendering( WebRequest
$request, File
$file ) {
300 $handler = $file->getHandler();
305 $config = MediaWikiServices
::getInstance()->getMainConfig();
306 $requestLanguage = $request->getVal( 'lang', $config->get( 'LanguageCode' ) );
307 if ( $handler->validateParam( 'lang', $requestLanguage ) ) {
308 return $file->getMatchedLanguage( $requestLanguage );
311 return $handler->getDefaultRenderLanguage( $file );
314 protected function openShowImage() {
315 global $wgEnableUploads, $wgSend404Code, $wgSVGMaxSize;
318 $out = $this->getContext()->getOutput();
319 $user = $this->getContext()->getUser();
320 $lang = $this->getContext()->getLanguage();
321 $dirmark = $lang->getDirMarkEntity();
322 $request = $this->getContext()->getRequest();
324 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
326 $maxHeight = $max[1];
328 if ( $this->displayImg
->exists() ) {
330 $page = $request->getIntOrNull( 'page' );
331 if ( is_null( $page ) ) {
335 $params = [ 'page' => $page ];
338 $renderLang = $this->getLanguageForRendering( $request, $this->displayImg
);
339 if ( !is_null( $renderLang ) ) {
340 $params['lang'] = $renderLang;
343 $width_orig = $this->displayImg
->getWidth( $page );
344 $width = $width_orig;
345 $height_orig = $this->displayImg
->getHeight( $page );
346 $height = $height_orig;
348 $filename = wfEscapeWikiText( $this->displayImg
->getName() );
349 $linktext = $filename;
351 // Avoid PHP 7.1 warning from passing $this by reference
354 Hooks
::run( 'ImageOpenShowImageInlineBefore', [ &$imagePage, &$out ] );
356 if ( $this->displayImg
->allowInlineDisplay() ) {
358 # "Download high res version" link below the image
359 # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
360 # Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
361 # We'll show a thumbnail of this image
362 if ( $width > $maxWidth ||
$height > $maxHeight ||
$this->displayImg
->isVectorized() ) {
363 list( $width, $height ) = $this->getDisplayWidthHeight(
364 $maxWidth, $maxHeight, $width, $height
366 $linktext = $this->getContext()->msg( 'show-big-image' )->escaped();
368 $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
369 # Generate thumbnails or thumbnail links as needed...
371 foreach ( $thumbSizes as $size ) {
372 // We include a thumbnail size in the list, if it is
373 // less than or equal to the original size of the image
374 // asset ($width_orig/$height_orig). We also exclude
375 // the current thumbnail's size ($width/$height)
376 // since that is added to the message separately, so
377 // it can be denoted as the current size being shown.
378 // Vectorized images are limited by $wgSVGMaxSize big,
379 // so all thumbs less than or equal that are shown.
380 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
381 ||
( $this->displayImg
->isVectorized()
382 && max( $size[0], $size[1] ) <= $wgSVGMaxSize )
384 && $size[0] != $width && $size[1] != $height
386 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
388 $otherSizes[] = $sizeLink;
392 $otherSizes = array_unique( $otherSizes );
394 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
395 $msgsmall = $this->getThumbPrevText( $params, $sizeLinkBigImagePreview );
396 if ( count( $otherSizes ) ) {
400 [ 'class' => 'mw-filepage-other-resolutions' ],
401 $this->getContext()->msg( 'show-big-image-other' )
402 ->rawParams( $lang->pipeList( $otherSizes ) )
403 ->params( count( $otherSizes ) )
407 } elseif ( $width == 0 && $height == 0 ) {
408 # Some sort of audio file that doesn't have dimensions
409 # Don't output a no hi res message for such a file
412 # Image is small enough to show full size on image page
413 $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
416 $params['width'] = $width;
417 $params['height'] = $height;
418 $thumbnail = $this->displayImg
->transform( $params );
419 Linker
::processResponsiveImages( $this->displayImg
, $thumbnail, $params );
421 $anchorclose = Html
::rawElement(
423 [ 'class' => 'mw-filepage-resolutioninfo' ],
427 $isMulti = $this->displayImg
->isMultipage() && $this->displayImg
->pageCount() > 1;
429 $out->addModules( 'mediawiki.page.image.pagination' );
430 $out->addHTML( '<table class="multipageimage"><tr><td>' );
435 'alt' => $this->displayImg
->getTitle()->getPrefixedText(),
438 $out->addHTML( '<div class="fullImageLink" id="file">' .
439 $thumbnail->toHtml( $options ) .
440 $anchorclose . "</div>\n" );
444 $count = $this->displayImg
->pageCount();
447 $label = $this->getContext()->msg( 'imgmultipageprev' )->text();
448 // on the client side, this link is generated in ajaxifyPageNavigation()
449 // in the mediawiki.page.image.pagination module
450 $link = Linker
::linkKnown(
452 htmlspecialchars( $label ),
454 [ 'page' => $page - 1 ]
456 $thumb1 = Linker
::makeThumbLinkObj(
462 [ 'page' => $page - 1 ]
468 if ( $page < $count ) {
469 $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
470 $link = Linker
::linkKnown(
472 htmlspecialchars( $label ),
474 [ 'page' => $page +
1 ]
476 $thumb2 = Linker
::makeThumbLinkObj(
482 [ 'page' => $page +
1 ]
491 'name' => 'pageselector',
492 'action' => $wgScript,
495 for ( $i = 1; $i <= $count; $i++
) {
496 $options[] = Xml
::option( $lang->formatNum( $i ), $i, $i == $page );
498 $select = Xml
::tags( 'select',
499 [ 'id' => 'pageselector', 'name' => 'page' ],
500 implode( "\n", $options ) );
503 '</td><td><div class="multipageimagenavbox">' .
504 Xml
::openElement( 'form', $formParams ) .
505 Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
506 $this->getContext()->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
507 $this->getContext()->msg( 'word-separator' )->escaped() .
508 Xml
::submitButton( $this->getContext()->msg( 'imgmultigo' )->text() ) .
509 Xml
::closeElement( 'form' ) .
510 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
513 } elseif ( $this->displayImg
->isSafeFile() ) {
514 # if direct link is allowed but it's not a renderable image, show an icon.
515 $icon = $this->displayImg
->iconThumb();
517 $out->addHTML( '<div class="fullImageLink" id="file">' .
518 $icon->toHtml( [ 'file-link' => true ] ) .
522 $longDesc = $this->getContext()->msg( 'parentheses', $this->displayImg
->getLongDesc() )->text();
524 $handler = $this->displayImg
->getHandler();
526 // If this is a filetype with potential issues, warn the user.
528 $warningConfig = $handler->getWarningConfig( $this->displayImg
);
530 if ( $warningConfig !== null ) {
531 // The warning will be displayed via CSS and JavaScript.
532 // We just need to tell the client side what message to use.
533 $output = $this->getContext()->getOutput();
534 $output->addJsConfigVars( 'wgFileWarning', $warningConfig );
535 $output->addModules( $warningConfig['module'] );
536 $output->addModules( 'mediawiki.filewarning' );
540 $medialink = "[[Media:$filename|$linktext]]";
542 if ( !$this->displayImg
->isSafeFile() ) {
543 $warning = $this->getContext()->msg( 'mediawarning' )->plain();
544 // dirmark is needed here to separate the file name, which
545 // most likely ends in Latin characters, from the description,
546 // which may begin with the file type. In RTL environment
547 // this will get messy.
548 // The dirmark, however, must not be immediately adjacent
549 // to the filename, because it can get copied with it.
551 // phpcs:disable Generic.Files.LineLength
552 $out->wrapWikiTextAsInterface( 'fullMedia', <<<EOT
553 <span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span>
557 $out->wrapWikiTextAsInterface( 'mediaWarning', $warning );
559 $out->wrapWikiTextAsInterface( 'fullMedia', <<<EOT
560 {$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
565 $renderLangOptions = $this->displayImg
->getAvailableLanguages();
566 if ( count( $renderLangOptions ) >= 1 ) {
567 $out->addHTML( $this->doRenderLangOpt( $renderLangOptions, $renderLang ) );
570 // Add cannot animate thumbnail warning
571 if ( !$this->displayImg
->canAnimateThumbIfAppropriate() ) {
572 // Include the extension so wiki admins can
573 // customize it on a per file-type basis
574 // (aka say things like use format X instead).
575 // additionally have a specific message for
576 // file-no-thumb-animation-gif
577 $ext = $this->displayImg
->getExtension();
578 $noAnimMesg = wfMessageFallback(
579 'file-no-thumb-animation-' . $ext,
580 'file-no-thumb-animation'
583 $out->wrapWikiTextAsInterface( 'mw-noanimatethumb', $noAnimMesg );
586 if ( !$this->displayImg
->isLocal() ) {
587 $this->printSharedImageText();
590 # Image does not exist
591 if ( !$this->getId() ) {
592 $dbr = wfGetDB( DB_REPLICA
);
594 # No article exists either
595 # Show deletion log to be consistent with normal articles
596 LogEventsList
::showLogExtract(
598 [ 'delete', 'move', 'protect' ],
599 $this->getTitle()->getPrefixedText(),
602 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
603 'showIfEmpty' => false,
604 'msgKey' => [ 'moveddeleted-notice' ]
609 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
610 // Only show an upload link if the user can upload
611 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
613 'filepage-nofile-link',
614 $uploadTitle->getFullURL( [ 'wpDestFile' => $this->mPage
->getFile()->getName() ] )
617 $nofile = 'filepage-nofile';
619 // Note, if there is an image description page, but
620 // no image, then this setRobotPolicy is overridden
621 // by Article::View().
622 $out->setRobotPolicy( 'noindex,nofollow' );
623 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
624 if ( !$this->getId() && $wgSend404Code ) {
625 // If there is no image, no shared image, and no description page,
626 // output a 404, to be consistent with Article::showMissingArticle.
627 $request->response()->statusHeader( 404 );
630 $out->setFileVersion( $this->displayImg
);
634 * Make the text under the image to say what size preview
636 * @param array $params parameters for thumbnail
637 * @param string $sizeLinkBigImagePreview HTML for the current size
638 * @return string HTML output
640 protected function getThumbPrevText( $params, $sizeLinkBigImagePreview ) {
641 if ( $sizeLinkBigImagePreview ) {
642 // Show a different message of preview is different format from original.
643 $previewTypeDiffers = false;
644 $origExt = $thumbExt = $this->displayImg
->getExtension();
645 if ( $this->displayImg
->getHandler() ) {
646 $origMime = $this->displayImg
->getMimeType();
647 $typeParams = $params;
648 $this->displayImg
->getHandler()->normaliseParams( $this->displayImg
, $typeParams );
649 list( $thumbExt, $thumbMime ) = $this->displayImg
->getHandler()->getThumbType(
650 $origExt, $origMime, $typeParams );
651 if ( $thumbMime !== $origMime ) {
652 $previewTypeDiffers = true;
655 if ( $previewTypeDiffers ) {
656 return $this->getContext()->msg( 'show-big-image-preview-differ' )->
657 rawParams( $sizeLinkBigImagePreview )->
658 params( strtoupper( $origExt ) )->
659 params( strtoupper( $thumbExt ) )->
662 return $this->getContext()->msg( 'show-big-image-preview' )->
663 rawParams( $sizeLinkBigImagePreview )->
672 * Creates an thumbnail of specified size and returns an HTML link to it
673 * @param array $params Scaler parameters
678 protected function makeSizeLink( $params, $width, $height ) {
679 $params['width'] = $width;
680 $params['height'] = $height;
681 $thumbnail = $this->displayImg
->transform( $params );
682 if ( $thumbnail && !$thumbnail->isError() ) {
683 return Html
::rawElement( 'a', [
684 'href' => $thumbnail->getUrl(),
685 'class' => 'mw-thumbnail-link'
686 ], $this->getContext()->msg( 'show-big-image-size' )->numParams(
687 $thumbnail->getWidth(), $thumbnail->getHeight()
695 * Show a notice that the file is from a shared repository
697 protected function printSharedImageText() {
698 $out = $this->getContext()->getOutput();
701 $descUrl = $this->mPage
->getFile()->getDescriptionUrl();
702 $descText = $this->mPage
->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
704 /* Add canonical to head if there is no local page for this shared file */
705 if ( $descUrl && $this->mPage
->getId() == 0 ) {
706 $out->setCanonicalUrl( $descUrl );
709 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
710 $repo = $this->mPage
->getFile()->getRepo()->getDisplayName();
714 $this->getContext()->msg( 'sharedupload-desc-here' )->plain() !== '-'
716 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-here', $repo, $descUrl ] );
717 } elseif ( $descUrl &&
718 $this->getContext()->msg( 'sharedupload-desc-there' )->plain() !== '-'
720 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-there', $repo, $descUrl ] );
722 $out->wrapWikiMsg( $wrap, [ 'sharedupload', $repo ], ''/*BACKCOMPAT*/ );
726 $this->mExtraDescription
= $descText;
730 public function getUploadUrl() {
732 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
733 return $uploadTitle->getFullURL( [
734 'wpDestFile' => $this->mPage
->getFile()->getName(),
740 * Print out the various links at the bottom of the image page, e.g. reupload,
741 * external editing (and instructions link) etc.
743 protected function uploadLinksBox() {
744 global $wgEnableUploads;
746 if ( !$wgEnableUploads ) {
751 if ( !$this->mPage
->getFile()->isLocal() ) {
755 $out = $this->getContext()->getOutput();
756 $out->addHTML( "<ul>\n" );
758 # "Upload a new version of this file" link
759 $canUpload = $this->getTitle()->quickUserCan( 'upload', $this->getContext()->getUser() );
760 if ( $canUpload && UploadBase
::userCanReUpload(
761 $this->getContext()->getUser(),
762 $this->mPage
->getFile() )
764 $ulink = Linker
::makeExternalLink(
765 $this->getUploadUrl(),
766 $this->getContext()->msg( 'uploadnewversion-linktext' )->text()
768 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\">"
769 . "<div class=\"plainlinks\">{$ulink}</div></li>\n" );
771 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">"
772 . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
775 $out->addHTML( "</ul>\n" );
781 protected function closeShowImage() {
785 * If the page we've just displayed is in the "Image" namespace,
786 * we follow it with an upload history of the image and its usage.
788 protected function imageHistory() {
790 $out = $this->getContext()->getOutput();
791 $pager = new ImageHistoryPseudoPager( $this );
792 $out->addHTML( $pager->getBody() );
793 $out->preventClickjacking( $pager->getPreventClickjacking() );
795 $this->mPage
->getFile()->resetHistory(); // free db resources
797 # Exist check because we don't want to show this on pages where an image
798 # doesn't exist along with the noimage message, that would suck. -ævar
799 if ( $this->mPage
->getFile()->exists() ) {
800 $this->uploadLinksBox();
805 * @param string $target
807 * @return ResultWrapper
809 protected function queryImageLinks( $target, $limit ) {
810 $dbr = wfGetDB( DB_REPLICA
);
813 [ 'imagelinks', 'page' ],
814 [ 'page_namespace', 'page_title', 'il_to' ],
815 [ 'il_to' => $target, 'il_from = page_id' ],
817 [ 'LIMIT' => $limit +
1, 'ORDER BY' => 'il_from', ]
821 protected function imageLinks() {
824 $out = $this->getContext()->getOutput();
828 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE
) as $redir ) {
829 $redirects[$redir->getDBkey()] = [];
831 'page_namespace' => NS_FILE
,
832 'page_title' => $redir->getDBkey(),
836 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit +
1 );
837 foreach ( $res as $row ) {
840 $count = count( $rows );
842 $hasMore = $count > $limit;
843 if ( !$hasMore && count( $redirects ) ) {
844 $res = $this->queryImageLinks( array_keys( $redirects ),
845 $limit - count( $rows ) +
1 );
846 foreach ( $res as $row ) {
847 $redirects[$row->il_to
][] = $row;
850 $hasMore = ( $res->numRows() +
count( $rows ) ) > $limit;
855 Html
::rawElement( 'div',
856 [ 'id' => 'mw-imagepage-nolinkstoimage' ], "\n$1\n" ),
862 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
864 $out->addWikiMsg( 'linkstoimage', $count );
866 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
867 $out->addWikiMsg( 'linkstoimage-more',
868 $this->getContext()->getLanguage()->formatNum( $limit ),
869 $this->getTitle()->getPrefixedDBkey()
874 Html
::openElement( 'ul',
875 [ 'class' => 'mw-imagepage-linkstoimage' ] ) . "\n"
879 // Sort the list by namespace:title
880 usort( $rows, [ $this, 'compare' ] );
882 // Create links for every element
884 foreach ( $rows as $element ) {
886 if ( $currentCount > $limit ) {
891 # Add a redirect=no to make redirect pages reachable
892 if ( isset( $redirects[$element->page_title
] ) ) {
893 $query['redirect'] = 'no';
895 $link = Linker
::linkKnown(
896 Title
::makeTitle( $element->page_namespace
, $element->page_title
),
899 if ( !isset( $redirects[$element->page_title
] ) ) {
902 } elseif ( count( $redirects[$element->page_title
] ) === 0 ) {
903 # Redirect without usages
904 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )
905 ->rawParams( $link, '' )
908 # Redirect with usages
910 foreach ( $redirects[$element->page_title
] as $row ) {
912 if ( $currentCount > $limit ) {
916 $link2 = Linker
::linkKnown( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
917 $li .= Html
::rawElement(
919 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
],
924 $ul = Html
::rawElement(
926 [ 'class' => 'mw-imagepage-redirectstofile' ],
929 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
930 $link, $ul )->parse();
932 $out->addHTML( Html
::rawElement(
934 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
],
940 $out->addHTML( Html
::closeElement( 'ul' ) . "\n" );
943 // Add a links to [[Special:Whatlinkshere]]
944 if ( $count > $limit ) {
945 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
947 $out->addHTML( Html
::closeElement( 'div' ) . "\n" );
950 protected function imageDupes() {
952 $out = $this->getContext()->getOutput();
954 $dupes = $this->mPage
->getDuplicates();
955 if ( count( $dupes ) == 0 ) {
959 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
960 $out->addWikiMsg( 'duplicatesoffile',
961 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
963 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
968 foreach ( $dupes as $file ) {
970 if ( $file->isLocal() ) {
971 $link = Linker
::linkKnown( $file->getTitle() );
973 $link = Linker
::makeExternalLink( $file->getDescriptionUrl(),
974 $file->getTitle()->getPrefixedText() );
975 $fromSrc = $this->getContext()->msg(
977 $file->getRepo()->getDisplayName()
980 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
982 $out->addHTML( "</ul></div>\n" );
986 * Delete the file, or an earlier version of it
988 public function delete() {
989 $file = $this->mPage
->getFile();
990 if ( !$file->exists() ||
!$file->isLocal() ||
$file->getRedirected() ) {
991 // Standard article deletion
996 $deleter = new FileDeleteForm( $file );
1001 * Display an error with a wikitext description
1003 * @param string $description
1005 function showError( $description ) {
1006 $out = $this->getContext()->getOutput();
1007 $out->setPageTitle( $this->getContext()->msg( 'internalerror' ) );
1008 $out->setRobotPolicy( 'noindex,nofollow' );
1009 $out->setArticleRelated( false );
1010 $out->enableClientCache( false );
1011 $out->addWikiTextAsInterface( $description );
1015 * Callback for usort() to do link sorts by (namespace, title)
1016 * Function copied from Title::compare()
1018 * @param object $a Object page to compare with
1019 * @param object $b Object page to compare with
1020 * @return int Result of string comparison, or namespace comparison
1022 protected function compare( $a, $b ) {
1023 return $a->page_namespace
<=> $b->page_namespace
1024 ?
: strcmp( $a->page_title
, $b->page_title
);
1028 * Returns the corresponding $wgImageLimits entry for the selected user option
1031 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
1035 public function getImageLimitsFromOption( $user, $optionName ) {
1036 global $wgImageLimits;
1038 $option = $user->getIntOption( $optionName );
1039 if ( !isset( $wgImageLimits[$option] ) ) {
1040 $option = User
::getDefaultOption( $optionName );
1043 // The user offset might still be incorrect, specially if
1044 // $wgImageLimits got changed (see T10858).
1045 if ( !isset( $wgImageLimits[$option] ) ) {
1046 // Default to the first offset in $wgImageLimits
1050 // if nothing is set, fallback to a hardcoded default
1051 return $wgImageLimits[$option] ??
[ 800, 600 ];
1055 * Output a drop-down box for language options for the file
1057 * @param array $langChoices Array of string language codes
1058 * @param string $renderLang Language code for the language we want the file to rendered in.
1059 * @return string HTML to insert underneath image.
1061 protected function doRenderLangOpt( array $langChoices, $renderLang ) {
1065 $matchedRenderLang = $this->displayImg
->getMatchedLanguage( $renderLang );
1067 foreach ( $langChoices as $lang ) {
1068 $opts .= $this->createXmlOptionStringForLanguage(
1070 $matchedRenderLang === $lang
1074 // Allow for the default case in an svg <switch> that is displayed if no
1075 // systemLanguage attribute matches
1078 $this->getContext()->msg( 'img-lang-default' )->text(),
1080 is_null( $matchedRenderLang )
1083 $select = Html
::rawElement(
1085 [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1088 $submit = Xml
::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1090 $formContents = $this->getContext()->msg( 'img-lang-info' )
1091 ->rawParams( $select, $submit )
1093 $formContents .= Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1095 $langSelectLine = Html
::rawElement( 'div', [ 'id' => 'mw-imglangselector-line' ],
1096 Html
::rawElement( 'form', [ 'action' => $wgScript ], $formContents )
1098 return $langSelectLine;
1102 * @param string $lang
1103 * @param bool $selected
1106 private function createXmlOptionStringForLanguage( $lang, $selected ) {
1107 $code = LanguageCode
::bcp47( $lang );
1108 $name = Language
::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1109 if ( $name !== '' ) {
1110 $display = $this->getContext()->msg( 'img-lang-opt', $code, $name )->text();
1123 * Get the width and height to display image at.
1125 * @note This method assumes that it is only called if one
1126 * of the dimensions are bigger than the max, or if the
1127 * image is vectorized.
1129 * @param int $maxWidth Max width to display at
1130 * @param int $maxHeight Max height to display at
1131 * @param int $width Actual width of the image
1132 * @param int $height Actual height of the image
1133 * @throws MWException
1134 * @return array Array (width, height)
1136 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1137 if ( !$maxWidth ||
!$maxHeight ) {
1138 // should never happen
1139 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1142 if ( !$width ||
!$height ) {
1146 # Calculate the thumbnail size.
1147 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1148 // Vectorized image, do nothing.
1149 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1150 # The limiting factor is the width, not the height.
1151 $height = round( $height * $maxWidth / $width );
1153 # Note that $height <= $maxHeight now.
1155 $newwidth = floor( $width * $maxHeight / $height );
1156 $height = round( $height * $newwidth / $width );
1158 # Note that $height <= $maxHeight now, but might not be identical
1159 # because of rounding.
1161 return [ $width, $height ];
1165 * Get alternative thumbnail sizes.
1167 * @note This will only list several alternatives if thumbnails are rendered on 404
1168 * @param int $origWidth Actual width of image
1169 * @param int $origHeight Actual height of image
1170 * @return array An array of [width, height] pairs.
1172 protected function getThumbSizes( $origWidth, $origHeight ) {
1173 global $wgImageLimits;
1174 if ( $this->displayImg
->getRepo()->canTransformVia404() ) {
1175 $thumbSizes = $wgImageLimits;
1176 // Also include the full sized resolution in the list, so
1177 // that users know they can get it. This will link to the
1178 // original file asset if mustRender() === false. In the case
1179 // that we mustRender, some users have indicated that they would
1180 // find it useful to have the full size image in the rendered
1182 $thumbSizes[] = [ $origWidth, $origHeight ];
1184 # Creating thumb links triggers thumbnail generation.
1185 # Just generate the thumb for the current users prefs.
1187 $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' )
1189 if ( !$this->displayImg
->mustRender() ) {
1190 // We can safely include a link to the "full-size" preview,
1191 // without actually rendering.
1192 $thumbSizes[] = [ $origWidth, $origHeight ];
1199 * @see WikiFilePage::getFile
1202 public function getFile() {
1203 return $this->mPage
->getFile();
1207 * @see WikiFilePage::isLocal
1210 public function isLocal() {
1211 return $this->mPage
->isLocal();
1215 * @see WikiFilePage::getDuplicates
1216 * @return array|null
1218 public function getDuplicates() {
1219 return $this->mPage
->getDuplicates();
1223 * @see WikiFilePage::getForeignCategories
1224 * @return TitleArray|Title[]
1226 public function getForeignCategories() {
1227 $this->mPage
->getForeignCategories();