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