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 list( $maxWidth, $maxHeight ) = $this->getImageLimitsFromOption( $user, 'imagesize' );
326 if ( $this->displayImg
->exists() ) {
328 $page = $request->getIntOrNull( 'page' );
329 if ( is_null( $page ) ) {
333 $params = [ 'page' => $page ];
336 $renderLang = $this->getLanguageForRendering( $request, $this->displayImg
);
337 if ( !is_null( $renderLang ) ) {
338 $params['lang'] = $renderLang;
341 $width_orig = $this->displayImg
->getWidth( $page );
342 $width = $width_orig;
343 $height_orig = $this->displayImg
->getHeight( $page );
344 $height = $height_orig;
346 $filename = wfEscapeWikiText( $this->displayImg
->getName() );
347 $linktext = $filename;
349 // Avoid PHP 7.1 warning from passing $this by reference
352 Hooks
::run( 'ImageOpenShowImageInlineBefore', [ &$imagePage, &$out ] );
354 if ( $this->displayImg
->allowInlineDisplay() ) {
356 # "Download high res version" link below the image
357 # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
358 # Language::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
359 # We'll show a thumbnail of this image
360 if ( $width > $maxWidth ||
$height > $maxHeight ||
$this->displayImg
->isVectorized() ) {
361 list( $width, $height ) = $this->getDisplayWidthHeight(
362 $maxWidth, $maxHeight, $width, $height
364 $linktext = $this->getContext()->msg( 'show-big-image' )->escaped();
366 $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
367 # Generate thumbnails or thumbnail links as needed...
369 foreach ( $thumbSizes as $size ) {
370 // We include a thumbnail size in the list, if it is
371 // less than or equal to the original size of the image
372 // asset ($width_orig/$height_orig). We also exclude
373 // the current thumbnail's size ($width/$height)
374 // since that is added to the message separately, so
375 // it can be denoted as the current size being shown.
376 // Vectorized images are limited by $wgSVGMaxSize big,
377 // so all thumbs less than or equal that are shown.
378 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
379 ||
( $this->displayImg
->isVectorized()
380 && max( $size[0], $size[1] ) <= $wgSVGMaxSize )
382 && $size[0] != $width && $size[1] != $height
384 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
386 $otherSizes[] = $sizeLink;
390 $otherSizes = array_unique( $otherSizes );
392 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
393 $msgsmall = $this->getThumbPrevText( $params, $sizeLinkBigImagePreview );
394 if ( count( $otherSizes ) ) {
398 [ 'class' => 'mw-filepage-other-resolutions' ],
399 $this->getContext()->msg( 'show-big-image-other' )
400 ->rawParams( $lang->pipeList( $otherSizes ) )
401 ->params( count( $otherSizes ) )
405 } elseif ( $width == 0 && $height == 0 ) {
406 # Some sort of audio file that doesn't have dimensions
407 # Don't output a no hi res message for such a file
410 # Image is small enough to show full size on image page
411 $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
414 $params['width'] = $width;
415 $params['height'] = $height;
416 $thumbnail = $this->displayImg
->transform( $params );
417 Linker
::processResponsiveImages( $this->displayImg
, $thumbnail, $params );
419 $anchorclose = Html
::rawElement(
421 [ 'class' => 'mw-filepage-resolutioninfo' ],
425 $isMulti = $this->displayImg
->isMultipage() && $this->displayImg
->pageCount() > 1;
427 $out->addModules( 'mediawiki.page.image.pagination' );
428 $out->addHTML( '<table class="multipageimage"><tr><td>' );
433 'alt' => $this->displayImg
->getTitle()->getPrefixedText(),
436 $out->addHTML( '<div class="fullImageLink" id="file">' .
437 $thumbnail->toHtml( $options ) .
438 $anchorclose . "</div>\n" );
442 $count = $this->displayImg
->pageCount();
445 $label = $this->getContext()->msg( 'imgmultipageprev' )->text();
446 // on the client side, this link is generated in ajaxifyPageNavigation()
447 // in the mediawiki.page.image.pagination module
448 $link = Linker
::linkKnown(
450 htmlspecialchars( $label ),
452 [ 'page' => $page - 1 ]
454 $thumb1 = Linker
::makeThumbLinkObj(
460 [ 'page' => $page - 1 ]
466 if ( $page < $count ) {
467 $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
468 $link = Linker
::linkKnown(
470 htmlspecialchars( $label ),
472 [ 'page' => $page +
1 ]
474 $thumb2 = Linker
::makeThumbLinkObj(
480 [ 'page' => $page +
1 ]
489 'name' => 'pageselector',
490 'action' => $wgScript,
493 for ( $i = 1; $i <= $count; $i++
) {
494 $options[] = Xml
::option( $lang->formatNum( $i ), $i, $i == $page );
496 $select = Xml
::tags( 'select',
497 [ 'id' => 'pageselector', 'name' => 'page' ],
498 implode( "\n", $options ) );
501 '</td><td><div class="multipageimagenavbox">' .
502 Xml
::openElement( 'form', $formParams ) .
503 Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
504 $this->getContext()->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
505 $this->getContext()->msg( 'word-separator' )->escaped() .
506 Xml
::submitButton( $this->getContext()->msg( 'imgmultigo' )->text() ) .
507 Xml
::closeElement( 'form' ) .
508 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
511 } elseif ( $this->displayImg
->isSafeFile() ) {
512 # if direct link is allowed but it's not a renderable image, show an icon.
513 $icon = $this->displayImg
->iconThumb();
515 $out->addHTML( '<div class="fullImageLink" id="file">' .
516 $icon->toHtml( [ 'file-link' => true ] ) .
520 $longDesc = $this->getContext()->msg( 'parentheses', $this->displayImg
->getLongDesc() )->text();
522 $handler = $this->displayImg
->getHandler();
524 // If this is a filetype with potential issues, warn the user.
526 $warningConfig = $handler->getWarningConfig( $this->displayImg
);
528 if ( $warningConfig !== null ) {
529 // The warning will be displayed via CSS and JavaScript.
530 // We just need to tell the client side what message to use.
531 $output = $this->getContext()->getOutput();
532 $output->addJsConfigVars( 'wgFileWarning', $warningConfig );
533 $output->addModules( $warningConfig['module'] );
534 $output->addModules( 'mediawiki.filewarning' );
538 $medialink = "[[Media:$filename|$linktext]]";
540 if ( !$this->displayImg
->isSafeFile() ) {
541 $warning = $this->getContext()->msg( 'mediawarning' )->plain();
542 // dirmark is needed here to separate the file name, which
543 // most likely ends in Latin characters, from the description,
544 // which may begin with the file type. In RTL environment
545 // this will get messy.
546 // The dirmark, however, must not be immediately adjacent
547 // to the filename, because it can get copied with it.
549 // phpcs:disable Generic.Files.LineLength
550 $out->wrapWikiTextAsInterface( 'fullMedia', <<<EOT
551 <span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span>
555 $out->wrapWikiTextAsInterface( 'mediaWarning', $warning );
557 $out->wrapWikiTextAsInterface( 'fullMedia', <<<EOT
558 {$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
563 $renderLangOptions = $this->displayImg
->getAvailableLanguages();
564 if ( count( $renderLangOptions ) >= 1 ) {
565 $out->addHTML( $this->doRenderLangOpt( $renderLangOptions, $renderLang ) );
568 // Add cannot animate thumbnail warning
569 if ( !$this->displayImg
->canAnimateThumbIfAppropriate() ) {
570 // Include the extension so wiki admins can
571 // customize it on a per file-type basis
572 // (aka say things like use format X instead).
573 // additionally have a specific message for
574 // file-no-thumb-animation-gif
575 $ext = $this->displayImg
->getExtension();
576 $noAnimMesg = wfMessageFallback(
577 'file-no-thumb-animation-' . $ext,
578 'file-no-thumb-animation'
581 $out->wrapWikiTextAsInterface( 'mw-noanimatethumb', $noAnimMesg );
584 if ( !$this->displayImg
->isLocal() ) {
585 $this->printSharedImageText();
588 # Image does not exist
589 if ( !$this->getId() ) {
590 $dbr = wfGetDB( DB_REPLICA
);
592 # No article exists either
593 # Show deletion log to be consistent with normal articles
594 LogEventsList
::showLogExtract(
596 [ 'delete', 'move', 'protect' ],
597 $this->getTitle()->getPrefixedText(),
600 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
601 'showIfEmpty' => false,
602 'msgKey' => [ 'moveddeleted-notice' ]
607 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
608 // Only show an upload link if the user can upload
609 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
611 'filepage-nofile-link',
612 $uploadTitle->getFullURL( [ 'wpDestFile' => $this->mPage
->getFile()->getName() ] )
615 $nofile = 'filepage-nofile';
617 // Note, if there is an image description page, but
618 // no image, then this setRobotPolicy is overridden
619 // by Article::View().
620 $out->setRobotPolicy( 'noindex,nofollow' );
621 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
622 if ( !$this->getId() && $wgSend404Code ) {
623 // If there is no image, no shared image, and no description page,
624 // output a 404, to be consistent with Article::showMissingArticle.
625 $request->response()->statusHeader( 404 );
628 $out->setFileVersion( $this->displayImg
);
632 * Make the text under the image to say what size preview
634 * @param array $params parameters for thumbnail
635 * @param string $sizeLinkBigImagePreview HTML for the current size
636 * @return string HTML output
638 protected function getThumbPrevText( $params, $sizeLinkBigImagePreview ) {
639 if ( $sizeLinkBigImagePreview ) {
640 // Show a different message of preview is different format from original.
641 $previewTypeDiffers = false;
642 $origExt = $thumbExt = $this->displayImg
->getExtension();
643 if ( $this->displayImg
->getHandler() ) {
644 $origMime = $this->displayImg
->getMimeType();
645 $typeParams = $params;
646 $this->displayImg
->getHandler()->normaliseParams( $this->displayImg
, $typeParams );
647 list( $thumbExt, $thumbMime ) = $this->displayImg
->getHandler()->getThumbType(
648 $origExt, $origMime, $typeParams );
649 if ( $thumbMime !== $origMime ) {
650 $previewTypeDiffers = true;
653 if ( $previewTypeDiffers ) {
654 return $this->getContext()->msg( 'show-big-image-preview-differ' )->
655 rawParams( $sizeLinkBigImagePreview )->
656 params( strtoupper( $origExt ) )->
657 params( strtoupper( $thumbExt ) )->
660 return $this->getContext()->msg( 'show-big-image-preview' )->
661 rawParams( $sizeLinkBigImagePreview )->
670 * Creates an thumbnail of specified size and returns an HTML link to it
671 * @param array $params Scaler parameters
676 protected function makeSizeLink( $params, $width, $height ) {
677 $params['width'] = $width;
678 $params['height'] = $height;
679 $thumbnail = $this->displayImg
->transform( $params );
680 if ( $thumbnail && !$thumbnail->isError() ) {
681 return Html
::rawElement( 'a', [
682 'href' => $thumbnail->getUrl(),
683 'class' => 'mw-thumbnail-link'
684 ], $this->getContext()->msg( 'show-big-image-size' )->numParams(
685 $thumbnail->getWidth(), $thumbnail->getHeight()
693 * Show a notice that the file is from a shared repository
695 protected function printSharedImageText() {
696 $out = $this->getContext()->getOutput();
699 $descUrl = $this->mPage
->getFile()->getDescriptionUrl();
700 $descText = $this->mPage
->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
702 /* Add canonical to head if there is no local page for this shared file */
703 if ( $descUrl && $this->mPage
->getId() == 0 ) {
704 $out->setCanonicalUrl( $descUrl );
707 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
708 $repo = $this->mPage
->getFile()->getRepo()->getDisplayName();
712 $this->getContext()->msg( 'sharedupload-desc-here' )->plain() !== '-'
714 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-here', $repo, $descUrl ] );
715 } elseif ( $descUrl &&
716 $this->getContext()->msg( 'sharedupload-desc-there' )->plain() !== '-'
718 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-there', $repo, $descUrl ] );
720 $out->wrapWikiMsg( $wrap, [ 'sharedupload', $repo ], ''/*BACKCOMPAT*/ );
724 $this->mExtraDescription
= $descText;
728 public function getUploadUrl() {
730 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
731 return $uploadTitle->getFullURL( [
732 'wpDestFile' => $this->mPage
->getFile()->getName(),
738 * Print out the various links at the bottom of the image page, e.g. reupload,
739 * external editing (and instructions link) etc.
741 protected function uploadLinksBox() {
742 global $wgEnableUploads;
744 if ( !$wgEnableUploads ) {
749 if ( !$this->mPage
->getFile()->isLocal() ) {
753 $out = $this->getContext()->getOutput();
754 $out->addHTML( "<ul>\n" );
756 # "Upload a new version of this file" link
757 $canUpload = $this->getTitle()->quickUserCan( 'upload', $this->getContext()->getUser() );
758 if ( $canUpload && UploadBase
::userCanReUpload(
759 $this->getContext()->getUser(),
760 $this->mPage
->getFile() )
762 $ulink = Linker
::makeExternalLink(
763 $this->getUploadUrl(),
764 $this->getContext()->msg( 'uploadnewversion-linktext' )->text()
766 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\">"
767 . "<div class=\"plainlinks\">{$ulink}</div></li>\n" );
769 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">"
770 . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
773 $out->addHTML( "</ul>\n" );
779 protected function closeShowImage() {
783 * If the page we've just displayed is in the "Image" namespace,
784 * we follow it with an upload history of the image and its usage.
786 protected function imageHistory() {
788 $out = $this->getContext()->getOutput();
789 $pager = new ImageHistoryPseudoPager( $this );
790 $out->addHTML( $pager->getBody() );
791 $out->preventClickjacking( $pager->getPreventClickjacking() );
793 $this->mPage
->getFile()->resetHistory(); // free db resources
795 # Exist check because we don't want to show this on pages where an image
796 # doesn't exist along with the noimage message, that would suck. -ævar
797 if ( $this->mPage
->getFile()->exists() ) {
798 $this->uploadLinksBox();
803 * @param string $target
805 * @return ResultWrapper
807 protected function queryImageLinks( $target, $limit ) {
808 $dbr = wfGetDB( DB_REPLICA
);
811 [ 'imagelinks', 'page' ],
812 [ 'page_namespace', 'page_title', 'il_to' ],
813 [ 'il_to' => $target, 'il_from = page_id' ],
815 [ 'LIMIT' => $limit +
1, 'ORDER BY' => 'il_from', ]
819 protected function imageLinks() {
822 $out = $this->getContext()->getOutput();
826 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE
) as $redir ) {
827 $redirects[$redir->getDBkey()] = [];
829 'page_namespace' => NS_FILE
,
830 'page_title' => $redir->getDBkey(),
834 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit +
1 );
835 foreach ( $res as $row ) {
838 $count = count( $rows );
840 $hasMore = $count > $limit;
841 if ( !$hasMore && count( $redirects ) ) {
842 $res = $this->queryImageLinks( array_keys( $redirects ),
843 $limit - count( $rows ) +
1 );
844 foreach ( $res as $row ) {
845 $redirects[$row->il_to
][] = $row;
848 $hasMore = ( $res->numRows() +
count( $rows ) ) > $limit;
853 Html
::rawElement( 'div',
854 [ 'id' => 'mw-imagepage-nolinkstoimage' ], "\n$1\n" ),
860 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
862 $out->addWikiMsg( 'linkstoimage', $count );
864 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
865 $out->addWikiMsg( 'linkstoimage-more',
866 $this->getContext()->getLanguage()->formatNum( $limit ),
867 $this->getTitle()->getPrefixedDBkey()
872 Html
::openElement( 'ul',
873 [ 'class' => 'mw-imagepage-linkstoimage' ] ) . "\n"
877 // Sort the list by namespace:title
878 usort( $rows, [ $this, 'compare' ] );
880 // Create links for every element
882 foreach ( $rows as $element ) {
884 if ( $currentCount > $limit ) {
889 # Add a redirect=no to make redirect pages reachable
890 if ( isset( $redirects[$element->page_title
] ) ) {
891 $query['redirect'] = 'no';
893 $link = Linker
::linkKnown(
894 Title
::makeTitle( $element->page_namespace
, $element->page_title
),
897 if ( !isset( $redirects[$element->page_title
] ) ) {
900 } elseif ( count( $redirects[$element->page_title
] ) === 0 ) {
901 # Redirect without usages
902 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )
903 ->rawParams( $link, '' )
906 # Redirect with usages
908 foreach ( $redirects[$element->page_title
] as $row ) {
910 if ( $currentCount > $limit ) {
914 $link2 = Linker
::linkKnown( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
915 $li .= Html
::rawElement(
917 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
],
922 $ul = Html
::rawElement(
924 [ 'class' => 'mw-imagepage-redirectstofile' ],
927 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
928 $link, $ul )->parse();
930 $out->addHTML( Html
::rawElement(
932 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
],
938 $out->addHTML( Html
::closeElement( 'ul' ) . "\n" );
941 // Add a links to [[Special:Whatlinkshere]]
942 if ( $count > $limit ) {
943 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
945 $out->addHTML( Html
::closeElement( 'div' ) . "\n" );
948 protected function imageDupes() {
950 $out = $this->getContext()->getOutput();
952 $dupes = $this->mPage
->getDuplicates();
953 if ( count( $dupes ) == 0 ) {
957 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
958 $out->addWikiMsg( 'duplicatesoffile',
959 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
961 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
966 foreach ( $dupes as $file ) {
968 if ( $file->isLocal() ) {
969 $link = Linker
::linkKnown( $file->getTitle() );
971 $link = Linker
::makeExternalLink( $file->getDescriptionUrl(),
972 $file->getTitle()->getPrefixedText() );
973 $fromSrc = $this->getContext()->msg(
975 $file->getRepo()->getDisplayName()
978 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
980 $out->addHTML( "</ul></div>\n" );
984 * Delete the file, or an earlier version of it
986 public function delete() {
987 $file = $this->mPage
->getFile();
988 if ( !$file->exists() ||
!$file->isLocal() ||
$file->getRedirected() ) {
989 // Standard article deletion
994 $deleter = new FileDeleteForm( $file );
999 * Display an error with a wikitext description
1001 * @param string $description
1003 function showError( $description ) {
1004 $out = $this->getContext()->getOutput();
1005 $out->setPageTitle( $this->getContext()->msg( 'internalerror' ) );
1006 $out->setRobotPolicy( 'noindex,nofollow' );
1007 $out->setArticleRelated( false );
1008 $out->enableClientCache( false );
1009 $out->addWikiTextAsInterface( $description );
1013 * Callback for usort() to do link sorts by (namespace, title)
1014 * Function copied from Title::compare()
1016 * @param object $a Object page to compare with
1017 * @param object $b Object page to compare with
1018 * @return int Result of string comparison, or namespace comparison
1020 protected function compare( $a, $b ) {
1021 return $a->page_namespace
<=> $b->page_namespace
1022 ?
: strcmp( $a->page_title
, $b->page_title
);
1026 * Returns the corresponding $wgImageLimits entry for the selected user option
1029 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
1033 public function getImageLimitsFromOption( $user, $optionName ) {
1034 global $wgImageLimits;
1036 $option = $user->getIntOption( $optionName );
1037 if ( !isset( $wgImageLimits[$option] ) ) {
1038 $option = User
::getDefaultOption( $optionName );
1041 // The user offset might still be incorrect, specially if
1042 // $wgImageLimits got changed (see T10858).
1043 if ( !isset( $wgImageLimits[$option] ) ) {
1044 // Default to the first offset in $wgImageLimits
1048 // if nothing is set, fallback to a hardcoded default
1049 return $wgImageLimits[$option] ??
[ 800, 600 ];
1053 * Output a drop-down box for language options for the file
1055 * @param array $langChoices Array of string language codes
1056 * @param string $renderLang Language code for the language we want the file to rendered in.
1057 * @return string HTML to insert underneath image.
1059 protected function doRenderLangOpt( array $langChoices, $renderLang ) {
1063 $matchedRenderLang = $this->displayImg
->getMatchedLanguage( $renderLang );
1065 foreach ( $langChoices as $lang ) {
1066 $opts .= $this->createXmlOptionStringForLanguage(
1068 $matchedRenderLang === $lang
1072 // Allow for the default case in an svg <switch> that is displayed if no
1073 // systemLanguage attribute matches
1076 $this->getContext()->msg( 'img-lang-default' )->text(),
1078 is_null( $matchedRenderLang )
1081 $select = Html
::rawElement(
1083 [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1086 $submit = Xml
::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1088 $formContents = $this->getContext()->msg( 'img-lang-info' )
1089 ->rawParams( $select, $submit )
1091 $formContents .= Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1093 $langSelectLine = Html
::rawElement( 'div', [ 'id' => 'mw-imglangselector-line' ],
1094 Html
::rawElement( 'form', [ 'action' => $wgScript ], $formContents )
1096 return $langSelectLine;
1100 * @param string $lang
1101 * @param bool $selected
1104 private function createXmlOptionStringForLanguage( $lang, $selected ) {
1105 $code = LanguageCode
::bcp47( $lang );
1106 $name = Language
::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1107 if ( $name !== '' ) {
1108 $display = $this->getContext()->msg( 'img-lang-opt', $code, $name )->text();
1121 * Get the width and height to display image at.
1123 * @note This method assumes that it is only called if one
1124 * of the dimensions are bigger than the max, or if the
1125 * image is vectorized.
1127 * @param int $maxWidth Max width to display at
1128 * @param int $maxHeight Max height to display at
1129 * @param int $width Actual width of the image
1130 * @param int $height Actual height of the image
1131 * @throws MWException
1132 * @return array Array (width, height)
1134 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1135 if ( !$maxWidth ||
!$maxHeight ) {
1136 // should never happen
1137 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1140 if ( !$width ||
!$height ) {
1144 # Calculate the thumbnail size.
1145 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1146 // Vectorized image, do nothing.
1147 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1148 # The limiting factor is the width, not the height.
1149 $height = round( $height * $maxWidth / $width );
1151 # Note that $height <= $maxHeight now.
1153 $newwidth = floor( $width * $maxHeight / $height );
1154 $height = round( $height * $newwidth / $width );
1156 # Note that $height <= $maxHeight now, but might not be identical
1157 # because of rounding.
1159 return [ $width, $height ];
1163 * Get alternative thumbnail sizes.
1165 * @note This will only list several alternatives if thumbnails are rendered on 404
1166 * @param int $origWidth Actual width of image
1167 * @param int $origHeight Actual height of image
1168 * @return array An array of [width, height] pairs.
1170 protected function getThumbSizes( $origWidth, $origHeight ) {
1171 global $wgImageLimits;
1172 if ( $this->displayImg
->getRepo()->canTransformVia404() ) {
1173 $thumbSizes = $wgImageLimits;
1174 // Also include the full sized resolution in the list, so
1175 // that users know they can get it. This will link to the
1176 // original file asset if mustRender() === false. In the case
1177 // that we mustRender, some users have indicated that they would
1178 // find it useful to have the full size image in the rendered
1180 $thumbSizes[] = [ $origWidth, $origHeight ];
1182 # Creating thumb links triggers thumbnail generation.
1183 # Just generate the thumb for the current users prefs.
1185 $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' )
1187 if ( !$this->displayImg
->mustRender() ) {
1188 // We can safely include a link to the "full-size" preview,
1189 // without actually rendering.
1190 $thumbSizes[] = [ $origWidth, $origHeight ];
1197 * @see WikiFilePage::getFile
1200 public function getFile() {
1201 return $this->mPage
->getFile();
1205 * @see WikiFilePage::isLocal
1208 public function isLocal() {
1209 return $this->mPage
->isLocal();
1213 * @see WikiFilePage::getDuplicates
1214 * @return array|null
1216 public function getDuplicates() {
1217 return $this->mPage
->getDuplicates();
1221 * @see WikiFilePage::getForeignCategories
1222 * @return TitleArray|Title[]
1224 public function getForeignCategories() {
1225 return $this->mPage
->getForeignCategories();