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