MediaWiki REL1_32
ImagePage.php
Go to the documentation of this file.
1<?php
24
30class ImagePage extends Article {
32 private $displayImg;
33
35 private $repo;
36
38 private $fileLoaded;
39
41 protected $mExtraDescription = false;
42
46 protected $mPage;
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->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
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
214 public function getDisplayedFile() {
215 $this->loadFile();
216 return $this->displayImg;
217 }
218
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
251 protected function makeMetadataTable( $metadata ) {
252 $r = "<div class=\"mw-imagepage-section-metadata\">";
253 $r .= $this->getContext()->msg( 'metadata-help' )->plain();
254 // Intial state is collapsed
255 // see filepage.css and mediawiki.action.view.metadata module.
256 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata collapsed\">\n";
257 foreach ( $metadata as $type => $stuff ) {
258 foreach ( $stuff as $v ) {
259 $class = str_replace( ' ', '_', $v['id'] );
260 if ( $type == 'collapsed' ) {
261 $class .= ' mw-metadata-collapsible';
262 }
263 $r .= Html::rawElement( 'tr',
264 [ 'class' => $class ],
265 Html::rawElement( 'th', [], $v['name'] )
266 . Html::rawElement( 'td', [], $v['value'] )
267 );
268 }
269 }
270 $r .= "</table>\n</div>\n";
271 return $r;
272 }
273
284 $this->loadFile();
285 if ( $this->mPage->getFile() && !$this->mPage->getFile()->isLocal() && 0 == $this->getId() ) {
286 return new ParserOutput();
287 }
288 return parent::getEmptyPageParserOutput( $options );
289 }
290
291 private function getLanguageForRendering( WebRequest $request, File $file ) {
292 $handler = $this->displayImg->getHandler();
293 if ( !$handler ) {
294 return null;
295 }
296
297 $requestLanguage = $request->getVal( 'lang' );
298 if ( !is_null( $requestLanguage ) ) {
299 if ( $handler->validateParam( 'lang', $requestLanguage ) ) {
300 return $requestLanguage;
301 }
302 }
303
304 return $handler->getDefaultRenderLanguage( $this->displayImg );
305 }
306
307 protected function openShowImage() {
309
310 $this->loadFile();
311 $out = $this->getContext()->getOutput();
312 $user = $this->getContext()->getUser();
313 $lang = $this->getContext()->getLanguage();
314 $dirmark = $lang->getDirMarkEntity();
315 $request = $this->getContext()->getRequest();
316
317 $max = $this->getImageLimitsFromOption( $user, 'imagesize' );
318 $maxWidth = $max[0];
319 $maxHeight = $max[1];
320
321 if ( $this->displayImg->exists() ) {
322 # image
323 $page = $request->getIntOrNull( 'page' );
324 if ( is_null( $page ) ) {
325 $params = [];
326 $page = 1;
327 } else {
328 $params = [ 'page' => $page ];
329 }
330
331 $renderLang = $this->getLanguageForRendering( $request, $this->displayImg );
332 if ( !is_null( $renderLang ) ) {
333 $params['lang'] = $renderLang;
334 }
335
336 $width_orig = $this->displayImg->getWidth( $page );
337 $width = $width_orig;
338 $height_orig = $this->displayImg->getHeight( $page );
339 $height = $height_orig;
340
341 $filename = wfEscapeWikiText( $this->displayImg->getName() );
342 $linktext = $filename;
343
344 // Avoid PHP 7.1 warning from passing $this by reference
345 $imagePage = $this;
346
347 Hooks::run( 'ImageOpenShowImageInlineBefore', [ &$imagePage, &$out ] );
348
349 if ( $this->displayImg->allowInlineDisplay() ) {
350 # image
351 # "Download high res version" link below the image
352 # $msgsize = $this->getContext()->msg( 'file-info-size', $width_orig, $height_orig,
353 # Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
354 # We'll show a thumbnail of this image
355 if ( $width > $maxWidth || $height > $maxHeight || $this->displayImg->isVectorized() ) {
356 list( $width, $height ) = $this->getDisplayWidthHeight(
357 $maxWidth, $maxHeight, $width, $height
358 );
359 $linktext = $this->getContext()->msg( 'show-big-image' )->escaped();
360
361 $thumbSizes = $this->getThumbSizes( $width_orig, $height_orig );
362 # Generate thumbnails or thumbnail links as needed...
363 $otherSizes = [];
364 foreach ( $thumbSizes as $size ) {
365 // We include a thumbnail size in the list, if it is
366 // less than or equal to the original size of the image
367 // asset ($width_orig/$height_orig). We also exclude
368 // the current thumbnail's size ($width/$height)
369 // since that is added to the message separately, so
370 // it can be denoted as the current size being shown.
371 // Vectorized images are limited by $wgSVGMaxSize big,
372 // so all thumbs less than or equal that are shown.
373 if ( ( ( $size[0] <= $width_orig && $size[1] <= $height_orig )
374 || ( $this->displayImg->isVectorized()
375 && max( $size[0], $size[1] ) <= $wgSVGMaxSize )
376 )
377 && $size[0] != $width && $size[1] != $height
378 ) {
379 $sizeLink = $this->makeSizeLink( $params, $size[0], $size[1] );
380 if ( $sizeLink ) {
381 $otherSizes[] = $sizeLink;
382 }
383 }
384 }
385 $otherSizes = array_unique( $otherSizes );
386
387 $sizeLinkBigImagePreview = $this->makeSizeLink( $params, $width, $height );
388 $msgsmall = $this->getThumbPrevText( $params, $sizeLinkBigImagePreview );
389 if ( count( $otherSizes ) ) {
390 $msgsmall .= ' ' .
391 Html::rawElement(
392 'span',
393 [ 'class' => 'mw-filepage-other-resolutions' ],
394 $this->getContext()->msg( 'show-big-image-other' )
395 ->rawParams( $lang->pipeList( $otherSizes ) )
396 ->params( count( $otherSizes ) )
397 ->parse()
398 );
399 }
400 } elseif ( $width == 0 && $height == 0 ) {
401 # Some sort of audio file that doesn't have dimensions
402 # Don't output a no hi res message for such a file
403 $msgsmall = '';
404 } else {
405 # Image is small enough to show full size on image page
406 $msgsmall = $this->getContext()->msg( 'file-nohires' )->parse();
407 }
408
409 $params['width'] = $width;
410 $params['height'] = $height;
411 $thumbnail = $this->displayImg->transform( $params );
412 Linker::processResponsiveImages( $this->displayImg, $thumbnail, $params );
413
414 $anchorclose = Html::rawElement(
415 'div',
416 [ 'class' => 'mw-filepage-resolutioninfo' ],
417 $msgsmall
418 );
419
420 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
421 if ( $isMulti ) {
422 $out->addModules( 'mediawiki.page.image.pagination' );
423 $out->addHTML( '<table class="multipageimage"><tr><td>' );
424 }
425
426 if ( $thumbnail ) {
427 $options = [
428 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
429 'file-link' => true,
430 ];
431 $out->addHTML( '<div class="fullImageLink" id="file">' .
432 $thumbnail->toHtml( $options ) .
433 $anchorclose . "</div>\n" );
434 }
435
436 if ( $isMulti ) {
437 $count = $this->displayImg->pageCount();
438
439 if ( $page > 1 ) {
440 $label = $this->getContext()->msg( 'imgmultipageprev' )->text();
441 // on the client side, this link is generated in ajaxifyPageNavigation()
442 // in the mediawiki.page.image.pagination module
444 $this->getTitle(),
445 htmlspecialchars( $label ),
446 [],
447 [ 'page' => $page - 1 ]
448 );
449 $thumb1 = Linker::makeThumbLinkObj(
450 $this->getTitle(),
451 $this->displayImg,
452 $link,
453 $label,
454 'none',
455 [ 'page' => $page - 1 ]
456 );
457 } else {
458 $thumb1 = '';
459 }
460
461 if ( $page < $count ) {
462 $label = $this->getContext()->msg( 'imgmultipagenext' )->text();
464 $this->getTitle(),
465 htmlspecialchars( $label ),
466 [],
467 [ 'page' => $page + 1 ]
468 );
469 $thumb2 = Linker::makeThumbLinkObj(
470 $this->getTitle(),
471 $this->displayImg,
472 $link,
473 $label,
474 'none',
475 [ 'page' => $page + 1 ]
476 );
477 } else {
478 $thumb2 = '';
479 }
480
481 global $wgScript;
482
483 $formParams = [
484 'name' => 'pageselector',
485 'action' => $wgScript,
486 ];
487 $options = [];
488 for ( $i = 1; $i <= $count; $i++ ) {
489 $options[] = Xml::option( $lang->formatNum( $i ), $i, $i == $page );
490 }
491 $select = Xml::tags( 'select',
492 [ 'id' => 'pageselector', 'name' => 'page' ],
493 implode( "\n", $options ) );
494
495 $out->addHTML(
496 '</td><td><div class="multipageimagenavbox">' .
497 Xml::openElement( 'form', $formParams ) .
498 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
499 $this->getContext()->msg( 'imgmultigoto' )->rawParams( $select )->parse() .
500 $this->getContext()->msg( 'word-separator' )->escaped() .
501 Xml::submitButton( $this->getContext()->msg( 'imgmultigo' )->text() ) .
502 Xml::closeElement( 'form' ) .
503 "<hr />$thumb1\n$thumb2<br style=\"clear: both\" /></div></td></tr></table>"
504 );
505 }
506 } elseif ( $this->displayImg->isSafeFile() ) {
507 # if direct link is allowed but it's not a renderable image, show an icon.
508 $icon = $this->displayImg->iconThumb();
509
510 $out->addHTML( '<div class="fullImageLink" id="file">' .
511 $icon->toHtml( [ 'file-link' => true ] ) .
512 "</div>\n" );
513 }
514
515 $longDesc = $this->getContext()->msg( 'parentheses', $this->displayImg->getLongDesc() )->text();
516
517 $handler = $this->displayImg->getHandler();
518
519 // If this is a filetype with potential issues, warn the user.
520 if ( $handler ) {
521 $warningConfig = $handler->getWarningConfig( $this->displayImg );
522
523 if ( $warningConfig !== null ) {
524 // The warning will be displayed via CSS and JavaScript.
525 // We just need to tell the client side what message to use.
526 $output = $this->getContext()->getOutput();
527 $output->addJsConfigVars( 'wgFileWarning', $warningConfig );
528 $output->addModules( $warningConfig['module'] );
529 $output->addModules( 'mediawiki.filewarning' );
530 }
531 }
532
533 $medialink = "[[Media:$filename|$linktext]]";
534
535 if ( !$this->displayImg->isSafeFile() ) {
536 $warning = $this->getContext()->msg( 'mediawarning' )->plain();
537 // dirmark is needed here to separate the file name, which
538 // most likely ends in Latin characters, from the description,
539 // which may begin with the file type. In RTL environment
540 // this will get messy.
541 // The dirmark, however, must not be immediately adjacent
542 // to the filename, because it can get copied with it.
543 // See T27277.
544 // phpcs:disable Generic.Files.LineLength
545 $out->addWikiText( <<<EOT
546<div class="fullMedia"><span class="dangerousLink">{$medialink}</span> $dirmark<span class="fileInfo">$longDesc</span></div>
547<div class="mediaWarning">$warning</div>
548EOT
549 );
550 // phpcs:enable
551 } else {
552 $out->addWikiText( <<<EOT
553<div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">$longDesc</span>
554</div>
555EOT
556 );
557 }
558
559 $renderLangOptions = $this->displayImg->getAvailableLanguages();
560 if ( count( $renderLangOptions ) >= 1 ) {
561 $out->addHTML( $this->doRenderLangOpt( $renderLangOptions, $renderLang ) );
562 }
563
564 // Add cannot animate thumbnail warning
565 if ( !$this->displayImg->canAnimateThumbIfAppropriate() ) {
566 // Include the extension so wiki admins can
567 // customize it on a per file-type basis
568 // (aka say things like use format X instead).
569 // additionally have a specific message for
570 // file-no-thumb-animation-gif
571 $ext = $this->displayImg->getExtension();
572 $noAnimMesg = wfMessageFallback(
573 'file-no-thumb-animation-' . $ext,
574 'file-no-thumb-animation'
575 )->plain();
576
577 $out->addWikiText( <<<EOT
578<div class="mw-noanimatethumb">{$noAnimMesg}</div>
579EOT
580 );
581 }
582
583 if ( !$this->displayImg->isLocal() ) {
584 $this->printSharedImageText();
585 }
586 } else {
587 # Image does not exist
588 if ( !$this->getId() ) {
590
591 # No article exists either
592 # Show deletion log to be consistent with normal articles
594 $out,
595 [ 'delete', 'move', 'protect' ],
596 $this->getTitle()->getPrefixedText(),
597 '',
598 [ 'lim' => 10,
599 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
600 'showIfEmpty' => false,
601 'msgKey' => [ 'moveddeleted-notice' ]
602 ]
603 );
604 }
605
606 if ( $wgEnableUploads && $user->isAllowed( 'upload' ) ) {
607 // Only show an upload link if the user can upload
608 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
609 $nofile = [
610 'filepage-nofile-link',
611 $uploadTitle->getFullURL( [ 'wpDestFile' => $this->mPage->getFile()->getName() ] )
612 ];
613 } else {
614 $nofile = 'filepage-nofile';
615 }
616 // Note, if there is an image description page, but
617 // no image, then this setRobotPolicy is overridden
618 // by Article::View().
619 $out->setRobotPolicy( 'noindex,nofollow' );
620 $out->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
621 if ( !$this->getId() && $wgSend404Code ) {
622 // If there is no image, no shared image, and no description page,
623 // output a 404, to be consistent with Article::showMissingArticle.
624 $request->response()->statusHeader( 404 );
625 }
626 }
627 $out->setFileVersion( $this->displayImg );
628 }
629
637 protected function getThumbPrevText( $params, $sizeLinkBigImagePreview ) {
638 if ( $sizeLinkBigImagePreview ) {
639 // Show a different message of preview is different format from original.
640 $previewTypeDiffers = false;
641 $origExt = $thumbExt = $this->displayImg->getExtension();
642 if ( $this->displayImg->getHandler() ) {
643 $origMime = $this->displayImg->getMimeType();
644 $typeParams = $params;
645 $this->displayImg->getHandler()->normaliseParams( $this->displayImg, $typeParams );
646 list( $thumbExt, $thumbMime ) = $this->displayImg->getHandler()->getThumbType(
647 $origExt, $origMime, $typeParams );
648 if ( $thumbMime !== $origMime ) {
649 $previewTypeDiffers = true;
650 }
651 }
652 if ( $previewTypeDiffers ) {
653 return $this->getContext()->msg( 'show-big-image-preview-differ' )->
654 rawParams( $sizeLinkBigImagePreview )->
655 params( strtoupper( $origExt ) )->
656 params( strtoupper( $thumbExt ) )->
657 parse();
658 } else {
659 return $this->getContext()->msg( 'show-big-image-preview' )->
660 rawParams( $sizeLinkBigImagePreview )->
661 parse();
662 }
663 } else {
664 return '';
665 }
666 }
667
675 protected function makeSizeLink( $params, $width, $height ) {
676 $params['width'] = $width;
677 $params['height'] = $height;
678 $thumbnail = $this->displayImg->transform( $params );
679 if ( $thumbnail && !$thumbnail->isError() ) {
680 return Html::rawElement( 'a', [
681 'href' => $thumbnail->getUrl(),
682 'class' => 'mw-thumbnail-link'
683 ], $this->getContext()->msg( 'show-big-image-size' )->numParams(
684 $thumbnail->getWidth(), $thumbnail->getHeight()
685 )->parse() );
686 } else {
687 return '';
688 }
689 }
690
694 protected function printSharedImageText() {
695 $out = $this->getContext()->getOutput();
696 $this->loadFile();
697
698 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
699 $descText = $this->mPage->getFile()->getDescriptionText( $this->getContext()->getLanguage() );
700
701 /* Add canonical to head if there is no local page for this shared file */
702 if ( $descUrl && $this->mPage->getId() == 0 ) {
703 $out->setCanonicalUrl( $descUrl );
704 }
705
706 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
707 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
708
709 if ( $descUrl &&
710 $descText &&
711 $this->getContext()->msg( 'sharedupload-desc-here' )->plain() !== '-'
712 ) {
713 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-here', $repo, $descUrl ] );
714 } elseif ( $descUrl &&
715 $this->getContext()->msg( 'sharedupload-desc-there' )->plain() !== '-'
716 ) {
717 $out->wrapWikiMsg( $wrap, [ 'sharedupload-desc-there', $repo, $descUrl ] );
718 } else {
719 $out->wrapWikiMsg( $wrap, [ 'sharedupload', $repo ], ''/*BACKCOMPAT*/ );
720 }
721
722 if ( $descText ) {
723 $this->mExtraDescription = $descText;
724 }
725 }
726
727 public function getUploadUrl() {
728 $this->loadFile();
729 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
730 return $uploadTitle->getFullURL( [
731 'wpDestFile' => $this->mPage->getFile()->getName(),
732 'wpForReUpload' => 1
733 ] );
734 }
735
740 protected function uploadLinksBox() {
741 global $wgEnableUploads;
742
743 if ( !$wgEnableUploads ) {
744 return;
745 }
746
747 $this->loadFile();
748 if ( !$this->mPage->getFile()->isLocal() ) {
749 return;
750 }
751
752 $out = $this->getContext()->getOutput();
753 $out->addHTML( "<ul>\n" );
754
755 # "Upload a new version of this file" link
756 $canUpload = $this->getTitle()->quickUserCan( 'upload', $this->getContext()->getUser() );
757 if ( $canUpload && UploadBase::userCanReUpload(
758 $this->getContext()->getUser(),
759 $this->mPage->getFile() )
760 ) {
762 $this->getUploadUrl(),
763 $this->getContext()->msg( 'uploadnewversion-linktext' )->text()
764 );
765 $out->addHTML( "<li id=\"mw-imagepage-reupload-link\">"
766 . "<div class=\"plainlinks\">{$ulink}</div></li>\n" );
767 } else {
768 $out->addHTML( "<li id=\"mw-imagepage-upload-disallowed\">"
769 . $this->getContext()->msg( 'upload-disallowed-here' )->escaped() . "</li>\n" );
770 }
771
772 $out->addHTML( "</ul>\n" );
773 }
774
778 protected function closeShowImage() {
779 }
780
785 protected function imageHistory() {
786 $this->loadFile();
787 $out = $this->getContext()->getOutput();
788 $pager = new ImageHistoryPseudoPager( $this );
789 $out->addHTML( $pager->getBody() );
790 $out->preventClickjacking( $pager->getPreventClickjacking() );
791
792 $this->mPage->getFile()->resetHistory(); // free db resources
793
794 # Exist check because we don't want to show this on pages where an image
795 # doesn't exist along with the noimage message, that would suck. -ævar
796 if ( $this->mPage->getFile()->exists() ) {
797 $this->uploadLinksBox();
798 }
799 }
800
806 protected function queryImageLinks( $target, $limit ) {
808
809 return $dbr->select(
810 [ 'imagelinks', 'page' ],
811 [ 'page_namespace', 'page_title', 'il_to' ],
812 [ 'il_to' => $target, 'il_from = page_id' ],
813 __METHOD__,
814 [ 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', ]
815 );
816 }
817
818 protected function imageLinks() {
819 $limit = 100;
820
821 $out = $this->getContext()->getOutput();
822
823 $rows = [];
824 $redirects = [];
825 foreach ( $this->getTitle()->getRedirectsHere( NS_FILE ) as $redir ) {
826 $redirects[$redir->getDBkey()] = [];
827 $rows[] = (object)[
828 'page_namespace' => NS_FILE,
829 'page_title' => $redir->getDBkey(),
830 ];
831 }
832
833 $res = $this->queryImageLinks( $this->getTitle()->getDBkey(), $limit + 1 );
834 foreach ( $res as $row ) {
835 $rows[] = $row;
836 }
837 $count = count( $rows );
838
839 $hasMore = $count > $limit;
840 if ( !$hasMore && count( $redirects ) ) {
841 $res = $this->queryImageLinks( array_keys( $redirects ),
842 $limit - count( $rows ) + 1 );
843 foreach ( $res as $row ) {
844 $redirects[$row->il_to][] = $row;
845 $count++;
846 }
847 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
848 }
849
850 if ( $count == 0 ) {
851 $out->wrapWikiMsg(
852 Html::rawElement( 'div',
853 [ 'id' => 'mw-imagepage-nolinkstoimage' ], "\n$1\n" ),
854 'nolinkstoimage'
855 );
856 return;
857 }
858
859 $out->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
860 if ( !$hasMore ) {
861 $out->addWikiMsg( 'linkstoimage', $count );
862 } else {
863 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
864 $out->addWikiMsg( 'linkstoimage-more',
865 $this->getContext()->getLanguage()->formatNum( $limit ),
866 $this->getTitle()->getPrefixedDBkey()
867 );
868 }
869
870 $out->addHTML(
871 Html::openElement( 'ul',
872 [ 'class' => 'mw-imagepage-linkstoimage' ] ) . "\n"
873 );
874 $count = 0;
875
876 // Sort the list by namespace:title
877 usort( $rows, [ $this, 'compare' ] );
878
879 // Create links for every element
880 $currentCount = 0;
881 foreach ( $rows as $element ) {
882 $currentCount++;
883 if ( $currentCount > $limit ) {
884 break;
885 }
886
887 $query = [];
888 # Add a redirect=no to make redirect pages reachable
889 if ( isset( $redirects[$element->page_title] ) ) {
890 $query['redirect'] = 'no';
891 }
893 Title::makeTitle( $element->page_namespace, $element->page_title ),
894 null, [], $query
895 );
896 if ( !isset( $redirects[$element->page_title] ) ) {
897 # No redirects
898 $liContents = $link;
899 } elseif ( count( $redirects[$element->page_title] ) === 0 ) {
900 # Redirect without usages
901 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )
902 ->rawParams( $link, '' )
903 ->parse();
904 } else {
905 # Redirect with usages
906 $li = '';
907 foreach ( $redirects[$element->page_title] as $row ) {
908 $currentCount++;
909 if ( $currentCount > $limit ) {
910 break;
911 }
912
913 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
914 $li .= Html::rawElement(
915 'li',
916 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
917 $link2
918 ) . "\n";
919 }
920
921 $ul = Html::rawElement(
922 'ul',
923 [ 'class' => 'mw-imagepage-redirectstofile' ],
924 $li
925 ) . "\n";
926 $liContents = $this->getContext()->msg( 'linkstoimage-redirect' )->rawParams(
927 $link, $ul )->parse();
928 }
929 $out->addHTML( Html::rawElement(
930 'li',
931 [ 'class' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ],
932 $liContents
933 ) . "\n"
934 );
935
936 };
937 $out->addHTML( Html::closeElement( 'ul' ) . "\n" );
938 $res->free();
939
940 // Add a links to [[Special:Whatlinkshere]]
941 if ( $count > $limit ) {
942 $out->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
943 }
944 $out->addHTML( Html::closeElement( 'div' ) . "\n" );
945 }
946
947 protected function imageDupes() {
948 $this->loadFile();
949 $out = $this->getContext()->getOutput();
950
951 $dupes = $this->mPage->getDuplicates();
952 if ( count( $dupes ) == 0 ) {
953 return;
954 }
955
956 $out->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
957 $out->addWikiMsg( 'duplicatesoffile',
958 $this->getContext()->getLanguage()->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
959 );
960 $out->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
961
965 foreach ( $dupes as $file ) {
966 $fromSrc = '';
967 if ( $file->isLocal() ) {
968 $link = Linker::linkKnown( $file->getTitle() );
969 } else {
970 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
971 $file->getTitle()->getPrefixedText() );
972 $fromSrc = $this->getContext()->msg(
973 'shared-repo-from',
974 $file->getRepo()->getDisplayName()
975 )->escaped();
976 }
977 $out->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
978 }
979 $out->addHTML( "</ul></div>\n" );
980 }
981
985 public function delete() {
986 $file = $this->mPage->getFile();
987 if ( !$file->exists() || !$file->isLocal() || $file->getRedirected() ) {
988 // Standard article deletion
989 parent::delete();
990 return;
991 }
992
993 $deleter = new FileDeleteForm( $file );
994 $deleter->execute();
995 }
996
1002 function showError( $description ) {
1003 $out = $this->getContext()->getOutput();
1004 $out->setPageTitle( $this->getContext()->msg( 'internalerror' ) );
1005 $out->setRobotPolicy( 'noindex,nofollow' );
1006 $out->setArticleRelated( false );
1007 $out->enableClientCache( false );
1008 $out->addWikiText( $description );
1009 }
1010
1019 protected function compare( $a, $b ) {
1020 return $a->page_namespace <=> $b->page_namespace
1021 ?: strcmp( $a->page_title, $b->page_title );
1022 }
1023
1032 public function getImageLimitsFromOption( $user, $optionName ) {
1033 global $wgImageLimits;
1034
1035 $option = $user->getIntOption( $optionName );
1036 if ( !isset( $wgImageLimits[$option] ) ) {
1037 $option = User::getDefaultOption( $optionName );
1038 }
1039
1040 // The user offset might still be incorrect, specially if
1041 // $wgImageLimits got changed (see T10858).
1042 if ( !isset( $wgImageLimits[$option] ) ) {
1043 // Default to the first offset in $wgImageLimits
1044 $option = 0;
1045 }
1046
1047 // if nothing is set, fallback to a hardcoded default
1048 return $wgImageLimits[$option] ?? [ 800, 600 ];
1049 }
1050
1058 protected function doRenderLangOpt( array $langChoices, $renderLang ) {
1059 global $wgScript;
1060 $opts = '';
1061
1062 $matchedRenderLang = $this->displayImg->getMatchedLanguage( $renderLang );
1063
1064 foreach ( $langChoices as $lang ) {
1065 $opts .= $this->createXmlOptionStringForLanguage(
1066 $lang,
1067 $matchedRenderLang === $lang
1068 );
1069 }
1070
1071 // Allow for the default case in an svg <switch> that is displayed if no
1072 // systemLanguage attribute matches
1073 $opts .= "\n" .
1074 Xml::option(
1075 $this->getContext()->msg( 'img-lang-default' )->text(),
1076 'und',
1077 is_null( $matchedRenderLang )
1078 );
1079
1080 $select = Html::rawElement(
1081 'select',
1082 [ 'id' => 'mw-imglangselector', 'name' => 'lang' ],
1083 $opts
1084 );
1085 $submit = Xml::submitButton( $this->getContext()->msg( 'img-lang-go' )->text() );
1086
1087 $formContents = $this->getContext()->msg( 'img-lang-info' )
1088 ->rawParams( $select, $submit )
1089 ->parse();
1090 $formContents .= Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() );
1091
1092 $langSelectLine = Html::rawElement( 'div', [ 'id' => 'mw-imglangselector-line' ],
1093 Html::rawElement( 'form', [ 'action' => $wgScript ], $formContents )
1094 );
1095 return $langSelectLine;
1096 }
1097
1103 private function createXmlOptionStringForLanguage( $lang, $selected ) {
1104 $code = LanguageCode::bcp47( $lang );
1105 $name = Language::fetchLanguageName( $code, $this->getContext()->getLanguage()->getCode() );
1106 if ( $name !== '' ) {
1107 $display = $this->getContext()->msg( 'img-lang-opt', $code, $name )->text();
1108 } else {
1109 $display = $code;
1110 }
1111 return "\n" .
1112 Xml::option(
1113 $display,
1114 $lang,
1115 $selected
1116 );
1117 }
1118
1133 protected function getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height ) {
1134 if ( !$maxWidth || !$maxHeight ) {
1135 // should never happen
1136 throw new MWException( 'Using a choice from $wgImageLimits that is 0x0' );
1137 }
1138
1139 if ( !$width || !$height ) {
1140 return [ 0, 0 ];
1141 }
1142
1143 # Calculate the thumbnail size.
1144 if ( $width <= $maxWidth && $height <= $maxHeight ) {
1145 // Vectorized image, do nothing.
1146 } elseif ( $width / $height >= $maxWidth / $maxHeight ) {
1147 # The limiting factor is the width, not the height.
1148 $height = round( $height * $maxWidth / $width );
1149 $width = $maxWidth;
1150 # Note that $height <= $maxHeight now.
1151 } else {
1152 $newwidth = floor( $width * $maxHeight / $height );
1153 $height = round( $height * $newwidth / $width );
1154 $width = $newwidth;
1155 # Note that $height <= $maxHeight now, but might not be identical
1156 # because of rounding.
1157 }
1158 return [ $width, $height ];
1159 }
1160
1169 protected function getThumbSizes( $origWidth, $origHeight ) {
1170 global $wgImageLimits;
1171 if ( $this->displayImg->getRepo()->canTransformVia404() ) {
1172 $thumbSizes = $wgImageLimits;
1173 // Also include the full sized resolution in the list, so
1174 // that users know they can get it. This will link to the
1175 // original file asset if mustRender() === false. In the case
1176 // that we mustRender, some users have indicated that they would
1177 // find it useful to have the full size image in the rendered
1178 // image format.
1179 $thumbSizes[] = [ $origWidth, $origHeight ];
1180 } else {
1181 # Creating thumb links triggers thumbnail generation.
1182 # Just generate the thumb for the current users prefs.
1183 $thumbSizes = [
1184 $this->getImageLimitsFromOption( $this->getContext()->getUser(), 'thumbsize' )
1185 ];
1186 if ( !$this->displayImg->mustRender() ) {
1187 // We can safely include a link to the "full-size" preview,
1188 // without actually rendering.
1189 $thumbSizes[] = [ $origWidth, $origHeight ];
1190 }
1191 }
1192 return $thumbSizes;
1193 }
1194
1199 public function getFile() {
1200 return $this->mPage->getFile();
1201 }
1202
1207 public function isLocal() {
1208 return $this->mPage->isLocal();
1209 }
1210
1215 public function getDuplicates() {
1216 return $this->mPage->getDuplicates();
1217 }
1218
1223 public function getForeignCategories() {
1224 $this->mPage->getForeignCategories();
1225 }
1226
1227}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
$wgScript
The URL path to index.php.
$wgSend404Code
Some web hosts attempt to rewrite all responses with a 404 (not found) status code,...
$wgImageLimits
Limit images on image description pages to a user-selectable limit.
$wgSVGMaxSize
Don't scale a SVG larger than this.
$wgEnableUploads
Allow users to upload files.
$wgShowEXIF
Show Exif data, on by default if available.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfLocalFile( $title)
Get an object referring to a locally registered file.
wfFindFile( $title, $options=[])
Find a file.
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Class for viewing MediaWiki article and history.
Definition Article.php:38
getContext()
Gets the context this Article is executed in.
Definition Article.php:2232
getOldID()
Definition Article.php:326
getTitle()
Get the title object of the article.
Definition Article.php:221
getId()
Call to WikiPage function for backwards compatibility.
Definition Article.php:2466
getUser( $audience=Revision::FOR_PUBLIC, User $user=null)
Call to WikiPage function for backwards compatibility.
Definition Article.php:2554
File deletion user interface.
Base class for file repositories.
Definition FileRepo.php:39
getDisplayName()
Get the human-readable name of the repo.
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:51
Class for viewing MediaWiki file description pages.
Definition ImagePage.php:30
getLanguageForRendering(WebRequest $request, File $file)
showError( $description)
Display an error with a wikitext description.
imageHistory()
If the page we've just displayed is in the "Image" namespace, we follow it with an upload history of ...
compare( $a, $b)
Callback for usort() to do link sorts by (namespace, title) Function copied from Title::compare()
createXmlOptionStringForLanguage( $lang, $selected)
getThumbSizes( $origWidth, $origHeight)
Get alternative thumbnail sizes.
getImageLimitsFromOption( $user, $optionName)
Returns the corresponding $wgImageLimits entry for the selected user option.
getForeignCategories()
newPage(Title $title)
Definition ImagePage.php:52
getDisplayWidthHeight( $maxWidth, $maxHeight, $width, $height)
Get the width and height to display image at.
makeSizeLink( $params, $width, $height)
Creates an thumbnail of specified size and returns an HTML link to it.
setFile( $file)
Definition ImagePage.php:61
File $displayImg
Definition ImagePage.php:32
doRenderLangOpt(array $langChoices, $renderLang)
Output a drop-down box for language options for the file.
WikiFilePage $mPage
Definition ImagePage.php:46
FileRepo $repo
Definition ImagePage.php:35
makeMetadataTable( $metadata)
Make a table with metadata to be shown in the output page.
render()
Handler for action=render Include body text only; none of the image extras.
Definition ImagePage.php:93
bool $mExtraDescription
Definition ImagePage.php:41
getEmptyPageParserOutput(ParserOptions $options)
Overloading Article's getEmptyPageParserOutput method.
queryImageLinks( $target, $limit)
bool $fileLoaded
Definition ImagePage.php:38
uploadLinksBox()
Print out the various links at the bottom of the image page, e.g.
printSharedImageText()
Show a notice that the file is from a shared repository.
getDisplayedFile()
closeShowImage()
For overloading.
showTOC( $metadata)
Create the TOC.
view()
This is the default action of the index.php entry point: just view the page of the given title.
Definition ImagePage.php:98
getThumbPrevText( $params, $sizeLinkBigImagePreview)
Make the text under the image to say what size preview.
static linkKnown( $target, $html=null, $customAttribs=[], $query=[], $options=[ 'known'])
Identical to link(), except $options defaults to 'known'.
Definition Linker.php:141
static processResponsiveImages( $file, $thumb, $hp)
Process responsive images: add 1.5x and 2x subimages to the thumbnail, where applicable.
Definition Linker.php:638
static makeThumbLinkObj(Title $title, $file, $label='', $alt='', $align='right', $params=[], $framed=false, $manualthumb="")
Make HTML for a thumbnail including image, border and caption.
Definition Linker.php:490
static makeExternalLink( $url, $text, $escape=true, $linktype='', $attribs=[], $title=null)
Make an external link.
Definition Linker.php:826
static showLogExtract(&$out, $types=[], $page='', $user='', $param=[])
Show log extract.
MediaWiki exception.
Set options of the Parser.
Represents a title within MediaWiki.
Definition Title.php:39
static userCanReUpload(User $user, File $img)
Check if a user is the last uploader.
static getDefaultOption( $opt)
Get a given default option value.
Definition User.php:1818
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Special handling for file pages.
Result wrapper for grabbing data queried from an IDatabase object.
$res
Definition database.txt:21
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
Definition globals.txt:62
const NS_FILE
Definition Defines.php:70
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
Definition hooks.txt:2857
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2880
either a plain
Definition hooks.txt:2105
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:2050
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:994
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition hooks.txt:895
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition hooks.txt:894
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition hooks.txt:2062
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition hooks.txt:3106
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition hooks.txt:933
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition hooks.txt:1656
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
Definition hooks.txt:2317
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition hooks.txt:247
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
const DB_REPLICA
Definition defines.php:25
if(!is_readable( $file)) $ext
Definition router.php:55
$params
if(!isset( $args[0])) $lang