Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / ImagePage.php
bloba5beb5d983b10be48feca57e66a796440dd7bb1a
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() );
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() );
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 );
314 $width_orig = $this->displayImg->getWidth( $page );
315 $width = $width_orig;
316 $height_orig = $this->displayImg->getHeight( $page );
317 $height = $height_orig;
319 $filename = wfEscapeWikiText( $this->displayImg->getName() );
320 $linktext = $filename;
322 wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this, &$out ) );
324 if ( $this->displayImg->allowInlineDisplay() ) {
325 # image
327 # "Download high res version" link below the image
328 # $msgsize = wfMessage( 'file-info-size', $width_orig, $height_orig, Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
329 # We'll show a thumbnail of this image
330 if ( $width > $maxWidth || $height > $maxHeight ) {
331 # Calculate the thumbnail size.
332 # First case, the limiting factor is the width, not the height.
333 if ( $width / $height >= $maxWidth / $maxHeight ) { // FIXME: Possible division by 0. bug 36911
334 $height = round( $height * $maxWidth / $width ); // FIXME: Possible division by 0. bug 36911
335 $width = $maxWidth;
336 # Note that $height <= $maxHeight now.
337 } else {
338 $newwidth = floor( $width * $maxHeight / $height ); // FIXME: Possible division by 0. bug 36911
339 $height = round( $height * $newwidth / $width ); // FIXME: Possible division by 0. bug 36911
340 $width = $newwidth;
341 # Note that $height <= $maxHeight now, but might not be identical
342 # because of rounding.
344 $linktext = wfMessage( 'show-big-image' )->escaped();
345 if ( $this->displayImg->getRepo()->canTransformVia404() ) {
346 $thumbSizes = $wgImageLimits;
347 } else {
348 # Creating thumb links triggers thumbnail generation.
349 # Just generate the thumb for the current users prefs.
350 $thumbSizes = array( $this->getImageLimitsFromOption( $user, 'thumbsize' ) );
352 # Generate thumbnails or thumbnail links as needed...
353 $otherSizes = array();
354 foreach ( $thumbSizes as $size ) {
355 if ( $size[0] < $width_orig && $size[1] < $height_orig
356 && $size[0] != $width && $size[1] != $height )
358 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
359 if ( $sizeLink ) {
360 $otherSizes[] = $sizeLink;
364 $msgsmall = '';
365 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
366 if ( $sizeLinkBigImagePreview ) {
367 $msgsmall .= wfMessage( 'show-big-image-preview' )->
368 rawParams( $sizeLinkBigImagePreview )->
369 parse();
371 if ( count( $otherSizes ) ) {
372 $msgsmall .= ' ' .
373 Html::rawElement( 'span', array( 'class' => 'mw-filepage-other-resolutions' ),
374 wfMessage( 'show-big-image-other' )->rawParams( $lang->pipeList( $otherSizes ) )->
375 params( count( $otherSizes ) )->parse()
378 } elseif ( $width == 0 && $height == 0 ) {
379 # Some sort of audio file that doesn't have dimensions
380 # Don't output a no hi res message for such a file
381 $msgsmall = '';
382 } elseif ( $this->displayImg->isVectorized() ) {
383 # For vectorized images, full size is just the frame size
384 $msgsmall = '';
385 } else {
386 # Image is small enough to show full size on image page
387 $msgsmall = wfMessage( 'file-nohires' )->parse();
390 $params['width'] = $width;
391 $params['height'] = $height;
392 $thumbnail = $this->displayImg->transform( $params );
394 $anchorclose = Html::rawElement( 'div', array( 'class' => 'mw-filepage-resolutioninfo' ), $msgsmall );
396 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
397 if ( $isMulti ) {
398 $out->addHTML( '<table class="multipageimage"><tr><td>' );
401 if ( $thumbnail ) {
402 $options = array(
403 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
404 'file-link' => true,
406 $out->addHTML( '<div class="fullImageLink" id="file">' .
407 $thumbnail->toHtml( $options ) .
408 $anchorclose . "</div>\n" );
411 if ( $isMulti ) {
412 $count = $this->displayImg->pageCount();
414 if ( $page > 1 ) {
415 $label = $out->parse( wfMessage( 'imgmultipageprev' )->text(), false );
416 $link = Linker::linkKnown(
417 $this->getTitle(),
418 $label,
419 array(),
420 array( 'page' => $page - 1 )
422 $thumb1 = Linker::makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
423 array( 'page' => $page - 1 ) );
424 } else {
425 $thumb1 = '';
428 if ( $page < $count ) {
429 $label = wfMessage( 'imgmultipagenext' )->text();
430 $link = Linker::linkKnown(
431 $this->getTitle(),
432 $label,
433 array(),
434 array( 'page' => $page + 1 )
436 $thumb2 = Linker::makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
437 array( 'page' => $page + 1 ) );
438 } else {
439 $thumb2 = '';
442 global $wgScript;
444 $formParams = array(
445 'name' => 'pageselector',
446 'action' => $wgScript,
447 'onchange' => 'document.pageselector.submit();',
449 $options = array();
450 for ( $i = 1; $i <= $count; $i++ ) {
451 $options[] = Xml::option( $lang->formatNum( $i ), $i, $i == $page );
453 $select = Xml::tags( 'select',
454 array( 'id' => 'pageselector', 'name' => 'page' ),
455 implode( "\n", $options ) );
457 $out->addHTML(
458 '</td><td><div class="multipageimagenavbox">' .
459 Xml::openElement( 'form', $formParams ) .
460 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
461 wfMessage( 'imgmultigoto' )->rawParams( $select )->parse() .
462 Xml::submitButton( wfMessage( 'imgmultigo' )->text() ) .
463 Xml::closeElement( 'form' ) .
464 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
467 } elseif ( $this->displayImg->isSafeFile() ) {
468 # if direct link is allowed but it's not a renderable image, show an icon.
469 $icon = $this->displayImg->iconThumb();
471 $out->addHTML( '<div class="fullImageLink" id="file">' .
472 $icon->toHtml( array( 'file-link' => true ) ) .
473 "</div>\n" );
476 $longDesc = wfMessage( 'parentheses', $this->displayImg->getLongDesc() )->text();
478 $medialink = "[[Media:$filename|$linktext]]";
480 if ( !$this->displayImg->isSafeFile() ) {
481 $warning = wfMessage( 'mediawarning' )->plain();
482 // dirmark is needed here to separate the file name, which
483 // most likely ends in Latin characters, from the description,
484 // which may begin with the file type. In RTL environment
485 // this will get messy.
486 // The dirmark, however, must not be immediately adjacent
487 // to the filename, because it can get copied with it.
488 // See bug 25277.
489 $out->addWikiText( <<<EOT
490 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
491 <div class="mediaWarning">$warning</div>
494 } else {
495 $out->addWikiText( <<<EOT
496 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
497 </div>
502 // Add cannot animate thumbnail warning
503 if ( !$this->displayImg->canAnimateThumbIfAppropriate() ) {
504 // Include the extension so wiki admins can
505 // customize it on a per file-type basis
506 // (aka say things like use format X instead).
507 // additionally have a specific message for
508 // file-no-thumb-animation-gif
509 $ext = $this->displayImg->getExtension();
510 $noAnimMesg = wfMessageFallback(
511 'file-no-thumb-animation-' . $ext,
512 'file-no-thumb-animation'
513 )->plain();
515 $out->addWikiText( <<<EOT
516 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
521 if ( !$this->displayImg->isLocal() ) {
522 $this->printSharedImageText();
524 } else {
525 # Image does not exist
526 if ( !$this->getID() ) {
527 # No article exists either
528 # Show deletion log to be consistent with normal articles
529 LogEventsList::showLogExtract(
530 $out,
531 array( 'delete', 'move' ),
532 $this->getTitle()->getPrefixedText(),
534 array( 'lim' => 10,
535 'conds' => array( "log_action != 'revision'" ),
536 'showIfEmpty' => false,
537 'msgKey' => array( 'moveddeleted-notice' )
542 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
543 // Only show an upload link if the user can upload
544 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
545 $nofile = array(
546 'filepage-nofile-link',
547 $uploadTitle->getFullURL( array( 'wpDestFile' => $this->mPage->getFile()->getName() ) )
549 } else {
550 $nofile = 'filepage-nofile';
552 // Note, if there is an image description page, but
553 // no image, then this setRobotPolicy is overridden
554 // by Article::View().
555 $out->setRobotPolicy( 'noindex,nofollow' );
556 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
557 if ( !$this->getID() && $wgSend404Code ) {
558 // If there is no image, no shared image, and no description page,
559 // output a 404, to be consistent with articles.
560 $request->response()->header( 'HTTP/1.1 404 Not Found' );
563 $out->setFileVersion( $this->displayImg );
567 * Creates an thumbnail of specified size and returns an HTML link to it
568 * @param array $params Scaler parameters
569 * @param $width int
570 * @param $height int
571 * @return string
573 private function makeSizeLink( $params, $width, $height ) {
574 $params['width'] = $width;
575 $params['height'] = $height;
576 $thumbnail = $this->displayImg->transform( $params );
577 if ( $thumbnail && !$thumbnail->isError() ) {
578 return Html::rawElement( 'a', array(
579 'href' => $thumbnail->getUrl(),
580 'class' => 'mw-thumbnail-link'
581 ), wfMessage( 'show-big-image-size' )->numParams(
582 $thumbnail->getWidth(), $thumbnail->getHeight()
583 )->parse() );
584 } else {
585 return '';
590 * Show a notice that the file is from a shared repository
592 protected function printSharedImageText() {
593 $out = $this->getContext()->getOutput();
594 $this->loadFile();
596 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
597 $descText = $this->mPage->getFile()->getDescriptionText();
599 /* Add canonical to head if there is no local page for this shared file */
600 if ( $descUrl && $this->mPage->getID() == 0 ) {
601 $out->setCanonicalUrl( $descUrl );
604 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
605 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
607 if ( $descUrl && $descText && wfMessage( 'sharedupload-desc-here' )->plain() !== '-' ) {
608 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
609 } elseif ( $descUrl && wfMessage( 'sharedupload-desc-there' )->plain() !== '-' ) {
610 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
611 } else {
612 $out->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
615 if ( $descText ) {
616 $this->mExtraDescription = $descText;
620 public function getUploadUrl() {
621 $this->loadFile();
622 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
623 return $uploadTitle->getFullURL( array(
624 'wpDestFile' => $this->mPage->getFile()->getName(),
625 'wpForReUpload' => 1
626 ) );
630 * Print out the various links at the bottom of the image page, e.g. reupload,
631 * external editing (and instructions link) etc.
633 protected function uploadLinksBox() {
634 global $wgEnableUploads;
636 if ( !$wgEnableUploads ) {
637 return;
640 $this->loadFile();
641 if ( !$this->mPage->getFile()->isLocal() ) {
642 return;
645 $out = $this->getContext()->getOutput();
646 $out->addHTML( "<ul>\n" );
648 # "Upload a new version of this file" link
649 $canUpload = $this->getTitle()->userCan( 'upload', $this->getContext()->getUser() );
650 if ( $canUpload && UploadBase::userCanReUpload( $this->getContext()->getUser(), $this->mPage->getFile()->name ) ) {
651 $ulink = Linker::makeExternalLink( $this->getUploadUrl(), wfMessage( 'uploadnewversion-linktext' )->text() );
652 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\"><div class=\"plainlinks\">{$ulink}</div></li>\n" );
653 } else {
654 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">" . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
657 $out->addHTML( "</ul>\n" );
660 protected function closeShowImage() { } # For overloading
663 * If the page we've just displayed is in the "Image" namespace,
664 * we follow it with an upload history of the image and its usage.
666 protected function imageHistory() {
667 $this->loadFile();
668 $out = $this->getContext()->getOutput();
669 $pager = new ImageHistoryPseudoPager( $this );
670 $out->addHTML( $pager->getBody() );
671 $out->preventClickjacking( $pager->getPreventClickjacking() );
673 $this->mPage->getFile()->resetHistory(); // free db resources
675 # Exist check because we don't want to show this on pages where an image
676 # doesn't exist along with the noimage message, that would suck. -ævar
677 if ( $this->mPage->getFile()->exists() ) {
678 $this->uploadLinksBox();
683 * @param $target
684 * @param $limit
685 * @return ResultWrapper
687 protected function queryImageLinks( $target, $limit ) {
688 $dbr = wfGetDB( DB_SLAVE );
690 return $dbr->select(
691 array( 'imagelinks', 'page' ),
692 array( 'page_namespace', 'page_title', 'page_is_redirect', 'il_to' ),
693 array( 'il_to' => $target, 'il_from = page_id' ),
694 __METHOD__,
695 array( 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', )
699 protected function imageLinks() {
700 $limit = 100;
702 $out = $this->getContext()->getOutput();
703 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit + 1 );
704 $rows = array();
705 $redirects = array();
706 foreach ( $res as $row ) {
707 if ( $row->page_is_redirect ) {
708 $redirects[$row->page_title] = array();
710 $rows[] = $row;
712 $count = count( $rows );
714 $hasMore = $count > $limit;
715 if ( !$hasMore && count( $redirects ) ) {
716 $res = $this->queryImageLinks( array_keys( $redirects ),
717 $limit - count( $rows ) + 1 );
718 foreach ( $res as $row ) {
719 $redirects[$row->il_to][] = $row;
720 $count++;
722 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
725 if ( $count == 0 ) {
726 $out->wrapWikiMsg(
727 Html::rawElement( 'div',
728 array( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ),
729 'nolinkstoimage'
731 return;
734 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
735 if ( !$hasMore ) {
736 $out->addWikiMsg( 'linkstoimage', $count );
737 } else {
738 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
739 $out->addWikiMsg( 'linkstoimage-more',
740 $this->getContext()->getLanguage()->formatNum( $limit ),
741 $this->getTitle()->getPrefixedDBkey()
745 $out->addHTML(
746 Html::openElement( 'ul',
747 array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n"
749 $count = 0;
751 // Sort the list by namespace:title
752 usort( $rows, array( $this, 'compare' ) );
754 // Create links for every element
755 $currentCount = 0;
756 foreach ( $rows as $element ) {
757 $currentCount++;
758 if ( $currentCount > $limit ) {
759 break;
762 $link = Linker::linkKnown( Title::makeTitle( $element->page_namespace, $element->page_title ) );
763 if ( !isset( $redirects[$element->page_title] ) ) {
764 # No redirects
765 $liContents = $link;
766 } elseif ( count( $redirects[$element->page_title] ) === 0 ) {
767 # Redirect without usages
768 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams( $link, '' )->parse();
769 } else {
770 # Redirect with usages
771 $li = '';
772 foreach ( $redirects[$element->page_title] as $row ) {
773 $currentCount++;
774 if ( $currentCount > $limit ) {
775 break;
778 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
779 $li .= Html::rawElement(
780 'li',
781 array( 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
782 $link2
783 ) . "\n";
786 $ul = Html::rawElement(
787 'ul',
788 array( 'class' => 'mw-imagepage-redirectstofile' ),
790 ) . "\n";
791 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams(
792 $link, $ul )->parse();
794 $out->addHTML( Html::rawElement(
795 'li',
796 array( 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
797 $liContents
798 ) . "\n"
802 $out->addHTML( Html::closeElement( 'ul' ) . "\n" );
803 $res->free();
805 // Add a links to [[Special:Whatlinkshere]]
806 if ( $count > $limit ) {
807 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
809 $out->addHTML( Html::closeElement( 'div' ) . "\n" );
812 protected function imageDupes() {
813 $this->loadFile();
814 $out = $this->getContext()->getOutput();
816 $dupes = $this->mPage->getDuplicates();
817 if ( count( $dupes ) == 0 ) {
818 return;
821 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
822 $out->addWikiMsg( 'duplicatesoffile',
823 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
825 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
828 * @var $file File
830 foreach ( $dupes as $file ) {
831 $fromSrc = '';
832 if ( $file->isLocal() ) {
833 $link = Linker::linkKnown( $file->getTitle() );
834 } else {
835 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
836 $file->getTitle()->getPrefixedText() );
837 $fromSrc = wfMessage( 'shared-repo-from', $file->getRepo()->getDisplayName() )->text();
839 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
841 $out->addHTML( "</ul></div>\n" );
845 * Delete the file, or an earlier version of it
847 public function delete() {
848 $file = $this->mPage->getFile();
849 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
850 // Standard article deletion
851 parent::delete();
852 return;
855 $deleter = new FileDeleteForm( $file );
856 $deleter->execute();
860 * Display an error with a wikitext description
862 * @param $description String
864 function showError( $description ) {
865 $out = $this->getContext()->getOutput();
866 $out->setPageTitle( wfMessage( 'internalerror' ) );
867 $out->setRobotPolicy( 'noindex,nofollow' );
868 $out->setArticleRelated( false );
869 $out->enableClientCache( false );
870 $out->addWikiText( $description );
874 * Callback for usort() to do link sorts by (namespace, title)
875 * Function copied from Title::compare()
877 * @param $a object page to compare with
878 * @param $b object page to compare with
879 * @return Integer: result of string comparison, or namespace comparison
881 protected function compare( $a, $b ) {
882 if ( $a->page_namespace == $b->page_namespace ) {
883 return strcmp( $a->page_title, $b->page_title );
884 } else {
885 return $a->page_namespace - $b->page_namespace;
890 * Returns the corresponding $wgImageLimits entry for the selected user option
892 * @param $user User
893 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
894 * @return array
895 * @since 1.21
897 public function getImageLimitsFromOption( $user, $optionName ) {
898 global $wgImageLimits;
900 $option = $user->getIntOption( $optionName );
901 if ( !isset( $wgImageLimits[$option] ) ) {
902 $option = User::getDefaultOption( $optionName );
905 // The user offset might still be incorrect, specially if
906 // $wgImageLimits got changed (see bug #8858).
907 if ( !isset( $wgImageLimits[$option] ) ) {
908 // Default to the first offset in $wgImageLimits
909 $option = 0;
912 return isset( $wgImageLimits[$option] )
913 ? $wgImageLimits[$option]
914 : array( 800, 600 ); // if nothing is set, fallback to a hardcoded default
919 * Builds the image revision log shown on image pages
921 * @ingroup Media
923 class ImageHistoryList extends ContextSource {
926 * @var Title
928 protected $title;
931 * @var File
933 protected $img;
936 * @var ImagePage
938 protected $imagePage;
941 * @var File
943 protected $current;
945 protected $repo, $showThumb;
946 protected $preventClickjacking = false;
949 * @param ImagePage $imagePage
951 public function __construct( $imagePage ) {
952 global $wgShowArchiveThumbnails;
953 $this->current = $imagePage->getFile();
954 $this->img = $imagePage->getDisplayedFile();
955 $this->title = $imagePage->getTitle();
956 $this->imagePage = $imagePage;
957 $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
958 $this->setContext( $imagePage->getContext() );
962 * @return ImagePage
964 public function getImagePage() {
965 return $this->imagePage;
969 * @return File
971 public function getFile() {
972 return $this->img;
976 * @param $navLinks string
977 * @return string
979 public function beginImageHistoryList( $navLinks = '' ) {
980 return Xml::element( 'h2', array( 'id' => 'filehistory' ), $this->msg( 'filehist' )->text() ) . "\n"
981 . "<div id=\"mw-imagepage-section-filehistory\">\n"
982 . $this->msg( 'filehist-help' )->parseAsBlock()
983 . $navLinks . "\n"
984 . Xml::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
985 . '<tr><td></td>'
986 . ( $this->current->isLocal() && ( $this->getUser()->isAllowedAny( 'delete', 'deletedhistory' ) ) ? '<td></td>' : '' )
987 . '<th>' . $this->msg( 'filehist-datetime' )->escaped() . '</th>'
988 . ( $this->showThumb ? '<th>' . $this->msg( 'filehist-thumb' )->escaped() . '</th>' : '' )
989 . '<th>' . $this->msg( 'filehist-dimensions' )->escaped() . '</th>'
990 . '<th>' . $this->msg( 'filehist-user' )->escaped() . '</th>'
991 . '<th>' . $this->msg( 'filehist-comment' )->escaped() . '</th>'
992 . "</tr>\n";
996 * @param $navLinks string
997 * @return string
999 public function endImageHistoryList( $navLinks = '' ) {
1000 return "</table>\n$navLinks\n</div>\n";
1004 * @param $iscur
1005 * @param $file File
1006 * @return string
1008 public function imageHistoryLine( $iscur, $file ) {
1009 global $wgContLang;
1011 $user = $this->getUser();
1012 $lang = $this->getLanguage();
1013 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1014 $img = $iscur ? $file->getName() : $file->getArchiveName();
1015 $userId = $file->getUser( 'id' );
1016 $userText = $file->getUser( 'text' );
1017 $description = $file->getDescription( File::FOR_THIS_USER, $user );
1019 $local = $this->current->isLocal();
1020 $row = $selected = '';
1022 // Deletion link
1023 if ( $local && ( $user->isAllowedAny( 'delete', 'deletedhistory' ) ) ) {
1024 $row .= '<td>';
1025 # Link to remove from history
1026 if ( $user->isAllowed( 'delete' ) ) {
1027 $q = array( 'action' => 'delete' );
1028 if ( !$iscur ) {
1029 $q['oldimage'] = $img;
1031 $row .= Linker::linkKnown(
1032 $this->title,
1033 $this->msg( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' )->escaped(),
1034 array(), $q
1037 # Link to hide content. Don't show useless link to people who cannot hide revisions.
1038 $canHide = $user->isAllowed( 'deleterevision' );
1039 if ( $canHide || ( $user->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
1040 if ( $user->isAllowed( 'delete' ) ) {
1041 $row .= '<br />';
1043 // If file is top revision or locked from this user, don't link
1044 if ( $iscur || !$file->userCan( File::DELETED_RESTRICTED, $user ) ) {
1045 $del = Linker::revDeleteLinkDisabled( $canHide );
1046 } else {
1047 list( $ts, ) = explode( '!', $img, 2 );
1048 $query = array(
1049 'type' => 'oldimage',
1050 'target' => $this->title->getPrefixedText(),
1051 'ids' => $ts,
1053 $del = Linker::revDeleteLink( $query,
1054 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
1056 $row .= $del;
1058 $row .= '</td>';
1061 // Reversion link/current indicator
1062 $row .= '<td>';
1063 if ( $iscur ) {
1064 $row .= $this->msg( 'filehist-current' )->escaped();
1065 } elseif ( $local && $this->title->quickUserCan( 'edit', $user )
1066 && $this->title->quickUserCan( 'upload', $user )
1068 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1069 $row .= $this->msg( 'filehist-revert' )->escaped();
1070 } else {
1071 $row .= Linker::linkKnown(
1072 $this->title,
1073 $this->msg( 'filehist-revert' )->escaped(),
1074 array(),
1075 array(
1076 'action' => 'revert',
1077 'oldimage' => $img,
1078 'wpEditToken' => $user->getEditToken( $img )
1083 $row .= '</td>';
1085 // Date/time and image link
1086 if ( $file->getTimestamp() === $this->img->getTimestamp() ) {
1087 $selected = "class='filehistory-selected'";
1089 $row .= "<td $selected style='white-space: nowrap;'>";
1090 if ( !$file->userCan( File::DELETED_FILE, $user ) ) {
1091 # Don't link to unviewable files
1092 $row .= '<span class="history-deleted">' . $lang->userTimeAndDate( $timestamp, $user ) . '</span>';
1093 } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
1094 if ( $local ) {
1095 $this->preventClickjacking();
1096 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
1097 # Make a link to review the image
1098 $url = Linker::linkKnown(
1099 $revdel,
1100 $lang->userTimeAndDate( $timestamp, $user ),
1101 array(),
1102 array(
1103 'target' => $this->title->getPrefixedText(),
1104 'file' => $img,
1105 'token' => $user->getEditToken( $img )
1108 } else {
1109 $url = $lang->userTimeAndDate( $timestamp, $user );
1111 $row .= '<span class="history-deleted">' . $url . '</span>';
1112 } else {
1113 $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
1114 $row .= Xml::element( 'a', array( 'href' => $url ), $lang->userTimeAndDate( $timestamp, $user ) );
1116 $row .= "</td>";
1118 // Thumbnail
1119 if ( $this->showThumb ) {
1120 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1123 // Image dimensions + size
1124 $row .= '<td>';
1125 $row .= htmlspecialchars( $file->getDimensionsString() );
1126 $row .= $this->msg( 'word-separator' )->plain();
1127 $row .= '<span style="white-space: nowrap;">';
1128 $row .= $this->msg( 'parentheses' )->rawParams( Linker::formatSize( $file->getSize() ) )->plain();
1129 $row .= '</span>';
1130 $row .= '</td>';
1132 // Uploading user
1133 $row .= '<td>';
1134 // Hide deleted usernames
1135 if ( $file->isDeleted( File::DELETED_USER ) ) {
1136 $row .= '<span class="history-deleted">' . $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
1137 } else {
1138 if ( $local ) {
1139 $row .= Linker::userLink( $userId, $userText );
1140 $row .= $this->msg( 'word-separator' )->plain();
1141 $row .= '<span style="white-space: nowrap;">';
1142 $row .= Linker::userToolLinks( $userId, $userText );
1143 $row .= '</span>';
1144 } else {
1145 $row .= htmlspecialchars( $userText );
1148 $row .= '</td>';
1150 // Don't show deleted descriptions
1151 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1152 $row .= '<td><span class="history-deleted">' . $this->msg( 'rev-deleted-comment' )->escaped() . '</span></td>';
1153 } else {
1154 $row .= '<td dir="' . $wgContLang->getDir() . '">' . Linker::formatComment( $description, $this->title ) . '</td>';
1157 $rowClass = null;
1158 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1159 $classAttr = $rowClass ? " class='$rowClass'" : '';
1161 return "<tr{$classAttr}>{$row}</tr>\n";
1165 * @param $file File
1166 * @return string
1168 protected function getThumbForLine( $file ) {
1169 $lang = $this->getLanguage();
1170 $user = $this->getUser();
1171 if ( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE, $user )
1172 && !$file->isDeleted( File::DELETED_FILE ) )
1174 $params = array(
1175 'width' => '120',
1176 'height' => '120',
1178 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1180 $thumbnail = $file->transform( $params );
1181 $options = array(
1182 'alt' => $this->msg( 'filehist-thumbtext',
1183 $lang->userTimeAndDate( $timestamp, $user ),
1184 $lang->userDate( $timestamp, $user ),
1185 $lang->userTime( $timestamp, $user ) )->text(),
1186 'file-link' => true,
1189 if ( !$thumbnail ) {
1190 return $this->msg( 'filehist-nothumb' )->escaped();
1193 return $thumbnail->toHtml( $options );
1194 } else {
1195 return $this->msg( 'filehist-nothumb' )->escaped();
1200 * @param $enable bool
1202 protected function preventClickjacking( $enable = true ) {
1203 $this->preventClickjacking = $enable;
1207 * @return bool
1209 public function getPreventClickjacking() {
1210 return $this->preventClickjacking;
1214 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1215 protected $preventClickjacking = false;
1218 * @var File
1220 protected $mImg;
1223 * @var Title
1225 protected $mTitle;
1228 * @param ImagePage $imagePage
1230 function __construct( $imagePage ) {
1231 parent::__construct( $imagePage->getContext() );
1232 $this->mImagePage = $imagePage;
1233 $this->mTitle = clone ( $imagePage->getTitle() );
1234 $this->mTitle->setFragment( '#filehistory' );
1235 $this->mImg = null;
1236 $this->mHist = array();
1237 $this->mRange = array( 0, 0 ); // display range
1241 * @return Title
1243 function getTitle() {
1244 return $this->mTitle;
1247 function getQueryInfo() {
1248 return false;
1252 * @return string
1254 function getIndexField() {
1255 return '';
1259 * @param $row object
1260 * @return string
1262 function formatRow( $row ) {
1263 return '';
1267 * @return string
1269 function getBody() {
1270 $s = '';
1271 $this->doQuery();
1272 if ( count( $this->mHist ) ) {
1273 $list = new ImageHistoryList( $this->mImagePage );
1274 # Generate prev/next links
1275 $navLink = $this->getNavigationBar();
1276 $s = $list->beginImageHistoryList( $navLink );
1277 // Skip rows there just for paging links
1278 for ( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1279 $file = $this->mHist[$i];
1280 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1282 $s .= $list->endImageHistoryList( $navLink );
1284 if ( $list->getPreventClickjacking() ) {
1285 $this->preventClickjacking();
1288 return $s;
1291 function doQuery() {
1292 if ( $this->mQueryDone ) {
1293 return;
1295 $this->mImg = $this->mImagePage->getFile(); // ensure loading
1296 if ( !$this->mImg->exists() ) {
1297 return;
1299 $queryLimit = $this->mLimit + 1; // limit plus extra row
1300 if ( $this->mIsBackwards ) {
1301 // Fetch the file history
1302 $this->mHist = $this->mImg->getHistory( $queryLimit, null, $this->mOffset, false );
1303 // The current rev may not meet the offset/limit
1304 $numRows = count( $this->mHist );
1305 if ( $numRows <= $this->mLimit && $this->mImg->getTimestamp() > $this->mOffset ) {
1306 $this->mHist = array_merge( array( $this->mImg ), $this->mHist );
1308 } else {
1309 // The current rev may not meet the offset
1310 if ( !$this->mOffset || $this->mImg->getTimestamp() < $this->mOffset ) {
1311 $this->mHist[] = $this->mImg;
1313 // Old image versions (fetch extra row for nav links)
1314 $oiLimit = count( $this->mHist ) ? $this->mLimit : $this->mLimit + 1;
1315 // Fetch the file history
1316 $this->mHist = array_merge( $this->mHist,
1317 $this->mImg->getHistory( $oiLimit, $this->mOffset, null, false ) );
1319 $numRows = count( $this->mHist ); // Total number of query results
1320 if ( $numRows ) {
1321 # Index value of top item in the list
1322 $firstIndex = $this->mIsBackwards ?
1323 $this->mHist[$numRows - 1]->getTimestamp() : $this->mHist[0]->getTimestamp();
1324 # Discard the extra result row if there is one
1325 if ( $numRows > $this->mLimit && $numRows > 1 ) {
1326 if ( $this->mIsBackwards ) {
1327 # Index value of item past the index
1328 $this->mPastTheEndIndex = $this->mHist[0]->getTimestamp();
1329 # Index value of bottom item in the list
1330 $lastIndex = $this->mHist[1]->getTimestamp();
1331 # Display range
1332 $this->mRange = array( 1, $numRows - 1 );
1333 } else {
1334 # Index value of item past the index
1335 $this->mPastTheEndIndex = $this->mHist[$numRows - 1]->getTimestamp();
1336 # Index value of bottom item in the list
1337 $lastIndex = $this->mHist[$numRows - 2]->getTimestamp();
1338 # Display range
1339 $this->mRange = array( 0, $numRows - 2 );
1341 } else {
1342 # Setting indexes to an empty string means that they will be
1343 # omitted if they would otherwise appear in URLs. It just so
1344 # happens that this is the right thing to do in the standard
1345 # UI, in all the relevant cases.
1346 $this->mPastTheEndIndex = '';
1347 # Index value of bottom item in the list
1348 $lastIndex = $this->mIsBackwards ?
1349 $this->mHist[0]->getTimestamp() : $this->mHist[$numRows - 1]->getTimestamp();
1350 # Display range
1351 $this->mRange = array( 0, $numRows - 1 );
1353 } else {
1354 $firstIndex = '';
1355 $lastIndex = '';
1356 $this->mPastTheEndIndex = '';
1358 if ( $this->mIsBackwards ) {
1359 $this->mIsFirst = ( $numRows < $queryLimit );
1360 $this->mIsLast = ( $this->mOffset == '' );
1361 $this->mLastShown = $firstIndex;
1362 $this->mFirstShown = $lastIndex;
1363 } else {
1364 $this->mIsFirst = ( $this->mOffset == '' );
1365 $this->mIsLast = ( $numRows < $queryLimit );
1366 $this->mLastShown = $lastIndex;
1367 $this->mFirstShown = $firstIndex;
1369 $this->mQueryDone = true;
1373 * @param $enable bool
1375 protected function preventClickjacking( $enable = true ) {
1376 $this->preventClickjacking = $enable;
1380 * @return bool
1382 public function getPreventClickjacking() {
1383 return $this->preventClickjacking;