Tweak doc comment per bug 28340
[mediawiki.git] / includes / ImagePage.php
blobba544b9f08853a18715c23e37cbdb947ca2d54a7
1 <?php
3 /**
4 * Special handling for image description pages
6 * @ingroup Media
7 */
8 class ImagePage extends Article {
10 /**
11 * @var File
13 /* private */ var $img;
14 /**
15 * @var File
17 /* private */ var $displayImg;
18 /* private */ var $repo;
19 /* private */ var $fileLoaded;
21 var $mExtraDescription = false;
22 var $dupes;
24 function __construct( $title ) {
25 parent::__construct( $title );
26 $this->dupes = null;
27 $this->repo = null;
30 /**
31 * @param $file File:
32 * @return void
34 public function setFile( $file ) {
35 $this->displayImg = $file;
36 $this->img = $file;
37 $this->fileLoaded = true;
40 protected function loadFile() {
41 if ( $this->fileLoaded ) {
42 return true;
44 $this->fileLoaded = true;
46 $this->displayImg = $this->img = false;
47 wfRunHooks( 'ImagePageFindFile', array( $this, &$this->img, &$this->displayImg ) );
48 if ( !$this->img ) {
49 $this->img = wfFindFile( $this->mTitle );
50 if ( !$this->img ) {
51 $this->img = wfLocalFile( $this->mTitle );
54 if ( !$this->displayImg ) {
55 $this->displayImg = $this->img;
57 $this->repo = $this->img->getRepo();
60 /**
61 * Handler for action=render
62 * Include body text only; none of the image extras
64 public function render() {
65 global $wgOut;
66 $wgOut->setArticleBodyOnly( true );
67 parent::view();
70 public function view() {
71 global $wgOut, $wgShowEXIF, $wgRequest, $wgUser;
73 $diff = $wgRequest->getVal( 'diff' );
74 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
76 if ( $this->mTitle->getNamespace() != NS_FILE || ( isset( $diff ) && $diffOnly ) ) {
77 return parent::view();
80 $this->loadFile();
82 if ( $this->mTitle->getNamespace() == NS_FILE && $this->img->getRedirected() ) {
83 if ( $this->mTitle->getDBkey() == $this->img->getName() || isset( $diff ) ) {
84 // mTitle is the same as the redirect target so ask Article
85 // to perform the redirect for us.
86 $wgRequest->setVal( 'diffonly', 'true' );
87 return parent::view();
88 } else {
89 // mTitle is not the same as the redirect target so it is
90 // probably the redirect page itself. Fake the redirect symbol
91 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
92 $wgOut->addHTML( $this->viewRedirect( Title::makeTitle( NS_FILE, $this->img->getName() ),
93 /* $appendSubtitle */ true, /* $forceKnown */ true ) );
94 $this->viewUpdates();
95 return;
99 $this->showRedirectedFromHeader();
101 if ( $wgShowEXIF && $this->displayImg->exists() ) {
102 // FIXME: bad interface, see note on MediaHandler::formatMetadata().
103 $formattedMetadata = $this->displayImg->formatMetadata();
104 $showmeta = $formattedMetadata !== false;
105 } else {
106 $showmeta = false;
109 if ( !$diff && $this->displayImg->exists() )
110 $wgOut->addHTML( $this->showTOC( $showmeta ) );
112 if ( !$diff )
113 $this->openShowImage();
115 # No need to display noarticletext, we use our own message, output in openShowImage()
116 if ( $this->getID() ) {
117 parent::view();
118 } else {
119 # Just need to set the right headers
120 $wgOut->setArticleFlag( true );
121 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
122 $this->viewUpdates();
125 # Show shared description, if needed
126 if ( $this->mExtraDescription ) {
127 $fol = wfMessage( 'shareddescriptionfollows' );
128 if ( !$fol->isDisabled() ) {
129 $wgOut->addWikiText( $fol->plain() );
131 $wgOut->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
134 $this->closeShowImage();
135 $this->imageHistory();
136 // TODO: Cleanup the following
138 $wgOut->addHTML( Xml::element( 'h2',
139 array( 'id' => 'filelinks' ),
140 wfMsg( 'imagelinks' ) ) . "\n" );
141 $this->imageDupes();
142 # TODO! FIXME! For some freaky reason, we can't redirect to foreign images.
143 # Yet we return metadata about the target. Definitely an issue in the FileRepo
144 $this->imageRedirects();
145 $this->imageLinks();
147 # Allow extensions to add something after the image links
148 $html = '';
149 wfRunHooks( 'ImagePageAfterImageLinks', array( $this, &$html ) );
150 if ( $html )
151 $wgOut->addHTML( $html );
153 if ( $showmeta ) {
154 $wgOut->addHTML( Xml::element( 'h2', array( 'id' => 'metadata' ), wfMsg( 'metadata' ) ) . "\n" );
155 $wgOut->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
156 $wgOut->addModules( array( 'mediawiki.legacy.metadata' ) );
159 $css = $this->repo->getDescriptionStylesheetUrl();
160 if ( $css ) {
161 $wgOut->addStyle( $css );
165 public function getRedirectTarget() {
166 $this->loadFile();
167 if ( $this->img->isLocal() ) {
168 return parent::getRedirectTarget();
170 // Foreign image page
171 $from = $this->img->getRedirected();
172 $to = $this->img->getName();
173 if ( $from == $to ) {
174 return null;
176 return $this->mRedirectTarget = Title::makeTitle( NS_FILE, $to );
179 public function followRedirect() {
180 $this->loadFile();
181 if ( $this->img->isLocal() ) {
182 return parent::followRedirect();
184 $from = $this->img->getRedirected();
185 $to = $this->img->getName();
186 if ( $from == $to ) {
187 return false;
189 return Title::makeTitle( NS_FILE, $to );
192 public function isRedirect( $text = false ) {
193 $this->loadFile();
194 if ( $this->img->isLocal() )
195 return parent::isRedirect( $text );
197 return (bool)$this->img->getRedirected();
200 public function isLocal() {
201 $this->loadFile();
202 return $this->img->isLocal();
205 public function getFile() {
206 $this->loadFile();
207 return $this->img;
210 public function getDisplayedFile() {
211 $this->loadFile();
212 return $this->displayImg;
215 public function getDuplicates() {
216 $this->loadFile();
217 if ( !is_null( $this->dupes ) ) {
218 return $this->dupes;
220 if ( !( $hash = $this->img->getSha1() ) ) {
221 return $this->dupes = array();
223 $dupes = RepoGroup::singleton()->findBySha1( $hash );
224 // Remove duplicates with self and non matching file sizes
225 $self = $this->img->getRepoName() . ':' . $this->img->getName();
226 $size = $this->img->getSize();
227 foreach ( $dupes as $index => $file ) {
228 $key = $file->getRepoName() . ':' . $file->getName();
229 if ( $key == $self )
230 unset( $dupes[$index] );
231 if ( $file->getSize() != $size )
232 unset( $dupes[$index] );
234 return $this->dupes = $dupes;
239 * Create the TOC
241 * @param $metadata Boolean: whether or not to show the metadata link
242 * @return String
244 protected function showTOC( $metadata ) {
245 $r = array(
246 '<li><a href="#file">' . wfMsgHtml( 'file-anchor-link' ) . '</a></li>',
247 '<li><a href="#filehistory">' . wfMsgHtml( 'filehist' ) . '</a></li>',
248 '<li><a href="#filelinks">' . wfMsgHtml( 'imagelinks' ) . '</a></li>',
250 if ( $metadata ) {
251 $r[] = '<li><a href="#metadata">' . wfMsgHtml( 'metadata' ) . '</a></li>';
254 wfRunHooks( 'ImagePageShowTOC', array( $this, &$r ) );
256 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
260 * Make a table with metadata to be shown in the output page.
262 * FIXME: bad interface, see note on MediaHandler::formatMetadata().
264 * @param $metadata Array: the array containing the EXIF data
265 * @return String
267 protected function makeMetadataTable( $metadata ) {
268 $r = "<div class=\"mw-imagepage-section-metadata\">";
269 $r .= wfMsgNoTrans( 'metadata-help' );
270 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
271 foreach ( $metadata as $type => $stuff ) {
272 foreach ( $stuff as $v ) {
273 # FIXME, why is this using escapeId for a class?!
274 $class = Sanitizer::escapeId( $v['id'] );
275 if ( $type == 'collapsed' ) {
276 $class .= ' collapsable';
278 $r .= "<tr class=\"$class\">\n";
279 $r .= "<th>{$v['name']}</th>\n";
280 $r .= "<td>{$v['value']}</td>\n</tr>";
283 $r .= "</table>\n</div>\n";
284 return $r;
288 * Overloading Article's getContent method.
290 * Omit noarticletext if sharedupload; text will be fetched from the
291 * shared upload server if possible.
293 public function getContent() {
294 $this->loadFile();
295 if ( $this->img && !$this->img->isLocal() && 0 == $this->getID() ) {
296 return '';
298 return parent::getContent();
301 protected function openShowImage() {
302 global $wgOut, $wgUser, $wgImageLimits, $wgRequest,
303 $wgLang, $wgContLang, $wgEnableUploads;
305 $this->loadFile();
307 $sizeSel = intval( $wgUser->getOption( 'imagesize' ) );
308 if ( !isset( $wgImageLimits[$sizeSel] ) ) {
309 $sizeSel = User::getDefaultOption( 'imagesize' );
311 // The user offset might still be incorrect, specially if
312 // $wgImageLimits got changed (see bug #8858).
313 if ( !isset( $wgImageLimits[$sizeSel] ) ) {
314 // Default to the first offset in $wgImageLimits
315 $sizeSel = 0;
318 $max = $wgImageLimits[$sizeSel];
319 $maxWidth = $max[0];
320 $maxHeight = $max[1];
321 $sk = $wgUser->getSkin();
322 $dirmark = $wgContLang->getDirMark();
324 if ( $this->displayImg->exists() ) {
325 # image
326 $page = $wgRequest->getIntOrNull( 'page' );
327 if ( is_null( $page ) ) {
328 $params = array();
329 $page = 1;
330 } else {
331 $params = array( 'page' => $page );
333 $width_orig = $this->displayImg->getWidth( $page );
334 $width = $width_orig;
335 $height_orig = $this->displayImg->getHeight( $page );
336 $height = $height_orig;
338 $longDesc = wfMsg( 'parentheses', $this->displayImg->getLongDesc() );
340 wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this, &$wgOut ) );
342 if ( $this->displayImg->allowInlineDisplay() ) {
343 # image
345 # "Download high res version" link below the image
346 # $msgsize = wfMsgHtml('file-info-size', $width_orig, $height_orig, $sk->formatSize( $this->displayImg->getSize() ), $mime );
347 # We'll show a thumbnail of this image
348 if ( $width > $maxWidth || $height > $maxHeight ) {
349 # Calculate the thumbnail size.
350 # First case, the limiting factor is the width, not the height.
351 if ( $width / $height >= $maxWidth / $maxHeight ) {
352 $height = round( $height * $maxWidth / $width );
353 $width = $maxWidth;
354 # Note that $height <= $maxHeight now.
355 } else {
356 $newwidth = floor( $width * $maxHeight / $height );
357 $height = round( $height * $newwidth / $width );
358 $width = $newwidth;
359 # Note that $height <= $maxHeight now, but might not be identical
360 # because of rounding.
362 $msgbig = wfMsgHtml( 'show-big-image' );
363 $otherSizes = array();
364 foreach ( $wgImageLimits as $size ) {
365 if ( $size[0] < $width_orig && $size[1] < $height_orig &&
366 $size[0] != $width && $size[1] != $height ) {
367 $otherSizes[] = $this->makeSizeLink( $params, $size[0], $size[1] );
370 $msgsmall = wfMessage( 'show-big-image-preview' )->
371 rawParams( $this->makeSizeLink( $params, $width, $height ) )->
372 parse() . ' ' .
373 wfMessage( 'show-big-image-other' )->
374 rawParams( $wgLang->pipeList( $otherSizes ) )->parse();
375 } else {
376 # Image is small enough to show full size on image page
377 $msgsmall = wfMsgExt( 'file-nohires', array( 'parseinline' ) );
380 $params['width'] = $width;
381 $params['height'] = $height;
382 $thumbnail = $this->displayImg->transform( $params );
384 $showLink = true;
385 $anchorclose = "<br />" . $msgsmall;
387 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
388 if ( $isMulti ) {
389 $wgOut->addHTML( '<table class="multipageimage"><tr><td>' );
392 if ( $thumbnail ) {
393 $options = array(
394 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
395 'file-link' => true,
397 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
398 $thumbnail->toHtml( $options ) .
399 $anchorclose . "</div>\n" );
402 if ( $isMulti ) {
403 $count = $this->displayImg->pageCount();
405 if ( $page > 1 ) {
406 $label = $wgOut->parse( wfMsg( 'imgmultipageprev' ), false );
407 $link = $sk->link(
408 $this->mTitle,
409 $label,
410 array(),
411 array( 'page' => $page - 1 ),
412 array( 'known', 'noclasses' )
414 $thumb1 = $sk->makeThumbLinkObj( $this->mTitle, $this->displayImg, $link, $label, 'none',
415 array( 'page' => $page - 1 ) );
416 } else {
417 $thumb1 = '';
420 if ( $page < $count ) {
421 $label = wfMsg( 'imgmultipagenext' );
422 $link = $sk->link(
423 $this->mTitle,
424 $label,
425 array(),
426 array( 'page' => $page + 1 ),
427 array( 'known', 'noclasses' )
429 $thumb2 = $sk->makeThumbLinkObj( $this->mTitle, $this->displayImg, $link, $label, 'none',
430 array( 'page' => $page + 1 ) );
431 } else {
432 $thumb2 = '';
435 global $wgScript;
437 $formParams = array(
438 'name' => 'pageselector',
439 'action' => $wgScript,
440 'onchange' => 'document.pageselector.submit();',
443 for ( $i = 1; $i <= $count; $i++ ) {
444 $options[] = Xml::option( $wgLang->formatNum( $i ), $i, $i == $page );
446 $select = Xml::tags( 'select',
447 array( 'id' => 'pageselector', 'name' => 'page' ),
448 implode( "\n", $options ) );
450 $wgOut->addHTML(
451 '</td><td><div class="multipageimagenavbox">' .
452 Xml::openElement( 'form', $formParams ) .
453 Html::hidden( 'title', $this->getTitle()->getPrefixedDbKey() ) .
454 wfMsgExt( 'imgmultigoto', array( 'parseinline', 'replaceafter' ), $select ) .
455 Xml::submitButton( wfMsg( 'imgmultigo' ) ) .
456 Xml::closeElement( 'form' ) .
457 "<hr />$thumb1\n$thumb2<br clear=\"all\" /></div></td></tr></table>"
460 } else {
461 # if direct link is allowed but it's not a renderable image, show an icon.
462 if ( $this->displayImg->isSafeFile() ) {
463 $icon = $this->displayImg->iconThumb();
465 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
466 $icon->toHtml( array( 'file-link' => true ) ) .
467 "</div>\n" );
470 $showLink = true;
474 if ( $showLink ) {
475 $filename = wfEscapeWikiText( $this->displayImg->getName() );
476 $linktext = $filename;
477 if ( isset( $msgbig ) ) {
478 $linktext = wfEscapeWikiText( $msgbig );
480 $medialink = "[[Media:$filename|$linktext]]";
482 if ( !$this->displayImg->isSafeFile() ) {
483 $warning = wfMsgNoTrans( 'mediawarning' );
484 $wgOut->addWikiText( <<<EOT
485 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span>$dirmark <span class="fileInfo">$longDesc</span></div>
486 <div class="mediaWarning">$warning</div>
489 } else {
490 $wgOut->addWikiText( <<<EOT
491 <div class="fullMedia">{$medialink}{$dirmark} <span class="fileInfo">$longDesc</span>
492 </div>
498 if ( !$this->displayImg->isLocal() ) {
499 $this->printSharedImageText();
501 } else {
502 # Image does not exist
503 if ( $wgEnableUploads && $wgUser->isAllowed( 'upload' ) ) {
504 // Only show an upload link if the user can upload
505 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
506 $nofile = array(
507 'filepage-nofile-link',
508 $uploadTitle->getFullUrl( array( 'wpDestFile' => $this->img->getName() ) )
511 else
513 $nofile = 'filepage-nofile';
515 // Note, if there is an image description page, but
516 // no image, then this setRobotPolicy is overriden
517 // by Article::View().
518 $wgOut->setRobotPolicy( 'noindex,nofollow' );
519 $wgOut->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
520 if ( !$this->getID() ) {
521 // If there is no image, no shared image, and no description page,
522 // output a 404, to be consistent with articles.
523 $wgRequest->response()->header( "HTTP/1.1 404 Not Found" );
529 * Creates an thumbnail of specified size and returns an HTML link to it
530 * @param array $params Scaler parameters
531 * @param int $width
532 * @param int $height
534 private function makeSizeLink( $params, $width, $height ) {
535 global $wgLang;
537 $params['width'] = $width;
538 $params['height'] = $height;
539 $thumbnail = $this->displayImg->transform( $params );
540 if ( $thumbnail && !$thumbnail->isError() ) {
541 return Html::rawElement( 'a', array(
542 'href' => $thumbnail->getUrl(),
543 'class' => 'mw-thumbnail-link'
544 ), wfMessage( 'show-big-image-size' )->numParams(
545 $thumbnail->getWidth(), $thumbnail->getHeight()
546 )->parse() );
547 } else {
548 return '';
553 * Show a notice that the file is from a shared repository
555 protected function printSharedImageText() {
556 global $wgOut;
558 $this->loadFile();
560 $descUrl = $this->img->getDescriptionUrl();
561 $descText = $this->img->getDescriptionText();
563 /* Add canonical to head if there is no local page for this shared file */
564 if( $descUrl && $this->getID() == 0 ) {
565 $wgOut->addLink( array( 'rel' => 'canonical', 'href' => $descUrl ) );
568 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
569 $repo = $this->img->getRepo()->getDisplayName();
571 if ( $descUrl && $descText && wfMsgNoTrans( 'sharedupload-desc-here' ) !== '-' ) {
572 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
573 } elseif ( $descUrl && wfMsgNoTrans( 'sharedupload-desc-there' ) !== '-' ) {
574 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
575 } else {
576 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
579 if ( $descText ) {
580 $this->mExtraDescription = $descText;
584 public function getUploadUrl() {
585 $this->loadFile();
586 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
587 return $uploadTitle->getFullUrl( array(
588 'wpDestFile' => $this->img->getName(),
589 'wpForReUpload' => 1
590 ) );
594 * Print out the various links at the bottom of the image page, e.g. reupload,
595 * external editing (and instructions link) etc.
597 protected function uploadLinksBox() {
598 global $wgUser, $wgOut, $wgEnableUploads, $wgUseExternalEditor;
600 if ( !$wgEnableUploads ) {
601 return;
604 $this->loadFile();
605 if ( !$this->img->isLocal() )
606 return;
608 $sk = $wgUser->getSkin();
610 $wgOut->addHTML( "<br /><ul>\n" );
612 # "Upload a new version of this file" link
613 if ( UploadBase::userCanReUpload( $wgUser, $this->img->name ) ) {
614 $ulink = $sk->makeExternalLink( $this->getUploadUrl(), wfMsg( 'uploadnewversion-linktext' ) );
615 $wgOut->addHTML( "<li id=\"mw-imagepage-reupload-link\"><div class=\"plainlinks\">{$ulink}</div></li>\n" );
618 # External editing link
619 if ( $wgUseExternalEditor ) {
620 $elink = $sk->link(
621 $this->mTitle,
622 wfMsgHtml( 'edit-externally' ),
623 array(),
624 array(
625 'action' => 'edit',
626 'externaledit' => 'true',
627 'mode' => 'file'
629 array( 'known', 'noclasses' )
631 $wgOut->addHTML( '<li id="mw-imagepage-edit-external">' . $elink . ' <small>' . wfMsgExt( 'edit-externally-help', array( 'parseinline' ) ) . "</small></li>\n" );
634 $wgOut->addHTML( "</ul>\n" );
637 protected function closeShowImage() { } # For overloading
640 * If the page we've just displayed is in the "Image" namespace,
641 * we follow it with an upload history of the image and its usage.
643 protected function imageHistory() {
644 global $wgOut;
646 $this->loadFile();
647 $pager = new ImageHistoryPseudoPager( $this );
648 $wgOut->addHTML( $pager->getBody() );
649 $wgOut->preventClickjacking( $pager->getPreventClickjacking() );
651 $this->img->resetHistory(); // free db resources
653 # Exist check because we don't want to show this on pages where an image
654 # doesn't exist along with the noimage message, that would suck. -ævar
655 if ( $this->img->exists() ) {
656 $this->uploadLinksBox();
660 protected function imageLinks() {
661 global $wgUser, $wgOut, $wgLang;
663 $limit = 100;
665 $dbr = wfGetDB( DB_SLAVE );
667 $res = $dbr->select(
668 array( 'imagelinks', 'page' ),
669 array( 'page_namespace', 'page_title' ),
670 array( 'il_to' => $this->mTitle->getDBkey(), 'il_from = page_id' ),
671 __METHOD__,
672 array( 'LIMIT' => $limit + 1 )
674 $count = $dbr->numRows( $res );
675 if ( $count == 0 ) {
676 $wgOut->wrapWikiMsg( Html::rawElement( 'div', array ( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ), 'nolinkstoimage' );
677 return;
680 $wgOut->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
681 if ( $count <= $limit - 1 ) {
682 $wgOut->addWikiMsg( 'linkstoimage', $count );
683 } else {
684 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
685 $wgOut->addWikiMsg( 'linkstoimage-more',
686 $wgLang->formatNum( $limit ),
687 $this->mTitle->getPrefixedDBkey()
691 $wgOut->addHTML( Html::openElement( 'ul', array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n" );
692 $sk = $wgUser->getSkin();
693 $count = 0;
694 $elements = array();
695 foreach ( $res as $s ) {
696 $count++;
697 if ( $count <= $limit ) {
698 // We have not yet reached the extra one that tells us there is more to fetch
699 $elements[] = $s;
703 // Sort the list by namespace:title
704 usort ( $elements, array( $this, 'compare' ) );
706 // Create links for every element
707 foreach( $elements as $element ) {
708 $link = $sk->linkKnown( Title::makeTitle( $element->page_namespace, $element->page_title ) );
709 $wgOut->addHTML( Html::rawElement(
710 'li',
711 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
712 $link
713 ) . "\n"
717 $wgOut->addHTML( Html::closeElement( 'ul' ) . "\n" );
718 $res->free();
720 // Add a links to [[Special:Whatlinkshere]]
721 if ( $count > $limit ) {
722 $wgOut->addWikiMsg( 'morelinkstoimage', $this->mTitle->getPrefixedDBkey() );
724 $wgOut->addHTML( Html::closeElement( 'div' ) . "\n" );
727 protected function imageRedirects() {
728 global $wgUser, $wgOut, $wgLang;
730 $redirects = $this->getTitle()->getRedirectsHere( NS_FILE );
731 if ( count( $redirects ) == 0 ) return;
733 $wgOut->addHTML( "<div id='mw-imagepage-section-redirectstofile'>\n" );
734 $wgOut->addWikiMsg( 'redirectstofile',
735 $wgLang->formatNum( count( $redirects ) )
737 $wgOut->addHTML( "<ul class='mw-imagepage-redirectstofile'>\n" );
739 $sk = $wgUser->getSkin();
740 foreach ( $redirects as $title ) {
741 $link = $sk->link(
742 $title,
743 null,
744 array(),
745 array( 'redirect' => 'no' ),
746 array( 'known', 'noclasses' )
748 $wgOut->addHTML( "<li>{$link}</li>\n" );
750 $wgOut->addHTML( "</ul></div>\n" );
754 protected function imageDupes() {
755 global $wgOut, $wgUser, $wgLang;
757 $this->loadFile();
759 $dupes = $this->getDuplicates();
760 if ( count( $dupes ) == 0 ) {
761 return;
764 $wgOut->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
765 $wgOut->addWikiMsg( 'duplicatesoffile',
766 $wgLang->formatNum( count( $dupes ) ), $this->mTitle->getDBkey()
768 $wgOut->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
770 $sk = $wgUser->getSkin();
771 foreach ( $dupes as $file ) {
772 $fromSrc = '';
773 if ( $file->isLocal() ) {
774 $link = $sk->link(
775 $file->getTitle(),
776 null,
777 array(),
778 array(),
779 array( 'known', 'noclasses' )
781 } else {
782 $link = $sk->makeExternalLink( $file->getDescriptionUrl(),
783 $file->getTitle()->getPrefixedText() );
784 $fromSrc = wfMsg( 'shared-repo-from', $file->getRepo()->getDisplayName() );
786 $wgOut->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
788 $wgOut->addHTML( "</ul></div>\n" );
792 * Delete the file, or an earlier version of it
794 public function delete() {
795 global $wgUploadMaintenance;
796 if ( $wgUploadMaintenance && $this->mTitle && $this->mTitle->getNamespace() == NS_FILE ) {
797 global $wgOut;
798 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n", array( 'filedelete-maintenance' ) );
799 return;
802 $this->loadFile();
803 if ( !$this->img->exists() || !$this->img->isLocal() || $this->img->getRedirected() ) {
804 // Standard article deletion
805 parent::delete();
806 return;
808 $deleter = new FileDeleteForm( $this->img );
809 $deleter->execute();
813 * Revert the file to an earlier version
815 public function revert() {
816 $this->loadFile();
817 $reverter = new FileRevertForm( $this->img );
818 $reverter->execute();
822 * Override handling of action=purge
824 public function doPurge() {
825 $this->loadFile();
826 if ( $this->img->exists() ) {
827 wfDebug( "ImagePage::doPurge purging " . $this->img->getName() . "\n" );
828 $update = new HTMLCacheUpdate( $this->mTitle, 'imagelinks' );
829 $update->doUpdate();
830 $this->img->upgradeRow();
831 $this->img->purgeCache();
832 } else {
833 wfDebug( "ImagePage::doPurge no image for " . $this->img->getName() . "; limiting purge to cache only\n" );
834 // even if the file supposedly doesn't exist, force any cached information
835 // to be updated (in case the cached information is wrong)
836 $this->img->purgeCache();
838 parent::doPurge();
842 * Display an error with a wikitext description
844 function showError( $description ) {
845 global $wgOut;
846 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
847 $wgOut->setRobotPolicy( "noindex,nofollow" );
848 $wgOut->setArticleRelated( false );
849 $wgOut->enableClientCache( false );
850 $wgOut->addWikiText( $description );
854 * Callback for usort() to do link sorts by (namespace, title)
855 * Function copied from Title::compare()
857 * @param $a object page to compare with
858 * @param $b object page to compare with
859 * @return Integer: result of string comparison, or namespace comparison
861 protected function compare( $a, $b ) {
862 if ( $a->page_namespace == $b->page_namespace ) {
863 return strcmp( $a->page_title, $b->page_title );
864 } else {
865 return $a->page_namespace - $b->page_namespace;
871 * Builds the image revision log shown on image pages
873 * @ingroup Media
875 class ImageHistoryList {
878 * @var Title
880 protected $title;
883 * @var File
885 protected $img;
888 * @var ImagePage
890 protected $imagePage;
893 * @var Skin
895 protected $skin;
897 protected $repo, $showThumb;
898 protected $preventClickjacking = false;
901 * @param ImagePage $imagePage
903 public function __construct( $imagePage ) {
904 global $wgUser, $wgShowArchiveThumbnails;
905 $this->skin = $wgUser->getSkin();
906 $this->current = $imagePage->getFile();
907 $this->img = $imagePage->getDisplayedFile();
908 $this->title = $imagePage->getTitle();
909 $this->imagePage = $imagePage;
910 $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
913 public function getImagePage() {
914 return $this->imagePage;
917 public function getSkin() {
918 return $this->skin;
921 public function getFile() {
922 return $this->img;
925 public function beginImageHistoryList( $navLinks = '' ) {
926 global $wgOut, $wgUser;
927 return Xml::element( 'h2', array( 'id' => 'filehistory' ), wfMsg( 'filehist' ) ) . "\n"
928 . "<div id=\"mw-imagepage-section-filehistory\">\n"
929 . $wgOut->parse( wfMsgNoTrans( 'filehist-help' ) )
930 . $navLinks . "\n"
931 . Xml::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
932 . '<tr><td></td>'
933 . ( $this->current->isLocal() && ( $wgUser->isAllowedAny( 'delete', 'deletedhistory' ) ) ? '<td></td>' : '' )
934 . '<th>' . wfMsgHtml( 'filehist-datetime' ) . '</th>'
935 . ( $this->showThumb ? '<th>' . wfMsgHtml( 'filehist-thumb' ) . '</th>' : '' )
936 . '<th>' . wfMsgHtml( 'filehist-dimensions' ) . '</th>'
937 . '<th>' . wfMsgHtml( 'filehist-user' ) . '</th>'
938 . '<th>' . wfMsgHtml( 'filehist-comment' ) . '</th>'
939 . "</tr>\n";
942 public function endImageHistoryList( $navLinks = '' ) {
943 return "</table>\n$navLinks\n</div>\n";
947 * @param $iscur
948 * @param File $file
949 * @return string
951 public function imageHistoryLine( $iscur, $file ) {
952 global $wgUser, $wgLang;
954 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
955 $img = $iscur ? $file->getName() : $file->getArchiveName();
956 $user = $file->getUser( 'id' );
957 $usertext = $file->getUser( 'text' );
958 $description = $file->getDescription();
960 $local = $this->current->isLocal();
961 $row = $selected = '';
963 // Deletion link
964 if ( $local && ( $wgUser->isAllowedAny( 'delete', 'deletedhistory' ) ) ) {
965 $row .= '<td>';
966 # Link to remove from history
967 if ( $wgUser->isAllowed( 'delete' ) ) {
968 $q = array( 'action' => 'delete' );
969 if ( !$iscur )
970 $q['oldimage'] = $img;
971 $row .= $this->skin->link(
972 $this->title,
973 wfMsgHtml( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' ),
974 array(), $q, array( 'known' )
977 # Link to hide content. Don't show useless link to people who cannot hide revisions.
978 $canHide = $wgUser->isAllowed( 'deleterevision' );
979 if ( $canHide || ( $wgUser->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
980 if ( $wgUser->isAllowed( 'delete' ) ) {
981 $row .= '<br />';
983 // If file is top revision or locked from this user, don't link
984 if ( $iscur || !$file->userCan( File::DELETED_RESTRICTED ) ) {
985 $del = $this->skin->revDeleteLinkDisabled( $canHide );
986 } else {
987 list( $ts, $name ) = explode( '!', $img, 2 );
988 $query = array(
989 'type' => 'oldimage',
990 'target' => $this->title->getPrefixedText(),
991 'ids' => $ts,
993 $del = $this->skin->revDeleteLink( $query,
994 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
996 $row .= $del;
998 $row .= '</td>';
1001 // Reversion link/current indicator
1002 $row .= '<td>';
1003 if ( $iscur ) {
1004 $row .= wfMsgHtml( 'filehist-current' );
1005 } elseif ( $local && $wgUser->isLoggedIn() && $this->title->userCan( 'edit' ) ) {
1006 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1007 $row .= wfMsgHtml( 'filehist-revert' );
1008 } else {
1009 $row .= $this->skin->link(
1010 $this->title,
1011 wfMsgHtml( 'filehist-revert' ),
1012 array(),
1013 array(
1014 'action' => 'revert',
1015 'oldimage' => $img,
1016 'wpEditToken' => $wgUser->editToken( $img )
1018 array( 'known', 'noclasses' )
1022 $row .= '</td>';
1024 // Date/time and image link
1025 if ( $file->getTimestamp() === $this->img->getTimestamp() ) {
1026 $selected = "class='filehistory-selected'";
1028 $row .= "<td $selected style='white-space: nowrap;'>";
1029 if ( !$file->userCan( File::DELETED_FILE ) ) {
1030 # Don't link to unviewable files
1031 $row .= '<span class="history-deleted">' . $wgLang->timeAndDate( $timestamp, true ) . '</span>';
1032 } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
1033 $this->preventClickjacking();
1034 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
1035 # Make a link to review the image
1036 $url = $this->skin->link(
1037 $revdel,
1038 $wgLang->timeAndDate( $timestamp, true ),
1039 array(),
1040 array(
1041 'target' => $this->title->getPrefixedText(),
1042 'file' => $img,
1043 'token' => $wgUser->editToken( $img )
1045 array( 'known', 'noclasses' )
1047 $row .= '<span class="history-deleted">' . $url . '</span>';
1048 } else {
1049 $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
1050 $row .= Xml::element( 'a', array( 'href' => $url ), $wgLang->timeAndDate( $timestamp, true ) );
1052 $row .= "</td>";
1054 // Thumbnail
1055 if ( $this->showThumb ) {
1056 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1059 // Image dimensions + size
1060 $row .= '<td>';
1061 $row .= htmlspecialchars( $file->getDimensionsString() );
1062 $row .= " <span style='white-space: nowrap;'>(" . $this->skin->formatSize( $file->getSize() ) . ')</span>';
1063 $row .= '</td>';
1065 // Uploading user
1066 $row .= '<td>';
1067 if ( $local ) {
1068 // Hide deleted usernames
1069 if ( $file->isDeleted( File::DELETED_USER ) ) {
1070 $row .= '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-user' ) . '</span>';
1071 } else {
1072 $row .= $this->skin->userLink( $user, $usertext ) . " <span style='white-space: nowrap;'>" .
1073 $this->skin->userToolLinks( $user, $usertext ) . "</span>";
1075 } else {
1076 $row .= htmlspecialchars( $usertext );
1078 $row .= '</td><td>';
1080 // Don't show deleted descriptions
1081 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1082 $row .= '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-comment' ) . '</span>';
1083 } else {
1084 $row .= $this->skin->commentBlock( $description, $this->title );
1086 $row .= '</td>';
1088 $rowClass = null;
1089 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1090 $classAttr = $rowClass ? " class='$rowClass'" : "";
1092 return "<tr{$classAttr}>{$row}</tr>\n";
1096 * @param File $file
1097 * @return string
1099 protected function getThumbForLine( $file ) {
1100 global $wgLang;
1102 if ( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE ) && !$file->isDeleted( File::DELETED_FILE ) ) {
1103 $params = array(
1104 'width' => '120',
1105 'height' => '120',
1107 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1109 $thumbnail = $file->transform( $params );
1110 $options = array(
1111 'alt' => wfMsg( 'filehist-thumbtext',
1112 $wgLang->timeAndDate( $timestamp, true ),
1113 $wgLang->date( $timestamp, true ),
1114 $wgLang->time( $timestamp, true ) ),
1115 'file-link' => true,
1118 if ( !$thumbnail ) return wfMsgHtml( 'filehist-nothumb' );
1120 return $thumbnail->toHtml( $options );
1121 } else {
1122 return wfMsgHtml( 'filehist-nothumb' );
1126 protected function preventClickjacking( $enable = true ) {
1127 $this->preventClickjacking = $enable;
1130 public function getPreventClickjacking() {
1131 return $this->preventClickjacking;
1135 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1136 protected $preventClickjacking = false;
1139 * @var File
1141 protected $mImg;
1144 * @var Title
1146 protected $mTitle;
1149 * @param ImagePage $imagePage
1151 function __construct( $imagePage ) {
1152 parent::__construct();
1153 $this->mImagePage = $imagePage;
1154 $this->mTitle = clone ( $imagePage->getTitle() );
1155 $this->mTitle->setFragment( '#filehistory' );
1156 $this->mImg = null;
1157 $this->mHist = array();
1158 $this->mRange = array( 0, 0 ); // display range
1161 function getTitle() {
1162 return $this->mTitle;
1165 function getQueryInfo() {
1166 return false;
1169 function getIndexField() {
1170 return '';
1173 function formatRow( $row ) {
1174 return '';
1177 function getBody() {
1178 $s = '';
1179 $this->doQuery();
1180 if ( count( $this->mHist ) ) {
1181 $list = new ImageHistoryList( $this->mImagePage );
1182 # Generate prev/next links
1183 $navLink = $this->getNavigationBar();
1184 $s = $list->beginImageHistoryList( $navLink );
1185 // Skip rows there just for paging links
1186 for ( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1187 $file = $this->mHist[$i];
1188 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1190 $s .= $list->endImageHistoryList( $navLink );
1192 if ( $list->getPreventClickjacking() ) {
1193 $this->preventClickjacking();
1196 return $s;
1199 function doQuery() {
1200 if ( $this->mQueryDone ) 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;
1278 protected function preventClickjacking( $enable = true ) {
1279 $this->preventClickjacking = $enable;
1282 public function getPreventClickjacking() {
1283 return $this->preventClickjacking;