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