Merge "mediawiki.user: Move JS session token from cookie to sessionStorage"
[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 /**
24 * Class for viewing MediaWiki file description pages
25 *
26 * @ingroup Media
27 */
28 class ImagePage extends Article {
29 /** @var File */
30 private $displayImg;
31
32 /** @var FileRepo */
33 private $repo;
34
35 /** @var bool */
36 private $fileLoaded;
37
38 /** @var bool */
39 protected $mExtraDescription = false;
40
41 /**
42 * @var WikiFilePage
43 */
44 protected $mPage;
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 $img = wfFindFile( $this->getTitle() );
76 if ( !$img ) {
77 $img = wfLocalFile( $this->getTitle() );
78 }
79 }
80 $this->mPage->setFile( $img );
81 if ( !$this->displayImg ) { // not set by hook?
82 $this->displayImg = $img;
83 }
84 $this->repo = $img->getRepo();
85 }
86
87 /**
88 * Handler for action=render
89 * Include body text only; none of the image extras
90 */
91 public function render() {
92 $this->getContext()->getOutput()->setArticleBodyOnly( true );
93 parent::view();
94 }
95
96 public function view() {
97 global $wgShowEXIF;
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 // mTitle is the same as the redirect target so ask Article
117 // to perform the redirect for us.
118 $request->setVal( 'diffonly', 'true' );
119 parent::view();
120 return;
121 } else {
122 // mTitle is not the same as the redirect target so it is
123 // probably the redirect page itself. Fake the redirect symbol
124 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
125 $out->addHTML( $this->viewRedirect(
126 Title::makeTitle( NS_FILE, $this->mPage->getFile()->getName() ),
127 /* $appendSubtitle */ true,
128 /* $forceKnown */ true )
129 );
130 $this->mPage->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
131 return;
132 }
133 }
134
135 if ( $wgShowEXIF && $this->displayImg->exists() ) {
136 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
137 $formattedMetadata = $this->displayImg->formatMetadata( $this->getContext() );
138 $showmeta = $formattedMetadata !== false;
139 } else {
140 $showmeta = false;
141 }
142
143 if ( !$diff && $this->displayImg->exists() ) {
144 $out->addHTML( $this->showTOC( $showmeta ) );
145 }
146
147 if ( !$diff ) {
148 $this->openShowImage();
149 }
150
151 # No need to display noarticletext, we use our own message, output in openShowImage()
152 if ( $this->mPage->getId() ) {
153 # NS_FILE is in the user language, but this section (the actual wikitext)
154 # should be in page content language
155 $pageLang = $this->getTitle()->getPageViewLanguage();
156 $out->addHTML( Xml::openElement( 'div', [ 'id' => 'mw-imagepage-content',
157 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
158 'class' => 'mw-content-' . $pageLang->getDir() ] ) );
159
160 parent::view();
161
162 $out->addHTML( Xml::closeElement( 'div' ) );
163 } else {
164 # Just need to set the right headers
165 $out->setArticleFlag( true );
166 $out->setPageTitle( $this->getTitle()->getPrefixedText() );
167 $this->mPage->doViewUpdates( $this->getContext()->getUser(), $this->getOldID() );
168 }
169
170 # Show shared description, if needed
171 if ( $this->mExtraDescription ) {
172 $fol = $this->getContext()->msg( 'shareddescriptionfollows' );
173 if ( !$fol->isDisabled() ) {
174 $out->addWikiText( $fol->plain() );
175 }
176 $out->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
177 }
178
179 $this->closeShowImage();
180 $this->imageHistory();
181 // TODO: Cleanup the following
182
183 $out->addHTML( Xml::element( 'h2',
184 [ 'id' => 'filelinks' ],
185 $this->getContext()->msg( 'imagelinks' )->text() ) . "\n" );
186 $this->imageDupes();
187 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
188 # Yet we return metadata about the target. Definitely an issue in the FileRepo
189 $this->imageLinks();
190
191 # Allow extensions to add something after the image links
192 $html = '';
193 Hooks::run( 'ImagePageAfterImageLinks', [ $this, &$html ] );
194 if ( $html ) {
195 $out->addHTML( $html );
196 }
197
198 if ( $showmeta ) {
199 $out->addHTML( Xml::element(
200 'h2',
201 [ 'id' => 'metadata' ],
202 $this->getContext()->msg( 'metadata' )->text() ) . "\n" );
203 $out->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
204 $out->addModules( [ 'mediawiki.action.view.metadata' ] );
205 }
206
207 // Add remote Filepage.css
208 if ( !$this->repo->isLocal() ) {
209 $css = $this->repo->getDescriptionStylesheetUrl();
210 if ( $css ) {
211 $out->addStyle( $css );
212 }
213 }
214
215 $out->addModuleStyles( [
216 'filepage', // always show the local local Filepage.css, T31277
217 'mediawiki.action.view.filepage', // Add MediaWiki styles for a file page
218 ] );
219 }
220
221 /**
222 * @return File
223 */
224 public function getDisplayedFile() {
225 $this->loadFile();
226 return $this->displayImg;
227 }
228
229 /**
230 * Create the TOC
231 *
232 * @param bool $metadata Whether or not to show the metadata link
233 * @return string
234 */
235 protected function showTOC( $metadata ) {
236 $r = [
237 '<li><a href="#file">' . $this->getContext()->msg( 'file-anchor-link' )->escaped() . '</a></li>',
238 '<li><a href="#filehistory">' . $this->getContext()->msg( 'filehist' )->escaped() . '</a></li>',
239 '<li><a href="#filelinks">' . $this->getContext()->msg( 'imagelinks' )->escaped() . '</a></li>',
240 ];
241
242 Hooks::run( 'ImagePageShowTOC', [ $this, &$r ] );
243
244 if ( $metadata ) {
245 $r[] = '<li><a href="#metadata">' .
246 $this->getContext()->msg( 'metadata' )->escaped() .
247 '</a></li>';
248 }
249
250 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
251 }
252
253 /**
254 * Make a table with metadata to be shown in the output page.
255 *
256 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
257 *
258 * @param array $metadata The array containing the Exif data
259 * @return string The metadata table. This is treated as Wikitext (!)
260 */
261 protected function makeMetadataTable( $metadata ) {
262 $r = "<div class=\"mw-imagepage-section-metadata\">";
263 $r .= $this->getContext()->msg( 'metadata-help' )->plain();
264 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
265 foreach ( $metadata as $type => $stuff ) {
266 foreach ( $stuff as $v ) {
267 # @todo FIXME: Why is this using escapeId for a class?!
268 $class = Sanitizer::escapeId( $v['id'] );
269 if ( $type == 'collapsed' ) {
270 // Handled by mediawiki.action.view.metadata module.
271 $class .= ' collapsable';
272 }
273 $r .= "<tr class=\"$class\">\n";
274 $r .= "<th>{$v['name']}</th>\n";
275 $r .= "<td>{$v['value']}</td>\n</tr>";
276 }
277 }
278 $r .= "</table>\n</div>\n";
279 return $r;
280 }
281
282 /**
283 * Overloading Article's getContentObject method.
284 *
285 * Omit noarticletext if sharedupload; text will be fetched from the
286 * shared upload server if possible.
287 * @return string
288 */
289 public function getContentObject() {
290 $this->loadFile();
291 if ( $this->mPage->getFile() && !$this->mPage->getFile()->isLocal() && 0 == $this->getId() ) {
292 return null;
293 }
294 return parent::getContentObject();
295 }
296
297 protected function openShowImage() {
298 global $wgEnableUploads, $wgSend404Code, $wgSVGMaxSize;
299
300 $this->loadFile();
301 $out = $this->getContext()->getOutput();
302 $user = $this->getContext()->getUser();
303 $lang = $this->getContext()->getLanguage();
304 $dirmark = $lang->getDirMarkEntity();
305 $request = $this->getContext()->getRequest();
306
307 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
308 $maxWidth = $max[0];
309 $maxHeight = $max[1];
310
311 if ( $this->displayImg->exists() ) {
312 # image
313 $page = $request->getIntOrNull( 'page' );
314 if ( is_null( $page ) ) {
315 $params = [];
316 $page = 1;
317 } else {
318 $params = [ 'page' => $page ];
319 }
320
321 $renderLang = $request->getVal( 'lang' );
322 if ( !is_null( $renderLang ) ) {
323 $handler = $this->displayImg->getHandler();
324 if ( $handler && $handler->validateParam( 'lang', $renderLang ) ) {
325 $params['lang'] = $renderLang;
326 } else {
327 $renderLang = null;
328 }
329 }
330
331 $width_orig = $this->displayImg->getWidth( $page );
332 $width = $width_orig;
333 $height_orig = $this->displayImg->getHeight( $page );
334 $height = $height_orig;
335
336 $filename = wfEscapeWikiText( $this->displayImg->getName() );
337 $linktext = $filename;
338
339 // Avoid PHP 7.1 warning from passing $this by reference
340 $imagePage = $this;
341
342 Hooks::run( 'ImageOpenShowImageInlineBefore', [ &$imagePage, &$out ] );
343
344 if ( $this->displayImg->allowInlineDisplay() ) {
345 # image
346 # "Download high res version" link below the image
347 # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
348 # Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
349 # We'll show a thumbnail of this image
350 if ( $width > $maxWidth || $height > $maxHeight || $this->displayImg->isVectorized() ) {
351 list( $width, $height ) = $this->getDisplayWidthHeight(
352 $maxWidth, $maxHeight, $width, $height
353 );
354 $linktext = $this->getContext()->msg( 'show-big-image' )->escaped();
355
356 $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
357 # Generate thumbnails or thumbnail links as needed...
358 $otherSizes = [];
359 foreach ( $thumbSizes as $size ) {
360 // We include a thumbnail size in the list, if it is
361 // less than or equal to the original size of the image
362 // asset ($width_orig/$height_orig). We also exclude
363 // the current thumbnail's size ($width/$height)
364 // since that is added to the message separately, so
365 // it can be denoted as the current size being shown.
366 // Vectorized images are limited by $wgSVGMaxSize big,
367 // so all thumbs less than or equal that are shown.
368 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
369 || ( $this->displayImg->isVectorized()
370 && max( $size[0], $size[1] ) <= $wgSVGMaxSize )
371 )
372 && $size[0] != $width && $size[1] != $height
373 ) {
374 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
375 if ( $sizeLink ) {
376 $otherSizes[] = $sizeLink;
377 }
378 }
379 }
380 $otherSizes = array_unique( $otherSizes );
381
382 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
383 $msgsmall = $this->getThumbPrevText( $params, $sizeLinkBigImagePreview );
384 if ( count( $otherSizes ) ) {
385 $msgsmall .= ' ' .
386 Html::rawElement(
387 'span',
388 [ 'class' => 'mw-filepage-other-resolutions' ],
389 $this->getContext()->msg( 'show-big-image-other' )
390 ->rawParams( $lang->pipeList( $otherSizes ) )
391 ->params( count( $otherSizes ) )
392 ->parse()
393 );
394 }
395 } elseif ( $width == 0 && $height == 0 ) {
396 # Some sort of audio file that doesn't have dimensions
397 # Don't output a no hi res message for such a file
398 $msgsmall = '';
399 } else {
400 # Image is small enough to show full size on image page
401 $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
402 }
403
404 $params['width'] = $width;
405 $params['height'] = $height;
406 $thumbnail = $this->displayImg->transform( $params );
407 Linker::processResponsiveImages( $this->displayImg, $thumbnail, $params );
408
409 $anchorclose = Html::rawElement(
410 'div',
411 [ 'class' => 'mw-filepage-resolutioninfo' ],
412 $msgsmall
413 );
414
415 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
416 if ( $isMulti ) {
417 $out->addModules( 'mediawiki.page.image.pagination' );
418 $out->addHTML( '<table class="multipageimage"><tr><td>' );
419 }
420
421 if ( $thumbnail ) {
422 $options = [
423 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
424 'file-link' => true,
425 ];
426 $out->addHTML( '<div class="fullImageLink" id="file">' .
427 $thumbnail->toHtml( $options ) .
428 $anchorclose . "</div>\n" );
429 }
430
431 if ( $isMulti ) {
432 $count = $this->displayImg->pageCount();
433
434 if ( $page > 1 ) {
435 $label = $out->parse( $this->getContext()->msg( 'imgmultipageprev' )->text(), false );
436 // on the client side, this link is generated in ajaxifyPageNavigation()
437 // in the mediawiki.page.image.pagination module
438 $link = Linker::linkKnown(
439 $this->getTitle(),
440 $label,
441 [],
442 [ 'page' => $page - 1 ]
443 );
444 $thumb1 = Linker::makeThumbLinkObj(
445 $this->getTitle(),
446 $this->displayImg,
447 $link,
448 $label,
449 'none',
450 [ 'page' => $page - 1 ]
451 );
452 } else {
453 $thumb1 = '';
454 }
455
456 if ( $page < $count ) {
457 $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
458 $link = Linker::linkKnown(
459 $this->getTitle(),
460 $label,
461 [],
462 [ 'page' => $page + 1 ]
463 );
464 $thumb2 = Linker::makeThumbLinkObj(
465 $this->getTitle(),
466 $this->displayImg,
467 $link,
468 $label,
469 'none',
470 [ 'page' => $page + 1 ]
471 );
472 } else {
473 $thumb2 = '';
474 }
475
476 global $wgScript;
477
478 $formParams = [
479 'name' => 'pageselector',
480 'action' => $wgScript,
481 ];
482 $options = [];
483 for ( $i = 1; $i <= $count; $i++ ) {
484 $options[] = Xml::option( $lang->formatNum( $i ), $i, $i == $page );
485 }
486 $select = Xml::tags( 'select',
487 [ 'id' => 'pageselector', 'name' => 'page' ],
488 implode( "\n", $options ) );
489
490 $out->addHTML(
491 '</td><td><div class="multipageimagenavbox">' .
492 Xml::openElement( 'form', $formParams ) .
493 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
494 $this->getContext()->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
495 Xml::submitButton( $this->getContext()->msg( 'imgmultigo' )->text() ) .
496 Xml::closeElement( 'form' ) .
497 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
498 );
499 }
500 } elseif ( $this->displayImg->isSafeFile() ) {
501 # if direct link is allowed but it's not a renderable image, show an icon.
502 $icon = $this->displayImg->iconThumb();
503
504 $out->addHTML( '<div class="fullImageLink" id="file">' .
505 $icon->toHtml( [ 'file-link' => true ] ) .
506 "</div>\n" );
507 }
508
509 $longDesc = $this->getContext()->msg( 'parentheses', $this->displayImg->getLongDesc() )->text();
510
511 $handler = $this->displayImg->getHandler();
512
513 // If this is a filetype with potential issues, warn the user.
514 if ( $handler ) {
515 $warningConfig = $handler->getWarningConfig( $this->displayImg );
516
517 if ( $warningConfig !== null ) {
518 // The warning will be displayed via CSS and JavaScript.
519 // We just need to tell the client side what message to use.
520 $output = $this->getContext()->getOutput();
521 $output->addJsConfigVars( 'wgFileWarning', $warningConfig );
522 $output->addModules( $warningConfig['module'] );
523 $output->addModules( 'mediawiki.filewarning' );
524 }
525 }
526
527 $medialink = "[[Media:$filename|$linktext]]";
528
529 if ( !$this->displayImg->isSafeFile() ) {
530 $warning = $this->getContext()->msg( 'mediawarning' )->plain();
531 // dirmark is needed here to separate the file name, which
532 // most likely ends in Latin characters, from the description,
533 // which may begin with the file type. In RTL environment
534 // this will get messy.
535 // The dirmark, however, must not be immediately adjacent
536 // to the filename, because it can get copied with it.
537 // See T27277.
538 // @codingStandardsIgnoreStart Ignore long line
539 $out->addWikiText( <<<EOT
540 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
541 <div class="mediaWarning">$warning</div>
542 EOT
543 );
544 // @codingStandardsIgnoreEnd
545 } else {
546 $out->addWikiText( <<<EOT
547 <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
548 </div>
549 EOT
550 );
551 }
552
553 $renderLangOptions = $this->displayImg->getAvailableLanguages();
554 if ( count( $renderLangOptions ) >= 1 ) {
555 $currentLanguage = $renderLang;
556 $defaultLang = $this->displayImg->getDefaultRenderLanguage();
557 if ( is_null( $currentLanguage ) ) {
558 $currentLanguage = $defaultLang;
559 }
560 $out->addHTML( $this->doRenderLangOpt( $renderLangOptions, $currentLanguage, $defaultLang ) );
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->addWikiText( <<<EOT
577 <div class="mw-noanimatethumb">{$noAnimMesg}</div>
578 EOT
579 );
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' ],
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 $params array parameters for thumbnail
633 * @param $sizeLinkBigImagePreview HTML for the current size
634 * @return string HTML output
635 */
636 private 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 private 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 * Print out the various links at the bottom of the image page, e.g. reupload,
737 * external editing (and instructions link) etc.
738 */
739 protected function uploadLinksBox() {
740 global $wgEnableUploads;
741
742 if ( !$wgEnableUploads ) {
743 return;
744 }
745
746 $this->loadFile();
747 if ( !$this->mPage->getFile()->isLocal() ) {
748 return;
749 }
750
751 $out = $this->getContext()->getOutput();
752 $out->addHTML( "<ul>\n" );
753
754 # "Upload a new version of this file" link
755 $canUpload = $this->getTitle()->quickUserCan( 'upload', $this->getContext()->getUser() );
756 if ( $canUpload && UploadBase::userCanReUpload(
757 $this->getContext()->getUser(),
758 $this->mPage->getFile() )
759 ) {
760 $ulink = Linker::makeExternalLink(
761 $this->getUploadUrl(),
762 $this->getContext()->msg( 'uploadnewversion-linktext' )->text()
763 );
764 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\">"
765 . "<div class=\"plainlinks\">{$ulink}</div></li>\n" );
766 } else {
767 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">"
768 . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
769 }
770
771 $out->addHTML( "</ul>\n" );
772 }
773
774 /**
775 * For overloading
776 */
777 protected function closeShowImage() {
778 }
779
780 /**
781 * If the page we've just displayed is in the "Image" namespace,
782 * we follow it with an upload history of the image and its usage.
783 */
784 protected function imageHistory() {
785 $this->loadFile();
786 $out = $this->getContext()->getOutput();
787 $pager = new ImageHistoryPseudoPager( $this );
788 $out->addHTML( $pager->getBody() );
789 $out->preventClickjacking( $pager->getPreventClickjacking() );
790
791 $this->mPage->getFile()->resetHistory(); // free db resources
792
793 # Exist check because we don't want to show this on pages where an image
794 # doesn't exist along with the noimage message, that would suck. -ævar
795 if ( $this->mPage->getFile()->exists() ) {
796 $this->uploadLinksBox();
797 }
798 }
799
800 /**
801 * @param string $target
802 * @param int $limit
803 * @return ResultWrapper
804 */
805 protected function queryImageLinks( $target, $limit ) {
806 $dbr = wfGetDB( DB_REPLICA );
807
808 return $dbr->select(
809 [ 'imagelinks', 'page' ],
810 [ 'page_namespace', 'page_title', 'il_to' ],
811 [ 'il_to' => $target, 'il_from = page_id' ],
812 __METHOD__,
813 [ 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', ]
814 );
815 }
816
817 protected function imageLinks() {
818 $limit = 100;
819
820 $out = $this->getContext()->getOutput();
821
822 $rows = [];
823 $redirects = [];
824 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE ) as $redir ) {
825 $redirects[$redir->getDBkey()] = [];
826 $rows[] = (object)[
827 'page_namespace' => NS_FILE,
828 'page_title' => $redir->getDBkey(),
829 ];
830 }
831
832 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit + 1 );
833 foreach ( $res as $row ) {
834 $rows[] = $row;
835 }
836 $count = count( $rows );
837
838 $hasMore = $count > $limit;
839 if ( !$hasMore && count( $redirects ) ) {
840 $res = $this->queryImageLinks( array_keys( $redirects ),
841 $limit - count( $rows ) + 1 );
842 foreach ( $res as $row ) {
843 $redirects[$row->il_to][] = $row;
844 $count++;
845 }
846 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
847 }
848
849 if ( $count == 0 ) {
850 $out->wrapWikiMsg(
851 Html::rawElement( 'div',
852 [ 'id' => 'mw-imagepage-nolinkstoimage' ], "\n$1\n" ),
853 'nolinkstoimage'
854 );
855 return;
856 }
857
858 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
859 if ( !$hasMore ) {
860 $out->addWikiMsg( 'linkstoimage', $count );
861 } else {
862 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
863 $out->addWikiMsg( 'linkstoimage-more',
864 $this->getContext()->getLanguage()->formatNum( $limit ),
865 $this->getTitle()->getPrefixedDBkey()
866 );
867 }
868
869 $out->addHTML(
870 Html::openElement( 'ul',
871 [ 'class' => 'mw-imagepage-linkstoimage' ] ) . "\n"
872 );
873 $count = 0;
874
875 // Sort the list by namespace:title
876 usort( $rows, [ $this, 'compare' ] );
877
878 // Create links for every element
879 $currentCount = 0;
880 foreach ( $rows as $element ) {
881 $currentCount++;
882 if ( $currentCount > $limit ) {
883 break;
884 }
885
886 $query = [];
887 # Add a redirect=no to make redirect pages reachable
888 if ( isset( $redirects[$element->page_title] ) ) {
889 $query['redirect'] = 'no';
890 }
891 $link = Linker::linkKnown(
892 Title::makeTitle( $element->page_namespace, $element->page_title ),
893 null, [], $query
894 );
895 if ( !isset( $redirects[$element->page_title] ) ) {
896 # No redirects
897 $liContents = $link;
898 } elseif ( count( $redirects[$element->page_title] ) === 0 ) {
899 # Redirect without usages
900 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )
901 ->rawParams( $link, '' )
902 ->parse();
903 } else {
904 # Redirect with usages
905 $li = '';
906 foreach ( $redirects[$element->page_title] as $row ) {
907 $currentCount++;
908 if ( $currentCount > $limit ) {
909 break;
910 }
911
912 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
913 $li .= Html::rawElement(
914 'li',
915 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
916 $link2
917 ) . "\n";
918 }
919
920 $ul = Html::rawElement(
921 'ul',
922 [ 'class' => 'mw-imagepage-redirectstofile' ],
923 $li
924 ) . "\n";
925 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
926 $link, $ul )->parse();
927 }
928 $out->addHTML( Html::rawElement(
929 'li',
930 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
931 $liContents
932 ) . "\n"
933 );
934
935 };
936 $out->addHTML( Html::closeElement( 'ul' ) . "\n" );
937 $res->free();
938
939 // Add a links to [[Special:Whatlinkshere]]
940 if ( $count > $limit ) {
941 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
942 }
943 $out->addHTML( Html::closeElement( 'div' ) . "\n" );
944 }
945
946 protected function imageDupes() {
947 $this->loadFile();
948 $out = $this->getContext()->getOutput();
949
950 $dupes = $this->mPage->getDuplicates();
951 if ( count( $dupes ) == 0 ) {
952 return;
953 }
954
955 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
956 $out->addWikiMsg( 'duplicatesoffile',
957 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
958 );
959 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
960
961 /**
962 * @var $file File
963 */
964 foreach ( $dupes as $file ) {
965 $fromSrc = '';
966 if ( $file->isLocal() ) {
967 $link = Linker::linkKnown( $file->getTitle() );
968 } else {
969 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
970 $file->getTitle()->getPrefixedText() );
971 $fromSrc = $this->getContext()->msg(
972 'shared-repo-from',
973 $file->getRepo()->getDisplayName()
974 )->text();
975 }
976 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
977 }
978 $out->addHTML( "</ul></div>\n" );
979 }
980
981 /**
982 * Delete the file, or an earlier version of it
983 */
984 public function delete() {
985 $file = $this->mPage->getFile();
986 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
987 // Standard article deletion
988 parent::delete();
989 return;
990 }
991
992 $deleter = new FileDeleteForm( $file );
993 $deleter->execute();
994 }
995
996 /**
997 * Display an error with a wikitext description
998 *
999 * @param string $description
1000 */
1001 function showError( $description ) {
1002 $out = $this->getContext()->getOutput();
1003 $out->setPageTitle( $this->getContext()->msg( 'internalerror' ) );
1004 $out->setRobotPolicy( 'noindex,nofollow' );
1005 $out->setArticleRelated( false );
1006 $out->enableClientCache( false );
1007 $out->addWikiText( $description );
1008 }
1009
1010 /**
1011 * Callback for usort() to do link sorts by (namespace, title)
1012 * Function copied from Title::compare()
1013 *
1014 * @param object $a Object page to compare with
1015 * @param object $b Object page to compare with
1016 * @return int Result of string comparison, or namespace comparison
1017 */
1018 protected function compare( $a, $b ) {
1019 if ( $a->page_namespace == $b->page_namespace ) {
1020 return strcmp( $a->page_title, $b->page_title );
1021 } else {
1022 return $a->page_namespace - $b->page_namespace;
1023 }
1024 }
1025
1026 /**
1027 * Returns the corresponding $wgImageLimits entry for the selected user option
1028 *
1029 * @param User $user
1030 * @param string $optionName Name of a option to check, typically imagesize or thumbsize
1031 * @return array
1032 * @since 1.21
1033 */
1034 public function getImageLimitsFromOption( $user, $optionName ) {
1035 global $wgImageLimits;
1036
1037 $option = $user->getIntOption( $optionName );
1038 if ( !isset( $wgImageLimits[$option] ) ) {
1039 $option = User::getDefaultOption( $optionName );
1040 }
1041
1042 // The user offset might still be incorrect, specially if
1043 // $wgImageLimits got changed (see bug #8858).
1044 if ( !isset( $wgImageLimits[$option] ) ) {
1045 // Default to the first offset in $wgImageLimits
1046 $option = 0;
1047 }
1048
1049 return isset( $wgImageLimits[$option] )
1050 ? $wgImageLimits[$option]
1051 : [ 800, 600 ]; // if nothing is set, fallback to a hardcoded default
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 $curLang Language code file is being viewed in.
1059 * @param string $defaultLang Language code that image is rendered in by default
1060 * @return string HTML to insert underneath image.
1061 */
1062 protected function doRenderLangOpt( array $langChoices, $curLang, $defaultLang ) {
1063 global $wgScript;
1064 sort( $langChoices );
1065 $curLang = wfBCP47( $curLang );
1066 $defaultLang = wfBCP47( $defaultLang );
1067 $opts = '';
1068 $haveCurrentLang = false;
1069 $haveDefaultLang = false;
1070
1071 // We make a list of all the language choices in the file.
1072 // Additionally if the default language to render this file
1073 // is not included as being in this file (for example, in svgs
1074 // usually the fallback content is the english content) also
1075 // include a choice for that. Last of all, if we're viewing
1076 // the file in a language not on the list, add it as a choice.
1077 foreach ( $langChoices as $lang ) {
1078 $code = wfBCP47( $lang );
1079 $name = Language::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1080 if ( $name !== '' ) {
1081 $display = $this->getContext()->msg( 'img-lang-opt', $code, $name )->text();
1082 } else {
1083 $display = $code;
1084 }
1085 $opts .= "\n" . Xml::option( $display, $code, $curLang === $code );
1086 if ( $curLang === $code ) {
1087 $haveCurrentLang = true;
1088 }
1089 if ( $defaultLang === $code ) {
1090 $haveDefaultLang = true;
1091 }
1092 }
1093 if ( !$haveDefaultLang ) {
1094 // Its hard to know if the content is really in the default language, or
1095 // if its just unmarked content that could be in any language.
1096 $opts = Xml::option(
1097 $this->getContext()->msg( 'img-lang-default' )->text(),
1098 $defaultLang,
1099 $defaultLang === $curLang
1100 ) . $opts;
1101 }
1102 if ( !$haveCurrentLang && $defaultLang !== $curLang ) {
1103 $name = Language::fetchLanguageName( $curLang, $this->getContext()->getLanguage()->getCode() );
1104 if ( $name !== '' ) {
1105 $display = $this->getContext()->msg( 'img-lang-opt', $curLang, $name )->text();
1106 } else {
1107 $display = $curLang;
1108 }
1109 $opts = Xml::option( $display, $curLang, true ) . $opts;
1110 }
1111
1112 $select = Html::rawElement(
1113 'select',
1114 [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1115 $opts
1116 );
1117 $submit = Xml::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1118
1119 $formContents = $this->getContext()->msg( 'img-lang-info' )
1120 ->rawParams( $select, $submit )
1121 ->parse();
1122 $formContents .= Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1123
1124 $langSelectLine = Html::rawElement( 'div', [ 'id' => 'mw-imglangselector-line' ],
1125 Html::rawElement( 'form', [ 'action' => $wgScript ], $formContents )
1126 );
1127 return $langSelectLine;
1128 }
1129
1130 /**
1131 * Get the width and height to display image at.
1132 *
1133 * @note This method assumes that it is only called if one
1134 * of the dimensions are bigger than the max, or if the
1135 * image is vectorized.
1136 *
1137 * @param int $maxWidth Max width to display at
1138 * @param int $maxHeight Max height to display at
1139 * @param int $width Actual width of the image
1140 * @param int $height Actual height of the image
1141 * @throws MWException
1142 * @return array Array (width, height)
1143 */
1144 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1145 if ( !$maxWidth || !$maxHeight ) {
1146 // should never happen
1147 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1148 }
1149
1150 if ( !$width || !$height ) {
1151 return [ 0, 0 ];
1152 }
1153
1154 # Calculate the thumbnail size.
1155 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1156 // Vectorized image, do nothing.
1157 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1158 # The limiting factor is the width, not the height.
1159 $height = round( $height * $maxWidth / $width );
1160 $width = $maxWidth;
1161 # Note that $height <= $maxHeight now.
1162 } else {
1163 $newwidth = floor( $width * $maxHeight / $height );
1164 $height = round( $height * $newwidth / $width );
1165 $width = $newwidth;
1166 # Note that $height <= $maxHeight now, but might not be identical
1167 # because of rounding.
1168 }
1169 return [ $width, $height ];
1170 }
1171
1172 /**
1173 * Get alternative thumbnail sizes.
1174 *
1175 * @note This will only list several alternatives if thumbnails are rendered on 404
1176 * @param int $origWidth Actual width of image
1177 * @param int $origHeight Actual height of image
1178 * @return array An array of [width, height] pairs.
1179 */
1180 protected function getThumbSizes( $origWidth, $origHeight ) {
1181 global $wgImageLimits;
1182 if ( $this->displayImg->getRepo()->canTransformVia404() ) {
1183 $thumbSizes = $wgImageLimits;
1184 // Also include the full sized resolution in the list, so
1185 // that users know they can get it. This will link to the
1186 // original file asset if mustRender() === false. In the case
1187 // that we mustRender, some users have indicated that they would
1188 // find it useful to have the full size image in the rendered
1189 // image format.
1190 $thumbSizes[] = [ $origWidth, $origHeight ];
1191 } else {
1192 # Creating thumb links triggers thumbnail generation.
1193 # Just generate the thumb for the current users prefs.
1194 $thumbSizes = [
1195 $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' )
1196 ];
1197 if ( !$this->displayImg->mustRender() ) {
1198 // We can safely include a link to the "full-size" preview,
1199 // without actually rendering.
1200 $thumbSizes[] = [ $origWidth, $origHeight ];
1201 }
1202 }
1203 return $thumbSizes;
1204 }
1205
1206 /**
1207 * @see WikiFilePage::getFile
1208 * @return bool|File
1209 */
1210 public function getFile() {
1211 return $this->mPage->getFile();
1212 }
1213
1214 /**
1215 * @see WikiFilePage::isLocal
1216 * @return bool
1217 */
1218 public function isLocal() {
1219 return $this->mPage->isLocal();
1220 }
1221
1222 /**
1223 * @see WikiFilePage::getDuplicates
1224 * @return array|null
1225 */
1226 public function getDuplicates() {
1227 return $this->mPage->getDuplicates();
1228 }
1229
1230 /**
1231 * @see WikiFilePage::getForeignCategories
1232 * @return TitleArray|Title[]
1233 */
1234 public function getForeignCategories() {
1235 $this->mPage->getForeignCategories();
1236 }
1237
1238 }