(bug 2581, bug 6834) Added links to thumbnail in several resolutions to the file...
[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 if ( !$diff )
113 $this->openShowImage();
114
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();
123 }
124
125 # Show shared description, if needed
126 if ( $this->mExtraDescription ) {
127 $fol = wfMessage( 'shareddescriptionfollows' );
128 if ( !$fol->isDisabled() ) {
129 $wgOut->addWikiText( $fol->plain() );
130 }
131 $wgOut->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
132 }
133
134 $this->closeShowImage();
135 $this->imageHistory();
136 // TODO: Cleanup the following
137
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();
146
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 );
152
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' ) );
157 }
158
159 $css = $this->repo->getDescriptionStylesheetUrl();
160 if ( $css ) {
161 $wgOut->addStyle( $css );
162 }
163 }
164
165 public function getRedirectTarget() {
166 $this->loadFile();
167 if ( $this->img->isLocal() ) {
168 return parent::getRedirectTarget();
169 }
170 // Foreign image page
171 $from = $this->img->getRedirected();
172 $to = $this->img->getName();
173 if ( $from == $to ) {
174 return null;
175 }
176 return $this->mRedirectTarget = Title::makeTitle( NS_FILE, $to );
177 }
178
179 public function followRedirect() {
180 $this->loadFile();
181 if ( $this->img->isLocal() ) {
182 return parent::followRedirect();
183 }
184 $from = $this->img->getRedirected();
185 $to = $this->img->getName();
186 if ( $from == $to ) {
187 return false;
188 }
189 return Title::makeTitle( NS_FILE, $to );
190 }
191
192 public function isRedirect( $text = false ) {
193 $this->loadFile();
194 if ( $this->img->isLocal() )
195 return parent::isRedirect( $text );
196
197 return (bool)$this->img->getRedirected();
198 }
199
200 public function isLocal() {
201 $this->loadFile();
202 return $this->img->isLocal();
203 }
204
205 public function getFile() {
206 $this->loadFile();
207 return $this->img;
208 }
209
210 public function getDisplayedFile() {
211 $this->loadFile();
212 return $this->displayImg;
213 }
214
215 public function getDuplicates() {
216 $this->loadFile();
217 if ( !is_null( $this->dupes ) ) {
218 return $this->dupes;
219 }
220 if ( !( $hash = $this->img->getSha1() ) ) {
221 return $this->dupes = array();
222 }
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] );
233 }
234 return $this->dupes = $dupes;
235
236 }
237
238 /**
239 * Create the TOC
240 *
241 * @param $metadata Boolean: whether or not to show the metadata link
242 * @return String
243 */
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>',
249 );
250 if ( $metadata ) {
251 $r[] = '<li><a href="#metadata">' . wfMsgHtml( 'metadata' ) . '</a></li>';
252 }
253
254 wfRunHooks( 'ImagePageShowTOC', array( $this, &$r ) );
255
256 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
257 }
258
259 /**
260 * Make a table with metadata to be shown in the output page.
261 *
262 * FIXME: bad interface, see note on MediaHandler::formatMetadata().
263 *
264 * @param $metadata Array: the array containing the EXIF data
265 * @return String
266 */
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';
277 }
278 $r .= "<tr class=\"$class\">\n";
279 $r .= "<th>{$v['name']}</th>\n";
280 $r .= "<td>{$v['value']}</td>\n</tr>";
281 }
282 }
283 $r .= "</table>\n</div>\n";
284 return $r;
285 }
286
287 /**
288 * Overloading Article's getContent method.
289 *
290 * Omit noarticletext if sharedupload; text will be fetched from the
291 * shared upload server if possible.
292 */
293 public function getContent() {
294 $this->loadFile();
295 if ( $this->img && !$this->img->isLocal() && 0 == $this->getID() ) {
296 return '';
297 }
298 return parent::getContent();
299 }
300
301 protected function openShowImage() {
302 global $wgOut, $wgUser, $wgImageLimits, $wgRequest,
303 $wgLang, $wgContLang, $wgEnableUploads;
304
305 $this->loadFile();
306
307 $sizeSel = intval( $wgUser->getOption( 'imagesize' ) );
308 if ( !isset( $wgImageLimits[$sizeSel] ) ) {
309 $sizeSel = User::getDefaultOption( 'imagesize' );
310
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;
316 }
317 }
318 $max = $wgImageLimits[$sizeSel];
319 $maxWidth = $max[0];
320 $maxHeight = $max[1];
321 $sk = $wgUser->getSkin();
322 $dirmark = $wgContLang->getDirMark();
323
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 );
332 }
333 $width_orig = $this->displayImg->getWidth( $page );
334 $width = $width_orig;
335 $height_orig = $this->displayImg->getHeight( $page );
336 $height = $height_orig;
337
338 $longDesc = wfMsg( 'parentheses', $this->displayImg->getLongDesc() );
339
340 wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this, &$wgOut ) );
341
342 if ( $this->displayImg->allowInlineDisplay() ) {
343 # image
344
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.
361 }
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] );
368 }
369 }
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' ) );
378 }
379
380 $params['width'] = $width;
381 $params['height'] = $height;
382 $thumbnail = $this->displayImg->transform( $params );
383
384 $showLink = true;
385 $anchorclose = "<br />" . $msgsmall;
386
387 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
388 if ( $isMulti ) {
389 $wgOut->addHTML( '<table class="multipageimage"><tr><td>' );
390 }
391
392 if ( $thumbnail ) {
393 $options = array(
394 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
395 'file-link' => true,
396 );
397 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
398 $thumbnail->toHtml( $options ) .
399 $anchorclose . "</div>\n" );
400 }
401
402 if ( $isMulti ) {
403 $count = $this->displayImg->pageCount();
404
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' )
413 );
414 $thumb1 = $sk->makeThumbLinkObj( $this->mTitle, $this->displayImg, $link, $label, 'none',
415 array( 'page' => $page - 1 ) );
416 } else {
417 $thumb1 = '';
418 }
419
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' )
428 );
429 $thumb2 = $sk->makeThumbLinkObj( $this->mTitle, $this->displayImg, $link, $label, 'none',
430 array( 'page' => $page + 1 ) );
431 } else {
432 $thumb2 = '';
433 }
434
435 global $wgScript;
436
437 $formParams = array(
438 'name' => 'pageselector',
439 'action' => $wgScript,
440 'onchange' => 'document.pageselector.submit();',
441 );
442
443 for ( $i = 1; $i <= $count; $i++ ) {
444 $options[] = Xml::option( $wgLang->formatNum( $i ), $i, $i == $page );
445 }
446 $select = Xml::tags( 'select',
447 array( 'id' => 'pageselector', 'name' => 'page' ),
448 implode( "\n", $options ) );
449
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>"
458 );
459 }
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();
464
465 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
466 $icon->toHtml( array( 'file-link' => true ) ) .
467 "</div>\n" );
468 }
469
470 $showLink = true;
471 }
472
473
474 if ( $showLink ) {
475 $filename = wfEscapeWikiText( $this->displayImg->getName() );
476 $linktext = $filename;
477 if ( isset( $msgbig ) ) {
478 $linktext = wfEscapeWikiText( $msgbig );
479 }
480 $medialink = "[[Media:$filename|$linktext]]";
481
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>
487 EOT
488 );
489 } else {
490 $wgOut->addWikiText( <<<EOT
491 <div class="fullMedia">{$medialink}{$dirmark} <span class="fileInfo">$longDesc</span>
492 </div>
493 EOT
494 );
495 }
496 }
497
498 if ( !$this->displayImg->isLocal() ) {
499 $this->printSharedImageText();
500 }
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() ) )
509 );
510 }
511 else
512 {
513 $nofile = 'filepage-nofile';
514 }
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.x 404 Not Found" );
524 }
525 }
526 }
527
528 /**
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
533 */
534 private function makeSizeLink( $params, $width, $height ) {
535 global $wgLang;
536
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 '';
549 }
550 }
551
552 /**
553 * Show a notice that the file is from a shared repository
554 */
555 protected function printSharedImageText() {
556 global $wgOut;
557
558 $this->loadFile();
559
560 $descUrl = $this->img->getDescriptionUrl();
561 $descText = $this->img->getDescriptionText();
562
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 ) );
566 }
567
568 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
569 $repo = $this->img->getRepo()->getDisplayName();
570
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*/ );
577 }
578
579 if ( $descText ) {
580 $this->mExtraDescription = $descText;
581 }
582 }
583
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 ) );
591 }
592
593 /**
594 * Print out the various links at the bottom of the image page, e.g. reupload,
595 * external editing (and instructions link) etc.
596 */
597 protected function uploadLinksBox() {
598 global $wgUser, $wgOut, $wgEnableUploads, $wgUseExternalEditor;
599
600 if ( !$wgEnableUploads ) {
601 return;
602 }
603
604 $this->loadFile();
605 if ( !$this->img->isLocal() )
606 return;
607
608 $sk = $wgUser->getSkin();
609
610 $wgOut->addHTML( "<br /><ul>\n" );
611
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" );
616 }
617
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'
628 ),
629 array( 'known', 'noclasses' )
630 );
631 $wgOut->addHTML( '<li id="mw-imagepage-edit-external">' . $elink . ' <small>' . wfMsgExt( 'edit-externally-help', array( 'parseinline' ) ) . "</small></li>\n" );
632 }
633
634 $wgOut->addHTML( "</ul>\n" );
635 }
636
637 protected function closeShowImage() { } # For overloading
638
639 /**
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.
642 */
643 protected function imageHistory() {
644 global $wgOut;
645
646 $this->loadFile();
647 $pager = new ImageHistoryPseudoPager( $this );
648 $wgOut->addHTML( $pager->getBody() );
649 $wgOut->preventClickjacking( $pager->getPreventClickjacking() );
650
651 $this->img->resetHistory(); // free db resources
652
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();
657 }
658 }
659
660 protected function imageLinks() {
661 global $wgUser, $wgOut, $wgLang;
662
663 $limit = 100;
664
665 $dbr = wfGetDB( DB_SLAVE );
666
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 )
673 );
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;
678 }
679
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()
688 );
689 }
690
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;
700 }
701 }
702
703 // Sort the list by namespace:title
704 usort ( $elements, array( $this, 'compare' ) );
705
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"
714 );
715
716 };
717 $wgOut->addHTML( Html::closeElement( 'ul' ) . "\n" );
718 $res->free();
719
720 // Add a links to [[Special:Whatlinkshere]]
721 if ( $count > $limit ) {
722 $wgOut->addWikiMsg( 'morelinkstoimage', $this->mTitle->getPrefixedDBkey() );
723 }
724 $wgOut->addHTML( Html::closeElement( 'div' ) . "\n" );
725 }
726
727 protected function imageRedirects() {
728 global $wgUser, $wgOut, $wgLang;
729
730 $redirects = $this->getTitle()->getRedirectsHere( NS_FILE );
731 if ( count( $redirects ) == 0 ) return;
732
733 $wgOut->addHTML( "<div id='mw-imagepage-section-redirectstofile'>\n" );
734 $wgOut->addWikiMsg( 'redirectstofile',
735 $wgLang->formatNum( count( $redirects ) )
736 );
737 $wgOut->addHTML( "<ul class='mw-imagepage-redirectstofile'>\n" );
738
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' )
747 );
748 $wgOut->addHTML( "<li>{$link}</li>\n" );
749 }
750 $wgOut->addHTML( "</ul></div>\n" );
751
752 }
753
754 protected function imageDupes() {
755 global $wgOut, $wgUser, $wgLang;
756
757 $this->loadFile();
758
759 $dupes = $this->getDuplicates();
760 if ( count( $dupes ) == 0 ) {
761 return;
762 }
763
764 $wgOut->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
765 $wgOut->addWikiMsg( 'duplicatesoffile',
766 $wgLang->formatNum( count( $dupes ) ), $this->mTitle->getDBkey()
767 );
768 $wgOut->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
769
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' )
780 );
781 } else {
782 $link = $sk->makeExternalLink( $file->getDescriptionUrl(),
783 $file->getTitle()->getPrefixedText() );
784 $fromSrc = wfMsg( 'shared-repo-from', $file->getRepo()->getDisplayName() );
785 }
786 $wgOut->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
787 }
788 $wgOut->addHTML( "</ul></div>\n" );
789 }
790
791 /**
792 * Delete the file, or an earlier version of it
793 */
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;
800 }
801
802 $this->loadFile();
803 if ( !$this->img->exists() || !$this->img->isLocal() || $this->img->getRedirected() ) {
804 // Standard article deletion
805 parent::delete();
806 return;
807 }
808 $deleter = new FileDeleteForm( $this->img );
809 $deleter->execute();
810 }
811
812 /**
813 * Revert the file to an earlier version
814 */
815 public function revert() {
816 $this->loadFile();
817 $reverter = new FileRevertForm( $this->img );
818 $reverter->execute();
819 }
820
821 /**
822 * Override handling of action=purge
823 */
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();
837 }
838 parent::doPurge();
839 }
840
841 /**
842 * Display an error with a wikitext description
843 */
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 );
851 }
852
853 /**
854 * Callback for usort() to do link sorts by (namespace, title)
855 * Function copied from Title::compare()
856 *
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
860 */
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;
866 }
867 }
868 }
869
870 /**
871 * Builds the image revision log shown on image pages
872 *
873 * @ingroup Media
874 */
875 class ImageHistoryList {
876
877 /**
878 * @var Title
879 */
880 protected $title;
881
882 /**
883 * @var File
884 */
885 protected $img;
886
887 /**
888 * @var ImagePage
889 */
890 protected $imagePage;
891
892 /**
893 * @var Skin
894 */
895 protected $skin;
896
897 protected $repo, $showThumb;
898 protected $preventClickjacking = false;
899
900 /**
901 * @param ImagePage $imagePage
902 */
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();
911 }
912
913 public function getImagePage() {
914 return $this->imagePage;
915 }
916
917 public function getSkin() {
918 return $this->skin;
919 }
920
921 public function getFile() {
922 return $this->img;
923 }
924
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->isAllowed( 'delete' ) || $wgUser->isAllowed( '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";
940 }
941
942 public function endImageHistoryList( $navLinks = '' ) {
943 return "</table>\n$navLinks\n</div>\n";
944 }
945
946 /**
947 * @param $iscur
948 * @param File $file
949 * @return string
950 */
951 public function imageHistoryLine( $iscur, $file ) {
952 global $wgUser, $wgLang;
953
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();
959
960 $local = $this->current->isLocal();
961 $row = $selected = '';
962
963 // Deletion link
964 if ( $local && ( $wgUser->isAllowed( 'delete' ) || $wgUser->isAllowed( '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' )
975 );
976 }
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 />';
982 }
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,
992 );
993 $del = $this->skin->revDeleteLink( $query,
994 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
995 }
996 $row .= $del;
997 }
998 $row .= '</td>';
999 }
1000
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 )
1017 ),
1018 array( 'known', 'noclasses' )
1019 );
1020 }
1021 }
1022 $row .= '</td>';
1023
1024 // Date/time and image link
1025 if ( $file->getTimestamp() === $this->img->getTimestamp() ) {
1026 $selected = "class='filehistory-selected'";
1027 }
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 )
1044 ),
1045 array( 'known', 'noclasses' )
1046 );
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 ) );
1051 }
1052 $row .= "</td>";
1053
1054 // Thumbnail
1055 if ( $this->showThumb ) {
1056 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1057 }
1058
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>';
1064
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>";
1074 }
1075 } else {
1076 $row .= htmlspecialchars( $usertext );
1077 }
1078 $row .= '</td><td>';
1079
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 );
1085 }
1086 $row .= '</td>';
1087
1088 $rowClass = null;
1089 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1090 $classAttr = $rowClass ? " class='$rowClass'" : "";
1091
1092 return "<tr{$classAttr}>{$row}</tr>\n";
1093 }
1094
1095 /**
1096 * @param File $file
1097 * @return string
1098 */
1099 protected function getThumbForLine( $file ) {
1100 global $wgLang;
1101
1102 if ( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE ) && !$file->isDeleted( File::DELETED_FILE ) ) {
1103 $params = array(
1104 'width' => '120',
1105 'height' => '120',
1106 );
1107 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1108
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,
1116 );
1117
1118 if ( !$thumbnail ) return wfMsgHtml( 'filehist-nothumb' );
1119
1120 return $thumbnail->toHtml( $options );
1121 } else {
1122 return wfMsgHtml( 'filehist-nothumb' );
1123 }
1124 }
1125
1126 protected function preventClickjacking( $enable = true ) {
1127 $this->preventClickjacking = $enable;
1128 }
1129
1130 public function getPreventClickjacking() {
1131 return $this->preventClickjacking;
1132 }
1133 }
1134
1135 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1136 protected $preventClickjacking = false;
1137
1138 /**
1139 * @var File
1140 */
1141 protected $mImg;
1142
1143 /**
1144 * @var Title
1145 */
1146 protected $mTitle;
1147
1148 /**
1149 * @param ImagePage $imagePage
1150 */
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
1159 }
1160
1161 function getTitle() {
1162 return $this->mTitle;
1163 }
1164
1165 function getQueryInfo() {
1166 return false;
1167 }
1168
1169 function getIndexField() {
1170 return '';
1171 }
1172
1173 function formatRow( $row ) {
1174 return '';
1175 }
1176
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 );
1189 }
1190 $s .= $list->endImageHistoryList( $navLink );
1191
1192 if ( $list->getPreventClickjacking() ) {
1193 $this->preventClickjacking();
1194 }
1195 }
1196 return $s;
1197 }
1198
1199 function doQuery() {
1200 if ( $this->mQueryDone ) return;
1201 $this->mImg = $this->mImagePage->getFile(); // ensure loading
1202 if ( !$this->mImg->exists() ) {
1203 return;
1204 }
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 );
1213 }
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;
1218 }
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 ) );
1224 }
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 );
1246 }
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 );
1258 }
1259 } else {
1260 $firstIndex = '';
1261 $lastIndex = '';
1262 $this->mPastTheEndIndex = '';
1263 }
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;
1274 }
1275 $this->mQueryDone = true;
1276 }
1277
1278 protected function preventClickjacking( $enable = true ) {
1279 $this->preventClickjacking = $enable;
1280 }
1281
1282 public function getPreventClickjacking() {
1283 return $this->preventClickjacking;
1284 }
1285
1286 }