Use OutputPage::wrapWikiTextAsInterface() to add safe <div> wrappers
[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->addWikiTextAsInterface( $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->addWikiTextAsInterface( $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 // 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</div>\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() && 0 == $this->getId() ) {
286 return new ParserOutput();
287 }
288 return parent::getEmptyPageParserOutput( $options );
289 }
290
291 private function getLanguageForRendering( WebRequest $request, File $file ) {
292 $handler = $this->displayImg->getHandler();
293 if ( !$handler ) {
294 return null;
295 }
296
297 $requestLanguage = $request->getVal( 'lang' );
298 if ( !is_null( $requestLanguage ) ) {
299 if ( $handler->validateParam( 'lang', $requestLanguage ) ) {
300 return $requestLanguage;
301 }
302 }
303
304 return $handler->getDefaultRenderLanguage( $this->displayImg );
305 }
306
307 protected function openShowImage() {
308 global $wgEnableUploads, $wgSend404Code, $wgSVGMaxSize;
309
310 $this->loadFile();
311 $out = $this->getContext()->getOutput();
312 $user = $this->getContext()->getUser();
313 $lang = $this->getContext()->getLanguage();
314 $dirmark = $lang->getDirMarkEntity();
315 $request = $this->getContext()->getRequest();
316
317 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
318 $maxWidth = $max[0];
319 $maxHeight = $max[1];
320
321 if ( $this->displayImg->exists() ) {
322 # image
323 $page = $request->getIntOrNull( 'page' );
324 if ( is_null( $page ) ) {
325 $params = [];
326 $page = 1;
327 } else {
328 $params = [ 'page' => $page ];
329 }
330
331 $renderLang = $this->getLanguageForRendering( $request, $this->displayImg );
332 if ( !is_null( $renderLang ) ) {
333 $params['lang'] = $renderLang;
334 }
335
336 $width_orig = $this->displayImg->getWidth( $page );
337 $width = $width_orig;
338 $height_orig = $this->displayImg->getHeight( $page );
339 $height = $height_orig;
340
341 $filename = wfEscapeWikiText( $this->displayImg->getName() );
342 $linktext = $filename;
343
344 // Avoid PHP 7.1 warning from passing $this by reference
345 $imagePage = $this;
346
347 Hooks::run( 'ImageOpenShowImageInlineBefore', [ &$imagePage, &$out ] );
348
349 if ( $this->displayImg->allowInlineDisplay() ) {
350 # image
351 # "Download high res version" link below the image
352 # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
353 # Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
354 # We'll show a thumbnail of this image
355 if ( $width > $maxWidth || $height > $maxHeight || $this->displayImg->isVectorized() ) {
356 list( $width, $height ) = $this->getDisplayWidthHeight(
357 $maxWidth, $maxHeight, $width, $height
358 );
359 $linktext = $this->getContext()->msg( 'show-big-image' )->escaped();
360
361 $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
362 # Generate thumbnails or thumbnail links as needed...
363 $otherSizes = [];
364 foreach ( $thumbSizes as $size ) {
365 // We include a thumbnail size in the list, if it is
366 // less than or equal to the original size of the image
367 // asset ($width_orig/$height_orig). We also exclude
368 // the current thumbnail's size ($width/$height)
369 // since that is added to the message separately, so
370 // it can be denoted as the current size being shown.
371 // Vectorized images are limited by $wgSVGMaxSize big,
372 // so all thumbs less than or equal that are shown.
373 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
374 || ( $this->displayImg->isVectorized()
375 && max( $size[0], $size[1] ) <= $wgSVGMaxSize )
376 )
377 && $size[0] != $width && $size[1] != $height
378 ) {
379 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
380 if ( $sizeLink ) {
381 $otherSizes[] = $sizeLink;
382 }
383 }
384 }
385 $otherSizes = array_unique( $otherSizes );
386
387 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
388 $msgsmall = $this->getThumbPrevText( $params, $sizeLinkBigImagePreview );
389 if ( count( $otherSizes ) ) {
390 $msgsmall .= ' ' .
391 Html::rawElement(
392 'span',
393 [ 'class' => 'mw-filepage-other-resolutions' ],
394 $this->getContext()->msg( 'show-big-image-other' )
395 ->rawParams( $lang->pipeList( $otherSizes ) )
396 ->params( count( $otherSizes ) )
397 ->parse()
398 );
399 }
400 } elseif ( $width == 0 && $height == 0 ) {
401 # Some sort of audio file that doesn't have dimensions
402 # Don't output a no hi res message for such a file
403 $msgsmall = '';
404 } else {
405 # Image is small enough to show full size on image page
406 $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
407 }
408
409 $params['width'] = $width;
410 $params['height'] = $height;
411 $thumbnail = $this->displayImg->transform( $params );
412 Linker::processResponsiveImages( $this->displayImg, $thumbnail, $params );
413
414 $anchorclose = Html::rawElement(
415 'div',
416 [ 'class' => 'mw-filepage-resolutioninfo' ],
417 $msgsmall
418 );
419
420 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
421 if ( $isMulti ) {
422 $out->addModules( 'mediawiki.page.image.pagination' );
423 $out->addHTML( '<table class="multipageimage"><tr><td>' );
424 }
425
426 if ( $thumbnail ) {
427 $options = [
428 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
429 'file-link' => true,
430 ];
431 $out->addHTML( '<div class="fullImageLink" id="file">' .
432 $thumbnail->toHtml( $options ) .
433 $anchorclose . "</div>\n" );
434 }
435
436 if ( $isMulti ) {
437 $count = $this->displayImg->pageCount();
438
439 if ( $page > 1 ) {
440 $label = $this->getContext()->msg( 'imgmultipageprev' )->text();
441 // on the client side, this link is generated in ajaxifyPageNavigation()
442 // in the mediawiki.page.image.pagination module
443 $link = Linker::linkKnown(
444 $this->getTitle(),
445 htmlspecialchars( $label ),
446 [],
447 [ 'page' => $page - 1 ]
448 );
449 $thumb1 = Linker::makeThumbLinkObj(
450 $this->getTitle(),
451 $this->displayImg,
452 $link,
453 $label,
454 'none',
455 [ 'page' => $page - 1 ]
456 );
457 } else {
458 $thumb1 = '';
459 }
460
461 if ( $page < $count ) {
462 $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
463 $link = Linker::linkKnown(
464 $this->getTitle(),
465 htmlspecialchars( $label ),
466 [],
467 [ 'page' => $page + 1 ]
468 );
469 $thumb2 = Linker::makeThumbLinkObj(
470 $this->getTitle(),
471 $this->displayImg,
472 $link,
473 $label,
474 'none',
475 [ 'page' => $page + 1 ]
476 );
477 } else {
478 $thumb2 = '';
479 }
480
481 global $wgScript;
482
483 $formParams = [
484 'name' => 'pageselector',
485 'action' => $wgScript,
486 ];
487 $options = [];
488 for ( $i = 1; $i <= $count; $i++ ) {
489 $options[] = Xml::option( $lang->formatNum( $i ), $i, $i == $page );
490 }
491 $select = Xml::tags( 'select',
492 [ 'id' => 'pageselector', 'name' => 'page' ],
493 implode( "\n", $options ) );
494
495 $out->addHTML(
496 '</td><td><div class="multipageimagenavbox">' .
497 Xml::openElement( 'form', $formParams ) .
498 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
499 $this->getContext()->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
500 $this->getContext()->msg( 'word-separator' )->escaped() .
501 Xml::submitButton( $this->getContext()->msg( 'imgmultigo' )->text() ) .
502 Xml::closeElement( 'form' ) .
503 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
504 );
505 }
506 } elseif ( $this->displayImg->isSafeFile() ) {
507 # if direct link is allowed but it's not a renderable image, show an icon.
508 $icon = $this->displayImg->iconThumb();
509
510 $out->addHTML( '<div class="fullImageLink" id="file">' .
511 $icon->toHtml( [ 'file-link' => true ] ) .
512 "</div>\n" );
513 }
514
515 $longDesc = $this->getContext()->msg( 'parentheses', $this->displayImg->getLongDesc() )->text();
516
517 $handler = $this->displayImg->getHandler();
518
519 // If this is a filetype with potential issues, warn the user.
520 if ( $handler ) {
521 $warningConfig = $handler->getWarningConfig( $this->displayImg );
522
523 if ( $warningConfig !== null ) {
524 // The warning will be displayed via CSS and JavaScript.
525 // We just need to tell the client side what message to use.
526 $output = $this->getContext()->getOutput();
527 $output->addJsConfigVars( 'wgFileWarning', $warningConfig );
528 $output->addModules( $warningConfig['module'] );
529 $output->addModules( 'mediawiki.filewarning' );
530 }
531 }
532
533 $medialink = "[[Media:$filename|$linktext]]";
534
535 if ( !$this->displayImg->isSafeFile() ) {
536 $warning = $this->getContext()->msg( 'mediawarning' )->plain();
537 // dirmark is needed here to separate the file name, which
538 // most likely ends in Latin characters, from the description,
539 // which may begin with the file type. In RTL environment
540 // this will get messy.
541 // The dirmark, however, must not be immediately adjacent
542 // to the filename, because it can get copied with it.
543 // See T27277.
544 // phpcs:disable Generic.Files.LineLength
545 $out->wrapWikiTextAsInterface( 'fullMedia', <<<EOT
546 <span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span>
547 EOT
548 );
549 // phpcs:enable
550 $out->wrapWikiTextAsInterface( 'mediaWarning', $warning );
551 } else {
552 $out->wrapWikiTextAsInterface( 'fullMedia', <<<EOT
553 {$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
554 EOT
555 );
556 }
557
558 $renderLangOptions = $this->displayImg->getAvailableLanguages();
559 if ( count( $renderLangOptions ) >= 1 ) {
560 $out->addHTML( $this->doRenderLangOpt( $renderLangOptions, $renderLang ) );
561 }
562
563 // Add cannot animate thumbnail warning
564 if ( !$this->displayImg->canAnimateThumbIfAppropriate() ) {
565 // Include the extension so wiki admins can
566 // customize it on a per file-type basis
567 // (aka say things like use format X instead).
568 // additionally have a specific message for
569 // file-no-thumb-animation-gif
570 $ext = $this->displayImg->getExtension();
571 $noAnimMesg = wfMessageFallback(
572 'file-no-thumb-animation-' . $ext,
573 'file-no-thumb-animation'
574 )->plain();
575
576 $out->wrapWikiTextAsInterface( 'mw-noanimatethumb', $noAnimMesg );
577 }
578
579 if ( !$this->displayImg->isLocal() ) {
580 $this->printSharedImageText();
581 }
582 } else {
583 # Image does not exist
584 if ( !$this->getId() ) {
585 $dbr = wfGetDB( DB_REPLICA );
586
587 # No article exists either
588 # Show deletion log to be consistent with normal articles
589 LogEventsList::showLogExtract(
590 $out,
591 [ 'delete', 'move', 'protect' ],
592 $this->getTitle()->getPrefixedText(),
593 '',
594 [ 'lim' => 10,
595 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
596 'showIfEmpty' => false,
597 'msgKey' => [ 'moveddeleted-notice' ]
598 ]
599 );
600 }
601
602 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
603 // Only show an upload link if the user can upload
604 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
605 $nofile = [
606 'filepage-nofile-link',
607 $uploadTitle->getFullURL( [ 'wpDestFile' => $this->mPage->getFile()->getName() ] )
608 ];
609 } else {
610 $nofile = 'filepage-nofile';
611 }
612 // Note, if there is an image description page, but
613 // no image, then this setRobotPolicy is overridden
614 // by Article::View().
615 $out->setRobotPolicy( 'noindex,nofollow' );
616 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
617 if ( !$this->getId() && $wgSend404Code ) {
618 // If there is no image, no shared image, and no description page,
619 // output a 404, to be consistent with Article::showMissingArticle.
620 $request->response()->statusHeader( 404 );
621 }
622 }
623 $out->setFileVersion( $this->displayImg );
624 }
625
626 /**
627 * Make the text under the image to say what size preview
628 *
629 * @param array $params parameters for thumbnail
630 * @param string $sizeLinkBigImagePreview HTML for the current size
631 * @return string HTML output
632 */
633 protected function getThumbPrevText( $params, $sizeLinkBigImagePreview ) {
634 if ( $sizeLinkBigImagePreview ) {
635 // Show a different message of preview is different format from original.
636 $previewTypeDiffers = false;
637 $origExt = $thumbExt = $this->displayImg->getExtension();
638 if ( $this->displayImg->getHandler() ) {
639 $origMime = $this->displayImg->getMimeType();
640 $typeParams = $params;
641 $this->displayImg->getHandler()->normaliseParams( $this->displayImg, $typeParams );
642 list( $thumbExt, $thumbMime ) = $this->displayImg->getHandler()->getThumbType(
643 $origExt, $origMime, $typeParams );
644 if ( $thumbMime !== $origMime ) {
645 $previewTypeDiffers = true;
646 }
647 }
648 if ( $previewTypeDiffers ) {
649 return $this->getContext()->msg( 'show-big-image-preview-differ' )->
650 rawParams( $sizeLinkBigImagePreview )->
651 params( strtoupper( $origExt ) )->
652 params( strtoupper( $thumbExt ) )->
653 parse();
654 } else {
655 return $this->getContext()->msg( 'show-big-image-preview' )->
656 rawParams( $sizeLinkBigImagePreview )->
657 parse();
658 }
659 } else {
660 return '';
661 }
662 }
663
664 /**
665 * Creates an thumbnail of specified size and returns an HTML link to it
666 * @param array $params Scaler parameters
667 * @param int $width
668 * @param int $height
669 * @return string
670 */
671 protected function makeSizeLink( $params, $width, $height ) {
672 $params['width'] = $width;
673 $params['height'] = $height;
674 $thumbnail = $this->displayImg->transform( $params );
675 if ( $thumbnail && !$thumbnail->isError() ) {
676 return Html::rawElement( 'a', [
677 'href' => $thumbnail->getUrl(),
678 'class' => 'mw-thumbnail-link'
679 ], $this->getContext()->msg( 'show-big-image-size' )->numParams(
680 $thumbnail->getWidth(), $thumbnail->getHeight()
681 )->parse() );
682 } else {
683 return '';
684 }
685 }
686
687 /**
688 * Show a notice that the file is from a shared repository
689 */
690 protected function printSharedImageText() {
691 $out = $this->getContext()->getOutput();
692 $this->loadFile();
693
694 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
695 $descText = $this->mPage->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
696
697 /* Add canonical to head if there is no local page for this shared file */
698 if ( $descUrl && $this->mPage->getId() == 0 ) {
699 $out->setCanonicalUrl( $descUrl );
700 }
701
702 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
703 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
704
705 if ( $descUrl &&
706 $descText &&
707 $this->getContext()->msg( 'sharedupload-desc-here' )->plain() !== '-'
708 ) {
709 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-here', $repo, $descUrl ] );
710 } elseif ( $descUrl &&
711 $this->getContext()->msg( 'sharedupload-desc-there' )->plain() !== '-'
712 ) {
713 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-there', $repo, $descUrl ] );
714 } else {
715 $out->wrapWikiMsg( $wrap, [ 'sharedupload', $repo ], ''/*BACKCOMPAT*/ );
716 }
717
718 if ( $descText ) {
719 $this->mExtraDescription = $descText;
720 }
721 }
722
723 public function getUploadUrl() {
724 $this->loadFile();
725 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
726 return $uploadTitle->getFullURL( [
727 'wpDestFile' => $this->mPage->getFile()->getName(),
728 'wpForReUpload' => 1
729 ] );
730 }
731
732 /**
733 * Print out the various links at the bottom of the image page, e.g. reupload,
734 * external editing (and instructions link) etc.
735 */
736 protected function uploadLinksBox() {
737 global $wgEnableUploads;
738
739 if ( !$wgEnableUploads ) {
740 return;
741 }
742
743 $this->loadFile();
744 if ( !$this->mPage->getFile()->isLocal() ) {
745 return;
746 }
747
748 $out = $this->getContext()->getOutput();
749 $out->addHTML( "<ul>\n" );
750
751 # "Upload a new version of this file" link
752 $canUpload = $this->getTitle()->quickUserCan( 'upload', $this->getContext()->getUser() );
753 if ( $canUpload && UploadBase::userCanReUpload(
754 $this->getContext()->getUser(),
755 $this->mPage->getFile() )
756 ) {
757 $ulink = Linker::makeExternalLink(
758 $this->getUploadUrl(),
759 $this->getContext()->msg( 'uploadnewversion-linktext' )->text()
760 );
761 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\">"
762 . "<div class=\"plainlinks\">{$ulink}</div></li>\n" );
763 } else {
764 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">"
765 . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
766 }
767
768 $out->addHTML( "</ul>\n" );
769 }
770
771 /**
772 * For overloading
773 */
774 protected function closeShowImage() {
775 }
776
777 /**
778 * If the page we've just displayed is in the "Image" namespace,
779 * we follow it with an upload history of the image and its usage.
780 */
781 protected function imageHistory() {
782 $this->loadFile();
783 $out = $this->getContext()->getOutput();
784 $pager = new ImageHistoryPseudoPager( $this );
785 $out->addHTML( $pager->getBody() );
786 $out->preventClickjacking( $pager->getPreventClickjacking() );
787
788 $this->mPage->getFile()->resetHistory(); // free db resources
789
790 # Exist check because we don't want to show this on pages where an image
791 # doesn't exist along with the noimage message, that would suck. -ævar
792 if ( $this->mPage->getFile()->exists() ) {
793 $this->uploadLinksBox();
794 }
795 }
796
797 /**
798 * @param string $target
799 * @param int $limit
800 * @return ResultWrapper
801 */
802 protected function queryImageLinks( $target, $limit ) {
803 $dbr = wfGetDB( DB_REPLICA );
804
805 return $dbr->select(
806 [ 'imagelinks', 'page' ],
807 [ 'page_namespace', 'page_title', 'il_to' ],
808 [ 'il_to' => $target, 'il_from = page_id' ],
809 __METHOD__,
810 [ 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', ]
811 );
812 }
813
814 protected function imageLinks() {
815 $limit = 100;
816
817 $out = $this->getContext()->getOutput();
818
819 $rows = [];
820 $redirects = [];
821 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE ) as $redir ) {
822 $redirects[$redir->getDBkey()] = [];
823 $rows[] = (object)[
824 'page_namespace' => NS_FILE,
825 'page_title' => $redir->getDBkey(),
826 ];
827 }
828
829 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit + 1 );
830 foreach ( $res as $row ) {
831 $rows[] = $row;
832 }
833 $count = count( $rows );
834
835 $hasMore = $count > $limit;
836 if ( !$hasMore && count( $redirects ) ) {
837 $res = $this->queryImageLinks( array_keys( $redirects ),
838 $limit - count( $rows ) + 1 );
839 foreach ( $res as $row ) {
840 $redirects[$row->il_to][] = $row;
841 $count++;
842 }
843 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
844 }
845
846 if ( $count == 0 ) {
847 $out->wrapWikiMsg(
848 Html::rawElement( 'div',
849 [ 'id' => 'mw-imagepage-nolinkstoimage' ], "\n$1\n" ),
850 'nolinkstoimage'
851 );
852 return;
853 }
854
855 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
856 if ( !$hasMore ) {
857 $out->addWikiMsg( 'linkstoimage', $count );
858 } else {
859 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
860 $out->addWikiMsg( 'linkstoimage-more',
861 $this->getContext()->getLanguage()->formatNum( $limit ),
862 $this->getTitle()->getPrefixedDBkey()
863 );
864 }
865
866 $out->addHTML(
867 Html::openElement( 'ul',
868 [ 'class' => 'mw-imagepage-linkstoimage' ] ) . "\n"
869 );
870 $count = 0;
871
872 // Sort the list by namespace:title
873 usort( $rows, [ $this, 'compare' ] );
874
875 // Create links for every element
876 $currentCount = 0;
877 foreach ( $rows as $element ) {
878 $currentCount++;
879 if ( $currentCount > $limit ) {
880 break;
881 }
882
883 $query = [];
884 # Add a redirect=no to make redirect pages reachable
885 if ( isset( $redirects[$element->page_title] ) ) {
886 $query['redirect'] = 'no';
887 }
888 $link = Linker::linkKnown(
889 Title::makeTitle( $element->page_namespace, $element->page_title ),
890 null, [], $query
891 );
892 if ( !isset( $redirects[$element->page_title] ) ) {
893 # No redirects
894 $liContents = $link;
895 } elseif ( count( $redirects[$element->page_title] ) === 0 ) {
896 # Redirect without usages
897 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )
898 ->rawParams( $link, '' )
899 ->parse();
900 } else {
901 # Redirect with usages
902 $li = '';
903 foreach ( $redirects[$element->page_title] as $row ) {
904 $currentCount++;
905 if ( $currentCount > $limit ) {
906 break;
907 }
908
909 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
910 $li .= Html::rawElement(
911 'li',
912 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
913 $link2
914 ) . "\n";
915 }
916
917 $ul = Html::rawElement(
918 'ul',
919 [ 'class' => 'mw-imagepage-redirectstofile' ],
920 $li
921 ) . "\n";
922 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
923 $link, $ul )->parse();
924 }
925 $out->addHTML( Html::rawElement(
926 'li',
927 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
928 $liContents
929 ) . "\n"
930 );
931
932 };
933 $out->addHTML( Html::closeElement( 'ul' ) . "\n" );
934 $res->free();
935
936 // Add a links to [[Special:Whatlinkshere]]
937 if ( $count > $limit ) {
938 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
939 }
940 $out->addHTML( Html::closeElement( 'div' ) . "\n" );
941 }
942
943 protected function imageDupes() {
944 $this->loadFile();
945 $out = $this->getContext()->getOutput();
946
947 $dupes = $this->mPage->getDuplicates();
948 if ( count( $dupes ) == 0 ) {
949 return;
950 }
951
952 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
953 $out->addWikiMsg( 'duplicatesoffile',
954 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
955 );
956 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
957
958 /**
959 * @var $file File
960 */
961 foreach ( $dupes as $file ) {
962 $fromSrc = '';
963 if ( $file->isLocal() ) {
964 $link = Linker::linkKnown( $file->getTitle() );
965 } else {
966 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
967 $file->getTitle()->getPrefixedText() );
968 $fromSrc = $this->getContext()->msg(
969 'shared-repo-from',
970 $file->getRepo()->getDisplayName()
971 )->escaped();
972 }
973 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
974 }
975 $out->addHTML( "</ul></div>\n" );
976 }
977
978 /**
979 * Delete the file, or an earlier version of it
980 */
981 public function delete() {
982 $file = $this->mPage->getFile();
983 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
984 // Standard article deletion
985 parent::delete();
986 return;
987 }
988
989 $deleter = new FileDeleteForm( $file );
990 $deleter->execute();
991 }
992
993 /**
994 * Display an error with a wikitext description
995 *
996 * @param string $description
997 */
998 function showError( $description ) {
999 $out = $this->getContext()->getOutput();
1000 $out->setPageTitle( $this->getContext()->msg( 'internalerror' ) );
1001 $out->setRobotPolicy( 'noindex,nofollow' );
1002 $out->setArticleRelated( false );
1003 $out->enableClientCache( false );
1004 $out->addWikiTextAsInterface( $description );
1005 }
1006
1007 /**
1008 * Callback for usort() to do link sorts by (namespace, title)
1009 * Function copied from Title::compare()
1010 *
1011 * @param object $a Object page to compare with
1012 * @param object $b Object page to compare with
1013 * @return int Result of string comparison, or namespace comparison
1014 */
1015 protected function compare( $a, $b ) {
1016 return $a->page_namespace <=> $b->page_namespace
1017 ?: strcmp( $a->page_title, $b->page_title );
1018 }
1019
1020 /**
1021 * Returns the corresponding $wgImageLimits entry for the selected user option
1022 *
1023 * @param User $user
1024 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
1025 * @return array
1026 * @since 1.21
1027 */
1028 public function getImageLimitsFromOption( $user, $optionName ) {
1029 global $wgImageLimits;
1030
1031 $option = $user->getIntOption( $optionName );
1032 if ( !isset( $wgImageLimits[$option] ) ) {
1033 $option = User::getDefaultOption( $optionName );
1034 }
1035
1036 // The user offset might still be incorrect, specially if
1037 // $wgImageLimits got changed (see T10858).
1038 if ( !isset( $wgImageLimits[$option] ) ) {
1039 // Default to the first offset in $wgImageLimits
1040 $option = 0;
1041 }
1042
1043 // if nothing is set, fallback to a hardcoded default
1044 return $wgImageLimits[$option] ?? [ 800, 600 ];
1045 }
1046
1047 /**
1048 * Output a drop-down box for language options for the file
1049 *
1050 * @param array $langChoices Array of string language codes
1051 * @param string $renderLang Language code for the language we want the file to rendered in.
1052 * @return string HTML to insert underneath image.
1053 */
1054 protected function doRenderLangOpt( array $langChoices, $renderLang ) {
1055 global $wgScript;
1056 $opts = '';
1057
1058 $matchedRenderLang = $this->displayImg->getMatchedLanguage( $renderLang );
1059
1060 foreach ( $langChoices as $lang ) {
1061 $opts .= $this->createXmlOptionStringForLanguage(
1062 $lang,
1063 $matchedRenderLang === $lang
1064 );
1065 }
1066
1067 // Allow for the default case in an svg <switch> that is displayed if no
1068 // systemLanguage attribute matches
1069 $opts .= "\n" .
1070 Xml::option(
1071 $this->getContext()->msg( 'img-lang-default' )->text(),
1072 'und',
1073 is_null( $matchedRenderLang )
1074 );
1075
1076 $select = Html::rawElement(
1077 'select',
1078 [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1079 $opts
1080 );
1081 $submit = Xml::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1082
1083 $formContents = $this->getContext()->msg( 'img-lang-info' )
1084 ->rawParams( $select, $submit )
1085 ->parse();
1086 $formContents .= Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1087
1088 $langSelectLine = Html::rawElement( 'div', [ 'id' => 'mw-imglangselector-line' ],
1089 Html::rawElement( 'form', [ 'action' => $wgScript ], $formContents )
1090 );
1091 return $langSelectLine;
1092 }
1093
1094 /**
1095 * @param $lang string
1096 * @param $selected bool
1097 * @return string
1098 */
1099 private function createXmlOptionStringForLanguage( $lang, $selected ) {
1100 $code = LanguageCode::bcp47( $lang );
1101 $name = Language::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1102 if ( $name !== '' ) {
1103 $display = $this->getContext()->msg( 'img-lang-opt', $code, $name )->text();
1104 } else {
1105 $display = $code;
1106 }
1107 return "\n" .
1108 Xml::option(
1109 $display,
1110 $lang,
1111 $selected
1112 );
1113 }
1114
1115 /**
1116 * Get the width and height to display image at.
1117 *
1118 * @note This method assumes that it is only called if one
1119 * of the dimensions are bigger than the max, or if the
1120 * image is vectorized.
1121 *
1122 * @param int $maxWidth Max width to display at
1123 * @param int $maxHeight Max height to display at
1124 * @param int $width Actual width of the image
1125 * @param int $height Actual height of the image
1126 * @throws MWException
1127 * @return array Array (width, height)
1128 */
1129 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1130 if ( !$maxWidth || !$maxHeight ) {
1131 // should never happen
1132 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1133 }
1134
1135 if ( !$width || !$height ) {
1136 return [ 0, 0 ];
1137 }
1138
1139 # Calculate the thumbnail size.
1140 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1141 // Vectorized image, do nothing.
1142 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1143 # The limiting factor is the width, not the height.
1144 $height = round( $height * $maxWidth / $width );
1145 $width = $maxWidth;
1146 # Note that $height <= $maxHeight now.
1147 } else {
1148 $newwidth = floor( $width * $maxHeight / $height );
1149 $height = round( $height * $newwidth / $width );
1150 $width = $newwidth;
1151 # Note that $height <= $maxHeight now, but might not be identical
1152 # because of rounding.
1153 }
1154 return [ $width, $height ];
1155 }
1156
1157 /**
1158 * Get alternative thumbnail sizes.
1159 *
1160 * @note This will only list several alternatives if thumbnails are rendered on 404
1161 * @param int $origWidth Actual width of image
1162 * @param int $origHeight Actual height of image
1163 * @return array An array of [width, height] pairs.
1164 */
1165 protected function getThumbSizes( $origWidth, $origHeight ) {
1166 global $wgImageLimits;
1167 if ( $this->displayImg->getRepo()->canTransformVia404() ) {
1168 $thumbSizes = $wgImageLimits;
1169 // Also include the full sized resolution in the list, so
1170 // that users know they can get it. This will link to the
1171 // original file asset if mustRender() === false. In the case
1172 // that we mustRender, some users have indicated that they would
1173 // find it useful to have the full size image in the rendered
1174 // image format.
1175 $thumbSizes[] = [ $origWidth, $origHeight ];
1176 } else {
1177 # Creating thumb links triggers thumbnail generation.
1178 # Just generate the thumb for the current users prefs.
1179 $thumbSizes = [
1180 $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' )
1181 ];
1182 if ( !$this->displayImg->mustRender() ) {
1183 // We can safely include a link to the "full-size" preview,
1184 // without actually rendering.
1185 $thumbSizes[] = [ $origWidth, $origHeight ];
1186 }
1187 }
1188 return $thumbSizes;
1189 }
1190
1191 /**
1192 * @see WikiFilePage::getFile
1193 * @return bool|File
1194 */
1195 public function getFile() {
1196 return $this->mPage->getFile();
1197 }
1198
1199 /**
1200 * @see WikiFilePage::isLocal
1201 * @return bool
1202 */
1203 public function isLocal() {
1204 return $this->mPage->isLocal();
1205 }
1206
1207 /**
1208 * @see WikiFilePage::getDuplicates
1209 * @return array|null
1210 */
1211 public function getDuplicates() {
1212 return $this->mPage->getDuplicates();
1213 }
1214
1215 /**
1216 * @see WikiFilePage::getForeignCategories
1217 * @return TitleArray|Title[]
1218 */
1219 public function getForeignCategories() {
1220 $this->mPage->getForeignCategories();
1221 }
1222
1223 }