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 );
226 $out->addModuleStyles( [
227 'filepage', // always show the local local Filepage.css, bug 29277
228 'mediawiki.action.view.filepage', // Add MediaWiki styles for a file page
236 public function getDisplayedFile() {
238 return $this->displayImg
;
244 * @param bool $metadata Whether or not to show the metadata link
247 protected function showTOC( $metadata ) {
249 '<li><a href="#file">' . $this->getContext()->msg( 'file-anchor-link' )->escaped() . '</a></li>',
250 '<li><a href="#filehistory">' . $this->getContext()->msg( 'filehist' )->escaped() . '</a></li>',
251 '<li><a href="#filelinks">' . $this->getContext()->msg( 'imagelinks' )->escaped() . '</a></li>',
254 Hooks
::run( 'ImagePageShowTOC', [ $this, &$r ] );
257 $r[] = '<li><a href="#metadata">' .
258 $this->getContext()->msg( 'metadata' )->escaped() .
262 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
266 * Make a table with metadata to be shown in the output page.
268 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
270 * @param array $metadata The array containing the Exif data
271 * @return string The metadata table. This is treated as Wikitext (!)
273 protected function makeMetadataTable( $metadata ) {
274 $r = "<div class=\"mw-imagepage-section-metadata\">";
275 $r .= $this->getContext()->msg( 'metadata-help' )->plain();
276 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
277 foreach ( $metadata as $type => $stuff ) {
278 foreach ( $stuff as $v ) {
279 # @todo FIXME: Why is this using escapeId for a class?!
280 $class = Sanitizer
::escapeId( $v['id'] );
281 if ( $type == 'collapsed' ) {
282 // Handled by mediawiki.action.view.metadata module.
283 $class .= ' collapsable';
285 $r .= "<tr class=\"$class\">\n";
286 $r .= "<th>{$v['name']}</th>\n";
287 $r .= "<td>{$v['value']}</td>\n</tr>";
290 $r .= "</table>\n</div>\n";
295 * Overloading Article's getContentObject method.
297 * Omit noarticletext if sharedupload; text will be fetched from the
298 * shared upload server if possible.
301 public function getContentObject() {
303 if ( $this->mPage
->getFile() && !$this->mPage
->getFile()->isLocal() && 0 == $this->getId() ) {
306 return parent
::getContentObject();
309 protected function openShowImage() {
310 global $wgEnableUploads, $wgSend404Code, $wgSVGMaxSize;
313 $out = $this->getContext()->getOutput();
314 $user = $this->getContext()->getUser();
315 $lang = $this->getContext()->getLanguage();
316 $dirmark = $lang->getDirMarkEntity();
317 $request = $this->getContext()->getRequest();
319 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
321 $maxHeight = $max[1];
323 if ( $this->displayImg
->exists() ) {
325 $page = $request->getIntOrNull( 'page' );
326 if ( is_null( $page ) ) {
330 $params = [ 'page' => $page ];
333 $renderLang = $request->getVal( 'lang' );
334 if ( !is_null( $renderLang ) ) {
335 $handler = $this->displayImg
->getHandler();
336 if ( $handler && $handler->validateParam( 'lang', $renderLang ) ) {
337 $params['lang'] = $renderLang;
343 $width_orig = $this->displayImg
->getWidth( $page );
344 $width = $width_orig;
345 $height_orig = $this->displayImg
->getHeight( $page );
346 $height = $height_orig;
348 $filename = wfEscapeWikiText( $this->displayImg
->getName() );
349 $linktext = $filename;
351 Hooks
::run( 'ImageOpenShowImageInlineBefore', [ &$this, &$out ] );
353 if ( $this->displayImg
->allowInlineDisplay() ) {
355 # "Download high res version" link below the image
356 # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
357 # Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
358 # We'll show a thumbnail of this image
359 if ( $width > $maxWidth ||
$height > $maxHeight ||
$this->displayImg
->isVectorized() ) {
360 list( $width, $height ) = $this->getDisplayWidthHeight(
361 $maxWidth, $maxHeight, $width, $height
363 $linktext = $this->getContext()->msg( 'show-big-image' )->escaped();
365 $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
366 # Generate thumbnails or thumbnail links as needed...
368 foreach ( $thumbSizes as $size ) {
369 // We include a thumbnail size in the list, if it is
370 // less than or equal to the original size of the image
371 // asset ($width_orig/$height_orig). We also exclude
372 // the current thumbnail's size ($width/$height)
373 // since that is added to the message separately, so
374 // it can be denoted as the current size being shown.
375 // Vectorized images are limited by $wgSVGMaxSize big,
376 // so all thumbs less than or equal that are shown.
377 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
378 ||
( $this->displayImg
->isVectorized()
379 && max( $size[0], $size[1] ) <= $wgSVGMaxSize )
381 && $size[0] != $width && $size[1] != $height
383 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
385 $otherSizes[] = $sizeLink;
389 $otherSizes = array_unique( $otherSizes );
391 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
392 $msgsmall = $this->getThumbPrevText( $params, $sizeLinkBigImagePreview );
393 if ( count( $otherSizes ) ) {
397 [ 'class' => 'mw-filepage-other-resolutions' ],
398 $this->getContext()->msg( 'show-big-image-other' )
399 ->rawParams( $lang->pipeList( $otherSizes ) )
400 ->params( count( $otherSizes ) )
404 } elseif ( $width == 0 && $height == 0 ) {
405 # Some sort of audio file that doesn't have dimensions
406 # Don't output a no hi res message for such a file
409 # Image is small enough to show full size on image page
410 $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
413 $params['width'] = $width;
414 $params['height'] = $height;
415 $thumbnail = $this->displayImg
->transform( $params );
416 Linker
::processResponsiveImages( $this->displayImg
, $thumbnail, $params );
418 $anchorclose = Html
::rawElement(
420 [ 'class' => 'mw-filepage-resolutioninfo' ],
424 $isMulti = $this->displayImg
->isMultipage() && $this->displayImg
->pageCount() > 1;
426 $out->addModules( 'mediawiki.page.image.pagination' );
427 $out->addHTML( '<table class="multipageimage"><tr><td>' );
432 'alt' => $this->displayImg
->getTitle()->getPrefixedText(),
435 $out->addHTML( '<div class="fullImageLink" id="file">' .
436 $thumbnail->toHtml( $options ) .
437 $anchorclose . "</div>\n" );
441 $count = $this->displayImg
->pageCount();
444 $label = $out->parse( $this->getContext()->msg( 'imgmultipageprev' )->text(), false );
445 // on the client side, this link is generated in ajaxifyPageNavigation()
446 // in the mediawiki.page.image.pagination module
447 $link = Linker
::linkKnown(
451 [ 'page' => $page - 1 ]
453 $thumb1 = Linker
::makeThumbLinkObj(
459 [ 'page' => $page - 1 ]
465 if ( $page < $count ) {
466 $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
467 $link = Linker
::linkKnown(
471 [ 'page' => $page +
1 ]
473 $thumb2 = Linker
::makeThumbLinkObj(
479 [ 'page' => $page +
1 ]
488 'name' => 'pageselector',
489 'action' => $wgScript,
492 for ( $i = 1; $i <= $count; $i++
) {
493 $options[] = Xml
::option( $lang->formatNum( $i ), $i, $i == $page );
495 $select = Xml
::tags( 'select',
496 [ 'id' => 'pageselector', 'name' => 'page' ],
497 implode( "\n", $options ) );
500 '</td><td><div class="multipageimagenavbox">' .
501 Xml
::openElement( 'form', $formParams ) .
502 Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
503 $this->getContext()->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
504 Xml
::submitButton( $this->getContext()->msg( 'imgmultigo' )->text() ) .
505 Xml
::closeElement( 'form' ) .
506 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
509 } elseif ( $this->displayImg
->isSafeFile() ) {
510 # if direct link is allowed but it's not a renderable image, show an icon.
511 $icon = $this->displayImg
->iconThumb();
513 $out->addHTML( '<div class="fullImageLink" id="file">' .
514 $icon->toHtml( [ 'file-link' => true ] ) .
518 $longDesc = $this->getContext()->msg( 'parentheses', $this->displayImg
->getLongDesc() )->text();
520 $handler = $this->displayImg
->getHandler();
522 // If this is a filetype with potential issues, warn the user.
524 $warningConfig = $handler->getWarningConfig( $this->displayImg
);
526 if ( $warningConfig !== null ) {
527 // The warning will be displayed via CSS and JavaScript.
528 // We just need to tell the client side what message to use.
529 $output = $this->getContext()->getOutput();
530 $output->addJsConfigVars( 'wgFileWarning', $warningConfig );
531 $output->addModules( $warningConfig['module'] );
532 $output->addModules( 'mediawiki.filewarning' );
536 $medialink = "[[Media:$filename|$linktext]]";
538 if ( !$this->displayImg
->isSafeFile() ) {
539 $warning = $this->getContext()->msg( 'mediawarning' )->plain();
540 // dirmark is needed here to separate the file name, which
541 // most likely ends in Latin characters, from the description,
542 // which may begin with the file type. In RTL environment
543 // this will get messy.
544 // The dirmark, however, must not be immediately adjacent
545 // to the filename, because it can get copied with it.
547 // @codingStandardsIgnoreStart Ignore long line
548 $out->addWikiText( <<<EOT
549 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
550 <div class="mediaWarning">$warning</div>
553 // @codingStandardsIgnoreEnd
555 $out->addWikiText( <<<EOT
556 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
562 $renderLangOptions = $this->displayImg
->getAvailableLanguages();
563 if ( count( $renderLangOptions ) >= 1 ) {
564 $currentLanguage = $renderLang;
565 $defaultLang = $this->displayImg
->getDefaultRenderLanguage();
566 if ( is_null( $currentLanguage ) ) {
567 $currentLanguage = $defaultLang;
569 $out->addHTML( $this->doRenderLangOpt( $renderLangOptions, $currentLanguage, $defaultLang ) );
572 // Add cannot animate thumbnail warning
573 if ( !$this->displayImg
->canAnimateThumbIfAppropriate() ) {
574 // Include the extension so wiki admins can
575 // customize it on a per file-type basis
576 // (aka say things like use format X instead).
577 // additionally have a specific message for
578 // file-no-thumb-animation-gif
579 $ext = $this->displayImg
->getExtension();
580 $noAnimMesg = wfMessageFallback(
581 'file-no-thumb-animation-' . $ext,
582 'file-no-thumb-animation'
585 $out->addWikiText( <<<EOT
586 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
591 if ( !$this->displayImg
->isLocal() ) {
592 $this->printSharedImageText();
595 # Image does not exist
596 if ( !$this->getId() ) {
597 # No article exists either
598 # Show deletion log to be consistent with normal articles
599 LogEventsList
::showLogExtract(
601 [ 'delete', 'move' ],
602 $this->getTitle()->getPrefixedText(),
605 'conds' => [ "log_action != 'revision'" ],
606 'showIfEmpty' => false,
607 'msgKey' => [ 'moveddeleted-notice' ]
612 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
613 // Only show an upload link if the user can upload
614 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
616 'filepage-nofile-link',
617 $uploadTitle->getFullURL( [ 'wpDestFile' => $this->mPage
->getFile()->getName() ] )
620 $nofile = 'filepage-nofile';
622 // Note, if there is an image description page, but
623 // no image, then this setRobotPolicy is overridden
624 // by Article::View().
625 $out->setRobotPolicy( 'noindex,nofollow' );
626 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
627 if ( !$this->getId() && $wgSend404Code ) {
628 // If there is no image, no shared image, and no description page,
629 // output a 404, to be consistent with Article::showMissingArticle.
630 $request->response()->statusHeader( 404 );
633 $out->setFileVersion( $this->displayImg
);
637 * Make the text under the image to say what size preview
639 * @param $params array parameters for thumbnail
640 * @param $sizeLinkBigImagePreview HTML for the current size
641 * @return string HTML output
643 private function getThumbPrevText( $params, $sizeLinkBigImagePreview ) {
644 if ( $sizeLinkBigImagePreview ) {
645 // Show a different message of preview is different format from original.
646 $previewTypeDiffers = false;
647 $origExt = $thumbExt = $this->displayImg
->getExtension();
648 if ( $this->displayImg
->getHandler() ) {
649 $origMime = $this->displayImg
->getMimeType();
650 $typeParams = $params;
651 $this->displayImg
->getHandler()->normaliseParams( $this->displayImg
, $typeParams );
652 list( $thumbExt, $thumbMime ) = $this->displayImg
->getHandler()->getThumbType(
653 $origExt, $origMime, $typeParams );
654 if ( $thumbMime !== $origMime ) {
655 $previewTypeDiffers = true;
658 if ( $previewTypeDiffers ) {
659 return $this->getContext()->msg( 'show-big-image-preview-differ' )->
660 rawParams( $sizeLinkBigImagePreview )->
661 params( strtoupper( $origExt ) )->
662 params( strtoupper( $thumbExt ) )->
665 return $this->getContext()->msg( 'show-big-image-preview' )->
666 rawParams( $sizeLinkBigImagePreview )->
675 * Creates an thumbnail of specified size and returns an HTML link to it
676 * @param array $params Scaler parameters
681 private function makeSizeLink( $params, $width, $height ) {
682 $params['width'] = $width;
683 $params['height'] = $height;
684 $thumbnail = $this->displayImg
->transform( $params );
685 if ( $thumbnail && !$thumbnail->isError() ) {
686 return Html
::rawElement( 'a', [
687 'href' => $thumbnail->getUrl(),
688 'class' => 'mw-thumbnail-link'
689 ], $this->getContext()->msg( 'show-big-image-size' )->numParams(
690 $thumbnail->getWidth(), $thumbnail->getHeight()
698 * Show a notice that the file is from a shared repository
700 protected function printSharedImageText() {
701 $out = $this->getContext()->getOutput();
704 $descUrl = $this->mPage
->getFile()->getDescriptionUrl();
705 $descText = $this->mPage
->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
707 /* Add canonical to head if there is no local page for this shared file */
708 if ( $descUrl && $this->mPage
->getId() == 0 ) {
709 $out->setCanonicalUrl( $descUrl );
712 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
713 $repo = $this->mPage
->getFile()->getRepo()->getDisplayName();
717 $this->getContext()->msg( 'sharedupload-desc-here' )->plain() !== '-'
719 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-here', $repo, $descUrl ] );
720 } elseif ( $descUrl &&
721 $this->getContext()->msg( 'sharedupload-desc-there' )->plain() !== '-'
723 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-there', $repo, $descUrl ] );
725 $out->wrapWikiMsg( $wrap, [ 'sharedupload', $repo ], ''/*BACKCOMPAT*/ );
729 $this->mExtraDescription
= $descText;
733 public function getUploadUrl() {
735 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
736 return $uploadTitle->getFullURL( [
737 'wpDestFile' => $this->mPage
->getFile()->getName(),
743 * Print out the various links at the bottom of the image page, e.g. reupload,
744 * external editing (and instructions link) etc.
746 protected function uploadLinksBox() {
747 global $wgEnableUploads;
749 if ( !$wgEnableUploads ) {
754 if ( !$this->mPage
->getFile()->isLocal() ) {
758 $out = $this->getContext()->getOutput();
759 $out->addHTML( "<ul>\n" );
761 # "Upload a new version of this file" link
762 $canUpload = $this->getTitle()->quickUserCan( 'upload', $this->getContext()->getUser() );
763 if ( $canUpload && UploadBase
::userCanReUpload(
764 $this->getContext()->getUser(),
765 $this->mPage
->getFile() )
767 $ulink = Linker
::makeExternalLink(
768 $this->getUploadUrl(),
769 $this->getContext()->msg( 'uploadnewversion-linktext' )->text()
771 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\">"
772 . "<div class=\"plainlinks\">{$ulink}</div></li>\n" );
774 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">"
775 . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
778 $out->addHTML( "</ul>\n" );
784 protected function closeShowImage() {
788 * If the page we've just displayed is in the "Image" namespace,
789 * we follow it with an upload history of the image and its usage.
791 protected function imageHistory() {
793 $out = $this->getContext()->getOutput();
794 $pager = new ImageHistoryPseudoPager( $this );
795 $out->addHTML( $pager->getBody() );
796 $out->preventClickjacking( $pager->getPreventClickjacking() );
798 $this->mPage
->getFile()->resetHistory(); // free db resources
800 # Exist check because we don't want to show this on pages where an image
801 # doesn't exist along with the noimage message, that would suck. -ævar
802 if ( $this->mPage
->getFile()->exists() ) {
803 $this->uploadLinksBox();
808 * @param string $target
810 * @return ResultWrapper
812 protected function queryImageLinks( $target, $limit ) {
813 $dbr = wfGetDB( DB_SLAVE
);
816 [ 'imagelinks', 'page' ],
817 [ 'page_namespace', 'page_title', 'il_to' ],
818 [ 'il_to' => $target, 'il_from = page_id' ],
820 [ 'LIMIT' => $limit +
1, 'ORDER BY' => 'il_from', ]
824 protected function imageLinks() {
827 $out = $this->getContext()->getOutput();
831 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE
) as $redir ) {
832 $redirects[$redir->getDBkey()] = [];
834 'page_namespace' => NS_FILE
,
835 'page_title' => $redir->getDBkey(),
839 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit +
1 );
840 foreach ( $res as $row ) {
843 $count = count( $rows );
845 $hasMore = $count > $limit;
846 if ( !$hasMore && count( $redirects ) ) {
847 $res = $this->queryImageLinks( array_keys( $redirects ),
848 $limit - count( $rows ) +
1 );
849 foreach ( $res as $row ) {
850 $redirects[$row->il_to
][] = $row;
853 $hasMore = ( $res->numRows() +
count( $rows ) ) > $limit;
858 Html
::rawElement( 'div',
859 [ 'id' => 'mw-imagepage-nolinkstoimage' ], "\n$1\n" ),
865 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
867 $out->addWikiMsg( 'linkstoimage', $count );
869 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
870 $out->addWikiMsg( 'linkstoimage-more',
871 $this->getContext()->getLanguage()->formatNum( $limit ),
872 $this->getTitle()->getPrefixedDBkey()
877 Html
::openElement( 'ul',
878 [ 'class' => 'mw-imagepage-linkstoimage' ] ) . "\n"
882 // Sort the list by namespace:title
883 usort( $rows, [ $this, 'compare' ] );
885 // Create links for every element
887 foreach ( $rows as $element ) {
889 if ( $currentCount > $limit ) {
894 # Add a redirect=no to make redirect pages reachable
895 if ( isset( $redirects[$element->page_title
] ) ) {
896 $query['redirect'] = 'no';
898 $link = Linker
::linkKnown(
899 Title
::makeTitle( $element->page_namespace
, $element->page_title
),
902 if ( !isset( $redirects[$element->page_title
] ) ) {
905 } elseif ( count( $redirects[$element->page_title
] ) === 0 ) {
906 # Redirect without usages
907 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )
908 ->rawParams( $link, '' )
911 # Redirect with usages
913 foreach ( $redirects[$element->page_title
] as $row ) {
915 if ( $currentCount > $limit ) {
919 $link2 = Linker
::linkKnown( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
920 $li .= Html
::rawElement(
922 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
],
927 $ul = Html
::rawElement(
929 [ 'class' => 'mw-imagepage-redirectstofile' ],
932 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
933 $link, $ul )->parse();
935 $out->addHTML( Html
::rawElement(
937 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
],
943 $out->addHTML( Html
::closeElement( 'ul' ) . "\n" );
946 // Add a links to [[Special:Whatlinkshere]]
947 if ( $count > $limit ) {
948 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
950 $out->addHTML( Html
::closeElement( 'div' ) . "\n" );
953 protected function imageDupes() {
955 $out = $this->getContext()->getOutput();
957 $dupes = $this->mPage
->getDuplicates();
958 if ( count( $dupes ) == 0 ) {
962 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
963 $out->addWikiMsg( 'duplicatesoffile',
964 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
966 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
971 foreach ( $dupes as $file ) {
973 if ( $file->isLocal() ) {
974 $link = Linker
::linkKnown( $file->getTitle() );
976 $link = Linker
::makeExternalLink( $file->getDescriptionUrl(),
977 $file->getTitle()->getPrefixedText() );
978 $fromSrc = $this->getContext()->msg(
980 $file->getRepo()->getDisplayName()
983 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
985 $out->addHTML( "</ul></div>\n" );
989 * Delete the file, or an earlier version of it
991 public function delete() {
992 $file = $this->mPage
->getFile();
993 if ( !$file->exists() ||
!$file->isLocal() ||
$file->getRedirected() ) {
994 // Standard article deletion
999 $deleter = new FileDeleteForm( $file );
1000 $deleter->execute();
1004 * Display an error with a wikitext description
1006 * @param string $description
1008 function showError( $description ) {
1009 $out = $this->getContext()->getOutput();
1010 $out->setPageTitle( $this->getContext()->msg( 'internalerror' ) );
1011 $out->setRobotPolicy( 'noindex,nofollow' );
1012 $out->setArticleRelated( false );
1013 $out->enableClientCache( false );
1014 $out->addWikiText( $description );
1018 * Callback for usort() to do link sorts by (namespace, title)
1019 * Function copied from Title::compare()
1021 * @param object $a Object page to compare with
1022 * @param object $b Object page to compare with
1023 * @return int Result of string comparison, or namespace comparison
1025 protected function compare( $a, $b ) {
1026 if ( $a->page_namespace
== $b->page_namespace
) {
1027 return strcmp( $a->page_title
, $b->page_title
);
1029 return $a->page_namespace
- $b->page_namespace
;
1034 * Returns the corresponding $wgImageLimits entry for the selected user option
1037 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
1041 public function getImageLimitsFromOption( $user, $optionName ) {
1042 global $wgImageLimits;
1044 $option = $user->getIntOption( $optionName );
1045 if ( !isset( $wgImageLimits[$option] ) ) {
1046 $option = User
::getDefaultOption( $optionName );
1049 // The user offset might still be incorrect, specially if
1050 // $wgImageLimits got changed (see bug #8858).
1051 if ( !isset( $wgImageLimits[$option] ) ) {
1052 // Default to the first offset in $wgImageLimits
1056 return isset( $wgImageLimits[$option] )
1057 ?
$wgImageLimits[$option]
1058 : [ 800, 600 ]; // if nothing is set, fallback to a hardcoded default
1062 * Output a drop-down box for language options for the file
1064 * @param array $langChoices Array of string language codes
1065 * @param string $curLang Language code file is being viewed in.
1066 * @param string $defaultLang Language code that image is rendered in by default
1067 * @return string HTML to insert underneath image.
1069 protected function doRenderLangOpt( array $langChoices, $curLang, $defaultLang ) {
1071 sort( $langChoices );
1072 $curLang = wfBCP47( $curLang );
1073 $defaultLang = wfBCP47( $defaultLang );
1075 $haveCurrentLang = false;
1076 $haveDefaultLang = false;
1078 // We make a list of all the language choices in the file.
1079 // Additionally if the default language to render this file
1080 // is not included as being in this file (for example, in svgs
1081 // usually the fallback content is the english content) also
1082 // include a choice for that. Last of all, if we're viewing
1083 // the file in a language not on the list, add it as a choice.
1084 foreach ( $langChoices as $lang ) {
1085 $code = wfBCP47( $lang );
1086 $name = Language
::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1087 if ( $name !== '' ) {
1088 $display = $this->getContext()->msg( 'img-lang-opt', $code, $name )->text();
1092 $opts .= "\n" . Xml
::option( $display, $code, $curLang === $code );
1093 if ( $curLang === $code ) {
1094 $haveCurrentLang = true;
1096 if ( $defaultLang === $code ) {
1097 $haveDefaultLang = true;
1100 if ( !$haveDefaultLang ) {
1101 // Its hard to know if the content is really in the default language, or
1102 // if its just unmarked content that could be in any language.
1103 $opts = Xml
::option(
1104 $this->getContext()->msg( 'img-lang-default' )->text(),
1106 $defaultLang === $curLang
1109 if ( !$haveCurrentLang && $defaultLang !== $curLang ) {
1110 $name = Language
::fetchLanguageName( $curLang, $this->getContext()->getLanguage()->getCode() );
1111 if ( $name !== '' ) {
1112 $display = $this->getContext()->msg( 'img-lang-opt', $curLang, $name )->text();
1114 $display = $curLang;
1116 $opts = Xml
::option( $display, $curLang, true ) . $opts;
1119 $select = Html
::rawElement(
1121 [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1124 $submit = Xml
::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1126 $formContents = $this->getContext()->msg( 'img-lang-info' )
1127 ->rawParams( $select, $submit )
1129 $formContents .= Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1131 $langSelectLine = Html
::rawElement( 'div', [ 'id' => 'mw-imglangselector-line' ],
1132 Html
::rawElement( 'form', [ 'action' => $wgScript ], $formContents )
1134 return $langSelectLine;
1138 * Get the width and height to display image at.
1140 * @note This method assumes that it is only called if one
1141 * of the dimensions are bigger than the max, or if the
1142 * image is vectorized.
1144 * @param int $maxWidth Max width to display at
1145 * @param int $maxHeight Max height to display at
1146 * @param int $width Actual width of the image
1147 * @param int $height Actual height of the image
1148 * @throws MWException
1149 * @return array Array (width, height)
1151 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1152 if ( !$maxWidth ||
!$maxHeight ) {
1153 // should never happen
1154 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1157 if ( !$width ||
!$height ) {
1161 # Calculate the thumbnail size.
1162 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1163 // Vectorized image, do nothing.
1164 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1165 # The limiting factor is the width, not the height.
1166 $height = round( $height * $maxWidth / $width );
1168 # Note that $height <= $maxHeight now.
1170 $newwidth = floor( $width * $maxHeight / $height );
1171 $height = round( $height * $newwidth / $width );
1173 # Note that $height <= $maxHeight now, but might not be identical
1174 # because of rounding.
1176 return [ $width, $height ];
1180 * Get alternative thumbnail sizes.
1182 * @note This will only list several alternatives if thumbnails are rendered on 404
1183 * @param int $origWidth Actual width of image
1184 * @param int $origHeight Actual height of image
1185 * @return array An array of [width, height] pairs.
1187 protected function getThumbSizes( $origWidth, $origHeight ) {
1188 global $wgImageLimits;
1189 if ( $this->displayImg
->getRepo()->canTransformVia404() ) {
1190 $thumbSizes = $wgImageLimits;
1191 // Also include the full sized resolution in the list, so
1192 // that users know they can get it. This will link to the
1193 // original file asset if mustRender() === false. In the case
1194 // that we mustRender, some users have indicated that they would
1195 // find it useful to have the full size image in the rendered
1197 $thumbSizes[] = [ $origWidth, $origHeight ];
1199 # Creating thumb links triggers thumbnail generation.
1200 # Just generate the thumb for the current users prefs.
1202 $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' )
1204 if ( !$this->displayImg
->mustRender() ) {
1205 // We can safely include a link to the "full-size" preview,
1206 // without actually rendering.
1207 $thumbSizes[] = [ $origWidth, $origHeight ];
1214 * @see WikiFilePage::getFile
1217 public function getFile() {
1218 return $this->mPage
->getFile();
1222 * @see WikiFilePage::isLocal
1225 public function isLocal() {
1226 return $this->mPage
->isLocal();
1230 * @see WikiFilePage::getDuplicates
1231 * @return array|null
1233 public function getDuplicates() {
1234 return $this->mPage
->getDuplicates();
1238 * @see WikiFilePage::getForeignCategories
1239 * @return TitleArray|Title[]
1241 public function getForeignCategories() {
1242 $this->mPage
->getForeignCategories();