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