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