Merge "Provide command to adjust phpunit.xml for code coverage"
[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 MediaWiki\MediaWikiServices;
24 use Wikimedia\Rdbms\ResultWrapper;
25
26 /**
27 * Class for viewing MediaWiki file description pages
28 *
29 * @ingroup Media
30 *
31 * @property WikiFilePage $mPage Set by overwritten newPage() in this class
32 * @method WikiFilePage getPage()
33 */
34 class ImagePage extends Article {
35 /** @var File|false */
36 private $displayImg;
37
38 /** @var FileRepo */
39 private $repo;
40
41 /** @var bool */
42 private $fileLoaded;
43
44 /** @var bool */
45 protected $mExtraDescription = false;
46
47 /**
48 * @param Title $title
49 * @return WikiFilePage
50 */
51 protected function newPage( Title $title ) {
52 // Overload mPage with a file-specific page
53 return new WikiFilePage( $title );
54 }
55
56 /**
57 * @param File $file
58 * @return void
59 */
60 public function setFile( $file ) {
61 $this->mPage->setFile( $file );
62 $this->displayImg = $file;
63 $this->fileLoaded = true;
64 }
65
66 protected function loadFile() {
67 if ( $this->fileLoaded ) {
68 return;
69 }
70 $this->fileLoaded = true;
71
72 $this->displayImg = $img = false;
73
74 Hooks::run( 'ImagePageFindFile', [ $this, &$img, &$this->displayImg ] );
75 if ( !$img ) { // not set by hook?
76 $services = MediaWikiServices::getInstance();
77 $img = $services->getRepoGroup()->findFile( $this->getTitle() );
78 if ( !$img ) {
79 $img = $services->getRepoGroup()->getLocalRepo()->newFile( $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 public function view() {
90 global $wgShowEXIF;
91
92 // For action=render, include body text only; none of the image extras
93 if ( $this->viewIsRenderAction ) {
94 parent::view();
95 return;
96 }
97
98 $out = $this->getContext()->getOutput();
99 $request = $this->getContext()->getRequest();
100 $diff = $request->getVal( 'diff' );
101 $diffOnly = $request->getBool(
102 'diffonly',
103 $this->getContext()->getUser()->getOption( 'diffonly' )
104 );
105
106 if ( $this->getTitle()->getNamespace() != NS_FILE || ( $diff !== null && $diffOnly ) ) {
107 parent::view();
108 return;
109 }
110
111 $this->loadFile();
112
113 if ( $this->getTitle()->getNamespace() == NS_FILE && $this->mPage->getFile()->getRedirected() ) {
114 if ( $this->getTitle()->getDBkey() == $this->mPage->getFile()->getName() || $diff !== null ) {
115 $request->setVal( 'diffonly', 'true' );
116 }
117
118 parent::view();
119 return;
120 }
121
122 if ( $wgShowEXIF && $this->displayImg->exists() ) {
123 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
124 $formattedMetadata = $this->displayImg->formatMetadata( $this->getContext() );
125 $showmeta = $formattedMetadata !== false;
126 } else {
127 $showmeta = false;
128 }
129
130 if ( !$diff && $this->displayImg->exists() ) {
131 $out->addHTML( $this->showTOC( $showmeta ) );
132 }
133
134 if ( !$diff ) {
135 $this->openShowImage();
136 }
137
138 # No need to display noarticletext, we use our own message, output in openShowImage()
139 if ( $this->mPage->getId() ) {
140 # NS_FILE is in the user language, but this section (the actual wikitext)
141 # should be in page content language
142 $pageLang = $this->getTitle()->getPageViewLanguage();
143 $out->addHTML( Xml::openElement( 'div', [ 'id' => 'mw-imagepage-content',
144 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
145 'class' => 'mw-content-' . $pageLang->getDir() ] ) );
146
147 parent::view();
148
149 $out->addHTML( Xml::closeElement( 'div' ) );
150 } else {
151 # Just need to set the right headers
152 $out->setArticleFlag( true );
153 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
154 $this->mPage->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
155 }
156
157 # Show shared description, if needed
158 if ( $this->mExtraDescription ) {
159 $fol = $this->getContext()->msg( 'shareddescriptionfollows' );
160 if ( !$fol->isDisabled() ) {
161 $out->addWikiTextAsInterface( $fol->plain() );
162 }
163 $out->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
164 }
165
166 $this->closeShowImage();
167 $this->imageHistory();
168 // TODO: Cleanup the following
169
170 $out->addHTML( Xml::element( 'h2',
171 [ 'id' => 'filelinks' ],
172 $this->getContext()->msg( 'imagelinks' )->text() ) . "\n" );
173 $this->imageDupes();
174 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
175 # Yet we return metadata about the target. Definitely an issue in the FileRepo
176 $this->imageLinks();
177
178 # Allow extensions to add something after the image links
179 $html = '';
180 Hooks::run( 'ImagePageAfterImageLinks', [ $this, &$html ] );
181 if ( $html ) {
182 $out->addHTML( $html );
183 }
184
185 if ( $showmeta ) {
186 $out->addHTML( Xml::element(
187 'h2',
188 [ 'id' => 'metadata' ],
189 $this->getContext()->msg( 'metadata' )->text() ) . "\n" );
190 $out->wrapWikiTextAsInterface(
191 'mw-imagepage-section-metadata',
192 $this->makeMetadataTable( $formattedMetadata )
193 );
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 = $this->getContext()->msg( 'metadata-help' )->plain();
253 // Intial state is collapsed
254 // see filepage.css and mediawiki.action.view.metadata module.
255 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata collapsed\">\n";
256 foreach ( $metadata as $type => $stuff ) {
257 foreach ( $stuff as $v ) {
258 $class = str_replace( ' ', '_', $v['id'] );
259 if ( $type == 'collapsed' ) {
260 $class .= ' mw-metadata-collapsible';
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";
270 return $r;
271 }
272
273 /**
274 * Overloading Article's getEmptyPageParserOutput method.
275 *
276 * Omit noarticletext if sharedupload; text will be fetched from the
277 * shared upload server if possible.
278 *
279 * @param ParserOptions $options
280 * @return ParserOutput
281 */
282 public function getEmptyPageParserOutput( ParserOptions $options ) {
283 $this->loadFile();
284 if ( $this->mPage->getFile() && !$this->mPage->getFile()->isLocal() && $this->getId() == 0 ) {
285 return new ParserOutput();
286 }
287 return parent::getEmptyPageParserOutput( $options );
288 }
289
290 /**
291 * Returns language code to be used for dispaying the image, based on request context and
292 * languages available in the file.
293 *
294 * @param WebRequest $request
295 * @param File $file
296 * @return string|null
297 */
298 private function getLanguageForRendering( WebRequest $request, File $file ) {
299 $handler = $file->getHandler();
300 if ( !$handler ) {
301 return null;
302 }
303
304 $config = MediaWikiServices::getInstance()->getMainConfig();
305 $requestLanguage = $request->getVal( 'lang', $config->get( 'LanguageCode' ) );
306 if ( $handler->validateParam( 'lang', $requestLanguage ) ) {
307 return $file->getMatchedLanguage( $requestLanguage );
308 }
309
310 return $handler->getDefaultRenderLanguage( $file );
311 }
312
313 protected function openShowImage() {
314 global $wgEnableUploads, $wgSend404Code, $wgSVGMaxSize;
315
316 $this->loadFile();
317 $out = $this->getContext()->getOutput();
318 $user = $this->getContext()->getUser();
319 $lang = $this->getContext()->getLanguage();
320 $dirmark = $lang->getDirMarkEntity();
321 $request = $this->getContext()->getRequest();
322
323 list( $maxWidth, $maxHeight ) = $this->getImageLimitsFromOption( $user, 'imagesize' );
324
325 if ( $this->displayImg->exists() ) {
326 # image
327 $page = $request->getIntOrNull( 'page' );
328 if ( is_null( $page ) ) {
329 $params = [];
330 $page = 1;
331 } else {
332 $params = [ 'page' => $page ];
333 }
334
335 $renderLang = $this->getLanguageForRendering( $request, $this->displayImg );
336 if ( !is_null( $renderLang ) ) {
337 $params['lang'] = $renderLang;
338 }
339
340 $width_orig = $this->displayImg->getWidth( $page );
341 $width = $width_orig;
342 $height_orig = $this->displayImg->getHeight( $page );
343 $height = $height_orig;
344
345 $filename = wfEscapeWikiText( $this->displayImg->getName() );
346 $linktext = $filename;
347
348 // Avoid PHP 7.1 warning from passing $this by reference
349 $imagePage = $this;
350
351 Hooks::run( 'ImageOpenShowImageInlineBefore', [ &$imagePage, &$out ] );
352
353 if ( $this->displayImg->allowInlineDisplay() ) {
354 # image
355 # "Download high res version" link below the image
356 # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
357 # Language::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
358 # We'll show a thumbnail of this image
359 if ( $width > $maxWidth || $height > $maxHeight || $this->displayImg->isVectorized() ) {
360 list( $width, $height ) = $this->getDisplayWidthHeight(
361 $maxWidth, $maxHeight, $width, $height
362 );
363 $linktext = $this->getContext()->msg( 'show-big-image' )->escaped();
364
365 $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
366 # Generate thumbnails or thumbnail links as needed...
367 $otherSizes = [];
368 foreach ( $thumbSizes as $size ) {
369 // We include a thumbnail size in the list, if it is
370 // less than or equal to the original size of the image
371 // asset ($width_orig/$height_orig). We also exclude
372 // the current thumbnail's size ($width/$height)
373 // since that is added to the message separately, so
374 // it can be denoted as the current size being shown.
375 // Vectorized images are limited by $wgSVGMaxSize big,
376 // so all thumbs less than or equal that are shown.
377 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
378 || ( $this->displayImg->isVectorized()
379 && max( $size[0], $size[1] ) <= $wgSVGMaxSize )
380 )
381 && $size[0] != $width && $size[1] != $height
382 ) {
383 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
384 if ( $sizeLink ) {
385 $otherSizes[] = $sizeLink;
386 }
387 }
388 }
389 $otherSizes = array_unique( $otherSizes );
390
391 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
392 $msgsmall = $this->getThumbPrevText( $params, $sizeLinkBigImagePreview );
393 if ( count( $otherSizes ) ) {
394 $msgsmall .= ' ' .
395 Html::rawElement(
396 'span',
397 [ 'class' => 'mw-filepage-other-resolutions' ],
398 $this->getContext()->msg( 'show-big-image-other' )
399 ->rawParams( $lang->pipeList( $otherSizes ) )
400 ->params( count( $otherSizes ) )
401 ->parse()
402 );
403 }
404 } elseif ( $width == 0 && $height == 0 ) {
405 # Some sort of audio file that doesn't have dimensions
406 # Don't output a no hi res message for such a file
407 $msgsmall = '';
408 } else {
409 # Image is small enough to show full size on image page
410 $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
411 }
412
413 $params['width'] = $width;
414 $params['height'] = $height;
415 $thumbnail = $this->displayImg->transform( $params );
416 Linker::processResponsiveImages( $this->displayImg, $thumbnail, $params );
417
418 $anchorclose = Html::rawElement(
419 'div',
420 [ 'class' => 'mw-filepage-resolutioninfo' ],
421 $msgsmall
422 );
423
424 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
425 if ( $isMulti ) {
426 $out->addModules( 'mediawiki.page.image.pagination' );
427 $out->addHTML( '<table class="multipageimage"><tr><td>' );
428 }
429
430 if ( $thumbnail ) {
431 $options = [
432 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
433 'file-link' => true,
434 ];
435 $out->addHTML( '<div class="fullImageLink" id="file">' .
436 $thumbnail->toHtml( $options ) .
437 $anchorclose . "</div>\n" );
438 }
439
440 if ( $isMulti ) {
441 $count = $this->displayImg->pageCount();
442
443 if ( $page > 1 ) {
444 $label = $this->getContext()->msg( 'imgmultipageprev' )->text();
445 // on the client side, this link is generated in ajaxifyPageNavigation()
446 // in the mediawiki.page.image.pagination module
447 $link = Linker::linkKnown(
448 $this->getTitle(),
449 htmlspecialchars( $label ),
450 [],
451 [ 'page' => $page - 1 ]
452 );
453 $thumb1 = Linker::makeThumbLinkObj(
454 $this->getTitle(),
455 $this->displayImg,
456 $link,
457 $label,
458 'none',
459 [ 'page' => $page - 1 ]
460 );
461 } else {
462 $thumb1 = '';
463 }
464
465 if ( $page < $count ) {
466 $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
467 $link = Linker::linkKnown(
468 $this->getTitle(),
469 htmlspecialchars( $label ),
470 [],
471 [ 'page' => $page + 1 ]
472 );
473 $thumb2 = Linker::makeThumbLinkObj(
474 $this->getTitle(),
475 $this->displayImg,
476 $link,
477 $label,
478 'none',
479 [ 'page' => $page + 1 ]
480 );
481 } else {
482 $thumb2 = '';
483 }
484
485 global $wgScript;
486
487 $formParams = [
488 'name' => 'pageselector',
489 'action' => $wgScript,
490 ];
491 $options = [];
492 for ( $i = 1; $i <= $count; $i++ ) {
493 $options[] = Xml::option( $lang->formatNum( $i ), $i, $i == $page );
494 }
495 $select = Xml::tags( 'select',
496 [ 'id' => 'pageselector', 'name' => 'page' ],
497 implode( "\n", $options ) );
498
499 $out->addHTML(
500 '</td><td><div class="multipageimagenavbox">' .
501 Xml::openElement( 'form', $formParams ) .
502 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
503 $this->getContext()->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
504 $this->getContext()->msg( 'word-separator' )->escaped() .
505 Xml::submitButton( $this->getContext()->msg( 'imgmultigo' )->text() ) .
506 Xml::closeElement( 'form' ) .
507 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
508 );
509 }
510 } elseif ( $this->displayImg->isSafeFile() ) {
511 # if direct link is allowed but it's not a renderable image, show an icon.
512 $icon = $this->displayImg->iconThumb();
513
514 $out->addHTML( '<div class="fullImageLink" id="file">' .
515 $icon->toHtml( [ 'file-link' => true ] ) .
516 "</div>\n" );
517 }
518
519 $longDesc = $this->getContext()->msg( 'parentheses', $this->displayImg->getLongDesc() )->text();
520
521 $handler = $this->displayImg->getHandler();
522
523 // If this is a filetype with potential issues, warn the user.
524 if ( $handler ) {
525 $warningConfig = $handler->getWarningConfig( $this->displayImg );
526
527 if ( $warningConfig !== null ) {
528 // The warning will be displayed via CSS and JavaScript.
529 // We just need to tell the client side what message to use.
530 $output = $this->getContext()->getOutput();
531 $output->addJsConfigVars( 'wgFileWarning', $warningConfig );
532 $output->addModules( $warningConfig['module'] );
533 $output->addModules( 'mediawiki.filewarning' );
534 }
535 }
536
537 $medialink = "[[Media:$filename|$linktext]]";
538
539 if ( !$this->displayImg->isSafeFile() ) {
540 $warning = $this->getContext()->msg( 'mediawarning' )->plain();
541 // dirmark is needed here to separate the file name, which
542 // most likely ends in Latin characters, from the description,
543 // which may begin with the file type. In RTL environment
544 // this will get messy.
545 // The dirmark, however, must not be immediately adjacent
546 // to the filename, because it can get copied with it.
547 // See T27277.
548 // phpcs:disable Generic.Files.LineLength
549 $out->wrapWikiTextAsInterface( 'fullMedia', <<<EOT
550 <span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span>
551 EOT
552 );
553 // phpcs:enable
554 $out->wrapWikiTextAsInterface( 'mediaWarning', $warning );
555 } else {
556 $out->wrapWikiTextAsInterface( 'fullMedia', <<<EOT
557 {$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
558 EOT
559 );
560 }
561
562 $renderLangOptions = $this->displayImg->getAvailableLanguages();
563 if ( count( $renderLangOptions ) >= 1 ) {
564 $out->addHTML( $this->doRenderLangOpt( $renderLangOptions, $renderLang ) );
565 }
566
567 // Add cannot animate thumbnail warning
568 if ( !$this->displayImg->canAnimateThumbIfAppropriate() ) {
569 // Include the extension so wiki admins can
570 // customize it on a per file-type basis
571 // (aka say things like use format X instead).
572 // additionally have a specific message for
573 // file-no-thumb-animation-gif
574 $ext = $this->displayImg->getExtension();
575 $noAnimMesg = wfMessageFallback(
576 'file-no-thumb-animation-' . $ext,
577 'file-no-thumb-animation'
578 )->plain();
579
580 $out->wrapWikiTextAsInterface( 'mw-noanimatethumb', $noAnimMesg );
581 }
582
583 if ( !$this->displayImg->isLocal() ) {
584 $this->printSharedImageText();
585 }
586 } else {
587 # Image does not exist
588 if ( !$this->getId() ) {
589 $dbr = wfGetDB( DB_REPLICA );
590
591 # No article exists either
592 # Show deletion log to be consistent with normal articles
593 LogEventsList::showLogExtract(
594 $out,
595 [ 'delete', 'move', 'protect' ],
596 $this->getTitle()->getPrefixedText(),
597 '',
598 [ 'lim' => 10,
599 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
600 'showIfEmpty' => false,
601 'msgKey' => [ '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 = [
610 'filepage-nofile-link',
611 $uploadTitle->getFullURL( [ '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 array $params parameters for thumbnail
634 * @param string $sizeLinkBigImagePreview HTML for the current size
635 * @return string HTML output
636 */
637 protected 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 protected 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', [
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, [ 'sharedupload-desc-here', $repo, $descUrl ] );
714 } elseif ( $descUrl &&
715 $this->getContext()->msg( 'sharedupload-desc-there' )->plain() !== '-'
716 ) {
717 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-there', $repo, $descUrl ] );
718 } else {
719 $out->wrapWikiMsg( $wrap, [ '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( [
731 'wpDestFile' => $this->mPage->getFile()->getName(),
732 'wpForReUpload' => 1
733 ] );
734 }
735
736 /**
737 * Add the re-upload link (or message about not being able to re-upload) to the output.
738 */
739 protected function uploadLinksBox() {
740 if ( !$this->getContext()->getConfig()->get( 'EnableUploads' ) ) {
741 return;
742 }
743
744 $this->loadFile();
745 if ( !$this->mPage->getFile()->isLocal() ) {
746 return;
747 }
748
749 $canUpload = MediaWikiServices::getInstance()->getPermissionManager()
750 ->quickUserCan( 'upload', $this->getContext()->getUser(), $this->getTitle() );
751 if ( $canUpload && UploadBase::userCanReUpload(
752 $this->getContext()->getUser(),
753 $this->mPage->getFile() )
754 ) {
755 // "Upload a new version of this file" link
756 $ulink = Linker::makeExternalLink(
757 $this->getUploadUrl(),
758 $this->getContext()->msg( 'uploadnewversion-linktext' )->text()
759 );
760 $attrs = [ 'class' => 'plainlinks', 'id' => 'mw-imagepage-reupload-link' ];
761 $linkPara = Html::rawElement( 'p', $attrs, $ulink );
762 } else {
763 // "You cannot overwrite this file." message
764 $attrs = [ 'id' => 'mw-imagepage-upload-disallowed' ];
765 $msg = $this->getContext()->msg( 'upload-disallowed-here' )->text();
766 $linkPara = Html::element( 'p', $attrs, $msg );
767 }
768
769 $uploadLinks = Html::rawElement( 'div', [ 'class' => 'mw-imagepage-upload-links' ], $linkPara );
770 $this->getContext()->getOutput()->addHTML( $uploadLinks );
771 }
772
773 /**
774 * For overloading
775 */
776 protected function closeShowImage() {
777 }
778
779 /**
780 * If the page we've just displayed is in the "Image" namespace,
781 * we follow it with an upload history of the image and its usage.
782 */
783 protected function imageHistory() {
784 $this->loadFile();
785 $out = $this->getContext()->getOutput();
786 $pager = new ImageHistoryPseudoPager( $this );
787 $out->addHTML( $pager->getBody() );
788 $out->preventClickjacking( $pager->getPreventClickjacking() );
789
790 $this->mPage->getFile()->resetHistory(); // free db resources
791
792 # Exist check because we don't want to show this on pages where an image
793 # doesn't exist along with the noimage message, that would suck. -ævar
794 if ( $this->mPage->getFile()->exists() ) {
795 $this->uploadLinksBox();
796 }
797 }
798
799 /**
800 * @param string|string[] $target
801 * @param int $limit
802 * @return ResultWrapper
803 */
804 protected function queryImageLinks( $target, $limit ) {
805 $dbr = wfGetDB( DB_REPLICA );
806
807 return $dbr->select(
808 [ 'imagelinks', 'page' ],
809 [ 'page_namespace', 'page_title', 'il_to' ],
810 [ 'il_to' => $target, 'il_from = page_id' ],
811 __METHOD__,
812 [ 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', ]
813 );
814 }
815
816 protected function imageLinks() {
817 $limit = 100;
818
819 $out = $this->getContext()->getOutput();
820
821 $rows = [];
822 $redirects = [];
823 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE ) as $redir ) {
824 $redirects[$redir->getDBkey()] = [];
825 $rows[] = (object)[
826 'page_namespace' => NS_FILE,
827 'page_title' => $redir->getDBkey(),
828 ];
829 }
830
831 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit + 1 );
832 foreach ( $res as $row ) {
833 $rows[] = $row;
834 }
835 $count = count( $rows );
836
837 $hasMore = $count > $limit;
838 if ( !$hasMore && count( $redirects ) ) {
839 $res = $this->queryImageLinks( array_keys( $redirects ),
840 $limit - count( $rows ) + 1 );
841 foreach ( $res as $row ) {
842 $redirects[$row->il_to][] = $row;
843 $count++;
844 }
845 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
846 }
847
848 if ( $count == 0 ) {
849 $out->wrapWikiMsg(
850 Html::rawElement( 'div',
851 [ 'id' => 'mw-imagepage-nolinkstoimage' ], "\n$1\n" ),
852 'nolinkstoimage'
853 );
854 return;
855 }
856
857 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
858 if ( !$hasMore ) {
859 $out->addWikiMsg( 'linkstoimage', $count );
860 } else {
861 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
862 $out->addWikiMsg( 'linkstoimage-more',
863 $this->getContext()->getLanguage()->formatNum( $limit ),
864 $this->getTitle()->getPrefixedDBkey()
865 );
866 }
867
868 $out->addHTML(
869 Html::openElement( 'ul',
870 [ 'class' => 'mw-imagepage-linkstoimage' ] ) . "\n"
871 );
872 $count = 0;
873
874 // Sort the list by namespace:title
875 usort( $rows, [ $this, 'compare' ] );
876
877 // Create links for every element
878 $currentCount = 0;
879 foreach ( $rows as $element ) {
880 $currentCount++;
881 if ( $currentCount > $limit ) {
882 break;
883 }
884
885 $query = [];
886 # Add a redirect=no to make redirect pages reachable
887 if ( isset( $redirects[$element->page_title] ) ) {
888 $query['redirect'] = 'no';
889 }
890 $link = Linker::linkKnown(
891 Title::makeTitle( $element->page_namespace, $element->page_title ),
892 null, [], $query
893 );
894 if ( !isset( $redirects[$element->page_title] ) ) {
895 # No redirects
896 $liContents = $link;
897 } elseif ( count( $redirects[$element->page_title] ) === 0 ) {
898 # Redirect without usages
899 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )
900 ->rawParams( $link, '' )
901 ->parse();
902 } else {
903 # Redirect with usages
904 $li = '';
905 foreach ( $redirects[$element->page_title] as $row ) {
906 $currentCount++;
907 if ( $currentCount > $limit ) {
908 break;
909 }
910
911 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
912 $li .= Html::rawElement(
913 'li',
914 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
915 $link2
916 ) . "\n";
917 }
918
919 $ul = Html::rawElement(
920 'ul',
921 [ 'class' => 'mw-imagepage-redirectstofile' ],
922 $li
923 ) . "\n";
924 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
925 $link, $ul )->parse();
926 }
927 $out->addHTML( Html::rawElement(
928 'li',
929 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
930 $liContents
931 ) . "\n"
932 );
933
934 }
935 $out->addHTML( Html::closeElement( 'ul' ) . "\n" );
936 $res->free();
937
938 // Add a links to [[Special:Whatlinkshere]]
939 if ( $count > $limit ) {
940 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
941 }
942 $out->addHTML( Html::closeElement( 'div' ) . "\n" );
943 }
944
945 protected function imageDupes() {
946 $this->loadFile();
947 $out = $this->getContext()->getOutput();
948
949 $dupes = $this->mPage->getDuplicates();
950 if ( count( $dupes ) == 0 ) {
951 return;
952 }
953
954 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
955 $out->addWikiMsg( 'duplicatesoffile',
956 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
957 );
958 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
959
960 /**
961 * @var File $file
962 */
963 foreach ( $dupes as $file ) {
964 $fromSrc = '';
965 if ( $file->isLocal() ) {
966 $link = Linker::linkKnown( $file->getTitle() );
967 } else {
968 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
969 $file->getTitle()->getPrefixedText() );
970 $fromSrc = $this->getContext()->msg(
971 'shared-repo-from',
972 $file->getRepo()->getDisplayName()
973 )->escaped();
974 }
975 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
976 }
977 $out->addHTML( "</ul></div>\n" );
978 }
979
980 /**
981 * Delete the file, or an earlier version of it
982 */
983 public function delete() {
984 $file = $this->mPage->getFile();
985 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
986 // Standard article deletion
987 parent::delete();
988 return;
989 }
990 '@phan-var LocalFile $file';
991
992 $deleter = new FileDeleteForm( $file );
993 $deleter->execute();
994 }
995
996 /**
997 * Display an error with a wikitext description
998 *
999 * @param string $description
1000 */
1001 function showError( $description ) {
1002 $out = $this->getContext()->getOutput();
1003 $out->setPageTitle( $this->getContext()->msg( 'internalerror' ) );
1004 $out->setRobotPolicy( 'noindex,nofollow' );
1005 $out->setArticleRelated( false );
1006 $out->enableClientCache( false );
1007 $out->addWikiTextAsInterface( $description );
1008 }
1009
1010 /**
1011 * Callback for usort() to do link sorts by (namespace, title)
1012 * Function copied from Title::compare()
1013 *
1014 * @param object $a Object page to compare with
1015 * @param object $b Object page to compare with
1016 * @return int Result of string comparison, or namespace comparison
1017 */
1018 protected function compare( $a, $b ) {
1019 return $a->page_namespace <=> $b->page_namespace
1020 ?: strcmp( $a->page_title, $b->page_title );
1021 }
1022
1023 /**
1024 * Returns the corresponding $wgImageLimits entry for the selected user option
1025 *
1026 * @param User $user
1027 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
1028 * @return int[]
1029 * @since 1.21
1030 */
1031 public function getImageLimitsFromOption( $user, $optionName ) {
1032 global $wgImageLimits;
1033
1034 $option = $user->getIntOption( $optionName );
1035 if ( !isset( $wgImageLimits[$option] ) ) {
1036 $option = User::getDefaultOption( $optionName );
1037 }
1038
1039 // The user offset might still be incorrect, specially if
1040 // $wgImageLimits got changed (see T10858).
1041 if ( !isset( $wgImageLimits[$option] ) ) {
1042 // Default to the first offset in $wgImageLimits
1043 $option = 0;
1044 }
1045
1046 // if nothing is set, fallback to a hardcoded default
1047 return $wgImageLimits[$option] ?? [ 800, 600 ];
1048 }
1049
1050 /**
1051 * Output a drop-down box for language options for the file
1052 *
1053 * @param array $langChoices Array of string language codes
1054 * @param string $renderLang Language code for the language we want the file to rendered in.
1055 * @return string HTML to insert underneath image.
1056 */
1057 protected function doRenderLangOpt( array $langChoices, $renderLang ) {
1058 global $wgScript;
1059 $opts = '';
1060
1061 $matchedRenderLang = $this->displayImg->getMatchedLanguage( $renderLang );
1062
1063 foreach ( $langChoices as $lang ) {
1064 $opts .= $this->createXmlOptionStringForLanguage(
1065 $lang,
1066 $matchedRenderLang === $lang
1067 );
1068 }
1069
1070 // Allow for the default case in an svg <switch> that is displayed if no
1071 // systemLanguage attribute matches
1072 $opts .= "\n" .
1073 Xml::option(
1074 $this->getContext()->msg( 'img-lang-default' )->text(),
1075 'und',
1076 is_null( $matchedRenderLang )
1077 );
1078
1079 $select = Html::rawElement(
1080 'select',
1081 [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1082 $opts
1083 );
1084 $submit = Xml::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1085
1086 $formContents = $this->getContext()->msg( 'img-lang-info' )
1087 ->rawParams( $select, $submit )
1088 ->parse();
1089 $formContents .= Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1090
1091 $langSelectLine = Html::rawElement( 'div', [ 'id' => 'mw-imglangselector-line' ],
1092 Html::rawElement( 'form', [ 'action' => $wgScript ], $formContents )
1093 );
1094 return $langSelectLine;
1095 }
1096
1097 /**
1098 * @param string $lang
1099 * @param bool $selected
1100 * @return string
1101 */
1102 private function createXmlOptionStringForLanguage( $lang, $selected ) {
1103 $code = LanguageCode::bcp47( $lang );
1104 $name = Language::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1105 if ( $name !== '' ) {
1106 $display = $this->getContext()->msg( 'img-lang-opt', $code, $name )->text();
1107 } else {
1108 $display = $code;
1109 }
1110 return "\n" .
1111 Xml::option(
1112 $display,
1113 $lang,
1114 $selected
1115 );
1116 }
1117
1118 /**
1119 * Get the width and height to display image at.
1120 *
1121 * @note This method assumes that it is only called if one
1122 * of the dimensions are bigger than the max, or if the
1123 * image is vectorized.
1124 *
1125 * @param int $maxWidth Max width to display at
1126 * @param int $maxHeight Max height to display at
1127 * @param int $width Actual width of the image
1128 * @param int $height Actual height of the image
1129 * @throws MWException
1130 * @return array Array (width, height)
1131 */
1132 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1133 if ( !$maxWidth || !$maxHeight ) {
1134 // should never happen
1135 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1136 }
1137
1138 if ( !$width || !$height ) {
1139 return [ 0, 0 ];
1140 }
1141
1142 # Calculate the thumbnail size.
1143 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1144 // Vectorized image, do nothing.
1145 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1146 # The limiting factor is the width, not the height.
1147 $height = round( $height * $maxWidth / $width );
1148 $width = $maxWidth;
1149 # Note that $height <= $maxHeight now.
1150 } else {
1151 $newwidth = floor( $width * $maxHeight / $height );
1152 $height = round( $height * $newwidth / $width );
1153 $width = $newwidth;
1154 # Note that $height <= $maxHeight now, but might not be identical
1155 # because of rounding.
1156 }
1157 return [ $width, $height ];
1158 }
1159
1160 /**
1161 * Get alternative thumbnail sizes.
1162 *
1163 * @note This will only list several alternatives if thumbnails are rendered on 404
1164 * @param int $origWidth Actual width of image
1165 * @param int $origHeight Actual height of image
1166 * @return array An array of [width, height] pairs.
1167 */
1168 protected function getThumbSizes( $origWidth, $origHeight ) {
1169 global $wgImageLimits;
1170 if ( $this->displayImg->getRepo()->canTransformVia404() ) {
1171 $thumbSizes = $wgImageLimits;
1172 // Also include the full sized resolution in the list, so
1173 // that users know they can get it. This will link to the
1174 // original file asset if mustRender() === false. In the case
1175 // that we mustRender, some users have indicated that they would
1176 // find it useful to have the full size image in the rendered
1177 // image format.
1178 $thumbSizes[] = [ $origWidth, $origHeight ];
1179 } else {
1180 # Creating thumb links triggers thumbnail generation.
1181 # Just generate the thumb for the current users prefs.
1182 $thumbSizes = [
1183 $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' )
1184 ];
1185 if ( !$this->displayImg->mustRender() ) {
1186 // We can safely include a link to the "full-size" preview,
1187 // without actually rendering.
1188 $thumbSizes[] = [ $origWidth, $origHeight ];
1189 }
1190 }
1191 return $thumbSizes;
1192 }
1193
1194 /**
1195 * @see WikiFilePage::getFile
1196 * @return bool|File
1197 */
1198 public function getFile() {
1199 return $this->mPage->getFile();
1200 }
1201
1202 /**
1203 * @see WikiFilePage::isLocal
1204 * @return bool
1205 */
1206 public function isLocal() {
1207 return $this->mPage->isLocal();
1208 }
1209
1210 /**
1211 * @see WikiFilePage::getDuplicates
1212 * @return array|null
1213 */
1214 public function getDuplicates() {
1215 return $this->mPage->getDuplicates();
1216 }
1217
1218 /**
1219 * @see WikiFilePage::getForeignCategories
1220 * @return TitleArray|Title[]
1221 */
1222 public function getForeignCategories() {
1223 return $this->mPage->getForeignCategories();
1224 }
1225
1226 }