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