* partly fixes two issues exposed by bug 34280
[mediawiki.git] / includes / ImagePage.php
blob7e72db909e2bfd0c396f5c98439bf55d5bcdf0cf
1 <?php
2 /**
3 * Class for viewing MediaWiki file description pages
5 * @ingroup Media
6 */
7 class ImagePage extends Article {
9 /**
10 * @var File
12 private $displayImg;
13 /**
14 * @var FileRepo
16 private $repo;
17 private $fileLoaded;
19 var $mExtraDescription = false;
21 /**
22 * @param $title Title
23 * @return WikiFilePage
25 protected function newPage( Title $title ) {
26 // Overload mPage with a file-specific page
27 return new WikiFilePage( $title );
30 /**
31 * Constructor from a page id
32 * @param $id Int article ID to load
33 * @returnImagePage|null
35 public static function newFromID( $id ) {
36 $t = Title::newFromID( $id );
37 # @todo FIXME: Doesn't inherit right
38 return $t == null ? null : new self( $t );
39 # return $t == null ? null : new static( $t ); // PHP 5.3
42 /**
43 * @param $file File:
44 * @return void
46 public function setFile( $file ) {
47 $this->mPage->setFile( $file );
48 $this->displayImg = $file;
49 $this->fileLoaded = true;
52 protected function loadFile() {
53 if ( $this->fileLoaded ) {
54 return true;
56 $this->fileLoaded = true;
58 $this->displayImg = $img = false;
59 wfRunHooks( 'ImagePageFindFile', array( $this, &$img, &$this->displayImg ) );
60 if ( !$img ) { // not set by hook?
61 $img = wfFindFile( $this->getTitle() );
62 if ( !$img ) {
63 $img = wfLocalFile( $this->getTitle() );
66 $this->mPage->setFile( $img );
67 if ( !$this->displayImg ) { // not set by hook?
68 $this->displayImg = $img;
70 $this->repo = $img->getRepo();
73 /**
74 * Handler for action=render
75 * Include body text only; none of the image extras
77 public function render() {
78 global $wgOut;
79 $wgOut->setArticleBodyOnly( true );
80 parent::view();
83 public function view() {
84 global $wgOut, $wgShowEXIF, $wgRequest, $wgUser;
86 $diff = $wgRequest->getVal( 'diff' );
87 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
89 if ( $this->getTitle()->getNamespace() != NS_FILE || ( isset( $diff ) && $diffOnly ) ) {
90 return parent::view();
93 $this->loadFile();
95 if ( $this->getTitle()->getNamespace() == NS_FILE && $this->mPage->getFile()->getRedirected() ) {
96 if ( $this->getTitle()->getDBkey() == $this->mPage->getFile()->getName() || isset( $diff ) ) {
97 // mTitle is the same as the redirect target so ask Article
98 // to perform the redirect for us.
99 $wgRequest->setVal( 'diffonly', 'true' );
100 return parent::view();
101 } else {
102 // mTitle is not the same as the redirect target so it is
103 // probably the redirect page itself. Fake the redirect symbol
104 $wgOut->setPageTitle( $this->getTitle()->getPrefixedText() );
105 $wgOut->addHTML( $this->viewRedirect( Title::makeTitle( NS_FILE, $this->mPage->getFile()->getName() ),
106 /* $appendSubtitle */ true, /* $forceKnown */ true ) );
107 $this->mPage->doViewUpdates( $this->getContext()->getUser() );
108 return;
112 if ( $wgShowEXIF && $this->displayImg->exists() ) {
113 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
114 $formattedMetadata = $this->displayImg->formatMetadata();
115 $showmeta = $formattedMetadata !== false;
116 } else {
117 $showmeta = false;
120 if ( !$diff && $this->displayImg->exists() ) {
121 $wgOut->addHTML( $this->showTOC( $showmeta ) );
124 if ( !$diff ) {
125 $this->openShowImage();
128 # No need to display noarticletext, we use our own message, output in openShowImage()
129 if ( $this->mPage->getID() ) {
130 # NS_FILE is in the user language, but this section (the actual wikitext)
131 # should be in page content language
132 $pageLang = $this->getTitle()->getPageLanguage();
133 $wgOut->addHTML( Xml::openElement( 'div', array( 'id' => 'mw-imagepage-content',
134 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
135 'class' => 'mw-content-'.$pageLang->getDir() ) ) );
136 parent::view();
137 $wgOut->addHTML( Xml::closeElement( 'div' ) );
138 } else {
139 # Just need to set the right headers
140 $wgOut->setArticleFlag( true );
141 $wgOut->setPageTitle( $this->getTitle()->getPrefixedText() );
142 $this->mPage->doViewUpdates( $this->getContext()->getUser() );
145 # Show shared description, if needed
146 if ( $this->mExtraDescription ) {
147 $fol = wfMessage( 'shareddescriptionfollows' );
148 if ( !$fol->isDisabled() ) {
149 $wgOut->addWikiText( $fol->plain() );
151 $wgOut->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
154 $this->closeShowImage();
155 $this->imageHistory();
156 // TODO: Cleanup the following
158 $wgOut->addHTML( Xml::element( 'h2',
159 array( 'id' => 'filelinks' ),
160 wfMsg( 'imagelinks' ) ) . "\n" );
161 $this->imageDupes();
162 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
163 # Yet we return metadata about the target. Definitely an issue in the FileRepo
164 $this->imageLinks();
166 # Allow extensions to add something after the image links
167 $html = '';
168 wfRunHooks( 'ImagePageAfterImageLinks', array( $this, &$html ) );
169 if ( $html ) {
170 $wgOut->addHTML( $html );
173 if ( $showmeta ) {
174 $wgOut->addHTML( Xml::element( 'h2', array( 'id' => 'metadata' ), wfMsg( 'metadata' ) ) . "\n" );
175 $wgOut->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
176 $wgOut->addModules( array( 'mediawiki.action.view.metadata' ) );
179 // Add remote Filepage.css
180 if( !$this->repo->isLocal() ) {
181 $css = $this->repo->getDescriptionStylesheetUrl();
182 if ( $css ) {
183 $wgOut->addStyle( $css );
186 // always show the local local Filepage.css, bug 29277
187 $wgOut->addModuleStyles( 'filepage' );
191 * @return File
193 public function getDisplayedFile() {
194 $this->loadFile();
195 return $this->displayImg;
199 * Create the TOC
201 * @param $metadata Boolean: whether or not to show the metadata link
202 * @return String
204 protected function showTOC( $metadata ) {
205 $r = array(
206 '<li><a href="#file">' . wfMsgHtml( 'file-anchor-link' ) . '</a></li>',
207 '<li><a href="#filehistory">' . wfMsgHtml( 'filehist' ) . '</a></li>',
208 '<li><a href="#filelinks">' . wfMsgHtml( 'imagelinks' ) . '</a></li>',
210 if ( $metadata ) {
211 $r[] = '<li><a href="#metadata">' . wfMsgHtml( 'metadata' ) . '</a></li>';
214 wfRunHooks( 'ImagePageShowTOC', array( $this, &$r ) );
216 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
220 * Make a table with metadata to be shown in the output page.
222 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
224 * @param $metadata Array: the array containing the EXIF data
225 * @return String The metadata table. This is treated as Wikitext (!)
227 protected function makeMetadataTable( $metadata ) {
228 $r = "<div class=\"mw-imagepage-section-metadata\">";
229 $r .= wfMsgNoTrans( 'metadata-help' );
230 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
231 foreach ( $metadata as $type => $stuff ) {
232 foreach ( $stuff as $v ) {
233 # @todo FIXME: Why is this using escapeId for a class?!
234 $class = Sanitizer::escapeId( $v['id'] );
235 if ( $type == 'collapsed' ) {
236 $class .= ' collapsable';
238 $r .= "<tr class=\"$class\">\n";
239 $r .= "<th>{$v['name']}</th>\n";
240 $r .= "<td>{$v['value']}</td>\n</tr>";
243 $r .= "</table>\n</div>\n";
244 return $r;
248 * Overloading Article's getContent method.
250 * Omit noarticletext if sharedupload; text will be fetched from the
251 * shared upload server if possible.
252 * @return string
254 public function getContent() {
255 $this->loadFile();
256 if ( $this->mPage->getFile() && !$this->mPage->getFile()->isLocal() && 0 == $this->getID() ) {
257 return '';
259 return parent::getContent();
262 protected function openShowImage() {
263 global $wgOut, $wgUser, $wgImageLimits, $wgRequest,
264 $wgLang, $wgEnableUploads, $wgSend404Code;
266 $this->loadFile();
268 $sizeSel = intval( $wgUser->getOption( 'imagesize' ) );
269 if ( !isset( $wgImageLimits[$sizeSel] ) ) {
270 $sizeSel = User::getDefaultOption( 'imagesize' );
272 // The user offset might still be incorrect, specially if
273 // $wgImageLimits got changed (see bug #8858).
274 if ( !isset( $wgImageLimits[$sizeSel] ) ) {
275 // Default to the first offset in $wgImageLimits
276 $sizeSel = 0;
279 $max = $wgImageLimits[$sizeSel];
280 $maxWidth = $max[0];
281 $maxHeight = $max[1];
282 $dirmark = $wgLang->getDirMark();
284 if ( $this->displayImg->exists() ) {
285 # image
286 $page = $wgRequest->getIntOrNull( 'page' );
287 if ( is_null( $page ) ) {
288 $params = array();
289 $page = 1;
290 } else {
291 $params = array( 'page' => $page );
293 $width_orig = $this->displayImg->getWidth( $page );
294 $width = $width_orig;
295 $height_orig = $this->displayImg->getHeight( $page );
296 $height = $height_orig;
298 $longDesc = wfMsg( 'parentheses', $this->displayImg->getLongDesc() );
300 wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this, &$wgOut ) );
302 if ( $this->displayImg->allowInlineDisplay() ) {
303 # image
305 # "Download high res version" link below the image
306 # $msgsize = wfMsgHtml( 'file-info-size', $width_orig, $height_orig, Linker::formatSize( $this->displayImg->getSize() ), $mime );
307 # We'll show a thumbnail of this image
308 if ( $width > $maxWidth || $height > $maxHeight ) {
309 # Calculate the thumbnail size.
310 # First case, the limiting factor is the width, not the height.
311 if ( $width / $height >= $maxWidth / $maxHeight ) {
312 $height = round( $height * $maxWidth / $width );
313 $width = $maxWidth;
314 # Note that $height <= $maxHeight now.
315 } else {
316 $newwidth = floor( $width * $maxHeight / $height );
317 $height = round( $height * $newwidth / $width );
318 $width = $newwidth;
319 # Note that $height <= $maxHeight now, but might not be identical
320 # because of rounding.
322 $msgbig = wfMsgHtml( 'show-big-image' );
323 $otherSizes = array();
324 foreach ( $wgImageLimits as $size ) {
325 if ( $size[0] < $width_orig && $size[1] < $height_orig &&
326 $size[0] != $width && $size[1] != $height ) {
327 $otherSizes[] = $this->makeSizeLink( $params, $size[0], $size[1] );
330 $msgsmall = wfMessage( 'show-big-image-preview' )->
331 rawParams( $this->makeSizeLink( $params, $width, $height ) )->
332 parse();
333 if ( count( $otherSizes ) && $this->displayImg->getRepo()->canTransformVia404() ) {
334 $msgsmall .= ' ' .
335 Html::rawElement( 'span', array( 'class' => 'mw-filepage-other-resolutions' ),
336 wfMessage( 'show-big-image-other' )->rawParams( $wgLang->pipeList( $otherSizes ) )->
337 params( count( $otherSizes ) )->parse()
340 } elseif ( $width == 0 && $height == 0 ){
341 # Some sort of audio file that doesn't have dimensions
342 # Don't output a no hi res message for such a file
343 $msgsmall = '';
344 } else {
345 # Image is small enough to show full size on image page
346 $msgsmall = wfMessage( 'file-nohires' )->parse();
349 $params['width'] = $width;
350 $params['height'] = $height;
351 $thumbnail = $this->displayImg->transform( $params );
353 $showLink = true;
354 $anchorclose = Html::rawElement( 'div', array( 'class' => 'mw-filepage-resolutioninfo' ), $msgsmall );
356 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
357 if ( $isMulti ) {
358 $wgOut->addHTML( '<table class="multipageimage"><tr><td>' );
361 if ( $thumbnail ) {
362 $options = array(
363 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
364 'file-link' => true,
366 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
367 $thumbnail->toHtml( $options ) .
368 $anchorclose . "</div>\n" );
371 if ( $isMulti ) {
372 $count = $this->displayImg->pageCount();
374 if ( $page > 1 ) {
375 $label = $wgOut->parse( wfMsg( 'imgmultipageprev' ), false );
376 $link = Linker::link(
377 $this->getTitle(),
378 $label,
379 array(),
380 array( 'page' => $page - 1 ),
381 array( 'known', 'noclasses' )
383 $thumb1 = Linker::makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
384 array( 'page' => $page - 1 ) );
385 } else {
386 $thumb1 = '';
389 if ( $page < $count ) {
390 $label = wfMsg( 'imgmultipagenext' );
391 $link = Linker::link(
392 $this->getTitle(),
393 $label,
394 array(),
395 array( 'page' => $page + 1 ),
396 array( 'known', 'noclasses' )
398 $thumb2 = Linker::makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
399 array( 'page' => $page + 1 ) );
400 } else {
401 $thumb2 = '';
404 global $wgScript;
406 $formParams = array(
407 'name' => 'pageselector',
408 'action' => $wgScript,
409 'onchange' => 'document.pageselector.submit();',
411 $options = array();
412 for ( $i = 1; $i <= $count; $i++ ) {
413 $options[] = Xml::option( $wgLang->formatNum( $i ), $i, $i == $page );
415 $select = Xml::tags( 'select',
416 array( 'id' => 'pageselector', 'name' => 'page' ),
417 implode( "\n", $options ) );
419 $wgOut->addHTML(
420 '</td><td><div class="multipageimagenavbox">' .
421 Xml::openElement( 'form', $formParams ) .
422 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
423 wfMsgExt( 'imgmultigoto', array( 'parseinline', 'replaceafter' ), $select ) .
424 Xml::submitButton( wfMsg( 'imgmultigo' ) ) .
425 Xml::closeElement( 'form' ) .
426 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
429 } else {
430 # if direct link is allowed but it's not a renderable image, show an icon.
431 if ( $this->displayImg->isSafeFile() ) {
432 $icon = $this->displayImg->iconThumb();
434 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
435 $icon->toHtml( array( 'file-link' => true ) ) .
436 "</div>\n" );
439 $showLink = true;
442 if ( $showLink ) {
443 $filename = wfEscapeWikiText( $this->displayImg->getName() );
444 $linktext = $filename;
445 if ( isset( $msgbig ) ) {
446 $linktext = wfEscapeWikiText( $msgbig );
448 $medialink = "[[Media:$filename|$linktext]]";
450 if ( !$this->displayImg->isSafeFile() ) {
451 $warning = wfMsgNoTrans( 'mediawarning' );
452 $wgOut->addWikiText( <<<EOT
453 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span>$dirmark <span class="fileInfo">$longDesc</span></div>
454 <div class="mediaWarning">$warning</div>
457 } else {
458 $wgOut->addWikiText( <<<EOT
459 <div class="fullMedia">{$medialink}{$dirmark} <span class="fileInfo">$longDesc</span>
460 </div>
466 if ( !$this->displayImg->isLocal() ) {
467 $this->printSharedImageText();
469 } else {
470 # Image does not exist
471 if ( $wgEnableUploads && $wgUser->isAllowed( 'upload' ) ) {
472 // Only show an upload link if the user can upload
473 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
474 $nofile = array(
475 'filepage-nofile-link',
476 $uploadTitle->getFullURL( array( 'wpDestFile' => $this->mPage->getFile()->getName() ) )
478 } else {
479 $nofile = 'filepage-nofile';
481 // Note, if there is an image description page, but
482 // no image, then this setRobotPolicy is overriden
483 // by Article::View().
484 $wgOut->setRobotPolicy( 'noindex,nofollow' );
485 $wgOut->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
486 if ( !$this->getID() && $wgSend404Code ) {
487 // If there is no image, no shared image, and no description page,
488 // output a 404, to be consistent with articles.
489 $wgRequest->response()->header( 'HTTP/1.1 404 Not Found' );
492 $wgOut->setFileVersion( $this->displayImg );
496 * Creates an thumbnail of specified size and returns an HTML link to it
497 * @param $params array Scaler parameters
498 * @param $width int
499 * @param $height int
500 * @return string
502 private function makeSizeLink( $params, $width, $height ) {
503 $params['width'] = $width;
504 $params['height'] = $height;
505 $thumbnail = $this->displayImg->transform( $params );
506 if ( $thumbnail && !$thumbnail->isError() ) {
507 return Html::rawElement( 'a', array(
508 'href' => $thumbnail->getUrl(),
509 'class' => 'mw-thumbnail-link'
510 ), wfMessage( 'show-big-image-size' )->numParams(
511 $thumbnail->getWidth(), $thumbnail->getHeight()
512 )->parse() );
513 } else {
514 return '';
519 * Show a notice that the file is from a shared repository
521 protected function printSharedImageText() {
522 global $wgOut;
524 $this->loadFile();
526 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
527 $descText = $this->mPage->getFile()->getDescriptionText();
529 /* Add canonical to head if there is no local page for this shared file */
530 if( $descUrl && $this->mPage->getID() == 0 ) {
531 $wgOut->addLink( array( 'rel' => 'canonical', 'href' => $descUrl ) );
534 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
535 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
537 if ( $descUrl && $descText && wfMsgNoTrans( 'sharedupload-desc-here' ) !== '-' ) {
538 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
539 } elseif ( $descUrl && wfMsgNoTrans( 'sharedupload-desc-there' ) !== '-' ) {
540 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
541 } else {
542 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
545 if ( $descText ) {
546 $this->mExtraDescription = $descText;
550 public function getUploadUrl() {
551 $this->loadFile();
552 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
553 return $uploadTitle->getFullURL( array(
554 'wpDestFile' => $this->mPage->getFile()->getName(),
555 'wpForReUpload' => 1
556 ) );
560 * Print out the various links at the bottom of the image page, e.g. reupload,
561 * external editing (and instructions link) etc.
563 protected function uploadLinksBox() {
564 global $wgUser, $wgOut, $wgEnableUploads, $wgUseExternalEditor;
566 if ( !$wgEnableUploads ) {
567 return;
570 $this->loadFile();
571 if ( !$this->mPage->getFile()->isLocal() ) {
572 return;
575 $wgOut->addHTML( "<br /><ul>\n" );
577 # "Upload a new version of this file" link
578 if ( UploadBase::userCanReUpload( $wgUser, $this->mPage->getFile()->name ) ) {
579 $ulink = Linker::makeExternalLink( $this->getUploadUrl(), wfMsg( 'uploadnewversion-linktext' ) );
580 $wgOut->addHTML( "<li id=\"mw-imagepage-reupload-link\"><div class=\"plainlinks\">{$ulink}</div></li>\n" );
583 # External editing link
584 if ( $wgUseExternalEditor ) {
585 $elink = Linker::link(
586 $this->getTitle(),
587 wfMsgHtml( 'edit-externally' ),
588 array(),
589 array(
590 'action' => 'edit',
591 'externaledit' => 'true',
592 'mode' => 'file'
594 array( 'known', 'noclasses' )
596 $wgOut->addHTML(
597 '<li id="mw-imagepage-edit-external">' . $elink . ' <small>' .
598 wfMsgExt( 'edit-externally-help', array( 'parseinline' ) ) .
599 "</small></li>\n"
603 $wgOut->addHTML( "</ul>\n" );
606 protected function closeShowImage() { } # For overloading
609 * If the page we've just displayed is in the "Image" namespace,
610 * we follow it with an upload history of the image and its usage.
612 protected function imageHistory() {
613 global $wgOut;
615 $this->loadFile();
616 $pager = new ImageHistoryPseudoPager( $this );
617 $wgOut->addHTML( $pager->getBody() );
618 $wgOut->preventClickjacking( $pager->getPreventClickjacking() );
620 $this->mPage->getFile()->resetHistory(); // free db resources
622 # Exist check because we don't want to show this on pages where an image
623 # doesn't exist along with the noimage message, that would suck. -ævar
624 if ( $this->mPage->getFile()->exists() ) {
625 $this->uploadLinksBox();
630 * @param $target
631 * @param $limit
632 * @return ResultWrapper
634 protected function queryImageLinks( $target, $limit ) {
635 $dbr = wfGetDB( DB_SLAVE );
637 return $dbr->select(
638 array( 'imagelinks', 'page' ),
639 array( 'page_namespace', 'page_title', 'page_is_redirect', 'il_to' ),
640 array( 'il_to' => $target, 'il_from = page_id' ),
641 __METHOD__,
642 array( 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', )
646 protected function imageLinks() {
647 global $wgOut, $wgLang;
649 $limit = 100;
651 $res = $this->queryImageLinks( $this->getTitle()->getDbKey(), $limit + 1);
652 $rows = array();
653 $redirects = array();
654 foreach ( $res as $row ) {
655 if ( $row->page_is_redirect ) {
656 $redirects[$row->page_title] = array();
658 $rows[] = $row;
660 $count = count( $rows );
662 $hasMore = $count > $limit;
663 if ( !$hasMore && count( $redirects ) ) {
664 $res = $this->queryImageLinks( array_keys( $redirects ),
665 $limit - count( $rows ) + 1 );
666 foreach ( $res as $row ) {
667 $redirects[$row->il_to][] = $row;
668 $count++;
670 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
673 if ( $count == 0 ) {
674 $wgOut->wrapWikiMsg(
675 Html::rawElement( 'div',
676 array( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ),
677 'nolinkstoimage'
679 return;
682 $wgOut->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
683 if ( !$hasMore ) {
684 $wgOut->addWikiMsg( 'linkstoimage', $count );
685 } else {
686 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
687 $wgOut->addWikiMsg( 'linkstoimage-more',
688 $wgLang->formatNum( $limit ),
689 $this->getTitle()->getPrefixedDBkey()
693 $wgOut->addHTML(
694 Html::openElement( 'ul',
695 array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n"
697 $count = 0;
699 // Sort the list by namespace:title
700 usort( $rows, array( $this, 'compare' ) );
702 // Create links for every element
703 $currentCount = 0;
704 foreach( $rows as $element ) {
705 $currentCount++;
706 if ( $currentCount > $limit ) {
707 break;
710 $link = Linker::linkKnown( Title::makeTitle( $element->page_namespace, $element->page_title ) );
711 if ( !isset( $redirects[$element->page_title] ) ) {
712 $liContents = $link;
713 } else {
714 $ul = "<ul class='mw-imagepage-redirectstofile'>\n";
715 foreach ( $redirects[$element->page_title] as $row ) {
716 $currentCount++;
717 if ( $currentCount > $limit ) {
718 break;
721 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
722 $ul .= Html::rawElement(
723 'li',
724 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
725 $link2
726 ) . "\n";
728 $ul .= '</ul>';
729 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams(
730 $link, $ul )->parse();
732 $wgOut->addHTML( Html::rawElement(
733 'li',
734 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
735 $liContents
736 ) . "\n"
740 $wgOut->addHTML( Html::closeElement( 'ul' ) . "\n" );
741 $res->free();
743 // Add a links to [[Special:Whatlinkshere]]
744 if ( $count > $limit ) {
745 $wgOut->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
747 $wgOut->addHTML( Html::closeElement( 'div' ) . "\n" );
750 protected function imageDupes() {
751 global $wgOut, $wgLang;
753 $this->loadFile();
755 $dupes = $this->mPage->getDuplicates();
756 if ( count( $dupes ) == 0 ) {
757 return;
760 $wgOut->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
761 $wgOut->addWikiMsg( 'duplicatesoffile',
762 $wgLang->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
764 $wgOut->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
767 * @var $file File
769 foreach ( $dupes as $file ) {
770 $fromSrc = '';
771 if ( $file->isLocal() ) {
772 $link = Linker::link(
773 $file->getTitle(),
774 null,
775 array(),
776 array(),
777 array( 'known', 'noclasses' )
779 } else {
780 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
781 $file->getTitle()->getPrefixedText() );
782 $fromSrc = wfMsg( 'shared-repo-from', $file->getRepo()->getDisplayName() );
784 $wgOut->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
786 $wgOut->addHTML( "</ul></div>\n" );
790 * Delete the file, or an earlier version of it
792 public function delete() {
793 $file = $this->mPage->getFile();
794 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
795 // Standard article deletion
796 parent::delete();
797 return;
800 $deleter = new FileDeleteForm( $file );
801 $deleter->execute();
805 * Display an error with a wikitext description
807 * @param $description String
809 function showError( $description ) {
810 global $wgOut;
811 $wgOut->setPageTitle( wfMessage( 'internalerror' ) );
812 $wgOut->setRobotPolicy( 'noindex,nofollow' );
813 $wgOut->setArticleRelated( false );
814 $wgOut->enableClientCache( false );
815 $wgOut->addWikiText( $description );
819 * Callback for usort() to do link sorts by (namespace, title)
820 * Function copied from Title::compare()
822 * @param $a object page to compare with
823 * @param $b object page to compare with
824 * @return Integer: result of string comparison, or namespace comparison
826 protected function compare( $a, $b ) {
827 if ( $a->page_namespace == $b->page_namespace ) {
828 return strcmp( $a->page_title, $b->page_title );
829 } else {
830 return $a->page_namespace - $b->page_namespace;
836 * Builds the image revision log shown on image pages
838 * @ingroup Media
840 class ImageHistoryList {
843 * @var Title
845 protected $title;
848 * @var File
850 protected $img;
853 * @var ImagePage
855 protected $imagePage;
858 * @var File
860 protected $current;
862 protected $repo, $showThumb;
863 protected $preventClickjacking = false;
866 * @param ImagePage $imagePage
868 public function __construct( $imagePage ) {
869 global $wgShowArchiveThumbnails;
870 $this->current = $imagePage->getFile();
871 $this->img = $imagePage->getDisplayedFile();
872 $this->title = $imagePage->getTitle();
873 $this->imagePage = $imagePage;
874 $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
878 * @return ImagePage
880 public function getImagePage() {
881 return $this->imagePage;
885 * @return File
887 public function getFile() {
888 return $this->img;
892 * @param $navLinks string
893 * @return string
895 public function beginImageHistoryList( $navLinks = '' ) {
896 global $wgOut, $wgUser;
897 return Xml::element( 'h2', array( 'id' => 'filehistory' ), wfMsg( 'filehist' ) ) . "\n"
898 . "<div id=\"mw-imagepage-section-filehistory\">\n"
899 . $wgOut->parse( wfMsgNoTrans( 'filehist-help' ) )
900 . $navLinks . "\n"
901 . Xml::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
902 . '<tr><td></td>'
903 . ( $this->current->isLocal() && ( $wgUser->isAllowedAny( 'delete', 'deletedhistory' ) ) ? '<td></td>' : '' )
904 . '<th>' . wfMsgHtml( 'filehist-datetime' ) . '</th>'
905 . ( $this->showThumb ? '<th>' . wfMsgHtml( 'filehist-thumb' ) . '</th>' : '' )
906 . '<th>' . wfMsgHtml( 'filehist-dimensions' ) . '</th>'
907 . '<th>' . wfMsgHtml( 'filehist-user' ) . '</th>'
908 . '<th>' . wfMsgHtml( 'filehist-comment' ) . '</th>'
909 . "</tr>\n";
913 * @param $navLinks string
914 * @return string
916 public function endImageHistoryList( $navLinks = '' ) {
917 return "</table>\n$navLinks\n</div>\n";
921 * @param $iscur
922 * @param $file File
923 * @return string
925 public function imageHistoryLine( $iscur, $file ) {
926 global $wgUser, $wgLang, $wgContLang;
928 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
929 $img = $iscur ? $file->getName() : $file->getArchiveName();
930 $user = $file->getUser( 'id' );
931 $usertext = $file->getUser( 'text' );
932 $description = $file->getDescription();
934 $local = $this->current->isLocal();
935 $row = $selected = '';
937 // Deletion link
938 if ( $local && ( $wgUser->isAllowedAny( 'delete', 'deletedhistory' ) ) ) {
939 $row .= '<td>';
940 # Link to remove from history
941 if ( $wgUser->isAllowed( 'delete' ) ) {
942 $q = array( 'action' => 'delete' );
943 if ( !$iscur ) {
944 $q['oldimage'] = $img;
946 $row .= Linker::link(
947 $this->title,
948 wfMsgHtml( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' ),
949 array(), $q, array( 'known' )
952 # Link to hide content. Don't show useless link to people who cannot hide revisions.
953 $canHide = $wgUser->isAllowed( 'deleterevision' );
954 if ( $canHide || ( $wgUser->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
955 if ( $wgUser->isAllowed( 'delete' ) ) {
956 $row .= '<br />';
958 // If file is top revision or locked from this user, don't link
959 if ( $iscur || !$file->userCan( File::DELETED_RESTRICTED ) ) {
960 $del = Linker::revDeleteLinkDisabled( $canHide );
961 } else {
962 list( $ts, $name ) = explode( '!', $img, 2 );
963 $query = array(
964 'type' => 'oldimage',
965 'target' => $this->title->getPrefixedText(),
966 'ids' => $ts,
968 $del = Linker::revDeleteLink( $query,
969 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
971 $row .= $del;
973 $row .= '</td>';
976 // Reversion link/current indicator
977 $row .= '<td>';
978 if ( $iscur ) {
979 $row .= wfMsgHtml( 'filehist-current' );
980 } elseif ( $local && $wgUser->isLoggedIn() && $this->title->userCan( 'edit' ) ) {
981 if ( $file->isDeleted( File::DELETED_FILE ) ) {
982 $row .= wfMsgHtml( 'filehist-revert' );
983 } else {
984 $row .= Linker::link(
985 $this->title,
986 wfMsgHtml( 'filehist-revert' ),
987 array(),
988 array(
989 'action' => 'revert',
990 'oldimage' => $img,
991 'wpEditToken' => $wgUser->getEditToken( $img )
993 array( 'known', 'noclasses' )
997 $row .= '</td>';
999 // Date/time and image link
1000 if ( $file->getTimestamp() === $this->img->getTimestamp() ) {
1001 $selected = "class='filehistory-selected'";
1003 $row .= "<td $selected style='white-space: nowrap;'>";
1004 if ( !$file->userCan( File::DELETED_FILE ) ) {
1005 # Don't link to unviewable files
1006 $row .= '<span class="history-deleted">' . $wgLang->timeanddate( $timestamp, true ) . '</span>';
1007 } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
1008 if ( $local ) {
1009 $this->preventClickjacking();
1010 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
1011 # Make a link to review the image
1012 $url = Linker::link(
1013 $revdel,
1014 $wgLang->timeanddate( $timestamp, true ),
1015 array(),
1016 array(
1017 'target' => $this->title->getPrefixedText(),
1018 'file' => $img,
1019 'token' => $wgUser->getEditToken( $img )
1021 array( 'known', 'noclasses' )
1023 } else {
1024 $url = $wgLang->timeanddate( $timestamp, true );
1026 $row .= '<span class="history-deleted">' . $url . '</span>';
1027 } else {
1028 $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
1029 $row .= Xml::element( 'a', array( 'href' => $url ), $wgLang->timeanddate( $timestamp, true ) );
1031 $row .= "</td>";
1033 // Thumbnail
1034 if ( $this->showThumb ) {
1035 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1038 // Image dimensions + size
1039 $row .= '<td>';
1040 $row .= htmlspecialchars( $file->getDimensionsString() );
1041 $row .= ' <span style="white-space: nowrap;">(' . Linker::formatSize( $file->getSize() ) . ')</span>';
1042 $row .= '</td>';
1044 // Uploading user
1045 $row .= '<td>';
1046 // Hide deleted usernames
1047 if ( $file->isDeleted( File::DELETED_USER ) ) {
1048 $row .= '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-user' ) . '</span>';
1049 } else {
1050 if ( $local ) {
1051 $row .= Linker::userLink( $user, $usertext ) . ' <span style="white-space: nowrap;">' .
1052 Linker::userToolLinks( $user, $usertext ) . '</span>';
1053 } else {
1054 $row .= htmlspecialchars( $usertext );
1057 $row .= '</td>';
1059 // Don't show deleted descriptions
1060 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1061 $row .= '<td><span class="history-deleted">' . wfMsgHtml( 'rev-deleted-comment' ) . '</span></td>';
1062 } else {
1063 $row .= '<td dir="' . $wgContLang->getDir() . '">' . Linker::formatComment( $description, $this->title ) . '</td>';
1066 $rowClass = null;
1067 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1068 $classAttr = $rowClass ? " class='$rowClass'" : '';
1070 return "<tr{$classAttr}>{$row}</tr>\n";
1074 * @param $file File
1075 * @return string
1077 protected function getThumbForLine( $file ) {
1078 global $wgLang;
1080 if ( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE ) && !$file->isDeleted( File::DELETED_FILE ) ) {
1081 $params = array(
1082 'width' => '120',
1083 'height' => '120',
1085 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1087 $thumbnail = $file->transform( $params );
1088 $options = array(
1089 'alt' => wfMsg( 'filehist-thumbtext',
1090 $wgLang->timeanddate( $timestamp, true ),
1091 $wgLang->date( $timestamp, true ),
1092 $wgLang->time( $timestamp, true ) ),
1093 'file-link' => true,
1096 if ( !$thumbnail ) {
1097 return wfMsgHtml( 'filehist-nothumb' );
1100 return $thumbnail->toHtml( $options );
1101 } else {
1102 return wfMsgHtml( 'filehist-nothumb' );
1107 * @param $enable bool
1109 protected function preventClickjacking( $enable = true ) {
1110 $this->preventClickjacking = $enable;
1114 * @return bool
1116 public function getPreventClickjacking() {
1117 return $this->preventClickjacking;
1121 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1122 protected $preventClickjacking = false;
1125 * @var File
1127 protected $mImg;
1130 * @var Title
1132 protected $mTitle;
1135 * @param ImagePage $imagePage
1137 function __construct( $imagePage ) {
1138 parent::__construct();
1139 $this->mImagePage = $imagePage;
1140 $this->mTitle = clone ( $imagePage->getTitle() );
1141 $this->mTitle->setFragment( '#filehistory' );
1142 $this->mImg = null;
1143 $this->mHist = array();
1144 $this->mRange = array( 0, 0 ); // display range
1148 * @return Title
1150 function getTitle() {
1151 return $this->mTitle;
1154 function getQueryInfo() {
1155 return false;
1159 * @return string
1161 function getIndexField() {
1162 return '';
1166 * @return string
1168 function formatRow( $row ) {
1169 return '';
1173 * @return string
1175 function getBody() {
1176 $s = '';
1177 $this->doQuery();
1178 if ( count( $this->mHist ) ) {
1179 $list = new ImageHistoryList( $this->mImagePage );
1180 # Generate prev/next links
1181 $navLink = $this->getNavigationBar();
1182 $s = $list->beginImageHistoryList( $navLink );
1183 // Skip rows there just for paging links
1184 for ( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1185 $file = $this->mHist[$i];
1186 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1188 $s .= $list->endImageHistoryList( $navLink );
1190 if ( $list->getPreventClickjacking() ) {
1191 $this->preventClickjacking();
1194 return $s;
1197 function doQuery() {
1198 if ( $this->mQueryDone ) {
1199 return;
1201 $this->mImg = $this->mImagePage->getFile(); // ensure loading
1202 if ( !$this->mImg->exists() ) {
1203 return;
1205 $queryLimit = $this->mLimit + 1; // limit plus extra row
1206 if ( $this->mIsBackwards ) {
1207 // Fetch the file history
1208 $this->mHist = $this->mImg->getHistory( $queryLimit, null, $this->mOffset, false );
1209 // The current rev may not meet the offset/limit
1210 $numRows = count( $this->mHist );
1211 if ( $numRows <= $this->mLimit && $this->mImg->getTimestamp() > $this->mOffset ) {
1212 $this->mHist = array_merge( array( $this->mImg ), $this->mHist );
1214 } else {
1215 // The current rev may not meet the offset
1216 if ( !$this->mOffset || $this->mImg->getTimestamp() < $this->mOffset ) {
1217 $this->mHist[] = $this->mImg;
1219 // Old image versions (fetch extra row for nav links)
1220 $oiLimit = count( $this->mHist ) ? $this->mLimit : $this->mLimit + 1;
1221 // Fetch the file history
1222 $this->mHist = array_merge( $this->mHist,
1223 $this->mImg->getHistory( $oiLimit, $this->mOffset, null, false ) );
1225 $numRows = count( $this->mHist ); // Total number of query results
1226 if ( $numRows ) {
1227 # Index value of top item in the list
1228 $firstIndex = $this->mIsBackwards ?
1229 $this->mHist[$numRows - 1]->getTimestamp() : $this->mHist[0]->getTimestamp();
1230 # Discard the extra result row if there is one
1231 if ( $numRows > $this->mLimit && $numRows > 1 ) {
1232 if ( $this->mIsBackwards ) {
1233 # Index value of item past the index
1234 $this->mPastTheEndIndex = $this->mHist[0]->getTimestamp();
1235 # Index value of bottom item in the list
1236 $lastIndex = $this->mHist[1]->getTimestamp();
1237 # Display range
1238 $this->mRange = array( 1, $numRows - 1 );
1239 } else {
1240 # Index value of item past the index
1241 $this->mPastTheEndIndex = $this->mHist[$numRows - 1]->getTimestamp();
1242 # Index value of bottom item in the list
1243 $lastIndex = $this->mHist[$numRows - 2]->getTimestamp();
1244 # Display range
1245 $this->mRange = array( 0, $numRows - 2 );
1247 } else {
1248 # Setting indexes to an empty string means that they will be
1249 # omitted if they would otherwise appear in URLs. It just so
1250 # happens that this is the right thing to do in the standard
1251 # UI, in all the relevant cases.
1252 $this->mPastTheEndIndex = '';
1253 # Index value of bottom item in the list
1254 $lastIndex = $this->mIsBackwards ?
1255 $this->mHist[0]->getTimestamp() : $this->mHist[$numRows - 1]->getTimestamp();
1256 # Display range
1257 $this->mRange = array( 0, $numRows - 1 );
1259 } else {
1260 $firstIndex = '';
1261 $lastIndex = '';
1262 $this->mPastTheEndIndex = '';
1264 if ( $this->mIsBackwards ) {
1265 $this->mIsFirst = ( $numRows < $queryLimit );
1266 $this->mIsLast = ( $this->mOffset == '' );
1267 $this->mLastShown = $firstIndex;
1268 $this->mFirstShown = $lastIndex;
1269 } else {
1270 $this->mIsFirst = ( $this->mOffset == '' );
1271 $this->mIsLast = ( $numRows < $queryLimit );
1272 $this->mLastShown = $lastIndex;
1273 $this->mFirstShown = $firstIndex;
1275 $this->mQueryDone = true;
1279 * @param $enable bool
1281 protected function preventClickjacking( $enable = true ) {
1282 $this->preventClickjacking = $enable;
1286 * @return bool
1288 public function getPreventClickjacking() {
1289 return $this->preventClickjacking;