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