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 // mTitle is the same as the redirect target so ask Article
119 // to perform the redirect for us.
120 $request->setVal( 'diffonly', 'true' );
124 // mTitle is not the same as the redirect target so it is
125 // probably the redirect page itself. Fake the redirect symbol
126 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
127 $out->addHTML( $this->viewRedirect(
128 Title
::makeTitle( NS_FILE
, $this->mPage
->getFile()->getName() ),
129 /* $appendSubtitle */ true,
130 /* $forceKnown */ true )
132 $this->mPage
->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
137 if ( $wgShowEXIF && $this->displayImg
->exists() ) {
138 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
139 $formattedMetadata = $this->displayImg
->formatMetadata( $this->getContext() );
140 $showmeta = $formattedMetadata !== false;
145 if ( !$diff && $this->displayImg
->exists() ) {
146 $out->addHTML( $this->showTOC( $showmeta ) );
150 $this->openShowImage();
153 # No need to display noarticletext, we use our own message, output in openShowImage()
154 if ( $this->mPage
->getId() ) {
155 # NS_FILE is in the user language, but this section (the actual wikitext)
156 # should be in page content language
157 $pageLang = $this->getTitle()->getPageViewLanguage();
158 $out->addHTML( Xml
::openElement( 'div', [ 'id' => 'mw-imagepage-content',
159 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
160 'class' => 'mw-content-' . $pageLang->getDir() ] ) );
164 $out->addHTML( Xml
::closeElement( 'div' ) );
166 # Just need to set the right headers
167 $out->setArticleFlag( true );
168 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
169 $this->mPage
->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
172 # Show shared description, if needed
173 if ( $this->mExtraDescription
) {
174 $fol = $this->getContext()->msg( 'shareddescriptionfollows' );
175 if ( !$fol->isDisabled() ) {
176 $out->addWikiText( $fol->plain() );
178 $out->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription
. "</div>\n" );
181 $this->closeShowImage();
182 $this->imageHistory();
183 // TODO: Cleanup the following
185 $out->addHTML( Xml
::element( 'h2',
186 [ 'id' => 'filelinks' ],
187 $this->getContext()->msg( 'imagelinks' )->text() ) . "\n" );
189 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
190 # Yet we return metadata about the target. Definitely an issue in the FileRepo
193 # Allow extensions to add something after the image links
195 Hooks
::run( 'ImagePageAfterImageLinks', [ $this, &$html ] );
197 $out->addHTML( $html );
201 $out->addHTML( Xml
::element(
203 [ 'id' => 'metadata' ],
204 $this->getContext()->msg( 'metadata' )->text() ) . "\n" );
205 $out->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
206 $out->addModules( [ 'mediawiki.action.view.metadata' ] );
209 // Add remote Filepage.css
210 if ( !$this->repo
->isLocal() ) {
211 $css = $this->repo
->getDescriptionStylesheetUrl();
213 $out->addStyle( $css );
217 $out->addModuleStyles( [
218 'filepage', // always show the local local Filepage.css, T31277
219 'mediawiki.action.view.filepage', // Add MediaWiki styles for a file page
226 public function getDisplayedFile() {
228 return $this->displayImg
;
234 * @param bool $metadata Whether or not to show the metadata link
237 protected function showTOC( $metadata ) {
239 '<li><a href="#file">' . $this->getContext()->msg( 'file-anchor-link' )->escaped() . '</a></li>',
240 '<li><a href="#filehistory">' . $this->getContext()->msg( 'filehist' )->escaped() . '</a></li>',
241 '<li><a href="#filelinks">' . $this->getContext()->msg( 'imagelinks' )->escaped() . '</a></li>',
244 Hooks
::run( 'ImagePageShowTOC', [ $this, &$r ] );
247 $r[] = '<li><a href="#metadata">' .
248 $this->getContext()->msg( 'metadata' )->escaped() .
252 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
256 * Make a table with metadata to be shown in the output page.
258 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
260 * @param array $metadata The array containing the Exif data
261 * @return string The metadata table. This is treated as Wikitext (!)
263 protected function makeMetadataTable( $metadata ) {
264 $r = "<div class=\"mw-imagepage-section-metadata\">";
265 $r .= $this->getContext()->msg( 'metadata-help' )->plain();
266 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
267 foreach ( $metadata as $type => $stuff ) {
268 foreach ( $stuff as $v ) {
269 # @todo FIXME: Why is this using escapeId for a class?!
270 $class = Sanitizer
::escapeId( $v['id'] );
271 if ( $type == 'collapsed' ) {
272 // Handled by mediawiki.action.view.metadata module.
273 $class .= ' collapsable';
275 $r .= "<tr class=\"$class\">\n";
276 $r .= "<th>{$v['name']}</th>\n";
277 $r .= "<td>{$v['value']}</td>\n</tr>";
280 $r .= "</table>\n</div>\n";
285 * Overloading Article's getContentObject method.
287 * Omit noarticletext if sharedupload; text will be fetched from the
288 * shared upload server if possible.
291 public function getContentObject() {
293 if ( $this->mPage
->getFile() && !$this->mPage
->getFile()->isLocal() && 0 == $this->getId() ) {
296 return parent
::getContentObject();
299 protected function openShowImage() {
300 global $wgEnableUploads, $wgSend404Code, $wgSVGMaxSize;
303 $out = $this->getContext()->getOutput();
304 $user = $this->getContext()->getUser();
305 $lang = $this->getContext()->getLanguage();
306 $dirmark = $lang->getDirMarkEntity();
307 $request = $this->getContext()->getRequest();
309 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
311 $maxHeight = $max[1];
313 if ( $this->displayImg
->exists() ) {
315 $page = $request->getIntOrNull( 'page' );
316 if ( is_null( $page ) ) {
320 $params = [ 'page' => $page ];
323 $renderLang = $request->getVal( 'lang' );
324 if ( !is_null( $renderLang ) ) {
325 $handler = $this->displayImg
->getHandler();
326 if ( $handler && $handler->validateParam( 'lang', $renderLang ) ) {
327 $params['lang'] = $renderLang;
333 $width_orig = $this->displayImg
->getWidth( $page );
334 $width = $width_orig;
335 $height_orig = $this->displayImg
->getHeight( $page );
336 $height = $height_orig;
338 $filename = wfEscapeWikiText( $this->displayImg
->getName() );
339 $linktext = $filename;
341 // Avoid PHP 7.1 warning from passing $this by reference
344 Hooks
::run( 'ImageOpenShowImageInlineBefore', [ &$imagePage, &$out ] );
346 if ( $this->displayImg
->allowInlineDisplay() ) {
348 # "Download high res version" link below the image
349 # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
350 # Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
351 # We'll show a thumbnail of this image
352 if ( $width > $maxWidth ||
$height > $maxHeight ||
$this->displayImg
->isVectorized() ) {
353 list( $width, $height ) = $this->getDisplayWidthHeight(
354 $maxWidth, $maxHeight, $width, $height
356 $linktext = $this->getContext()->msg( 'show-big-image' )->escaped();
358 $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
359 # Generate thumbnails or thumbnail links as needed...
361 foreach ( $thumbSizes as $size ) {
362 // We include a thumbnail size in the list, if it is
363 // less than or equal to the original size of the image
364 // asset ($width_orig/$height_orig). We also exclude
365 // the current thumbnail's size ($width/$height)
366 // since that is added to the message separately, so
367 // it can be denoted as the current size being shown.
368 // Vectorized images are limited by $wgSVGMaxSize big,
369 // so all thumbs less than or equal that are shown.
370 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
371 ||
( $this->displayImg
->isVectorized()
372 && max( $size[0], $size[1] ) <= $wgSVGMaxSize )
374 && $size[0] != $width && $size[1] != $height
376 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
378 $otherSizes[] = $sizeLink;
382 $otherSizes = array_unique( $otherSizes );
384 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
385 $msgsmall = $this->getThumbPrevText( $params, $sizeLinkBigImagePreview );
386 if ( count( $otherSizes ) ) {
390 [ 'class' => 'mw-filepage-other-resolutions' ],
391 $this->getContext()->msg( 'show-big-image-other' )
392 ->rawParams( $lang->pipeList( $otherSizes ) )
393 ->params( count( $otherSizes ) )
397 } elseif ( $width == 0 && $height == 0 ) {
398 # Some sort of audio file that doesn't have dimensions
399 # Don't output a no hi res message for such a file
402 # Image is small enough to show full size on image page
403 $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
406 $params['width'] = $width;
407 $params['height'] = $height;
408 $thumbnail = $this->displayImg
->transform( $params );
409 Linker
::processResponsiveImages( $this->displayImg
, $thumbnail, $params );
411 $anchorclose = Html
::rawElement(
413 [ 'class' => 'mw-filepage-resolutioninfo' ],
417 $isMulti = $this->displayImg
->isMultipage() && $this->displayImg
->pageCount() > 1;
419 $out->addModules( 'mediawiki.page.image.pagination' );
420 $out->addHTML( '<table class="multipageimage"><tr><td>' );
425 'alt' => $this->displayImg
->getTitle()->getPrefixedText(),
428 $out->addHTML( '<div class="fullImageLink" id="file">' .
429 $thumbnail->toHtml( $options ) .
430 $anchorclose . "</div>\n" );
434 $count = $this->displayImg
->pageCount();
437 $label = $this->getContext()->msg( 'imgmultipageprev' )->text();
438 // on the client side, this link is generated in ajaxifyPageNavigation()
439 // in the mediawiki.page.image.pagination module
440 $link = Linker
::linkKnown(
444 [ 'page' => $page - 1 ]
446 $thumb1 = Linker
::makeThumbLinkObj(
452 [ 'page' => $page - 1 ]
458 if ( $page < $count ) {
459 $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
460 $link = Linker
::linkKnown(
464 [ 'page' => $page +
1 ]
466 $thumb2 = Linker
::makeThumbLinkObj(
472 [ 'page' => $page +
1 ]
481 'name' => 'pageselector',
482 'action' => $wgScript,
485 for ( $i = 1; $i <= $count; $i++
) {
486 $options[] = Xml
::option( $lang->formatNum( $i ), $i, $i == $page );
488 $select = Xml
::tags( 'select',
489 [ 'id' => 'pageselector', 'name' => 'page' ],
490 implode( "\n", $options ) );
493 '</td><td><div class="multipageimagenavbox">' .
494 Xml
::openElement( 'form', $formParams ) .
495 Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
496 $this->getContext()->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
497 $this->getContext()->msg( 'word-separator' )->escaped() .
498 Xml
::submitButton( $this->getContext()->msg( 'imgmultigo' )->text() ) .
499 Xml
::closeElement( 'form' ) .
500 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
503 } elseif ( $this->displayImg
->isSafeFile() ) {
504 # if direct link is allowed but it's not a renderable image, show an icon.
505 $icon = $this->displayImg
->iconThumb();
507 $out->addHTML( '<div class="fullImageLink" id="file">' .
508 $icon->toHtml( [ 'file-link' => true ] ) .
512 $longDesc = $this->getContext()->msg( 'parentheses', $this->displayImg
->getLongDesc() )->text();
514 $handler = $this->displayImg
->getHandler();
516 // If this is a filetype with potential issues, warn the user.
518 $warningConfig = $handler->getWarningConfig( $this->displayImg
);
520 if ( $warningConfig !== null ) {
521 // The warning will be displayed via CSS and JavaScript.
522 // We just need to tell the client side what message to use.
523 $output = $this->getContext()->getOutput();
524 $output->addJsConfigVars( 'wgFileWarning', $warningConfig );
525 $output->addModules( $warningConfig['module'] );
526 $output->addModules( 'mediawiki.filewarning' );
530 $medialink = "[[Media:$filename|$linktext]]";
532 if ( !$this->displayImg
->isSafeFile() ) {
533 $warning = $this->getContext()->msg( 'mediawarning' )->plain();
534 // dirmark is needed here to separate the file name, which
535 // most likely ends in Latin characters, from the description,
536 // which may begin with the file type. In RTL environment
537 // this will get messy.
538 // The dirmark, however, must not be immediately adjacent
539 // to the filename, because it can get copied with it.
541 // @codingStandardsIgnoreStart Ignore long line
542 $out->addWikiText( <<<EOT
543 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
544 <div class="mediaWarning">$warning</div>
547 // @codingStandardsIgnoreEnd
549 $out->addWikiText( <<<EOT
550 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
556 $renderLangOptions = $this->displayImg
->getAvailableLanguages();
557 if ( count( $renderLangOptions ) >= 1 ) {
558 $currentLanguage = $renderLang;
559 $defaultLang = $this->displayImg
->getDefaultRenderLanguage();
560 if ( is_null( $currentLanguage ) ) {
561 $currentLanguage = $defaultLang;
563 $out->addHTML( $this->doRenderLangOpt( $renderLangOptions, $currentLanguage, $defaultLang ) );
566 // Add cannot animate thumbnail warning
567 if ( !$this->displayImg
->canAnimateThumbIfAppropriate() ) {
568 // Include the extension so wiki admins can
569 // customize it on a per file-type basis
570 // (aka say things like use format X instead).
571 // additionally have a specific message for
572 // file-no-thumb-animation-gif
573 $ext = $this->displayImg
->getExtension();
574 $noAnimMesg = wfMessageFallback(
575 'file-no-thumb-animation-' . $ext,
576 'file-no-thumb-animation'
579 $out->addWikiText( <<<EOT
580 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
585 if ( !$this->displayImg
->isLocal() ) {
586 $this->printSharedImageText();
589 # Image does not exist
590 if ( !$this->getId() ) {
591 $dbr = wfGetDB( DB_REPLICA
);
593 # No article exists either
594 # Show deletion log to be consistent with normal articles
595 LogEventsList
::showLogExtract(
597 [ 'delete', 'move' ],
598 $this->getTitle()->getPrefixedText(),
601 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
602 'showIfEmpty' => false,
603 'msgKey' => [ 'moveddeleted-notice' ]
608 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
609 // Only show an upload link if the user can upload
610 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
612 'filepage-nofile-link',
613 $uploadTitle->getFullURL( [ 'wpDestFile' => $this->mPage
->getFile()->getName() ] )
616 $nofile = 'filepage-nofile';
618 // Note, if there is an image description page, but
619 // no image, then this setRobotPolicy is overridden
620 // by Article::View().
621 $out->setRobotPolicy( 'noindex,nofollow' );
622 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
623 if ( !$this->getId() && $wgSend404Code ) {
624 // If there is no image, no shared image, and no description page,
625 // output a 404, to be consistent with Article::showMissingArticle.
626 $request->response()->statusHeader( 404 );
629 $out->setFileVersion( $this->displayImg
);
633 * Make the text under the image to say what size preview
635 * @param $params array parameters for thumbnail
636 * @param $sizeLinkBigImagePreview HTML for the current size
637 * @return string HTML output
639 private function getThumbPrevText( $params, $sizeLinkBigImagePreview ) {
640 if ( $sizeLinkBigImagePreview ) {
641 // Show a different message of preview is different format from original.
642 $previewTypeDiffers = false;
643 $origExt = $thumbExt = $this->displayImg
->getExtension();
644 if ( $this->displayImg
->getHandler() ) {
645 $origMime = $this->displayImg
->getMimeType();
646 $typeParams = $params;
647 $this->displayImg
->getHandler()->normaliseParams( $this->displayImg
, $typeParams );
648 list( $thumbExt, $thumbMime ) = $this->displayImg
->getHandler()->getThumbType(
649 $origExt, $origMime, $typeParams );
650 if ( $thumbMime !== $origMime ) {
651 $previewTypeDiffers = true;
654 if ( $previewTypeDiffers ) {
655 return $this->getContext()->msg( 'show-big-image-preview-differ' )->
656 rawParams( $sizeLinkBigImagePreview )->
657 params( strtoupper( $origExt ) )->
658 params( strtoupper( $thumbExt ) )->
661 return $this->getContext()->msg( 'show-big-image-preview' )->
662 rawParams( $sizeLinkBigImagePreview )->
671 * Creates an thumbnail of specified size and returns an HTML link to it
672 * @param array $params Scaler parameters
677 private function makeSizeLink( $params, $width, $height ) {
678 $params['width'] = $width;
679 $params['height'] = $height;
680 $thumbnail = $this->displayImg
->transform( $params );
681 if ( $thumbnail && !$thumbnail->isError() ) {
682 return Html
::rawElement( 'a', [
683 'href' => $thumbnail->getUrl(),
684 'class' => 'mw-thumbnail-link'
685 ], $this->getContext()->msg( 'show-big-image-size' )->numParams(
686 $thumbnail->getWidth(), $thumbnail->getHeight()
694 * Show a notice that the file is from a shared repository
696 protected function printSharedImageText() {
697 $out = $this->getContext()->getOutput();
700 $descUrl = $this->mPage
->getFile()->getDescriptionUrl();
701 $descText = $this->mPage
->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
703 /* Add canonical to head if there is no local page for this shared file */
704 if ( $descUrl && $this->mPage
->getId() == 0 ) {
705 $out->setCanonicalUrl( $descUrl );
708 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
709 $repo = $this->mPage
->getFile()->getRepo()->getDisplayName();
713 $this->getContext()->msg( 'sharedupload-desc-here' )->plain() !== '-'
715 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-here', $repo, $descUrl ] );
716 } elseif ( $descUrl &&
717 $this->getContext()->msg( 'sharedupload-desc-there' )->plain() !== '-'
719 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-there', $repo, $descUrl ] );
721 $out->wrapWikiMsg( $wrap, [ 'sharedupload', $repo ], ''/*BACKCOMPAT*/ );
725 $this->mExtraDescription
= $descText;
729 public function getUploadUrl() {
731 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
732 return $uploadTitle->getFullURL( [
733 'wpDestFile' => $this->mPage
->getFile()->getName(),
739 * Print out the various links at the bottom of the image page, e.g. reupload,
740 * external editing (and instructions link) etc.
742 protected function uploadLinksBox() {
743 global $wgEnableUploads;
745 if ( !$wgEnableUploads ) {
750 if ( !$this->mPage
->getFile()->isLocal() ) {
754 $out = $this->getContext()->getOutput();
755 $out->addHTML( "<ul>\n" );
757 # "Upload a new version of this file" link
758 $canUpload = $this->getTitle()->quickUserCan( 'upload', $this->getContext()->getUser() );
759 if ( $canUpload && UploadBase
::userCanReUpload(
760 $this->getContext()->getUser(),
761 $this->mPage
->getFile() )
763 $ulink = Linker
::makeExternalLink(
764 $this->getUploadUrl(),
765 $this->getContext()->msg( 'uploadnewversion-linktext' )->text()
767 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\">"
768 . "<div class=\"plainlinks\">{$ulink}</div></li>\n" );
770 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">"
771 . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
774 $out->addHTML( "</ul>\n" );
780 protected function closeShowImage() {
784 * If the page we've just displayed is in the "Image" namespace,
785 * we follow it with an upload history of the image and its usage.
787 protected function imageHistory() {
789 $out = $this->getContext()->getOutput();
790 $pager = new ImageHistoryPseudoPager( $this );
791 $out->addHTML( $pager->getBody() );
792 $out->preventClickjacking( $pager->getPreventClickjacking() );
794 $this->mPage
->getFile()->resetHistory(); // free db resources
796 # Exist check because we don't want to show this on pages where an image
797 # doesn't exist along with the noimage message, that would suck. -ævar
798 if ( $this->mPage
->getFile()->exists() ) {
799 $this->uploadLinksBox();
804 * @param string $target
806 * @return ResultWrapper
808 protected function queryImageLinks( $target, $limit ) {
809 $dbr = wfGetDB( DB_REPLICA
);
812 [ 'imagelinks', 'page' ],
813 [ 'page_namespace', 'page_title', 'il_to' ],
814 [ 'il_to' => $target, 'il_from = page_id' ],
816 [ 'LIMIT' => $limit +
1, 'ORDER BY' => 'il_from', ]
820 protected function imageLinks() {
823 $out = $this->getContext()->getOutput();
827 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE
) as $redir ) {
828 $redirects[$redir->getDBkey()] = [];
830 'page_namespace' => NS_FILE
,
831 'page_title' => $redir->getDBkey(),
835 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit +
1 );
836 foreach ( $res as $row ) {
839 $count = count( $rows );
841 $hasMore = $count > $limit;
842 if ( !$hasMore && count( $redirects ) ) {
843 $res = $this->queryImageLinks( array_keys( $redirects ),
844 $limit - count( $rows ) +
1 );
845 foreach ( $res as $row ) {
846 $redirects[$row->il_to
][] = $row;
849 $hasMore = ( $res->numRows() +
count( $rows ) ) > $limit;
854 Html
::rawElement( 'div',
855 [ 'id' => 'mw-imagepage-nolinkstoimage' ], "\n$1\n" ),
861 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
863 $out->addWikiMsg( 'linkstoimage', $count );
865 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
866 $out->addWikiMsg( 'linkstoimage-more',
867 $this->getContext()->getLanguage()->formatNum( $limit ),
868 $this->getTitle()->getPrefixedDBkey()
873 Html
::openElement( 'ul',
874 [ 'class' => 'mw-imagepage-linkstoimage' ] ) . "\n"
878 // Sort the list by namespace:title
879 usort( $rows, [ $this, 'compare' ] );
881 // Create links for every element
883 foreach ( $rows as $element ) {
885 if ( $currentCount > $limit ) {
890 # Add a redirect=no to make redirect pages reachable
891 if ( isset( $redirects[$element->page_title
] ) ) {
892 $query['redirect'] = 'no';
894 $link = Linker
::linkKnown(
895 Title
::makeTitle( $element->page_namespace
, $element->page_title
),
898 if ( !isset( $redirects[$element->page_title
] ) ) {
901 } elseif ( count( $redirects[$element->page_title
] ) === 0 ) {
902 # Redirect without usages
903 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )
904 ->rawParams( $link, '' )
907 # Redirect with usages
909 foreach ( $redirects[$element->page_title
] as $row ) {
911 if ( $currentCount > $limit ) {
915 $link2 = Linker
::linkKnown( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
916 $li .= Html
::rawElement(
918 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
],
923 $ul = Html
::rawElement(
925 [ 'class' => 'mw-imagepage-redirectstofile' ],
928 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
929 $link, $ul )->parse();
931 $out->addHTML( Html
::rawElement(
933 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
],
939 $out->addHTML( Html
::closeElement( 'ul' ) . "\n" );
942 // Add a links to [[Special:Whatlinkshere]]
943 if ( $count > $limit ) {
944 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
946 $out->addHTML( Html
::closeElement( 'div' ) . "\n" );
949 protected function imageDupes() {
951 $out = $this->getContext()->getOutput();
953 $dupes = $this->mPage
->getDuplicates();
954 if ( count( $dupes ) == 0 ) {
958 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
959 $out->addWikiMsg( 'duplicatesoffile',
960 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
962 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
967 foreach ( $dupes as $file ) {
969 if ( $file->isLocal() ) {
970 $link = Linker
::linkKnown( $file->getTitle() );
972 $link = Linker
::makeExternalLink( $file->getDescriptionUrl(),
973 $file->getTitle()->getPrefixedText() );
974 $fromSrc = $this->getContext()->msg(
976 $file->getRepo()->getDisplayName()
979 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
981 $out->addHTML( "</ul></div>\n" );
985 * Delete the file, or an earlier version of it
987 public function delete() {
988 $file = $this->mPage
->getFile();
989 if ( !$file->exists() ||
!$file->isLocal() ||
$file->getRedirected() ) {
990 // Standard article deletion
995 $deleter = new FileDeleteForm( $file );
1000 * Display an error with a wikitext description
1002 * @param string $description
1004 function showError( $description ) {
1005 $out = $this->getContext()->getOutput();
1006 $out->setPageTitle( $this->getContext()->msg( 'internalerror' ) );
1007 $out->setRobotPolicy( 'noindex,nofollow' );
1008 $out->setArticleRelated( false );
1009 $out->enableClientCache( false );
1010 $out->addWikiText( $description );
1014 * Callback for usort() to do link sorts by (namespace, title)
1015 * Function copied from Title::compare()
1017 * @param object $a Object page to compare with
1018 * @param object $b Object page to compare with
1019 * @return int Result of string comparison, or namespace comparison
1021 protected function compare( $a, $b ) {
1022 if ( $a->page_namespace
== $b->page_namespace
) {
1023 return strcmp( $a->page_title
, $b->page_title
);
1025 return $a->page_namespace
- $b->page_namespace
;
1030 * Returns the corresponding $wgImageLimits entry for the selected user option
1033 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
1037 public function getImageLimitsFromOption( $user, $optionName ) {
1038 global $wgImageLimits;
1040 $option = $user->getIntOption( $optionName );
1041 if ( !isset( $wgImageLimits[$option] ) ) {
1042 $option = User
::getDefaultOption( $optionName );
1045 // The user offset might still be incorrect, specially if
1046 // $wgImageLimits got changed (see bug #8858).
1047 if ( !isset( $wgImageLimits[$option] ) ) {
1048 // Default to the first offset in $wgImageLimits
1052 return isset( $wgImageLimits[$option] )
1053 ?
$wgImageLimits[$option]
1054 : [ 800, 600 ]; // if nothing is set, fallback to a hardcoded default
1058 * Output a drop-down box for language options for the file
1060 * @param array $langChoices Array of string language codes
1061 * @param string $curLang Language code file is being viewed in.
1062 * @param string $defaultLang Language code that image is rendered in by default
1063 * @return string HTML to insert underneath image.
1065 protected function doRenderLangOpt( array $langChoices, $curLang, $defaultLang ) {
1067 sort( $langChoices );
1068 $curLang = wfBCP47( $curLang );
1069 $defaultLang = wfBCP47( $defaultLang );
1071 $haveCurrentLang = false;
1072 $haveDefaultLang = false;
1074 // We make a list of all the language choices in the file.
1075 // Additionally if the default language to render this file
1076 // is not included as being in this file (for example, in svgs
1077 // usually the fallback content is the english content) also
1078 // include a choice for that. Last of all, if we're viewing
1079 // the file in a language not on the list, add it as a choice.
1080 foreach ( $langChoices as $lang ) {
1081 $code = wfBCP47( $lang );
1082 $name = Language
::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1083 if ( $name !== '' ) {
1084 $display = $this->getContext()->msg( 'img-lang-opt', $code, $name )->text();
1088 $opts .= "\n" . Xml
::option( $display, $code, $curLang === $code );
1089 if ( $curLang === $code ) {
1090 $haveCurrentLang = true;
1092 if ( $defaultLang === $code ) {
1093 $haveDefaultLang = true;
1096 if ( !$haveDefaultLang ) {
1097 // Its hard to know if the content is really in the default language, or
1098 // if its just unmarked content that could be in any language.
1099 $opts = Xml
::option(
1100 $this->getContext()->msg( 'img-lang-default' )->text(),
1102 $defaultLang === $curLang
1105 if ( !$haveCurrentLang && $defaultLang !== $curLang ) {
1106 $name = Language
::fetchLanguageName( $curLang, $this->getContext()->getLanguage()->getCode() );
1107 if ( $name !== '' ) {
1108 $display = $this->getContext()->msg( 'img-lang-opt', $curLang, $name )->text();
1110 $display = $curLang;
1112 $opts = Xml
::option( $display, $curLang, true ) . $opts;
1115 $select = Html
::rawElement(
1117 [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1120 $submit = Xml
::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1122 $formContents = $this->getContext()->msg( 'img-lang-info' )
1123 ->rawParams( $select, $submit )
1125 $formContents .= Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1127 $langSelectLine = Html
::rawElement( 'div', [ 'id' => 'mw-imglangselector-line' ],
1128 Html
::rawElement( 'form', [ 'action' => $wgScript ], $formContents )
1130 return $langSelectLine;
1134 * Get the width and height to display image at.
1136 * @note This method assumes that it is only called if one
1137 * of the dimensions are bigger than the max, or if the
1138 * image is vectorized.
1140 * @param int $maxWidth Max width to display at
1141 * @param int $maxHeight Max height to display at
1142 * @param int $width Actual width of the image
1143 * @param int $height Actual height of the image
1144 * @throws MWException
1145 * @return array Array (width, height)
1147 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1148 if ( !$maxWidth ||
!$maxHeight ) {
1149 // should never happen
1150 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1153 if ( !$width ||
!$height ) {
1157 # Calculate the thumbnail size.
1158 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1159 // Vectorized image, do nothing.
1160 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1161 # The limiting factor is the width, not the height.
1162 $height = round( $height * $maxWidth / $width );
1164 # Note that $height <= $maxHeight now.
1166 $newwidth = floor( $width * $maxHeight / $height );
1167 $height = round( $height * $newwidth / $width );
1169 # Note that $height <= $maxHeight now, but might not be identical
1170 # because of rounding.
1172 return [ $width, $height ];
1176 * Get alternative thumbnail sizes.
1178 * @note This will only list several alternatives if thumbnails are rendered on 404
1179 * @param int $origWidth Actual width of image
1180 * @param int $origHeight Actual height of image
1181 * @return array An array of [width, height] pairs.
1183 protected function getThumbSizes( $origWidth, $origHeight ) {
1184 global $wgImageLimits;
1185 if ( $this->displayImg
->getRepo()->canTransformVia404() ) {
1186 $thumbSizes = $wgImageLimits;
1187 // Also include the full sized resolution in the list, so
1188 // that users know they can get it. This will link to the
1189 // original file asset if mustRender() === false. In the case
1190 // that we mustRender, some users have indicated that they would
1191 // find it useful to have the full size image in the rendered
1193 $thumbSizes[] = [ $origWidth, $origHeight ];
1195 # Creating thumb links triggers thumbnail generation.
1196 # Just generate the thumb for the current users prefs.
1198 $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' )
1200 if ( !$this->displayImg
->mustRender() ) {
1201 // We can safely include a link to the "full-size" preview,
1202 // without actually rendering.
1203 $thumbSizes[] = [ $origWidth, $origHeight ];
1210 * @see WikiFilePage::getFile
1213 public function getFile() {
1214 return $this->mPage
->getFile();
1218 * @see WikiFilePage::isLocal
1221 public function isLocal() {
1222 return $this->mPage
->isLocal();
1226 * @see WikiFilePage::getDuplicates
1227 * @return array|null
1229 public function getDuplicates() {
1230 return $this->mPage
->getDuplicates();
1234 * @see WikiFilePage::getForeignCategories
1235 * @return TitleArray|Title[]
1237 public function getForeignCategories() {
1238 $this->mPage
->getForeignCategories();