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
{
40 var $mExtraDescription = false;
44 * @return WikiFilePage
46 protected function newPage( Title
$title ) {
47 // Overload mPage with a file-specific page
48 return new WikiFilePage( $title );
52 * Constructor from a page id
53 * @param int $id article ID to load
54 * @return ImagePage|null
56 public static function newFromID( $id ) {
57 $t = Title
::newFromID( $id );
58 # @todo FIXME: Doesn't inherit right
59 return $t == null ?
null : new self( $t );
60 # return $t == null ? null : new static( $t ); // PHP 5.3
67 public function setFile( $file ) {
68 $this->mPage
->setFile( $file );
69 $this->displayImg
= $file;
70 $this->fileLoaded
= true;
73 protected function loadFile() {
74 if ( $this->fileLoaded
) {
77 $this->fileLoaded
= true;
79 $this->displayImg
= $img = false;
80 wfRunHooks( 'ImagePageFindFile', array( $this, &$img, &$this->displayImg
) );
81 if ( !$img ) { // not set by hook?
82 $img = wfFindFile( $this->getTitle() );
84 $img = wfLocalFile( $this->getTitle() );
87 $this->mPage
->setFile( $img );
88 if ( !$this->displayImg
) { // not set by hook?
89 $this->displayImg
= $img;
91 $this->repo
= $img->getRepo();
95 * Handler for action=render
96 * Include body text only; none of the image extras
98 public function render() {
99 $this->getContext()->getOutput()->setArticleBodyOnly( true );
103 public function view() {
106 $out = $this->getContext()->getOutput();
107 $request = $this->getContext()->getRequest();
108 $diff = $request->getVal( 'diff' );
109 $diffOnly = $request->getBool( 'diffonly', $this->getContext()->getUser()->getOption( 'diffonly' ) );
111 if ( $this->getTitle()->getNamespace() != NS_FILE ||
( $diff !== null && $diffOnly ) ) {
118 if ( $this->getTitle()->getNamespace() == NS_FILE
&& $this->mPage
->getFile()->getRedirected() ) {
119 if ( $this->getTitle()->getDBkey() == $this->mPage
->getFile()->getName() ||
$diff !== null ) {
120 // mTitle is the same as the redirect target so ask Article
121 // to perform the redirect for us.
122 $request->setVal( 'diffonly', 'true' );
126 // mTitle is not the same as the redirect target so it is
127 // probably the redirect page itself. Fake the redirect symbol
128 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
129 $out->addHTML( $this->viewRedirect( Title
::makeTitle( NS_FILE
, $this->mPage
->getFile()->getName() ),
130 /* $appendSubtitle */ true, /* $forceKnown */ true ) );
131 $this->mPage
->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
136 if ( $wgShowEXIF && $this->displayImg
->exists() ) {
137 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
138 $formattedMetadata = $this->displayImg
->formatMetadata();
139 $showmeta = $formattedMetadata !== false;
144 if ( !$diff && $this->displayImg
->exists() ) {
145 $out->addHTML( $this->showTOC( $showmeta ) );
149 $this->openShowImage();
152 # No need to display noarticletext, we use our own message, output in openShowImage()
153 if ( $this->mPage
->getID() ) {
154 # NS_FILE is in the user language, but this section (the actual wikitext)
155 # should be in page content language
156 $pageLang = $this->getTitle()->getPageViewLanguage();
157 $out->addHTML( Xml
::openElement( 'div', array( 'id' => 'mw-imagepage-content',
158 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
159 'class' => 'mw-content-' . $pageLang->getDir() ) ) );
163 $out->addHTML( Xml
::closeElement( 'div' ) );
165 # Just need to set the right headers
166 $out->setArticleFlag( true );
167 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
168 $this->mPage
->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
171 # Show shared description, if needed
172 if ( $this->mExtraDescription
) {
173 $fol = wfMessage( 'shareddescriptionfollows' );
174 if ( !$fol->isDisabled() ) {
175 $out->addWikiText( $fol->plain() );
177 $out->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription
. "</div>\n" );
180 $this->closeShowImage();
181 $this->imageHistory();
182 // TODO: Cleanup the following
184 $out->addHTML( Xml
::element( 'h2',
185 array( 'id' => 'filelinks' ),
186 wfMessage( 'imagelinks' )->text() ) . "\n" );
188 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
189 # Yet we return metadata about the target. Definitely an issue in the FileRepo
192 # Allow extensions to add something after the image links
194 wfRunHooks( 'ImagePageAfterImageLinks', array( $this, &$html ) );
196 $out->addHTML( $html );
200 $out->addHTML( Xml
::element(
202 array( 'id' => 'metadata' ),
203 wfMessage( 'metadata' )->text() ) . "\n" );
204 $out->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
205 $out->addModules( array( 'mediawiki.action.view.metadata' ) );
208 // Add remote Filepage.css
209 if ( !$this->repo
->isLocal() ) {
210 $css = $this->repo
->getDescriptionStylesheetUrl();
212 $out->addStyle( $css );
215 // always show the local local Filepage.css, bug 29277
216 $out->addModuleStyles( 'filepage' );
222 public function getDisplayedFile() {
224 return $this->displayImg
;
230 * @param $metadata Boolean: whether or not to show the metadata link
233 protected function showTOC( $metadata ) {
235 '<li><a href="#file">' . wfMessage( 'file-anchor-link' )->escaped() . '</a></li>',
236 '<li><a href="#filehistory">' . wfMessage( 'filehist' )->escaped() . '</a></li>',
237 '<li><a href="#filelinks">' . wfMessage( 'imagelinks' )->escaped() . '</a></li>',
240 $r[] = '<li><a href="#metadata">' . wfMessage( 'metadata' )->escaped() . '</a></li>';
243 wfRunHooks( 'ImagePageShowTOC', array( $this, &$r ) );
245 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
249 * Make a table with metadata to be shown in the output page.
251 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
253 * @param array $metadata the array containing the Exif data
254 * @return String The metadata table. This is treated as Wikitext (!)
256 protected function makeMetadataTable( $metadata ) {
257 $r = "<div class=\"mw-imagepage-section-metadata\">";
258 $r .= wfMessage( 'metadata-help' )->plain();
259 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
260 foreach ( $metadata as $type => $stuff ) {
261 foreach ( $stuff as $v ) {
262 # @todo FIXME: Why is this using escapeId for a class?!
263 $class = Sanitizer
::escapeId( $v['id'] );
264 if ( $type == 'collapsed' ) {
265 // Handled by mediawiki.action.view.metadata module
266 // and skins/common/shared.css.
267 $class .= ' collapsable';
269 $r .= "<tr class=\"$class\">\n";
270 $r .= "<th>{$v['name']}</th>\n";
271 $r .= "<td>{$v['value']}</td>\n</tr>";
274 $r .= "</table>\n</div>\n";
279 * Overloading Article's getContentObject method.
281 * Omit noarticletext if sharedupload; text will be fetched from the
282 * shared upload server if possible.
285 public function getContentObject() {
287 if ( $this->mPage
->getFile() && !$this->mPage
->getFile()->isLocal() && 0 == $this->getID() ) {
290 return parent
::getContentObject();
293 protected function openShowImage() {
294 global $wgImageLimits, $wgEnableUploads, $wgSend404Code;
297 $out = $this->getContext()->getOutput();
298 $user = $this->getContext()->getUser();
299 $lang = $this->getContext()->getLanguage();
300 $dirmark = $lang->getDirMarkEntity();
301 $request = $this->getContext()->getRequest();
303 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
305 $maxHeight = $max[1];
307 if ( $this->displayImg
->exists() ) {
309 $page = $request->getIntOrNull( 'page' );
310 if ( is_null( $page ) ) {
314 $params = array( 'page' => $page );
317 $renderLang = $request->getVal( 'lang' );
318 if ( !is_null( $renderLang ) ) {
319 $handler = $this->displayImg
->getHandler();
320 if ( $handler && $handler->validateParam( 'lang', $renderLang ) ) {
321 $params['lang'] = $renderLang;
327 $width_orig = $this->displayImg
->getWidth( $page );
328 $width = $width_orig;
329 $height_orig = $this->displayImg
->getHeight( $page );
330 $height = $height_orig;
332 $filename = wfEscapeWikiText( $this->displayImg
->getName() );
333 $linktext = $filename;
335 wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this, &$out ) );
337 if ( $this->displayImg
->allowInlineDisplay() ) {
340 # "Download high res version" link below the image
341 # $msgsize = wfMessage( 'file-info-size', $width_orig, $height_orig, Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
342 # We'll show a thumbnail of this image
343 if ( $width > $maxWidth ||
$height > $maxHeight ) {
344 # Calculate the thumbnail size.
345 # First case, the limiting factor is the width, not the height.
346 if ( $width / $height >= $maxWidth / $maxHeight ) { // FIXME: Possible division by 0. bug 36911
347 $height = round( $height * $maxWidth / $width ); // FIXME: Possible division by 0. bug 36911
349 # Note that $height <= $maxHeight now.
351 $newwidth = floor( $width * $maxHeight / $height ); // FIXME: Possible division by 0. bug 36911
352 $height = round( $height * $newwidth / $width ); // FIXME: Possible division by 0. bug 36911
354 # Note that $height <= $maxHeight now, but might not be identical
355 # because of rounding.
357 $linktext = wfMessage( 'show-big-image' )->escaped();
358 if ( $this->displayImg
->getRepo()->canTransformVia404() ) {
359 $thumbSizes = $wgImageLimits;
360 // Also include the full sized resolution in the list, so
361 // that users know they can get it. This will link to the
362 // original file asset if mustRender() === false. In the case
363 // that we mustRender, some users have indicated that they would
364 // find it useful to have the full size image in the rendered
366 $thumbSizes[] = array( $width_orig, $height_orig );
368 # Creating thumb links triggers thumbnail generation.
369 # Just generate the thumb for the current users prefs.
370 $thumbSizes = array( $this->getImageLimitsFromOption( $user, 'thumbsize' ) );
371 if ( !$this->displayImg
->mustRender() ) {
372 // We can safely include a link to the "full-size" preview,
373 // without actually rendering.
374 $thumbSizes[] = array( $width_orig, $height_orig );
377 # Generate thumbnails or thumbnail links as needed...
378 $otherSizes = array();
379 foreach ( $thumbSizes as $size ) {
380 // We include a thumbnail size in the list, if it is
381 // less than or equal to the original size of the image
382 // asset ($width_orig/$height_orig). We also exclude
383 // the current thumbnail's size ($width/$height)
384 // since that is added to the message separately, so
385 // it can be denoted as the current size being shown.
386 if ( $size[0] <= $width_orig && $size[1] <= $height_orig
387 && $size[0] != $width && $size[1] != $height
389 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
391 $otherSizes[] = $sizeLink;
395 $otherSizes = array_unique( $otherSizes );
397 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
398 if ( $sizeLinkBigImagePreview ) {
399 $msgsmall .= wfMessage( 'show-big-image-preview' )->
400 rawParams( $sizeLinkBigImagePreview )->
403 if ( count( $otherSizes ) ) {
405 Html
::rawElement( 'span', array( 'class' => 'mw-filepage-other-resolutions' ),
406 wfMessage( 'show-big-image-other' )->rawParams( $lang->pipeList( $otherSizes ) )->
407 params( count( $otherSizes ) )->parse()
410 } elseif ( $width == 0 && $height == 0 ) {
411 # Some sort of audio file that doesn't have dimensions
412 # Don't output a no hi res message for such a file
414 } elseif ( $this->displayImg
->isVectorized() ) {
415 # For vectorized images, full size is just the frame size
418 # Image is small enough to show full size on image page
419 $msgsmall = wfMessage( 'file-nohires' )->parse();
422 $params['width'] = $width;
423 $params['height'] = $height;
424 $thumbnail = $this->displayImg
->transform( $params );
425 Linker
::processResponsiveImages( $this->displayImg
, $thumbnail, $params );
427 $anchorclose = Html
::rawElement( 'div', array( 'class' => 'mw-filepage-resolutioninfo' ), $msgsmall );
429 $isMulti = $this->displayImg
->isMultipage() && $this->displayImg
->pageCount() > 1;
431 $out->addModules( 'mediawiki.page.image.pagination' );
432 $out->addHTML( '<table class="multipageimage"><tr><td>' );
437 'alt' => $this->displayImg
->getTitle()->getPrefixedText(),
440 $out->addHTML( '<div class="fullImageLink" id="file">' .
441 $thumbnail->toHtml( $options ) .
442 $anchorclose . "</div>\n" );
446 $count = $this->displayImg
->pageCount();
449 $label = $out->parse( wfMessage( 'imgmultipageprev' )->text(), false );
450 $link = Linker
::linkKnown(
454 array( 'page' => $page - 1 )
456 $thumb1 = Linker
::makeThumbLinkObj( $this->getTitle(), $this->displayImg
, $link, $label, 'none',
457 array( 'page' => $page - 1 ) );
462 if ( $page < $count ) {
463 $label = wfMessage( 'imgmultipagenext' )->text();
464 $link = Linker
::linkKnown(
468 array( 'page' => $page +
1 )
470 $thumb2 = Linker
::makeThumbLinkObj( $this->getTitle(), $this->displayImg
, $link, $label, 'none',
471 array( 'page' => $page +
1 ) );
479 'name' => 'pageselector',
480 'action' => $wgScript,
483 for ( $i = 1; $i <= $count; $i++
) {
484 $options[] = Xml
::option( $lang->formatNum( $i ), $i, $i == $page );
486 $select = Xml
::tags( 'select',
487 array( 'id' => 'pageselector', 'name' => 'page' ),
488 implode( "\n", $options ) );
491 '</td><td><div class="multipageimagenavbox">' .
492 Xml
::openElement( 'form', $formParams ) .
493 Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
494 wfMessage( 'imgmultigoto' )->rawParams( $select )->parse() .
495 Xml
::submitButton( wfMessage( 'imgmultigo' )->text() ) .
496 Xml
::closeElement( 'form' ) .
497 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
500 } elseif ( $this->displayImg
->isSafeFile() ) {
501 # if direct link is allowed but it's not a renderable image, show an icon.
502 $icon = $this->displayImg
->iconThumb();
504 $out->addHTML( '<div class="fullImageLink" id="file">' .
505 $icon->toHtml( array( 'file-link' => true ) ) .
509 $longDesc = wfMessage( 'parentheses', $this->displayImg
->getLongDesc() )->text();
511 $medialink = "[[Media:$filename|$linktext]]";
513 if ( !$this->displayImg
->isSafeFile() ) {
514 $warning = wfMessage( 'mediawarning' )->plain();
515 // dirmark is needed here to separate the file name, which
516 // most likely ends in Latin characters, from the description,
517 // which may begin with the file type. In RTL environment
518 // this will get messy.
519 // The dirmark, however, must not be immediately adjacent
520 // to the filename, because it can get copied with it.
522 $out->addWikiText( <<<EOT
523 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
524 <div class="mediaWarning">$warning</div>
528 $out->addWikiText( <<<EOT
529 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
535 $renderLangOptions = $this->displayImg
->getAvailableLanguages();
536 if ( count( $renderLangOptions ) >= 1 ) {
537 $currentLanguage = $renderLang;
538 $defaultLang = $this->displayImg
->getDefaultRenderLanguage();
539 if ( is_null( $currentLanguage ) ) {
540 $currentLanguage = $defaultLang;
542 $out->addHtml( $this->doRenderLangOpt( $renderLangOptions, $currentLanguage, $defaultLang ) );
545 // Add cannot animate thumbnail warning
546 if ( !$this->displayImg
->canAnimateThumbIfAppropriate() ) {
547 // Include the extension so wiki admins can
548 // customize it on a per file-type basis
549 // (aka say things like use format X instead).
550 // additionally have a specific message for
551 // file-no-thumb-animation-gif
552 $ext = $this->displayImg
->getExtension();
553 $noAnimMesg = wfMessageFallback(
554 'file-no-thumb-animation-' . $ext,
555 'file-no-thumb-animation'
558 $out->addWikiText( <<<EOT
559 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
564 if ( !$this->displayImg
->isLocal() ) {
565 $this->printSharedImageText();
568 # Image does not exist
569 if ( !$this->getID() ) {
570 # No article exists either
571 # Show deletion log to be consistent with normal articles
572 LogEventsList
::showLogExtract(
574 array( 'delete', 'move' ),
575 $this->getTitle()->getPrefixedText(),
578 'conds' => array( "log_action != 'revision'" ),
579 'showIfEmpty' => false,
580 'msgKey' => array( 'moveddeleted-notice' )
585 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
586 // Only show an upload link if the user can upload
587 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
589 'filepage-nofile-link',
590 $uploadTitle->getFullURL( array( 'wpDestFile' => $this->mPage
->getFile()->getName() ) )
593 $nofile = 'filepage-nofile';
595 // Note, if there is an image description page, but
596 // no image, then this setRobotPolicy is overridden
597 // by Article::View().
598 $out->setRobotPolicy( 'noindex,nofollow' );
599 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
600 if ( !$this->getID() && $wgSend404Code ) {
601 // If there is no image, no shared image, and no description page,
602 // output a 404, to be consistent with articles.
603 $request->response()->header( 'HTTP/1.1 404 Not Found' );
606 $out->setFileVersion( $this->displayImg
);
610 * Creates an thumbnail of specified size and returns an HTML link to it
611 * @param array $params Scaler parameters
616 private function makeSizeLink( $params, $width, $height ) {
617 $params['width'] = $width;
618 $params['height'] = $height;
619 $thumbnail = $this->displayImg
->transform( $params );
620 if ( $thumbnail && !$thumbnail->isError() ) {
621 return Html
::rawElement( 'a', array(
622 'href' => $thumbnail->getUrl(),
623 'class' => 'mw-thumbnail-link'
624 ), wfMessage( 'show-big-image-size' )->numParams(
625 $thumbnail->getWidth(), $thumbnail->getHeight()
633 * Show a notice that the file is from a shared repository
635 protected function printSharedImageText() {
636 $out = $this->getContext()->getOutput();
639 $descUrl = $this->mPage
->getFile()->getDescriptionUrl();
640 $descText = $this->mPage
->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
642 /* Add canonical to head if there is no local page for this shared file */
643 if ( $descUrl && $this->mPage
->getID() == 0 ) {
644 $out->setCanonicalUrl( $descUrl );
647 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
648 $repo = $this->mPage
->getFile()->getRepo()->getDisplayName();
650 if ( $descUrl && $descText && wfMessage( 'sharedupload-desc-here' )->plain() !== '-' ) {
651 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
652 } elseif ( $descUrl && wfMessage( 'sharedupload-desc-there' )->plain() !== '-' ) {
653 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
655 $out->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
659 $this->mExtraDescription
= $descText;
663 public function getUploadUrl() {
665 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
666 return $uploadTitle->getFullURL( array(
667 'wpDestFile' => $this->mPage
->getFile()->getName(),
673 * Print out the various links at the bottom of the image page, e.g. reupload,
674 * external editing (and instructions link) etc.
676 protected function uploadLinksBox() {
677 global $wgEnableUploads;
679 if ( !$wgEnableUploads ) {
684 if ( !$this->mPage
->getFile()->isLocal() ) {
688 $out = $this->getContext()->getOutput();
689 $out->addHTML( "<ul>\n" );
691 # "Upload a new version of this file" link
692 $canUpload = $this->getTitle()->userCan( 'upload', $this->getContext()->getUser() );
693 if ( $canUpload && UploadBase
::userCanReUpload( $this->getContext()->getUser(), $this->mPage
->getFile()->name
) ) {
694 $ulink = Linker
::makeExternalLink( $this->getUploadUrl(), wfMessage( 'uploadnewversion-linktext' )->text() );
695 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\"><div class=\"plainlinks\">{$ulink}</div></li>\n" );
697 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">" . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
700 $out->addHTML( "</ul>\n" );
703 protected function closeShowImage() { } # For overloading
706 * If the page we've just displayed is in the "Image" namespace,
707 * we follow it with an upload history of the image and its usage.
709 protected function imageHistory() {
711 $out = $this->getContext()->getOutput();
712 $pager = new ImageHistoryPseudoPager( $this );
713 $out->addHTML( $pager->getBody() );
714 $out->preventClickjacking( $pager->getPreventClickjacking() );
716 $this->mPage
->getFile()->resetHistory(); // free db resources
718 # Exist check because we don't want to show this on pages where an image
719 # doesn't exist along with the noimage message, that would suck. -ævar
720 if ( $this->mPage
->getFile()->exists() ) {
721 $this->uploadLinksBox();
728 * @return ResultWrapper
730 protected function queryImageLinks( $target, $limit ) {
731 $dbr = wfGetDB( DB_SLAVE
);
734 array( 'imagelinks', 'page' ),
735 array( 'page_namespace', 'page_title', 'page_is_redirect', 'il_to' ),
736 array( 'il_to' => $target, 'il_from = page_id' ),
738 array( 'LIMIT' => $limit +
1, 'ORDER BY' => 'il_from', )
742 protected function imageLinks() {
745 $out = $this->getContext()->getOutput();
746 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit +
1 );
748 $redirects = array();
749 foreach ( $res as $row ) {
750 if ( $row->page_is_redirect
) {
751 $redirects[$row->page_title
] = array();
755 $count = count( $rows );
757 $hasMore = $count > $limit;
758 if ( !$hasMore && count( $redirects ) ) {
759 $res = $this->queryImageLinks( array_keys( $redirects ),
760 $limit - count( $rows ) +
1 );
761 foreach ( $res as $row ) {
762 $redirects[$row->il_to
][] = $row;
765 $hasMore = ( $res->numRows() +
count( $rows ) ) > $limit;
770 Html
::rawElement( 'div',
771 array( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ),
777 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
779 $out->addWikiMsg( 'linkstoimage', $count );
781 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
782 $out->addWikiMsg( 'linkstoimage-more',
783 $this->getContext()->getLanguage()->formatNum( $limit ),
784 $this->getTitle()->getPrefixedDBkey()
789 Html
::openElement( 'ul',
790 array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n"
794 // Sort the list by namespace:title
795 usort( $rows, array( $this, 'compare' ) );
797 // Create links for every element
799 foreach ( $rows as $element ) {
801 if ( $currentCount > $limit ) {
806 # Add a redirect=no to make redirect pages reachable
807 if ( isset( $redirects[$element->page_title
] ) ) {
808 $query['redirect'] = 'no';
810 $link = Linker
::linkKnown(
811 Title
::makeTitle( $element->page_namespace
, $element->page_title
),
812 null, array(), $query
814 if ( !isset( $redirects[$element->page_title
] ) ) {
817 } elseif ( count( $redirects[$element->page_title
] ) === 0 ) {
818 # Redirect without usages
819 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams( $link, '' )->parse();
821 # Redirect with usages
823 foreach ( $redirects[$element->page_title
] as $row ) {
825 if ( $currentCount > $limit ) {
829 $link2 = Linker
::linkKnown( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
830 $li .= Html
::rawElement(
832 array( 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
),
837 $ul = Html
::rawElement(
839 array( 'class' => 'mw-imagepage-redirectstofile' ),
842 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams(
843 $link, $ul )->parse();
845 $out->addHTML( Html
::rawElement(
847 array( 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
),
853 $out->addHTML( Html
::closeElement( 'ul' ) . "\n" );
856 // Add a links to [[Special:Whatlinkshere]]
857 if ( $count > $limit ) {
858 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
860 $out->addHTML( Html
::closeElement( 'div' ) . "\n" );
863 protected function imageDupes() {
865 $out = $this->getContext()->getOutput();
867 $dupes = $this->mPage
->getDuplicates();
868 if ( count( $dupes ) == 0 ) {
872 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
873 $out->addWikiMsg( 'duplicatesoffile',
874 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
876 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
881 foreach ( $dupes as $file ) {
883 if ( $file->isLocal() ) {
884 $link = Linker
::linkKnown( $file->getTitle() );
886 $link = Linker
::makeExternalLink( $file->getDescriptionUrl(),
887 $file->getTitle()->getPrefixedText() );
888 $fromSrc = wfMessage( 'shared-repo-from', $file->getRepo()->getDisplayName() )->text();
890 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
892 $out->addHTML( "</ul></div>\n" );
896 * Delete the file, or an earlier version of it
898 public function delete() {
899 $file = $this->mPage
->getFile();
900 if ( !$file->exists() ||
!$file->isLocal() ||
$file->getRedirected() ) {
901 // Standard article deletion
906 $deleter = new FileDeleteForm( $file );
911 * Display an error with a wikitext description
913 * @param $description String
915 function showError( $description ) {
916 $out = $this->getContext()->getOutput();
917 $out->setPageTitle( wfMessage( 'internalerror' ) );
918 $out->setRobotPolicy( 'noindex,nofollow' );
919 $out->setArticleRelated( false );
920 $out->enableClientCache( false );
921 $out->addWikiText( $description );
925 * Callback for usort() to do link sorts by (namespace, title)
926 * Function copied from Title::compare()
928 * @param $a object page to compare with
929 * @param $b object page to compare with
930 * @return Integer: result of string comparison, or namespace comparison
932 protected function compare( $a, $b ) {
933 if ( $a->page_namespace
== $b->page_namespace
) {
934 return strcmp( $a->page_title
, $b->page_title
);
936 return $a->page_namespace
- $b->page_namespace
;
941 * Returns the corresponding $wgImageLimits entry for the selected user option
944 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
948 public function getImageLimitsFromOption( $user, $optionName ) {
949 global $wgImageLimits;
951 $option = $user->getIntOption( $optionName );
952 if ( !isset( $wgImageLimits[$option] ) ) {
953 $option = User
::getDefaultOption( $optionName );
956 // The user offset might still be incorrect, specially if
957 // $wgImageLimits got changed (see bug #8858).
958 if ( !isset( $wgImageLimits[$option] ) ) {
959 // Default to the first offset in $wgImageLimits
963 return isset( $wgImageLimits[$option] )
964 ?
$wgImageLimits[$option]
965 : array( 800, 600 ); // if nothing is set, fallback to a hardcoded default
969 * Output a drop-down box for language options for the file
971 * @param Array $langChoices Array of string language codes
972 * @param String $curLang Language code file is being viewed in.
973 * @param String $defaultLang Language code that image is rendered in by default
974 * @return String HTML to insert underneath image.
976 protected function doRenderLangOpt( array $langChoices, $curLang, $defaultLang ) {
978 sort( $langChoices );
979 $curLang = wfBCP47( $curLang );
980 $defaultLang = wfBCP47( $defaultLang );
982 $haveCurrentLang = false;
983 $haveDefaultLang = false;
985 // We make a list of all the language choices in the file.
986 // Additionally if the default language to render this file
987 // is not included as being in this file (for example, in svgs
988 // usually the fallback content is the english content) also
989 // include a choice for that. Last of all, if we're viewing
990 // the file in a language not on the list, add it as a choice.
991 foreach ( $langChoices as $lang ) {
992 $code = wfBCP47( $lang );
993 $name = Language
::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
994 if ( $name !== '' ) {
995 $display = wfMessage( 'img-lang-opt', $code, $name )->text();
999 $opts .= "\n" . Xml
::option( $display, $code, $curLang === $code );
1000 if ( $curLang === $code ) {
1001 $haveCurrentLang = true;
1003 if ( $defaultLang === $code ) {
1004 $haveDefaultLang = true;
1007 if ( !$haveDefaultLang ) {
1008 // Its hard to know if the content is really in the default language, or
1009 // if its just unmarked content that could be in any language.
1010 $opts = Xml
::option( wfMessage( 'img-lang-default' )->text(), $defaultLang, $defaultLang === $curLang ) . $opts;
1012 if ( !$haveCurrentLang && $defaultLang !== $curLang ) {
1013 $name = Language
::fetchLanguageName( $curLang, $this->getContext()->getLanguage()->getCode() );
1014 if ( $name !== '' ) {
1015 $display = wfMessage( 'img-lang-opt', $curLang, $name )->text();
1017 $display = $curLang;
1019 $opts = Xml
::option( $display, $curLang, true ) . $opts;
1022 $select = Html
::rawElement( 'select', array( 'id' => 'mw-imglangselector', 'name' => 'lang' ), $opts );
1023 $submit = Xml
::submitButton( wfMessage( 'img-lang-go' )->text() );
1025 $formContents = wfMessage( 'img-lang-info' )->rawParams( $select, $submit )->parse()
1026 . Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1028 $langSelectLine = Html
::rawElement( 'div', array( 'id' => 'mw-imglangselector-line' ),
1029 Html
::rawElement( 'form', array( 'action' => $wgScript ), $formContents )
1031 return $langSelectLine;
1036 * Builds the image revision log shown on image pages
1040 class ImageHistoryList
extends ContextSource
{
1055 protected $imagePage;
1062 protected $repo, $showThumb;
1063 protected $preventClickjacking = false;
1066 * @param ImagePage $imagePage
1068 public function __construct( $imagePage ) {
1069 global $wgShowArchiveThumbnails;
1070 $this->current
= $imagePage->getFile();
1071 $this->img
= $imagePage->getDisplayedFile();
1072 $this->title
= $imagePage->getTitle();
1073 $this->imagePage
= $imagePage;
1074 $this->showThumb
= $wgShowArchiveThumbnails && $this->img
->canRender();
1075 $this->setContext( $imagePage->getContext() );
1081 public function getImagePage() {
1082 return $this->imagePage
;
1088 public function getFile() {
1093 * @param $navLinks string
1096 public function beginImageHistoryList( $navLinks = '' ) {
1097 return Xml
::element( 'h2', array( 'id' => 'filehistory' ), $this->msg( 'filehist' )->text() ) . "\n"
1098 . "<div id=\"mw-imagepage-section-filehistory\">\n"
1099 . $this->msg( 'filehist-help' )->parseAsBlock()
1101 . Xml
::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
1103 . ( $this->current
->isLocal() && ( $this->getUser()->isAllowedAny( 'delete', 'deletedhistory' ) ) ?
'<td></td>' : '' )
1104 . '<th>' . $this->msg( 'filehist-datetime' )->escaped() . '</th>'
1105 . ( $this->showThumb ?
'<th>' . $this->msg( 'filehist-thumb' )->escaped() . '</th>' : '' )
1106 . '<th>' . $this->msg( 'filehist-dimensions' )->escaped() . '</th>'
1107 . '<th>' . $this->msg( 'filehist-user' )->escaped() . '</th>'
1108 . '<th>' . $this->msg( 'filehist-comment' )->escaped() . '</th>'
1113 * @param $navLinks string
1116 public function endImageHistoryList( $navLinks = '' ) {
1117 return "</table>\n$navLinks\n</div>\n";
1125 public function imageHistoryLine( $iscur, $file ) {
1128 $user = $this->getUser();
1129 $lang = $this->getLanguage();
1130 $timestamp = wfTimestamp( TS_MW
, $file->getTimestamp() );
1131 $img = $iscur ?
$file->getName() : $file->getArchiveName();
1132 $userId = $file->getUser( 'id' );
1133 $userText = $file->getUser( 'text' );
1134 $description = $file->getDescription( File
::FOR_THIS_USER
, $user );
1136 $local = $this->current
->isLocal();
1137 $row = $selected = '';
1140 if ( $local && ( $user->isAllowedAny( 'delete', 'deletedhistory' ) ) ) {
1142 # Link to remove from history
1143 if ( $user->isAllowed( 'delete' ) ) {
1144 $q = array( 'action' => 'delete' );
1146 $q['oldimage'] = $img;
1148 $row .= Linker
::linkKnown(
1150 $this->msg( $iscur ?
'filehist-deleteall' : 'filehist-deleteone' )->escaped(),
1154 # Link to hide content. Don't show useless link to people who cannot hide revisions.
1155 $canHide = $user->isAllowed( 'deleterevision' );
1156 if ( $canHide ||
( $user->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
1157 if ( $user->isAllowed( 'delete' ) ) {
1160 // If file is top revision or locked from this user, don't link
1161 if ( $iscur ||
!$file->userCan( File
::DELETED_RESTRICTED
, $user ) ) {
1162 $del = Linker
::revDeleteLinkDisabled( $canHide );
1164 list( $ts, ) = explode( '!', $img, 2 );
1166 'type' => 'oldimage',
1167 'target' => $this->title
->getPrefixedText(),
1170 $del = Linker
::revDeleteLink( $query,
1171 $file->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
1178 // Reversion link/current indicator
1181 $row .= $this->msg( 'filehist-current' )->escaped();
1182 } elseif ( $local && $this->title
->quickUserCan( 'edit', $user )
1183 && $this->title
->quickUserCan( 'upload', $user )
1185 if ( $file->isDeleted( File
::DELETED_FILE
) ) {
1186 $row .= $this->msg( 'filehist-revert' )->escaped();
1188 $row .= Linker
::linkKnown(
1190 $this->msg( 'filehist-revert' )->escaped(),
1193 'action' => 'revert',
1195 'wpEditToken' => $user->getEditToken( $img )
1202 // Date/time and image link
1203 if ( $file->getTimestamp() === $this->img
->getTimestamp() ) {
1204 $selected = "class='filehistory-selected'";
1206 $row .= "<td $selected style='white-space: nowrap;'>";
1207 if ( !$file->userCan( File
::DELETED_FILE
, $user ) ) {
1208 # Don't link to unviewable files
1209 $row .= '<span class="history-deleted">' . $lang->userTimeAndDate( $timestamp, $user ) . '</span>';
1210 } elseif ( $file->isDeleted( File
::DELETED_FILE
) ) {
1212 $this->preventClickjacking();
1213 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
1214 # Make a link to review the image
1215 $url = Linker
::linkKnown(
1217 $lang->userTimeAndDate( $timestamp, $user ),
1220 'target' => $this->title
->getPrefixedText(),
1222 'token' => $user->getEditToken( $img )
1226 $url = $lang->userTimeAndDate( $timestamp, $user );
1228 $row .= '<span class="history-deleted">' . $url . '</span>';
1230 $url = $iscur ?
$this->current
->getUrl() : $this->current
->getArchiveUrl( $img );
1231 $row .= Xml
::element( 'a', array( 'href' => $url ), $lang->userTimeAndDate( $timestamp, $user ) );
1236 if ( $this->showThumb
) {
1237 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1240 // Image dimensions + size
1242 $row .= htmlspecialchars( $file->getDimensionsString() );
1243 $row .= $this->msg( 'word-separator' )->plain();
1244 $row .= '<span style="white-space: nowrap;">';
1245 $row .= $this->msg( 'parentheses' )->rawParams( Linker
::formatSize( $file->getSize() ) )->plain();
1251 // Hide deleted usernames
1252 if ( $file->isDeleted( File
::DELETED_USER
) ) {
1253 $row .= '<span class="history-deleted">' . $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
1256 $row .= Linker
::userLink( $userId, $userText );
1257 $row .= $this->msg( 'word-separator' )->plain();
1258 $row .= '<span style="white-space: nowrap;">';
1259 $row .= Linker
::userToolLinks( $userId, $userText );
1262 $row .= htmlspecialchars( $userText );
1267 // Don't show deleted descriptions
1268 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
1269 $row .= '<td><span class="history-deleted">' . $this->msg( 'rev-deleted-comment' )->escaped() . '</span></td>';
1271 $row .= '<td dir="' . $wgContLang->getDir() . '">' . Linker
::formatComment( $description, $this->title
) . '</td>';
1275 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1276 $classAttr = $rowClass ?
" class='$rowClass'" : '';
1278 return "<tr{$classAttr}>{$row}</tr>\n";
1285 protected function getThumbForLine( $file ) {
1286 $lang = $this->getLanguage();
1287 $user = $this->getUser();
1288 if ( $file->allowInlineDisplay() && $file->userCan( File
::DELETED_FILE
, $user )
1289 && !$file->isDeleted( File
::DELETED_FILE
)
1295 $timestamp = wfTimestamp( TS_MW
, $file->getTimestamp() );
1297 $thumbnail = $file->transform( $params );
1299 'alt' => $this->msg( 'filehist-thumbtext',
1300 $lang->userTimeAndDate( $timestamp, $user ),
1301 $lang->userDate( $timestamp, $user ),
1302 $lang->userTime( $timestamp, $user ) )->text(),
1303 'file-link' => true,
1306 if ( !$thumbnail ) {
1307 return $this->msg( 'filehist-nothumb' )->escaped();
1310 return $thumbnail->toHtml( $options );
1312 return $this->msg( 'filehist-nothumb' )->escaped();
1317 * @param $enable bool
1319 protected function preventClickjacking( $enable = true ) {
1320 $this->preventClickjacking
= $enable;
1326 public function getPreventClickjacking() {
1327 return $this->preventClickjacking
;
1331 class ImageHistoryPseudoPager
extends ReverseChronologicalPager
{
1332 protected $preventClickjacking = false;
1345 * @param ImagePage $imagePage
1347 function __construct( $imagePage ) {
1348 parent
::__construct( $imagePage->getContext() );
1349 $this->mImagePage
= $imagePage;
1350 $this->mTitle
= clone ( $imagePage->getTitle() );
1351 $this->mTitle
->setFragment( '#filehistory' );
1353 $this->mHist
= array();
1354 $this->mRange
= array( 0, 0 ); // display range
1360 function getTitle() {
1361 return $this->mTitle
;
1364 function getQueryInfo() {
1371 function getIndexField() {
1376 * @param $row object
1379 function formatRow( $row ) {
1386 function getBody() {
1389 if ( count( $this->mHist
) ) {
1390 $list = new ImageHistoryList( $this->mImagePage
);
1391 # Generate prev/next links
1392 $navLink = $this->getNavigationBar();
1393 $s = $list->beginImageHistoryList( $navLink );
1394 // Skip rows there just for paging links
1395 for ( $i = $this->mRange
[0]; $i <= $this->mRange
[1]; $i++
) {
1396 $file = $this->mHist
[$i];
1397 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1399 $s .= $list->endImageHistoryList( $navLink );
1401 if ( $list->getPreventClickjacking() ) {
1402 $this->preventClickjacking();
1408 function doQuery() {
1409 if ( $this->mQueryDone
) {
1412 $this->mImg
= $this->mImagePage
->getFile(); // ensure loading
1413 if ( !$this->mImg
->exists() ) {
1416 $queryLimit = $this->mLimit +
1; // limit plus extra row
1417 if ( $this->mIsBackwards
) {
1418 // Fetch the file history
1419 $this->mHist
= $this->mImg
->getHistory( $queryLimit, null, $this->mOffset
, false );
1420 // The current rev may not meet the offset/limit
1421 $numRows = count( $this->mHist
);
1422 if ( $numRows <= $this->mLimit
&& $this->mImg
->getTimestamp() > $this->mOffset
) {
1423 $this->mHist
= array_merge( array( $this->mImg
), $this->mHist
);
1426 // The current rev may not meet the offset
1427 if ( !$this->mOffset ||
$this->mImg
->getTimestamp() < $this->mOffset
) {
1428 $this->mHist
[] = $this->mImg
;
1430 // Old image versions (fetch extra row for nav links)
1431 $oiLimit = count( $this->mHist
) ?
$this->mLimit
: $this->mLimit +
1;
1432 // Fetch the file history
1433 $this->mHist
= array_merge( $this->mHist
,
1434 $this->mImg
->getHistory( $oiLimit, $this->mOffset
, null, false ) );
1436 $numRows = count( $this->mHist
); // Total number of query results
1438 # Index value of top item in the list
1439 $firstIndex = $this->mIsBackwards ?
1440 $this->mHist
[$numRows - 1]->getTimestamp() : $this->mHist
[0]->getTimestamp();
1441 # Discard the extra result row if there is one
1442 if ( $numRows > $this->mLimit
&& $numRows > 1 ) {
1443 if ( $this->mIsBackwards
) {
1444 # Index value of item past the index
1445 $this->mPastTheEndIndex
= $this->mHist
[0]->getTimestamp();
1446 # Index value of bottom item in the list
1447 $lastIndex = $this->mHist
[1]->getTimestamp();
1449 $this->mRange
= array( 1, $numRows - 1 );
1451 # Index value of item past the index
1452 $this->mPastTheEndIndex
= $this->mHist
[$numRows - 1]->getTimestamp();
1453 # Index value of bottom item in the list
1454 $lastIndex = $this->mHist
[$numRows - 2]->getTimestamp();
1456 $this->mRange
= array( 0, $numRows - 2 );
1459 # Setting indexes to an empty string means that they will be
1460 # omitted if they would otherwise appear in URLs. It just so
1461 # happens that this is the right thing to do in the standard
1462 # UI, in all the relevant cases.
1463 $this->mPastTheEndIndex
= '';
1464 # Index value of bottom item in the list
1465 $lastIndex = $this->mIsBackwards ?
1466 $this->mHist
[0]->getTimestamp() : $this->mHist
[$numRows - 1]->getTimestamp();
1468 $this->mRange
= array( 0, $numRows - 1 );
1473 $this->mPastTheEndIndex
= '';
1475 if ( $this->mIsBackwards
) {
1476 $this->mIsFirst
= ( $numRows < $queryLimit );
1477 $this->mIsLast
= ( $this->mOffset
== '' );
1478 $this->mLastShown
= $firstIndex;
1479 $this->mFirstShown
= $lastIndex;
1481 $this->mIsFirst
= ( $this->mOffset
== '' );
1482 $this->mIsLast
= ( $numRows < $queryLimit );
1483 $this->mLastShown
= $lastIndex;
1484 $this->mFirstShown
= $firstIndex;
1486 $this->mQueryDone
= true;
1490 * @param $enable bool
1492 protected function preventClickjacking( $enable = true ) {
1493 $this->preventClickjacking
= $enable;
1499 public function getPreventClickjacking() {
1500 return $this->preventClickjacking
;