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