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