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