Fixed spacing
[mediawiki.git] / includes / page / ImagePage.php
blob9aff6ef27c70c934567b7519f6e7dbe8d0e5b54a
1 <?php
2 /**
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
20 * @file
23 /**
24 * Class for viewing MediaWiki file description pages
26 * @ingroup Media
28 class ImagePage extends Article {
29 /** @var File */
30 private $displayImg;
32 /** @var FileRepo */
33 private $repo;
35 /** @var bool */
36 private $fileLoaded;
38 /** @var bool */
39 protected $mExtraDescription = false;
41 /**
42 * @param Title $title
43 * @return WikiFilePage
45 protected function newPage( Title $title ) {
46 // Overload mPage with a file-specific page
47 return new WikiFilePage( $title );
50 /**
51 * Constructor from a page id
52 * @param int $id Article ID to load
53 * @return ImagePage|null
55 public static function newFromID( $id ) {
56 $t = Title::newFromID( $id );
57 # @todo FIXME: Doesn't inherit right
58 return $t == null ? null : new self( $t );
59 # return $t == null ? null : new static( $t ); // PHP 5.3
62 /**
63 * @param File $file
64 * @return void
66 public function setFile( $file ) {
67 $this->mPage->setFile( $file );
68 $this->displayImg = $file;
69 $this->fileLoaded = true;
72 protected function loadFile() {
73 if ( $this->fileLoaded ) {
74 return;
76 $this->fileLoaded = true;
78 $this->displayImg = $img = false;
79 wfRunHooks( 'ImagePageFindFile', array( $this, &$img, &$this->displayImg ) );
80 if ( !$img ) { // not set by hook?
81 $img = wfFindFile( $this->getTitle() );
82 if ( !$img ) {
83 $img = wfLocalFile( $this->getTitle() );
86 $this->mPage->setFile( $img );
87 if ( !$this->displayImg ) { // not set by hook?
88 $this->displayImg = $img;
90 $this->repo = $img->getRepo();
93 /**
94 * Handler for action=render
95 * Include body text only; none of the image extras
97 public function render() {
98 $this->getContext()->getOutput()->setArticleBodyOnly( true );
99 parent::view();
102 public function view() {
103 global $wgShowEXIF;
105 $out = $this->getContext()->getOutput();
106 $request = $this->getContext()->getRequest();
107 $diff = $request->getVal( 'diff' );
108 $diffOnly = $request->getBool(
109 'diffonly',
110 $this->getContext()->getUser()->getOption( 'diffonly' )
113 if ( $this->getTitle()->getNamespace() != NS_FILE || ( $diff !== null && $diffOnly ) ) {
114 parent::view();
115 return;
118 $this->loadFile();
120 if ( $this->getTitle()->getNamespace() == NS_FILE && $this->mPage->getFile()->getRedirected() ) {
121 if ( $this->getTitle()->getDBkey() == $this->mPage->getFile()->getName() || $diff !== null ) {
122 // mTitle is the same as the redirect target so ask Article
123 // to perform the redirect for us.
124 $request->setVal( 'diffonly', 'true' );
125 parent::view();
126 return;
127 } else {
128 // mTitle is not the same as the redirect target so it is
129 // probably the redirect page itself. Fake the redirect symbol
130 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
131 $out->addHTML( $this->viewRedirect(
132 Title::makeTitle( NS_FILE, $this->mPage->getFile()->getName() ),
133 /* $appendSubtitle */ true,
134 /* $forceKnown */ true )
136 $this->mPage->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
137 return;
141 if ( $wgShowEXIF && $this->displayImg->exists() ) {
142 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
143 $formattedMetadata = $this->displayImg->formatMetadata();
144 $showmeta = $formattedMetadata !== false;
145 } else {
146 $showmeta = false;
149 if ( !$diff && $this->displayImg->exists() ) {
150 $out->addHTML( $this->showTOC( $showmeta ) );
153 if ( !$diff ) {
154 $this->openShowImage();
157 # No need to display noarticletext, we use our own message, output in openShowImage()
158 if ( $this->mPage->getID() ) {
159 # NS_FILE is in the user language, but this section (the actual wikitext)
160 # should be in page content language
161 $pageLang = $this->getTitle()->getPageViewLanguage();
162 $out->addHTML( Xml::openElement( 'div', array( 'id' => 'mw-imagepage-content',
163 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
164 'class' => 'mw-content-' . $pageLang->getDir() ) ) );
166 parent::view();
168 $out->addHTML( Xml::closeElement( 'div' ) );
169 } else {
170 # Just need to set the right headers
171 $out->setArticleFlag( true );
172 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
173 $this->mPage->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
176 # Show shared description, if needed
177 if ( $this->mExtraDescription ) {
178 $fol = wfMessage( 'shareddescriptionfollows' );
179 if ( !$fol->isDisabled() ) {
180 $out->addWikiText( $fol->plain() );
182 $out->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
185 $this->closeShowImage();
186 $this->imageHistory();
187 // TODO: Cleanup the following
189 $out->addHTML( Xml::element( 'h2',
190 array( 'id' => 'filelinks' ),
191 wfMessage( 'imagelinks' )->text() ) . "\n" );
192 $this->imageDupes();
193 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
194 # Yet we return metadata about the target. Definitely an issue in the FileRepo
195 $this->imageLinks();
197 # Allow extensions to add something after the image links
198 $html = '';
199 wfRunHooks( 'ImagePageAfterImageLinks', array( $this, &$html ) );
200 if ( $html ) {
201 $out->addHTML( $html );
204 if ( $showmeta ) {
205 $out->addHTML( Xml::element(
206 'h2',
207 array( 'id' => 'metadata' ),
208 wfMessage( 'metadata' )->text() ) . "\n" );
209 $out->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
210 $out->addModules( array( 'mediawiki.action.view.metadata' ) );
213 // Add remote Filepage.css
214 if ( !$this->repo->isLocal() ) {
215 $css = $this->repo->getDescriptionStylesheetUrl();
216 if ( $css ) {
217 $out->addStyle( $css );
220 // always show the local local Filepage.css, bug 29277
221 $out->addModuleStyles( 'filepage' );
225 * @return File
227 public function getDisplayedFile() {
228 $this->loadFile();
229 return $this->displayImg;
233 * Create the TOC
235 * @param bool $metadata Whether or not to show the metadata link
236 * @return string
238 protected function showTOC( $metadata ) {
239 $r = array(
240 '<li><a href="#file">' . wfMessage( 'file-anchor-link' )->escaped() . '</a></li>',
241 '<li><a href="#filehistory">' . wfMessage( 'filehist' )->escaped() . '</a></li>',
242 '<li><a href="#filelinks">' . wfMessage( 'imagelinks' )->escaped() . '</a></li>',
244 if ( $metadata ) {
245 $r[] = '<li><a href="#metadata">' . wfMessage( 'metadata' )->escaped() . '</a></li>';
248 wfRunHooks( 'ImagePageShowTOC', array( $this, &$r ) );
250 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
254 * Make a table with metadata to be shown in the output page.
256 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
258 * @param array $metadata The array containing the Exif data
259 * @return string The metadata table. This is treated as Wikitext (!)
261 protected function makeMetadataTable( $metadata ) {
262 $r = "<div class=\"mw-imagepage-section-metadata\">";
263 $r .= wfMessage( 'metadata-help' )->plain();
264 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
265 foreach ( $metadata as $type => $stuff ) {
266 foreach ( $stuff as $v ) {
267 # @todo FIXME: Why is this using escapeId for a class?!
268 $class = Sanitizer::escapeId( $v['id'] );
269 if ( $type == 'collapsed' ) {
270 // Handled by mediawiki.action.view.metadata module
271 // and skins/common/shared.css.
272 $class .= ' collapsable';
274 $r .= "<tr class=\"$class\">\n";
275 $r .= "<th>{$v['name']}</th>\n";
276 $r .= "<td>{$v['value']}</td>\n</tr>";
279 $r .= "</table>\n</div>\n";
280 return $r;
284 * Overloading Article's getContentObject method.
286 * Omit noarticletext if sharedupload; text will be fetched from the
287 * shared upload server if possible.
288 * @return string
290 public function getContentObject() {
291 $this->loadFile();
292 if ( $this->mPage->getFile() && !$this->mPage->getFile()->isLocal() && 0 == $this->getID() ) {
293 return null;
295 return parent::getContentObject();
298 protected function openShowImage() {
299 global $wgEnableUploads, $wgSend404Code;
301 $this->loadFile();
302 $out = $this->getContext()->getOutput();
303 $user = $this->getContext()->getUser();
304 $lang = $this->getContext()->getLanguage();
305 $dirmark = $lang->getDirMarkEntity();
306 $request = $this->getContext()->getRequest();
308 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
309 $maxWidth = $max[0];
310 $maxHeight = $max[1];
312 if ( $this->displayImg->exists() ) {
313 # image
314 $page = $request->getIntOrNull( 'page' );
315 if ( is_null( $page ) ) {
316 $params = array();
317 $page = 1;
318 } else {
319 $params = array( 'page' => $page );
322 $renderLang = $request->getVal( 'lang' );
323 if ( !is_null( $renderLang ) ) {
324 $handler = $this->displayImg->getHandler();
325 if ( $handler && $handler->validateParam( 'lang', $renderLang ) ) {
326 $params['lang'] = $renderLang;
327 } else {
328 $renderLang = null;
332 $width_orig = $this->displayImg->getWidth( $page );
333 $width = $width_orig;
334 $height_orig = $this->displayImg->getHeight( $page );
335 $height = $height_orig;
337 $filename = wfEscapeWikiText( $this->displayImg->getName() );
338 $linktext = $filename;
340 wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this, &$out ) );
342 if ( $this->displayImg->allowInlineDisplay() ) {
343 # image
344 # "Download high res version" link below the image
345 # $msgsize = wfMessage( 'file-info-size', $width_orig, $height_orig,
346 # Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
347 # We'll show a thumbnail of this image
348 if ( $width > $maxWidth || $height > $maxHeight || $this->displayImg->isVectorized() ) {
349 list( $width, $height ) = $this->getDisplayWidthHeight(
350 $maxWidth, $maxHeight, $width, $height
352 $linktext = wfMessage( 'show-big-image' )->escaped();
354 $thumbSizes = $this->getThumbSizes( $width, $height, $width_orig, $height_orig );
355 # Generate thumbnails or thumbnail links as needed...
356 $otherSizes = array();
357 foreach ( $thumbSizes as $size ) {
358 // We include a thumbnail size in the list, if it is
359 // less than or equal to the original size of the image
360 // asset ($width_orig/$height_orig). We also exclude
361 // the current thumbnail's size ($width/$height)
362 // since that is added to the message separately, so
363 // it can be denoted as the current size being shown.
364 // Vectorized images are "infinitely" big, so all thumb
365 // sizes are shown.
366 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
367 || $this->displayImg->isVectorized() )
368 && $size[0] != $width && $size[1] != $height
370 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
371 if ( $sizeLink ) {
372 $otherSizes[] = $sizeLink;
376 $otherSizes = array_unique( $otherSizes );
378 $msgsmall = '';
379 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
380 if ( $sizeLinkBigImagePreview ) {
381 $msgsmall .= wfMessage( 'show-big-image-preview' )->
382 rawParams( $sizeLinkBigImagePreview )->
383 parse();
385 if ( count( $otherSizes ) ) {
386 $msgsmall .= ' ' .
387 Html::rawElement( 'span', array( 'class' => 'mw-filepage-other-resolutions' ),
388 wfMessage( 'show-big-image-other' )->rawParams( $lang->pipeList( $otherSizes ) )->
389 params( count( $otherSizes ) )->parse()
392 } elseif ( $width == 0 && $height == 0 ) {
393 # Some sort of audio file that doesn't have dimensions
394 # Don't output a no hi res message for such a file
395 $msgsmall = '';
396 } else {
397 # Image is small enough to show full size on image page
398 $msgsmall = wfMessage( 'file-nohires' )->parse();
401 $params['width'] = $width;
402 $params['height'] = $height;
403 $thumbnail = $this->displayImg->transform( $params );
404 Linker::processResponsiveImages( $this->displayImg, $thumbnail, $params );
406 $anchorclose = Html::rawElement(
407 'div',
408 array( 'class' => 'mw-filepage-resolutioninfo' ),
409 $msgsmall
412 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
413 if ( $isMulti ) {
414 $out->addModules( 'mediawiki.page.image.pagination' );
415 $out->addHTML( '<table class="multipageimage"><tr><td>' );
418 if ( $thumbnail ) {
419 $options = array(
420 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
421 'file-link' => true,
423 $out->addHTML( '<div class="fullImageLink" id="file">' .
424 $thumbnail->toHtml( $options ) .
425 $anchorclose . "</div>\n" );
428 if ( $isMulti ) {
429 $count = $this->displayImg->pageCount();
431 if ( $page > 1 ) {
432 $label = $out->parse( wfMessage( 'imgmultipageprev' )->text(), false );
433 $link = Linker::linkKnown(
434 $this->getTitle(),
435 $label,
436 array(),
437 array( 'page' => $page - 1 )
439 $thumb1 = Linker::makeThumbLinkObj(
440 $this->getTitle(),
441 $this->displayImg,
442 $link,
443 $label,
444 'none',
445 array( 'page' => $page - 1 )
447 } else {
448 $thumb1 = '';
451 if ( $page < $count ) {
452 $label = wfMessage( 'imgmultipagenext' )->text();
453 $link = Linker::linkKnown(
454 $this->getTitle(),
455 $label,
456 array(),
457 array( 'page' => $page + 1 )
459 $thumb2 = Linker::makeThumbLinkObj(
460 $this->getTitle(),
461 $this->displayImg,
462 $link,
463 $label,
464 'none',
465 array( 'page' => $page + 1 )
467 } else {
468 $thumb2 = '';
471 global $wgScript;
473 $formParams = array(
474 'name' => 'pageselector',
475 'action' => $wgScript,
477 $options = array();
478 for ( $i = 1; $i <= $count; $i++ ) {
479 $options[] = Xml::option( $lang->formatNum( $i ), $i, $i == $page );
481 $select = Xml::tags( 'select',
482 array( 'id' => 'pageselector', 'name' => 'page' ),
483 implode( "\n", $options ) );
485 $out->addHTML(
486 '</td><td><div class="multipageimagenavbox">' .
487 Xml::openElement( 'form', $formParams ) .
488 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
489 wfMessage( 'imgmultigoto' )->rawParams( $select )->parse() .
490 Xml::submitButton( wfMessage( 'imgmultigo' )->text() ) .
491 Xml::closeElement( 'form' ) .
492 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
495 } elseif ( $this->displayImg->isSafeFile() ) {
496 # if direct link is allowed but it's not a renderable image, show an icon.
497 $icon = $this->displayImg->iconThumb();
499 $out->addHTML( '<div class="fullImageLink" id="file">' .
500 $icon->toHtml( array( 'file-link' => true ) ) .
501 "</div>\n" );
504 $longDesc = wfMessage( 'parentheses', $this->displayImg->getLongDesc() )->text();
506 $medialink = "[[Media:$filename|$linktext]]";
508 if ( !$this->displayImg->isSafeFile() ) {
509 $warning = wfMessage( 'mediawarning' )->plain();
510 // dirmark is needed here to separate the file name, which
511 // most likely ends in Latin characters, from the description,
512 // which may begin with the file type. In RTL environment
513 // this will get messy.
514 // The dirmark, however, must not be immediately adjacent
515 // to the filename, because it can get copied with it.
516 // See bug 25277.
517 // @codingStandardsIgnoreStart Ignore long line
518 $out->addWikiText( <<<EOT
519 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
520 <div class="mediaWarning">$warning</div>
523 // @codingStandardsIgnoreEnd
524 } else {
525 $out->addWikiText( <<<EOT
526 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
527 </div>
532 $renderLangOptions = $this->displayImg->getAvailableLanguages();
533 if ( count( $renderLangOptions ) >= 1 ) {
534 $currentLanguage = $renderLang;
535 $defaultLang = $this->displayImg->getDefaultRenderLanguage();
536 if ( is_null( $currentLanguage ) ) {
537 $currentLanguage = $defaultLang;
539 $out->addHtml( $this->doRenderLangOpt( $renderLangOptions, $currentLanguage, $defaultLang ) );
542 // Add cannot animate thumbnail warning
543 if ( !$this->displayImg->canAnimateThumbIfAppropriate() ) {
544 // Include the extension so wiki admins can
545 // customize it on a per file-type basis
546 // (aka say things like use format X instead).
547 // additionally have a specific message for
548 // file-no-thumb-animation-gif
549 $ext = $this->displayImg->getExtension();
550 $noAnimMesg = wfMessageFallback(
551 'file-no-thumb-animation-' . $ext,
552 'file-no-thumb-animation'
553 )->plain();
555 $out->addWikiText( <<<EOT
556 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
561 if ( !$this->displayImg->isLocal() ) {
562 $this->printSharedImageText();
564 } else {
565 # Image does not exist
566 if ( !$this->getID() ) {
567 # No article exists either
568 # Show deletion log to be consistent with normal articles
569 LogEventsList::showLogExtract(
570 $out,
571 array( 'delete', 'move' ),
572 $this->getTitle()->getPrefixedText(),
574 array( 'lim' => 10,
575 'conds' => array( "log_action != 'revision'" ),
576 'showIfEmpty' => false,
577 'msgKey' => array( 'moveddeleted-notice' )
582 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
583 // Only show an upload link if the user can upload
584 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
585 $nofile = array(
586 'filepage-nofile-link',
587 $uploadTitle->getFullURL( array( 'wpDestFile' => $this->mPage->getFile()->getName() ) )
589 } else {
590 $nofile = 'filepage-nofile';
592 // Note, if there is an image description page, but
593 // no image, then this setRobotPolicy is overridden
594 // by Article::View().
595 $out->setRobotPolicy( 'noindex,nofollow' );
596 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
597 if ( !$this->getID() && $wgSend404Code ) {
598 // If there is no image, no shared image, and no description page,
599 // output a 404, to be consistent with articles.
600 $request->response()->header( 'HTTP/1.1 404 Not Found' );
603 $out->setFileVersion( $this->displayImg );
607 * Creates an thumbnail of specified size and returns an HTML link to it
608 * @param array $params Scaler parameters
609 * @param int $width
610 * @param int $height
611 * @return string
613 private function makeSizeLink( $params, $width, $height ) {
614 $params['width'] = $width;
615 $params['height'] = $height;
616 $thumbnail = $this->displayImg->transform( $params );
617 if ( $thumbnail && !$thumbnail->isError() ) {
618 return Html::rawElement( 'a', array(
619 'href' => $thumbnail->getUrl(),
620 'class' => 'mw-thumbnail-link'
621 ), wfMessage( 'show-big-image-size' )->numParams(
622 $thumbnail->getWidth(), $thumbnail->getHeight()
623 )->parse() );
624 } else {
625 return '';
630 * Show a notice that the file is from a shared repository
632 protected function printSharedImageText() {
633 $out = $this->getContext()->getOutput();
634 $this->loadFile();
636 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
637 $descText = $this->mPage->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
639 /* Add canonical to head if there is no local page for this shared file */
640 if ( $descUrl && $this->mPage->getID() == 0 ) {
641 $out->setCanonicalUrl( $descUrl );
644 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
645 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
647 if ( $descUrl && $descText && wfMessage( 'sharedupload-desc-here' )->plain() !== '-' ) {
648 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
649 } elseif ( $descUrl && wfMessage( 'sharedupload-desc-there' )->plain() !== '-' ) {
650 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
651 } else {
652 $out->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
655 if ( $descText ) {
656 $this->mExtraDescription = $descText;
660 public function getUploadUrl() {
661 $this->loadFile();
662 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
663 return $uploadTitle->getFullURL( array(
664 'wpDestFile' => $this->mPage->getFile()->getName(),
665 'wpForReUpload' => 1
666 ) );
670 * Print out the various links at the bottom of the image page, e.g. reupload,
671 * external editing (and instructions link) etc.
673 protected function uploadLinksBox() {
674 global $wgEnableUploads;
676 if ( !$wgEnableUploads ) {
677 return;
680 $this->loadFile();
681 if ( !$this->mPage->getFile()->isLocal() ) {
682 return;
685 $out = $this->getContext()->getOutput();
686 $out->addHTML( "<ul>\n" );
688 # "Upload a new version of this file" link
689 $canUpload = $this->getTitle()->userCan( 'upload', $this->getContext()->getUser() );
690 if ( $canUpload && UploadBase::userCanReUpload(
691 $this->getContext()->getUser(),
692 $this->mPage->getFile()->name )
694 $ulink = Linker::makeExternalLink(
695 $this->getUploadUrl(),
696 wfMessage( 'uploadnewversion-linktext' )->text()
698 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\">"
699 . "<div class=\"plainlinks\">{$ulink}</div></li>\n" );
700 } else {
701 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">"
702 . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
705 $out->addHTML( "</ul>\n" );
709 * For overloading
711 protected function closeShowImage() {
715 * If the page we've just displayed is in the "Image" namespace,
716 * we follow it with an upload history of the image and its usage.
718 protected function imageHistory() {
719 $this->loadFile();
720 $out = $this->getContext()->getOutput();
721 $pager = new ImageHistoryPseudoPager( $this );
722 $out->addHTML( $pager->getBody() );
723 $out->preventClickjacking( $pager->getPreventClickjacking() );
725 $this->mPage->getFile()->resetHistory(); // free db resources
727 # Exist check because we don't want to show this on pages where an image
728 # doesn't exist along with the noimage message, that would suck. -ævar
729 if ( $this->mPage->getFile()->exists() ) {
730 $this->uploadLinksBox();
735 * @param string $target
736 * @param int $limit
737 * @return ResultWrapper
739 protected function queryImageLinks( $target, $limit ) {
740 $dbr = wfGetDB( DB_SLAVE );
742 return $dbr->select(
743 array( 'imagelinks', 'page' ),
744 array( 'page_namespace', 'page_title', 'il_to' ),
745 array( 'il_to' => $target, 'il_from = page_id' ),
746 __METHOD__,
747 array( 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', )
751 protected function imageLinks() {
752 $limit = 100;
754 $out = $this->getContext()->getOutput();
756 $rows = array();
757 $redirects = array();
758 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE ) as $redir ) {
759 $redirects[$redir->getDBkey()] = array();
760 $rows[] = (object)array(
761 'page_namespace' => NS_FILE,
762 'page_title' => $redir->getDBkey(),
766 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit + 1 );
767 foreach ( $res as $row ) {
768 $rows[] = $row;
770 $count = count( $rows );
772 $hasMore = $count > $limit;
773 if ( !$hasMore && count( $redirects ) ) {
774 $res = $this->queryImageLinks( array_keys( $redirects ),
775 $limit - count( $rows ) + 1 );
776 foreach ( $res as $row ) {
777 $redirects[$row->il_to][] = $row;
778 $count++;
780 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
783 if ( $count == 0 ) {
784 $out->wrapWikiMsg(
785 Html::rawElement( 'div',
786 array( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ),
787 'nolinkstoimage'
789 return;
792 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
793 if ( !$hasMore ) {
794 $out->addWikiMsg( 'linkstoimage', $count );
795 } else {
796 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
797 $out->addWikiMsg( 'linkstoimage-more',
798 $this->getContext()->getLanguage()->formatNum( $limit ),
799 $this->getTitle()->getPrefixedDBkey()
803 $out->addHTML(
804 Html::openElement( 'ul',
805 array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n"
807 $count = 0;
809 // Sort the list by namespace:title
810 usort( $rows, array( $this, 'compare' ) );
812 // Create links for every element
813 $currentCount = 0;
814 foreach ( $rows as $element ) {
815 $currentCount++;
816 if ( $currentCount > $limit ) {
817 break;
820 $query = array();
821 # Add a redirect=no to make redirect pages reachable
822 if ( isset( $redirects[$element->page_title] ) ) {
823 $query['redirect'] = 'no';
825 $link = Linker::linkKnown(
826 Title::makeTitle( $element->page_namespace, $element->page_title ),
827 null, array(), $query
829 if ( !isset( $redirects[$element->page_title] ) ) {
830 # No redirects
831 $liContents = $link;
832 } elseif ( count( $redirects[$element->page_title] ) === 0 ) {
833 # Redirect without usages
834 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams( $link, '' )->parse();
835 } else {
836 # Redirect with usages
837 $li = '';
838 foreach ( $redirects[$element->page_title] as $row ) {
839 $currentCount++;
840 if ( $currentCount > $limit ) {
841 break;
844 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
845 $li .= Html::rawElement(
846 'li',
847 array( 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
848 $link2
849 ) . "\n";
852 $ul = Html::rawElement(
853 'ul',
854 array( 'class' => 'mw-imagepage-redirectstofile' ),
856 ) . "\n";
857 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams(
858 $link, $ul )->parse();
860 $out->addHTML( Html::rawElement(
861 'li',
862 array( 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
863 $liContents
864 ) . "\n"
868 $out->addHTML( Html::closeElement( 'ul' ) . "\n" );
869 $res->free();
871 // Add a links to [[Special:Whatlinkshere]]
872 if ( $count > $limit ) {
873 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
875 $out->addHTML( Html::closeElement( 'div' ) . "\n" );
878 protected function imageDupes() {
879 $this->loadFile();
880 $out = $this->getContext()->getOutput();
882 $dupes = $this->mPage->getDuplicates();
883 if ( count( $dupes ) == 0 ) {
884 return;
887 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
888 $out->addWikiMsg( 'duplicatesoffile',
889 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
891 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
894 * @var $file File
896 foreach ( $dupes as $file ) {
897 $fromSrc = '';
898 if ( $file->isLocal() ) {
899 $link = Linker::linkKnown( $file->getTitle() );
900 } else {
901 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
902 $file->getTitle()->getPrefixedText() );
903 $fromSrc = wfMessage( 'shared-repo-from', $file->getRepo()->getDisplayName() )->text();
905 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
907 $out->addHTML( "</ul></div>\n" );
911 * Delete the file, or an earlier version of it
913 public function delete() {
914 $file = $this->mPage->getFile();
915 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
916 // Standard article deletion
917 parent::delete();
918 return;
921 $deleter = new FileDeleteForm( $file );
922 $deleter->execute();
926 * Display an error with a wikitext description
928 * @param string $description
930 function showError( $description ) {
931 $out = $this->getContext()->getOutput();
932 $out->setPageTitle( wfMessage( 'internalerror' ) );
933 $out->setRobotPolicy( 'noindex,nofollow' );
934 $out->setArticleRelated( false );
935 $out->enableClientCache( false );
936 $out->addWikiText( $description );
940 * Callback for usort() to do link sorts by (namespace, title)
941 * Function copied from Title::compare()
943 * @param object $a Object page to compare with
944 * @param object $b Object page to compare with
945 * @return int Result of string comparison, or namespace comparison
947 protected function compare( $a, $b ) {
948 if ( $a->page_namespace == $b->page_namespace ) {
949 return strcmp( $a->page_title, $b->page_title );
950 } else {
951 return $a->page_namespace - $b->page_namespace;
956 * Returns the corresponding $wgImageLimits entry for the selected user option
958 * @param User $user
959 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
960 * @return array
961 * @since 1.21
963 public function getImageLimitsFromOption( $user, $optionName ) {
964 global $wgImageLimits;
966 $option = $user->getIntOption( $optionName );
967 if ( !isset( $wgImageLimits[$option] ) ) {
968 $option = User::getDefaultOption( $optionName );
971 // The user offset might still be incorrect, specially if
972 // $wgImageLimits got changed (see bug #8858).
973 if ( !isset( $wgImageLimits[$option] ) ) {
974 // Default to the first offset in $wgImageLimits
975 $option = 0;
978 return isset( $wgImageLimits[$option] )
979 ? $wgImageLimits[$option]
980 : array( 800, 600 ); // if nothing is set, fallback to a hardcoded default
984 * Output a drop-down box for language options for the file
986 * @param array $langChoices Array of string language codes
987 * @param string $curLang Language code file is being viewed in.
988 * @param string $defaultLang Language code that image is rendered in by default
989 * @return string HTML to insert underneath image.
991 protected function doRenderLangOpt( array $langChoices, $curLang, $defaultLang ) {
992 global $wgScript;
993 sort( $langChoices );
994 $curLang = wfBCP47( $curLang );
995 $defaultLang = wfBCP47( $defaultLang );
996 $opts = '';
997 $haveCurrentLang = false;
998 $haveDefaultLang = false;
1000 // We make a list of all the language choices in the file.
1001 // Additionally if the default language to render this file
1002 // is not included as being in this file (for example, in svgs
1003 // usually the fallback content is the english content) also
1004 // include a choice for that. Last of all, if we're viewing
1005 // the file in a language not on the list, add it as a choice.
1006 foreach ( $langChoices as $lang ) {
1007 $code = wfBCP47( $lang );
1008 $name = Language::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1009 if ( $name !== '' ) {
1010 $display = wfMessage( 'img-lang-opt', $code, $name )->text();
1011 } else {
1012 $display = $code;
1014 $opts .= "\n" . Xml::option( $display, $code, $curLang === $code );
1015 if ( $curLang === $code ) {
1016 $haveCurrentLang = true;
1018 if ( $defaultLang === $code ) {
1019 $haveDefaultLang = true;
1022 if ( !$haveDefaultLang ) {
1023 // Its hard to know if the content is really in the default language, or
1024 // if its just unmarked content that could be in any language.
1025 $opts = Xml::option(
1026 wfMessage( 'img-lang-default' )->text(),
1027 $defaultLang,
1028 $defaultLang === $curLang
1029 ) . $opts;
1031 if ( !$haveCurrentLang && $defaultLang !== $curLang ) {
1032 $name = Language::fetchLanguageName( $curLang, $this->getContext()->getLanguage()->getCode() );
1033 if ( $name !== '' ) {
1034 $display = wfMessage( 'img-lang-opt', $curLang, $name )->text();
1035 } else {
1036 $display = $curLang;
1038 $opts = Xml::option( $display, $curLang, true ) . $opts;
1041 $select = Html::rawElement(
1042 'select',
1043 array( 'id' => 'mw-imglangselector', 'name' => 'lang' ),
1044 $opts
1046 $submit = Xml::submitButton( wfMessage( 'img-lang-go' )->text() );
1048 $formContents = wfMessage( 'img-lang-info' )->rawParams( $select, $submit )->parse()
1049 . Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1051 $langSelectLine = Html::rawElement( 'div', array( 'id' => 'mw-imglangselector-line' ),
1052 Html::rawElement( 'form', array( 'action' => $wgScript ), $formContents )
1054 return $langSelectLine;
1058 * Get the width and height to display image at.
1060 * @note This method assumes that it is only called if one
1061 * of the dimensions are bigger than the max, or if the
1062 * image is vectorized.
1064 * @param $maxWidth integer Max width to display at
1065 * @param $maxHeight integer Max height to display at
1066 * @param $width integer Actual width of the image
1067 * @param $height integer Actual height of the image
1068 * @throws MWException
1069 * @return Array (width, height)
1071 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1072 if ( !$maxWidth || !$maxHeight ) {
1073 // should never happen
1074 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1077 if ( !$width || !$height ) {
1078 return array( 0, 0 );
1081 # Calculate the thumbnail size.
1082 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1083 // Vectorized image, do nothing.
1084 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1085 # The limiting factor is the width, not the height.
1086 $height = round( $height * $maxWidth / $width );
1087 $width = $maxWidth;
1088 # Note that $height <= $maxHeight now.
1089 } else {
1090 $newwidth = floor( $width * $maxHeight / $height );
1091 $height = round( $height * $newwidth / $width );
1092 $width = $newwidth;
1093 # Note that $height <= $maxHeight now, but might not be identical
1094 # because of rounding.
1096 return array( $width, $height );
1100 * Get alternative thumbnail sizes.
1102 * @note This will only list several alternatives if thumbnails are rendered on 404
1103 * @param $origWidth Actual width of image
1104 * @param $origHeight Actual height of image
1105 * @return Array An array of [width, height] pairs.
1107 protected function getThumbSizes( $origWidth, $origHeight ) {
1108 global $wgImageLimits;
1109 if ( $this->displayImg->getRepo()->canTransformVia404() ) {
1110 $thumbSizes = $wgImageLimits;
1111 // Also include the full sized resolution in the list, so
1112 // that users know they can get it. This will link to the
1113 // original file asset if mustRender() === false. In the case
1114 // that we mustRender, some users have indicated that they would
1115 // find it useful to have the full size image in the rendered
1116 // image format.
1117 $thumbSizes[] = array( $origWidth, $origHeight );
1118 } else {
1119 # Creating thumb links triggers thumbnail generation.
1120 # Just generate the thumb for the current users prefs.
1121 $thumbSizes = array( $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' ) );
1122 if ( !$this->displayImg->mustRender() ) {
1123 // We can safely include a link to the "full-size" preview,
1124 // without actually rendering.
1125 $thumbSizes[] = array( $origWidth, $origHeight );
1128 return $thumbSizes;
1134 * Builds the image revision log shown on image pages
1136 * @ingroup Media
1138 class ImageHistoryList extends ContextSource {
1141 * @var Title
1143 protected $title;
1146 * @var File
1148 protected $img;
1151 * @var ImagePage
1153 protected $imagePage;
1156 * @var File
1158 protected $current;
1160 protected $repo, $showThumb;
1161 protected $preventClickjacking = false;
1164 * @param ImagePage $imagePage
1166 public function __construct( $imagePage ) {
1167 global $wgShowArchiveThumbnails;
1168 $this->current = $imagePage->getFile();
1169 $this->img = $imagePage->getDisplayedFile();
1170 $this->title = $imagePage->getTitle();
1171 $this->imagePage = $imagePage;
1172 $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
1173 $this->setContext( $imagePage->getContext() );
1177 * @return ImagePage
1179 public function getImagePage() {
1180 return $this->imagePage;
1184 * @return File
1186 public function getFile() {
1187 return $this->img;
1191 * @param string $navLinks
1192 * @return string
1194 public function beginImageHistoryList( $navLinks = '' ) {
1195 return Xml::element( 'h2', array( 'id' => 'filehistory' ), $this->msg( 'filehist' )->text() )
1196 . "\n"
1197 . "<div id=\"mw-imagepage-section-filehistory\">\n"
1198 . $this->msg( 'filehist-help' )->parseAsBlock()
1199 . $navLinks . "\n"
1200 . Xml::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
1201 . '<tr><td></td>'
1202 . ( $this->current->isLocal()
1203 && ( $this->getUser()->isAllowedAny( 'delete', 'deletedhistory' ) ) ? '<td></td>' : '' )
1204 . '<th>' . $this->msg( 'filehist-datetime' )->escaped() . '</th>'
1205 . ( $this->showThumb ? '<th>' . $this->msg( 'filehist-thumb' )->escaped() . '</th>' : '' )
1206 . '<th>' . $this->msg( 'filehist-dimensions' )->escaped() . '</th>'
1207 . '<th>' . $this->msg( 'filehist-user' )->escaped() . '</th>'
1208 . '<th>' . $this->msg( 'filehist-comment' )->escaped() . '</th>'
1209 . "</tr>\n";
1213 * @param string $navLinks
1214 * @return string
1216 public function endImageHistoryList( $navLinks = '' ) {
1217 return "</table>\n$navLinks\n</div>\n";
1221 * @param bool $iscur
1222 * @param File $file
1223 * @return string
1225 public function imageHistoryLine( $iscur, $file ) {
1226 global $wgContLang;
1228 $user = $this->getUser();
1229 $lang = $this->getLanguage();
1230 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1231 $img = $iscur ? $file->getName() : $file->getArchiveName();
1232 $userId = $file->getUser( 'id' );
1233 $userText = $file->getUser( 'text' );
1234 $description = $file->getDescription( File::FOR_THIS_USER, $user );
1236 $local = $this->current->isLocal();
1237 $row = $selected = '';
1239 // Deletion link
1240 if ( $local && ( $user->isAllowedAny( 'delete', 'deletedhistory' ) ) ) {
1241 $row .= '<td>';
1242 # Link to remove from history
1243 if ( $user->isAllowed( 'delete' ) ) {
1244 $q = array( 'action' => 'delete' );
1245 if ( !$iscur ) {
1246 $q['oldimage'] = $img;
1248 $row .= Linker::linkKnown(
1249 $this->title,
1250 $this->msg( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' )->escaped(),
1251 array(), $q
1254 # Link to hide content. Don't show useless link to people who cannot hide revisions.
1255 $canHide = $user->isAllowed( 'deleterevision' );
1256 if ( $canHide || ( $user->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
1257 if ( $user->isAllowed( 'delete' ) ) {
1258 $row .= '<br />';
1260 // If file is top revision or locked from this user, don't link
1261 if ( $iscur || !$file->userCan( File::DELETED_RESTRICTED, $user ) ) {
1262 $del = Linker::revDeleteLinkDisabled( $canHide );
1263 } else {
1264 list( $ts, ) = explode( '!', $img, 2 );
1265 $query = array(
1266 'type' => 'oldimage',
1267 'target' => $this->title->getPrefixedText(),
1268 'ids' => $ts,
1270 $del = Linker::revDeleteLink( $query,
1271 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
1273 $row .= $del;
1275 $row .= '</td>';
1278 // Reversion link/current indicator
1279 $row .= '<td>';
1280 if ( $iscur ) {
1281 $row .= $this->msg( 'filehist-current' )->escaped();
1282 } elseif ( $local && $this->title->quickUserCan( 'edit', $user )
1283 && $this->title->quickUserCan( 'upload', $user )
1285 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1286 $row .= $this->msg( 'filehist-revert' )->escaped();
1287 } else {
1288 $row .= Linker::linkKnown(
1289 $this->title,
1290 $this->msg( 'filehist-revert' )->escaped(),
1291 array(),
1292 array(
1293 'action' => 'revert',
1294 'oldimage' => $img,
1295 'wpEditToken' => $user->getEditToken( $img )
1300 $row .= '</td>';
1302 // Date/time and image link
1303 if ( $file->getTimestamp() === $this->img->getTimestamp() ) {
1304 $selected = "class='filehistory-selected'";
1306 $row .= "<td $selected style='white-space: nowrap;'>";
1307 if ( !$file->userCan( File::DELETED_FILE, $user ) ) {
1308 # Don't link to unviewable files
1309 $row .= '<span class="history-deleted">'
1310 . $lang->userTimeAndDate( $timestamp, $user ) . '</span>';
1311 } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
1312 if ( $local ) {
1313 $this->preventClickjacking();
1314 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
1315 # Make a link to review the image
1316 $url = Linker::linkKnown(
1317 $revdel,
1318 $lang->userTimeAndDate( $timestamp, $user ),
1319 array(),
1320 array(
1321 'target' => $this->title->getPrefixedText(),
1322 'file' => $img,
1323 'token' => $user->getEditToken( $img )
1326 } else {
1327 $url = $lang->userTimeAndDate( $timestamp, $user );
1329 $row .= '<span class="history-deleted">' . $url . '</span>';
1330 } else {
1331 $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
1332 $row .= Xml::element(
1333 'a',
1334 array( 'href' => $url ),
1335 $lang->userTimeAndDate( $timestamp, $user )
1338 $row .= "</td>";
1340 // Thumbnail
1341 if ( $this->showThumb ) {
1342 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1345 // Image dimensions + size
1346 $row .= '<td>';
1347 $row .= htmlspecialchars( $file->getDimensionsString() );
1348 $row .= $this->msg( 'word-separator' )->escaped();
1349 $row .= '<span style="white-space: nowrap;">';
1350 $row .= $this->msg( 'parentheses' )->sizeParams( $file->getSize() )->escaped();
1351 $row .= '</span>';
1352 $row .= '</td>';
1354 // Uploading user
1355 $row .= '<td>';
1356 // Hide deleted usernames
1357 if ( $file->isDeleted( File::DELETED_USER ) ) {
1358 $row .= '<span class="history-deleted">'
1359 . $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
1360 } else {
1361 if ( $local ) {
1362 $row .= Linker::userLink( $userId, $userText );
1363 $row .= $this->msg( 'word-separator' )->escaped();
1364 $row .= '<span style="white-space: nowrap;">';
1365 $row .= Linker::userToolLinks( $userId, $userText );
1366 $row .= '</span>';
1367 } else {
1368 $row .= htmlspecialchars( $userText );
1371 $row .= '</td>';
1373 // Don't show deleted descriptions
1374 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1375 $row .= '<td><span class="history-deleted">' .
1376 $this->msg( 'rev-deleted-comment' )->escaped() . '</span></td>';
1377 } else {
1378 $row .= '<td dir="' . $wgContLang->getDir() . '">' .
1379 Linker::formatComment( $description, $this->title ) . '</td>';
1382 $rowClass = null;
1383 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1384 $classAttr = $rowClass ? " class='$rowClass'" : '';
1386 return "<tr{$classAttr}>{$row}</tr>\n";
1390 * @param File $file
1391 * @return string
1393 protected function getThumbForLine( $file ) {
1394 $lang = $this->getLanguage();
1395 $user = $this->getUser();
1396 if ( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE, $user )
1397 && !$file->isDeleted( File::DELETED_FILE )
1399 $params = array(
1400 'width' => '120',
1401 'height' => '120',
1403 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1405 $thumbnail = $file->transform( $params );
1406 $options = array(
1407 'alt' => $this->msg( 'filehist-thumbtext',
1408 $lang->userTimeAndDate( $timestamp, $user ),
1409 $lang->userDate( $timestamp, $user ),
1410 $lang->userTime( $timestamp, $user ) )->text(),
1411 'file-link' => true,
1414 if ( !$thumbnail ) {
1415 return $this->msg( 'filehist-nothumb' )->escaped();
1418 return $thumbnail->toHtml( $options );
1419 } else {
1420 return $this->msg( 'filehist-nothumb' )->escaped();
1425 * @param bool $enable
1427 protected function preventClickjacking( $enable = true ) {
1428 $this->preventClickjacking = $enable;
1432 * @return bool
1434 public function getPreventClickjacking() {
1435 return $this->preventClickjacking;
1439 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1440 protected $preventClickjacking = false;
1443 * @var File
1445 protected $mImg;
1448 * @var Title
1450 protected $mTitle;
1453 * @param ImagePage $imagePage
1455 function __construct( $imagePage ) {
1456 parent::__construct( $imagePage->getContext() );
1457 $this->mImagePage = $imagePage;
1458 $this->mTitle = clone ( $imagePage->getTitle() );
1459 $this->mTitle->setFragment( '#filehistory' );
1460 $this->mImg = null;
1461 $this->mHist = array();
1462 $this->mRange = array( 0, 0 ); // display range
1466 * @return Title
1468 function getTitle() {
1469 return $this->mTitle;
1472 function getQueryInfo() {
1473 return false;
1477 * @return string
1479 function getIndexField() {
1480 return '';
1484 * @param object $row
1485 * @return string
1487 function formatRow( $row ) {
1488 return '';
1492 * @return string
1494 function getBody() {
1495 $s = '';
1496 $this->doQuery();
1497 if ( count( $this->mHist ) ) {
1498 $list = new ImageHistoryList( $this->mImagePage );
1499 # Generate prev/next links
1500 $navLink = $this->getNavigationBar();
1501 $s = $list->beginImageHistoryList( $navLink );
1502 // Skip rows there just for paging links
1503 for ( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1504 $file = $this->mHist[$i];
1505 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1507 $s .= $list->endImageHistoryList( $navLink );
1509 if ( $list->getPreventClickjacking() ) {
1510 $this->preventClickjacking();
1513 return $s;
1516 function doQuery() {
1517 if ( $this->mQueryDone ) {
1518 return;
1520 $this->mImg = $this->mImagePage->getFile(); // ensure loading
1521 if ( !$this->mImg->exists() ) {
1522 return;
1524 $queryLimit = $this->mLimit + 1; // limit plus extra row
1525 if ( $this->mIsBackwards ) {
1526 // Fetch the file history
1527 $this->mHist = $this->mImg->getHistory( $queryLimit, null, $this->mOffset, false );
1528 // The current rev may not meet the offset/limit
1529 $numRows = count( $this->mHist );
1530 if ( $numRows <= $this->mLimit && $this->mImg->getTimestamp() > $this->mOffset ) {
1531 $this->mHist = array_merge( array( $this->mImg ), $this->mHist );
1533 } else {
1534 // The current rev may not meet the offset
1535 if ( !$this->mOffset || $this->mImg->getTimestamp() < $this->mOffset ) {
1536 $this->mHist[] = $this->mImg;
1538 // Old image versions (fetch extra row for nav links)
1539 $oiLimit = count( $this->mHist ) ? $this->mLimit : $this->mLimit + 1;
1540 // Fetch the file history
1541 $this->mHist = array_merge( $this->mHist,
1542 $this->mImg->getHistory( $oiLimit, $this->mOffset, null, false ) );
1544 $numRows = count( $this->mHist ); // Total number of query results
1545 if ( $numRows ) {
1546 # Index value of top item in the list
1547 $firstIndex = $this->mIsBackwards ?
1548 $this->mHist[$numRows - 1]->getTimestamp() : $this->mHist[0]->getTimestamp();
1549 # Discard the extra result row if there is one
1550 if ( $numRows > $this->mLimit && $numRows > 1 ) {
1551 if ( $this->mIsBackwards ) {
1552 # Index value of item past the index
1553 $this->mPastTheEndIndex = $this->mHist[0]->getTimestamp();
1554 # Index value of bottom item in the list
1555 $lastIndex = $this->mHist[1]->getTimestamp();
1556 # Display range
1557 $this->mRange = array( 1, $numRows - 1 );
1558 } else {
1559 # Index value of item past the index
1560 $this->mPastTheEndIndex = $this->mHist[$numRows - 1]->getTimestamp();
1561 # Index value of bottom item in the list
1562 $lastIndex = $this->mHist[$numRows - 2]->getTimestamp();
1563 # Display range
1564 $this->mRange = array( 0, $numRows - 2 );
1566 } else {
1567 # Setting indexes to an empty string means that they will be
1568 # omitted if they would otherwise appear in URLs. It just so
1569 # happens that this is the right thing to do in the standard
1570 # UI, in all the relevant cases.
1571 $this->mPastTheEndIndex = '';
1572 # Index value of bottom item in the list
1573 $lastIndex = $this->mIsBackwards ?
1574 $this->mHist[0]->getTimestamp() : $this->mHist[$numRows - 1]->getTimestamp();
1575 # Display range
1576 $this->mRange = array( 0, $numRows - 1 );
1578 } else {
1579 $firstIndex = '';
1580 $lastIndex = '';
1581 $this->mPastTheEndIndex = '';
1583 if ( $this->mIsBackwards ) {
1584 $this->mIsFirst = ( $numRows < $queryLimit );
1585 $this->mIsLast = ( $this->mOffset == '' );
1586 $this->mLastShown = $firstIndex;
1587 $this->mFirstShown = $lastIndex;
1588 } else {
1589 $this->mIsFirst = ( $this->mOffset == '' );
1590 $this->mIsLast = ( $numRows < $queryLimit );
1591 $this->mLastShown = $lastIndex;
1592 $this->mFirstShown = $firstIndex;
1594 $this->mQueryDone = true;
1598 * @param bool $enable
1600 protected function preventClickjacking( $enable = true ) {
1601 $this->preventClickjacking = $enable;
1605 * @return bool
1607 public function getPreventClickjacking() {
1608 return $this->preventClickjacking;