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