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
24 * Class for viewing MediaWiki file description pages
28 class ImagePage
extends Article
{
39 protected $mExtraDescription = false;
48 * @return WikiFilePage
50 protected function newPage( Title
$title ) {
51 // Overload mPage with a file-specific page
52 return new WikiFilePage( $title );
56 * Constructor from a page id
57 * @param int $id Article ID to load
58 * @return ImagePage|null
60 public static function newFromID( $id ) {
61 $t = Title
::newFromID( $id );
62 # @todo FIXME: Doesn't inherit right
63 return $t == null ?
null : new self( $t );
64 # return $t == null ? null : new static( $t ); // PHP 5.3
71 public function setFile( $file ) {
72 $this->mPage
->setFile( $file );
73 $this->displayImg
= $file;
74 $this->fileLoaded
= true;
77 protected function loadFile() {
78 if ( $this->fileLoaded
) {
81 $this->fileLoaded
= true;
83 $this->displayImg
= $img = false;
84 Hooks
::run( 'ImagePageFindFile', [ $this, &$img, &$this->displayImg
] );
85 if ( !$img ) { // not set by hook?
86 $img = wfFindFile( $this->getTitle() );
88 $img = wfLocalFile( $this->getTitle() );
91 $this->mPage
->setFile( $img );
92 if ( !$this->displayImg
) { // not set by hook?
93 $this->displayImg
= $img;
95 $this->repo
= $img->getRepo();
99 * Handler for action=render
100 * Include body text only; none of the image extras
102 public function render() {
103 $this->getContext()->getOutput()->setArticleBodyOnly( true );
107 public function view() {
110 $out = $this->getContext()->getOutput();
111 $request = $this->getContext()->getRequest();
112 $diff = $request->getVal( 'diff' );
113 $diffOnly = $request->getBool(
115 $this->getContext()->getUser()->getOption( 'diffonly' )
118 if ( $this->getTitle()->getNamespace() != NS_FILE ||
( $diff !== null && $diffOnly ) ) {
125 if ( $this->getTitle()->getNamespace() == NS_FILE
&& $this->mPage
->getFile()->getRedirected() ) {
126 if ( $this->getTitle()->getDBkey() == $this->mPage
->getFile()->getName() ||
$diff !== null ) {
127 // mTitle is the same as the redirect target so ask Article
128 // to perform the redirect for us.
129 $request->setVal( 'diffonly', 'true' );
133 // mTitle is not the same as the redirect target so it is
134 // probably the redirect page itself. Fake the redirect symbol
135 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
136 $out->addHTML( $this->viewRedirect(
137 Title
::makeTitle( NS_FILE
, $this->mPage
->getFile()->getName() ),
138 /* $appendSubtitle */ true,
139 /* $forceKnown */ true )
141 $this->mPage
->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
146 if ( $wgShowEXIF && $this->displayImg
->exists() ) {
147 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
148 $formattedMetadata = $this->displayImg
->formatMetadata( $this->getContext() );
149 $showmeta = $formattedMetadata !== false;
154 if ( !$diff && $this->displayImg
->exists() ) {
155 $out->addHTML( $this->showTOC( $showmeta ) );
159 $this->openShowImage();
162 # No need to display noarticletext, we use our own message, output in openShowImage()
163 if ( $this->mPage
->getId() ) {
164 # NS_FILE is in the user language, but this section (the actual wikitext)
165 # should be in page content language
166 $pageLang = $this->getTitle()->getPageViewLanguage();
167 $out->addHTML( Xml
::openElement( 'div', [ 'id' => 'mw-imagepage-content',
168 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
169 'class' => 'mw-content-' . $pageLang->getDir() ] ) );
173 $out->addHTML( Xml
::closeElement( 'div' ) );
175 # Just need to set the right headers
176 $out->setArticleFlag( true );
177 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
178 $this->mPage
->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
181 # Show shared description, if needed
182 if ( $this->mExtraDescription
) {
183 $fol = $this->getContext()->msg( 'shareddescriptionfollows' );
184 if ( !$fol->isDisabled() ) {
185 $out->addWikiText( $fol->plain() );
187 $out->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription
. "</div>\n" );
190 $this->closeShowImage();
191 $this->imageHistory();
192 // TODO: Cleanup the following
194 $out->addHTML( Xml
::element( 'h2',
195 [ 'id' => 'filelinks' ],
196 $this->getContext()->msg( 'imagelinks' )->text() ) . "\n" );
198 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
199 # Yet we return metadata about the target. Definitely an issue in the FileRepo
202 # Allow extensions to add something after the image links
204 Hooks
::run( 'ImagePageAfterImageLinks', [ $this, &$html ] );
206 $out->addHTML( $html );
210 $out->addHTML( Xml
::element(
212 [ 'id' => 'metadata' ],
213 $this->getContext()->msg( 'metadata' )->text() ) . "\n" );
214 $out->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
215 $out->addModules( [ 'mediawiki.action.view.metadata' ] );
218 // Add remote Filepage.css
219 if ( !$this->repo
->isLocal() ) {
220 $css = $this->repo
->getDescriptionStylesheetUrl();
222 $out->addStyle( $css );
225 // always show the local local Filepage.css, bug 29277
226 $out->addModuleStyles( 'filepage' );
228 // Add MediaWiki styles for a file page
229 $out->addModuleStyles( 'mediawiki.action.view.filepage' );
235 public function getDisplayedFile() {
237 return $this->displayImg
;
243 * @param bool $metadata Whether or not to show the metadata link
246 protected function showTOC( $metadata ) {
248 '<li><a href="#file">' . $this->getContext()->msg( 'file-anchor-link' )->escaped() . '</a></li>',
249 '<li><a href="#filehistory">' . $this->getContext()->msg( 'filehist' )->escaped() . '</a></li>',
250 '<li><a href="#filelinks">' . $this->getContext()->msg( 'imagelinks' )->escaped() . '</a></li>',
253 Hooks
::run( 'ImagePageShowTOC', [ $this, &$r ] );
256 $r[] = '<li><a href="#metadata">' .
257 $this->getContext()->msg( 'metadata' )->escaped() .
261 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
265 * Make a table with metadata to be shown in the output page.
267 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
269 * @param array $metadata The array containing the Exif data
270 * @return string The metadata table. This is treated as Wikitext (!)
272 protected function makeMetadataTable( $metadata ) {
273 $r = "<div class=\"mw-imagepage-section-metadata\">";
274 $r .= $this->getContext()->msg( 'metadata-help' )->plain();
275 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
276 foreach ( $metadata as $type => $stuff ) {
277 foreach ( $stuff as $v ) {
278 # @todo FIXME: Why is this using escapeId for a class?!
279 $class = Sanitizer
::escapeId( $v['id'] );
280 if ( $type == 'collapsed' ) {
281 // Handled by mediawiki.action.view.metadata module.
282 $class .= ' collapsable';
284 $r .= "<tr class=\"$class\">\n";
285 $r .= "<th>{$v['name']}</th>\n";
286 $r .= "<td>{$v['value']}</td>\n</tr>";
289 $r .= "</table>\n</div>\n";
294 * Overloading Article's getContentObject method.
296 * Omit noarticletext if sharedupload; text will be fetched from the
297 * shared upload server if possible.
300 public function getContentObject() {
302 if ( $this->mPage
->getFile() && !$this->mPage
->getFile()->isLocal() && 0 == $this->getId() ) {
305 return parent
::getContentObject();
308 protected function openShowImage() {
309 global $wgEnableUploads, $wgSend404Code, $wgSVGMaxSize;
312 $out = $this->getContext()->getOutput();
313 $user = $this->getContext()->getUser();
314 $lang = $this->getContext()->getLanguage();
315 $dirmark = $lang->getDirMarkEntity();
316 $request = $this->getContext()->getRequest();
318 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
320 $maxHeight = $max[1];
322 if ( $this->displayImg
->exists() ) {
324 $page = $request->getIntOrNull( 'page' );
325 if ( is_null( $page ) ) {
329 $params = [ 'page' => $page ];
332 $renderLang = $request->getVal( 'lang' );
333 if ( !is_null( $renderLang ) ) {
334 $handler = $this->displayImg
->getHandler();
335 if ( $handler && $handler->validateParam( 'lang', $renderLang ) ) {
336 $params['lang'] = $renderLang;
342 $width_orig = $this->displayImg
->getWidth( $page );
343 $width = $width_orig;
344 $height_orig = $this->displayImg
->getHeight( $page );
345 $height = $height_orig;
347 $filename = wfEscapeWikiText( $this->displayImg
->getName() );
348 $linktext = $filename;
350 Hooks
::run( 'ImageOpenShowImageInlineBefore', [ &$this, &$out ] );
352 if ( $this->displayImg
->allowInlineDisplay() ) {
354 # "Download high res version" link below the image
355 # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
356 # Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
357 # We'll show a thumbnail of this image
358 if ( $width > $maxWidth ||
$height > $maxHeight ||
$this->displayImg
->isVectorized() ) {
359 list( $width, $height ) = $this->getDisplayWidthHeight(
360 $maxWidth, $maxHeight, $width, $height
362 $linktext = $this->getContext()->msg( 'show-big-image' )->escaped();
364 $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
365 # Generate thumbnails or thumbnail links as needed...
367 foreach ( $thumbSizes as $size ) {
368 // We include a thumbnail size in the list, if it is
369 // less than or equal to the original size of the image
370 // asset ($width_orig/$height_orig). We also exclude
371 // the current thumbnail's size ($width/$height)
372 // since that is added to the message separately, so
373 // it can be denoted as the current size being shown.
374 // Vectorized images are limited by $wgSVGMaxSize big,
375 // so all thumbs less than or equal that are shown.
376 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
377 ||
( $this->displayImg
->isVectorized()
378 && max( $size[0], $size[1] ) <= $wgSVGMaxSize )
380 && $size[0] != $width && $size[1] != $height
382 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
384 $otherSizes[] = $sizeLink;
388 $otherSizes = array_unique( $otherSizes );
390 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
391 $msgsmall = $this->getThumbPrevText( $params, $sizeLinkBigImagePreview );
392 if ( count( $otherSizes ) ) {
396 [ 'class' => 'mw-filepage-other-resolutions' ],
397 $this->getContext()->msg( 'show-big-image-other' )
398 ->rawParams( $lang->pipeList( $otherSizes ) )
399 ->params( count( $otherSizes ) )
403 } elseif ( $width == 0 && $height == 0 ) {
404 # Some sort of audio file that doesn't have dimensions
405 # Don't output a no hi res message for such a file
408 # Image is small enough to show full size on image page
409 $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
412 $params['width'] = $width;
413 $params['height'] = $height;
414 $thumbnail = $this->displayImg
->transform( $params );
415 Linker
::processResponsiveImages( $this->displayImg
, $thumbnail, $params );
417 $anchorclose = Html
::rawElement(
419 [ 'class' => 'mw-filepage-resolutioninfo' ],
423 $isMulti = $this->displayImg
->isMultipage() && $this->displayImg
->pageCount() > 1;
425 $out->addModules( 'mediawiki.page.image.pagination' );
426 $out->addHTML( '<table class="multipageimage"><tr><td>' );
431 'alt' => $this->displayImg
->getTitle()->getPrefixedText(),
434 $out->addHTML( '<div class="fullImageLink" id="file">' .
435 $thumbnail->toHtml( $options ) .
436 $anchorclose . "</div>\n" );
440 $count = $this->displayImg
->pageCount();
443 $label = $out->parse( $this->getContext()->msg( 'imgmultipageprev' )->text(), false );
444 // on the client side, this link is generated in ajaxifyPageNavigation()
445 // in the mediawiki.page.image.pagination module
446 $link = Linker
::linkKnown(
450 [ 'page' => $page - 1 ]
452 $thumb1 = Linker
::makeThumbLinkObj(
458 [ 'page' => $page - 1 ]
464 if ( $page < $count ) {
465 $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
466 $link = Linker
::linkKnown(
470 [ 'page' => $page +
1 ]
472 $thumb2 = Linker
::makeThumbLinkObj(
478 [ 'page' => $page +
1 ]
487 'name' => 'pageselector',
488 'action' => $wgScript,
491 for ( $i = 1; $i <= $count; $i++
) {
492 $options[] = Xml
::option( $lang->formatNum( $i ), $i, $i == $page );
494 $select = Xml
::tags( 'select',
495 [ 'id' => 'pageselector', 'name' => 'page' ],
496 implode( "\n", $options ) );
499 '</td><td><div class="multipageimagenavbox">' .
500 Xml
::openElement( 'form', $formParams ) .
501 Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
502 $this->getContext()->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
503 Xml
::submitButton( $this->getContext()->msg( 'imgmultigo' )->text() ) .
504 Xml
::closeElement( 'form' ) .
505 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
508 } elseif ( $this->displayImg
->isSafeFile() ) {
509 # if direct link is allowed but it's not a renderable image, show an icon.
510 $icon = $this->displayImg
->iconThumb();
512 $out->addHTML( '<div class="fullImageLink" id="file">' .
513 $icon->toHtml( [ 'file-link' => true ] ) .
517 $longDesc = $this->getContext()->msg( 'parentheses', $this->displayImg
->getLongDesc() )->text();
519 $handler = $this->displayImg
->getHandler();
521 // If this is a filetype with potential issues, warn the user.
523 $warningConfig = $handler->getWarningConfig( $this->displayImg
);
525 if ( $warningConfig !== null ) {
526 // The warning will be displayed via CSS and JavaScript.
527 // We just need to tell the client side what message to use.
528 $output = $this->getContext()->getOutput();
529 $output->addJsConfigVars( 'wgFileWarning', $warningConfig );
530 $output->addModules( $warningConfig['module'] );
531 $output->addModules( 'mediawiki.filewarning' );
535 $medialink = "[[Media:$filename|$linktext]]";
537 if ( !$this->displayImg
->isSafeFile() ) {
538 $warning = $this->getContext()->msg( 'mediawarning' )->plain();
539 // dirmark is needed here to separate the file name, which
540 // most likely ends in Latin characters, from the description,
541 // which may begin with the file type. In RTL environment
542 // this will get messy.
543 // The dirmark, however, must not be immediately adjacent
544 // to the filename, because it can get copied with it.
546 // @codingStandardsIgnoreStart Ignore long line
547 $out->addWikiText( <<<EOT
548 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
549 <div class="mediaWarning">$warning</div>
552 // @codingStandardsIgnoreEnd
554 $out->addWikiText( <<<EOT
555 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
561 $renderLangOptions = $this->displayImg
->getAvailableLanguages();
562 if ( count( $renderLangOptions ) >= 1 ) {
563 $currentLanguage = $renderLang;
564 $defaultLang = $this->displayImg
->getDefaultRenderLanguage();
565 if ( is_null( $currentLanguage ) ) {
566 $currentLanguage = $defaultLang;
568 $out->addHTML( $this->doRenderLangOpt( $renderLangOptions, $currentLanguage, $defaultLang ) );
571 // Add cannot animate thumbnail warning
572 if ( !$this->displayImg
->canAnimateThumbIfAppropriate() ) {
573 // Include the extension so wiki admins can
574 // customize it on a per file-type basis
575 // (aka say things like use format X instead).
576 // additionally have a specific message for
577 // file-no-thumb-animation-gif
578 $ext = $this->displayImg
->getExtension();
579 $noAnimMesg = wfMessageFallback(
580 'file-no-thumb-animation-' . $ext,
581 'file-no-thumb-animation'
584 $out->addWikiText( <<<EOT
585 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
590 if ( !$this->displayImg
->isLocal() ) {
591 $this->printSharedImageText();
594 # Image does not exist
595 if ( !$this->getId() ) {
596 # No article exists either
597 # Show deletion log to be consistent with normal articles
598 LogEventsList
::showLogExtract(
600 [ 'delete', 'move' ],
601 $this->getTitle()->getPrefixedText(),
604 'conds' => [ "log_action != 'revision'" ],
605 'showIfEmpty' => false,
606 'msgKey' => [ 'moveddeleted-notice' ]
611 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
612 // Only show an upload link if the user can upload
613 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
615 'filepage-nofile-link',
616 $uploadTitle->getFullURL( [ 'wpDestFile' => $this->mPage
->getFile()->getName() ] )
619 $nofile = 'filepage-nofile';
621 // Note, if there is an image description page, but
622 // no image, then this setRobotPolicy is overridden
623 // by Article::View().
624 $out->setRobotPolicy( 'noindex,nofollow' );
625 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
626 if ( !$this->getId() && $wgSend404Code ) {
627 // If there is no image, no shared image, and no description page,
628 // output a 404, to be consistent with Article::showMissingArticle.
629 $request->response()->statusHeader( 404 );
632 $out->setFileVersion( $this->displayImg
);
636 * Make the text under the image to say what size preview
638 * @param $params array parameters for thumbnail
639 * @param $sizeLinkBigImagePreview HTML for the current size
640 * @return string HTML output
642 private function getThumbPrevText( $params, $sizeLinkBigImagePreview ) {
643 if ( $sizeLinkBigImagePreview ) {
644 // Show a different message of preview is different format from original.
645 $previewTypeDiffers = false;
646 $origExt = $thumbExt = $this->displayImg
->getExtension();
647 if ( $this->displayImg
->getHandler() ) {
648 $origMime = $this->displayImg
->getMimeType();
649 $typeParams = $params;
650 $this->displayImg
->getHandler()->normaliseParams( $this->displayImg
, $typeParams );
651 list( $thumbExt, $thumbMime ) = $this->displayImg
->getHandler()->getThumbType(
652 $origExt, $origMime, $typeParams );
653 if ( $thumbMime !== $origMime ) {
654 $previewTypeDiffers = true;
657 if ( $previewTypeDiffers ) {
658 return $this->getContext()->msg( 'show-big-image-preview-differ' )->
659 rawParams( $sizeLinkBigImagePreview )->
660 params( strtoupper( $origExt ) )->
661 params( strtoupper( $thumbExt ) )->
664 return $this->getContext()->msg( 'show-big-image-preview' )->
665 rawParams( $sizeLinkBigImagePreview )->
674 * Creates an thumbnail of specified size and returns an HTML link to it
675 * @param array $params Scaler parameters
680 private function makeSizeLink( $params, $width, $height ) {
681 $params['width'] = $width;
682 $params['height'] = $height;
683 $thumbnail = $this->displayImg
->transform( $params );
684 if ( $thumbnail && !$thumbnail->isError() ) {
685 return Html
::rawElement( 'a', [
686 'href' => $thumbnail->getUrl(),
687 'class' => 'mw-thumbnail-link'
688 ], $this->getContext()->msg( 'show-big-image-size' )->numParams(
689 $thumbnail->getWidth(), $thumbnail->getHeight()
697 * Show a notice that the file is from a shared repository
699 protected function printSharedImageText() {
700 $out = $this->getContext()->getOutput();
703 $descUrl = $this->mPage
->getFile()->getDescriptionUrl();
704 $descText = $this->mPage
->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
706 /* Add canonical to head if there is no local page for this shared file */
707 if ( $descUrl && $this->mPage
->getId() == 0 ) {
708 $out->setCanonicalUrl( $descUrl );
711 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
712 $repo = $this->mPage
->getFile()->getRepo()->getDisplayName();
716 $this->getContext()->msg( 'sharedupload-desc-here' )->plain() !== '-'
718 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-here', $repo, $descUrl ] );
719 } elseif ( $descUrl &&
720 $this->getContext()->msg( 'sharedupload-desc-there' )->plain() !== '-'
722 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-there', $repo, $descUrl ] );
724 $out->wrapWikiMsg( $wrap, [ 'sharedupload', $repo ], ''/*BACKCOMPAT*/ );
728 $this->mExtraDescription
= $descText;
732 public function getUploadUrl() {
734 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
735 return $uploadTitle->getFullURL( [
736 'wpDestFile' => $this->mPage
->getFile()->getName(),
742 * Print out the various links at the bottom of the image page, e.g. reupload,
743 * external editing (and instructions link) etc.
745 protected function uploadLinksBox() {
746 global $wgEnableUploads;
748 if ( !$wgEnableUploads ) {
753 if ( !$this->mPage
->getFile()->isLocal() ) {
757 $out = $this->getContext()->getOutput();
758 $out->addHTML( "<ul>\n" );
760 # "Upload a new version of this file" link
761 $canUpload = $this->getTitle()->quickUserCan( 'upload', $this->getContext()->getUser() );
762 if ( $canUpload && UploadBase
::userCanReUpload(
763 $this->getContext()->getUser(),
764 $this->mPage
->getFile() )
766 $ulink = Linker
::makeExternalLink(
767 $this->getUploadUrl(),
768 $this->getContext()->msg( 'uploadnewversion-linktext' )->text()
770 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\">"
771 . "<div class=\"plainlinks\">{$ulink}</div></li>\n" );
773 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">"
774 . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
777 $out->addHTML( "</ul>\n" );
783 protected function closeShowImage() {
787 * If the page we've just displayed is in the "Image" namespace,
788 * we follow it with an upload history of the image and its usage.
790 protected function imageHistory() {
792 $out = $this->getContext()->getOutput();
793 $pager = new ImageHistoryPseudoPager( $this );
794 $out->addHTML( $pager->getBody() );
795 $out->preventClickjacking( $pager->getPreventClickjacking() );
797 $this->mPage
->getFile()->resetHistory(); // free db resources
799 # Exist check because we don't want to show this on pages where an image
800 # doesn't exist along with the noimage message, that would suck. -ævar
801 if ( $this->mPage
->getFile()->exists() ) {
802 $this->uploadLinksBox();
807 * @param string $target
809 * @return ResultWrapper
811 protected function queryImageLinks( $target, $limit ) {
812 $dbr = wfGetDB( DB_SLAVE
);
815 [ 'imagelinks', 'page' ],
816 [ 'page_namespace', 'page_title', 'il_to' ],
817 [ 'il_to' => $target, 'il_from = page_id' ],
819 [ 'LIMIT' => $limit +
1, 'ORDER BY' => 'il_from', ]
823 protected function imageLinks() {
826 $out = $this->getContext()->getOutput();
830 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE
) as $redir ) {
831 $redirects[$redir->getDBkey()] = [];
833 'page_namespace' => NS_FILE
,
834 'page_title' => $redir->getDBkey(),
838 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit +
1 );
839 foreach ( $res as $row ) {
842 $count = count( $rows );
844 $hasMore = $count > $limit;
845 if ( !$hasMore && count( $redirects ) ) {
846 $res = $this->queryImageLinks( array_keys( $redirects ),
847 $limit - count( $rows ) +
1 );
848 foreach ( $res as $row ) {
849 $redirects[$row->il_to
][] = $row;
852 $hasMore = ( $res->numRows() +
count( $rows ) ) > $limit;
857 Html
::rawElement( 'div',
858 [ 'id' => 'mw-imagepage-nolinkstoimage' ], "\n$1\n" ),
864 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
866 $out->addWikiMsg( 'linkstoimage', $count );
868 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
869 $out->addWikiMsg( 'linkstoimage-more',
870 $this->getContext()->getLanguage()->formatNum( $limit ),
871 $this->getTitle()->getPrefixedDBkey()
876 Html
::openElement( 'ul',
877 [ 'class' => 'mw-imagepage-linkstoimage' ] ) . "\n"
881 // Sort the list by namespace:title
882 usort( $rows, [ $this, 'compare' ] );
884 // Create links for every element
886 foreach ( $rows as $element ) {
888 if ( $currentCount > $limit ) {
893 # Add a redirect=no to make redirect pages reachable
894 if ( isset( $redirects[$element->page_title
] ) ) {
895 $query['redirect'] = 'no';
897 $link = Linker
::linkKnown(
898 Title
::makeTitle( $element->page_namespace
, $element->page_title
),
901 if ( !isset( $redirects[$element->page_title
] ) ) {
904 } elseif ( count( $redirects[$element->page_title
] ) === 0 ) {
905 # Redirect without usages
906 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )
907 ->rawParams( $link, '' )
910 # Redirect with usages
912 foreach ( $redirects[$element->page_title
] as $row ) {
914 if ( $currentCount > $limit ) {
918 $link2 = Linker
::linkKnown( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
919 $li .= Html
::rawElement(
921 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
],
926 $ul = Html
::rawElement(
928 [ 'class' => 'mw-imagepage-redirectstofile' ],
931 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
932 $link, $ul )->parse();
934 $out->addHTML( Html
::rawElement(
936 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
],
942 $out->addHTML( Html
::closeElement( 'ul' ) . "\n" );
945 // Add a links to [[Special:Whatlinkshere]]
946 if ( $count > $limit ) {
947 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
949 $out->addHTML( Html
::closeElement( 'div' ) . "\n" );
952 protected function imageDupes() {
954 $out = $this->getContext()->getOutput();
956 $dupes = $this->mPage
->getDuplicates();
957 if ( count( $dupes ) == 0 ) {
961 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
962 $out->addWikiMsg( 'duplicatesoffile',
963 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
965 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
970 foreach ( $dupes as $file ) {
972 if ( $file->isLocal() ) {
973 $link = Linker
::linkKnown( $file->getTitle() );
975 $link = Linker
::makeExternalLink( $file->getDescriptionUrl(),
976 $file->getTitle()->getPrefixedText() );
977 $fromSrc = $this->getContext()->msg(
979 $file->getRepo()->getDisplayName()
982 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
984 $out->addHTML( "</ul></div>\n" );
988 * Delete the file, or an earlier version of it
990 public function delete() {
991 $file = $this->mPage
->getFile();
992 if ( !$file->exists() ||
!$file->isLocal() ||
$file->getRedirected() ) {
993 // Standard article deletion
998 $deleter = new FileDeleteForm( $file );
1003 * Display an error with a wikitext description
1005 * @param string $description
1007 function showError( $description ) {
1008 $out = $this->getContext()->getOutput();
1009 $out->setPageTitle( $this->getContext()->msg( 'internalerror' ) );
1010 $out->setRobotPolicy( 'noindex,nofollow' );
1011 $out->setArticleRelated( false );
1012 $out->enableClientCache( false );
1013 $out->addWikiText( $description );
1017 * Callback for usort() to do link sorts by (namespace, title)
1018 * Function copied from Title::compare()
1020 * @param object $a Object page to compare with
1021 * @param object $b Object page to compare with
1022 * @return int Result of string comparison, or namespace comparison
1024 protected function compare( $a, $b ) {
1025 if ( $a->page_namespace
== $b->page_namespace
) {
1026 return strcmp( $a->page_title
, $b->page_title
);
1028 return $a->page_namespace
- $b->page_namespace
;
1033 * Returns the corresponding $wgImageLimits entry for the selected user option
1036 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
1040 public function getImageLimitsFromOption( $user, $optionName ) {
1041 global $wgImageLimits;
1043 $option = $user->getIntOption( $optionName );
1044 if ( !isset( $wgImageLimits[$option] ) ) {
1045 $option = User
::getDefaultOption( $optionName );
1048 // The user offset might still be incorrect, specially if
1049 // $wgImageLimits got changed (see bug #8858).
1050 if ( !isset( $wgImageLimits[$option] ) ) {
1051 // Default to the first offset in $wgImageLimits
1055 return isset( $wgImageLimits[$option] )
1056 ?
$wgImageLimits[$option]
1057 : [ 800, 600 ]; // if nothing is set, fallback to a hardcoded default
1061 * Output a drop-down box for language options for the file
1063 * @param array $langChoices Array of string language codes
1064 * @param string $curLang Language code file is being viewed in.
1065 * @param string $defaultLang Language code that image is rendered in by default
1066 * @return string HTML to insert underneath image.
1068 protected function doRenderLangOpt( array $langChoices, $curLang, $defaultLang ) {
1070 sort( $langChoices );
1071 $curLang = wfBCP47( $curLang );
1072 $defaultLang = wfBCP47( $defaultLang );
1074 $haveCurrentLang = false;
1075 $haveDefaultLang = false;
1077 // We make a list of all the language choices in the file.
1078 // Additionally if the default language to render this file
1079 // is not included as being in this file (for example, in svgs
1080 // usually the fallback content is the english content) also
1081 // include a choice for that. Last of all, if we're viewing
1082 // the file in a language not on the list, add it as a choice.
1083 foreach ( $langChoices as $lang ) {
1084 $code = wfBCP47( $lang );
1085 $name = Language
::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1086 if ( $name !== '' ) {
1087 $display = $this->getContext()->msg( 'img-lang-opt', $code, $name )->text();
1091 $opts .= "\n" . Xml
::option( $display, $code, $curLang === $code );
1092 if ( $curLang === $code ) {
1093 $haveCurrentLang = true;
1095 if ( $defaultLang === $code ) {
1096 $haveDefaultLang = true;
1099 if ( !$haveDefaultLang ) {
1100 // Its hard to know if the content is really in the default language, or
1101 // if its just unmarked content that could be in any language.
1102 $opts = Xml
::option(
1103 $this->getContext()->msg( 'img-lang-default' )->text(),
1105 $defaultLang === $curLang
1108 if ( !$haveCurrentLang && $defaultLang !== $curLang ) {
1109 $name = Language
::fetchLanguageName( $curLang, $this->getContext()->getLanguage()->getCode() );
1110 if ( $name !== '' ) {
1111 $display = $this->getContext()->msg( 'img-lang-opt', $curLang, $name )->text();
1113 $display = $curLang;
1115 $opts = Xml
::option( $display, $curLang, true ) . $opts;
1118 $select = Html
::rawElement(
1120 [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1123 $submit = Xml
::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1125 $formContents = $this->getContext()->msg( 'img-lang-info' )
1126 ->rawParams( $select, $submit )
1128 $formContents .= Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1130 $langSelectLine = Html
::rawElement( 'div', [ 'id' => 'mw-imglangselector-line' ],
1131 Html
::rawElement( 'form', [ 'action' => $wgScript ], $formContents )
1133 return $langSelectLine;
1137 * Get the width and height to display image at.
1139 * @note This method assumes that it is only called if one
1140 * of the dimensions are bigger than the max, or if the
1141 * image is vectorized.
1143 * @param int $maxWidth Max width to display at
1144 * @param int $maxHeight Max height to display at
1145 * @param int $width Actual width of the image
1146 * @param int $height Actual height of the image
1147 * @throws MWException
1148 * @return array Array (width, height)
1150 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1151 if ( !$maxWidth ||
!$maxHeight ) {
1152 // should never happen
1153 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1156 if ( !$width ||
!$height ) {
1160 # Calculate the thumbnail size.
1161 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1162 // Vectorized image, do nothing.
1163 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1164 # The limiting factor is the width, not the height.
1165 $height = round( $height * $maxWidth / $width );
1167 # Note that $height <= $maxHeight now.
1169 $newwidth = floor( $width * $maxHeight / $height );
1170 $height = round( $height * $newwidth / $width );
1172 # Note that $height <= $maxHeight now, but might not be identical
1173 # because of rounding.
1175 return [ $width, $height ];
1179 * Get alternative thumbnail sizes.
1181 * @note This will only list several alternatives if thumbnails are rendered on 404
1182 * @param int $origWidth Actual width of image
1183 * @param int $origHeight Actual height of image
1184 * @return array An array of [width, height] pairs.
1186 protected function getThumbSizes( $origWidth, $origHeight ) {
1187 global $wgImageLimits;
1188 if ( $this->displayImg
->getRepo()->canTransformVia404() ) {
1189 $thumbSizes = $wgImageLimits;
1190 // Also include the full sized resolution in the list, so
1191 // that users know they can get it. This will link to the
1192 // original file asset if mustRender() === false. In the case
1193 // that we mustRender, some users have indicated that they would
1194 // find it useful to have the full size image in the rendered
1196 $thumbSizes[] = [ $origWidth, $origHeight ];
1198 # Creating thumb links triggers thumbnail generation.
1199 # Just generate the thumb for the current users prefs.
1201 $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' )
1203 if ( !$this->displayImg
->mustRender() ) {
1204 // We can safely include a link to the "full-size" preview,
1205 // without actually rendering.
1206 $thumbSizes[] = [ $origWidth, $origHeight ];
1213 * @see WikiFilePage::getFile
1216 public function getFile() {
1217 return $this->mPage
->getFile();
1221 * @see WikiFilePage::isLocal
1224 public function isLocal() {
1225 return $this->mPage
->isLocal();
1229 * @see WikiFilePage::getDuplicates
1230 * @return array|null
1232 public function getDuplicates() {
1233 return $this->mPage
->getDuplicates();
1237 * @see WikiFilePage::getForeignCategories
1238 * @return TitleArray|Title[]
1240 public function getForeignCategories() {
1241 $this->mPage
->getForeignCategories();