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