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