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