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