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();
90 * Handler for action=render
91 * Include body text only; none of the image extras
93 public function render() {
94 $this->getContext()->getOutput()->setArticleBodyOnly( true );
98 public function view() {
101 $out = $this->getContext()->getOutput();
102 $request = $this->getContext()->getRequest();
103 $diff = $request->getVal( 'diff' );
104 $diffOnly = $request->getBool(
106 $this->getContext()->getUser()->getOption( 'diffonly' )
109 if ( $this->getTitle()->getNamespace() != NS_FILE ||
( $diff !== null && $diffOnly ) ) {
116 if ( $this->getTitle()->getNamespace() == NS_FILE
&& $this->mPage
->getFile()->getRedirected() ) {
117 if ( $this->getTitle()->getDBkey() == $this->mPage
->getFile()->getName() ||
$diff !== null ) {
118 $request->setVal( 'diffonly', 'true' );
125 if ( $wgShowEXIF && $this->displayImg
->exists() ) {
126 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
127 $formattedMetadata = $this->displayImg
->formatMetadata( $this->getContext() );
128 $showmeta = $formattedMetadata !== false;
133 if ( !$diff && $this->displayImg
->exists() ) {
134 $out->addHTML( $this->showTOC( $showmeta ) );
138 $this->openShowImage();
141 # No need to display noarticletext, we use our own message, output in openShowImage()
142 if ( $this->mPage
->getId() ) {
143 # NS_FILE is in the user language, but this section (the actual wikitext)
144 # should be in page content language
145 $pageLang = $this->getTitle()->getPageViewLanguage();
146 $out->addHTML( Xml
::openElement( 'div', [ 'id' => 'mw-imagepage-content',
147 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
148 'class' => 'mw-content-' . $pageLang->getDir() ] ) );
152 $out->addHTML( Xml
::closeElement( 'div' ) );
154 # Just need to set the right headers
155 $out->setArticleFlag( true );
156 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
157 $this->mPage
->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
160 # Show shared description, if needed
161 if ( $this->mExtraDescription
) {
162 $fol = $this->getContext()->msg( 'shareddescriptionfollows' );
163 if ( !$fol->isDisabled() ) {
164 $out->addWikiText( $fol->plain() );
166 $out->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription
. "</div>\n" );
169 $this->closeShowImage();
170 $this->imageHistory();
171 // TODO: Cleanup the following
173 $out->addHTML( Xml
::element( 'h2',
174 [ 'id' => 'filelinks' ],
175 $this->getContext()->msg( 'imagelinks' )->text() ) . "\n" );
177 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
178 # Yet we return metadata about the target. Definitely an issue in the FileRepo
181 # Allow extensions to add something after the image links
183 Hooks
::run( 'ImagePageAfterImageLinks', [ $this, &$html ] );
185 $out->addHTML( $html );
189 $out->addHTML( Xml
::element(
191 [ 'id' => 'metadata' ],
192 $this->getContext()->msg( 'metadata' )->text() ) . "\n" );
193 $out->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
194 $out->addModules( [ 'mediawiki.action.view.metadata' ] );
197 // Add remote Filepage.css
198 if ( !$this->repo
->isLocal() ) {
199 $css = $this->repo
->getDescriptionStylesheetUrl();
201 $out->addStyle( $css );
205 $out->addModuleStyles( [
206 'filepage', // always show the local local Filepage.css, T31277
207 'mediawiki.action.view.filepage', // Add MediaWiki styles for a file page
214 public function getDisplayedFile() {
216 return $this->displayImg
;
222 * @param bool $metadata Whether or not to show the metadata link
225 protected function showTOC( $metadata ) {
227 '<li><a href="#file">' . $this->getContext()->msg( 'file-anchor-link' )->escaped() . '</a></li>',
228 '<li><a href="#filehistory">' . $this->getContext()->msg( 'filehist' )->escaped() . '</a></li>',
229 '<li><a href="#filelinks">' . $this->getContext()->msg( 'imagelinks' )->escaped() . '</a></li>',
232 Hooks
::run( 'ImagePageShowTOC', [ $this, &$r ] );
235 $r[] = '<li><a href="#metadata">' .
236 $this->getContext()->msg( 'metadata' )->escaped() .
240 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
244 * Make a table with metadata to be shown in the output page.
246 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
248 * @param array $metadata The array containing the Exif data
249 * @return string The metadata table. This is treated as Wikitext (!)
251 protected function makeMetadataTable( $metadata ) {
252 $r = "<div class=\"mw-imagepage-section-metadata\">";
253 $r .= $this->getContext()->msg( 'metadata-help' )->plain();
254 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
255 foreach ( $metadata as $type => $stuff ) {
256 foreach ( $stuff as $v ) {
257 # @todo FIXME: Why is this using escapeId for a class?!
258 $class = Sanitizer
::escapeId( $v['id'] );
259 if ( $type == 'collapsed' ) {
260 // Handled by mediawiki.action.view.metadata module.
261 $class .= ' collapsable';
263 $r .= "<tr class=\"$class\">\n";
264 $r .= "<th>{$v['name']}</th>\n";
265 $r .= "<td>{$v['value']}</td>\n</tr>";
268 $r .= "</table>\n</div>\n";
273 * Overloading Article's getContentObject method.
275 * Omit noarticletext if sharedupload; text will be fetched from the
276 * shared upload server if possible.
279 public function getContentObject() {
281 if ( $this->mPage
->getFile() && !$this->mPage
->getFile()->isLocal() && 0 == $this->getId() ) {
284 return parent
::getContentObject();
287 protected function openShowImage() {
288 global $wgEnableUploads, $wgSend404Code, $wgSVGMaxSize;
291 $out = $this->getContext()->getOutput();
292 $user = $this->getContext()->getUser();
293 $lang = $this->getContext()->getLanguage();
294 $dirmark = $lang->getDirMarkEntity();
295 $request = $this->getContext()->getRequest();
297 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
299 $maxHeight = $max[1];
301 if ( $this->displayImg
->exists() ) {
303 $page = $request->getIntOrNull( 'page' );
304 if ( is_null( $page ) ) {
308 $params = [ 'page' => $page ];
311 $renderLang = $request->getVal( 'lang' );
312 if ( !is_null( $renderLang ) ) {
313 $handler = $this->displayImg
->getHandler();
314 if ( $handler && $handler->validateParam( 'lang', $renderLang ) ) {
315 $params['lang'] = $renderLang;
321 $width_orig = $this->displayImg
->getWidth( $page );
322 $width = $width_orig;
323 $height_orig = $this->displayImg
->getHeight( $page );
324 $height = $height_orig;
326 $filename = wfEscapeWikiText( $this->displayImg
->getName() );
327 $linktext = $filename;
329 // Avoid PHP 7.1 warning from passing $this by reference
332 Hooks
::run( 'ImageOpenShowImageInlineBefore', [ &$imagePage, &$out ] );
334 if ( $this->displayImg
->allowInlineDisplay() ) {
336 # "Download high res version" link below the image
337 # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
338 # Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
339 # We'll show a thumbnail of this image
340 if ( $width > $maxWidth ||
$height > $maxHeight ||
$this->displayImg
->isVectorized() ) {
341 list( $width, $height ) = $this->getDisplayWidthHeight(
342 $maxWidth, $maxHeight, $width, $height
344 $linktext = $this->getContext()->msg( 'show-big-image' )->escaped();
346 $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
347 # Generate thumbnails or thumbnail links as needed...
349 foreach ( $thumbSizes as $size ) {
350 // We include a thumbnail size in the list, if it is
351 // less than or equal to the original size of the image
352 // asset ($width_orig/$height_orig). We also exclude
353 // the current thumbnail's size ($width/$height)
354 // since that is added to the message separately, so
355 // it can be denoted as the current size being shown.
356 // Vectorized images are limited by $wgSVGMaxSize big,
357 // so all thumbs less than or equal that are shown.
358 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
359 ||
( $this->displayImg
->isVectorized()
360 && max( $size[0], $size[1] ) <= $wgSVGMaxSize )
362 && $size[0] != $width && $size[1] != $height
364 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
366 $otherSizes[] = $sizeLink;
370 $otherSizes = array_unique( $otherSizes );
372 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
373 $msgsmall = $this->getThumbPrevText( $params, $sizeLinkBigImagePreview );
374 if ( count( $otherSizes ) ) {
378 [ 'class' => 'mw-filepage-other-resolutions' ],
379 $this->getContext()->msg( 'show-big-image-other' )
380 ->rawParams( $lang->pipeList( $otherSizes ) )
381 ->params( count( $otherSizes ) )
385 } elseif ( $width == 0 && $height == 0 ) {
386 # Some sort of audio file that doesn't have dimensions
387 # Don't output a no hi res message for such a file
390 # Image is small enough to show full size on image page
391 $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
394 $params['width'] = $width;
395 $params['height'] = $height;
396 $thumbnail = $this->displayImg
->transform( $params );
397 Linker
::processResponsiveImages( $this->displayImg
, $thumbnail, $params );
399 $anchorclose = Html
::rawElement(
401 [ 'class' => 'mw-filepage-resolutioninfo' ],
405 $isMulti = $this->displayImg
->isMultipage() && $this->displayImg
->pageCount() > 1;
407 $out->addModules( 'mediawiki.page.image.pagination' );
408 $out->addHTML( '<table class="multipageimage"><tr><td>' );
413 'alt' => $this->displayImg
->getTitle()->getPrefixedText(),
416 $out->addHTML( '<div class="fullImageLink" id="file">' .
417 $thumbnail->toHtml( $options ) .
418 $anchorclose . "</div>\n" );
422 $count = $this->displayImg
->pageCount();
425 $label = $this->getContext()->msg( 'imgmultipageprev' )->text();
426 // on the client side, this link is generated in ajaxifyPageNavigation()
427 // in the mediawiki.page.image.pagination module
428 $link = Linker
::linkKnown(
432 [ 'page' => $page - 1 ]
434 $thumb1 = Linker
::makeThumbLinkObj(
440 [ 'page' => $page - 1 ]
446 if ( $page < $count ) {
447 $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
448 $link = Linker
::linkKnown(
452 [ 'page' => $page +
1 ]
454 $thumb2 = Linker
::makeThumbLinkObj(
460 [ 'page' => $page +
1 ]
469 'name' => 'pageselector',
470 'action' => $wgScript,
473 for ( $i = 1; $i <= $count; $i++
) {
474 $options[] = Xml
::option( $lang->formatNum( $i ), $i, $i == $page );
476 $select = Xml
::tags( 'select',
477 [ 'id' => 'pageselector', 'name' => 'page' ],
478 implode( "\n", $options ) );
481 '</td><td><div class="multipageimagenavbox">' .
482 Xml
::openElement( 'form', $formParams ) .
483 Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
484 $this->getContext()->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
485 $this->getContext()->msg( 'word-separator' )->escaped() .
486 Xml
::submitButton( $this->getContext()->msg( 'imgmultigo' )->text() ) .
487 Xml
::closeElement( 'form' ) .
488 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
491 } elseif ( $this->displayImg
->isSafeFile() ) {
492 # if direct link is allowed but it's not a renderable image, show an icon.
493 $icon = $this->displayImg
->iconThumb();
495 $out->addHTML( '<div class="fullImageLink" id="file">' .
496 $icon->toHtml( [ 'file-link' => true ] ) .
500 $longDesc = $this->getContext()->msg( 'parentheses', $this->displayImg
->getLongDesc() )->text();
502 $handler = $this->displayImg
->getHandler();
504 // If this is a filetype with potential issues, warn the user.
506 $warningConfig = $handler->getWarningConfig( $this->displayImg
);
508 if ( $warningConfig !== null ) {
509 // The warning will be displayed via CSS and JavaScript.
510 // We just need to tell the client side what message to use.
511 $output = $this->getContext()->getOutput();
512 $output->addJsConfigVars( 'wgFileWarning', $warningConfig );
513 $output->addModules( $warningConfig['module'] );
514 $output->addModules( 'mediawiki.filewarning' );
518 $medialink = "[[Media:$filename|$linktext]]";
520 if ( !$this->displayImg
->isSafeFile() ) {
521 $warning = $this->getContext()->msg( 'mediawarning' )->plain();
522 // dirmark is needed here to separate the file name, which
523 // most likely ends in Latin characters, from the description,
524 // which may begin with the file type. In RTL environment
525 // this will get messy.
526 // The dirmark, however, must not be immediately adjacent
527 // to the filename, because it can get copied with it.
529 // @codingStandardsIgnoreStart Ignore long line
530 $out->addWikiText( <<<EOT
531 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
532 <div class="mediaWarning">$warning</div>
535 // @codingStandardsIgnoreEnd
537 $out->addWikiText( <<<EOT
538 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
544 $renderLangOptions = $this->displayImg
->getAvailableLanguages();
545 if ( count( $renderLangOptions ) >= 1 ) {
546 $currentLanguage = $renderLang;
547 $defaultLang = $this->displayImg
->getDefaultRenderLanguage();
548 if ( is_null( $currentLanguage ) ) {
549 $currentLanguage = $defaultLang;
551 $out->addHTML( $this->doRenderLangOpt( $renderLangOptions, $currentLanguage, $defaultLang ) );
554 // Add cannot animate thumbnail warning
555 if ( !$this->displayImg
->canAnimateThumbIfAppropriate() ) {
556 // Include the extension so wiki admins can
557 // customize it on a per file-type basis
558 // (aka say things like use format X instead).
559 // additionally have a specific message for
560 // file-no-thumb-animation-gif
561 $ext = $this->displayImg
->getExtension();
562 $noAnimMesg = wfMessageFallback(
563 'file-no-thumb-animation-' . $ext,
564 'file-no-thumb-animation'
567 $out->addWikiText( <<<EOT
568 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
573 if ( !$this->displayImg
->isLocal() ) {
574 $this->printSharedImageText();
577 # Image does not exist
578 if ( !$this->getId() ) {
579 $dbr = wfGetDB( DB_REPLICA
);
581 # No article exists either
582 # Show deletion log to be consistent with normal articles
583 LogEventsList
::showLogExtract(
585 [ 'delete', 'move' ],
586 $this->getTitle()->getPrefixedText(),
589 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
590 'showIfEmpty' => false,
591 'msgKey' => [ 'moveddeleted-notice' ]
596 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
597 // Only show an upload link if the user can upload
598 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
600 'filepage-nofile-link',
601 $uploadTitle->getFullURL( [ 'wpDestFile' => $this->mPage
->getFile()->getName() ] )
604 $nofile = 'filepage-nofile';
606 // Note, if there is an image description page, but
607 // no image, then this setRobotPolicy is overridden
608 // by Article::View().
609 $out->setRobotPolicy( 'noindex,nofollow' );
610 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
611 if ( !$this->getId() && $wgSend404Code ) {
612 // If there is no image, no shared image, and no description page,
613 // output a 404, to be consistent with Article::showMissingArticle.
614 $request->response()->statusHeader( 404 );
617 $out->setFileVersion( $this->displayImg
);
621 * Make the text under the image to say what size preview
623 * @param $params array parameters for thumbnail
624 * @param $sizeLinkBigImagePreview HTML for the current size
625 * @return string HTML output
627 private function getThumbPrevText( $params, $sizeLinkBigImagePreview ) {
628 if ( $sizeLinkBigImagePreview ) {
629 // Show a different message of preview is different format from original.
630 $previewTypeDiffers = false;
631 $origExt = $thumbExt = $this->displayImg
->getExtension();
632 if ( $this->displayImg
->getHandler() ) {
633 $origMime = $this->displayImg
->getMimeType();
634 $typeParams = $params;
635 $this->displayImg
->getHandler()->normaliseParams( $this->displayImg
, $typeParams );
636 list( $thumbExt, $thumbMime ) = $this->displayImg
->getHandler()->getThumbType(
637 $origExt, $origMime, $typeParams );
638 if ( $thumbMime !== $origMime ) {
639 $previewTypeDiffers = true;
642 if ( $previewTypeDiffers ) {
643 return $this->getContext()->msg( 'show-big-image-preview-differ' )->
644 rawParams( $sizeLinkBigImagePreview )->
645 params( strtoupper( $origExt ) )->
646 params( strtoupper( $thumbExt ) )->
649 return $this->getContext()->msg( 'show-big-image-preview' )->
650 rawParams( $sizeLinkBigImagePreview )->
659 * Creates an thumbnail of specified size and returns an HTML link to it
660 * @param array $params Scaler parameters
665 private function makeSizeLink( $params, $width, $height ) {
666 $params['width'] = $width;
667 $params['height'] = $height;
668 $thumbnail = $this->displayImg
->transform( $params );
669 if ( $thumbnail && !$thumbnail->isError() ) {
670 return Html
::rawElement( 'a', [
671 'href' => $thumbnail->getUrl(),
672 'class' => 'mw-thumbnail-link'
673 ], $this->getContext()->msg( 'show-big-image-size' )->numParams(
674 $thumbnail->getWidth(), $thumbnail->getHeight()
682 * Show a notice that the file is from a shared repository
684 protected function printSharedImageText() {
685 $out = $this->getContext()->getOutput();
688 $descUrl = $this->mPage
->getFile()->getDescriptionUrl();
689 $descText = $this->mPage
->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
691 /* Add canonical to head if there is no local page for this shared file */
692 if ( $descUrl && $this->mPage
->getId() == 0 ) {
693 $out->setCanonicalUrl( $descUrl );
696 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
697 $repo = $this->mPage
->getFile()->getRepo()->getDisplayName();
701 $this->getContext()->msg( 'sharedupload-desc-here' )->plain() !== '-'
703 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-here', $repo, $descUrl ] );
704 } elseif ( $descUrl &&
705 $this->getContext()->msg( 'sharedupload-desc-there' )->plain() !== '-'
707 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-there', $repo, $descUrl ] );
709 $out->wrapWikiMsg( $wrap, [ 'sharedupload', $repo ], ''/*BACKCOMPAT*/ );
713 $this->mExtraDescription
= $descText;
717 public function getUploadUrl() {
719 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
720 return $uploadTitle->getFullURL( [
721 'wpDestFile' => $this->mPage
->getFile()->getName(),
727 * Print out the various links at the bottom of the image page, e.g. reupload,
728 * external editing (and instructions link) etc.
730 protected function uploadLinksBox() {
731 global $wgEnableUploads;
733 if ( !$wgEnableUploads ) {
738 if ( !$this->mPage
->getFile()->isLocal() ) {
742 $out = $this->getContext()->getOutput();
743 $out->addHTML( "<ul>\n" );
745 # "Upload a new version of this file" link
746 $canUpload = $this->getTitle()->quickUserCan( 'upload', $this->getContext()->getUser() );
747 if ( $canUpload && UploadBase
::userCanReUpload(
748 $this->getContext()->getUser(),
749 $this->mPage
->getFile() )
751 $ulink = Linker
::makeExternalLink(
752 $this->getUploadUrl(),
753 $this->getContext()->msg( 'uploadnewversion-linktext' )->text()
755 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\">"
756 . "<div class=\"plainlinks\">{$ulink}</div></li>\n" );
758 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">"
759 . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
762 $out->addHTML( "</ul>\n" );
768 protected function closeShowImage() {
772 * If the page we've just displayed is in the "Image" namespace,
773 * we follow it with an upload history of the image and its usage.
775 protected function imageHistory() {
777 $out = $this->getContext()->getOutput();
778 $pager = new ImageHistoryPseudoPager( $this );
779 $out->addHTML( $pager->getBody() );
780 $out->preventClickjacking( $pager->getPreventClickjacking() );
782 $this->mPage
->getFile()->resetHistory(); // free db resources
784 # Exist check because we don't want to show this on pages where an image
785 # doesn't exist along with the noimage message, that would suck. -ævar
786 if ( $this->mPage
->getFile()->exists() ) {
787 $this->uploadLinksBox();
792 * @param string $target
794 * @return ResultWrapper
796 protected function queryImageLinks( $target, $limit ) {
797 $dbr = wfGetDB( DB_REPLICA
);
800 [ 'imagelinks', 'page' ],
801 [ 'page_namespace', 'page_title', 'il_to' ],
802 [ 'il_to' => $target, 'il_from = page_id' ],
804 [ 'LIMIT' => $limit +
1, 'ORDER BY' => 'il_from', ]
808 protected function imageLinks() {
811 $out = $this->getContext()->getOutput();
815 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE
) as $redir ) {
816 $redirects[$redir->getDBkey()] = [];
818 'page_namespace' => NS_FILE
,
819 'page_title' => $redir->getDBkey(),
823 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit +
1 );
824 foreach ( $res as $row ) {
827 $count = count( $rows );
829 $hasMore = $count > $limit;
830 if ( !$hasMore && count( $redirects ) ) {
831 $res = $this->queryImageLinks( array_keys( $redirects ),
832 $limit - count( $rows ) +
1 );
833 foreach ( $res as $row ) {
834 $redirects[$row->il_to
][] = $row;
837 $hasMore = ( $res->numRows() +
count( $rows ) ) > $limit;
842 Html
::rawElement( 'div',
843 [ 'id' => 'mw-imagepage-nolinkstoimage' ], "\n$1\n" ),
849 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
851 $out->addWikiMsg( 'linkstoimage', $count );
853 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
854 $out->addWikiMsg( 'linkstoimage-more',
855 $this->getContext()->getLanguage()->formatNum( $limit ),
856 $this->getTitle()->getPrefixedDBkey()
861 Html
::openElement( 'ul',
862 [ 'class' => 'mw-imagepage-linkstoimage' ] ) . "\n"
866 // Sort the list by namespace:title
867 usort( $rows, [ $this, 'compare' ] );
869 // Create links for every element
871 foreach ( $rows as $element ) {
873 if ( $currentCount > $limit ) {
878 # Add a redirect=no to make redirect pages reachable
879 if ( isset( $redirects[$element->page_title
] ) ) {
880 $query['redirect'] = 'no';
882 $link = Linker
::linkKnown(
883 Title
::makeTitle( $element->page_namespace
, $element->page_title
),
886 if ( !isset( $redirects[$element->page_title
] ) ) {
889 } elseif ( count( $redirects[$element->page_title
] ) === 0 ) {
890 # Redirect without usages
891 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )
892 ->rawParams( $link, '' )
895 # Redirect with usages
897 foreach ( $redirects[$element->page_title
] as $row ) {
899 if ( $currentCount > $limit ) {
903 $link2 = Linker
::linkKnown( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
904 $li .= Html
::rawElement(
906 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
],
911 $ul = Html
::rawElement(
913 [ 'class' => 'mw-imagepage-redirectstofile' ],
916 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
917 $link, $ul )->parse();
919 $out->addHTML( Html
::rawElement(
921 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
],
927 $out->addHTML( Html
::closeElement( 'ul' ) . "\n" );
930 // Add a links to [[Special:Whatlinkshere]]
931 if ( $count > $limit ) {
932 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
934 $out->addHTML( Html
::closeElement( 'div' ) . "\n" );
937 protected function imageDupes() {
939 $out = $this->getContext()->getOutput();
941 $dupes = $this->mPage
->getDuplicates();
942 if ( count( $dupes ) == 0 ) {
946 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
947 $out->addWikiMsg( 'duplicatesoffile',
948 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
950 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
955 foreach ( $dupes as $file ) {
957 if ( $file->isLocal() ) {
958 $link = Linker
::linkKnown( $file->getTitle() );
960 $link = Linker
::makeExternalLink( $file->getDescriptionUrl(),
961 $file->getTitle()->getPrefixedText() );
962 $fromSrc = $this->getContext()->msg(
964 $file->getRepo()->getDisplayName()
967 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
969 $out->addHTML( "</ul></div>\n" );
973 * Delete the file, or an earlier version of it
975 public function delete() {
976 $file = $this->mPage
->getFile();
977 if ( !$file->exists() ||
!$file->isLocal() ||
$file->getRedirected() ) {
978 // Standard article deletion
983 $deleter = new FileDeleteForm( $file );
988 * Display an error with a wikitext description
990 * @param string $description
992 function showError( $description ) {
993 $out = $this->getContext()->getOutput();
994 $out->setPageTitle( $this->getContext()->msg( 'internalerror' ) );
995 $out->setRobotPolicy( 'noindex,nofollow' );
996 $out->setArticleRelated( false );
997 $out->enableClientCache( false );
998 $out->addWikiText( $description );
1002 * Callback for usort() to do link sorts by (namespace, title)
1003 * Function copied from Title::compare()
1005 * @param object $a Object page to compare with
1006 * @param object $b Object page to compare with
1007 * @return int Result of string comparison, or namespace comparison
1009 protected function compare( $a, $b ) {
1010 if ( $a->page_namespace
== $b->page_namespace
) {
1011 return strcmp( $a->page_title
, $b->page_title
);
1013 return $a->page_namespace
- $b->page_namespace
;
1018 * Returns the corresponding $wgImageLimits entry for the selected user option
1021 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
1025 public function getImageLimitsFromOption( $user, $optionName ) {
1026 global $wgImageLimits;
1028 $option = $user->getIntOption( $optionName );
1029 if ( !isset( $wgImageLimits[$option] ) ) {
1030 $option = User
::getDefaultOption( $optionName );
1033 // The user offset might still be incorrect, specially if
1034 // $wgImageLimits got changed (see bug #8858).
1035 if ( !isset( $wgImageLimits[$option] ) ) {
1036 // Default to the first offset in $wgImageLimits
1040 return isset( $wgImageLimits[$option] )
1041 ?
$wgImageLimits[$option]
1042 : [ 800, 600 ]; // if nothing is set, fallback to a hardcoded default
1046 * Output a drop-down box for language options for the file
1048 * @param array $langChoices Array of string language codes
1049 * @param string $curLang Language code file is being viewed in.
1050 * @param string $defaultLang Language code that image is rendered in by default
1051 * @return string HTML to insert underneath image.
1053 protected function doRenderLangOpt( array $langChoices, $curLang, $defaultLang ) {
1055 sort( $langChoices );
1056 $curLang = wfBCP47( $curLang );
1057 $defaultLang = wfBCP47( $defaultLang );
1059 $haveCurrentLang = false;
1060 $haveDefaultLang = false;
1062 // We make a list of all the language choices in the file.
1063 // Additionally if the default language to render this file
1064 // is not included as being in this file (for example, in svgs
1065 // usually the fallback content is the english content) also
1066 // include a choice for that. Last of all, if we're viewing
1067 // the file in a language not on the list, add it as a choice.
1068 foreach ( $langChoices as $lang ) {
1069 $code = wfBCP47( $lang );
1070 $name = Language
::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1071 if ( $name !== '' ) {
1072 $display = $this->getContext()->msg( 'img-lang-opt', $code, $name )->text();
1076 $opts .= "\n" . Xml
::option( $display, $code, $curLang === $code );
1077 if ( $curLang === $code ) {
1078 $haveCurrentLang = true;
1080 if ( $defaultLang === $code ) {
1081 $haveDefaultLang = true;
1084 if ( !$haveDefaultLang ) {
1085 // Its hard to know if the content is really in the default language, or
1086 // if its just unmarked content that could be in any language.
1087 $opts = Xml
::option(
1088 $this->getContext()->msg( 'img-lang-default' )->text(),
1090 $defaultLang === $curLang
1093 if ( !$haveCurrentLang && $defaultLang !== $curLang ) {
1094 $name = Language
::fetchLanguageName( $curLang, $this->getContext()->getLanguage()->getCode() );
1095 if ( $name !== '' ) {
1096 $display = $this->getContext()->msg( 'img-lang-opt', $curLang, $name )->text();
1098 $display = $curLang;
1100 $opts = Xml
::option( $display, $curLang, true ) . $opts;
1103 $select = Html
::rawElement(
1105 [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1108 $submit = Xml
::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1110 $formContents = $this->getContext()->msg( 'img-lang-info' )
1111 ->rawParams( $select, $submit )
1113 $formContents .= Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1115 $langSelectLine = Html
::rawElement( 'div', [ 'id' => 'mw-imglangselector-line' ],
1116 Html
::rawElement( 'form', [ 'action' => $wgScript ], $formContents )
1118 return $langSelectLine;
1122 * Get the width and height to display image at.
1124 * @note This method assumes that it is only called if one
1125 * of the dimensions are bigger than the max, or if the
1126 * image is vectorized.
1128 * @param int $maxWidth Max width to display at
1129 * @param int $maxHeight Max height to display at
1130 * @param int $width Actual width of the image
1131 * @param int $height Actual height of the image
1132 * @throws MWException
1133 * @return array Array (width, height)
1135 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1136 if ( !$maxWidth ||
!$maxHeight ) {
1137 // should never happen
1138 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1141 if ( !$width ||
!$height ) {
1145 # Calculate the thumbnail size.
1146 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1147 // Vectorized image, do nothing.
1148 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1149 # The limiting factor is the width, not the height.
1150 $height = round( $height * $maxWidth / $width );
1152 # Note that $height <= $maxHeight now.
1154 $newwidth = floor( $width * $maxHeight / $height );
1155 $height = round( $height * $newwidth / $width );
1157 # Note that $height <= $maxHeight now, but might not be identical
1158 # because of rounding.
1160 return [ $width, $height ];
1164 * Get alternative thumbnail sizes.
1166 * @note This will only list several alternatives if thumbnails are rendered on 404
1167 * @param int $origWidth Actual width of image
1168 * @param int $origHeight Actual height of image
1169 * @return array An array of [width, height] pairs.
1171 protected function getThumbSizes( $origWidth, $origHeight ) {
1172 global $wgImageLimits;
1173 if ( $this->displayImg
->getRepo()->canTransformVia404() ) {
1174 $thumbSizes = $wgImageLimits;
1175 // Also include the full sized resolution in the list, so
1176 // that users know they can get it. This will link to the
1177 // original file asset if mustRender() === false. In the case
1178 // that we mustRender, some users have indicated that they would
1179 // find it useful to have the full size image in the rendered
1181 $thumbSizes[] = [ $origWidth, $origHeight ];
1183 # Creating thumb links triggers thumbnail generation.
1184 # Just generate the thumb for the current users prefs.
1186 $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' )
1188 if ( !$this->displayImg
->mustRender() ) {
1189 // We can safely include a link to the "full-size" preview,
1190 // without actually rendering.
1191 $thumbSizes[] = [ $origWidth, $origHeight ];
1198 * @see WikiFilePage::getFile
1201 public function getFile() {
1202 return $this->mPage
->getFile();
1206 * @see WikiFilePage::isLocal
1209 public function isLocal() {
1210 return $this->mPage
->isLocal();
1214 * @see WikiFilePage::getDuplicates
1215 * @return array|null
1217 public function getDuplicates() {
1218 return $this->mPage
->getDuplicates();
1222 * @see WikiFilePage::getForeignCategories
1223 * @return TitleArray|Title[]
1225 public function getForeignCategories() {
1226 $this->mPage
->getForeignCategories();