When displaying non-local File pages, add link rel=canonical.
[lhc/web/wiklou.git] / includes / ImagePage.php
1 <?php
2
3 if ( !defined( 'MEDIAWIKI' ) )
4 die( 1 );
5
6 /**
7 * Special handling for image description pages
8 *
9 * @ingroup Media
10 */
11 class ImagePage extends Article {
12
13 /* private */ var $img; // Image object
14 /* private */ var $displayImg;
15 /* private */ var $repo;
16 /* private */ var $fileLoaded;
17 var $mExtraDescription = false;
18 var $dupes;
19
20 function __construct( $title ) {
21 parent::__construct( $title );
22 $this->dupes = null;
23 $this->repo = null;
24 }
25
26 /**
27 * @param $file File:
28 * @return void
29 */
30 public function setFile( $file ) {
31 $this->displayImg = $file;
32 $this->img = $file;
33 $this->fileLoaded = true;
34 }
35
36 protected function loadFile() {
37 if ( $this->fileLoaded ) {
38 return true;
39 }
40 $this->fileLoaded = true;
41
42 $this->displayImg = $this->img = false;
43 wfRunHooks( 'ImagePageFindFile', array( $this, &$this->img, &$this->displayImg ) );
44 if ( !$this->img ) {
45 $this->img = wfFindFile( $this->mTitle );
46 if ( !$this->img ) {
47 $this->img = wfLocalFile( $this->mTitle );
48 }
49 }
50 if ( !$this->displayImg ) {
51 $this->displayImg = $this->img;
52 }
53 $this->repo = $this->img->getRepo();
54 }
55
56 /**
57 * Handler for action=render
58 * Include body text only; none of the image extras
59 */
60 public function render() {
61 global $wgOut;
62 $wgOut->setArticleBodyOnly( true );
63 parent::view();
64 }
65
66 public function view() {
67 global $wgOut, $wgShowEXIF, $wgRequest, $wgUser;
68
69 $diff = $wgRequest->getVal( 'diff' );
70 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
71
72 if ( $this->mTitle->getNamespace() != NS_FILE || ( isset( $diff ) && $diffOnly ) ) {
73 return parent::view();
74 }
75
76 $this->loadFile();
77
78 if ( $this->mTitle->getNamespace() == NS_FILE && $this->img->getRedirected() ) {
79 if ( $this->mTitle->getDBkey() == $this->img->getName() || isset( $diff ) ) {
80 // mTitle is the same as the redirect target so ask Article
81 // to perform the redirect for us.
82 $wgRequest->setVal( 'diffonly', 'true' );
83 return parent::view();
84 } else {
85 // mTitle is not the same as the redirect target so it is
86 // probably the redirect page itself. Fake the redirect symbol
87 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
88 $wgOut->addHTML( $this->viewRedirect( Title::makeTitle( NS_FILE, $this->img->getName() ),
89 /* $appendSubtitle */ true, /* $forceKnown */ true ) );
90 $this->viewUpdates();
91 return;
92 }
93 }
94
95 $this->showRedirectedFromHeader();
96
97 if ( $wgShowEXIF && $this->displayImg->exists() ) {
98 // FIXME: bad interface, see note on MediaHandler::formatMetadata().
99 $formattedMetadata = $this->displayImg->formatMetadata();
100 $showmeta = $formattedMetadata !== false;
101 } else {
102 $showmeta = false;
103 }
104
105 if ( !$diff && $this->displayImg->exists() )
106 $wgOut->addHTML( $this->showTOC( $showmeta ) );
107
108 if ( !$diff )
109 $this->openShowImage();
110
111 # No need to display noarticletext, we use our own message, output in openShowImage()
112 if ( $this->getID() ) {
113 parent::view();
114 } else {
115 # Just need to set the right headers
116 $wgOut->setArticleFlag( true );
117 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
118 $this->viewUpdates();
119 }
120
121 # Show shared description, if needed
122 if ( $this->mExtraDescription ) {
123 $fol = wfMsgNoTrans( 'shareddescriptionfollows' );
124 if ( $fol != '-' && !wfEmptyMsg( 'shareddescriptionfollows', $fol ) ) {
125 $wgOut->addWikiText( $fol );
126 }
127 $wgOut->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
128 }
129
130 $this->closeShowImage();
131 $this->imageHistory();
132 // TODO: Cleanup the following
133
134 $wgOut->addHTML( Xml::element( 'h2',
135 array( 'id' => 'filelinks' ),
136 wfMsg( 'imagelinks' ) ) . "\n" );
137 $this->imageDupes();
138 # TODO! FIXME! For some freaky reason, we can't redirect to foreign images.
139 # Yet we return metadata about the target. Definitely an issue in the FileRepo
140 $this->imageRedirects();
141 $this->imageLinks();
142
143 # Allow extensions to add something after the image links
144 $html = '';
145 wfRunHooks( 'ImagePageAfterImageLinks', array( $this, &$html ) );
146 if ( $html )
147 $wgOut->addHTML( $html );
148
149 if ( $showmeta ) {
150 $wgOut->addHTML( Xml::element( 'h2', array( 'id' => 'metadata' ), wfMsg( 'metadata' ) ) . "\n" );
151 $wgOut->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
152 $wgOut->addModules( array( 'mediawiki.legacy.metadata' ) );
153 }
154
155 $css = $this->repo->getDescriptionStylesheetUrl();
156 if ( $css ) {
157 $wgOut->addStyle( $css );
158 }
159 }
160
161 public function getRedirectTarget() {
162 $this->loadFile();
163 if ( $this->img->isLocal() ) {
164 return parent::getRedirectTarget();
165 }
166 // Foreign image page
167 $from = $this->img->getRedirected();
168 $to = $this->img->getName();
169 if ( $from == $to ) {
170 return null;
171 }
172 return $this->mRedirectTarget = Title::makeTitle( NS_FILE, $to );
173 }
174 public function followRedirect() {
175 $this->loadFile();
176 if ( $this->img->isLocal() ) {
177 return parent::followRedirect();
178 }
179 $from = $this->img->getRedirected();
180 $to = $this->img->getName();
181 if ( $from == $to ) {
182 return false;
183 }
184 return Title::makeTitle( NS_FILE, $to );
185 }
186 public function isRedirect( $text = false ) {
187 $this->loadFile();
188 if ( $this->img->isLocal() )
189 return parent::isRedirect( $text );
190
191 return (bool)$this->img->getRedirected();
192 }
193
194 public function isLocal() {
195 $this->loadFile();
196 return $this->img->isLocal();
197 }
198
199 public function getFile() {
200 $this->loadFile();
201 return $this->img;
202 }
203
204 public function getDisplayedFile() {
205 $this->loadFile();
206 return $this->displayImg;
207 }
208
209 public function getDuplicates() {
210 $this->loadFile();
211 if ( !is_null( $this->dupes ) ) {
212 return $this->dupes;
213 }
214 if ( !( $hash = $this->img->getSha1() ) ) {
215 return $this->dupes = array();
216 }
217 $dupes = RepoGroup::singleton()->findBySha1( $hash );
218 // Remove duplicates with self and non matching file sizes
219 $self = $this->img->getRepoName() . ':' . $this->img->getName();
220 $size = $this->img->getSize();
221 foreach ( $dupes as $index => $file ) {
222 $key = $file->getRepoName() . ':' . $file->getName();
223 if ( $key == $self )
224 unset( $dupes[$index] );
225 if ( $file->getSize() != $size )
226 unset( $dupes[$index] );
227 }
228 return $this->dupes = $dupes;
229
230 }
231
232
233 /**
234 * Create the TOC
235 *
236 * @param $metadata Boolean: whether or not to show the metadata link
237 * @return String
238 */
239 protected function showTOC( $metadata ) {
240 $r = array(
241 '<li><a href="#file">' . wfMsgHtml( 'file-anchor-link' ) . '</a></li>',
242 '<li><a href="#filehistory">' . wfMsgHtml( 'filehist' ) . '</a></li>',
243 '<li><a href="#filelinks">' . wfMsgHtml( 'imagelinks' ) . '</a></li>',
244 );
245 if ( $metadata ) {
246 $r[] = '<li><a href="#metadata">' . wfMsgHtml( 'metadata' ) . '</a></li>';
247 }
248
249 wfRunHooks( 'ImagePageShowTOC', array( $this, &$r ) );
250
251 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
252 }
253
254 /**
255 * Make a table with metadata to be shown in the output page.
256 *
257 * FIXME: bad interface, see note on MediaHandler::formatMetadata().
258 *
259 * @param $metadata Array: the array containing the EXIF data
260 * @return String
261 */
262 protected function makeMetadataTable( $metadata ) {
263 $r = "<div class=\"mw-imagepage-section-metadata\">";
264 $r .= wfMsgNoTrans( 'metadata-help' );
265 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
266 foreach ( $metadata as $type => $stuff ) {
267 foreach ( $stuff as $v ) {
268 # FIXME, why is this using escapeId for a class?!
269 $class = Sanitizer::escapeId( $v['id'] );
270 if ( $type == 'collapsed' ) {
271 $class .= ' collapsable';
272 }
273 $r .= "<tr class=\"$class\">\n";
274 $r .= "<th>{$v['name']}</th>\n";
275 $r .= "<td>{$v['value']}</td>\n</tr>";
276 }
277 }
278 $r .= "</table>\n</div>\n";
279 return $r;
280 }
281
282 /**
283 * Overloading Article's getContent method.
284 *
285 * Omit noarticletext if sharedupload; text will be fetched from the
286 * shared upload server if possible.
287 */
288 public function getContent() {
289 $this->loadFile();
290 if ( $this->img && !$this->img->isLocal() && 0 == $this->getID() ) {
291 return '';
292 }
293 return Article::getContent();
294 }
295
296 protected function openShowImage() {
297 global $wgOut, $wgUser, $wgImageLimits, $wgRequest,
298 $wgLang, $wgContLang, $wgEnableUploads;
299
300 $this->loadFile();
301
302 $full_url = $this->displayImg->getURL();
303 $sizeSel = intval( $wgUser->getOption( 'imagesize' ) );
304 if ( !isset( $wgImageLimits[$sizeSel] ) ) {
305 $sizeSel = User::getDefaultOption( 'imagesize' );
306
307 // The user offset might still be incorrect, specially if
308 // $wgImageLimits got changed (see bug #8858).
309 if ( !isset( $wgImageLimits[$sizeSel] ) ) {
310 // Default to the first offset in $wgImageLimits
311 $sizeSel = 0;
312 }
313 }
314 $max = $wgImageLimits[$sizeSel];
315 $maxWidth = $max[0];
316 $maxHeight = $max[1];
317 $sk = $wgUser->getSkin();
318 $dirmark = $wgContLang->getDirMark();
319
320 if ( $this->displayImg->exists() ) {
321 # image
322 $page = $wgRequest->getIntOrNull( 'page' );
323 if ( is_null( $page ) ) {
324 $params = array();
325 $page = 1;
326 } else {
327 $params = array( 'page' => $page );
328 }
329 $width_orig = $this->displayImg->getWidth( $page );
330 $width = $width_orig;
331 $height_orig = $this->displayImg->getHeight( $page );
332 $height = $height_orig;
333
334 $longDesc = $this->displayImg->getLongDesc();
335
336 wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this, &$wgOut ) );
337
338 if ( $this->displayImg->allowInlineDisplay() ) {
339 # image
340
341 # "Download high res version" link below the image
342 # $msgsize = wfMsgHtml('file-info-size', $width_orig, $height_orig, $sk->formatSize( $this->displayImg->getSize() ), $mime );
343 # We'll show a thumbnail of this image
344 if ( $width > $maxWidth || $height > $maxHeight ) {
345 # Calculate the thumbnail size.
346 # First case, the limiting factor is the width, not the height.
347 if ( $width / $height >= $maxWidth / $maxHeight ) {
348 $height = round( $height * $maxWidth / $width );
349 $width = $maxWidth;
350 # Note that $height <= $maxHeight now.
351 } else {
352 $newwidth = floor( $width * $maxHeight / $height );
353 $height = round( $height * $newwidth / $width );
354 $width = $newwidth;
355 # Note that $height <= $maxHeight now, but might not be identical
356 # because of rounding.
357 }
358 $msgbig = wfMsgHtml( 'show-big-image' );
359 $msgsmall = wfMsgExt( 'show-big-image-thumb', 'parseinline',
360 $wgLang->formatNum( $width ),
361 $wgLang->formatNum( $height )
362 );
363 } else {
364 # Image is small enough to show full size on image page
365 $msgsmall = wfMsgExt( 'file-nohires', array( 'parseinline' ) );
366 }
367
368 $params['width'] = $width;
369 $thumbnail = $this->displayImg->transform( $params );
370
371 $showLink = true;
372 $anchorclose = '';
373 if ( !$this->displayImg->mustRender() ) {
374 $anchorclose = "<br />" . $msgsmall;
375 }
376
377 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
378 if ( $isMulti ) {
379 $wgOut->addHTML( '<table class="multipageimage"><tr><td>' );
380 }
381
382 if ( $thumbnail ) {
383 $options = array(
384 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
385 'file-link' => true,
386 );
387 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
388 $thumbnail->toHtml( $options ) .
389 $anchorclose . "</div>\n" );
390 }
391
392 if ( $isMulti ) {
393 $count = $this->displayImg->pageCount();
394
395 if ( $page > 1 ) {
396 $label = $wgOut->parse( wfMsg( 'imgmultipageprev' ), false );
397 $link = $sk->link(
398 $this->mTitle,
399 $label,
400 array(),
401 array( 'page' => $page - 1 ),
402 array( 'known', 'noclasses' )
403 );
404 $thumb1 = $sk->makeThumbLinkObj( $this->mTitle, $this->displayImg, $link, $label, 'none',
405 array( 'page' => $page - 1 ) );
406 } else {
407 $thumb1 = '';
408 }
409
410 if ( $page < $count ) {
411 $label = wfMsg( 'imgmultipagenext' );
412 $link = $sk->link(
413 $this->mTitle,
414 $label,
415 array(),
416 array( 'page' => $page + 1 ),
417 array( 'known', 'noclasses' )
418 );
419 $thumb2 = $sk->makeThumbLinkObj( $this->mTitle, $this->displayImg, $link, $label, 'none',
420 array( 'page' => $page + 1 ) );
421 } else {
422 $thumb2 = '';
423 }
424
425 global $wgScript;
426
427 $formParams = array(
428 'name' => 'pageselector',
429 'action' => $wgScript,
430 'onchange' => 'document.pageselector.submit();',
431 );
432
433 for ( $i = 1; $i <= $count; $i++ ) {
434 $options[] = Xml::option( $wgLang->formatNum( $i ), $i, $i == $page );
435 }
436 $select = Xml::tags( 'select',
437 array( 'id' => 'pageselector', 'name' => 'page' ),
438 implode( "\n", $options ) );
439
440 $wgOut->addHTML(
441 '</td><td><div class="multipageimagenavbox">' .
442 Xml::openElement( 'form', $formParams ) .
443 Html::hidden( 'title', $this->getTitle()->getPrefixedDbKey() ) .
444 wfMsgExt( 'imgmultigoto', array( 'parseinline', 'replaceafter' ), $select ) .
445 Xml::submitButton( wfMsg( 'imgmultigo' ) ) .
446 Xml::closeElement( 'form' ) .
447 "<hr />$thumb1\n$thumb2<br clear=\"all\" /></div></td></tr></table>"
448 );
449 }
450 } else {
451 # if direct link is allowed but it's not a renderable image, show an icon.
452 if ( $this->displayImg->isSafeFile() ) {
453 $icon = $this->displayImg->iconThumb();
454
455 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
456 $icon->toHtml( array( 'file-link' => true ) ) .
457 "</div>\n" );
458 }
459
460 $showLink = true;
461 }
462
463
464 if ( $showLink ) {
465 $filename = wfEscapeWikiText( $this->displayImg->getName() );
466 $linktext = $filename;
467 if ( isset( $msgbig ) ) {
468 $linktext = wfEscapeWikiText( $msgbig );
469 }
470 $medialink = "[[Media:$filename|$linktext]]";
471
472 if ( !$this->displayImg->isSafeFile() ) {
473 $warning = wfMsgNoTrans( 'mediawarning' );
474 $wgOut->addWikiText( <<<EOT
475 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span>$dirmark <span class="fileInfo">$longDesc</span></div>
476 <div class="mediaWarning">$warning</div>
477 EOT
478 );
479 } else {
480 $wgOut->addWikiText( <<<EOT
481 <div class="fullMedia">{$medialink}{$dirmark} <span class="fileInfo">$longDesc</span>
482 </div>
483 EOT
484 );
485 }
486 }
487
488 if ( !$this->displayImg->isLocal() ) {
489 $this->printSharedImageText();
490 }
491 } else {
492 # Image does not exist
493 if ( $wgEnableUploads && $wgUser->isAllowed( 'upload' ) ) {
494 // Only show an upload link if the user can upload
495 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
496 $nofile = array(
497 'filepage-nofile-link',
498 $uploadTitle->getFullUrl( array( 'wpDestFile' => $this->img->getName() ) )
499 );
500 }
501 else
502 {
503 $nofile = 'filepage-nofile';
504 }
505 $wgOut->setRobotPolicy( 'noindex,nofollow' );
506 $wgOut->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
507 }
508 }
509
510 /**
511 * Show a notice that the file is from a shared repository
512 */
513 protected function printSharedImageText() {
514 global $wgOut;
515
516 $this->loadFile();
517
518 $descUrl = $this->img->getDescriptionUrl();
519 $descText = $this->img->getDescriptionText();
520
521 if( $descUrl ) {
522 $wgOut->addLink( array( 'rel' => 'canonical', 'href' => $descUrl ) );
523 }
524
525 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
526 $repo = $this->img->getRepo()->getDisplayName();
527
528 if ( $descUrl && $descText && wfMsgNoTrans( 'sharedupload-desc-here' ) !== '-' ) {
529 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
530 } elseif ( $descUrl && wfMsgNoTrans( 'sharedupload-desc-there' ) !== '-' ) {
531 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
532 } else {
533 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
534 }
535
536 if ( $descText ) {
537 $this->mExtraDescription = $descText;
538 }
539 }
540
541 public function getUploadUrl() {
542 $this->loadFile();
543 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
544 return $uploadTitle->getFullUrl( array(
545 'wpDestFile' => $this->img->getName(),
546 'wpForReUpload' => 1
547 ) );
548 }
549
550 /**
551 * Print out the various links at the bottom of the image page, e.g. reupload,
552 * external editing (and instructions link) etc.
553 */
554 protected function uploadLinksBox() {
555 global $wgUser, $wgOut, $wgEnableUploads, $wgUseExternalEditor;
556
557 if ( !$wgEnableUploads ) { return; }
558
559 $this->loadFile();
560 if ( !$this->img->isLocal() )
561 return;
562
563 $sk = $wgUser->getSkin();
564
565 $wgOut->addHTML( "<br /><ul>\n" );
566
567 # "Upload a new version of this file" link
568 if ( UploadBase::userCanReUpload( $wgUser, $this->img->name ) ) {
569 $ulink = $sk->makeExternalLink( $this->getUploadUrl(), wfMsg( 'uploadnewversion-linktext' ) );
570 $wgOut->addHTML( "<li id=\"mw-imagepage-reupload-link\"><div class=\"plainlinks\">{$ulink}</div></li>\n" );
571 }
572
573 # External editing link
574 if ( $wgUseExternalEditor ) {
575 $elink = $sk->link(
576 $this->mTitle,
577 wfMsgHtml( 'edit-externally' ),
578 array(),
579 array(
580 'action' => 'edit',
581 'externaledit' => 'true',
582 'mode' => 'file'
583 ),
584 array( 'known', 'noclasses' )
585 );
586 $wgOut->addHTML( '<li id="mw-imagepage-edit-external">' . $elink . ' <small>' . wfMsgExt( 'edit-externally-help', array( 'parseinline' ) ) . "</small></li>\n" );
587 }
588
589 $wgOut->addHTML( "</ul>\n" );
590 }
591
592 protected function closeShowImage() { } # For overloading
593
594 /**
595 * If the page we've just displayed is in the "Image" namespace,
596 * we follow it with an upload history of the image and its usage.
597 */
598 protected function imageHistory() {
599 global $wgOut;
600
601 $this->loadFile();
602 $pager = new ImageHistoryPseudoPager( $this );
603 $wgOut->addHTML( $pager->getBody() );
604
605 $this->img->resetHistory(); // free db resources
606
607 # Exist check because we don't want to show this on pages where an image
608 # doesn't exist along with the noimage message, that would suck. -ævar
609 if ( $this->img->exists() ) {
610 $this->uploadLinksBox();
611 }
612 }
613
614 protected function imageLinks() {
615 global $wgUser, $wgOut, $wgLang;
616
617 $limit = 100;
618
619 $dbr = wfGetDB( DB_SLAVE );
620
621 $res = $dbr->select(
622 array( 'imagelinks', 'page' ),
623 array( 'page_namespace', 'page_title' ),
624 array( 'il_to' => $this->mTitle->getDBkey(), 'il_from = page_id' ),
625 __METHOD__,
626 array( 'LIMIT' => $limit + 1 )
627 );
628 $count = $dbr->numRows( $res );
629 if ( $count == 0 ) {
630 $wgOut->wrapWikiMsg( Html::rawElement( 'div', array ( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ), 'nolinkstoimage' );
631 return;
632 }
633
634 $wgOut->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
635 if ( $count <= $limit - 1 ) {
636 $wgOut->addWikiMsg( 'linkstoimage', $count );
637 } else {
638 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
639 $wgOut->addWikiMsg( 'linkstoimage-more',
640 $wgLang->formatNum( $limit ),
641 $this->mTitle->getPrefixedDBkey()
642 );
643 }
644
645 $wgOut->addHTML( Html::openElement( 'ul', array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n" );
646 $sk = $wgUser->getSkin();
647 $count = 0;
648 $elements = array();
649 foreach ( $res as $s ) {
650 $count++;
651 if ( $count <= $limit ) {
652 // We have not yet reached the extra one that tells us there is more to fetch
653 $elements[] = $s;
654 }
655 }
656
657 // Sort the list by namespace:title
658 usort ( $elements, array( $this, 'compare' ) );
659
660 // Create links for every element
661 foreach( $elements as $element ) {
662 $link = $sk->linkKnown( Title::makeTitle( $element->page_namespace, $element->page_title ) );
663 $wgOut->addHTML( Html::rawElement(
664 'li',
665 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
666 $link
667 ) . "\n"
668 );
669
670 };
671 $wgOut->addHTML( Html::closeElement( 'ul' ) . "\n" );
672 $res->free();
673
674 // Add a links to [[Special:Whatlinkshere]]
675 if ( $count > $limit ) {
676 $wgOut->addWikiMsg( 'morelinkstoimage', $this->mTitle->getPrefixedDBkey() );
677 }
678 $wgOut->addHTML( Html::closeElement( 'div' ) . "\n" );
679 }
680
681 protected function imageRedirects() {
682 global $wgUser, $wgOut, $wgLang;
683
684 $redirects = $this->getTitle()->getRedirectsHere( NS_FILE );
685 if ( count( $redirects ) == 0 ) return;
686
687 $wgOut->addHTML( "<div id='mw-imagepage-section-redirectstofile'>\n" );
688 $wgOut->addWikiMsg( 'redirectstofile',
689 $wgLang->formatNum( count( $redirects ) )
690 );
691 $wgOut->addHTML( "<ul class='mw-imagepage-redirectstofile'>\n" );
692
693 $sk = $wgUser->getSkin();
694 foreach ( $redirects as $title ) {
695 $link = $sk->link(
696 $title,
697 null,
698 array(),
699 array( 'redirect' => 'no' ),
700 array( 'known', 'noclasses' )
701 );
702 $wgOut->addHTML( "<li>{$link}</li>\n" );
703 }
704 $wgOut->addHTML( "</ul></div>\n" );
705
706 }
707
708 protected function imageDupes() {
709 global $wgOut, $wgUser, $wgLang;
710
711 $this->loadFile();
712
713 $dupes = $this->getDuplicates();
714 if ( count( $dupes ) == 0 ) return;
715
716 $wgOut->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
717 $wgOut->addWikiMsg( 'duplicatesoffile',
718 $wgLang->formatNum( count( $dupes ) ), $this->mTitle->getDBkey()
719 );
720 $wgOut->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
721
722 $sk = $wgUser->getSkin();
723 foreach ( $dupes as $file ) {
724 $fromSrc = '';
725 if ( $file->isLocal() ) {
726 $link = $sk->link(
727 $file->getTitle(),
728 null,
729 array(),
730 array(),
731 array( 'known', 'noclasses' )
732 );
733 } else {
734 $link = $sk->makeExternalLink( $file->getDescriptionUrl(),
735 $file->getTitle()->getPrefixedText() );
736 $fromSrc = wfMsg( 'shared-repo-from', $file->getRepo()->getDisplayName() );
737 }
738 $wgOut->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
739 }
740 $wgOut->addHTML( "</ul></div>\n" );
741 }
742
743 /**
744 * Delete the file, or an earlier version of it
745 */
746 public function delete() {
747 global $wgUploadMaintenance;
748 if ( $wgUploadMaintenance && $this->mTitle && $this->mTitle->getNamespace() == NS_FILE ) {
749 global $wgOut;
750 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n", array( 'filedelete-maintenance' ) );
751 return;
752 }
753
754 $this->loadFile();
755 if ( !$this->img->exists() || !$this->img->isLocal() || $this->img->getRedirected() ) {
756 // Standard article deletion
757 parent::delete();
758 return;
759 }
760 $deleter = new FileDeleteForm( $this->img );
761 $deleter->execute();
762 }
763
764 /**
765 * Revert the file to an earlier version
766 */
767 public function revert() {
768 $this->loadFile();
769 $reverter = new FileRevertForm( $this->img );
770 $reverter->execute();
771 }
772
773 /**
774 * Override handling of action=purge
775 */
776 public function doPurge() {
777 $this->loadFile();
778 if ( $this->img->exists() ) {
779 wfDebug( "ImagePage::doPurge purging " . $this->img->getName() . "\n" );
780 $update = new HTMLCacheUpdate( $this->mTitle, 'imagelinks' );
781 $update->doUpdate();
782 $this->img->upgradeRow();
783 $this->img->purgeCache();
784 } else {
785 wfDebug( "ImagePage::doPurge no image for " . $this->img->getName() . "; limiting purge to cache only\n" );
786 // even if the file supposedly doesn't exist, force any cached information
787 // to be updated (in case the cached information is wrong)
788 $this->img->purgeCache();
789 }
790 parent::doPurge();
791 }
792
793 /**
794 * Display an error with a wikitext description
795 */
796 function showError( $description ) {
797 global $wgOut;
798 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
799 $wgOut->setRobotPolicy( "noindex,nofollow" );
800 $wgOut->setArticleRelated( false );
801 $wgOut->enableClientCache( false );
802 $wgOut->addWikiText( $description );
803 }
804
805
806 /**
807 * Callback for usort() to do link sorts by (namespace, title)
808 * Function copied from Title::compare()
809 *
810 * @param $a object page to compare with
811 * @param $b object page to compare with
812 * @return Integer: result of string comparison, or namespace comparison
813 */
814 protected function compare( $a, $b ) {
815 if ( $a->page_namespace == $b->page_namespace ) {
816 return strcmp( $a->page_title, $b->page_title );
817 } else {
818 return $a->page_namespace - $b->page_namespace;
819 }
820 }
821 }
822
823 /**
824 * Builds the image revision log shown on image pages
825 *
826 * @ingroup Media
827 */
828 class ImageHistoryList {
829
830 protected $imagePage, $img, $skin, $title, $repo, $showThumb;
831
832 public function __construct( $imagePage ) {
833 global $wgUser, $wgShowArchiveThumbnails;
834 $this->skin = $wgUser->getSkin();
835 $this->current = $imagePage->getFile();
836 $this->img = $imagePage->getDisplayedFile();
837 $this->title = $imagePage->getTitle();
838 $this->imagePage = $imagePage;
839 $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
840 }
841
842 public function getImagePage() {
843 return $this->imagePage;
844 }
845
846 public function getSkin() {
847 return $this->skin;
848 }
849
850 public function getFile() {
851 return $this->img;
852 }
853
854 public function beginImageHistoryList( $navLinks = '' ) {
855 global $wgOut, $wgUser;
856 return Xml::element( 'h2', array( 'id' => 'filehistory' ), wfMsg( 'filehist' ) ) . "\n"
857 . "<div id=\"mw-imagepage-section-filehistory\">\n"
858 . $wgOut->parse( wfMsgNoTrans( 'filehist-help' ) )
859 . $navLinks . "\n"
860 . Xml::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
861 . '<tr><td></td>'
862 . ( $this->current->isLocal() && ( $wgUser->isAllowed( 'delete' ) || $wgUser->isAllowed( 'deletedhistory' ) ) ? '<td></td>' : '' )
863 . '<th>' . wfMsgHtml( 'filehist-datetime' ) . '</th>'
864 . ( $this->showThumb ? '<th>' . wfMsgHtml( 'filehist-thumb' ) . '</th>' : '' )
865 . '<th>' . wfMsgHtml( 'filehist-dimensions' ) . '</th>'
866 . '<th>' . wfMsgHtml( 'filehist-user' ) . '</th>'
867 . '<th>' . wfMsgHtml( 'filehist-comment' ) . '</th>'
868 . "</tr>\n";
869 }
870
871 public function endImageHistoryList( $navLinks = '' ) {
872 return "</table>\n$navLinks\n</div>\n";
873 }
874
875 public function imageHistoryLine( $iscur, $file ) {
876 global $wgUser, $wgLang;
877
878 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
879 $img = $iscur ? $file->getName() : $file->getArchiveName();
880 $user = $file->getUser( 'id' );
881 $usertext = $file->getUser( 'text' );
882 $description = $file->getDescription();
883
884 $local = $this->current->isLocal();
885 $row = $selected = '';
886
887 // Deletion link
888 if ( $local && ( $wgUser->isAllowed( 'delete' ) || $wgUser->isAllowed( 'deletedhistory' ) ) ) {
889 $row .= '<td>';
890 # Link to remove from history
891 if ( $wgUser->isAllowed( 'delete' ) ) {
892 $q = array( 'action' => 'delete' );
893 if ( !$iscur )
894 $q['oldimage'] = $img;
895 $row .= $this->skin->link(
896 $this->title,
897 wfMsgHtml( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' ),
898 array(), $q, array( 'known' )
899 );
900 }
901 # Link to hide content. Don't show useless link to people who cannot hide revisions.
902 $canHide = $wgUser->isAllowed( 'deleterevision' );
903 if ( $canHide || ( $wgUser->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
904 if ( $wgUser->isAllowed( 'delete' ) ) {
905 $row .= '<br />';
906 }
907 // If file is top revision or locked from this user, don't link
908 if ( $iscur || !$file->userCan( File::DELETED_RESTRICTED ) ) {
909 $del = $this->skin->revDeleteLinkDisabled( $canHide );
910 } else {
911 list( $ts, $name ) = explode( '!', $img, 2 );
912 $query = array(
913 'type' => 'oldimage',
914 'target' => $this->title->getPrefixedText(),
915 'ids' => $ts,
916 );
917 $del = $this->skin->revDeleteLink( $query,
918 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
919 }
920 $row .= $del;
921 }
922 $row .= '</td>';
923 }
924
925 // Reversion link/current indicator
926 $row .= '<td>';
927 if ( $iscur ) {
928 $row .= wfMsgHtml( 'filehist-current' );
929 } elseif ( $local && $wgUser->isLoggedIn() && $this->title->userCan( 'edit' ) ) {
930 if ( $file->isDeleted( File::DELETED_FILE ) ) {
931 $row .= wfMsgHtml( 'filehist-revert' );
932 } else {
933 $row .= $this->skin->link(
934 $this->title,
935 wfMsgHtml( 'filehist-revert' ),
936 array(),
937 array(
938 'action' => 'revert',
939 'oldimage' => $img,
940 'wpEditToken' => $wgUser->editToken( $img )
941 ),
942 array( 'known', 'noclasses' )
943 );
944 }
945 }
946 $row .= '</td>';
947
948 // Date/time and image link
949 if ( $file->getTimestamp() === $this->img->getTimestamp() ) {
950 $selected = "class='filehistory-selected'";
951 }
952 $row .= "<td $selected style='white-space: nowrap;'>";
953 if ( !$file->userCan( File::DELETED_FILE ) ) {
954 # Don't link to unviewable files
955 $row .= '<span class="history-deleted">' . $wgLang->timeAndDate( $timestamp, true ) . '</span>';
956 } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
957 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
958 # Make a link to review the image
959 $url = $this->skin->link(
960 $revdel,
961 $wgLang->timeAndDate( $timestamp, true ),
962 array(),
963 array(
964 'target' => $this->title->getPrefixedText(),
965 'file' => $img,
966 'token' => $wgUser->editToken( $img )
967 ),
968 array( 'known', 'noclasses' )
969 );
970 $row .= '<span class="history-deleted">' . $url . '</span>';
971 } else {
972 $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
973 $row .= Xml::element( 'a', array( 'href' => $url ), $wgLang->timeAndDate( $timestamp, true ) );
974 }
975 $row .= "</td>";
976
977 // Thumbnail
978 if ( $this->showThumb ) {
979 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
980 }
981
982 // Image dimensions + size
983 $row .= '<td>';
984 $row .= htmlspecialchars( $file->getDimensionsString() );
985 $row .= " <span style='white-space: nowrap;'>(" . $this->skin->formatSize( $file->getSize() ) . ')</span>';
986 $row .= '</td>';
987
988 // Uploading user
989 $row .= '<td>';
990 if ( $local ) {
991 // Hide deleted usernames
992 if ( $file->isDeleted( File::DELETED_USER ) ) {
993 $row .= '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-user' ) . '</span>';
994 } else {
995 $row .= $this->skin->userLink( $user, $usertext ) . " <span style='white-space: nowrap;'>" .
996 $this->skin->userToolLinks( $user, $usertext ) . "</span>";
997 }
998 } else {
999 $row .= htmlspecialchars( $usertext );
1000 }
1001 $row .= '</td><td>';
1002
1003 // Don't show deleted descriptions
1004 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1005 $row .= '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-comment' ) . '</span>';
1006 } else {
1007 $row .= $this->skin->commentBlock( $description, $this->title );
1008 }
1009 $row .= '</td>';
1010
1011 $rowClass = null;
1012 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1013 $classAttr = $rowClass ? " class='$rowClass'" : "";
1014
1015 return "<tr{$classAttr}>{$row}</tr>\n";
1016 }
1017
1018 protected function getThumbForLine( $file ) {
1019 global $wgLang;
1020
1021 if ( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE ) && !$file->isDeleted( File::DELETED_FILE ) ) {
1022 $params = array(
1023 'width' => '120',
1024 'height' => '120',
1025 );
1026 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1027
1028 $thumbnail = $file->transform( $params );
1029 $options = array(
1030 'alt' => wfMsg( 'filehist-thumbtext',
1031 $wgLang->timeAndDate( $timestamp, true ),
1032 $wgLang->date( $timestamp, true ),
1033 $wgLang->time( $timestamp, true ) ),
1034 'file-link' => true,
1035 );
1036
1037 if ( !$thumbnail ) return wfMsgHtml( 'filehist-nothumb' );
1038
1039 return $thumbnail->toHtml( $options );
1040 } else {
1041 return wfMsgHtml( 'filehist-nothumb' );
1042 }
1043 }
1044 }
1045
1046 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1047 function __construct( $imagePage ) {
1048 parent::__construct();
1049 $this->mImagePage = $imagePage;
1050 $this->mTitle = clone ( $imagePage->getTitle() );
1051 $this->mTitle->setFragment( '#filehistory' );
1052 $this->mImg = null;
1053 $this->mHist = array();
1054 $this->mRange = array( 0, 0 ); // display range
1055 }
1056
1057 function getTitle() {
1058 return $this->mTitle;
1059 }
1060
1061 function getQueryInfo() {
1062 return false;
1063 }
1064
1065 function getIndexField() {
1066 return '';
1067 }
1068
1069 function formatRow( $row ) {
1070 return '';
1071 }
1072
1073 function getBody() {
1074 $s = '';
1075 $this->doQuery();
1076 if ( count( $this->mHist ) ) {
1077 $list = new ImageHistoryList( $this->mImagePage );
1078 # Generate prev/next links
1079 $navLink = $this->getNavigationBar();
1080 $s = $list->beginImageHistoryList( $navLink );
1081 // Skip rows there just for paging links
1082 for ( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1083 $file = $this->mHist[$i];
1084 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1085 }
1086 $s .= $list->endImageHistoryList( $navLink );
1087 }
1088 return $s;
1089 }
1090
1091 function doQuery() {
1092 if ( $this->mQueryDone ) return;
1093 $this->mImg = $this->mImagePage->getFile(); // ensure loading
1094 if ( !$this->mImg->exists() ) {
1095 return;
1096 }
1097 $queryLimit = $this->mLimit + 1; // limit plus extra row
1098 if ( $this->mIsBackwards ) {
1099 // Fetch the file history
1100 $this->mHist = $this->mImg->getHistory( $queryLimit, null, $this->mOffset, false );
1101 // The current rev may not meet the offset/limit
1102 $numRows = count( $this->mHist );
1103 if ( $numRows <= $this->mLimit && $this->mImg->getTimestamp() > $this->mOffset ) {
1104 $this->mHist = array_merge( array( $this->mImg ), $this->mHist );
1105 }
1106 } else {
1107 // The current rev may not meet the offset
1108 if ( !$this->mOffset || $this->mImg->getTimestamp() < $this->mOffset ) {
1109 $this->mHist[] = $this->mImg;
1110 }
1111 // Old image versions (fetch extra row for nav links)
1112 $oiLimit = count( $this->mHist ) ? $this->mLimit : $this->mLimit + 1;
1113 // Fetch the file history
1114 $this->mHist = array_merge( $this->mHist,
1115 $this->mImg->getHistory( $oiLimit, $this->mOffset, null, false ) );
1116 }
1117 $numRows = count( $this->mHist ); // Total number of query results
1118 if ( $numRows ) {
1119 # Index value of top item in the list
1120 $firstIndex = $this->mIsBackwards ?
1121 $this->mHist[$numRows - 1]->getTimestamp() : $this->mHist[0]->getTimestamp();
1122 # Discard the extra result row if there is one
1123 if ( $numRows > $this->mLimit && $numRows > 1 ) {
1124 if ( $this->mIsBackwards ) {
1125 # Index value of item past the index
1126 $this->mPastTheEndIndex = $this->mHist[0]->getTimestamp();
1127 # Index value of bottom item in the list
1128 $lastIndex = $this->mHist[1]->getTimestamp();
1129 # Display range
1130 $this->mRange = array( 1, $numRows - 1 );
1131 } else {
1132 # Index value of item past the index
1133 $this->mPastTheEndIndex = $this->mHist[$numRows - 1]->getTimestamp();
1134 # Index value of bottom item in the list
1135 $lastIndex = $this->mHist[$numRows - 2]->getTimestamp();
1136 # Display range
1137 $this->mRange = array( 0, $numRows - 2 );
1138 }
1139 } else {
1140 # Setting indexes to an empty string means that they will be
1141 # omitted if they would otherwise appear in URLs. It just so
1142 # happens that this is the right thing to do in the standard
1143 # UI, in all the relevant cases.
1144 $this->mPastTheEndIndex = '';
1145 # Index value of bottom item in the list
1146 $lastIndex = $this->mIsBackwards ?
1147 $this->mHist[0]->getTimestamp() : $this->mHist[$numRows - 1]->getTimestamp();
1148 # Display range
1149 $this->mRange = array( 0, $numRows - 1 );
1150 }
1151 } else {
1152 $firstIndex = '';
1153 $lastIndex = '';
1154 $this->mPastTheEndIndex = '';
1155 }
1156 if ( $this->mIsBackwards ) {
1157 $this->mIsFirst = ( $numRows < $queryLimit );
1158 $this->mIsLast = ( $this->mOffset == '' );
1159 $this->mLastShown = $firstIndex;
1160 $this->mFirstShown = $lastIndex;
1161 } else {
1162 $this->mIsFirst = ( $this->mOffset == '' );
1163 $this->mIsLast = ( $numRows < $queryLimit );
1164 $this->mLastShown = $lastIndex;
1165 $this->mFirstShown = $firstIndex;
1166 }
1167 $this->mQueryDone = true;
1168 }
1169 }