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 $class .= ' collapsable'; // sic
267 $r .= "<tr class=\"$class\">\n";
268 $r .= "<th>{$v['name']}</th>\n";
269 $r .= "<td>{$v['value']}</td>\n</tr>";
272 $r .= "</table>\n</div>\n";
277 * Overloading Article's getContentObject method.
279 * Omit noarticletext if sharedupload; text will be fetched from the
280 * shared upload server if possible.
283 public function getContentObject() {
285 if ( $this->mPage
->getFile() && !$this->mPage
->getFile()->isLocal() && 0 == $this->getID() ) {
288 return parent
::getContentObject();
291 protected function openShowImage() {
292 global $wgImageLimits, $wgEnableUploads, $wgSend404Code;
295 $out = $this->getContext()->getOutput();
296 $user = $this->getContext()->getUser();
297 $lang = $this->getContext()->getLanguage();
298 $dirmark = $lang->getDirMarkEntity();
299 $request = $this->getContext()->getRequest();
301 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
303 $maxHeight = $max[1];
305 if ( $this->displayImg
->exists() ) {
307 $page = $request->getIntOrNull( 'page' );
308 if ( is_null( $page ) ) {
312 $params = array( 'page' => $page );
315 $renderLang = $request->getVal( 'lang' );
316 if ( !is_null( $renderLang ) ) {
317 $params['lang'] = $renderLang;
320 $width_orig = $this->displayImg
->getWidth( $page );
321 $width = $width_orig;
322 $height_orig = $this->displayImg
->getHeight( $page );
323 $height = $height_orig;
325 $filename = wfEscapeWikiText( $this->displayImg
->getName() );
326 $linktext = $filename;
328 wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this, &$out ) );
330 if ( $this->displayImg
->allowInlineDisplay() ) {
333 # "Download high res version" link below the image
334 # $msgsize = wfMessage( 'file-info-size', $width_orig, $height_orig, Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
335 # We'll show a thumbnail of this image
336 if ( $width > $maxWidth ||
$height > $maxHeight ) {
337 # Calculate the thumbnail size.
338 # First case, the limiting factor is the width, not the height.
339 if ( $width / $height >= $maxWidth / $maxHeight ) { // FIXME: Possible division by 0. bug 36911
340 $height = round( $height * $maxWidth / $width ); // FIXME: Possible division by 0. bug 36911
342 # Note that $height <= $maxHeight now.
344 $newwidth = floor( $width * $maxHeight / $height ); // FIXME: Possible division by 0. bug 36911
345 $height = round( $height * $newwidth / $width ); // FIXME: Possible division by 0. bug 36911
347 # Note that $height <= $maxHeight now, but might not be identical
348 # because of rounding.
350 $linktext = wfMessage( 'show-big-image' )->escaped();
351 if ( $this->displayImg
->getRepo()->canTransformVia404() ) {
352 $thumbSizes = $wgImageLimits;
353 // Also include the full sized resolution in the list, so
354 // that users know they can get it. This will link to the
355 // original file asset if mustRender() === false. In the case
356 // that we mustRender, some users have indicated that they would
357 // find it useful to have the full size image in the rendered
359 $thumbSizes[] = array( $width_orig, $height_orig );
361 # Creating thumb links triggers thumbnail generation.
362 # Just generate the thumb for the current users prefs.
363 $thumbSizes = array( $this->getImageLimitsFromOption( $user, 'thumbsize' ) );
364 if ( !$this->displayImg
->mustRender() ) {
365 // We can safely include a link to the "full-size" preview,
366 // without actually rendering.
367 $thumbSizes[] = array( $width_orig, $height_orig );
370 # Generate thumbnails or thumbnail links as needed...
371 $otherSizes = array();
372 foreach ( $thumbSizes as $size ) {
373 // We include a thumbnail size in the list, if it is
374 // less than or equal to the original size of the image
375 // asset ($width_orig/$height_orig). We also exclude
376 // the current thumbnail's size ($width/$height)
377 // since that is added to the message separately, so
378 // it can be denoted as the current size being shown.
379 if ( $size[0] <= $width_orig && $size[1] <= $height_orig
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 if ( $sizeLinkBigImagePreview ) {
392 $msgsmall .= wfMessage( 'show-big-image-preview' )->
393 rawParams( $sizeLinkBigImagePreview )->
396 if ( count( $otherSizes ) ) {
398 Html
::rawElement( 'span', array( 'class' => 'mw-filepage-other-resolutions' ),
399 wfMessage( 'show-big-image-other' )->rawParams( $lang->pipeList( $otherSizes ) )->
400 params( count( $otherSizes ) )->parse()
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
407 } elseif ( $this->displayImg
->isVectorized() ) {
408 # For vectorized images, full size is just the frame size
411 # Image is small enough to show full size on image page
412 $msgsmall = wfMessage( 'file-nohires' )->parse();
415 $params['width'] = $width;
416 $params['height'] = $height;
417 $thumbnail = $this->displayImg
->transform( $params );
418 Linker
::processResponsiveImages( $this->displayImg
, $thumbnail, $params );
420 $anchorclose = Html
::rawElement( 'div', array( 'class' => 'mw-filepage-resolutioninfo' ), $msgsmall );
422 $isMulti = $this->displayImg
->isMultipage() && $this->displayImg
->pageCount() > 1;
424 $out->addModules( 'mediawiki.page.image.pagination' );
425 $out->addHTML( '<table class="multipageimage"><tr><td>' );
430 'alt' => $this->displayImg
->getTitle()->getPrefixedText(),
433 $out->addHTML( '<div class="fullImageLink" id="file">' .
434 $thumbnail->toHtml( $options ) .
435 $anchorclose . "</div>\n" );
439 $count = $this->displayImg
->pageCount();
442 $label = $out->parse( wfMessage( 'imgmultipageprev' )->text(), false );
443 $link = Linker
::linkKnown(
447 array( 'page' => $page - 1 )
449 $thumb1 = Linker
::makeThumbLinkObj( $this->getTitle(), $this->displayImg
, $link, $label, 'none',
450 array( 'page' => $page - 1 ) );
455 if ( $page < $count ) {
456 $label = wfMessage( 'imgmultipagenext' )->text();
457 $link = Linker
::linkKnown(
461 array( 'page' => $page +
1 )
463 $thumb2 = Linker
::makeThumbLinkObj( $this->getTitle(), $this->displayImg
, $link, $label, 'none',
464 array( 'page' => $page +
1 ) );
472 'name' => 'pageselector',
473 'action' => $wgScript,
476 for ( $i = 1; $i <= $count; $i++
) {
477 $options[] = Xml
::option( $lang->formatNum( $i ), $i, $i == $page );
479 $select = Xml
::tags( 'select',
480 array( 'id' => 'pageselector', 'name' => 'page' ),
481 implode( "\n", $options ) );
484 '</td><td><div class="multipageimagenavbox">' .
485 Xml
::openElement( 'form', $formParams ) .
486 Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
487 wfMessage( 'imgmultigoto' )->rawParams( $select )->parse() .
488 Xml
::submitButton( wfMessage( 'imgmultigo' )->text() ) .
489 Xml
::closeElement( 'form' ) .
490 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
493 } elseif ( $this->displayImg
->isSafeFile() ) {
494 # if direct link is allowed but it's not a renderable image, show an icon.
495 $icon = $this->displayImg
->iconThumb();
497 $out->addHTML( '<div class="fullImageLink" id="file">' .
498 $icon->toHtml( array( 'file-link' => true ) ) .
502 $longDesc = wfMessage( 'parentheses', $this->displayImg
->getLongDesc() )->text();
504 $medialink = "[[Media:$filename|$linktext]]";
506 if ( !$this->displayImg
->isSafeFile() ) {
507 $warning = wfMessage( 'mediawarning' )->plain();
508 // dirmark is needed here to separate the file name, which
509 // most likely ends in Latin characters, from the description,
510 // which may begin with the file type. In RTL environment
511 // this will get messy.
512 // The dirmark, however, must not be immediately adjacent
513 // to the filename, because it can get copied with it.
515 $out->addWikiText( <<<EOT
516 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
517 <div class="mediaWarning">$warning</div>
521 $out->addWikiText( <<<EOT
522 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
528 $renderLangOptions = $this->displayImg
->getAvailableLanguages();
529 if ( count( $renderLangOptions ) >= 1 ) {
530 $currentLanguage = $renderLang;
531 $defaultLang = $this->displayImg
->getDefaultRenderLanguage();
532 if ( is_null( $currentLanguage ) ) {
533 $currentLanguage = $defaultLang;
535 $out->addHtml( $this->doRenderLangOpt( $renderLangOptions, $currentLanguage, $defaultLang ) );
538 // Add cannot animate thumbnail warning
539 if ( !$this->displayImg
->canAnimateThumbIfAppropriate() ) {
540 // Include the extension so wiki admins can
541 // customize it on a per file-type basis
542 // (aka say things like use format X instead).
543 // additionally have a specific message for
544 // file-no-thumb-animation-gif
545 $ext = $this->displayImg
->getExtension();
546 $noAnimMesg = wfMessageFallback(
547 'file-no-thumb-animation-' . $ext,
548 'file-no-thumb-animation'
551 $out->addWikiText( <<<EOT
552 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
557 if ( !$this->displayImg
->isLocal() ) {
558 $this->printSharedImageText();
561 # Image does not exist
562 if ( !$this->getID() ) {
563 # No article exists either
564 # Show deletion log to be consistent with normal articles
565 LogEventsList
::showLogExtract(
567 array( 'delete', 'move' ),
568 $this->getTitle()->getPrefixedText(),
571 'conds' => array( "log_action != 'revision'" ),
572 'showIfEmpty' => false,
573 'msgKey' => array( 'moveddeleted-notice' )
578 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
579 // Only show an upload link if the user can upload
580 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
582 'filepage-nofile-link',
583 $uploadTitle->getFullURL( array( 'wpDestFile' => $this->mPage
->getFile()->getName() ) )
586 $nofile = 'filepage-nofile';
588 // Note, if there is an image description page, but
589 // no image, then this setRobotPolicy is overridden
590 // by Article::View().
591 $out->setRobotPolicy( 'noindex,nofollow' );
592 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
593 if ( !$this->getID() && $wgSend404Code ) {
594 // If there is no image, no shared image, and no description page,
595 // output a 404, to be consistent with articles.
596 $request->response()->header( 'HTTP/1.1 404 Not Found' );
599 $out->setFileVersion( $this->displayImg
);
603 * Creates an thumbnail of specified size and returns an HTML link to it
604 * @param array $params Scaler parameters
609 private function makeSizeLink( $params, $width, $height ) {
610 $params['width'] = $width;
611 $params['height'] = $height;
612 $thumbnail = $this->displayImg
->transform( $params );
613 if ( $thumbnail && !$thumbnail->isError() ) {
614 return Html
::rawElement( 'a', array(
615 'href' => $thumbnail->getUrl(),
616 'class' => 'mw-thumbnail-link'
617 ), wfMessage( 'show-big-image-size' )->numParams(
618 $thumbnail->getWidth(), $thumbnail->getHeight()
626 * Show a notice that the file is from a shared repository
628 protected function printSharedImageText() {
629 $out = $this->getContext()->getOutput();
632 $descUrl = $this->mPage
->getFile()->getDescriptionUrl();
633 $descText = $this->mPage
->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
635 /* Add canonical to head if there is no local page for this shared file */
636 if ( $descUrl && $this->mPage
->getID() == 0 ) {
637 $out->setCanonicalUrl( $descUrl );
640 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
641 $repo = $this->mPage
->getFile()->getRepo()->getDisplayName();
643 if ( $descUrl && $descText && wfMessage( 'sharedupload-desc-here' )->plain() !== '-' ) {
644 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
645 } elseif ( $descUrl && wfMessage( 'sharedupload-desc-there' )->plain() !== '-' ) {
646 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
648 $out->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
652 $this->mExtraDescription
= $descText;
656 public function getUploadUrl() {
658 $uploadTitle = SpecialPage
::getTitleFor( 'Upload' );
659 return $uploadTitle->getFullURL( array(
660 'wpDestFile' => $this->mPage
->getFile()->getName(),
666 * Print out the various links at the bottom of the image page, e.g. reupload,
667 * external editing (and instructions link) etc.
669 protected function uploadLinksBox() {
670 global $wgEnableUploads;
672 if ( !$wgEnableUploads ) {
677 if ( !$this->mPage
->getFile()->isLocal() ) {
681 $out = $this->getContext()->getOutput();
682 $out->addHTML( "<ul>\n" );
684 # "Upload a new version of this file" link
685 $canUpload = $this->getTitle()->userCan( 'upload', $this->getContext()->getUser() );
686 if ( $canUpload && UploadBase
::userCanReUpload( $this->getContext()->getUser(), $this->mPage
->getFile()->name
) ) {
687 $ulink = Linker
::makeExternalLink( $this->getUploadUrl(), wfMessage( 'uploadnewversion-linktext' )->text() );
688 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\"><div class=\"plainlinks\">{$ulink}</div></li>\n" );
690 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">" . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
693 $out->addHTML( "</ul>\n" );
696 protected function closeShowImage() { } # For overloading
699 * If the page we've just displayed is in the "Image" namespace,
700 * we follow it with an upload history of the image and its usage.
702 protected function imageHistory() {
704 $out = $this->getContext()->getOutput();
705 $pager = new ImageHistoryPseudoPager( $this );
706 $out->addHTML( $pager->getBody() );
707 $out->preventClickjacking( $pager->getPreventClickjacking() );
709 $this->mPage
->getFile()->resetHistory(); // free db resources
711 # Exist check because we don't want to show this on pages where an image
712 # doesn't exist along with the noimage message, that would suck. -ævar
713 if ( $this->mPage
->getFile()->exists() ) {
714 $this->uploadLinksBox();
721 * @return ResultWrapper
723 protected function queryImageLinks( $target, $limit ) {
724 $dbr = wfGetDB( DB_SLAVE
);
727 array( 'imagelinks', 'page' ),
728 array( 'page_namespace', 'page_title', 'page_is_redirect', 'il_to' ),
729 array( 'il_to' => $target, 'il_from = page_id' ),
731 array( 'LIMIT' => $limit +
1, 'ORDER BY' => 'il_from', )
735 protected function imageLinks() {
738 $out = $this->getContext()->getOutput();
739 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit +
1 );
741 $redirects = array();
742 foreach ( $res as $row ) {
743 if ( $row->page_is_redirect
) {
744 $redirects[$row->page_title
] = array();
748 $count = count( $rows );
750 $hasMore = $count > $limit;
751 if ( !$hasMore && count( $redirects ) ) {
752 $res = $this->queryImageLinks( array_keys( $redirects ),
753 $limit - count( $rows ) +
1 );
754 foreach ( $res as $row ) {
755 $redirects[$row->il_to
][] = $row;
758 $hasMore = ( $res->numRows() +
count( $rows ) ) > $limit;
763 Html
::rawElement( 'div',
764 array( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ),
770 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
772 $out->addWikiMsg( 'linkstoimage', $count );
774 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
775 $out->addWikiMsg( 'linkstoimage-more',
776 $this->getContext()->getLanguage()->formatNum( $limit ),
777 $this->getTitle()->getPrefixedDBkey()
782 Html
::openElement( 'ul',
783 array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n"
787 // Sort the list by namespace:title
788 usort( $rows, array( $this, 'compare' ) );
790 // Create links for every element
792 foreach ( $rows as $element ) {
794 if ( $currentCount > $limit ) {
799 # Add a redirect=no to make redirect pages reachable
800 if ( isset( $redirects[$element->page_title
] ) ) {
801 $query['redirect'] = 'no';
803 $link = Linker
::linkKnown(
804 Title
::makeTitle( $element->page_namespace
, $element->page_title
),
805 null, array(), $query
807 if ( !isset( $redirects[$element->page_title
] ) ) {
810 } elseif ( count( $redirects[$element->page_title
] ) === 0 ) {
811 # Redirect without usages
812 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams( $link, '' )->parse();
814 # Redirect with usages
816 foreach ( $redirects[$element->page_title
] as $row ) {
818 if ( $currentCount > $limit ) {
822 $link2 = Linker
::linkKnown( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
823 $li .= Html
::rawElement(
825 array( 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
),
830 $ul = Html
::rawElement(
832 array( 'class' => 'mw-imagepage-redirectstofile' ),
835 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams(
836 $link, $ul )->parse();
838 $out->addHTML( Html
::rawElement(
840 array( 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace
),
846 $out->addHTML( Html
::closeElement( 'ul' ) . "\n" );
849 // Add a links to [[Special:Whatlinkshere]]
850 if ( $count > $limit ) {
851 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
853 $out->addHTML( Html
::closeElement( 'div' ) . "\n" );
856 protected function imageDupes() {
858 $out = $this->getContext()->getOutput();
860 $dupes = $this->mPage
->getDuplicates();
861 if ( count( $dupes ) == 0 ) {
865 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
866 $out->addWikiMsg( 'duplicatesoffile',
867 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
869 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
874 foreach ( $dupes as $file ) {
876 if ( $file->isLocal() ) {
877 $link = Linker
::linkKnown( $file->getTitle() );
879 $link = Linker
::makeExternalLink( $file->getDescriptionUrl(),
880 $file->getTitle()->getPrefixedText() );
881 $fromSrc = wfMessage( 'shared-repo-from', $file->getRepo()->getDisplayName() )->text();
883 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
885 $out->addHTML( "</ul></div>\n" );
889 * Delete the file, or an earlier version of it
891 public function delete() {
892 $file = $this->mPage
->getFile();
893 if ( !$file->exists() ||
!$file->isLocal() ||
$file->getRedirected() ) {
894 // Standard article deletion
899 $deleter = new FileDeleteForm( $file );
904 * Display an error with a wikitext description
906 * @param $description String
908 function showError( $description ) {
909 $out = $this->getContext()->getOutput();
910 $out->setPageTitle( wfMessage( 'internalerror' ) );
911 $out->setRobotPolicy( 'noindex,nofollow' );
912 $out->setArticleRelated( false );
913 $out->enableClientCache( false );
914 $out->addWikiText( $description );
918 * Callback for usort() to do link sorts by (namespace, title)
919 * Function copied from Title::compare()
921 * @param $a object page to compare with
922 * @param $b object page to compare with
923 * @return Integer: result of string comparison, or namespace comparison
925 protected function compare( $a, $b ) {
926 if ( $a->page_namespace
== $b->page_namespace
) {
927 return strcmp( $a->page_title
, $b->page_title
);
929 return $a->page_namespace
- $b->page_namespace
;
934 * Returns the corresponding $wgImageLimits entry for the selected user option
937 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
941 public function getImageLimitsFromOption( $user, $optionName ) {
942 global $wgImageLimits;
944 $option = $user->getIntOption( $optionName );
945 if ( !isset( $wgImageLimits[$option] ) ) {
946 $option = User
::getDefaultOption( $optionName );
949 // The user offset might still be incorrect, specially if
950 // $wgImageLimits got changed (see bug #8858).
951 if ( !isset( $wgImageLimits[$option] ) ) {
952 // Default to the first offset in $wgImageLimits
956 return isset( $wgImageLimits[$option] )
957 ?
$wgImageLimits[$option]
958 : array( 800, 600 ); // if nothing is set, fallback to a hardcoded default
962 * Output a drop-down box for language options for the file
964 * @param Array $langChoices Array of string language codes
965 * @param String $curLang Language code file is being viewed in.
966 * @param String $defaultLang Language code that image is rendered in by default
967 * @return String HTML to insert underneath image.
969 protected function doRenderLangOpt( array $langChoices, $curLang, $defaultLang ) {
971 sort( $langChoices );
972 $curLang = wfBCP47( $curLang );
973 $defaultLang = wfBCP47( $defaultLang );
975 $haveCurrentLang = false;
976 $haveDefaultLang = false;
978 // We make a list of all the language choices in the file.
979 // Additionally if the default language to render this file
980 // is not included as being in this file (for example, in svgs
981 // usually the fallback content is the english content) also
982 // include a choice for that. Last of all, if we're viewing
983 // the file in a language not on the list, add it as a choice.
984 foreach ( $langChoices as $lang ) {
985 $code = wfBCP47( $lang );
986 $name = Language
::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
987 if ( $name !== '' ) {
988 $display = wfMessage( 'img-lang-opt', $code, $name )->text();
992 $opts .= "\n" . XML
::Option( $display, $code, $curLang === $code );
993 if ( $curLang === $code ) {
994 $haveCurrentLang = true;
996 if ( $defaultLang === $code ) {
997 $haveDefaultLang = true;
1000 if ( !$haveDefaultLang ) {
1001 // Its hard to know if the content is really in the default language, or
1002 // if its just unmarked content that could be in any language.
1003 $opts = XML
::Option( wfMessage( 'img-lang-default' )->text(), '', $defaultLang === $curLang ) . $opts;
1005 if ( !$haveCurrentLang && $defaultLang !== $curLang ) {
1006 $name = Language
::fetchLanguageName( $curLang, $this->getContext()->getLanguage()->getCode() );
1007 if ( $name !== '' ) {
1008 $display = wfMessage( 'img-lang-opt', $curLang, $name )->text();
1010 $display = $curLang;
1012 $opts = XML
::Option( $display, $curLang, true ) . $opts;
1015 $select = Html
::rawElement( 'select', array( 'id' => 'mw-imglangselector', 'name' => 'lang' ), $opts );
1016 $submit = Xml
::submitButton( wfMessage( 'img-lang-go' )->text() );
1018 $formContents = wfMessage( 'img-lang-info' )->rawParams( $select, $submit )->parse()
1019 . Html
::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1021 $langSelectLine = Html
::rawElement( 'div', array( 'id' => 'mw-imglangselector-line' ),
1022 Html
::rawElement( 'form', array( 'action' => $wgScript ), $formContents )
1024 return $langSelectLine;
1029 * Builds the image revision log shown on image pages
1033 class ImageHistoryList
extends ContextSource
{
1048 protected $imagePage;
1055 protected $repo, $showThumb;
1056 protected $preventClickjacking = false;
1059 * @param ImagePage $imagePage
1061 public function __construct( $imagePage ) {
1062 global $wgShowArchiveThumbnails;
1063 $this->current
= $imagePage->getFile();
1064 $this->img
= $imagePage->getDisplayedFile();
1065 $this->title
= $imagePage->getTitle();
1066 $this->imagePage
= $imagePage;
1067 $this->showThumb
= $wgShowArchiveThumbnails && $this->img
->canRender();
1068 $this->setContext( $imagePage->getContext() );
1074 public function getImagePage() {
1075 return $this->imagePage
;
1081 public function getFile() {
1086 * @param $navLinks string
1089 public function beginImageHistoryList( $navLinks = '' ) {
1090 return Xml
::element( 'h2', array( 'id' => 'filehistory' ), $this->msg( 'filehist' )->text() ) . "\n"
1091 . "<div id=\"mw-imagepage-section-filehistory\">\n"
1092 . $this->msg( 'filehist-help' )->parseAsBlock()
1094 . Xml
::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
1096 . ( $this->current
->isLocal() && ( $this->getUser()->isAllowedAny( 'delete', 'deletedhistory' ) ) ?
'<td></td>' : '' )
1097 . '<th>' . $this->msg( 'filehist-datetime' )->escaped() . '</th>'
1098 . ( $this->showThumb ?
'<th>' . $this->msg( 'filehist-thumb' )->escaped() . '</th>' : '' )
1099 . '<th>' . $this->msg( 'filehist-dimensions' )->escaped() . '</th>'
1100 . '<th>' . $this->msg( 'filehist-user' )->escaped() . '</th>'
1101 . '<th>' . $this->msg( 'filehist-comment' )->escaped() . '</th>'
1106 * @param $navLinks string
1109 public function endImageHistoryList( $navLinks = '' ) {
1110 return "</table>\n$navLinks\n</div>\n";
1118 public function imageHistoryLine( $iscur, $file ) {
1121 $user = $this->getUser();
1122 $lang = $this->getLanguage();
1123 $timestamp = wfTimestamp( TS_MW
, $file->getTimestamp() );
1124 $img = $iscur ?
$file->getName() : $file->getArchiveName();
1125 $userId = $file->getUser( 'id' );
1126 $userText = $file->getUser( 'text' );
1127 $description = $file->getDescription( File
::FOR_THIS_USER
, $user );
1129 $local = $this->current
->isLocal();
1130 $row = $selected = '';
1133 if ( $local && ( $user->isAllowedAny( 'delete', 'deletedhistory' ) ) ) {
1135 # Link to remove from history
1136 if ( $user->isAllowed( 'delete' ) ) {
1137 $q = array( 'action' => 'delete' );
1139 $q['oldimage'] = $img;
1141 $row .= Linker
::linkKnown(
1143 $this->msg( $iscur ?
'filehist-deleteall' : 'filehist-deleteone' )->escaped(),
1147 # Link to hide content. Don't show useless link to people who cannot hide revisions.
1148 $canHide = $user->isAllowed( 'deleterevision' );
1149 if ( $canHide ||
( $user->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
1150 if ( $user->isAllowed( 'delete' ) ) {
1153 // If file is top revision or locked from this user, don't link
1154 if ( $iscur ||
!$file->userCan( File
::DELETED_RESTRICTED
, $user ) ) {
1155 $del = Linker
::revDeleteLinkDisabled( $canHide );
1157 list( $ts, ) = explode( '!', $img, 2 );
1159 'type' => 'oldimage',
1160 'target' => $this->title
->getPrefixedText(),
1163 $del = Linker
::revDeleteLink( $query,
1164 $file->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
1171 // Reversion link/current indicator
1174 $row .= $this->msg( 'filehist-current' )->escaped();
1175 } elseif ( $local && $this->title
->quickUserCan( 'edit', $user )
1176 && $this->title
->quickUserCan( 'upload', $user )
1178 if ( $file->isDeleted( File
::DELETED_FILE
) ) {
1179 $row .= $this->msg( 'filehist-revert' )->escaped();
1181 $row .= Linker
::linkKnown(
1183 $this->msg( 'filehist-revert' )->escaped(),
1186 'action' => 'revert',
1188 'wpEditToken' => $user->getEditToken( $img )
1195 // Date/time and image link
1196 if ( $file->getTimestamp() === $this->img
->getTimestamp() ) {
1197 $selected = "class='filehistory-selected'";
1199 $row .= "<td $selected style='white-space: nowrap;'>";
1200 if ( !$file->userCan( File
::DELETED_FILE
, $user ) ) {
1201 # Don't link to unviewable files
1202 $row .= '<span class="history-deleted">' . $lang->userTimeAndDate( $timestamp, $user ) . '</span>';
1203 } elseif ( $file->isDeleted( File
::DELETED_FILE
) ) {
1205 $this->preventClickjacking();
1206 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
1207 # Make a link to review the image
1208 $url = Linker
::linkKnown(
1210 $lang->userTimeAndDate( $timestamp, $user ),
1213 'target' => $this->title
->getPrefixedText(),
1215 'token' => $user->getEditToken( $img )
1219 $url = $lang->userTimeAndDate( $timestamp, $user );
1221 $row .= '<span class="history-deleted">' . $url . '</span>';
1223 $url = $iscur ?
$this->current
->getUrl() : $this->current
->getArchiveUrl( $img );
1224 $row .= Xml
::element( 'a', array( 'href' => $url ), $lang->userTimeAndDate( $timestamp, $user ) );
1229 if ( $this->showThumb
) {
1230 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1233 // Image dimensions + size
1235 $row .= htmlspecialchars( $file->getDimensionsString() );
1236 $row .= $this->msg( 'word-separator' )->plain();
1237 $row .= '<span style="white-space: nowrap;">';
1238 $row .= $this->msg( 'parentheses' )->rawParams( Linker
::formatSize( $file->getSize() ) )->plain();
1244 // Hide deleted usernames
1245 if ( $file->isDeleted( File
::DELETED_USER
) ) {
1246 $row .= '<span class="history-deleted">' . $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
1249 $row .= Linker
::userLink( $userId, $userText );
1250 $row .= $this->msg( 'word-separator' )->plain();
1251 $row .= '<span style="white-space: nowrap;">';
1252 $row .= Linker
::userToolLinks( $userId, $userText );
1255 $row .= htmlspecialchars( $userText );
1260 // Don't show deleted descriptions
1261 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
1262 $row .= '<td><span class="history-deleted">' . $this->msg( 'rev-deleted-comment' )->escaped() . '</span></td>';
1264 $row .= '<td dir="' . $wgContLang->getDir() . '">' . Linker
::formatComment( $description, $this->title
) . '</td>';
1268 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1269 $classAttr = $rowClass ?
" class='$rowClass'" : '';
1271 return "<tr{$classAttr}>{$row}</tr>\n";
1278 protected function getThumbForLine( $file ) {
1279 $lang = $this->getLanguage();
1280 $user = $this->getUser();
1281 if ( $file->allowInlineDisplay() && $file->userCan( File
::DELETED_FILE
, $user )
1282 && !$file->isDeleted( File
::DELETED_FILE
)
1288 $timestamp = wfTimestamp( TS_MW
, $file->getTimestamp() );
1290 $thumbnail = $file->transform( $params );
1292 'alt' => $this->msg( 'filehist-thumbtext',
1293 $lang->userTimeAndDate( $timestamp, $user ),
1294 $lang->userDate( $timestamp, $user ),
1295 $lang->userTime( $timestamp, $user ) )->text(),
1296 'file-link' => true,
1299 if ( !$thumbnail ) {
1300 return $this->msg( 'filehist-nothumb' )->escaped();
1303 return $thumbnail->toHtml( $options );
1305 return $this->msg( 'filehist-nothumb' )->escaped();
1310 * @param $enable bool
1312 protected function preventClickjacking( $enable = true ) {
1313 $this->preventClickjacking
= $enable;
1319 public function getPreventClickjacking() {
1320 return $this->preventClickjacking
;
1324 class ImageHistoryPseudoPager
extends ReverseChronologicalPager
{
1325 protected $preventClickjacking = false;
1338 * @param ImagePage $imagePage
1340 function __construct( $imagePage ) {
1341 parent
::__construct( $imagePage->getContext() );
1342 $this->mImagePage
= $imagePage;
1343 $this->mTitle
= clone ( $imagePage->getTitle() );
1344 $this->mTitle
->setFragment( '#filehistory' );
1346 $this->mHist
= array();
1347 $this->mRange
= array( 0, 0 ); // display range
1353 function getTitle() {
1354 return $this->mTitle
;
1357 function getQueryInfo() {
1364 function getIndexField() {
1369 * @param $row object
1372 function formatRow( $row ) {
1379 function getBody() {
1382 if ( count( $this->mHist
) ) {
1383 $list = new ImageHistoryList( $this->mImagePage
);
1384 # Generate prev/next links
1385 $navLink = $this->getNavigationBar();
1386 $s = $list->beginImageHistoryList( $navLink );
1387 // Skip rows there just for paging links
1388 for ( $i = $this->mRange
[0]; $i <= $this->mRange
[1]; $i++
) {
1389 $file = $this->mHist
[$i];
1390 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1392 $s .= $list->endImageHistoryList( $navLink );
1394 if ( $list->getPreventClickjacking() ) {
1395 $this->preventClickjacking();
1401 function doQuery() {
1402 if ( $this->mQueryDone
) {
1405 $this->mImg
= $this->mImagePage
->getFile(); // ensure loading
1406 if ( !$this->mImg
->exists() ) {
1409 $queryLimit = $this->mLimit +
1; // limit plus extra row
1410 if ( $this->mIsBackwards
) {
1411 // Fetch the file history
1412 $this->mHist
= $this->mImg
->getHistory( $queryLimit, null, $this->mOffset
, false );
1413 // The current rev may not meet the offset/limit
1414 $numRows = count( $this->mHist
);
1415 if ( $numRows <= $this->mLimit
&& $this->mImg
->getTimestamp() > $this->mOffset
) {
1416 $this->mHist
= array_merge( array( $this->mImg
), $this->mHist
);
1419 // The current rev may not meet the offset
1420 if ( !$this->mOffset ||
$this->mImg
->getTimestamp() < $this->mOffset
) {
1421 $this->mHist
[] = $this->mImg
;
1423 // Old image versions (fetch extra row for nav links)
1424 $oiLimit = count( $this->mHist
) ?
$this->mLimit
: $this->mLimit +
1;
1425 // Fetch the file history
1426 $this->mHist
= array_merge( $this->mHist
,
1427 $this->mImg
->getHistory( $oiLimit, $this->mOffset
, null, false ) );
1429 $numRows = count( $this->mHist
); // Total number of query results
1431 # Index value of top item in the list
1432 $firstIndex = $this->mIsBackwards ?
1433 $this->mHist
[$numRows - 1]->getTimestamp() : $this->mHist
[0]->getTimestamp();
1434 # Discard the extra result row if there is one
1435 if ( $numRows > $this->mLimit
&& $numRows > 1 ) {
1436 if ( $this->mIsBackwards
) {
1437 # Index value of item past the index
1438 $this->mPastTheEndIndex
= $this->mHist
[0]->getTimestamp();
1439 # Index value of bottom item in the list
1440 $lastIndex = $this->mHist
[1]->getTimestamp();
1442 $this->mRange
= array( 1, $numRows - 1 );
1444 # Index value of item past the index
1445 $this->mPastTheEndIndex
= $this->mHist
[$numRows - 1]->getTimestamp();
1446 # Index value of bottom item in the list
1447 $lastIndex = $this->mHist
[$numRows - 2]->getTimestamp();
1449 $this->mRange
= array( 0, $numRows - 2 );
1452 # Setting indexes to an empty string means that they will be
1453 # omitted if they would otherwise appear in URLs. It just so
1454 # happens that this is the right thing to do in the standard
1455 # UI, in all the relevant cases.
1456 $this->mPastTheEndIndex
= '';
1457 # Index value of bottom item in the list
1458 $lastIndex = $this->mIsBackwards ?
1459 $this->mHist
[0]->getTimestamp() : $this->mHist
[$numRows - 1]->getTimestamp();
1461 $this->mRange
= array( 0, $numRows - 1 );
1466 $this->mPastTheEndIndex
= '';
1468 if ( $this->mIsBackwards
) {
1469 $this->mIsFirst
= ( $numRows < $queryLimit );
1470 $this->mIsLast
= ( $this->mOffset
== '' );
1471 $this->mLastShown
= $firstIndex;
1472 $this->mFirstShown
= $lastIndex;
1474 $this->mIsFirst
= ( $this->mOffset
== '' );
1475 $this->mIsLast
= ( $numRows < $queryLimit );
1476 $this->mLastShown
= $lastIndex;
1477 $this->mFirstShown
= $firstIndex;
1479 $this->mQueryDone
= true;
1483 * @param $enable bool
1485 protected function preventClickjacking( $enable = true ) {
1486 $this->preventClickjacking
= $enable;
1492 public function getPreventClickjacking() {
1493 return $this->preventClickjacking
;