Add a way for packagers to override some installation details
[mediawiki.git] / includes / ImagePage.php
blob8f683e92073b9e8464e4d867ff06b2c0cf8f6b5f
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 $id Int 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 || ( isset( $diff ) && $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() || isset( $diff ) ) {
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()->getPageLanguage();
157 $out->addHTML( Xml::openElement( 'div', array( 'id' => 'mw-imagepage-content',
158 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
159 'class' => 'mw-content-'.$pageLang->getDir() ) ) );
160 parent::view();
161 $out->addHTML( Xml::closeElement( 'div' ) );
162 } else {
163 # Just need to set the right headers
164 $out->setArticleFlag( true );
165 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
166 $this->mPage->doViewUpdates( $this->getContext()->getUser() );
169 # Show shared description, if needed
170 if ( $this->mExtraDescription ) {
171 $fol = wfMessage( 'shareddescriptionfollows' );
172 if ( !$fol->isDisabled() ) {
173 $out->addWikiText( $fol->plain() );
175 $out->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
178 $this->closeShowImage();
179 $this->imageHistory();
180 // TODO: Cleanup the following
182 $out->addHTML( Xml::element( 'h2',
183 array( 'id' => 'filelinks' ),
184 wfMsg( 'imagelinks' ) ) . "\n" );
185 $this->imageDupes();
186 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
187 # Yet we return metadata about the target. Definitely an issue in the FileRepo
188 $this->imageLinks();
190 # Allow extensions to add something after the image links
191 $html = '';
192 wfRunHooks( 'ImagePageAfterImageLinks', array( $this, &$html ) );
193 if ( $html ) {
194 $out->addHTML( $html );
197 if ( $showmeta ) {
198 $out->addHTML( Xml::element( 'h2', array( 'id' => 'metadata' ), wfMsg( 'metadata' ) ) . "\n" );
199 $out->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
200 $out->addModules( array( 'mediawiki.action.view.metadata' ) );
203 // Add remote Filepage.css
204 if( !$this->repo->isLocal() ) {
205 $css = $this->repo->getDescriptionStylesheetUrl();
206 if ( $css ) {
207 $out->addStyle( $css );
210 // always show the local local Filepage.css, bug 29277
211 $out->addModuleStyles( 'filepage' );
215 * @return File
217 public function getDisplayedFile() {
218 $this->loadFile();
219 return $this->displayImg;
223 * Create the TOC
225 * @param $metadata Boolean: whether or not to show the metadata link
226 * @return String
228 protected function showTOC( $metadata ) {
229 $r = array(
230 '<li><a href="#file">' . wfMsgHtml( 'file-anchor-link' ) . '</a></li>',
231 '<li><a href="#filehistory">' . wfMsgHtml( 'filehist' ) . '</a></li>',
232 '<li><a href="#filelinks">' . wfMsgHtml( 'imagelinks' ) . '</a></li>',
234 if ( $metadata ) {
235 $r[] = '<li><a href="#metadata">' . wfMsgHtml( 'metadata' ) . '</a></li>';
238 wfRunHooks( 'ImagePageShowTOC', array( $this, &$r ) );
240 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
244 * Make a table with metadata to be shown in the output page.
246 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
248 * @param $metadata Array: the array containing the EXIF data
249 * @return String The metadata table. This is treated as Wikitext (!)
251 protected function makeMetadataTable( $metadata ) {
252 $r = "<div class=\"mw-imagepage-section-metadata\">";
253 $r .= wfMsgNoTrans( 'metadata-help' );
254 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
255 foreach ( $metadata as $type => $stuff ) {
256 foreach ( $stuff as $v ) {
257 # @todo FIXME: Why is this using escapeId for a class?!
258 $class = Sanitizer::escapeId( $v['id'] );
259 if ( $type == 'collapsed' ) {
260 $class .= ' collapsable';
262 $r .= "<tr class=\"$class\">\n";
263 $r .= "<th>{$v['name']}</th>\n";
264 $r .= "<td>{$v['value']}</td>\n</tr>";
267 $r .= "</table>\n</div>\n";
268 return $r;
272 * Overloading Article's getContent method.
274 * Omit noarticletext if sharedupload; text will be fetched from the
275 * shared upload server if possible.
276 * @return string
278 public function getContent() {
279 $this->loadFile();
280 if ( $this->mPage->getFile() && !$this->mPage->getFile()->isLocal() && 0 == $this->getID() ) {
281 return '';
283 return parent::getContent();
286 protected function openShowImage() {
287 global $wgImageLimits, $wgEnableUploads, $wgSend404Code;
289 $this->loadFile();
290 $out = $this->getContext()->getOutput();
291 $user = $this->getContext()->getUser();
292 $lang = $this->getContext()->getLanguage();
293 $dirmark = $lang->getDirMarkEntity();
294 $request = $this->getContext()->getRequest();
296 $sizeSel = intval( $user->getOption( 'imagesize' ) );
297 if ( !isset( $wgImageLimits[$sizeSel] ) ) {
298 $sizeSel = User::getDefaultOption( 'imagesize' );
300 // The user offset might still be incorrect, specially if
301 // $wgImageLimits got changed (see bug #8858).
302 if ( !isset( $wgImageLimits[$sizeSel] ) ) {
303 // Default to the first offset in $wgImageLimits
304 $sizeSel = 0;
307 $max = $wgImageLimits[$sizeSel];
308 $maxWidth = $max[0];
309 $maxHeight = $max[1];
311 if ( $this->displayImg->exists() ) {
312 # image
313 $page = $request->getIntOrNull( 'page' );
314 if ( is_null( $page ) ) {
315 $params = array();
316 $page = 1;
317 } else {
318 $params = array( 'page' => $page );
320 $width_orig = $this->displayImg->getWidth( $page );
321 $width = $width_orig;
322 $height_orig = $this->displayImg->getHeight( $page );
323 $height = $height_orig;
325 $longDesc = wfMsg( 'parentheses', $this->displayImg->getLongDesc() );
327 wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this, &$out ) );
329 if ( $this->displayImg->allowInlineDisplay() ) {
330 # image
332 # "Download high res version" link below the image
333 # $msgsize = wfMsgHtml( 'file-info-size', $width_orig, $height_orig, Linker::formatSize( $this->displayImg->getSize() ), $mime );
334 # We'll show a thumbnail of this image
335 if ( $width > $maxWidth || $height > $maxHeight ) {
336 # Calculate the thumbnail size.
337 # First case, the limiting factor is the width, not the height.
338 if ( $width / $height >= $maxWidth / $maxHeight ) {
339 $height = round( $height * $maxWidth / $width );
340 $width = $maxWidth;
341 # Note that $height <= $maxHeight now.
342 } else {
343 $newwidth = floor( $width * $maxHeight / $height );
344 $height = round( $height * $newwidth / $width );
345 $width = $newwidth;
346 # Note that $height <= $maxHeight now, but might not be identical
347 # because of rounding.
349 $msgbig = wfMsgHtml( 'show-big-image' );
350 if ( $this->displayImg->getRepo()->canTransformVia404() ) {
351 $thumbSizes = $wgImageLimits;
352 } else {
353 # Creating thumb links triggers thumbnail generation.
354 # Just generate the thumb for the current users prefs.
355 $thumbOption = $user->getOption( 'thumbsize' );
356 $thumbSizes = array( isset( $wgImageLimits[$thumbOption] )
357 ? $wgImageLimits[$thumbOption]
358 : $wgImageLimits[User::getDefaultOption( 'thumbsize' )] );
360 # Generate thumbnails or thumbnail links as needed...
361 $otherSizes = array();
362 foreach ( $thumbSizes as $size ) {
363 if ( $size[0] < $width_orig && $size[1] < $height_orig
364 && $size[0] != $width && $size[1] != $height )
366 $otherSizes[] = $this->makeSizeLink( $params, $size[0], $size[1] );
369 $msgsmall = wfMessage( 'show-big-image-preview' )->
370 rawParams( $this->makeSizeLink( $params, $width, $height ) )->
371 parse();
372 if ( count( $otherSizes ) ) {
373 $msgsmall .= ' ' .
374 Html::rawElement( 'span', array( 'class' => 'mw-filepage-other-resolutions' ),
375 wfMessage( 'show-big-image-other' )->rawParams( $lang->pipeList( $otherSizes ) )->
376 params( count( $otherSizes ) )->parse()
379 } elseif ( $width == 0 && $height == 0 ){
380 # Some sort of audio file that doesn't have dimensions
381 # Don't output a no hi res message for such a file
382 $msgsmall = '';
383 } else {
384 # Image is small enough to show full size on image page
385 $msgsmall = wfMessage( 'file-nohires' )->parse();
388 $params['width'] = $width;
389 $params['height'] = $height;
390 $thumbnail = $this->displayImg->transform( $params );
392 $showLink = true;
393 $anchorclose = Html::rawElement( 'div', array( 'class' => 'mw-filepage-resolutioninfo' ), $msgsmall );
395 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
396 if ( $isMulti ) {
397 $out->addHTML( '<table class="multipageimage"><tr><td>' );
400 if ( $thumbnail ) {
401 $options = array(
402 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
403 'file-link' => true,
405 $out->addHTML( '<div class="fullImageLink" id="file">' .
406 $thumbnail->toHtml( $options ) .
407 $anchorclose . "</div>\n" );
410 if ( $isMulti ) {
411 $count = $this->displayImg->pageCount();
413 if ( $page > 1 ) {
414 $label = $out->parse( wfMsg( 'imgmultipageprev' ), false );
415 $link = Linker::link(
416 $this->getTitle(),
417 $label,
418 array(),
419 array( 'page' => $page - 1 ),
420 array( 'known', 'noclasses' )
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 = wfMsg( 'imgmultipagenext' );
430 $link = Linker::link(
431 $this->getTitle(),
432 $label,
433 array(),
434 array( 'page' => $page + 1 ),
435 array( 'known', 'noclasses' )
437 $thumb2 = Linker::makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
438 array( 'page' => $page + 1 ) );
439 } else {
440 $thumb2 = '';
443 global $wgScript;
445 $formParams = array(
446 'name' => 'pageselector',
447 'action' => $wgScript,
448 'onchange' => 'document.pageselector.submit();',
450 $options = array();
451 for ( $i = 1; $i <= $count; $i++ ) {
452 $options[] = Xml::option( $lang->formatNum( $i ), $i, $i == $page );
454 $select = Xml::tags( 'select',
455 array( 'id' => 'pageselector', 'name' => 'page' ),
456 implode( "\n", $options ) );
458 $out->addHTML(
459 '</td><td><div class="multipageimagenavbox">' .
460 Xml::openElement( 'form', $formParams ) .
461 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
462 wfMsgExt( 'imgmultigoto', array( 'parseinline', 'replaceafter' ), $select ) .
463 Xml::submitButton( wfMsg( 'imgmultigo' ) ) .
464 Xml::closeElement( 'form' ) .
465 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
468 } else {
469 # if direct link is allowed but it's not a renderable image, show an icon.
470 if ( $this->displayImg->isSafeFile() ) {
471 $icon = $this->displayImg->iconThumb();
473 $out->addHTML( '<div class="fullImageLink" id="file">' .
474 $icon->toHtml( array( 'file-link' => true ) ) .
475 "</div>\n" );
478 $showLink = true;
481 if ( $showLink ) {
482 $filename = wfEscapeWikiText( $this->displayImg->getName() );
483 $linktext = $filename;
484 if ( isset( $msgbig ) ) {
485 $linktext = wfEscapeWikiText( $msgbig );
487 $medialink = "[[Media:$filename|$linktext]]";
489 if ( !$this->displayImg->isSafeFile() ) {
490 $warning = wfMsgNoTrans( 'mediawarning' );
491 // dirmark is needed here to separate the file name, which
492 // most likely ends in Latin characters, from the description,
493 // which may begin with the file type. In RTL environment
494 // this will get messy.
495 // The dirmark, however, must not be immediately adjacent
496 // to the filename, because it can get copied with it.
497 // See bug 25277.
498 $out->addWikiText( <<<EOT
499 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
500 <div class="mediaWarning">$warning</div>
503 } else {
504 $out->addWikiText( <<<EOT
505 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
506 </div>
512 if ( !$this->displayImg->isLocal() ) {
513 $this->printSharedImageText();
515 } else {
516 # Image does not exist
517 if ( !$this->getID() ) {
518 # No article exists either
519 # Show deletion log to be consistent with normal articles
520 LogEventsList::showLogExtract(
521 $out,
522 array( 'delete', 'move' ),
523 $this->getTitle()->getPrefixedText(),
525 array( 'lim' => 10,
526 'conds' => array( "log_action != 'revision'" ),
527 'showIfEmpty' => false,
528 'msgKey' => array( 'moveddeleted-notice' )
533 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
534 // Only show an upload link if the user can upload
535 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
536 $nofile = array(
537 'filepage-nofile-link',
538 $uploadTitle->getFullURL( array( 'wpDestFile' => $this->mPage->getFile()->getName() ) )
540 } else {
541 $nofile = 'filepage-nofile';
543 // Note, if there is an image description page, but
544 // no image, then this setRobotPolicy is overriden
545 // by Article::View().
546 $out->setRobotPolicy( 'noindex,nofollow' );
547 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
548 if ( !$this->getID() && $wgSend404Code ) {
549 // If there is no image, no shared image, and no description page,
550 // output a 404, to be consistent with articles.
551 $request->response()->header( 'HTTP/1.1 404 Not Found' );
554 $out->setFileVersion( $this->displayImg );
558 * Creates an thumbnail of specified size and returns an HTML link to it
559 * @param $params array Scaler parameters
560 * @param $width int
561 * @param $height int
562 * @return string
564 private function makeSizeLink( $params, $width, $height ) {
565 $params['width'] = $width;
566 $params['height'] = $height;
567 $thumbnail = $this->displayImg->transform( $params );
568 if ( $thumbnail && !$thumbnail->isError() ) {
569 return Html::rawElement( 'a', array(
570 'href' => $thumbnail->getUrl(),
571 'class' => 'mw-thumbnail-link'
572 ), wfMessage( 'show-big-image-size' )->numParams(
573 $thumbnail->getWidth(), $thumbnail->getHeight()
574 )->parse() );
575 } else {
576 return '';
581 * Show a notice that the file is from a shared repository
583 protected function printSharedImageText() {
584 $out = $this->getContext()->getOutput();
585 $this->loadFile();
587 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
588 $descText = $this->mPage->getFile()->getDescriptionText();
590 /* Add canonical to head if there is no local page for this shared file */
591 if( $descUrl && $this->mPage->getID() == 0 ) {
592 $out->addLink( array( 'rel' => 'canonical', 'href' => $descUrl ) );
595 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
596 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
598 if ( $descUrl && $descText && wfMsgNoTrans( 'sharedupload-desc-here' ) !== '-' ) {
599 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
600 } elseif ( $descUrl && wfMsgNoTrans( 'sharedupload-desc-there' ) !== '-' ) {
601 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
602 } else {
603 $out->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
606 if ( $descText ) {
607 $this->mExtraDescription = $descText;
611 public function getUploadUrl() {
612 $this->loadFile();
613 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
614 return $uploadTitle->getFullURL( array(
615 'wpDestFile' => $this->mPage->getFile()->getName(),
616 'wpForReUpload' => 1
617 ) );
621 * Print out the various links at the bottom of the image page, e.g. reupload,
622 * external editing (and instructions link) etc.
624 protected function uploadLinksBox() {
625 global $wgEnableUploads, $wgUseExternalEditor;
627 if ( !$wgEnableUploads ) {
628 return;
631 $this->loadFile();
632 if ( !$this->mPage->getFile()->isLocal() ) {
633 return;
636 $out = $this->getContext()->getOutput();
637 $out->addHTML( "<br /><ul>\n" );
639 # "Upload a new version of this file" link
640 if ( UploadBase::userCanReUpload( $this->getContext()->getUser(), $this->mPage->getFile()->name ) ) {
641 $ulink = Linker::makeExternalLink( $this->getUploadUrl(), wfMsg( 'uploadnewversion-linktext' ) );
642 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\"><div class=\"plainlinks\">{$ulink}</div></li>\n" );
645 # External editing link
646 if ( $wgUseExternalEditor ) {
647 $elink = Linker::link(
648 $this->getTitle(),
649 wfMsgHtml( 'edit-externally' ),
650 array(),
651 array(
652 'action' => 'edit',
653 'externaledit' => 'true',
654 'mode' => 'file'
656 array( 'known', 'noclasses' )
658 $out->addHTML(
659 '<li id="mw-imagepage-edit-external">' . $elink . ' <small>' .
660 wfMsgExt( 'edit-externally-help', array( 'parseinline' ) ) .
661 "</small></li>\n"
665 $out->addHTML( "</ul>\n" );
668 protected function closeShowImage() { } # For overloading
671 * If the page we've just displayed is in the "Image" namespace,
672 * we follow it with an upload history of the image and its usage.
674 protected function imageHistory() {
675 $this->loadFile();
676 $out = $this->getContext()->getOutput();
677 $pager = new ImageHistoryPseudoPager( $this );
678 $out->addHTML( $pager->getBody() );
679 $out->preventClickjacking( $pager->getPreventClickjacking() );
681 $this->mPage->getFile()->resetHistory(); // free db resources
683 # Exist check because we don't want to show this on pages where an image
684 # doesn't exist along with the noimage message, that would suck. -ævar
685 if ( $this->mPage->getFile()->exists() ) {
686 $this->uploadLinksBox();
691 * @param $target
692 * @param $limit
693 * @return ResultWrapper
695 protected function queryImageLinks( $target, $limit ) {
696 $dbr = wfGetDB( DB_SLAVE );
698 return $dbr->select(
699 array( 'imagelinks', 'page' ),
700 array( 'page_namespace', 'page_title', 'page_is_redirect', 'il_to' ),
701 array( 'il_to' => $target, 'il_from = page_id' ),
702 __METHOD__,
703 array( 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', )
707 protected function imageLinks() {
708 $limit = 100;
710 $out = $this->getContext()->getOutput();
711 $res = $this->queryImageLinks( $this->getTitle()->getDbKey(), $limit + 1);
712 $rows = array();
713 $redirects = array();
714 foreach ( $res as $row ) {
715 if ( $row->page_is_redirect ) {
716 $redirects[$row->page_title] = array();
718 $rows[] = $row;
720 $count = count( $rows );
722 $hasMore = $count > $limit;
723 if ( !$hasMore && count( $redirects ) ) {
724 $res = $this->queryImageLinks( array_keys( $redirects ),
725 $limit - count( $rows ) + 1 );
726 foreach ( $res as $row ) {
727 $redirects[$row->il_to][] = $row;
728 $count++;
730 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
733 if ( $count == 0 ) {
734 $out->wrapWikiMsg(
735 Html::rawElement( 'div',
736 array( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ),
737 'nolinkstoimage'
739 return;
742 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
743 if ( !$hasMore ) {
744 $out->addWikiMsg( 'linkstoimage', $count );
745 } else {
746 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
747 $out->addWikiMsg( 'linkstoimage-more',
748 $this->getContext()->getLanguage()->formatNum( $limit ),
749 $this->getTitle()->getPrefixedDBkey()
753 $out->addHTML(
754 Html::openElement( 'ul',
755 array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n"
757 $count = 0;
759 // Sort the list by namespace:title
760 usort( $rows, array( $this, 'compare' ) );
762 // Create links for every element
763 $currentCount = 0;
764 foreach( $rows as $element ) {
765 $currentCount++;
766 if ( $currentCount > $limit ) {
767 break;
770 $link = Linker::linkKnown( Title::makeTitle( $element->page_namespace, $element->page_title ) );
771 if ( !isset( $redirects[$element->page_title] ) ) {
772 $liContents = $link;
773 } else {
774 $ul = "<ul class='mw-imagepage-redirectstofile'>\n";
775 foreach ( $redirects[$element->page_title] as $row ) {
776 $currentCount++;
777 if ( $currentCount > $limit ) {
778 break;
781 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
782 $ul .= Html::rawElement(
783 'li',
784 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
785 $link2
786 ) . "\n";
788 $ul .= '</ul>';
789 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams(
790 $link, $ul )->parse();
792 $out->addHTML( Html::rawElement(
793 'li',
794 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
795 $liContents
796 ) . "\n"
800 $out->addHTML( Html::closeElement( 'ul' ) . "\n" );
801 $res->free();
803 // Add a links to [[Special:Whatlinkshere]]
804 if ( $count > $limit ) {
805 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
807 $out->addHTML( Html::closeElement( 'div' ) . "\n" );
810 protected function imageDupes() {
811 $this->loadFile();
812 $out = $this->getContext()->getOutput();
814 $dupes = $this->mPage->getDuplicates();
815 if ( count( $dupes ) == 0 ) {
816 return;
819 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
820 $out->addWikiMsg( 'duplicatesoffile',
821 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
823 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
826 * @var $file File
828 foreach ( $dupes as $file ) {
829 $fromSrc = '';
830 if ( $file->isLocal() ) {
831 $link = Linker::link(
832 $file->getTitle(),
833 null,
834 array(),
835 array(),
836 array( 'known', 'noclasses' )
838 } else {
839 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
840 $file->getTitle()->getPrefixedText() );
841 $fromSrc = wfMsg( 'shared-repo-from', $file->getRepo()->getDisplayName() );
843 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
845 $out->addHTML( "</ul></div>\n" );
849 * Delete the file, or an earlier version of it
851 public function delete() {
852 $file = $this->mPage->getFile();
853 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
854 // Standard article deletion
855 parent::delete();
856 return;
859 $deleter = new FileDeleteForm( $file );
860 $deleter->execute();
864 * Display an error with a wikitext description
866 * @param $description String
868 function showError( $description ) {
869 $out = $this->getContext()->getOutput();
870 $out->setPageTitle( wfMessage( 'internalerror' ) );
871 $out->setRobotPolicy( 'noindex,nofollow' );
872 $out->setArticleRelated( false );
873 $out->enableClientCache( false );
874 $out->addWikiText( $description );
878 * Callback for usort() to do link sorts by (namespace, title)
879 * Function copied from Title::compare()
881 * @param $a object page to compare with
882 * @param $b object page to compare with
883 * @return Integer: result of string comparison, or namespace comparison
885 protected function compare( $a, $b ) {
886 if ( $a->page_namespace == $b->page_namespace ) {
887 return strcmp( $a->page_title, $b->page_title );
888 } else {
889 return $a->page_namespace - $b->page_namespace;
895 * Builds the image revision log shown on image pages
897 * @ingroup Media
899 class ImageHistoryList extends ContextSource {
902 * @var Title
904 protected $title;
907 * @var File
909 protected $img;
912 * @var ImagePage
914 protected $imagePage;
917 * @var File
919 protected $current;
921 protected $repo, $showThumb;
922 protected $preventClickjacking = false;
925 * @param ImagePage $imagePage
927 public function __construct( $imagePage ) {
928 global $wgShowArchiveThumbnails;
929 $this->current = $imagePage->getFile();
930 $this->img = $imagePage->getDisplayedFile();
931 $this->title = $imagePage->getTitle();
932 $this->imagePage = $imagePage;
933 $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
934 $this->setContext( $imagePage->getContext() );
938 * @return ImagePage
940 public function getImagePage() {
941 return $this->imagePage;
945 * @return File
947 public function getFile() {
948 return $this->img;
952 * @param $navLinks string
953 * @return string
955 public function beginImageHistoryList( $navLinks = '' ) {
956 return Xml::element( 'h2', array( 'id' => 'filehistory' ), wfMsg( 'filehist' ) ) . "\n"
957 . "<div id=\"mw-imagepage-section-filehistory\">\n"
958 . $this->getOutput()->parse( wfMsgNoTrans( 'filehist-help' ) )
959 . $navLinks . "\n"
960 . Xml::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
961 . '<tr><td></td>'
962 . ( $this->current->isLocal() && ( $this->getUser()->isAllowedAny( 'delete', 'deletedhistory' ) ) ? '<td></td>' : '' )
963 . '<th>' . wfMsgHtml( 'filehist-datetime' ) . '</th>'
964 . ( $this->showThumb ? '<th>' . wfMsgHtml( 'filehist-thumb' ) . '</th>' : '' )
965 . '<th>' . wfMsgHtml( 'filehist-dimensions' ) . '</th>'
966 . '<th>' . wfMsgHtml( 'filehist-user' ) . '</th>'
967 . '<th>' . wfMsgHtml( 'filehist-comment' ) . '</th>'
968 . "</tr>\n";
972 * @param $navLinks string
973 * @return string
975 public function endImageHistoryList( $navLinks = '' ) {
976 return "</table>\n$navLinks\n</div>\n";
980 * @param $iscur
981 * @param $file File
982 * @return string
984 public function imageHistoryLine( $iscur, $file ) {
985 global $wgContLang;
987 $user = $this->getUser();
988 $lang = $this->getLanguage();
989 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
990 $img = $iscur ? $file->getName() : $file->getArchiveName();
991 $userId = $file->getUser( 'id' );
992 $userText = $file->getUser( 'text' );
993 $description = $file->getDescription( File::FOR_THIS_USER, $user );
995 $local = $this->current->isLocal();
996 $row = $selected = '';
998 // Deletion link
999 if ( $local && ( $user->isAllowedAny( 'delete', 'deletedhistory' ) ) ) {
1000 $row .= '<td>';
1001 # Link to remove from history
1002 if ( $user->isAllowed( 'delete' ) ) {
1003 $q = array( 'action' => 'delete' );
1004 if ( !$iscur ) {
1005 $q['oldimage'] = $img;
1007 $row .= Linker::link(
1008 $this->title,
1009 wfMsgHtml( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' ),
1010 array(), $q, array( 'known' )
1013 # Link to hide content. Don't show useless link to people who cannot hide revisions.
1014 $canHide = $user->isAllowed( 'deleterevision' );
1015 if ( $canHide || ( $user->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
1016 if ( $user->isAllowed( 'delete' ) ) {
1017 $row .= '<br />';
1019 // If file is top revision or locked from this user, don't link
1020 if ( $iscur || !$file->userCan( File::DELETED_RESTRICTED ) ) {
1021 $del = Linker::revDeleteLinkDisabled( $canHide );
1022 } else {
1023 list( $ts, ) = explode( '!', $img, 2 );
1024 $query = array(
1025 'type' => 'oldimage',
1026 'target' => $this->title->getPrefixedText(),
1027 'ids' => $ts,
1029 $del = Linker::revDeleteLink( $query,
1030 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
1032 $row .= $del;
1034 $row .= '</td>';
1037 // Reversion link/current indicator
1038 $row .= '<td>';
1039 if ( $iscur ) {
1040 $row .= wfMsgHtml( 'filehist-current' );
1041 } elseif ( $local && $this->title->quickUserCan( 'edit' )
1042 && $this->title->quickUserCan( 'upload' )
1044 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1045 $row .= wfMsgHtml( 'filehist-revert' );
1046 } else {
1047 $row .= Linker::link(
1048 $this->title,
1049 wfMsgHtml( 'filehist-revert' ),
1050 array(),
1051 array(
1052 'action' => 'revert',
1053 'oldimage' => $img,
1054 'wpEditToken' => $user->getEditToken( $img )
1056 array( 'known', 'noclasses' )
1060 $row .= '</td>';
1062 // Date/time and image link
1063 if ( $file->getTimestamp() === $this->img->getTimestamp() ) {
1064 $selected = "class='filehistory-selected'";
1066 $row .= "<td $selected style='white-space: nowrap;'>";
1067 if ( !$file->userCan( File::DELETED_FILE ) ) {
1068 # Don't link to unviewable files
1069 $row .= '<span class="history-deleted">' . $lang->timeanddate( $timestamp, true ) . '</span>';
1070 } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
1071 if ( $local ) {
1072 $this->preventClickjacking();
1073 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
1074 # Make a link to review the image
1075 $url = Linker::link(
1076 $revdel,
1077 $lang->timeanddate( $timestamp, true ),
1078 array(),
1079 array(
1080 'target' => $this->title->getPrefixedText(),
1081 'file' => $img,
1082 'token' => $user->getEditToken( $img )
1084 array( 'known', 'noclasses' )
1086 } else {
1087 $url = $lang->timeanddate( $timestamp, true );
1089 $row .= '<span class="history-deleted">' . $url . '</span>';
1090 } else {
1091 $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
1092 $row .= Xml::element( 'a', array( 'href' => $url ), $lang->timeanddate( $timestamp, true ) );
1094 $row .= "</td>";
1096 // Thumbnail
1097 if ( $this->showThumb ) {
1098 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1101 // Image dimensions + size
1102 $row .= '<td>';
1103 $row .= htmlspecialchars( $file->getDimensionsString() );
1104 $row .= $this->getContext()->msg( 'word-separator' )->plain();
1105 $row .= '<span style="white-space: nowrap;">';
1106 $row .= $this->getContext()->msg( 'parentheses' )->rawParams( Linker::formatSize( $file->getSize() ) )->plain();
1107 $row .= '</span>';
1108 $row .= '</td>';
1110 // Uploading user
1111 $row .= '<td>';
1112 // Hide deleted usernames
1113 if ( $file->isDeleted( File::DELETED_USER ) ) {
1114 $row .= '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-user' ) . '</span>';
1115 } else {
1116 if ( $local ) {
1117 $row .= Linker::userLink( $userId, $userText );
1118 $row .= $this->getContext()->msg( 'word-separator' )->plain();
1119 $row .= '<span style="white-space: nowrap;">';
1120 $row .= Linker::userToolLinks( $userId, $userText );
1121 $row .= '</span>';
1122 } else {
1123 $row .= htmlspecialchars( $userText );
1126 $row .= '</td>';
1128 // Don't show deleted descriptions
1129 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1130 $row .= '<td><span class="history-deleted">' . wfMsgHtml( 'rev-deleted-comment' ) . '</span></td>';
1131 } else {
1132 $row .= '<td dir="' . $wgContLang->getDir() . '">' . Linker::formatComment( $description, $this->title ) . '</td>';
1135 $rowClass = null;
1136 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1137 $classAttr = $rowClass ? " class='$rowClass'" : '';
1139 return "<tr{$classAttr}>{$row}</tr>\n";
1143 * @param $file File
1144 * @return string
1146 protected function getThumbForLine( $file ) {
1147 $lang = $this->getLanguage();
1148 if ( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE ) && !$file->isDeleted( File::DELETED_FILE ) ) {
1149 $params = array(
1150 'width' => '120',
1151 'height' => '120',
1153 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1155 $thumbnail = $file->transform( $params );
1156 $options = array(
1157 'alt' => wfMsg( 'filehist-thumbtext',
1158 $lang->timeanddate( $timestamp, true ),
1159 $lang->date( $timestamp, true ),
1160 $lang->time( $timestamp, true ) ),
1161 'file-link' => true,
1164 if ( !$thumbnail ) {
1165 return wfMsgHtml( 'filehist-nothumb' );
1168 return $thumbnail->toHtml( $options );
1169 } else {
1170 return wfMsgHtml( 'filehist-nothumb' );
1175 * @param $enable bool
1177 protected function preventClickjacking( $enable = true ) {
1178 $this->preventClickjacking = $enable;
1182 * @return bool
1184 public function getPreventClickjacking() {
1185 return $this->preventClickjacking;
1189 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1190 protected $preventClickjacking = false;
1193 * @var File
1195 protected $mImg;
1198 * @var Title
1200 protected $mTitle;
1203 * @param ImagePage $imagePage
1205 function __construct( $imagePage ) {
1206 parent::__construct();
1207 $this->mImagePage = $imagePage;
1208 $this->mTitle = clone ( $imagePage->getTitle() );
1209 $this->mTitle->setFragment( '#filehistory' );
1210 $this->mImg = null;
1211 $this->mHist = array();
1212 $this->mRange = array( 0, 0 ); // display range
1216 * @return Title
1218 function getTitle() {
1219 return $this->mTitle;
1222 function getQueryInfo() {
1223 return false;
1227 * @return string
1229 function getIndexField() {
1230 return '';
1234 * @param $row object
1235 * @return string
1237 function formatRow( $row ) {
1238 return '';
1242 * @return string
1244 function getBody() {
1245 $s = '';
1246 $this->doQuery();
1247 if ( count( $this->mHist ) ) {
1248 $list = new ImageHistoryList( $this->mImagePage );
1249 # Generate prev/next links
1250 $navLink = $this->getNavigationBar();
1251 $s = $list->beginImageHistoryList( $navLink );
1252 // Skip rows there just for paging links
1253 for ( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1254 $file = $this->mHist[$i];
1255 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1257 $s .= $list->endImageHistoryList( $navLink );
1259 if ( $list->getPreventClickjacking() ) {
1260 $this->preventClickjacking();
1263 return $s;
1266 function doQuery() {
1267 if ( $this->mQueryDone ) {
1268 return;
1270 $this->mImg = $this->mImagePage->getFile(); // ensure loading
1271 if ( !$this->mImg->exists() ) {
1272 return;
1274 $queryLimit = $this->mLimit + 1; // limit plus extra row
1275 if ( $this->mIsBackwards ) {
1276 // Fetch the file history
1277 $this->mHist = $this->mImg->getHistory( $queryLimit, null, $this->mOffset, false );
1278 // The current rev may not meet the offset/limit
1279 $numRows = count( $this->mHist );
1280 if ( $numRows <= $this->mLimit && $this->mImg->getTimestamp() > $this->mOffset ) {
1281 $this->mHist = array_merge( array( $this->mImg ), $this->mHist );
1283 } else {
1284 // The current rev may not meet the offset
1285 if ( !$this->mOffset || $this->mImg->getTimestamp() < $this->mOffset ) {
1286 $this->mHist[] = $this->mImg;
1288 // Old image versions (fetch extra row for nav links)
1289 $oiLimit = count( $this->mHist ) ? $this->mLimit : $this->mLimit + 1;
1290 // Fetch the file history
1291 $this->mHist = array_merge( $this->mHist,
1292 $this->mImg->getHistory( $oiLimit, $this->mOffset, null, false ) );
1294 $numRows = count( $this->mHist ); // Total number of query results
1295 if ( $numRows ) {
1296 # Index value of top item in the list
1297 $firstIndex = $this->mIsBackwards ?
1298 $this->mHist[$numRows - 1]->getTimestamp() : $this->mHist[0]->getTimestamp();
1299 # Discard the extra result row if there is one
1300 if ( $numRows > $this->mLimit && $numRows > 1 ) {
1301 if ( $this->mIsBackwards ) {
1302 # Index value of item past the index
1303 $this->mPastTheEndIndex = $this->mHist[0]->getTimestamp();
1304 # Index value of bottom item in the list
1305 $lastIndex = $this->mHist[1]->getTimestamp();
1306 # Display range
1307 $this->mRange = array( 1, $numRows - 1 );
1308 } else {
1309 # Index value of item past the index
1310 $this->mPastTheEndIndex = $this->mHist[$numRows - 1]->getTimestamp();
1311 # Index value of bottom item in the list
1312 $lastIndex = $this->mHist[$numRows - 2]->getTimestamp();
1313 # Display range
1314 $this->mRange = array( 0, $numRows - 2 );
1316 } else {
1317 # Setting indexes to an empty string means that they will be
1318 # omitted if they would otherwise appear in URLs. It just so
1319 # happens that this is the right thing to do in the standard
1320 # UI, in all the relevant cases.
1321 $this->mPastTheEndIndex = '';
1322 # Index value of bottom item in the list
1323 $lastIndex = $this->mIsBackwards ?
1324 $this->mHist[0]->getTimestamp() : $this->mHist[$numRows - 1]->getTimestamp();
1325 # Display range
1326 $this->mRange = array( 0, $numRows - 1 );
1328 } else {
1329 $firstIndex = '';
1330 $lastIndex = '';
1331 $this->mPastTheEndIndex = '';
1333 if ( $this->mIsBackwards ) {
1334 $this->mIsFirst = ( $numRows < $queryLimit );
1335 $this->mIsLast = ( $this->mOffset == '' );
1336 $this->mLastShown = $firstIndex;
1337 $this->mFirstShown = $lastIndex;
1338 } else {
1339 $this->mIsFirst = ( $this->mOffset == '' );
1340 $this->mIsLast = ( $numRows < $queryLimit );
1341 $this->mLastShown = $lastIndex;
1342 $this->mFirstShown = $firstIndex;
1344 $this->mQueryDone = true;
1348 * @param $enable bool
1350 protected function preventClickjacking( $enable = true ) {
1351 $this->preventClickjacking = $enable;
1355 * @return bool
1357 public function getPreventClickjacking() {
1358 return $this->preventClickjacking;