SpecialPages: Add ul { margin-top: 0; margin-bottom: 0 } for multicolumn
[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 use Wikimedia\Rdbms\ResultWrapper;
24
25 /**
26 * Class for viewing MediaWiki file description pages
27 *
28 * @ingroup Media
29 */
30 class ImagePage extends Article {
31 /** @var File */
32 private $displayImg;
33
34 /** @var FileRepo */
35 private $repo;
36
37 /** @var bool */
38 private $fileLoaded;
39
40 /** @var bool */
41 protected $mExtraDescription = false;
42
43 /**
44 * @var WikiFilePage
45 */
46 protected $mPage;
47
48 /**
49 * @param Title $title
50 * @return WikiFilePage
51 */
52 protected function newPage( Title $title ) {
53 // Overload mPage with a file-specific page
54 return new WikiFilePage( $title );
55 }
56
57 /**
58 * @param File $file
59 * @return void
60 */
61 public function setFile( $file ) {
62 $this->mPage->setFile( $file );
63 $this->displayImg = $file;
64 $this->fileLoaded = true;
65 }
66
67 protected function loadFile() {
68 if ( $this->fileLoaded ) {
69 return;
70 }
71 $this->fileLoaded = true;
72
73 $this->displayImg = $img = false;
74
75 Hooks::run( 'ImagePageFindFile', [ $this, &$img, &$this->displayImg ] );
76 if ( !$img ) { // not set by hook?
77 $img = wfFindFile( $this->getTitle() );
78 if ( !$img ) {
79 $img = wfLocalFile( $this->getTitle() );
80 }
81 }
82 $this->mPage->setFile( $img );
83 if ( !$this->displayImg ) { // not set by hook?
84 $this->displayImg = $img;
85 }
86 $this->repo = $img->getRepo();
87 }
88
89 /**
90 * Handler for action=render
91 * Include body text only; none of the image extras
92 */
93 public function render() {
94 $this->getContext()->getOutput()->setArticleBodyOnly( true );
95 parent::view();
96 }
97
98 public function view() {
99 global $wgShowEXIF;
100
101 $out = $this->getContext()->getOutput();
102 $request = $this->getContext()->getRequest();
103 $diff = $request->getVal( 'diff' );
104 $diffOnly = $request->getBool(
105 'diffonly',
106 $this->getContext()->getUser()->getOption( 'diffonly' )
107 );
108
109 if ( $this->getTitle()->getNamespace() != NS_FILE || ( $diff !== null && $diffOnly ) ) {
110 parent::view();
111 return;
112 }
113
114 $this->loadFile();
115
116 if ( $this->getTitle()->getNamespace() == NS_FILE && $this->mPage->getFile()->getRedirected() ) {
117 if ( $this->getTitle()->getDBkey() == $this->mPage->getFile()->getName() || $diff !== null ) {
118 $request->setVal( 'diffonly', 'true' );
119 }
120
121 parent::view();
122 return;
123 }
124
125 if ( $wgShowEXIF && $this->displayImg->exists() ) {
126 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
127 $formattedMetadata = $this->displayImg->formatMetadata( $this->getContext() );
128 $showmeta = $formattedMetadata !== false;
129 } else {
130 $showmeta = false;
131 }
132
133 if ( !$diff && $this->displayImg->exists() ) {
134 $out->addHTML( $this->showTOC( $showmeta ) );
135 }
136
137 if ( !$diff ) {
138 $this->openShowImage();
139 }
140
141 # No need to display noarticletext, we use our own message, output in openShowImage()
142 if ( $this->mPage->getId() ) {
143 # NS_FILE is in the user language, but this section (the actual wikitext)
144 # should be in page content language
145 $pageLang = $this->getTitle()->getPageViewLanguage();
146 $out->addHTML( Xml::openElement( 'div', [ 'id' => 'mw-imagepage-content',
147 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
148 'class' => 'mw-content-' . $pageLang->getDir() ] ) );
149
150 parent::view();
151
152 $out->addHTML( Xml::closeElement( 'div' ) );
153 } else {
154 # Just need to set the right headers
155 $out->setArticleFlag( true );
156 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
157 $this->mPage->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
158 }
159
160 # Show shared description, if needed
161 if ( $this->mExtraDescription ) {
162 $fol = $this->getContext()->msg( 'shareddescriptionfollows' );
163 if ( !$fol->isDisabled() ) {
164 $out->addWikiText( $fol->plain() );
165 }
166 $out->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
167 }
168
169 $this->closeShowImage();
170 $this->imageHistory();
171 // TODO: Cleanup the following
172
173 $out->addHTML( Xml::element( 'h2',
174 [ 'id' => 'filelinks' ],
175 $this->getContext()->msg( 'imagelinks' )->text() ) . "\n" );
176 $this->imageDupes();
177 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
178 # Yet we return metadata about the target. Definitely an issue in the FileRepo
179 $this->imageLinks();
180
181 # Allow extensions to add something after the image links
182 $html = '';
183 Hooks::run( 'ImagePageAfterImageLinks', [ $this, &$html ] );
184 if ( $html ) {
185 $out->addHTML( $html );
186 }
187
188 if ( $showmeta ) {
189 $out->addHTML( Xml::element(
190 'h2',
191 [ 'id' => 'metadata' ],
192 $this->getContext()->msg( 'metadata' )->text() ) . "\n" );
193 $out->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
194 $out->addModules( [ 'mediawiki.action.view.metadata' ] );
195 }
196
197 // Add remote Filepage.css
198 if ( !$this->repo->isLocal() ) {
199 $css = $this->repo->getDescriptionStylesheetUrl();
200 if ( $css ) {
201 $out->addStyle( $css );
202 }
203 }
204
205 $out->addModuleStyles( [
206 'filepage', // always show the local local Filepage.css, T31277
207 'mediawiki.action.view.filepage', // Add MediaWiki styles for a file page
208 ] );
209 }
210
211 /**
212 * @return File
213 */
214 public function getDisplayedFile() {
215 $this->loadFile();
216 return $this->displayImg;
217 }
218
219 /**
220 * Create the TOC
221 *
222 * @param bool $metadata Whether or not to show the metadata link
223 * @return string
224 */
225 protected function showTOC( $metadata ) {
226 $r = [
227 '<li><a href="#file">' . $this->getContext()->msg( 'file-anchor-link' )->escaped() . '</a></li>',
228 '<li><a href="#filehistory">' . $this->getContext()->msg( 'filehist' )->escaped() . '</a></li>',
229 '<li><a href="#filelinks">' . $this->getContext()->msg( 'imagelinks' )->escaped() . '</a></li>',
230 ];
231
232 Hooks::run( 'ImagePageShowTOC', [ $this, &$r ] );
233
234 if ( $metadata ) {
235 $r[] = '<li><a href="#metadata">' .
236 $this->getContext()->msg( 'metadata' )->escaped() .
237 '</a></li>';
238 }
239
240 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
241 }
242
243 /**
244 * Make a table with metadata to be shown in the output page.
245 *
246 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
247 *
248 * @param array $metadata The array containing the Exif data
249 * @return string The metadata table. This is treated as Wikitext (!)
250 */
251 protected function makeMetadataTable( $metadata ) {
252 $r = "<div class=\"mw-imagepage-section-metadata\">";
253 $r .= $this->getContext()->msg( 'metadata-help' )->plain();
254 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
255 foreach ( $metadata as $type => $stuff ) {
256 foreach ( $stuff as $v ) {
257 $class = str_replace( ' ', '_', $v['id'] );
258 if ( $type == 'collapsed' ) {
259 // Handled by mediawiki.action.view.metadata module.
260 $class .= ' collapsable';
261 }
262 $r .= Html::rawElement( 'tr',
263 [ 'class' => $class ],
264 Html::rawElement( 'th', [], $v['name'] )
265 . Html::rawElement( 'td', [], $v['value'] )
266 );
267 }
268 }
269 $r .= "</table>\n</div>\n";
270 return $r;
271 }
272
273 /**
274 * Overloading Article's getContentObject method.
275 *
276 * Omit noarticletext if sharedupload; text will be fetched from the
277 * shared upload server if possible.
278 * @return string
279 */
280 public function getContentObject() {
281 $this->loadFile();
282 if ( $this->mPage->getFile() && !$this->mPage->getFile()->isLocal() && 0 == $this->getId() ) {
283 return null;
284 }
285 return parent::getContentObject();
286 }
287
288 private function getLanguageForRendering( WebRequest $request, File $file ) {
289 $handler = $this->displayImg->getHandler();
290 if ( !$handler ) {
291 return null;
292 }
293
294 $requestLanguage = $request->getVal( 'lang' );
295 if ( !is_null( $requestLanguage ) ) {
296 if ( $handler->validateParam( 'lang', $requestLanguage ) ) {
297 return $requestLanguage;
298 }
299 }
300
301 return $handler->getDefaultRenderLanguage( $this->displayImg );
302 }
303
304 protected function openShowImage() {
305 global $wgEnableUploads, $wgSend404Code, $wgSVGMaxSize;
306
307 $this->loadFile();
308 $out = $this->getContext()->getOutput();
309 $user = $this->getContext()->getUser();
310 $lang = $this->getContext()->getLanguage();
311 $dirmark = $lang->getDirMarkEntity();
312 $request = $this->getContext()->getRequest();
313
314 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
315 $maxWidth = $max[0];
316 $maxHeight = $max[1];
317
318 if ( $this->displayImg->exists() ) {
319 # image
320 $page = $request->getIntOrNull( 'page' );
321 if ( is_null( $page ) ) {
322 $params = [];
323 $page = 1;
324 } else {
325 $params = [ 'page' => $page ];
326 }
327
328 $renderLang = $this->getLanguageForRendering( $request, $this->displayImg );
329 if ( !is_null( $renderLang ) ) {
330 $params['lang'] = $renderLang;
331 }
332
333 $width_orig = $this->displayImg->getWidth( $page );
334 $width = $width_orig;
335 $height_orig = $this->displayImg->getHeight( $page );
336 $height = $height_orig;
337
338 $filename = wfEscapeWikiText( $this->displayImg->getName() );
339 $linktext = $filename;
340
341 // Avoid PHP 7.1 warning from passing $this by reference
342 $imagePage = $this;
343
344 Hooks::run( 'ImageOpenShowImageInlineBefore', [ &$imagePage, &$out ] );
345
346 if ( $this->displayImg->allowInlineDisplay() ) {
347 # image
348 # "Download high res version" link below the image
349 # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
350 # Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
351 # We'll show a thumbnail of this image
352 if ( $width > $maxWidth || $height > $maxHeight || $this->displayImg->isVectorized() ) {
353 list( $width, $height ) = $this->getDisplayWidthHeight(
354 $maxWidth, $maxHeight, $width, $height
355 );
356 $linktext = $this->getContext()->msg( 'show-big-image' )->escaped();
357
358 $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
359 # Generate thumbnails or thumbnail links as needed...
360 $otherSizes = [];
361 foreach ( $thumbSizes as $size ) {
362 // We include a thumbnail size in the list, if it is
363 // less than or equal to the original size of the image
364 // asset ($width_orig/$height_orig). We also exclude
365 // the current thumbnail's size ($width/$height)
366 // since that is added to the message separately, so
367 // it can be denoted as the current size being shown.
368 // Vectorized images are limited by $wgSVGMaxSize big,
369 // so all thumbs less than or equal that are shown.
370 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
371 || ( $this->displayImg->isVectorized()
372 && max( $size[0], $size[1] ) <= $wgSVGMaxSize )
373 )
374 && $size[0] != $width && $size[1] != $height
375 ) {
376 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
377 if ( $sizeLink ) {
378 $otherSizes[] = $sizeLink;
379 }
380 }
381 }
382 $otherSizes = array_unique( $otherSizes );
383
384 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
385 $msgsmall = $this->getThumbPrevText( $params, $sizeLinkBigImagePreview );
386 if ( count( $otherSizes ) ) {
387 $msgsmall .= ' ' .
388 Html::rawElement(
389 'span',
390 [ 'class' => 'mw-filepage-other-resolutions' ],
391 $this->getContext()->msg( 'show-big-image-other' )
392 ->rawParams( $lang->pipeList( $otherSizes ) )
393 ->params( count( $otherSizes ) )
394 ->parse()
395 );
396 }
397 } elseif ( $width == 0 && $height == 0 ) {
398 # Some sort of audio file that doesn't have dimensions
399 # Don't output a no hi res message for such a file
400 $msgsmall = '';
401 } else {
402 # Image is small enough to show full size on image page
403 $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
404 }
405
406 $params['width'] = $width;
407 $params['height'] = $height;
408 $thumbnail = $this->displayImg->transform( $params );
409 Linker::processResponsiveImages( $this->displayImg, $thumbnail, $params );
410
411 $anchorclose = Html::rawElement(
412 'div',
413 [ 'class' => 'mw-filepage-resolutioninfo' ],
414 $msgsmall
415 );
416
417 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
418 if ( $isMulti ) {
419 $out->addModules( 'mediawiki.page.image.pagination' );
420 $out->addHTML( '<table class="multipageimage"><tr><td>' );
421 }
422
423 if ( $thumbnail ) {
424 $options = [
425 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
426 'file-link' => true,
427 ];
428 $out->addHTML( '<div class="fullImageLink" id="file">' .
429 $thumbnail->toHtml( $options ) .
430 $anchorclose . "</div>\n" );
431 }
432
433 if ( $isMulti ) {
434 $count = $this->displayImg->pageCount();
435
436 if ( $page > 1 ) {
437 $label = $this->getContext()->msg( 'imgmultipageprev' )->text();
438 // on the client side, this link is generated in ajaxifyPageNavigation()
439 // in the mediawiki.page.image.pagination module
440 $link = Linker::linkKnown(
441 $this->getTitle(),
442 $label,
443 [],
444 [ 'page' => $page - 1 ]
445 );
446 $thumb1 = Linker::makeThumbLinkObj(
447 $this->getTitle(),
448 $this->displayImg,
449 $link,
450 $label,
451 'none',
452 [ 'page' => $page - 1 ]
453 );
454 } else {
455 $thumb1 = '';
456 }
457
458 if ( $page < $count ) {
459 $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
460 $link = Linker::linkKnown(
461 $this->getTitle(),
462 $label,
463 [],
464 [ 'page' => $page + 1 ]
465 );
466 $thumb2 = Linker::makeThumbLinkObj(
467 $this->getTitle(),
468 $this->displayImg,
469 $link,
470 $label,
471 'none',
472 [ 'page' => $page + 1 ]
473 );
474 } else {
475 $thumb2 = '';
476 }
477
478 global $wgScript;
479
480 $formParams = [
481 'name' => 'pageselector',
482 'action' => $wgScript,
483 ];
484 $options = [];
485 for ( $i = 1; $i <= $count; $i++ ) {
486 $options[] = Xml::option( $lang->formatNum( $i ), $i, $i == $page );
487 }
488 $select = Xml::tags( 'select',
489 [ 'id' => 'pageselector', 'name' => 'page' ],
490 implode( "\n", $options ) );
491
492 $out->addHTML(
493 '</td><td><div class="multipageimagenavbox">' .
494 Xml::openElement( 'form', $formParams ) .
495 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
496 $this->getContext()->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
497 $this->getContext()->msg( 'word-separator' )->escaped() .
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( [ '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 T27277.
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 $out->addHTML( $this->doRenderLangOpt( $renderLangOptions, $renderLang ) );
559 }
560
561 // Add cannot animate thumbnail warning
562 if ( !$this->displayImg->canAnimateThumbIfAppropriate() ) {
563 // Include the extension so wiki admins can
564 // customize it on a per file-type basis
565 // (aka say things like use format X instead).
566 // additionally have a specific message for
567 // file-no-thumb-animation-gif
568 $ext = $this->displayImg->getExtension();
569 $noAnimMesg = wfMessageFallback(
570 'file-no-thumb-animation-' . $ext,
571 'file-no-thumb-animation'
572 )->plain();
573
574 $out->addWikiText( <<<EOT
575 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
576 EOT
577 );
578 }
579
580 if ( !$this->displayImg->isLocal() ) {
581 $this->printSharedImageText();
582 }
583 } else {
584 # Image does not exist
585 if ( !$this->getId() ) {
586 $dbr = wfGetDB( DB_REPLICA );
587
588 # No article exists either
589 # Show deletion log to be consistent with normal articles
590 LogEventsList::showLogExtract(
591 $out,
592 [ 'delete', 'move' ],
593 $this->getTitle()->getPrefixedText(),
594 '',
595 [ 'lim' => 10,
596 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
597 'showIfEmpty' => false,
598 'msgKey' => [ 'moveddeleted-notice' ]
599 ]
600 );
601 }
602
603 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
604 // Only show an upload link if the user can upload
605 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
606 $nofile = [
607 'filepage-nofile-link',
608 $uploadTitle->getFullURL( [ 'wpDestFile' => $this->mPage->getFile()->getName() ] )
609 ];
610 } else {
611 $nofile = 'filepage-nofile';
612 }
613 // Note, if there is an image description page, but
614 // no image, then this setRobotPolicy is overridden
615 // by Article::View().
616 $out->setRobotPolicy( 'noindex,nofollow' );
617 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
618 if ( !$this->getId() && $wgSend404Code ) {
619 // If there is no image, no shared image, and no description page,
620 // output a 404, to be consistent with Article::showMissingArticle.
621 $request->response()->statusHeader( 404 );
622 }
623 }
624 $out->setFileVersion( $this->displayImg );
625 }
626
627 /**
628 * Make the text under the image to say what size preview
629 *
630 * @param array $params parameters for thumbnail
631 * @param string $sizeLinkBigImagePreview HTML for the current size
632 * @return string HTML output
633 */
634 private function getThumbPrevText( $params, $sizeLinkBigImagePreview ) {
635 if ( $sizeLinkBigImagePreview ) {
636 // Show a different message of preview is different format from original.
637 $previewTypeDiffers = false;
638 $origExt = $thumbExt = $this->displayImg->getExtension();
639 if ( $this->displayImg->getHandler() ) {
640 $origMime = $this->displayImg->getMimeType();
641 $typeParams = $params;
642 $this->displayImg->getHandler()->normaliseParams( $this->displayImg, $typeParams );
643 list( $thumbExt, $thumbMime ) = $this->displayImg->getHandler()->getThumbType(
644 $origExt, $origMime, $typeParams );
645 if ( $thumbMime !== $origMime ) {
646 $previewTypeDiffers = true;
647 }
648 }
649 if ( $previewTypeDiffers ) {
650 return $this->getContext()->msg( 'show-big-image-preview-differ' )->
651 rawParams( $sizeLinkBigImagePreview )->
652 params( strtoupper( $origExt ) )->
653 params( strtoupper( $thumbExt ) )->
654 parse();
655 } else {
656 return $this->getContext()->msg( 'show-big-image-preview' )->
657 rawParams( $sizeLinkBigImagePreview )->
658 parse();
659 }
660 } else {
661 return '';
662 }
663 }
664
665 /**
666 * Creates an thumbnail of specified size and returns an HTML link to it
667 * @param array $params Scaler parameters
668 * @param int $width
669 * @param int $height
670 * @return string
671 */
672 private function makeSizeLink( $params, $width, $height ) {
673 $params['width'] = $width;
674 $params['height'] = $height;
675 $thumbnail = $this->displayImg->transform( $params );
676 if ( $thumbnail && !$thumbnail->isError() ) {
677 return Html::rawElement( 'a', [
678 'href' => $thumbnail->getUrl(),
679 'class' => 'mw-thumbnail-link'
680 ], $this->getContext()->msg( 'show-big-image-size' )->numParams(
681 $thumbnail->getWidth(), $thumbnail->getHeight()
682 )->parse() );
683 } else {
684 return '';
685 }
686 }
687
688 /**
689 * Show a notice that the file is from a shared repository
690 */
691 protected function printSharedImageText() {
692 $out = $this->getContext()->getOutput();
693 $this->loadFile();
694
695 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
696 $descText = $this->mPage->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
697
698 /* Add canonical to head if there is no local page for this shared file */
699 if ( $descUrl && $this->mPage->getId() == 0 ) {
700 $out->setCanonicalUrl( $descUrl );
701 }
702
703 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
704 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
705
706 if ( $descUrl &&
707 $descText &&
708 $this->getContext()->msg( 'sharedupload-desc-here' )->plain() !== '-'
709 ) {
710 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-here', $repo, $descUrl ] );
711 } elseif ( $descUrl &&
712 $this->getContext()->msg( 'sharedupload-desc-there' )->plain() !== '-'
713 ) {
714 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-there', $repo, $descUrl ] );
715 } else {
716 $out->wrapWikiMsg( $wrap, [ 'sharedupload', $repo ], ''/*BACKCOMPAT*/ );
717 }
718
719 if ( $descText ) {
720 $this->mExtraDescription = $descText;
721 }
722 }
723
724 public function getUploadUrl() {
725 $this->loadFile();
726 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
727 return $uploadTitle->getFullURL( [
728 'wpDestFile' => $this->mPage->getFile()->getName(),
729 'wpForReUpload' => 1
730 ] );
731 }
732
733 /**
734 * Print out the various links at the bottom of the image page, e.g. reupload,
735 * external editing (and instructions link) etc.
736 */
737 protected function uploadLinksBox() {
738 global $wgEnableUploads;
739
740 if ( !$wgEnableUploads ) {
741 return;
742 }
743
744 $this->loadFile();
745 if ( !$this->mPage->getFile()->isLocal() ) {
746 return;
747 }
748
749 $out = $this->getContext()->getOutput();
750 $out->addHTML( "<ul>\n" );
751
752 # "Upload a new version of this file" link
753 $canUpload = $this->getTitle()->quickUserCan( 'upload', $this->getContext()->getUser() );
754 if ( $canUpload && UploadBase::userCanReUpload(
755 $this->getContext()->getUser(),
756 $this->mPage->getFile() )
757 ) {
758 $ulink = Linker::makeExternalLink(
759 $this->getUploadUrl(),
760 $this->getContext()->msg( 'uploadnewversion-linktext' )->text()
761 );
762 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\">"
763 . "<div class=\"plainlinks\">{$ulink}</div></li>\n" );
764 } else {
765 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">"
766 . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
767 }
768
769 $out->addHTML( "</ul>\n" );
770 }
771
772 /**
773 * For overloading
774 */
775 protected function closeShowImage() {
776 }
777
778 /**
779 * If the page we've just displayed is in the "Image" namespace,
780 * we follow it with an upload history of the image and its usage.
781 */
782 protected function imageHistory() {
783 $this->loadFile();
784 $out = $this->getContext()->getOutput();
785 $pager = new ImageHistoryPseudoPager( $this );
786 $out->addHTML( $pager->getBody() );
787 $out->preventClickjacking( $pager->getPreventClickjacking() );
788
789 $this->mPage->getFile()->resetHistory(); // free db resources
790
791 # Exist check because we don't want to show this on pages where an image
792 # doesn't exist along with the noimage message, that would suck. -ævar
793 if ( $this->mPage->getFile()->exists() ) {
794 $this->uploadLinksBox();
795 }
796 }
797
798 /**
799 * @param string $target
800 * @param int $limit
801 * @return ResultWrapper
802 */
803 protected function queryImageLinks( $target, $limit ) {
804 $dbr = wfGetDB( DB_REPLICA );
805
806 return $dbr->select(
807 [ 'imagelinks', 'page' ],
808 [ 'page_namespace', 'page_title', 'il_to' ],
809 [ 'il_to' => $target, 'il_from = page_id' ],
810 __METHOD__,
811 [ 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', ]
812 );
813 }
814
815 protected function imageLinks() {
816 $limit = 100;
817
818 $out = $this->getContext()->getOutput();
819
820 $rows = [];
821 $redirects = [];
822 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE ) as $redir ) {
823 $redirects[$redir->getDBkey()] = [];
824 $rows[] = (object)[
825 'page_namespace' => NS_FILE,
826 'page_title' => $redir->getDBkey(),
827 ];
828 }
829
830 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit + 1 );
831 foreach ( $res as $row ) {
832 $rows[] = $row;
833 }
834 $count = count( $rows );
835
836 $hasMore = $count > $limit;
837 if ( !$hasMore && count( $redirects ) ) {
838 $res = $this->queryImageLinks( array_keys( $redirects ),
839 $limit - count( $rows ) + 1 );
840 foreach ( $res as $row ) {
841 $redirects[$row->il_to][] = $row;
842 $count++;
843 }
844 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
845 }
846
847 if ( $count == 0 ) {
848 $out->wrapWikiMsg(
849 Html::rawElement( 'div',
850 [ 'id' => 'mw-imagepage-nolinkstoimage' ], "\n$1\n" ),
851 'nolinkstoimage'
852 );
853 return;
854 }
855
856 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
857 if ( !$hasMore ) {
858 $out->addWikiMsg( 'linkstoimage', $count );
859 } else {
860 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
861 $out->addWikiMsg( 'linkstoimage-more',
862 $this->getContext()->getLanguage()->formatNum( $limit ),
863 $this->getTitle()->getPrefixedDBkey()
864 );
865 }
866
867 $out->addHTML(
868 Html::openElement( 'ul',
869 [ 'class' => 'mw-imagepage-linkstoimage' ] ) . "\n"
870 );
871 $count = 0;
872
873 // Sort the list by namespace:title
874 usort( $rows, [ $this, 'compare' ] );
875
876 // Create links for every element
877 $currentCount = 0;
878 foreach ( $rows as $element ) {
879 $currentCount++;
880 if ( $currentCount > $limit ) {
881 break;
882 }
883
884 $query = [];
885 # Add a redirect=no to make redirect pages reachable
886 if ( isset( $redirects[$element->page_title] ) ) {
887 $query['redirect'] = 'no';
888 }
889 $link = Linker::linkKnown(
890 Title::makeTitle( $element->page_namespace, $element->page_title ),
891 null, [], $query
892 );
893 if ( !isset( $redirects[$element->page_title] ) ) {
894 # No redirects
895 $liContents = $link;
896 } elseif ( count( $redirects[$element->page_title] ) === 0 ) {
897 # Redirect without usages
898 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )
899 ->rawParams( $link, '' )
900 ->parse();
901 } else {
902 # Redirect with usages
903 $li = '';
904 foreach ( $redirects[$element->page_title] as $row ) {
905 $currentCount++;
906 if ( $currentCount > $limit ) {
907 break;
908 }
909
910 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
911 $li .= Html::rawElement(
912 'li',
913 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
914 $link2
915 ) . "\n";
916 }
917
918 $ul = Html::rawElement(
919 'ul',
920 [ 'class' => 'mw-imagepage-redirectstofile' ],
921 $li
922 ) . "\n";
923 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
924 $link, $ul )->parse();
925 }
926 $out->addHTML( Html::rawElement(
927 'li',
928 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
929 $liContents
930 ) . "\n"
931 );
932
933 };
934 $out->addHTML( Html::closeElement( 'ul' ) . "\n" );
935 $res->free();
936
937 // Add a links to [[Special:Whatlinkshere]]
938 if ( $count > $limit ) {
939 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
940 }
941 $out->addHTML( Html::closeElement( 'div' ) . "\n" );
942 }
943
944 protected function imageDupes() {
945 $this->loadFile();
946 $out = $this->getContext()->getOutput();
947
948 $dupes = $this->mPage->getDuplicates();
949 if ( count( $dupes ) == 0 ) {
950 return;
951 }
952
953 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
954 $out->addWikiMsg( 'duplicatesoffile',
955 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
956 );
957 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
958
959 /**
960 * @var $file File
961 */
962 foreach ( $dupes as $file ) {
963 $fromSrc = '';
964 if ( $file->isLocal() ) {
965 $link = Linker::linkKnown( $file->getTitle() );
966 } else {
967 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
968 $file->getTitle()->getPrefixedText() );
969 $fromSrc = $this->getContext()->msg(
970 'shared-repo-from',
971 $file->getRepo()->getDisplayName()
972 )->escaped();
973 }
974 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
975 }
976 $out->addHTML( "</ul></div>\n" );
977 }
978
979 /**
980 * Delete the file, or an earlier version of it
981 */
982 public function delete() {
983 $file = $this->mPage->getFile();
984 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
985 // Standard article deletion
986 parent::delete();
987 return;
988 }
989
990 $deleter = new FileDeleteForm( $file );
991 $deleter->execute();
992 }
993
994 /**
995 * Display an error with a wikitext description
996 *
997 * @param string $description
998 */
999 function showError( $description ) {
1000 $out = $this->getContext()->getOutput();
1001 $out->setPageTitle( $this->getContext()->msg( 'internalerror' ) );
1002 $out->setRobotPolicy( 'noindex,nofollow' );
1003 $out->setArticleRelated( false );
1004 $out->enableClientCache( false );
1005 $out->addWikiText( $description );
1006 }
1007
1008 /**
1009 * Callback for usort() to do link sorts by (namespace, title)
1010 * Function copied from Title::compare()
1011 *
1012 * @param object $a Object page to compare with
1013 * @param object $b Object page to compare with
1014 * @return int Result of string comparison, or namespace comparison
1015 */
1016 protected function compare( $a, $b ) {
1017 if ( $a->page_namespace == $b->page_namespace ) {
1018 return strcmp( $a->page_title, $b->page_title );
1019 } else {
1020 return $a->page_namespace - $b->page_namespace;
1021 }
1022 }
1023
1024 /**
1025 * Returns the corresponding $wgImageLimits entry for the selected user option
1026 *
1027 * @param User $user
1028 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
1029 * @return array
1030 * @since 1.21
1031 */
1032 public function getImageLimitsFromOption( $user, $optionName ) {
1033 global $wgImageLimits;
1034
1035 $option = $user->getIntOption( $optionName );
1036 if ( !isset( $wgImageLimits[$option] ) ) {
1037 $option = User::getDefaultOption( $optionName );
1038 }
1039
1040 // The user offset might still be incorrect, specially if
1041 // $wgImageLimits got changed (see bug #8858).
1042 if ( !isset( $wgImageLimits[$option] ) ) {
1043 // Default to the first offset in $wgImageLimits
1044 $option = 0;
1045 }
1046
1047 return isset( $wgImageLimits[$option] )
1048 ? $wgImageLimits[$option]
1049 : [ 800, 600 ]; // if nothing is set, fallback to a hardcoded default
1050 }
1051
1052 /**
1053 * Output a drop-down box for language options for the file
1054 *
1055 * @param array $langChoices Array of string language codes
1056 * @param string $renderLang Language code for the language we want the file to rendered in.
1057 * @return string HTML to insert underneath image.
1058 */
1059 protected function doRenderLangOpt( array $langChoices, $renderLang ) {
1060 global $wgScript;
1061 $opts = '';
1062
1063 $matchedRenderLang = $this->displayImg->getMatchedLanguage( $renderLang );
1064
1065 foreach ( $langChoices as $lang ) {
1066 $opts .= $this->createXmlOptionStringForLanguage(
1067 $lang,
1068 $matchedRenderLang === $lang
1069 );
1070 }
1071
1072 // Allow for the default case in an svg <switch> that is displayed if no
1073 // systemLanguage attribute matches
1074 $opts .= "\n" .
1075 Xml::option(
1076 $this->getContext()->msg( 'img-lang-default' )->text(),
1077 'und',
1078 is_null( $matchedRenderLang )
1079 );
1080
1081 $select = Html::rawElement(
1082 'select',
1083 [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1084 $opts
1085 );
1086 $submit = Xml::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1087
1088 $formContents = $this->getContext()->msg( 'img-lang-info' )
1089 ->rawParams( $select, $submit )
1090 ->parse();
1091 $formContents .= Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1092
1093 $langSelectLine = Html::rawElement( 'div', [ 'id' => 'mw-imglangselector-line' ],
1094 Html::rawElement( 'form', [ 'action' => $wgScript ], $formContents )
1095 );
1096 return $langSelectLine;
1097 }
1098
1099 /**
1100 * @param $lang string
1101 * @param $selected bool
1102 * @return string
1103 */
1104 private function createXmlOptionStringForLanguage( $lang, $selected ) {
1105 $code = LanguageCode::bcp47( $lang );
1106 $name = Language::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1107 if ( $name !== '' ) {
1108 $display = $this->getContext()->msg( 'img-lang-opt', $code, $name )->text();
1109 } else {
1110 $display = $code;
1111 }
1112 return "\n" .
1113 Xml::option(
1114 $display,
1115 $lang,
1116 $selected
1117 );
1118 }
1119
1120 /**
1121 * Get the width and height to display image at.
1122 *
1123 * @note This method assumes that it is only called if one
1124 * of the dimensions are bigger than the max, or if the
1125 * image is vectorized.
1126 *
1127 * @param int $maxWidth Max width to display at
1128 * @param int $maxHeight Max height to display at
1129 * @param int $width Actual width of the image
1130 * @param int $height Actual height of the image
1131 * @throws MWException
1132 * @return array Array (width, height)
1133 */
1134 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1135 if ( !$maxWidth || !$maxHeight ) {
1136 // should never happen
1137 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1138 }
1139
1140 if ( !$width || !$height ) {
1141 return [ 0, 0 ];
1142 }
1143
1144 # Calculate the thumbnail size.
1145 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1146 // Vectorized image, do nothing.
1147 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1148 # The limiting factor is the width, not the height.
1149 $height = round( $height * $maxWidth / $width );
1150 $width = $maxWidth;
1151 # Note that $height <= $maxHeight now.
1152 } else {
1153 $newwidth = floor( $width * $maxHeight / $height );
1154 $height = round( $height * $newwidth / $width );
1155 $width = $newwidth;
1156 # Note that $height <= $maxHeight now, but might not be identical
1157 # because of rounding.
1158 }
1159 return [ $width, $height ];
1160 }
1161
1162 /**
1163 * Get alternative thumbnail sizes.
1164 *
1165 * @note This will only list several alternatives if thumbnails are rendered on 404
1166 * @param int $origWidth Actual width of image
1167 * @param int $origHeight Actual height of image
1168 * @return array An array of [width, height] pairs.
1169 */
1170 protected function getThumbSizes( $origWidth, $origHeight ) {
1171 global $wgImageLimits;
1172 if ( $this->displayImg->getRepo()->canTransformVia404() ) {
1173 $thumbSizes = $wgImageLimits;
1174 // Also include the full sized resolution in the list, so
1175 // that users know they can get it. This will link to the
1176 // original file asset if mustRender() === false. In the case
1177 // that we mustRender, some users have indicated that they would
1178 // find it useful to have the full size image in the rendered
1179 // image format.
1180 $thumbSizes[] = [ $origWidth, $origHeight ];
1181 } else {
1182 # Creating thumb links triggers thumbnail generation.
1183 # Just generate the thumb for the current users prefs.
1184 $thumbSizes = [
1185 $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' )
1186 ];
1187 if ( !$this->displayImg->mustRender() ) {
1188 // We can safely include a link to the "full-size" preview,
1189 // without actually rendering.
1190 $thumbSizes[] = [ $origWidth, $origHeight ];
1191 }
1192 }
1193 return $thumbSizes;
1194 }
1195
1196 /**
1197 * @see WikiFilePage::getFile
1198 * @return bool|File
1199 */
1200 public function getFile() {
1201 return $this->mPage->getFile();
1202 }
1203
1204 /**
1205 * @see WikiFilePage::isLocal
1206 * @return bool
1207 */
1208 public function isLocal() {
1209 return $this->mPage->isLocal();
1210 }
1211
1212 /**
1213 * @see WikiFilePage::getDuplicates
1214 * @return array|null
1215 */
1216 public function getDuplicates() {
1217 return $this->mPage->getDuplicates();
1218 }
1219
1220 /**
1221 * @see WikiFilePage::getForeignCategories
1222 * @return TitleArray|Title[]
1223 */
1224 public function getForeignCategories() {
1225 $this->mPage->getForeignCategories();
1226 }
1227
1228 }