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