MediaWiki  master
ImagePage.php
Go to the documentation of this file.
1 <?php
25 
33 class ImagePage extends Article {
34  use MediaFileTrait;
35 
37  private $displayImg;
38 
40  private $repo;
41 
43  private $fileLoaded;
44 
46  protected $mExtraDescription = false;
47 
52  protected function newPage( Title $title ) {
53  // Overload mPage with a file-specific page
54  return new WikiFilePage( $title );
55  }
56 
61  public function setFile( $file ) {
62  $this->getPage()->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  $this->getHookRunner()->onImagePageFindFile( $this, $img, $this->displayImg );
76  if ( !$img ) { // not set by hook?
77  $services = MediaWikiServices::getInstance();
78  $img = $services->getRepoGroup()->findFile( $this->getTitle() );
79  if ( !$img ) {
80  $img = $services->getRepoGroup()->getLocalRepo()->newFile( $this->getTitle() );
81  }
82  }
83  $this->getPage()->setFile( $img );
84  if ( !$this->displayImg ) { // not set by hook?
85  $this->displayImg = $img;
86  }
87  $this->repo = $img->getRepo();
88  }
89 
90  public function view() {
91  global $wgShowEXIF;
92 
93  // For action=render, include body text only; none of the image extras
94  if ( $this->viewIsRenderAction ) {
95  parent::view();
96  return;
97  }
98 
99  $out = $this->getContext()->getOutput();
100  $request = $this->getContext()->getRequest();
101  $diff = $request->getVal( 'diff' );
102  $diffOnly = $request->getBool(
103  'diffonly',
104  $this->getContext()->getUser()->getOption( 'diffonly' )
105  );
106 
107  if ( $this->getTitle()->getNamespace() !== NS_FILE || ( $diff !== null && $diffOnly ) ) {
108  parent::view();
109  return;
110  }
111 
112  $this->loadFile();
113 
114  if (
115  $this->getTitle()->getNamespace() === NS_FILE
116  && $this->getFile()->getRedirected()
117  ) {
118  if (
119  $this->getTitle()->getDBkey() == $this->getFile()->getName()
120  || $diff !== null
121  ) {
122  $request->setVal( 'diffonly', 'true' );
123  }
124 
125  parent::view();
126  return;
127  }
128 
129  if ( $wgShowEXIF && $this->displayImg->exists() ) {
130  // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
131  $formattedMetadata = $this->displayImg->formatMetadata( $this->getContext() );
132  } else {
133  $formattedMetadata = false;
134  }
135 
136  if ( !$diff && $this->displayImg->exists() ) {
137  $out->addHTML( $this->showTOC( (bool)$formattedMetadata ) );
138  }
139 
140  if ( !$diff ) {
141  $this->openShowImage();
142  }
143 
144  # No need to display noarticletext, we use our own message, output in openShowImage()
145  if ( $this->getPage()->getId() ) {
146  # NS_FILE is in the user language, but this section (the actual wikitext)
147  # should be in page content language
148  $pageLang = $this->getTitle()->getPageViewLanguage();
149  $out->addHTML( Xml::openElement( 'div', [ 'id' => 'mw-imagepage-content',
150  'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
151  'class' => 'mw-content-' . $pageLang->getDir() ] ) );
152 
153  parent::view();
154 
155  $out->addHTML( Xml::closeElement( 'div' ) );
156  } else {
157  # Just need to set the right headers
158  $out->setArticleFlag( true );
159  $out->setPageTitle( $this->getTitle()->getPrefixedText() );
160  $this->getPage()->doViewUpdates(
161  $this->getContext()->getUser(),
162  $this->getOldID()
163  );
164  }
165 
166  # Show shared description, if needed
167  if ( $this->mExtraDescription ) {
168  $fol = $this->getContext()->msg( 'shareddescriptionfollows' );
169  if ( !$fol->isDisabled() ) {
170  $out->addWikiTextAsInterface( $fol->plain() );
171  }
172  $out->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
173  }
174 
175  $this->closeShowImage();
176  $this->imageHistory();
177  // TODO: Cleanup the following
178 
179  $out->addHTML( Xml::element( 'h2',
180  [ 'id' => 'filelinks' ],
181  $this->getContext()->msg( 'imagelinks' )->text() ) . "\n" );
182  $this->imageDupes();
183  # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
184  # Yet we return metadata about the target. Definitely an issue in the FileRepo
185  $this->imageLinks();
186 
187  # Allow extensions to add something after the image links
188  $html = '';
189  $this->getHookRunner()->onImagePageAfterImageLinks( $this, $html );
190  if ( $html ) {
191  $out->addHTML( $html );
192  }
193 
194  if ( $formattedMetadata ) {
195  $out->addHTML( Xml::element(
196  'h2',
197  [ 'id' => 'metadata' ],
198  $this->getContext()->msg( 'metadata' )->text() ) . "\n" );
199  $out->wrapWikiTextAsInterface(
200  'mw-imagepage-section-metadata',
201  $this->makeMetadataTable( $formattedMetadata )
202  );
203  $out->addModules( [ 'mediawiki.action.view.metadata' ] );
204  }
205 
206  // Add remote Filepage.css
207  if ( !$this->repo->isLocal() ) {
208  $css = $this->repo->getDescriptionStylesheetUrl();
209  if ( $css ) {
210  $out->addStyle( $css );
211  }
212  }
213 
214  $out->addModuleStyles( [
215  'filepage', // always show the local local Filepage.css, T31277
216  'mediawiki.action.view.filepage', // Add MediaWiki styles for a file page
217  ] );
218  }
219 
223  public function getDisplayedFile() {
224  $this->loadFile();
225  return $this->displayImg;
226  }
227 
234  protected function showTOC( $metadata ) {
235  $r = [
236  '<li><a href="#file">' . $this->getContext()->msg( 'file-anchor-link' )->escaped() . '</a></li>',
237  '<li><a href="#filehistory">' . $this->getContext()->msg( 'filehist' )->escaped() . '</a></li>',
238  '<li><a href="#filelinks">' . $this->getContext()->msg( 'imagelinks' )->escaped() . '</a></li>',
239  ];
240 
241  $this->getHookRunner()->onImagePageShowTOC( $this, $r );
242 
243  if ( $metadata ) {
244  $r[] = '<li><a href="#metadata">' .
245  $this->getContext()->msg( 'metadata' )->escaped() .
246  '</a></li>';
247  }
248 
249  return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
250  }
251 
260  protected function makeMetadataTable( $metadata ) {
261  $r = $this->getContext()->msg( 'metadata-help' )->plain();
262  // Initial state is collapsed
263  // see filepage.css and mediawiki.action.view.metadata module.
264  $r .= "<table id=\"mw_metadata\" class=\"mw_metadata collapsed\">\n";
265  foreach ( $metadata as $type => $stuff ) {
266  foreach ( $stuff as $v ) {
267  $class = str_replace( ' ', '_', $v['id'] );
268  if ( $type == 'collapsed' ) {
269  $class .= ' mw-metadata-collapsible';
270  }
271  $r .= Html::rawElement( 'tr',
272  [ 'class' => $class ],
273  Html::rawElement( 'th', [], $v['name'] )
274  . Html::rawElement( 'td', [], $v['value'] )
275  );
276  }
277  }
278  $r .= "</table>\n";
279  return $r;
280  }
281 
290  private function getLanguageForRendering( WebRequest $request, File $file ) {
291  $handler = $file->getHandler();
292  if ( !$handler ) {
293  return null;
294  }
295 
296  $config = MediaWikiServices::getInstance()->getMainConfig();
297  $requestLanguage = $request->getVal( 'lang', $config->get( 'LanguageCode' ) );
298  if ( $handler->validateParam( 'lang', $requestLanguage ) ) {
299  return $file->getMatchedLanguage( $requestLanguage );
300  }
301 
302  return $handler->getDefaultRenderLanguage( $file );
303  }
304 
305  protected function openShowImage() {
307 
308  $this->loadFile();
309  $out = $this->getContext()->getOutput();
310  $user = $this->getContext()->getUser();
311  $lang = $this->getContext()->getLanguage();
312  $dirmark = $lang->getDirMarkEntity();
313  $request = $this->getContext()->getRequest();
314 
315  if ( $this->displayImg->exists() ) {
316  list( $maxWidth, $maxHeight ) = $this->getImageLimitsFromOption( $user, 'imagesize' );
317 
318  # image
319  $page = $request->getIntOrNull( 'page' );
320  if ( $page === null ) {
321  $params = [];
322  $page = 1;
323  } else {
324  $params = [ 'page' => $page ];
325  }
326 
327  $renderLang = $this->getLanguageForRendering( $request, $this->displayImg );
328  if ( $renderLang !== null ) {
329  $params['lang'] = $renderLang;
330  }
331 
332  $width_orig = $this->displayImg->getWidth( $page );
333  $width = $width_orig;
334  $height_orig = $this->displayImg->getHeight( $page );
335  $height = $height_orig;
336 
337  $filename = wfEscapeWikiText( $this->displayImg->getName() );
338  $linktext = $filename;
339 
340  $this->getHookRunner()->onImageOpenShowImageInlineBefore( $this, $out );
341 
342  if ( $this->displayImg->allowInlineDisplay() ) {
343  # image
344  # "Download high res version" link below the image
345  # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
346  # Language::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
347  # We'll show a thumbnail of this image
348  if ( $width > $maxWidth ||
349  $height > $maxHeight ||
350  $this->displayImg->isVectorized()
351  ) {
352  list( $width, $height ) = $this->displayImg->getDisplayWidthHeight(
353  $maxWidth, $maxHeight, $page
354  );
355  $linktext = $this->getContext()->msg( 'show-big-image' )->escaped();
356 
357  $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
358  # Generate thumbnails or thumbnail links as needed...
359  $otherSizes = [];
360  foreach ( $thumbSizes as $size ) {
361  // We include a thumbnail size in the list, if it is
362  // less than or equal to the original size of the image
363  // asset ($width_orig/$height_orig). We also exclude
364  // the current thumbnail's size ($width/$height)
365  // since that is added to the message separately, so
366  // it can be denoted as the current size being shown.
367  // Vectorized images are limited by $wgSVGMaxSize big,
368  // so all thumbs less than or equal that are shown.
369  if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
370  || ( $this->displayImg->isVectorized()
371  && max( $size[0], $size[1] ) <= $wgSVGMaxSize )
372  )
373  && $size[0] != $width && $size[1] != $height
374  ) {
375  $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
376  if ( $sizeLink ) {
377  $otherSizes[] = $sizeLink;
378  }
379  }
380  }
381  $otherSizes = array_unique( $otherSizes );
382 
383  $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
384  $msgsmall = $this->getThumbPrevText( $params, $sizeLinkBigImagePreview );
385  if ( count( $otherSizes ) ) {
386  $msgsmall .= ' ' .
388  'span',
389  [ 'class' => 'mw-filepage-other-resolutions' ],
390  $this->getContext()->msg( 'show-big-image-other' )
391  ->rawParams( $lang->pipeList( $otherSizes ) )
392  ->params( count( $otherSizes ) )
393  ->parse()
394  );
395  }
396  } elseif ( $width == 0 && $height == 0 ) {
397  # Some sort of audio file that doesn't have dimensions
398  # Don't output a no hi res message for such a file
399  $msgsmall = '';
400  } else {
401  # Image is small enough to show full size on image page
402  $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
403  }
404 
405  $params['width'] = $width;
406  $params['height'] = $height;
407  // Allow the MediaHandler to handle query string parameters on the file page,
408  // e.g. start time for videos (T203994)
409  $params['imagePageParams'] = $request->getQueryValuesOnly();
410  $thumbnail = $this->displayImg->transform( $params );
411  Linker::processResponsiveImages( $this->displayImg, $thumbnail, $params );
412 
413  $anchorclose = Html::rawElement(
414  'div',
415  [ 'class' => 'mw-filepage-resolutioninfo' ],
416  $msgsmall
417  );
418 
419  $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
420  if ( $isMulti ) {
421  $out->addModules( 'mediawiki.page.image.pagination' );
422  $out->addHTML( '<table class="multipageimage"><tr><td>' );
423  }
424 
425  if ( $thumbnail ) {
426  $options = [
427  'alt' => $this->displayImg->getTitle()->getPrefixedText(),
428  'file-link' => true,
429  ];
430  $out->addHTML( '<div class="fullImageLink" id="file">' .
431  $thumbnail->toHtml( $options ) .
432  $anchorclose . "</div>\n" );
433  }
434 
435  if ( $isMulti ) {
436  $count = $this->displayImg->pageCount();
437  $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
438 
439  if ( $page > 1 ) {
440  $label = $this->getContext()->msg( 'imgmultipageprev' )->text();
441  // on the client side, this link is generated in ajaxifyPageNavigation()
442  // in the mediawiki.page.image.pagination module
443  $link = $linkRenderer->makeKnownLink(
444  $this->getTitle(),
445  $label,
446  [],
447  [ 'page' => $page - 1 ]
448  );
449  // @phan-suppress-next-line SecurityCheck-DoubleEscaped link getting a key, false positive
450  $thumb1 = Linker::makeThumbLinkObj(
451  $this->getTitle(),
452  $this->displayImg,
453  $link,
454  $label,
455  'none',
456  [ 'page' => $page - 1 ]
457  );
458  } else {
459  $thumb1 = '';
460  }
461 
462  if ( $page < $count ) {
463  $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
464  $link = $linkRenderer->makeKnownLink(
465  $this->getTitle(),
466  $label,
467  [],
468  [ 'page' => $page + 1 ]
469  );
470  // @phan-suppress-next-line SecurityCheck-DoubleEscaped link getting a key, false positive
471  $thumb2 = Linker::makeThumbLinkObj(
472  $this->getTitle(),
473  $this->displayImg,
474  $link,
475  $label,
476  'none',
477  [ 'page' => $page + 1 ]
478  );
479  } else {
480  $thumb2 = '';
481  }
482 
483  global $wgScript;
484 
485  $formParams = [
486  'name' => 'pageselector',
487  'action' => $wgScript,
488  ];
489  $options = [];
490  for ( $i = 1; $i <= $count; $i++ ) {
491  $options[] = Xml::option( $lang->formatNum( $i ), $i, $i == $page );
492  }
493  $select = Xml::tags( 'select',
494  [ 'id' => 'pageselector', 'name' => 'page' ],
495  implode( "\n", $options ) );
496 
497  $out->addHTML(
498  '</td><td><div class="multipageimagenavbox">' .
499  Xml::openElement( 'form', $formParams ) .
500  Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
501  $this->getContext()->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
502  $this->getContext()->msg( 'word-separator' )->escaped() .
503  Xml::submitButton( $this->getContext()->msg( 'imgmultigo' )->text() ) .
504  Xml::closeElement( 'form' ) .
505  "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
506  );
507  }
508  } elseif ( $this->displayImg->isSafeFile() ) {
509  # if direct link is allowed but it's not a renderable image, show an icon.
510  $icon = $this->displayImg->iconThumb();
511 
512  $out->addHTML( '<div class="fullImageLink" id="file">' .
513  $icon->toHtml( [ 'file-link' => true ] ) .
514  "</div>\n" );
515  }
516 
517  $longDesc = $this->getContext()->msg( 'parentheses', $this->displayImg->getLongDesc() )->text();
518 
519  $handler = $this->displayImg->getHandler();
520 
521  // If this is a filetype with potential issues, warn the user.
522  if ( $handler ) {
523  $warningConfig = $handler->getWarningConfig( $this->displayImg );
524 
525  if ( $warningConfig !== null ) {
526  // The warning will be displayed via CSS and JavaScript.
527  // We just need to tell the client side what message to use.
528  $output = $this->getContext()->getOutput();
529  $output->addJsConfigVars( 'wgFileWarning', $warningConfig );
530  $output->addModules( $warningConfig['module'] );
531  $output->addModules( 'mediawiki.filewarning' );
532  }
533  }
534 
535  $medialink = "[[Media:$filename|$linktext]]";
536 
537  if ( !$this->displayImg->isSafeFile() ) {
538  $warning = $this->getContext()->msg( 'mediawarning' )->plain();
539  // dirmark is needed here to separate the file name, which
540  // most likely ends in Latin characters, from the description,
541  // which may begin with the file type. In RTL environment
542  // this will get messy.
543  // The dirmark, however, must not be immediately adjacent
544  // to the filename, because it can get copied with it.
545  // See T27277.
546  // phpcs:disable Generic.Files.LineLength
547  $out->wrapWikiTextAsInterface( 'fullMedia', <<<EOT
548 <span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span>
549 EOT
550  );
551  // phpcs:enable
552  $out->wrapWikiTextAsInterface( 'mediaWarning', $warning );
553  } else {
554  $out->wrapWikiTextAsInterface( 'fullMedia', <<<EOT
555 {$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
556 EOT
557  );
558  }
559 
560  $renderLangOptions = $this->displayImg->getAvailableLanguages();
561  if ( count( $renderLangOptions ) >= 1 ) {
562  $out->addHTML( $this->doRenderLangOpt( $renderLangOptions, $renderLang ) );
563  }
564 
565  // Add cannot animate thumbnail warning
566  if ( !$this->displayImg->canAnimateThumbIfAppropriate() ) {
567  // Include the extension so wiki admins can
568  // customize it on a per file-type basis
569  // (aka say things like use format X instead).
570  // additionally have a specific message for
571  // file-no-thumb-animation-gif
572  $ext = $this->displayImg->getExtension();
573  $noAnimMesg = wfMessageFallback(
574  'file-no-thumb-animation-' . $ext,
575  'file-no-thumb-animation'
576  )->plain();
577 
578  $out->wrapWikiTextAsInterface( 'mw-noanimatethumb', $noAnimMesg );
579  }
580 
581  if ( !$this->displayImg->isLocal() ) {
582  $this->printSharedImageText();
583  }
584  } else {
585  # Image does not exist
586  if ( !$this->getPage()->getId() ) {
587  $dbr = wfGetDB( DB_REPLICA );
588 
589  # No article exists either
590  # Show deletion log to be consistent with normal articles
592  $out,
593  [ 'delete', 'move', 'protect' ],
594  $this->getTitle()->getPrefixedText(),
595  '',
596  [ 'lim' => 10,
597  'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
598  'showIfEmpty' => false,
599  'msgKey' => [ 'moveddeleted-notice' ]
600  ]
601  );
602  }
603 
604  if ( $wgEnableUploads && MediaWikiServices::getInstance()
606  ->userHasRight( $user, 'upload' )
607  ) {
608  // Only show an upload link if the user can upload
609  $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
610  $nofile = [
611  'filepage-nofile-link',
612  $uploadTitle->getFullURL( [
613  'wpDestFile' => $this->getFile()->getName()
614  ] )
615  ];
616  } else {
617  $nofile = 'filepage-nofile';
618  }
619  // Note, if there is an image description page, but
620  // no image, then this setRobotPolicy is overridden
621  // by Article::View().
622  $out->setRobotPolicy( 'noindex,nofollow' );
623  $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
624  if ( !$this->getPage()->getId() && $wgSend404Code ) {
625  // If there is no image, no shared image, and no description page,
626  // output a 404, to be consistent with Article::showMissingArticle.
627  $request->response()->statusHeader( 404 );
628  }
629  }
630  $out->setFileVersion( $this->displayImg );
631  }
632 
640  protected function getThumbPrevText( $params, $sizeLinkBigImagePreview ) {
641  if ( $sizeLinkBigImagePreview ) {
642  // Show a different message of preview is different format from original.
643  $previewTypeDiffers = false;
644  $origExt = $thumbExt = $this->displayImg->getExtension();
645  if ( $this->displayImg->getHandler() ) {
646  $origMime = $this->displayImg->getMimeType();
647  $typeParams = $params;
648  $this->displayImg->getHandler()->normaliseParams( $this->displayImg, $typeParams );
649  list( $thumbExt, $thumbMime ) = $this->displayImg->getHandler()->getThumbType(
650  $origExt, $origMime, $typeParams );
651  if ( $thumbMime !== $origMime ) {
652  $previewTypeDiffers = true;
653  }
654  }
655  if ( $previewTypeDiffers ) {
656  return $this->getContext()->msg( 'show-big-image-preview-differ' )->
657  rawParams( $sizeLinkBigImagePreview )->
658  params( strtoupper( $origExt ) )->
659  params( strtoupper( $thumbExt ) )->
660  parse();
661  } else {
662  return $this->getContext()->msg( 'show-big-image-preview' )->
663  rawParams( $sizeLinkBigImagePreview )->
664  parse();
665  }
666  } else {
667  return '';
668  }
669  }
670 
678  protected function makeSizeLink( $params, $width, $height ) {
679  $params['width'] = $width;
680  $params['height'] = $height;
681  $thumbnail = $this->displayImg->transform( $params );
682  if ( $thumbnail && !$thumbnail->isError() ) {
683  return Html::rawElement( 'a', [
684  'href' => $thumbnail->getUrl(),
685  'class' => 'mw-thumbnail-link'
686  ], $this->getContext()->msg( 'show-big-image-size' )->numParams(
687  $thumbnail->getWidth(), $thumbnail->getHeight()
688  )->parse() );
689  } else {
690  return '';
691  }
692  }
693 
697  protected function printSharedImageText() {
698  $out = $this->getContext()->getOutput();
699  $this->loadFile();
700 
701  $descUrl = $this->getFile()->getDescriptionUrl();
702  $descText = $this->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
703 
704  /* Add canonical to head if there is no local page for this shared file */
705  if ( $descUrl && !$this->getPage()->getId() ) {
706  $out->setCanonicalUrl( $descUrl );
707  }
708 
709  $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
710  $repo = $this->getFile()->getRepo()->getDisplayName();
711 
712  if ( $descUrl &&
713  $descText &&
714  $this->getContext()->msg( 'sharedupload-desc-here' )->plain() !== '-'
715  ) {
716  $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-here', $repo, $descUrl ] );
717  } elseif ( $descUrl &&
718  $this->getContext()->msg( 'sharedupload-desc-there' )->plain() !== '-'
719  ) {
720  $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-there', $repo, $descUrl ] );
721  } else {
722  $out->wrapWikiMsg( $wrap, [ 'sharedupload', $repo ], ''/*BACKCOMPAT*/ );
723  }
724 
725  if ( $descText ) {
726  $this->mExtraDescription = $descText;
727  }
728  }
729 
730  public function getUploadUrl() {
731  $this->loadFile();
732  $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
733  return $uploadTitle->getFullURL( [
734  'wpDestFile' => $this->getFile()->getName(),
735  'wpForReUpload' => 1
736  ] );
737  }
738 
742  protected function uploadLinksBox() {
743  if ( !$this->getContext()->getConfig()->get( 'EnableUploads' ) ) {
744  return;
745  }
746 
747  $this->loadFile();
748  if ( !$this->getFile()->isLocal() ) {
749  return;
750  }
751 
752  $canUpload = MediaWikiServices::getInstance()->getPermissionManager()
753  ->quickUserCan( 'upload', $this->getContext()->getUser(), $this->getTitle() );
754  if ( $canUpload && UploadBase::userCanReUpload(
755  $this->getContext()->getUser(),
756  $this->getFile() )
757  ) {
758  // "Upload a new version of this file" link
759  $ulink = Linker::makeExternalLink(
760  $this->getUploadUrl(),
761  $this->getContext()->msg( 'uploadnewversion-linktext' )->text()
762  );
763  $attrs = [ 'class' => 'plainlinks', 'id' => 'mw-imagepage-reupload-link' ];
764  $linkPara = Html::rawElement( 'p', $attrs, $ulink );
765  } else {
766  // "You cannot overwrite this file." message
767  $attrs = [ 'id' => 'mw-imagepage-upload-disallowed' ];
768  $msg = $this->getContext()->msg( 'upload-disallowed-here' )->text();
769  $linkPara = Html::element( 'p', $attrs, $msg );
770  }
771 
772  $uploadLinks = Html::rawElement( 'div', [ 'class' => 'mw-imagepage-upload-links' ], $linkPara );
773  $this->getContext()->getOutput()->addHTML( $uploadLinks );
774  }
775 
779  protected function closeShowImage() {
780  }
781 
786  protected function imageHistory() {
787  $this->loadFile();
788  $out = $this->getContext()->getOutput();
789  $pager = new ImageHistoryPseudoPager(
790  $this,
791  MediaWikiServices::getInstance()->getLinkBatchFactory()
792  );
793  $out->addHTML( $pager->getBody() );
794  $out->preventClickjacking( $pager->getPreventClickjacking() );
795 
796  $this->getFile()->resetHistory(); // free db resources
797 
798  # Exist check because we don't want to show this on pages where an image
799  # doesn't exist along with the noimage message, that would suck. -√¶var
800  if ( $this->getFile()->exists() ) {
801  $this->uploadLinksBox();
802  }
803  }
804 
810  protected function queryImageLinks( $target, $limit ) {
811  $dbr = wfGetDB( DB_REPLICA );
812 
813  return $dbr->select(
814  [ 'imagelinks', 'page' ],
815  [ 'page_namespace', 'page_title', 'il_to' ],
816  [ 'il_to' => $target, 'il_from = page_id' ],
817  __METHOD__,
818  [ 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', ]
819  );
820  }
821 
822  protected function imageLinks() {
823  $limit = 100;
824 
825  $out = $this->getContext()->getOutput();
826 
827  $rows = [];
828  $redirects = [];
829  foreach ( $this->getTitle()->getRedirectsHere( NS_FILE ) as $redir ) {
830  $redirects[$redir->getDBkey()] = [];
831  $rows[] = (object)[
832  'page_namespace' => NS_FILE,
833  'page_title' => $redir->getDBkey(),
834  ];
835  }
836 
837  $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit + 1 );
838  foreach ( $res as $row ) {
839  $rows[] = $row;
840  }
841  $count = count( $rows );
842 
843  $hasMore = $count > $limit;
844  if ( !$hasMore && count( $redirects ) ) {
845  $res = $this->queryImageLinks( array_keys( $redirects ),
846  $limit - count( $rows ) + 1 );
847  foreach ( $res as $row ) {
848  $redirects[$row->il_to][] = $row;
849  $count++;
850  }
851  $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
852  }
853 
854  if ( $count == 0 ) {
855  $out->wrapWikiMsg(
856  Html::rawElement( 'div',
857  [ 'id' => 'mw-imagepage-nolinkstoimage' ], "\n$1\n" ),
858  'nolinkstoimage'
859  );
860  return;
861  }
862 
863  $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
864  if ( !$hasMore ) {
865  $out->addWikiMsg( 'linkstoimage', $count );
866  } else {
867  // More links than the limit. Add a link to [[Special:Whatlinkshere]]
868  $out->addWikiMsg( 'linkstoimage-more',
869  $this->getContext()->getLanguage()->formatNum( $limit ),
870  $this->getTitle()->getPrefixedDBkey()
871  );
872  }
873 
874  $out->addHTML(
875  Html::openElement( 'ul',
876  [ 'class' => 'mw-imagepage-linkstoimage' ] ) . "\n"
877  );
878  // Sort the list by namespace:title
879  usort( $rows, [ $this, 'compare' ] );
880 
881  $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
882 
883  // Create links for every element
884  $currentCount = 0;
885  foreach ( $rows as $element ) {
886  $currentCount++;
887  if ( $currentCount > $limit ) {
888  break;
889  }
890 
891  $query = [];
892  # Add a redirect=no to make redirect pages reachable
893  if ( isset( $redirects[$element->page_title] ) ) {
894  $query['redirect'] = 'no';
895  }
896  $link = $linkRenderer->makeKnownLink(
897  Title::makeTitle( $element->page_namespace, $element->page_title ),
898  null, [], $query
899  );
900  if ( !isset( $redirects[$element->page_title] ) ) {
901  # No redirects
902  $liContents = $link;
903  } elseif ( count( $redirects[$element->page_title] ) === 0 ) {
904  # Redirect without usages
905  $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )
906  ->rawParams( $link, '' )
907  ->parse();
908  } else {
909  # Redirect with usages
910  $li = '';
911  foreach ( $redirects[$element->page_title] as $row ) {
912  $currentCount++;
913  if ( $currentCount > $limit ) {
914  break;
915  }
916 
917  $link2 = $linkRenderer->makeKnownLink(
918  Title::makeTitle( $row->page_namespace, $row->page_title ) );
919  $li .= Html::rawElement(
920  'li',
921  [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
922  $link2
923  ) . "\n";
924  }
925 
927  'ul',
928  [ 'class' => 'mw-imagepage-redirectstofile' ],
929  $li
930  ) . "\n";
931  $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
932  $link, $ul )->parse();
933  }
934  $out->addHTML( Html::rawElement(
935  'li',
936  [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
937  $liContents
938  ) . "\n"
939  );
940 
941  }
942  $out->addHTML( Html::closeElement( 'ul' ) . "\n" );
943  $res->free();
944 
945  // Add a links to [[Special:Whatlinkshere]]
946  if ( $currentCount > $limit ) {
947  $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
948  }
949  $out->addHTML( Html::closeElement( 'div' ) . "\n" );
950  }
951 
952  protected function imageDupes() {
953  $this->loadFile();
954  $out = $this->getContext()->getOutput();
955 
956  $dupes = $this->getPage()->getDuplicates();
957  if ( count( $dupes ) == 0 ) {
958  return;
959  }
960 
961  $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
962  $out->addWikiMsg( 'duplicatesoffile',
963  $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
964  );
965  $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
966 
967  $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
968 
972  foreach ( $dupes as $file ) {
973  $fromSrc = '';
974  if ( $file->isLocal() ) {
975  $link = $linkRenderer->makeKnownLink( $file->getTitle() );
976  } else {
977  $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
978  $file->getTitle()->getPrefixedText() );
979  $fromSrc = $this->getContext()->msg(
980  'shared-repo-from',
981  $file->getRepo()->getDisplayName()
982  )->escaped();
983  }
984  $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
985  }
986  $out->addHTML( "</ul></div>\n" );
987  }
988 
992  public function delete() {
993  $file = $this->getFile();
994  if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
995  // Standard article deletion
996  parent::delete();
997  return;
998  }
999  '@phan-var LocalFile $file';
1000 
1001  $context = $this->getContext();
1002  $deleter = new FileDeleteForm(
1003  $file,
1004  $context->getUser(),
1005  $context->getOutput()
1006  );
1007  $deleter->execute();
1008  }
1009 
1015  public function showError( $description ) {
1016  $out = $this->getContext()->getOutput();
1017  $out->setPageTitle( $this->getContext()->msg( 'internalerror' ) );
1018  $out->setRobotPolicy( 'noindex,nofollow' );
1019  $out->setArticleRelated( false );
1020  $out->enableClientCache( false );
1021  $out->addWikiTextAsInterface( $description );
1022  }
1023 
1032  protected function compare( $a, $b ) {
1033  return $a->page_namespace <=> $b->page_namespace
1034  ?: strcmp( $a->page_title, $b->page_title );
1035  }
1036 
1046  public function getImageLimitsFromOption( $user, $optionName ) {
1047  return MediaFileTrait::getImageLimitsFromOption( $user, $optionName );
1048  }
1049 
1057  protected function doRenderLangOpt( array $langChoices, $renderLang ) {
1058  global $wgScript;
1059  $opts = '';
1060 
1061  $matchedRenderLang = $this->displayImg->getMatchedLanguage( $renderLang );
1062 
1063  foreach ( $langChoices as $lang ) {
1064  $opts .= $this->createXmlOptionStringForLanguage(
1065  $lang,
1066  $matchedRenderLang === $lang
1067  );
1068  }
1069 
1070  // Allow for the default case in an svg <switch> that is displayed if no
1071  // systemLanguage attribute matches
1072  $opts .= "\n" .
1073  Xml::option(
1074  $this->getContext()->msg( 'img-lang-default' )->text(),
1075  'und',
1076  $matchedRenderLang === null
1077  );
1078 
1079  $select = Html::rawElement(
1080  'select',
1081  [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1082  $opts
1083  );
1084  $submit = Xml::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1085 
1086  $formContents = $this->getContext()->msg( 'img-lang-info' )
1087  ->rawParams( $select, $submit )
1088  ->parse();
1089  $formContents .= Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1090 
1091  $langSelectLine = Html::rawElement( 'div', [ 'id' => 'mw-imglangselector-line' ],
1092  Html::rawElement( 'form', [ 'action' => $wgScript ], $formContents )
1093  );
1094  return $langSelectLine;
1095  }
1096 
1102  private function createXmlOptionStringForLanguage( $lang, $selected ) {
1103  $code = LanguageCode::bcp47( $lang );
1104  $name = MediaWikiServices::getInstance()
1105  ->getLanguageNameUtils()
1106  ->getLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1107  if ( $name !== '' ) {
1108  $display = $this->getContext()->msg( 'img-lang-opt', $code, $name )->text();
1109  } else {
1110  $display = $code;
1111  }
1112  return "\n" .
1113  Xml::option(
1114  $display,
1115  $lang,
1116  $selected
1117  );
1118  }
1119 
1129  protected function getThumbSizes( $origWidth, $origHeight ) {
1130  global $wgImageLimits;
1131  if ( $this->displayImg->getRepo()->canTransformVia404() ) {
1132  $thumbSizes = $wgImageLimits;
1133  // Also include the full sized resolution in the list, so
1134  // that users know they can get it. This will link to the
1135  // original file asset if mustRender() === false. In the case
1136  // that we mustRender, some users have indicated that they would
1137  // find it useful to have the full size image in the rendered
1138  // image format.
1139  $thumbSizes[] = [ $origWidth, $origHeight ];
1140  } else {
1141  # Creating thumb links triggers thumbnail generation.
1142  # Just generate the thumb for the current users prefs.
1143  $thumbSizes = [
1144  $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' )
1145  ];
1146  if ( !$this->displayImg->mustRender() ) {
1147  // We can safely include a link to the "full-size" preview,
1148  // without actually rendering.
1149  $thumbSizes[] = [ $origWidth, $origHeight ];
1150  }
1151  }
1152  return $thumbSizes;
1153  }
1154 
1159  public function getFile() {
1160  return $this->getPage()->getFile();
1161  }
1162 
1167  public function isLocal() {
1168  return $this->getPage()->isLocal();
1169  }
1170 
1175  public function getDuplicates() {
1176  return $this->getPage()->getDuplicates();
1177  }
1178 
1183  public function getForeignCategories() {
1184  return $this->getPage()->getForeignCategories();
1185  }
1186 
1187 }
$wgSend404Code
$wgSend404Code
Some web hosts attempt to rewrite all responses with a 404 (not found) status code,...
Definition: DefaultSettings.php:3662
ImagePage\makeSizeLink
makeSizeLink( $params, $width, $height)
Creates an thumbnail of specified size and returns an HTML link to it.
Definition: ImagePage.php:678
ImagePage\getForeignCategories
getForeignCategories()
Definition: ImagePage.php:1183
wfMessageFallback
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
Definition: GlobalFunctions.php:1253
ImagePage\getUploadUrl
getUploadUrl()
Definition: ImagePage.php:730
ImagePage\createXmlOptionStringForLanguage
createXmlOptionStringForLanguage( $lang, $selected)
Definition: ImagePage.php:1102
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:166
ImagePage\closeShowImage
closeShowImage()
For overloading.
Definition: ImagePage.php:779
ImagePage\openShowImage
openShowImage()
Definition: ImagePage.php:305
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
ImagePage\getFile
getFile()
Definition: ImagePage.php:1159
$wgScript
$wgScript
The URL path to index.php.
Definition: DefaultSettings.php:204
$wgSVGMaxSize
$wgSVGMaxSize
Don't scale a SVG larger than this.
Definition: DefaultSettings.php:1301
getUser
getUser()
ImagePage\$fileLoaded
bool $fileLoaded
Definition: ImagePage.php:43
ImagePage\uploadLinksBox
uploadLinksBox()
Add the re-upload link (or message about not being able to re-upload) to the output.
Definition: ImagePage.php:742
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
Xml\option
static option( $text, $value=null, $selected=false, $attribs=[])
Convenience function to build an HTML drop-down list item.
Definition: Xml.php:490
SpecialPage\getTitleFor
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
Definition: SpecialPage.php:106
Linker\processResponsiveImages
static processResponsiveImages( $file, $thumb, $hp)
Process responsive images: add 1.5x and 2x subimages to the thumbnail, where applicable.
Definition: Linker.php:639
ImagePage
Class for viewing MediaWiki file description pages.
Definition: ImagePage.php:33
$res
$res
Definition: testCompression.php:57
Linker\makeThumbLinkObj
static makeThumbLinkObj(LinkTarget $title, $file, $label='', $alt='', $align='right', $params=[], $framed=false, $manualthumb="")
Make HTML for a thumbnail including image, border and caption.
Definition: Linker.php:490
ImagePage\setFile
setFile( $file)
Definition: ImagePage.php:61
Xml\openElement
static openElement( $element, $attribs=null)
This opens an XML element.
Definition: Xml.php:110
Article\$linkRenderer
LinkRenderer $linkRenderer
Definition: Article.php:96
ImagePage\$repo
FileRepo $repo
Definition: ImagePage.php:40
$dbr
$dbr
Definition: testCompression.php:54
ImagePage\getLanguageForRendering
getLanguageForRendering(WebRequest $request, File $file)
Returns language code to be used for dispaying the image, based on request context and languages avai...
Definition: ImagePage.php:290
FileRepo
Base class for file repositories.
Definition: FileRepo.php:41
Html\closeElement
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:318
File
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:63
Article\getTitle
getTitle()
Get the title object of the article.
Definition: Article.php:219
Wikimedia\Rdbms\IResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: IResultWrapper.php:24
ImagePage\showTOC
showTOC( $metadata)
Create the TOC.
Definition: ImagePage.php:234
Article\exists
exists()
Definition: Article.php:2500
ImagePage\imageLinks
imageLinks()
Definition: ImagePage.php:822
getPermissionManager
getPermissionManager()
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2466
Xml\element
static element( $element, $attribs=null, $contents='', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition: Xml.php:41
ImagePage\newPage
newPage(Title $title)
Definition: ImagePage.php:52
Article\getPage
getPage()
Get the WikiPage object of this instance.
Definition: Article.php:229
Article\getContext
getContext()
Gets the context this Article is executed in.
Definition: Article.php:2340
FileDeleteForm
File deletion user interface.
Definition: FileDeleteForm.php:31
$title
$title
Definition: testCompression.php:38
Linker\makeExternalLink
static makeExternalLink( $url, $text, $escape=true, $linktype='', $attribs=[], $title=null)
Make an external link.
Definition: Linker.php:845
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:624
LogEventsList\showLogExtract
static showLogExtract(&$out, $types=[], $page='', $user='', $param=[])
Show log extract.
Definition: LogEventsList.php:618
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
ImagePage\showError
showError( $description)
Display an error with a wikitext description.
Definition: ImagePage.php:1015
ImagePage\view
view()
This is the default action of the index.php entry point: just view the page of the given title.
Definition: ImagePage.php:90
ImagePage\imageDupes
imageDupes()
Definition: ImagePage.php:952
Html\hidden
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition: Html.php:805
ImagePage\makeMetadataTable
makeMetadataTable( $metadata)
Make a table with metadata to be shown in the output page.
Definition: ImagePage.php:260
ImagePage\getThumbPrevText
getThumbPrevText( $params, $sizeLinkBigImagePreview)
Make the text under the image to say what size preview.
Definition: ImagePage.php:640
ImagePage\getThumbSizes
getThumbSizes( $origWidth, $origHeight)
Get alternative thumbnail sizes.
Definition: ImagePage.php:1129
$ul
$ul
Definition: upgradeLogging.php:222
Xml\tags
static tags( $element, $attribs, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:132
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1504
ImagePage\getDisplayedFile
getDisplayedFile()
Definition: ImagePage.php:223
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:42
$wgImageLimits
$wgImageLimits
Limit images on image description pages to a user-selectable limit.
Definition: DefaultSettings.php:1553
Title
Represents a title within MediaWiki.
Definition: Title.php:46
ImagePage\queryImageLinks
queryImageLinks( $target, $limit)
Definition: ImagePage.php:810
Xml\closeElement
static closeElement( $element)
Shortcut to close an XML element.
Definition: Xml.php:119
UploadBase\userCanReUpload
static userCanReUpload(User $user, File $img)
Check if a user is the last uploader.
Definition: UploadBase.php:2024
WebRequest\getVal
getVal( $name, $default=null)
Fetch a scalar from the input or return $default if it's not set.
Definition: WebRequest.php:504
ImagePage\$displayImg
File false $displayImg
Definition: ImagePage.php:37
ImagePage\doRenderLangOpt
doRenderLangOpt(array $langChoices, $renderLang)
Output a drop-down box for language options for the file.
Definition: ImagePage.php:1057
LanguageCode\bcp47
static bcp47( $code)
Get the normalised IETF language tag See unit test for examples.
Definition: LanguageCode.php:175
Html\openElement
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:254
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:212
$wgEnableUploads
$wgEnableUploads
Allow users to upload files.
Definition: DefaultSettings.php:468
ImagePage\compare
compare( $a, $b)
Callback for usort() to do link sorts by (namespace, title) Function copied from Title::compare()
Definition: ImagePage.php:1032
Article\getId
getId()
Definition: Article.php:2601
ImagePage\getImageLimitsFromOption
getImageLimitsFromOption( $user, $optionName)
Returns the corresponding $wgImageLimits entry for the selected user option.
Definition: ImagePage.php:1046
$ext
if(!is_readable( $file)) $ext
Definition: router.php:48
WikiFilePage
Special handling for file pages.
Definition: WikiFilePage.php:31
ImageHistoryPseudoPager
Definition: ImageHistoryPseudoPager.php:25
Article
Class for viewing MediaWiki article and history.
Definition: Article.php:47
Html\element
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:234
NS_FILE
const NS_FILE
Definition: Defines.php:69
ImagePage\loadFile
loadFile()
Definition: ImagePage.php:67
ImagePage\isLocal
isLocal()
Definition: ImagePage.php:1167
Article\getOldID
getOldID()
Definition: Article.php:309
ImagePage\$mExtraDescription
bool $mExtraDescription
Definition: ImagePage.php:46
$wgShowEXIF
$wgShowEXIF
Show Exif data, on by default if available.
Definition: DefaultSettings.php:879
ImagePage\getDuplicates
getDuplicates()
Definition: ImagePage.php:1175
ImagePage\printSharedImageText
printSharedImageText()
Show a notice that the file is from a shared repository.
Definition: ImagePage.php:697
ImagePage\imageHistory
imageHistory()
If the page we've just displayed is in the "Image" namespace, we follow it with an upload history of ...
Definition: ImagePage.php:786
Xml\submitButton
static submitButton( $value, $attribs=[])
Convenience function to build an HTML submit button When $wgUseMediaWikiUIEverywhere is true it will ...
Definition: Xml.php:465
$type
$type
Definition: testCompression.php:52