Making missing old files not try to render a thumbnail
[lhc/web/wiklou.git] / includes / page / ImagePage.php
1 <?php
2 /**
3 * Special handling for file description pages.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * Class for viewing MediaWiki file description pages
25 *
26 * @ingroup Media
27 */
28 class ImagePage extends Article {
29 /** @var File */
30 private $displayImg;
31
32 /** @var FileRepo */
33 private $repo;
34
35 /** @var bool */
36 private $fileLoaded;
37
38 /** @var bool */
39 protected $mExtraDescription = false;
40
41 /**
42 * @param Title $title
43 * @return WikiFilePage
44 */
45 protected function newPage( Title $title ) {
46 // Overload mPage with a file-specific page
47 return new WikiFilePage( $title );
48 }
49
50 /**
51 * Constructor from a page id
52 * @param int $id Article ID to load
53 * @return ImagePage|null
54 */
55 public static function newFromID( $id ) {
56 $t = Title::newFromID( $id );
57 # @todo FIXME: Doesn't inherit right
58 return $t == null ? null : new self( $t );
59 # return $t == null ? null : new static( $t ); // PHP 5.3
60 }
61
62 /**
63 * @param File $file
64 * @return void
65 */
66 public function setFile( $file ) {
67 $this->mPage->setFile( $file );
68 $this->displayImg = $file;
69 $this->fileLoaded = true;
70 }
71
72 protected function loadFile() {
73 if ( $this->fileLoaded ) {
74 return;
75 }
76 $this->fileLoaded = true;
77
78 $this->displayImg = $img = false;
79 wfRunHooks( 'ImagePageFindFile', array( $this, &$img, &$this->displayImg ) );
80 if ( !$img ) { // not set by hook?
81 $img = wfFindFile( $this->getTitle() );
82 if ( !$img ) {
83 $img = wfLocalFile( $this->getTitle() );
84 }
85 }
86 $this->mPage->setFile( $img );
87 if ( !$this->displayImg ) { // not set by hook?
88 $this->displayImg = $img;
89 }
90 $this->repo = $img->getRepo();
91 }
92
93 /**
94 * Handler for action=render
95 * Include body text only; none of the image extras
96 */
97 public function render() {
98 $this->getContext()->getOutput()->setArticleBodyOnly( true );
99 parent::view();
100 }
101
102 public function view() {
103 global $wgShowEXIF;
104
105 $out = $this->getContext()->getOutput();
106 $request = $this->getContext()->getRequest();
107 $diff = $request->getVal( 'diff' );
108 $diffOnly = $request->getBool(
109 'diffonly',
110 $this->getContext()->getUser()->getOption( 'diffonly' )
111 );
112
113 if ( $this->getTitle()->getNamespace() != NS_FILE || ( $diff !== null && $diffOnly ) ) {
114 parent::view();
115 return;
116 }
117
118 $this->loadFile();
119
120 if ( $this->getTitle()->getNamespace() == NS_FILE && $this->mPage->getFile()->getRedirected() ) {
121 if ( $this->getTitle()->getDBkey() == $this->mPage->getFile()->getName() || $diff !== null ) {
122 // mTitle is the same as the redirect target so ask Article
123 // to perform the redirect for us.
124 $request->setVal( 'diffonly', 'true' );
125 parent::view();
126 return;
127 } else {
128 // mTitle is not the same as the redirect target so it is
129 // probably the redirect page itself. Fake the redirect symbol
130 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
131 $out->addHTML( $this->viewRedirect(
132 Title::makeTitle( NS_FILE, $this->mPage->getFile()->getName() ),
133 /* $appendSubtitle */ true,
134 /* $forceKnown */ true )
135 );
136 $this->mPage->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
137 return;
138 }
139 }
140
141 if ( $wgShowEXIF && $this->displayImg->exists() ) {
142 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
143 $formattedMetadata = $this->displayImg->formatMetadata();
144 $showmeta = $formattedMetadata !== false;
145 } else {
146 $showmeta = false;
147 }
148
149 if ( !$diff && $this->displayImg->exists() ) {
150 $out->addHTML( $this->showTOC( $showmeta ) );
151 }
152
153 if ( !$diff ) {
154 $this->openShowImage();
155 }
156
157 # No need to display noarticletext, we use our own message, output in openShowImage()
158 if ( $this->mPage->getID() ) {
159 # NS_FILE is in the user language, but this section (the actual wikitext)
160 # should be in page content language
161 $pageLang = $this->getTitle()->getPageViewLanguage();
162 $out->addHTML( Xml::openElement( 'div', array( 'id' => 'mw-imagepage-content',
163 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
164 'class' => 'mw-content-' . $pageLang->getDir() ) ) );
165
166 parent::view();
167
168 $out->addHTML( Xml::closeElement( 'div' ) );
169 } else {
170 # Just need to set the right headers
171 $out->setArticleFlag( true );
172 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
173 $this->mPage->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
174 }
175
176 # Show shared description, if needed
177 if ( $this->mExtraDescription ) {
178 $fol = wfMessage( 'shareddescriptionfollows' );
179 if ( !$fol->isDisabled() ) {
180 $out->addWikiText( $fol->plain() );
181 }
182 $out->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
183 }
184
185 $this->closeShowImage();
186 $this->imageHistory();
187 // TODO: Cleanup the following
188
189 $out->addHTML( Xml::element( 'h2',
190 array( 'id' => 'filelinks' ),
191 wfMessage( 'imagelinks' )->text() ) . "\n" );
192 $this->imageDupes();
193 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
194 # Yet we return metadata about the target. Definitely an issue in the FileRepo
195 $this->imageLinks();
196
197 # Allow extensions to add something after the image links
198 $html = '';
199 wfRunHooks( 'ImagePageAfterImageLinks', array( $this, &$html ) );
200 if ( $html ) {
201 $out->addHTML( $html );
202 }
203
204 if ( $showmeta ) {
205 $out->addHTML( Xml::element(
206 'h2',
207 array( 'id' => 'metadata' ),
208 wfMessage( 'metadata' )->text() ) . "\n" );
209 $out->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
210 $out->addModules( array( 'mediawiki.action.view.metadata' ) );
211 }
212
213 // Add remote Filepage.css
214 if ( !$this->repo->isLocal() ) {
215 $css = $this->repo->getDescriptionStylesheetUrl();
216 if ( $css ) {
217 $out->addStyle( $css );
218 }
219 }
220 // always show the local local Filepage.css, bug 29277
221 $out->addModuleStyles( 'filepage' );
222 }
223
224 /**
225 * @return File
226 */
227 public function getDisplayedFile() {
228 $this->loadFile();
229 return $this->displayImg;
230 }
231
232 /**
233 * Create the TOC
234 *
235 * @param bool $metadata Whether or not to show the metadata link
236 * @return string
237 */
238 protected function showTOC( $metadata ) {
239 $r = array(
240 '<li><a href="#file">' . wfMessage( 'file-anchor-link' )->escaped() . '</a></li>',
241 '<li><a href="#filehistory">' . wfMessage( 'filehist' )->escaped() . '</a></li>',
242 '<li><a href="#filelinks">' . wfMessage( 'imagelinks' )->escaped() . '</a></li>',
243 );
244 if ( $metadata ) {
245 $r[] = '<li><a href="#metadata">' . wfMessage( 'metadata' )->escaped() . '</a></li>';
246 }
247
248 wfRunHooks( 'ImagePageShowTOC', array( $this, &$r ) );
249
250 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
251 }
252
253 /**
254 * Make a table with metadata to be shown in the output page.
255 *
256 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
257 *
258 * @param array $metadata The array containing the Exif data
259 * @return string The metadata table. This is treated as Wikitext (!)
260 */
261 protected function makeMetadataTable( $metadata ) {
262 $r = "<div class=\"mw-imagepage-section-metadata\">";
263 $r .= wfMessage( 'metadata-help' )->plain();
264 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
265 foreach ( $metadata as $type => $stuff ) {
266 foreach ( $stuff as $v ) {
267 # @todo FIXME: Why is this using escapeId for a class?!
268 $class = Sanitizer::escapeId( $v['id'] );
269 if ( $type == 'collapsed' ) {
270 // Handled by mediawiki.action.view.metadata module
271 // and skins/common/shared.css.
272 $class .= ' collapsable';
273 }
274 $r .= "<tr class=\"$class\">\n";
275 $r .= "<th>{$v['name']}</th>\n";
276 $r .= "<td>{$v['value']}</td>\n</tr>";
277 }
278 }
279 $r .= "</table>\n</div>\n";
280 return $r;
281 }
282
283 /**
284 * Overloading Article's getContentObject method.
285 *
286 * Omit noarticletext if sharedupload; text will be fetched from the
287 * shared upload server if possible.
288 * @return string
289 */
290 public function getContentObject() {
291 $this->loadFile();
292 if ( $this->mPage->getFile() && !$this->mPage->getFile()->isLocal() && 0 == $this->getID() ) {
293 return null;
294 }
295 return parent::getContentObject();
296 }
297
298 protected function openShowImage() {
299 global $wgEnableUploads, $wgSend404Code;
300
301 $this->loadFile();
302 $out = $this->getContext()->getOutput();
303 $user = $this->getContext()->getUser();
304 $lang = $this->getContext()->getLanguage();
305 $dirmark = $lang->getDirMarkEntity();
306 $request = $this->getContext()->getRequest();
307
308 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
309 $maxWidth = $max[0];
310 $maxHeight = $max[1];
311
312 if ( $this->displayImg->exists() ) {
313 # image
314 $page = $request->getIntOrNull( 'page' );
315 if ( is_null( $page ) ) {
316 $params = array();
317 $page = 1;
318 } else {
319 $params = array( 'page' => $page );
320 }
321
322 $renderLang = $request->getVal( 'lang' );
323 if ( !is_null( $renderLang ) ) {
324 $handler = $this->displayImg->getHandler();
325 if ( $handler && $handler->validateParam( 'lang', $renderLang ) ) {
326 $params['lang'] = $renderLang;
327 } else {
328 $renderLang = null;
329 }
330 }
331
332 $width_orig = $this->displayImg->getWidth( $page );
333 $width = $width_orig;
334 $height_orig = $this->displayImg->getHeight( $page );
335 $height = $height_orig;
336
337 $filename = wfEscapeWikiText( $this->displayImg->getName() );
338 $linktext = $filename;
339
340 wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this, &$out ) );
341
342 if ( $this->displayImg->allowInlineDisplay() ) {
343 # image
344 # "Download high res version" link below the image
345 # $msgsize = wfMessage( 'file-info-size', $width_orig, $height_orig,
346 # Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
347 # We'll show a thumbnail of this image
348 if ( $width > $maxWidth || $height > $maxHeight || $this->displayImg->isVectorized() ) {
349 list( $width, $height ) = $this->getDisplayWidthHeight(
350 $maxWidth, $maxHeight, $width, $height
351 );
352 $linktext = wfMessage( 'show-big-image' )->escaped();
353
354 $thumbSizes = $this->getThumbSizes( $width, $height, $width_orig, $height_orig );
355 # Generate thumbnails or thumbnail links as needed...
356 $otherSizes = array();
357 foreach ( $thumbSizes as $size ) {
358 // We include a thumbnail size in the list, if it is
359 // less than or equal to the original size of the image
360 // asset ($width_orig/$height_orig). We also exclude
361 // the current thumbnail's size ($width/$height)
362 // since that is added to the message separately, so
363 // it can be denoted as the current size being shown.
364 // Vectorized images are "infinitely" big, so all thumb
365 // sizes are shown.
366 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
367 || $this->displayImg->isVectorized() )
368 && $size[0] != $width && $size[1] != $height
369 ) {
370 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
371 if ( $sizeLink ) {
372 $otherSizes[] = $sizeLink;
373 }
374 }
375 }
376 $otherSizes = array_unique( $otherSizes );
377
378 $msgsmall = '';
379 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
380 if ( $sizeLinkBigImagePreview ) {
381 $msgsmall .= wfMessage( 'show-big-image-preview' )->
382 rawParams( $sizeLinkBigImagePreview )->
383 parse();
384 }
385 if ( count( $otherSizes ) ) {
386 $msgsmall .= ' ' .
387 Html::rawElement( 'span', array( 'class' => 'mw-filepage-other-resolutions' ),
388 wfMessage( 'show-big-image-other' )->rawParams( $lang->pipeList( $otherSizes ) )->
389 params( count( $otherSizes ) )->parse()
390 );
391 }
392 } elseif ( $width == 0 && $height == 0 ) {
393 # Some sort of audio file that doesn't have dimensions
394 # Don't output a no hi res message for such a file
395 $msgsmall = '';
396 } else {
397 # Image is small enough to show full size on image page
398 $msgsmall = wfMessage( 'file-nohires' )->parse();
399 }
400
401 $params['width'] = $width;
402 $params['height'] = $height;
403 $thumbnail = $this->displayImg->transform( $params );
404 Linker::processResponsiveImages( $this->displayImg, $thumbnail, $params );
405
406 $anchorclose = Html::rawElement(
407 'div',
408 array( 'class' => 'mw-filepage-resolutioninfo' ),
409 $msgsmall
410 );
411
412 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
413 if ( $isMulti ) {
414 $out->addModules( 'mediawiki.page.image.pagination' );
415 $out->addHTML( '<table class="multipageimage"><tr><td>' );
416 }
417
418 if ( $thumbnail ) {
419 $options = array(
420 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
421 'file-link' => true,
422 );
423 $out->addHTML( '<div class="fullImageLink" id="file">' .
424 $thumbnail->toHtml( $options ) .
425 $anchorclose . "</div>\n" );
426 }
427
428 if ( $isMulti ) {
429 $count = $this->displayImg->pageCount();
430
431 if ( $page > 1 ) {
432 $label = $out->parse( wfMessage( 'imgmultipageprev' )->text(), false );
433 // on the client side, this link is generated in ajaxifyPageNavigation()
434 // in the mediawiki.page.image.pagination module
435 $link = Linker::linkKnown(
436 $this->getTitle(),
437 $label,
438 array(),
439 array( 'page' => $page - 1 )
440 );
441 $thumb1 = Linker::makeThumbLinkObj(
442 $this->getTitle(),
443 $this->displayImg,
444 $link,
445 $label,
446 'none',
447 array( 'page' => $page - 1 )
448 );
449 } else {
450 $thumb1 = '';
451 }
452
453 if ( $page < $count ) {
454 $label = wfMessage( 'imgmultipagenext' )->text();
455 $link = Linker::linkKnown(
456 $this->getTitle(),
457 $label,
458 array(),
459 array( 'page' => $page + 1 )
460 );
461 $thumb2 = Linker::makeThumbLinkObj(
462 $this->getTitle(),
463 $this->displayImg,
464 $link,
465 $label,
466 'none',
467 array( 'page' => $page + 1 )
468 );
469 } else {
470 $thumb2 = '';
471 }
472
473 global $wgScript;
474
475 $formParams = array(
476 'name' => 'pageselector',
477 'action' => $wgScript,
478 );
479 $options = array();
480 for ( $i = 1; $i <= $count; $i++ ) {
481 $options[] = Xml::option( $lang->formatNum( $i ), $i, $i == $page );
482 }
483 $select = Xml::tags( 'select',
484 array( 'id' => 'pageselector', 'name' => 'page' ),
485 implode( "\n", $options ) );
486
487 $out->addHTML(
488 '</td><td><div class="multipageimagenavbox">' .
489 Xml::openElement( 'form', $formParams ) .
490 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
491 wfMessage( 'imgmultigoto' )->rawParams( $select )->parse() .
492 Xml::submitButton( wfMessage( 'imgmultigo' )->text() ) .
493 Xml::closeElement( 'form' ) .
494 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
495 );
496 }
497 } elseif ( $this->displayImg->isSafeFile() ) {
498 # if direct link is allowed but it's not a renderable image, show an icon.
499 $icon = $this->displayImg->iconThumb();
500
501 $out->addHTML( '<div class="fullImageLink" id="file">' .
502 $icon->toHtml( array( 'file-link' => true ) ) .
503 "</div>\n" );
504 }
505
506 $longDesc = wfMessage( 'parentheses', $this->displayImg->getLongDesc() )->text();
507
508 $medialink = "[[Media:$filename|$linktext]]";
509
510 if ( !$this->displayImg->isSafeFile() ) {
511 $warning = wfMessage( 'mediawarning' )->plain();
512 // dirmark is needed here to separate the file name, which
513 // most likely ends in Latin characters, from the description,
514 // which may begin with the file type. In RTL environment
515 // this will get messy.
516 // The dirmark, however, must not be immediately adjacent
517 // to the filename, because it can get copied with it.
518 // See bug 25277.
519 // @codingStandardsIgnoreStart Ignore long line
520 $out->addWikiText( <<<EOT
521 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
522 <div class="mediaWarning">$warning</div>
523 EOT
524 );
525 // @codingStandardsIgnoreEnd
526 } else {
527 $out->addWikiText( <<<EOT
528 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
529 </div>
530 EOT
531 );
532 }
533
534 $renderLangOptions = $this->displayImg->getAvailableLanguages();
535 if ( count( $renderLangOptions ) >= 1 ) {
536 $currentLanguage = $renderLang;
537 $defaultLang = $this->displayImg->getDefaultRenderLanguage();
538 if ( is_null( $currentLanguage ) ) {
539 $currentLanguage = $defaultLang;
540 }
541 $out->addHtml( $this->doRenderLangOpt( $renderLangOptions, $currentLanguage, $defaultLang ) );
542 }
543
544 // Add cannot animate thumbnail warning
545 if ( !$this->displayImg->canAnimateThumbIfAppropriate() ) {
546 // Include the extension so wiki admins can
547 // customize it on a per file-type basis
548 // (aka say things like use format X instead).
549 // additionally have a specific message for
550 // file-no-thumb-animation-gif
551 $ext = $this->displayImg->getExtension();
552 $noAnimMesg = wfMessageFallback(
553 'file-no-thumb-animation-' . $ext,
554 'file-no-thumb-animation'
555 )->plain();
556
557 $out->addWikiText( <<<EOT
558 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
559 EOT
560 );
561 }
562
563 if ( !$this->displayImg->isLocal() ) {
564 $this->printSharedImageText();
565 }
566 } else {
567 # Image does not exist
568 if ( !$this->getID() ) {
569 # No article exists either
570 # Show deletion log to be consistent with normal articles
571 LogEventsList::showLogExtract(
572 $out,
573 array( 'delete', 'move' ),
574 $this->getTitle()->getPrefixedText(),
575 '',
576 array( 'lim' => 10,
577 'conds' => array( "log_action != 'revision'" ),
578 'showIfEmpty' => false,
579 'msgKey' => array( 'moveddeleted-notice' )
580 )
581 );
582 }
583
584 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
585 // Only show an upload link if the user can upload
586 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
587 $nofile = array(
588 'filepage-nofile-link',
589 $uploadTitle->getFullURL( array( 'wpDestFile' => $this->mPage->getFile()->getName() ) )
590 );
591 } else {
592 $nofile = 'filepage-nofile';
593 }
594 // Note, if there is an image description page, but
595 // no image, then this setRobotPolicy is overridden
596 // by Article::View().
597 $out->setRobotPolicy( 'noindex,nofollow' );
598 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
599 if ( !$this->getID() && $wgSend404Code ) {
600 // If there is no image, no shared image, and no description page,
601 // output a 404, to be consistent with articles.
602 $request->response()->header( 'HTTP/1.1 404 Not Found' );
603 }
604 }
605 $out->setFileVersion( $this->displayImg );
606 }
607
608 /**
609 * Creates an thumbnail of specified size and returns an HTML link to it
610 * @param array $params Scaler parameters
611 * @param int $width
612 * @param int $height
613 * @return string
614 */
615 private function makeSizeLink( $params, $width, $height ) {
616 $params['width'] = $width;
617 $params['height'] = $height;
618 $thumbnail = $this->displayImg->transform( $params );
619 if ( $thumbnail && !$thumbnail->isError() ) {
620 return Html::rawElement( 'a', array(
621 'href' => $thumbnail->getUrl(),
622 'class' => 'mw-thumbnail-link'
623 ), wfMessage( 'show-big-image-size' )->numParams(
624 $thumbnail->getWidth(), $thumbnail->getHeight()
625 )->parse() );
626 } else {
627 return '';
628 }
629 }
630
631 /**
632 * Show a notice that the file is from a shared repository
633 */
634 protected function printSharedImageText() {
635 $out = $this->getContext()->getOutput();
636 $this->loadFile();
637
638 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
639 $descText = $this->mPage->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
640
641 /* Add canonical to head if there is no local page for this shared file */
642 if ( $descUrl && $this->mPage->getID() == 0 ) {
643 $out->setCanonicalUrl( $descUrl );
644 }
645
646 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
647 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
648
649 if ( $descUrl && $descText && wfMessage( 'sharedupload-desc-here' )->plain() !== '-' ) {
650 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
651 } elseif ( $descUrl && wfMessage( 'sharedupload-desc-there' )->plain() !== '-' ) {
652 $out->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
653 } else {
654 $out->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
655 }
656
657 if ( $descText ) {
658 $this->mExtraDescription = $descText;
659 }
660 }
661
662 public function getUploadUrl() {
663 $this->loadFile();
664 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
665 return $uploadTitle->getFullURL( array(
666 'wpDestFile' => $this->mPage->getFile()->getName(),
667 'wpForReUpload' => 1
668 ) );
669 }
670
671 /**
672 * Print out the various links at the bottom of the image page, e.g. reupload,
673 * external editing (and instructions link) etc.
674 */
675 protected function uploadLinksBox() {
676 global $wgEnableUploads;
677
678 if ( !$wgEnableUploads ) {
679 return;
680 }
681
682 $this->loadFile();
683 if ( !$this->mPage->getFile()->isLocal() ) {
684 return;
685 }
686
687 $out = $this->getContext()->getOutput();
688 $out->addHTML( "<ul>\n" );
689
690 # "Upload a new version of this file" link
691 $canUpload = $this->getTitle()->userCan( 'upload', $this->getContext()->getUser() );
692 if ( $canUpload && UploadBase::userCanReUpload(
693 $this->getContext()->getUser(),
694 $this->mPage->getFile()->name )
695 ) {
696 $ulink = Linker::makeExternalLink(
697 $this->getUploadUrl(),
698 wfMessage( 'uploadnewversion-linktext' )->text()
699 );
700 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\">"
701 . "<div class=\"plainlinks\">{$ulink}</div></li>\n" );
702 } else {
703 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">"
704 . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
705 }
706
707 $out->addHTML( "</ul>\n" );
708 }
709
710 /**
711 * For overloading
712 */
713 protected function closeShowImage() {
714 }
715
716 /**
717 * If the page we've just displayed is in the "Image" namespace,
718 * we follow it with an upload history of the image and its usage.
719 */
720 protected function imageHistory() {
721 $this->loadFile();
722 $out = $this->getContext()->getOutput();
723 $pager = new ImageHistoryPseudoPager( $this );
724 $out->addHTML( $pager->getBody() );
725 $out->preventClickjacking( $pager->getPreventClickjacking() );
726
727 $this->mPage->getFile()->resetHistory(); // free db resources
728
729 # Exist check because we don't want to show this on pages where an image
730 # doesn't exist along with the noimage message, that would suck. -ævar
731 if ( $this->mPage->getFile()->exists() ) {
732 $this->uploadLinksBox();
733 }
734 }
735
736 /**
737 * @param string $target
738 * @param int $limit
739 * @return ResultWrapper
740 */
741 protected function queryImageLinks( $target, $limit ) {
742 $dbr = wfGetDB( DB_SLAVE );
743
744 return $dbr->select(
745 array( 'imagelinks', 'page' ),
746 array( 'page_namespace', 'page_title', 'il_to' ),
747 array( 'il_to' => $target, 'il_from = page_id' ),
748 __METHOD__,
749 array( 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', )
750 );
751 }
752
753 protected function imageLinks() {
754 $limit = 100;
755
756 $out = $this->getContext()->getOutput();
757
758 $rows = array();
759 $redirects = array();
760 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE ) as $redir ) {
761 $redirects[$redir->getDBkey()] = array();
762 $rows[] = (object)array(
763 'page_namespace' => NS_FILE,
764 'page_title' => $redir->getDBkey(),
765 );
766 }
767
768 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit + 1 );
769 foreach ( $res as $row ) {
770 $rows[] = $row;
771 }
772 $count = count( $rows );
773
774 $hasMore = $count > $limit;
775 if ( !$hasMore && count( $redirects ) ) {
776 $res = $this->queryImageLinks( array_keys( $redirects ),
777 $limit - count( $rows ) + 1 );
778 foreach ( $res as $row ) {
779 $redirects[$row->il_to][] = $row;
780 $count++;
781 }
782 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
783 }
784
785 if ( $count == 0 ) {
786 $out->wrapWikiMsg(
787 Html::rawElement( 'div',
788 array( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ),
789 'nolinkstoimage'
790 );
791 return;
792 }
793
794 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
795 if ( !$hasMore ) {
796 $out->addWikiMsg( 'linkstoimage', $count );
797 } else {
798 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
799 $out->addWikiMsg( 'linkstoimage-more',
800 $this->getContext()->getLanguage()->formatNum( $limit ),
801 $this->getTitle()->getPrefixedDBkey()
802 );
803 }
804
805 $out->addHTML(
806 Html::openElement( 'ul',
807 array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n"
808 );
809 $count = 0;
810
811 // Sort the list by namespace:title
812 usort( $rows, array( $this, 'compare' ) );
813
814 // Create links for every element
815 $currentCount = 0;
816 foreach ( $rows as $element ) {
817 $currentCount++;
818 if ( $currentCount > $limit ) {
819 break;
820 }
821
822 $query = array();
823 # Add a redirect=no to make redirect pages reachable
824 if ( isset( $redirects[$element->page_title] ) ) {
825 $query['redirect'] = 'no';
826 }
827 $link = Linker::linkKnown(
828 Title::makeTitle( $element->page_namespace, $element->page_title ),
829 null, array(), $query
830 );
831 if ( !isset( $redirects[$element->page_title] ) ) {
832 # No redirects
833 $liContents = $link;
834 } elseif ( count( $redirects[$element->page_title] ) === 0 ) {
835 # Redirect without usages
836 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams( $link, '' )->parse();
837 } else {
838 # Redirect with usages
839 $li = '';
840 foreach ( $redirects[$element->page_title] as $row ) {
841 $currentCount++;
842 if ( $currentCount > $limit ) {
843 break;
844 }
845
846 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
847 $li .= Html::rawElement(
848 'li',
849 array( 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
850 $link2
851 ) . "\n";
852 }
853
854 $ul = Html::rawElement(
855 'ul',
856 array( 'class' => 'mw-imagepage-redirectstofile' ),
857 $li
858 ) . "\n";
859 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams(
860 $link, $ul )->parse();
861 }
862 $out->addHTML( Html::rawElement(
863 'li',
864 array( 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
865 $liContents
866 ) . "\n"
867 );
868
869 };
870 $out->addHTML( Html::closeElement( 'ul' ) . "\n" );
871 $res->free();
872
873 // Add a links to [[Special:Whatlinkshere]]
874 if ( $count > $limit ) {
875 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
876 }
877 $out->addHTML( Html::closeElement( 'div' ) . "\n" );
878 }
879
880 protected function imageDupes() {
881 $this->loadFile();
882 $out = $this->getContext()->getOutput();
883
884 $dupes = $this->mPage->getDuplicates();
885 if ( count( $dupes ) == 0 ) {
886 return;
887 }
888
889 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
890 $out->addWikiMsg( 'duplicatesoffile',
891 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
892 );
893 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
894
895 /**
896 * @var $file File
897 */
898 foreach ( $dupes as $file ) {
899 $fromSrc = '';
900 if ( $file->isLocal() ) {
901 $link = Linker::linkKnown( $file->getTitle() );
902 } else {
903 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
904 $file->getTitle()->getPrefixedText() );
905 $fromSrc = wfMessage( 'shared-repo-from', $file->getRepo()->getDisplayName() )->text();
906 }
907 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
908 }
909 $out->addHTML( "</ul></div>\n" );
910 }
911
912 /**
913 * Delete the file, or an earlier version of it
914 */
915 public function delete() {
916 $file = $this->mPage->getFile();
917 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
918 // Standard article deletion
919 parent::delete();
920 return;
921 }
922
923 $deleter = new FileDeleteForm( $file );
924 $deleter->execute();
925 }
926
927 /**
928 * Display an error with a wikitext description
929 *
930 * @param string $description
931 */
932 function showError( $description ) {
933 $out = $this->getContext()->getOutput();
934 $out->setPageTitle( wfMessage( 'internalerror' ) );
935 $out->setRobotPolicy( 'noindex,nofollow' );
936 $out->setArticleRelated( false );
937 $out->enableClientCache( false );
938 $out->addWikiText( $description );
939 }
940
941 /**
942 * Callback for usort() to do link sorts by (namespace, title)
943 * Function copied from Title::compare()
944 *
945 * @param object $a Object page to compare with
946 * @param object $b Object page to compare with
947 * @return int Result of string comparison, or namespace comparison
948 */
949 protected function compare( $a, $b ) {
950 if ( $a->page_namespace == $b->page_namespace ) {
951 return strcmp( $a->page_title, $b->page_title );
952 } else {
953 return $a->page_namespace - $b->page_namespace;
954 }
955 }
956
957 /**
958 * Returns the corresponding $wgImageLimits entry for the selected user option
959 *
960 * @param User $user
961 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
962 * @return array
963 * @since 1.21
964 */
965 public function getImageLimitsFromOption( $user, $optionName ) {
966 global $wgImageLimits;
967
968 $option = $user->getIntOption( $optionName );
969 if ( !isset( $wgImageLimits[$option] ) ) {
970 $option = User::getDefaultOption( $optionName );
971 }
972
973 // The user offset might still be incorrect, specially if
974 // $wgImageLimits got changed (see bug #8858).
975 if ( !isset( $wgImageLimits[$option] ) ) {
976 // Default to the first offset in $wgImageLimits
977 $option = 0;
978 }
979
980 return isset( $wgImageLimits[$option] )
981 ? $wgImageLimits[$option]
982 : array( 800, 600 ); // if nothing is set, fallback to a hardcoded default
983 }
984
985 /**
986 * Output a drop-down box for language options for the file
987 *
988 * @param array $langChoices Array of string language codes
989 * @param string $curLang Language code file is being viewed in.
990 * @param string $defaultLang Language code that image is rendered in by default
991 * @return string HTML to insert underneath image.
992 */
993 protected function doRenderLangOpt( array $langChoices, $curLang, $defaultLang ) {
994 global $wgScript;
995 sort( $langChoices );
996 $curLang = wfBCP47( $curLang );
997 $defaultLang = wfBCP47( $defaultLang );
998 $opts = '';
999 $haveCurrentLang = false;
1000 $haveDefaultLang = false;
1001
1002 // We make a list of all the language choices in the file.
1003 // Additionally if the default language to render this file
1004 // is not included as being in this file (for example, in svgs
1005 // usually the fallback content is the english content) also
1006 // include a choice for that. Last of all, if we're viewing
1007 // the file in a language not on the list, add it as a choice.
1008 foreach ( $langChoices as $lang ) {
1009 $code = wfBCP47( $lang );
1010 $name = Language::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1011 if ( $name !== '' ) {
1012 $display = wfMessage( 'img-lang-opt', $code, $name )->text();
1013 } else {
1014 $display = $code;
1015 }
1016 $opts .= "\n" . Xml::option( $display, $code, $curLang === $code );
1017 if ( $curLang === $code ) {
1018 $haveCurrentLang = true;
1019 }
1020 if ( $defaultLang === $code ) {
1021 $haveDefaultLang = true;
1022 }
1023 }
1024 if ( !$haveDefaultLang ) {
1025 // Its hard to know if the content is really in the default language, or
1026 // if its just unmarked content that could be in any language.
1027 $opts = Xml::option(
1028 wfMessage( 'img-lang-default' )->text(),
1029 $defaultLang,
1030 $defaultLang === $curLang
1031 ) . $opts;
1032 }
1033 if ( !$haveCurrentLang && $defaultLang !== $curLang ) {
1034 $name = Language::fetchLanguageName( $curLang, $this->getContext()->getLanguage()->getCode() );
1035 if ( $name !== '' ) {
1036 $display = wfMessage( 'img-lang-opt', $curLang, $name )->text();
1037 } else {
1038 $display = $curLang;
1039 }
1040 $opts = Xml::option( $display, $curLang, true ) . $opts;
1041 }
1042
1043 $select = Html::rawElement(
1044 'select',
1045 array( 'id' => 'mw-imglangselector', 'name' => 'lang' ),
1046 $opts
1047 );
1048 $submit = Xml::submitButton( wfMessage( 'img-lang-go' )->text() );
1049
1050 $formContents = wfMessage( 'img-lang-info' )->rawParams( $select, $submit )->parse()
1051 . Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1052
1053 $langSelectLine = Html::rawElement( 'div', array( 'id' => 'mw-imglangselector-line' ),
1054 Html::rawElement( 'form', array( 'action' => $wgScript ), $formContents )
1055 );
1056 return $langSelectLine;
1057 }
1058
1059 /**
1060 * Get the width and height to display image at.
1061 *
1062 * @note This method assumes that it is only called if one
1063 * of the dimensions are bigger than the max, or if the
1064 * image is vectorized.
1065 *
1066 * @param int $maxWidth Max width to display at
1067 * @param int $maxHeight Max height to display at
1068 * @param int $width Actual width of the image
1069 * @param int $height Actual height of the image
1070 * @throws MWException
1071 * @return array Array (width, height)
1072 */
1073 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1074 if ( !$maxWidth || !$maxHeight ) {
1075 // should never happen
1076 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1077 }
1078
1079 if ( !$width || !$height ) {
1080 return array( 0, 0 );
1081 }
1082
1083 # Calculate the thumbnail size.
1084 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1085 // Vectorized image, do nothing.
1086 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1087 # The limiting factor is the width, not the height.
1088 $height = round( $height * $maxWidth / $width );
1089 $width = $maxWidth;
1090 # Note that $height <= $maxHeight now.
1091 } else {
1092 $newwidth = floor( $width * $maxHeight / $height );
1093 $height = round( $height * $newwidth / $width );
1094 $width = $newwidth;
1095 # Note that $height <= $maxHeight now, but might not be identical
1096 # because of rounding.
1097 }
1098 return array( $width, $height );
1099 }
1100
1101 /**
1102 * Get alternative thumbnail sizes.
1103 *
1104 * @note This will only list several alternatives if thumbnails are rendered on 404
1105 * @param int $origWidth Actual width of image
1106 * @param int $origHeight Actual height of image
1107 * @return array An array of [width, height] pairs.
1108 */
1109 protected function getThumbSizes( $origWidth, $origHeight ) {
1110 global $wgImageLimits;
1111 if ( $this->displayImg->getRepo()->canTransformVia404() ) {
1112 $thumbSizes = $wgImageLimits;
1113 // Also include the full sized resolution in the list, so
1114 // that users know they can get it. This will link to the
1115 // original file asset if mustRender() === false. In the case
1116 // that we mustRender, some users have indicated that they would
1117 // find it useful to have the full size image in the rendered
1118 // image format.
1119 $thumbSizes[] = array( $origWidth, $origHeight );
1120 } else {
1121 # Creating thumb links triggers thumbnail generation.
1122 # Just generate the thumb for the current users prefs.
1123 $thumbSizes = array( $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' ) );
1124 if ( !$this->displayImg->mustRender() ) {
1125 // We can safely include a link to the "full-size" preview,
1126 // without actually rendering.
1127 $thumbSizes[] = array( $origWidth, $origHeight );
1128 }
1129 }
1130 return $thumbSizes;
1131 }
1132
1133 }
1134
1135 /**
1136 * Builds the image revision log shown on image pages
1137 *
1138 * @ingroup Media
1139 */
1140 class ImageHistoryList extends ContextSource {
1141
1142 /**
1143 * @var Title
1144 */
1145 protected $title;
1146
1147 /**
1148 * @var File
1149 */
1150 protected $img;
1151
1152 /**
1153 * @var ImagePage
1154 */
1155 protected $imagePage;
1156
1157 /**
1158 * @var File
1159 */
1160 protected $current;
1161
1162 protected $repo, $showThumb;
1163 protected $preventClickjacking = false;
1164
1165 /**
1166 * @param ImagePage $imagePage
1167 */
1168 public function __construct( $imagePage ) {
1169 global $wgShowArchiveThumbnails;
1170 $this->current = $imagePage->getFile();
1171 $this->img = $imagePage->getDisplayedFile();
1172 $this->title = $imagePage->getTitle();
1173 $this->imagePage = $imagePage;
1174 $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
1175 $this->setContext( $imagePage->getContext() );
1176 }
1177
1178 /**
1179 * @return ImagePage
1180 */
1181 public function getImagePage() {
1182 return $this->imagePage;
1183 }
1184
1185 /**
1186 * @return File
1187 */
1188 public function getFile() {
1189 return $this->img;
1190 }
1191
1192 /**
1193 * @param string $navLinks
1194 * @return string
1195 */
1196 public function beginImageHistoryList( $navLinks = '' ) {
1197 return Xml::element( 'h2', array( 'id' => 'filehistory' ), $this->msg( 'filehist' )->text() )
1198 . "\n"
1199 . "<div id=\"mw-imagepage-section-filehistory\">\n"
1200 . $this->msg( 'filehist-help' )->parseAsBlock()
1201 . $navLinks . "\n"
1202 . Xml::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
1203 . '<tr><td></td>'
1204 . ( $this->current->isLocal()
1205 && ( $this->getUser()->isAllowedAny( 'delete', 'deletedhistory' ) ) ? '<td></td>' : '' )
1206 . '<th>' . $this->msg( 'filehist-datetime' )->escaped() . '</th>'
1207 . ( $this->showThumb ? '<th>' . $this->msg( 'filehist-thumb' )->escaped() . '</th>' : '' )
1208 . '<th>' . $this->msg( 'filehist-dimensions' )->escaped() . '</th>'
1209 . '<th>' . $this->msg( 'filehist-user' )->escaped() . '</th>'
1210 . '<th>' . $this->msg( 'filehist-comment' )->escaped() . '</th>'
1211 . "</tr>\n";
1212 }
1213
1214 /**
1215 * @param string $navLinks
1216 * @return string
1217 */
1218 public function endImageHistoryList( $navLinks = '' ) {
1219 return "</table>\n$navLinks\n</div>\n";
1220 }
1221
1222 /**
1223 * @param bool $iscur
1224 * @param File $file
1225 * @return string
1226 */
1227 public function imageHistoryLine( $iscur, $file ) {
1228 global $wgContLang;
1229
1230 $user = $this->getUser();
1231 $lang = $this->getLanguage();
1232 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1233 $img = $iscur ? $file->getName() : $file->getArchiveName();
1234 $userId = $file->getUser( 'id' );
1235 $userText = $file->getUser( 'text' );
1236 $description = $file->getDescription( File::FOR_THIS_USER, $user );
1237
1238 $local = $this->current->isLocal();
1239 $row = $selected = '';
1240
1241 // Deletion link
1242 if ( $local && ( $user->isAllowedAny( 'delete', 'deletedhistory' ) ) ) {
1243 $row .= '<td>';
1244 # Link to remove from history
1245 if ( $user->isAllowed( 'delete' ) ) {
1246 $q = array( 'action' => 'delete' );
1247 if ( !$iscur ) {
1248 $q['oldimage'] = $img;
1249 }
1250 $row .= Linker::linkKnown(
1251 $this->title,
1252 $this->msg( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' )->escaped(),
1253 array(), $q
1254 );
1255 }
1256 # Link to hide content. Don't show useless link to people who cannot hide revisions.
1257 $canHide = $user->isAllowed( 'deleterevision' );
1258 if ( $canHide || ( $user->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
1259 if ( $user->isAllowed( 'delete' ) ) {
1260 $row .= '<br />';
1261 }
1262 // If file is top revision or locked from this user, don't link
1263 if ( $iscur || !$file->userCan( File::DELETED_RESTRICTED, $user ) ) {
1264 $del = Linker::revDeleteLinkDisabled( $canHide );
1265 } else {
1266 list( $ts, ) = explode( '!', $img, 2 );
1267 $query = array(
1268 'type' => 'oldimage',
1269 'target' => $this->title->getPrefixedText(),
1270 'ids' => $ts,
1271 );
1272 $del = Linker::revDeleteLink( $query,
1273 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
1274 }
1275 $row .= $del;
1276 }
1277 $row .= '</td>';
1278 }
1279
1280 // Reversion link/current indicator
1281 $row .= '<td>';
1282 if ( $iscur ) {
1283 $row .= $this->msg( 'filehist-current' )->escaped();
1284 } elseif ( $local && $this->title->quickUserCan( 'edit', $user )
1285 && $this->title->quickUserCan( 'upload', $user )
1286 ) {
1287 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1288 $row .= $this->msg( 'filehist-revert' )->escaped();
1289 } else {
1290 $row .= Linker::linkKnown(
1291 $this->title,
1292 $this->msg( 'filehist-revert' )->escaped(),
1293 array(),
1294 array(
1295 'action' => 'revert',
1296 'oldimage' => $img,
1297 'wpEditToken' => $user->getEditToken( $img )
1298 )
1299 );
1300 }
1301 }
1302 $row .= '</td>';
1303
1304 // Date/time and image link
1305 if ( $file->getTimestamp() === $this->img->getTimestamp() ) {
1306 $selected = "class='filehistory-selected'";
1307 }
1308 $row .= "<td $selected style='white-space: nowrap;'>";
1309 if ( !$file->userCan( File::DELETED_FILE, $user ) ) {
1310 # Don't link to unviewable files
1311 $row .= '<span class="history-deleted">'
1312 . $lang->userTimeAndDate( $timestamp, $user ) . '</span>';
1313 } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
1314 if ( $local ) {
1315 $this->preventClickjacking();
1316 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
1317 # Make a link to review the image
1318 $url = Linker::linkKnown(
1319 $revdel,
1320 $lang->userTimeAndDate( $timestamp, $user ),
1321 array(),
1322 array(
1323 'target' => $this->title->getPrefixedText(),
1324 'file' => $img,
1325 'token' => $user->getEditToken( $img )
1326 )
1327 );
1328 } else {
1329 $url = $lang->userTimeAndDate( $timestamp, $user );
1330 }
1331 $row .= '<span class="history-deleted">' . $url . '</span>';
1332 } elseif ( !$file->exists() ) {
1333 $row .= '<span class="mw-file-missing">'
1334 . $lang->userTimeAndDate( $timestamp, $user ) . '</span>';
1335 } else {
1336 $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
1337 $row .= Xml::element(
1338 'a',
1339 array( 'href' => $url ),
1340 $lang->userTimeAndDate( $timestamp, $user )
1341 );
1342 }
1343 $row .= "</td>";
1344
1345 // Thumbnail
1346 if ( $this->showThumb ) {
1347 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1348 }
1349
1350 // Image dimensions + size
1351 $row .= '<td>';
1352 $row .= htmlspecialchars( $file->getDimensionsString() );
1353 $row .= $this->msg( 'word-separator' )->escaped();
1354 $row .= '<span style="white-space: nowrap;">';
1355 $row .= $this->msg( 'parentheses' )->sizeParams( $file->getSize() )->escaped();
1356 $row .= '</span>';
1357 $row .= '</td>';
1358
1359 // Uploading user
1360 $row .= '<td>';
1361 // Hide deleted usernames
1362 if ( $file->isDeleted( File::DELETED_USER ) ) {
1363 $row .= '<span class="history-deleted">'
1364 . $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
1365 } else {
1366 if ( $local ) {
1367 $row .= Linker::userLink( $userId, $userText );
1368 $row .= $this->msg( 'word-separator' )->escaped();
1369 $row .= '<span style="white-space: nowrap;">';
1370 $row .= Linker::userToolLinks( $userId, $userText );
1371 $row .= '</span>';
1372 } else {
1373 $row .= htmlspecialchars( $userText );
1374 }
1375 }
1376 $row .= '</td>';
1377
1378 // Don't show deleted descriptions
1379 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1380 $row .= '<td><span class="history-deleted">' .
1381 $this->msg( 'rev-deleted-comment' )->escaped() . '</span></td>';
1382 } else {
1383 $row .= '<td dir="' . $wgContLang->getDir() . '">' .
1384 Linker::formatComment( $description, $this->title ) . '</td>';
1385 }
1386
1387 $rowClass = null;
1388 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1389 $classAttr = $rowClass ? " class='$rowClass'" : '';
1390
1391 return "<tr{$classAttr}>{$row}</tr>\n";
1392 }
1393
1394 /**
1395 * @param File $file
1396 * @return string
1397 */
1398 protected function getThumbForLine( $file ) {
1399 $lang = $this->getLanguage();
1400 $user = $this->getUser();
1401 if ( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE, $user )
1402 && !$file->isDeleted( File::DELETED_FILE )
1403 ) {
1404 $params = array(
1405 'width' => '120',
1406 'height' => '120',
1407 );
1408 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1409
1410 $thumbnail = $file->transform( $params );
1411 $options = array(
1412 'alt' => $this->msg( 'filehist-thumbtext',
1413 $lang->userTimeAndDate( $timestamp, $user ),
1414 $lang->userDate( $timestamp, $user ),
1415 $lang->userTime( $timestamp, $user ) )->text(),
1416 'file-link' => true,
1417 );
1418
1419 if ( !$thumbnail ) {
1420 return $this->msg( 'filehist-nothumb' )->escaped();
1421 }
1422
1423 return $thumbnail->toHtml( $options );
1424 } else {
1425 return $this->msg( 'filehist-nothumb' )->escaped();
1426 }
1427 }
1428
1429 /**
1430 * @param bool $enable
1431 */
1432 protected function preventClickjacking( $enable = true ) {
1433 $this->preventClickjacking = $enable;
1434 }
1435
1436 /**
1437 * @return bool
1438 */
1439 public function getPreventClickjacking() {
1440 return $this->preventClickjacking;
1441 }
1442 }
1443
1444 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1445 protected $preventClickjacking = false;
1446
1447 /**
1448 * @var File
1449 */
1450 protected $mImg;
1451
1452 /**
1453 * @var Title
1454 */
1455 protected $mTitle;
1456
1457 /**
1458 * @param ImagePage $imagePage
1459 */
1460 function __construct( $imagePage ) {
1461 parent::__construct( $imagePage->getContext() );
1462 $this->mImagePage = $imagePage;
1463 $this->mTitle = clone ( $imagePage->getTitle() );
1464 $this->mTitle->setFragment( '#filehistory' );
1465 $this->mImg = null;
1466 $this->mHist = array();
1467 $this->mRange = array( 0, 0 ); // display range
1468 }
1469
1470 /**
1471 * @return Title
1472 */
1473 function getTitle() {
1474 return $this->mTitle;
1475 }
1476
1477 function getQueryInfo() {
1478 return false;
1479 }
1480
1481 /**
1482 * @return string
1483 */
1484 function getIndexField() {
1485 return '';
1486 }
1487
1488 /**
1489 * @param object $row
1490 * @return string
1491 */
1492 function formatRow( $row ) {
1493 return '';
1494 }
1495
1496 /**
1497 * @return string
1498 */
1499 function getBody() {
1500 $s = '';
1501 $this->doQuery();
1502 if ( count( $this->mHist ) ) {
1503 $list = new ImageHistoryList( $this->mImagePage );
1504 # Generate prev/next links
1505 $navLink = $this->getNavigationBar();
1506 $s = $list->beginImageHistoryList( $navLink );
1507 // Skip rows there just for paging links
1508 for ( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1509 $file = $this->mHist[$i];
1510 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1511 }
1512 $s .= $list->endImageHistoryList( $navLink );
1513
1514 if ( $list->getPreventClickjacking() ) {
1515 $this->preventClickjacking();
1516 }
1517 }
1518 return $s;
1519 }
1520
1521 function doQuery() {
1522 if ( $this->mQueryDone ) {
1523 return;
1524 }
1525 $this->mImg = $this->mImagePage->getFile(); // ensure loading
1526 if ( !$this->mImg->exists() ) {
1527 return;
1528 }
1529 $queryLimit = $this->mLimit + 1; // limit plus extra row
1530 if ( $this->mIsBackwards ) {
1531 // Fetch the file history
1532 $this->mHist = $this->mImg->getHistory( $queryLimit, null, $this->mOffset, false );
1533 // The current rev may not meet the offset/limit
1534 $numRows = count( $this->mHist );
1535 if ( $numRows <= $this->mLimit && $this->mImg->getTimestamp() > $this->mOffset ) {
1536 $this->mHist = array_merge( array( $this->mImg ), $this->mHist );
1537 }
1538 } else {
1539 // The current rev may not meet the offset
1540 if ( !$this->mOffset || $this->mImg->getTimestamp() < $this->mOffset ) {
1541 $this->mHist[] = $this->mImg;
1542 }
1543 // Old image versions (fetch extra row for nav links)
1544 $oiLimit = count( $this->mHist ) ? $this->mLimit : $this->mLimit + 1;
1545 // Fetch the file history
1546 $this->mHist = array_merge( $this->mHist,
1547 $this->mImg->getHistory( $oiLimit, $this->mOffset, null, false ) );
1548 }
1549 $numRows = count( $this->mHist ); // Total number of query results
1550 if ( $numRows ) {
1551 # Index value of top item in the list
1552 $firstIndex = $this->mIsBackwards ?
1553 $this->mHist[$numRows - 1]->getTimestamp() : $this->mHist[0]->getTimestamp();
1554 # Discard the extra result row if there is one
1555 if ( $numRows > $this->mLimit && $numRows > 1 ) {
1556 if ( $this->mIsBackwards ) {
1557 # Index value of item past the index
1558 $this->mPastTheEndIndex = $this->mHist[0]->getTimestamp();
1559 # Index value of bottom item in the list
1560 $lastIndex = $this->mHist[1]->getTimestamp();
1561 # Display range
1562 $this->mRange = array( 1, $numRows - 1 );
1563 } else {
1564 # Index value of item past the index
1565 $this->mPastTheEndIndex = $this->mHist[$numRows - 1]->getTimestamp();
1566 # Index value of bottom item in the list
1567 $lastIndex = $this->mHist[$numRows - 2]->getTimestamp();
1568 # Display range
1569 $this->mRange = array( 0, $numRows - 2 );
1570 }
1571 } else {
1572 # Setting indexes to an empty string means that they will be
1573 # omitted if they would otherwise appear in URLs. It just so
1574 # happens that this is the right thing to do in the standard
1575 # UI, in all the relevant cases.
1576 $this->mPastTheEndIndex = '';
1577 # Index value of bottom item in the list
1578 $lastIndex = $this->mIsBackwards ?
1579 $this->mHist[0]->getTimestamp() : $this->mHist[$numRows - 1]->getTimestamp();
1580 # Display range
1581 $this->mRange = array( 0, $numRows - 1 );
1582 }
1583 } else {
1584 $firstIndex = '';
1585 $lastIndex = '';
1586 $this->mPastTheEndIndex = '';
1587 }
1588 if ( $this->mIsBackwards ) {
1589 $this->mIsFirst = ( $numRows < $queryLimit );
1590 $this->mIsLast = ( $this->mOffset == '' );
1591 $this->mLastShown = $firstIndex;
1592 $this->mFirstShown = $lastIndex;
1593 } else {
1594 $this->mIsFirst = ( $this->mOffset == '' );
1595 $this->mIsLast = ( $numRows < $queryLimit );
1596 $this->mLastShown = $lastIndex;
1597 $this->mFirstShown = $firstIndex;
1598 }
1599 $this->mQueryDone = true;
1600 }
1601
1602 /**
1603 * @param bool $enable
1604 */
1605 protected function preventClickjacking( $enable = true ) {
1606 $this->preventClickjacking = $enable;
1607 }
1608
1609 /**
1610 * @return bool
1611 */
1612 public function getPreventClickjacking() {
1613 return $this->preventClickjacking;
1614 }
1615
1616 }