Refactor diffs
[mediawiki.git] / includes / ImagePage.php
blobcf05ee258569ebd2ad3cba6eb9434942009c245c
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 {
30 /**
31 * @var File
33 private $displayImg;
34 /**
35 * @var FileRepo
37 private $repo;
38 private $fileLoaded;
40 var $mExtraDescription = false;
42 /**
43 * @param $title Title
44 * @return WikiFilePage
46 protected function newPage( Title $title ) {
47 // Overload mPage with a file-specific page
48 return new WikiFilePage( $title );
51 /**
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
63 /**
64 * @param $file File:
65 * @return void
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 ) {
75 return;
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() );
83 if ( !$img ) {
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();
94 /**
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 );
100 parent::view();
103 public function view() {
104 global $wgShowEXIF;
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 ) ) {
112 parent::view();
113 return;
116 $this->loadFile();
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' );
123 parent::view();
124 return;
125 } else {
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() );
132 return;
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;
140 } else {
141 $showmeta = false;
144 if ( !$diff && $this->displayImg->exists() ) {
145 $out->addHTML( $this->showTOC( $showmeta ) );
148 if ( !$diff ) {
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() ) ) );
161 parent::view();
163 $out->addHTML( Xml::closeElement( 'div' ) );
164 } else {
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" );
187 $this->imageDupes();
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
190 $this->imageLinks();
192 # Allow extensions to add something after the image links
193 $html = '';
194 wfRunHooks( 'ImagePageAfterImageLinks', array( $this, &$html ) );
195 if ( $html ) {
196 $out->addHTML( $html );
199 if ( $showmeta ) {
200 $out->addHTML( Xml::element(
201 'h2',
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();
211 if ( $css ) {
212 $out->addStyle( $css );
215 // always show the local local Filepage.css, bug 29277
216 $out->addModuleStyles( 'filepage' );
220 * @return File
222 public function getDisplayedFile() {
223 $this->loadFile();
224 return $this->displayImg;
228 * Create the TOC
230 * @param $metadata Boolean: whether or not to show the metadata link
231 * @return String
233 protected function showTOC( $metadata ) {
234 $r = array(
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>',
239 if ( $metadata ) {
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";
273 return $r;
277 * Overloading Article's getContentObject method.
279 * Omit noarticletext if sharedupload; text will be fetched from the
280 * shared upload server if possible.
281 * @return string
283 public function getContentObject() {
284 $this->loadFile();
285 if ( $this->mPage->getFile() && !$this->mPage->getFile()->isLocal() && 0 == $this->getID() ) {
286 return null;
288 return parent::getContentObject();
291 protected function openShowImage() {
292 global $wgImageLimits, $wgEnableUploads, $wgSend404Code;
294 $this->loadFile();
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' );
302 $maxWidth = $max[0];
303 $maxHeight = $max[1];
305 if ( $this->displayImg->exists() ) {
306 # image
307 $page = $request->getIntOrNull( 'page' );
308 if ( is_null( $page ) ) {
309 $params = array();
310 $page = 1;
311 } else {
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() ) {
331 # image
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
341 $width = $maxWidth;
342 # Note that $height <= $maxHeight now.
343 } else {
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
346 $width = $newwidth;
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 } else {
354 # Creating thumb links triggers thumbnail generation.
355 # Just generate the thumb for the current users prefs.
356 $thumbSizes = array( $this->getImageLimitsFromOption( $user, 'thumbsize' ) );
358 # Generate thumbnails or thumbnail links as needed...
359 $otherSizes = array();
360 foreach ( $thumbSizes as $size ) {
361 if ( $size[0] < $width_orig && $size[1] < $height_orig
362 && $size[0] != $width && $size[1] != $height )
364 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
365 if ( $sizeLink ) {
366 $otherSizes[] = $sizeLink;
370 $msgsmall = '';
371 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
372 if ( $sizeLinkBigImagePreview ) {
373 $msgsmall .= wfMessage( 'show-big-image-preview' )->
374 rawParams( $sizeLinkBigImagePreview )->
375 parse();
377 if ( count( $otherSizes ) ) {
378 $msgsmall .= ' ' .
379 Html::rawElement( 'span', array( 'class' => 'mw-filepage-other-resolutions' ),
380 wfMessage( 'show-big-image-other' )->rawParams( $lang->pipeList( $otherSizes ) )->
381 params( count( $otherSizes ) )->parse()
384 } elseif ( $width == 0 && $height == 0 ) {
385 # Some sort of audio file that doesn't have dimensions
386 # Don't output a no hi res message for such a file
387 $msgsmall = '';
388 } elseif ( $this->displayImg->isVectorized() ) {
389 # For vectorized images, full size is just the frame size
390 $msgsmall = '';
391 } else {
392 # Image is small enough to show full size on image page
393 $msgsmall = wfMessage( 'file-nohires' )->parse();
396 $params['width'] = $width;
397 $params['height'] = $height;
398 $thumbnail = $this->displayImg->transform( $params );
400 $anchorclose = Html::rawElement( 'div', array( 'class' => 'mw-filepage-resolutioninfo' ), $msgsmall );
402 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
403 if ( $isMulti ) {
404 $out->addModules( 'mediawiki.page.image.pagination' );
405 $out->addHTML( '<table class="multipageimage"><tr><td>' );
408 if ( $thumbnail ) {
409 $options = array(
410 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
411 'file-link' => true,
413 $out->addHTML( '<div class="fullImageLink" id="file">' .
414 $thumbnail->toHtml( $options ) .
415 $anchorclose . "</div>\n" );
418 if ( $isMulti ) {
419 $count = $this->displayImg->pageCount();
421 if ( $page > 1 ) {
422 $label = $out->parse( wfMessage( 'imgmultipageprev' )->text(), false );
423 $link = Linker::linkKnown(
424 $this->getTitle(),
425 $label,
426 array(),
427 array( 'page' => $page - 1 )
429 $thumb1 = Linker::makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
430 array( 'page' => $page - 1 ) );
431 } else {
432 $thumb1 = '';
435 if ( $page < $count ) {
436 $label = wfMessage( 'imgmultipagenext' )->text();
437 $link = Linker::linkKnown(
438 $this->getTitle(),
439 $label,
440 array(),
441 array( 'page' => $page + 1 )
443 $thumb2 = Linker::makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
444 array( 'page' => $page + 1 ) );
445 } else {
446 $thumb2 = '';
449 global $wgScript;
451 $formParams = array(
452 'name' => 'pageselector',
453 'action' => $wgScript,
455 $options = array();
456 for ( $i = 1; $i <= $count; $i++ ) {
457 $options[] = Xml::option( $lang->formatNum( $i ), $i, $i == $page );
459 $select = Xml::tags( 'select',
460 array( 'id' => 'pageselector', 'name' => 'page' ),
461 implode( "\n", $options ) );
463 $out->addHTML(
464 '</td><td><div class="multipageimagenavbox">' .
465 Xml::openElement( 'form', $formParams ) .
466 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
467 wfMessage( 'imgmultigoto' )->rawParams( $select )->parse() .
468 Xml::submitButton( wfMessage( 'imgmultigo' )->text() ) .
469 Xml::closeElement( 'form' ) .
470 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
473 } elseif ( $this->displayImg->isSafeFile() ) {
474 # if direct link is allowed but it's not a renderable image, show an icon.
475 $icon = $this->displayImg->iconThumb();
477 $out->addHTML( '<div class="fullImageLink" id="file">' .
478 $icon->toHtml( array( 'file-link' => true ) ) .
479 "</div>\n" );
482 $longDesc = wfMessage( 'parentheses', $this->displayImg->getLongDesc() )->text();
484 $medialink = "[[Media:$filename|$linktext]]";
486 if ( !$this->displayImg->isSafeFile() ) {
487 $warning = wfMessage( 'mediawarning' )->plain();
488 // dirmark is needed here to separate the file name, which
489 // most likely ends in Latin characters, from the description,
490 // which may begin with the file type. In RTL environment
491 // this will get messy.
492 // The dirmark, however, must not be immediately adjacent
493 // to the filename, because it can get copied with it.
494 // See bug 25277.
495 $out->addWikiText( <<<EOT
496 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
497 <div class="mediaWarning">$warning</div>
500 } else {
501 $out->addWikiText( <<<EOT
502 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
503 </div>
508 // Add cannot animate thumbnail warning
509 if ( !$this->displayImg->canAnimateThumbIfAppropriate() ) {
510 // Include the extension so wiki admins can
511 // customize it on a per file-type basis
512 // (aka say things like use format X instead).
513 // additionally have a specific message for
514 // file-no-thumb-animation-gif
515 $ext = $this->displayImg->getExtension();
516 $noAnimMesg = wfMessageFallback(
517 'file-no-thumb-animation-' . $ext,
518 'file-no-thumb-animation'
519 )->plain();
521 $out->addWikiText( <<<EOT
522 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
527 if ( !$this->displayImg->isLocal() ) {
528 $this->printSharedImageText();
530 } else {
531 # Image does not exist
532 if ( !$this->getID() ) {
533 # No article exists either
534 # Show deletion log to be consistent with normal articles
535 LogEventsList::showLogExtract(
536 $out,
537 array( 'delete', 'move' ),
538 $this->getTitle()->getPrefixedText(),
540 array( 'lim' => 10,
541 'conds' => array( "log_action != 'revision'" ),
542 'showIfEmpty' => false,
543 'msgKey' => array( 'moveddeleted-notice' )
548 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
549 // Only show an upload link if the user can upload
550 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
551 $nofile = array(
552 'filepage-nofile-link',
553 $uploadTitle->getFullURL( array( 'wpDestFile' => $this->mPage->getFile()->getName() ) )
555 } else {
556 $nofile = 'filepage-nofile';
558 // Note, if there is an image description page, but
559 // no image, then this setRobotPolicy is overridden
560 // by Article::View().
561 $out->setRobotPolicy( 'noindex,nofollow' );
562 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
563 if ( !$this->getID() && $wgSend404Code ) {
564 // If there is no image, no shared image, and no description page,
565 // output a 404, to be consistent with articles.
566 $request->response()->header( 'HTTP/1.1 404 Not Found' );
569 $out->setFileVersion( $this->displayImg );
573 * Creates an thumbnail of specified size and returns an HTML link to it
574 * @param array $params Scaler parameters
575 * @param $width int
576 * @param $height int
577 * @return string
579 private function makeSizeLink( $params, $width, $height ) {
580 $params['width'] = $width;
581 $params['height'] = $height;
582 $thumbnail = $this->displayImg->transform( $params );
583 if ( $thumbnail && !$thumbnail->isError() ) {
584 return Html::rawElement( 'a', array(
585 'href' => $thumbnail->getUrl(),
586 'class' => 'mw-thumbnail-link'
587 ), wfMessage( 'show-big-image-size' )->numParams(
588 $thumbnail->getWidth(), $thumbnail->getHeight()
589 )->parse() );
590 } else {
591 return '';
596 * Show a notice that the file is from a shared repository
598 protected function printSharedImageText() {
599 $out = $this->getContext()->getOutput();
600 $this->loadFile();
602 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
603 $descText = $this->mPage->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
605 /* Add canonical to head if there is no local page for this shared file */
606 if ( $descUrl && $this->mPage->getID() == 0 ) {
607 $out->setCanonicalUrl( $descUrl );
610 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
611 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
613 if ( $descUrl && $descText && wfMessage( 'sharedupload-desc-here' )->plain() !== '-' ) {
614 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
615 } elseif ( $descUrl && wfMessage( 'sharedupload-desc-there' )->plain() !== '-' ) {
616 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
617 } else {
618 $out->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
621 if ( $descText ) {
622 $this->mExtraDescription = $descText;
626 public function getUploadUrl() {
627 $this->loadFile();
628 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
629 return $uploadTitle->getFullURL( array(
630 'wpDestFile' => $this->mPage->getFile()->getName(),
631 'wpForReUpload' => 1
632 ) );
636 * Print out the various links at the bottom of the image page, e.g. reupload,
637 * external editing (and instructions link) etc.
639 protected function uploadLinksBox() {
640 global $wgEnableUploads;
642 if ( !$wgEnableUploads ) {
643 return;
646 $this->loadFile();
647 if ( !$this->mPage->getFile()->isLocal() ) {
648 return;
651 $out = $this->getContext()->getOutput();
652 $out->addHTML( "<ul>\n" );
654 # "Upload a new version of this file" link
655 $canUpload = $this->getTitle()->userCan( 'upload', $this->getContext()->getUser() );
656 if ( $canUpload && UploadBase::userCanReUpload( $this->getContext()->getUser(), $this->mPage->getFile()->name ) ) {
657 $ulink = Linker::makeExternalLink( $this->getUploadUrl(), wfMessage( 'uploadnewversion-linktext' )->text() );
658 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\"><div class=\"plainlinks\">{$ulink}</div></li>\n" );
659 } else {
660 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">" . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
663 $out->addHTML( "</ul>\n" );
666 protected function closeShowImage() { } # For overloading
669 * If the page we've just displayed is in the "Image" namespace,
670 * we follow it with an upload history of the image and its usage.
672 protected function imageHistory() {
673 $this->loadFile();
674 $out = $this->getContext()->getOutput();
675 $pager = new ImageHistoryPseudoPager( $this );
676 $out->addHTML( $pager->getBody() );
677 $out->preventClickjacking( $pager->getPreventClickjacking() );
679 $this->mPage->getFile()->resetHistory(); // free db resources
681 # Exist check because we don't want to show this on pages where an image
682 # doesn't exist along with the noimage message, that would suck. -ævar
683 if ( $this->mPage->getFile()->exists() ) {
684 $this->uploadLinksBox();
689 * @param $target
690 * @param $limit
691 * @return ResultWrapper
693 protected function queryImageLinks( $target, $limit ) {
694 $dbr = wfGetDB( DB_SLAVE );
696 return $dbr->select(
697 array( 'imagelinks', 'page' ),
698 array( 'page_namespace', 'page_title', 'page_is_redirect', 'il_to' ),
699 array( 'il_to' => $target, 'il_from = page_id' ),
700 __METHOD__,
701 array( 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', )
705 protected function imageLinks() {
706 $limit = 100;
708 $out = $this->getContext()->getOutput();
709 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit + 1 );
710 $rows = array();
711 $redirects = array();
712 foreach ( $res as $row ) {
713 if ( $row->page_is_redirect ) {
714 $redirects[$row->page_title] = array();
716 $rows[] = $row;
718 $count = count( $rows );
720 $hasMore = $count > $limit;
721 if ( !$hasMore && count( $redirects ) ) {
722 $res = $this->queryImageLinks( array_keys( $redirects ),
723 $limit - count( $rows ) + 1 );
724 foreach ( $res as $row ) {
725 $redirects[$row->il_to][] = $row;
726 $count++;
728 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
731 if ( $count == 0 ) {
732 $out->wrapWikiMsg(
733 Html::rawElement( 'div',
734 array( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ),
735 'nolinkstoimage'
737 return;
740 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
741 if ( !$hasMore ) {
742 $out->addWikiMsg( 'linkstoimage', $count );
743 } else {
744 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
745 $out->addWikiMsg( 'linkstoimage-more',
746 $this->getContext()->getLanguage()->formatNum( $limit ),
747 $this->getTitle()->getPrefixedDBkey()
751 $out->addHTML(
752 Html::openElement( 'ul',
753 array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n"
755 $count = 0;
757 // Sort the list by namespace:title
758 usort( $rows, array( $this, 'compare' ) );
760 // Create links for every element
761 $currentCount = 0;
762 foreach ( $rows as $element ) {
763 $currentCount++;
764 if ( $currentCount > $limit ) {
765 break;
768 $query = array();
769 # Add a redirect=no to make redirect pages reachable
770 if ( isset( $redirects[$element->page_title] ) ) {
771 $query['redirect'] = 'no';
773 $link = Linker::linkKnown(
774 Title::makeTitle( $element->page_namespace, $element->page_title ),
775 null, array(), $query
777 if ( !isset( $redirects[$element->page_title] ) ) {
778 # No redirects
779 $liContents = $link;
780 } elseif ( count( $redirects[$element->page_title] ) === 0 ) {
781 # Redirect without usages
782 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams( $link, '' )->parse();
783 } else {
784 # Redirect with usages
785 $li = '';
786 foreach ( $redirects[$element->page_title] as $row ) {
787 $currentCount++;
788 if ( $currentCount > $limit ) {
789 break;
792 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
793 $li .= Html::rawElement(
794 'li',
795 array( 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
796 $link2
797 ) . "\n";
800 $ul = Html::rawElement(
801 'ul',
802 array( 'class' => 'mw-imagepage-redirectstofile' ),
804 ) . "\n";
805 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams(
806 $link, $ul )->parse();
808 $out->addHTML( Html::rawElement(
809 'li',
810 array( 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
811 $liContents
812 ) . "\n"
816 $out->addHTML( Html::closeElement( 'ul' ) . "\n" );
817 $res->free();
819 // Add a links to [[Special:Whatlinkshere]]
820 if ( $count > $limit ) {
821 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
823 $out->addHTML( Html::closeElement( 'div' ) . "\n" );
826 protected function imageDupes() {
827 $this->loadFile();
828 $out = $this->getContext()->getOutput();
830 $dupes = $this->mPage->getDuplicates();
831 if ( count( $dupes ) == 0 ) {
832 return;
835 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
836 $out->addWikiMsg( 'duplicatesoffile',
837 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
839 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
842 * @var $file File
844 foreach ( $dupes as $file ) {
845 $fromSrc = '';
846 if ( $file->isLocal() ) {
847 $link = Linker::linkKnown( $file->getTitle() );
848 } else {
849 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
850 $file->getTitle()->getPrefixedText() );
851 $fromSrc = wfMessage( 'shared-repo-from', $file->getRepo()->getDisplayName() )->text();
853 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
855 $out->addHTML( "</ul></div>\n" );
859 * Delete the file, or an earlier version of it
861 public function delete() {
862 $file = $this->mPage->getFile();
863 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
864 // Standard article deletion
865 parent::delete();
866 return;
869 $deleter = new FileDeleteForm( $file );
870 $deleter->execute();
874 * Display an error with a wikitext description
876 * @param $description String
878 function showError( $description ) {
879 $out = $this->getContext()->getOutput();
880 $out->setPageTitle( wfMessage( 'internalerror' ) );
881 $out->setRobotPolicy( 'noindex,nofollow' );
882 $out->setArticleRelated( false );
883 $out->enableClientCache( false );
884 $out->addWikiText( $description );
888 * Callback for usort() to do link sorts by (namespace, title)
889 * Function copied from Title::compare()
891 * @param $a object page to compare with
892 * @param $b object page to compare with
893 * @return Integer: result of string comparison, or namespace comparison
895 protected function compare( $a, $b ) {
896 if ( $a->page_namespace == $b->page_namespace ) {
897 return strcmp( $a->page_title, $b->page_title );
898 } else {
899 return $a->page_namespace - $b->page_namespace;
904 * Returns the corresponding $wgImageLimits entry for the selected user option
906 * @param $user User
907 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
908 * @return array
909 * @since 1.21
911 public function getImageLimitsFromOption( $user, $optionName ) {
912 global $wgImageLimits;
914 $option = $user->getIntOption( $optionName );
915 if ( !isset( $wgImageLimits[$option] ) ) {
916 $option = User::getDefaultOption( $optionName );
919 // The user offset might still be incorrect, specially if
920 // $wgImageLimits got changed (see bug #8858).
921 if ( !isset( $wgImageLimits[$option] ) ) {
922 // Default to the first offset in $wgImageLimits
923 $option = 0;
926 return isset( $wgImageLimits[$option] )
927 ? $wgImageLimits[$option]
928 : array( 800, 600 ); // if nothing is set, fallback to a hardcoded default
933 * Builds the image revision log shown on image pages
935 * @ingroup Media
937 class ImageHistoryList extends ContextSource {
940 * @var Title
942 protected $title;
945 * @var File
947 protected $img;
950 * @var ImagePage
952 protected $imagePage;
955 * @var File
957 protected $current;
959 protected $repo, $showThumb;
960 protected $preventClickjacking = false;
963 * @param ImagePage $imagePage
965 public function __construct( $imagePage ) {
966 global $wgShowArchiveThumbnails;
967 $this->current = $imagePage->getFile();
968 $this->img = $imagePage->getDisplayedFile();
969 $this->title = $imagePage->getTitle();
970 $this->imagePage = $imagePage;
971 $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
972 $this->setContext( $imagePage->getContext() );
976 * @return ImagePage
978 public function getImagePage() {
979 return $this->imagePage;
983 * @return File
985 public function getFile() {
986 return $this->img;
990 * @param $navLinks string
991 * @return string
993 public function beginImageHistoryList( $navLinks = '' ) {
994 return Xml::element( 'h2', array( 'id' => 'filehistory' ), $this->msg( 'filehist' )->text() ) . "\n"
995 . "<div id=\"mw-imagepage-section-filehistory\">\n"
996 . $this->msg( 'filehist-help' )->parseAsBlock()
997 . $navLinks . "\n"
998 . Xml::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
999 . '<tr><td></td>'
1000 . ( $this->current->isLocal() && ( $this->getUser()->isAllowedAny( 'delete', 'deletedhistory' ) ) ? '<td></td>' : '' )
1001 . '<th>' . $this->msg( 'filehist-datetime' )->escaped() . '</th>'
1002 . ( $this->showThumb ? '<th>' . $this->msg( 'filehist-thumb' )->escaped() . '</th>' : '' )
1003 . '<th>' . $this->msg( 'filehist-dimensions' )->escaped() . '</th>'
1004 . '<th>' . $this->msg( 'filehist-user' )->escaped() . '</th>'
1005 . '<th>' . $this->msg( 'filehist-comment' )->escaped() . '</th>'
1006 . "</tr>\n";
1010 * @param $navLinks string
1011 * @return string
1013 public function endImageHistoryList( $navLinks = '' ) {
1014 return "</table>\n$navLinks\n</div>\n";
1018 * @param $iscur
1019 * @param $file File
1020 * @return string
1022 public function imageHistoryLine( $iscur, $file ) {
1023 global $wgContLang;
1025 $user = $this->getUser();
1026 $lang = $this->getLanguage();
1027 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1028 $img = $iscur ? $file->getName() : $file->getArchiveName();
1029 $userId = $file->getUser( 'id' );
1030 $userText = $file->getUser( 'text' );
1031 $description = $file->getDescription( File::FOR_THIS_USER, $user );
1033 $local = $this->current->isLocal();
1034 $row = $selected = '';
1036 // Deletion link
1037 if ( $local && ( $user->isAllowedAny( 'delete', 'deletedhistory' ) ) ) {
1038 $row .= '<td>';
1039 # Link to remove from history
1040 if ( $user->isAllowed( 'delete' ) ) {
1041 $q = array( 'action' => 'delete' );
1042 if ( !$iscur ) {
1043 $q['oldimage'] = $img;
1045 $row .= Linker::linkKnown(
1046 $this->title,
1047 $this->msg( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' )->escaped(),
1048 array(), $q
1051 # Link to hide content. Don't show useless link to people who cannot hide revisions.
1052 $canHide = $user->isAllowed( 'deleterevision' );
1053 if ( $canHide || ( $user->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
1054 if ( $user->isAllowed( 'delete' ) ) {
1055 $row .= '<br />';
1057 // If file is top revision or locked from this user, don't link
1058 if ( $iscur || !$file->userCan( File::DELETED_RESTRICTED, $user ) ) {
1059 $del = Linker::revDeleteLinkDisabled( $canHide );
1060 } else {
1061 list( $ts, ) = explode( '!', $img, 2 );
1062 $query = array(
1063 'type' => 'oldimage',
1064 'target' => $this->title->getPrefixedText(),
1065 'ids' => $ts,
1067 $del = Linker::revDeleteLink( $query,
1068 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
1070 $row .= $del;
1072 $row .= '</td>';
1075 // Reversion link/current indicator
1076 $row .= '<td>';
1077 if ( $iscur ) {
1078 $row .= $this->msg( 'filehist-current' )->escaped();
1079 } elseif ( $local && $this->title->quickUserCan( 'edit', $user )
1080 && $this->title->quickUserCan( 'upload', $user )
1082 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1083 $row .= $this->msg( 'filehist-revert' )->escaped();
1084 } else {
1085 $row .= Linker::linkKnown(
1086 $this->title,
1087 $this->msg( 'filehist-revert' )->escaped(),
1088 array(),
1089 array(
1090 'action' => 'revert',
1091 'oldimage' => $img,
1092 'wpEditToken' => $user->getEditToken( $img )
1097 $row .= '</td>';
1099 // Date/time and image link
1100 if ( $file->getTimestamp() === $this->img->getTimestamp() ) {
1101 $selected = "class='filehistory-selected'";
1103 $row .= "<td $selected style='white-space: nowrap;'>";
1104 if ( !$file->userCan( File::DELETED_FILE, $user ) ) {
1105 # Don't link to unviewable files
1106 $row .= '<span class="history-deleted">' . $lang->userTimeAndDate( $timestamp, $user ) . '</span>';
1107 } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
1108 if ( $local ) {
1109 $this->preventClickjacking();
1110 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
1111 # Make a link to review the image
1112 $url = Linker::linkKnown(
1113 $revdel,
1114 $lang->userTimeAndDate( $timestamp, $user ),
1115 array(),
1116 array(
1117 'target' => $this->title->getPrefixedText(),
1118 'file' => $img,
1119 'token' => $user->getEditToken( $img )
1122 } else {
1123 $url = $lang->userTimeAndDate( $timestamp, $user );
1125 $row .= '<span class="history-deleted">' . $url . '</span>';
1126 } else {
1127 $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
1128 $row .= Xml::element( 'a', array( 'href' => $url ), $lang->userTimeAndDate( $timestamp, $user ) );
1130 $row .= "</td>";
1132 // Thumbnail
1133 if ( $this->showThumb ) {
1134 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1137 // Image dimensions + size
1138 $row .= '<td>';
1139 $row .= htmlspecialchars( $file->getDimensionsString() );
1140 $row .= $this->msg( 'word-separator' )->plain();
1141 $row .= '<span style="white-space: nowrap;">';
1142 $row .= $this->msg( 'parentheses' )->rawParams( Linker::formatSize( $file->getSize() ) )->plain();
1143 $row .= '</span>';
1144 $row .= '</td>';
1146 // Uploading user
1147 $row .= '<td>';
1148 // Hide deleted usernames
1149 if ( $file->isDeleted( File::DELETED_USER ) ) {
1150 $row .= '<span class="history-deleted">' . $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
1151 } else {
1152 if ( $local ) {
1153 $row .= Linker::userLink( $userId, $userText );
1154 $row .= $this->msg( 'word-separator' )->plain();
1155 $row .= '<span style="white-space: nowrap;">';
1156 $row .= Linker::userToolLinks( $userId, $userText );
1157 $row .= '</span>';
1158 } else {
1159 $row .= htmlspecialchars( $userText );
1162 $row .= '</td>';
1164 // Don't show deleted descriptions
1165 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1166 $row .= '<td><span class="history-deleted">' . $this->msg( 'rev-deleted-comment' )->escaped() . '</span></td>';
1167 } else {
1168 $row .= '<td dir="' . $wgContLang->getDir() . '">' . Linker::formatComment( $description, $this->title ) . '</td>';
1171 $rowClass = null;
1172 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1173 $classAttr = $rowClass ? " class='$rowClass'" : '';
1175 return "<tr{$classAttr}>{$row}</tr>\n";
1179 * @param $file File
1180 * @return string
1182 protected function getThumbForLine( $file ) {
1183 $lang = $this->getLanguage();
1184 $user = $this->getUser();
1185 if ( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE, $user )
1186 && !$file->isDeleted( File::DELETED_FILE ) )
1188 $params = array(
1189 'width' => '120',
1190 'height' => '120',
1192 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1194 $thumbnail = $file->transform( $params );
1195 $options = array(
1196 'alt' => $this->msg( 'filehist-thumbtext',
1197 $lang->userTimeAndDate( $timestamp, $user ),
1198 $lang->userDate( $timestamp, $user ),
1199 $lang->userTime( $timestamp, $user ) )->text(),
1200 'file-link' => true,
1203 if ( !$thumbnail ) {
1204 return $this->msg( 'filehist-nothumb' )->escaped();
1207 return $thumbnail->toHtml( $options );
1208 } else {
1209 return $this->msg( 'filehist-nothumb' )->escaped();
1214 * @param $enable bool
1216 protected function preventClickjacking( $enable = true ) {
1217 $this->preventClickjacking = $enable;
1221 * @return bool
1223 public function getPreventClickjacking() {
1224 return $this->preventClickjacking;
1228 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1229 protected $preventClickjacking = false;
1232 * @var File
1234 protected $mImg;
1237 * @var Title
1239 protected $mTitle;
1242 * @param ImagePage $imagePage
1244 function __construct( $imagePage ) {
1245 parent::__construct( $imagePage->getContext() );
1246 $this->mImagePage = $imagePage;
1247 $this->mTitle = clone ( $imagePage->getTitle() );
1248 $this->mTitle->setFragment( '#filehistory' );
1249 $this->mImg = null;
1250 $this->mHist = array();
1251 $this->mRange = array( 0, 0 ); // display range
1255 * @return Title
1257 function getTitle() {
1258 return $this->mTitle;
1261 function getQueryInfo() {
1262 return false;
1266 * @return string
1268 function getIndexField() {
1269 return '';
1273 * @param $row object
1274 * @return string
1276 function formatRow( $row ) {
1277 return '';
1281 * @return string
1283 function getBody() {
1284 $s = '';
1285 $this->doQuery();
1286 if ( count( $this->mHist ) ) {
1287 $list = new ImageHistoryList( $this->mImagePage );
1288 # Generate prev/next links
1289 $navLink = $this->getNavigationBar();
1290 $s = $list->beginImageHistoryList( $navLink );
1291 // Skip rows there just for paging links
1292 for ( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1293 $file = $this->mHist[$i];
1294 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1296 $s .= $list->endImageHistoryList( $navLink );
1298 if ( $list->getPreventClickjacking() ) {
1299 $this->preventClickjacking();
1302 return $s;
1305 function doQuery() {
1306 if ( $this->mQueryDone ) {
1307 return;
1309 $this->mImg = $this->mImagePage->getFile(); // ensure loading
1310 if ( !$this->mImg->exists() ) {
1311 return;
1313 $queryLimit = $this->mLimit + 1; // limit plus extra row
1314 if ( $this->mIsBackwards ) {
1315 // Fetch the file history
1316 $this->mHist = $this->mImg->getHistory( $queryLimit, null, $this->mOffset, false );
1317 // The current rev may not meet the offset/limit
1318 $numRows = count( $this->mHist );
1319 if ( $numRows <= $this->mLimit && $this->mImg->getTimestamp() > $this->mOffset ) {
1320 $this->mHist = array_merge( array( $this->mImg ), $this->mHist );
1322 } else {
1323 // The current rev may not meet the offset
1324 if ( !$this->mOffset || $this->mImg->getTimestamp() < $this->mOffset ) {
1325 $this->mHist[] = $this->mImg;
1327 // Old image versions (fetch extra row for nav links)
1328 $oiLimit = count( $this->mHist ) ? $this->mLimit : $this->mLimit + 1;
1329 // Fetch the file history
1330 $this->mHist = array_merge( $this->mHist,
1331 $this->mImg->getHistory( $oiLimit, $this->mOffset, null, false ) );
1333 $numRows = count( $this->mHist ); // Total number of query results
1334 if ( $numRows ) {
1335 # Index value of top item in the list
1336 $firstIndex = $this->mIsBackwards ?
1337 $this->mHist[$numRows - 1]->getTimestamp() : $this->mHist[0]->getTimestamp();
1338 # Discard the extra result row if there is one
1339 if ( $numRows > $this->mLimit && $numRows > 1 ) {
1340 if ( $this->mIsBackwards ) {
1341 # Index value of item past the index
1342 $this->mPastTheEndIndex = $this->mHist[0]->getTimestamp();
1343 # Index value of bottom item in the list
1344 $lastIndex = $this->mHist[1]->getTimestamp();
1345 # Display range
1346 $this->mRange = array( 1, $numRows - 1 );
1347 } else {
1348 # Index value of item past the index
1349 $this->mPastTheEndIndex = $this->mHist[$numRows - 1]->getTimestamp();
1350 # Index value of bottom item in the list
1351 $lastIndex = $this->mHist[$numRows - 2]->getTimestamp();
1352 # Display range
1353 $this->mRange = array( 0, $numRows - 2 );
1355 } else {
1356 # Setting indexes to an empty string means that they will be
1357 # omitted if they would otherwise appear in URLs. It just so
1358 # happens that this is the right thing to do in the standard
1359 # UI, in all the relevant cases.
1360 $this->mPastTheEndIndex = '';
1361 # Index value of bottom item in the list
1362 $lastIndex = $this->mIsBackwards ?
1363 $this->mHist[0]->getTimestamp() : $this->mHist[$numRows - 1]->getTimestamp();
1364 # Display range
1365 $this->mRange = array( 0, $numRows - 1 );
1367 } else {
1368 $firstIndex = '';
1369 $lastIndex = '';
1370 $this->mPastTheEndIndex = '';
1372 if ( $this->mIsBackwards ) {
1373 $this->mIsFirst = ( $numRows < $queryLimit );
1374 $this->mIsLast = ( $this->mOffset == '' );
1375 $this->mLastShown = $firstIndex;
1376 $this->mFirstShown = $lastIndex;
1377 } else {
1378 $this->mIsFirst = ( $this->mOffset == '' );
1379 $this->mIsLast = ( $numRows < $queryLimit );
1380 $this->mLastShown = $lastIndex;
1381 $this->mFirstShown = $firstIndex;
1383 $this->mQueryDone = true;
1387 * @param $enable bool
1389 protected function preventClickjacking( $enable = true ) {
1390 $this->preventClickjacking = $enable;
1394 * @return bool
1396 public function getPreventClickjacking() {
1397 return $this->preventClickjacking;