MediaWiki master
TraditionalImageGallery.php
Go to the documentation of this file.
1<?php
2
14use Wikimedia\Assert\Assert;
15
49 public function toHTML() {
50 $resolveFilesViaParser = $this->mParser instanceof Parser;
51 if ( $resolveFilesViaParser ) {
52 $parserOutput = $this->mParser->getOutput();
53 $repoGroup = null;
54 $linkRenderer = $this->mParser->getLinkRenderer();
55 $badFileLookup = $this->mParser->getBadFileLookup();
56 } else {
57 $parserOutput = $this->getOutput();
58 $services = MediaWikiServices::getInstance();
59 $repoGroup = $services->getRepoGroup();
60 $linkRenderer = $services->getLinkRenderer();
61 $badFileLookup = $services->getBadFileLookup();
62 }
63
64 if ( $this->mPerRow > 0 ) {
65 $maxwidth = $this->mPerRow * ( $this->mWidths + $this->getAllPadding() );
66 $oldStyle = $this->mAttribs['style'] ?? '';
67 $this->mAttribs['style'] = "max-width: {$maxwidth}px;" . $oldStyle;
68 }
69
70 $attribs = Sanitizer::mergeAttributes(
71 [ 'class' => 'gallery mw-gallery-' . $this->mMode ], $this->mAttribs );
72
73 $parserOutput->addModules( $this->getModules() );
74 $parserOutput->addModuleStyles( [ 'mediawiki.page.gallery.styles' ] );
75 $output = Html::openElement( 'ul', $attribs );
76 if ( $this->mCaption ) {
77 $output .= "\n\t" . Html::rawElement( 'li', [ 'class' => 'gallerycaption' ], $this->mCaption );
78 }
79
80 if ( $this->mShowFilename ) {
81 // Preload LinkCache info for when generating links
82 // of the filename below
83 $linkBatchFactory = MediaWikiServices::getInstance()->getLinkBatchFactory();
84 $lb = $linkBatchFactory->newLinkBatch();
85 foreach ( $this->mImages as [ $title, /* see below */ ] ) {
86 $lb->addObj( $title );
87 }
88 $lb->execute();
89 }
90
91 $lang = $this->getRenderLang();
92 $enableLegacyMediaDOM =
93 $this->getConfig()->get( MainConfigNames::ParserEnableLegacyMediaDOM );
94 $hookRunner = new HookRunner( MediaWikiServices::getInstance()->getHookContainer() );
95
96 # Output each image...
97 foreach ( $this->mImages as [ $nt, $text, $alt, $link, $handlerOpts, $loading, $imageOptions ] ) {
98 // "text" means "caption" here
101 $descQuery = false;
102 if ( $nt->inNamespace( NS_FILE ) && !$nt->isExternal() ) {
103 # Get the file...
104 if ( $resolveFilesViaParser ) {
105 # Give extensions a chance to select the file revision for us
106 $options = [];
107 $hookRunner->onBeforeParserFetchFileAndTitle(
108 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
109 $this->mParser, $nt, $options, $descQuery );
110 # Fetch and register the file (file title may be different via hooks)
111 [ $img, $nt ] = $this->mParser->fetchFileAndTitle( $nt, $options );
112 } else {
113 $img = $repoGroup->findFile( $nt );
114 }
115 } else {
116 $img = false;
117 }
118
119 $transformOptions = $this->getThumbParams( $img ) + $handlerOpts;
120 $thumb = $img ? $img->transform( $transformOptions ) : false;
121
122 $rdfaType = 'mw:File';
123
124 $isBadFile = $img && $thumb && $this->mHideBadImages &&
125 $badFileLookup->isBadFile( $nt->getDBkey(), $this->getContextTitle() );
126
127 if ( !$img || !$thumb || ( !$enableLegacyMediaDOM && $thumb->isError() ) || $isBadFile ) {
128 $rdfaType = 'mw:Error ' . $rdfaType;
129
130 if ( $enableLegacyMediaDOM ) {
131 if ( $isBadFile ) {
132 $thumbhtml = $linkRenderer->makeKnownLink( $nt, $nt->getText() );
133 } else {
134 $thumbhtml = htmlspecialchars( $img ? $img->getLastError() : $nt->getText() );
135 }
136 } else {
137 $currentExists = $img && $img->exists();
138 if ( $currentExists && !$thumb ) {
139 $label = wfMessage( 'thumbnail_error', '' )->text();
140 } elseif ( $thumb && $thumb->isError() ) {
141 Assert::invariant(
142 $thumb instanceof MediaTransformError,
143 'Unknown MediaTransformOutput: ' . get_class( $thumb )
144 );
145 $label = $thumb->toText();
146 } else {
147 $label = $alt ?? '';
148 }
149 $thumbhtml = Linker::makeBrokenImageLinkObj(
150 $nt, $label, '', '', '', false, $transformOptions, $currentExists
151 );
152 $thumbhtml = Html::rawElement( 'span', [ 'typeof' => $rdfaType ], $thumbhtml );
153 }
154
155 $thumbhtml = "\n\t\t\t" . Html::rawElement(
156 'div',
157 [
158 'class' => 'thumb',
159 'style' => 'height: ' . ( $this->getThumbPadding() + $this->mHeights ) . 'px;'
160 ],
161 $thumbhtml
162 );
163
164 if ( !$img && $resolveFilesViaParser ) {
165 $this->mParser->addTrackingCategory( 'broken-file-category' );
166 }
167 } else {
169 $vpad = $this->getVPad( $this->mHeights, $thumb->getHeight() );
170
171 // Backwards compat before the $imageOptions existed
172 if ( $imageOptions === null ) {
173 $imageParameters = [
174 'desc-link' => true,
175 'desc-query' => $descQuery,
176 'alt' => $alt ?? '',
177 'custom-url-link' => $link
178 ];
179 } else {
180 $params = [];
181 // An empty alt indicates an image is not a key part of the
182 // content and that non-visual browsers may omit it from
183 // rendering. Only set the parameter if it's explicitly
184 // requested.
185 if ( $alt !== null ) {
186 $params['alt'] = $alt;
187 }
188 $params['title'] = $imageOptions['title'];
189 if ( !$enableLegacyMediaDOM ) {
190 $params['img-class'] = 'mw-file-element';
191 }
192 $imageParameters = Linker::getImageLinkMTOParams(
193 $imageOptions, $descQuery, $this->mParser
194 ) + $params;
195 }
196
197 if ( $loading === ImageGalleryBase::LOADING_LAZY ) {
198 $imageParameters['loading'] = 'lazy';
199 }
200
201 $this->adjustImageParameters( $thumb, $imageParameters );
202
203 Linker::processResponsiveImages( $img, $thumb, $transformOptions );
204
205 $thumbhtml = $thumb->toHtml( $imageParameters );
206
207 if ( !$enableLegacyMediaDOM ) {
208 $thumbhtml = Html::rawElement(
209 'span', [ 'typeof' => $rdfaType ], $thumbhtml
210 );
211 } else {
212 $thumbhtml = Html::rawElement( 'div', [
213 # Auto-margin centering for block-level elements. Needed
214 # now that we have video handlers since they may emit block-
215 # level elements as opposed to simple <img> tags. ref
216 # http://css-discuss.incutio.com/?page=CenteringBlockElement
217 'style' => "margin:{$vpad}px auto;",
218 ], $thumbhtml );
219 }
220
221 # Set both fixed width and min-height.
222 $width = $this->getThumbDivWidth( $thumb->getWidth() );
223 $height = $this->getThumbPadding() + $this->mHeights;
224 $thumbhtml = "\n\t\t\t" . Html::rawElement( 'div', [
225 'class' => 'thumb',
226 'style' => "width: {$width}px;" .
227 ( !$enableLegacyMediaDOM && $this->mMode === 'traditional' ?
228 " height: {$height}px;" : '' ),
229 ], $thumbhtml );
230
231 // Call parser transform hook
232 if ( $resolveFilesViaParser ) {
234 $handler = $img->getHandler();
235 if ( $handler ) {
236 $handler->parserTransformHook( $this->mParser, $img );
237 }
238 $this->mParser->modifyImageHtml(
239 $img, [ 'handler' => $imageParameters ], $thumbhtml );
240 }
241 }
242
243 $meta = [];
244 if ( $img ) {
245 if ( $this->mShowDimensions ) {
246 $meta[] = htmlspecialchars( $img->getDimensionsString() );
247 }
248 if ( $this->mShowBytes ) {
249 $meta[] = htmlspecialchars( $lang->formatSize( $img->getSize() ) );
250 }
251 } elseif ( $this->mShowDimensions || $this->mShowBytes ) {
252 $meta[] = $this->msg( 'filemissing' )->escaped();
253 }
254 $meta = $lang->semicolonList( $meta );
255 if ( $meta ) {
256 $meta .= Html::rawElement( 'br', [] ) . "\n";
257 }
258
259 $textlink = $this->mShowFilename ?
260 $this->getCaptionHtml( $nt, $lang, $linkRenderer ) :
261 '';
262
263 $galleryText = $this->wrapGalleryText( $textlink . $text . $meta, $thumb );
264
265 $gbWidth = $this->getGBWidthOverwrite( $thumb ) ?: $this->getGBWidth( $thumb ) . 'px';
266 # Weird double wrapping (the extra div inside the li) needed due to FF2 bug
267 # Can be safely removed if FF2 falls completely out of existence
268 $output .= "\n\t\t" .
269 Html::rawElement(
270 'li',
271 [ 'class' => 'gallerybox', 'style' => 'width: ' . $gbWidth ],
272 ( $enableLegacyMediaDOM ? Html::openElement( 'div', [ 'style' => 'width: ' . $gbWidth ] ) : '' )
273 . $thumbhtml
274 . $galleryText
275 . "\n\t\t"
276 . ( $enableLegacyMediaDOM ? Html::closeElement( 'div' ) : '' )
277 );
278 }
279 $output .= "\n" . Html::closeElement( 'ul' );
280
281 return $output;
282 }
283
290 protected function getCaptionHtml( Title $nt, Language $lang, LinkRenderer $linkRenderer ) {
291 // Preloaded into LinkCache in toHTML
292 return $linkRenderer->makeKnownLink(
293 $nt,
294 is_int( $this->getCaptionLength() ) ?
295 $lang->truncateForVisual( $nt->getText(), $this->getCaptionLength() ) :
296 $nt->getText(),
297 [
298 'class' => 'galleryfilename' .
299 ( $this->getCaptionLength() === true ? ' galleryfilename-truncate' : '' )
300 ]
301 ) . "\n";
302 }
303
312 protected function wrapGalleryText( $galleryText, $thumb ) {
313 return "\n\t\t\t" . Html::rawElement( 'div', [ 'class' => "gallerytext" ], $galleryText );
314 }
315
322 protected function getThumbPadding() {
323 return 30;
324 }
325
331 protected function getGBPadding() {
332 return 5;
333 }
334
342 protected function getGBBorders() {
343 return 8;
344 }
345
353 protected function getCaptionLength() {
355 }
356
362 protected function getAllPadding() {
363 return $this->getThumbPadding() + $this->getGBPadding() + $this->getGBBorders();
364 }
365
375 protected function getVPad( $boxHeight, $thumbHeight ) {
376 return ( $this->getThumbPadding() + $boxHeight - $thumbHeight ) / 2;
377 }
378
385 protected function getThumbParams( $img ) {
386 return [
387 'width' => $this->mWidths,
388 'height' => $this->mHeights
389 ];
390 }
391
399 protected function getThumbDivWidth( $thumbWidth ) {
400 return $this->mWidths + $this->getThumbPadding();
401 }
402
413 protected function getGBWidth( $thumb ) {
414 return $this->mWidths + $this->getThumbPadding() + $this->getGBPadding();
415 }
416
428 protected function getGBWidthOverwrite( $thumb ) {
429 return false;
430 }
431
439 protected function getModules() {
440 return [];
441 }
442
450 protected function adjustImageParameters( $thumb, &$imageParameters ) {
451 }
452}
const NS_FILE
Definition Defines.php:71
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
bool int $mCaptionLength
Length to truncate filename to in caption when using "showfilename".
getRenderLang()
Determines the correct language to be used for this image gallery.
Basic media transform error class.
Base class for the output of MediaHandler::doTransform() and File::transform().
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:93
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
This class is a collection of static functions that serve two purposes:
Definition Html.php:56
Base class for language-specific code.
Definition Language.php:82
truncateForVisual( $string, $length, $ellipsis='...', $adjustLength=true)
Truncate a string to a specified number of characters, appending an optional string (e....
Class that generates HTML for internal links.
makeKnownLink( $target, $text=null, array $extraAttribs=[], array $query=[])
Make a link that's styled as if the target page exists (usually a "blue link", although the styling m...
Some internal bits split of from Skin.php.
Definition Linker.php:62
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:147
HTML sanitizer for MediaWiki.
Definition Sanitizer.php:46
Represents a title within MediaWiki.
Definition Title.php:78
exists( $flags=0)
Check if page exists.
Definition Title.php:3143
getText()
Get the text form (spaces not underscores) of the main part.
Definition Title.php:1013
getThumbPadding()
How much padding the thumb has between the image and the inner div that contains the border.
getCaptionLength()
Length (in characters) to truncate filename to in caption when using "showfilename" (if int).
getVPad( $boxHeight, $thumbHeight)
Get vertical padding for a thumbnail.
getCaptionHtml(Title $nt, Language $lang, LinkRenderer $linkRenderer)
getThumbParams( $img)
Get the transform parameters for a thumbnail.
toHTML()
Return a HTML representation of the image gallery.
getGBWidth( $thumb)
Computed width of gallerybox .
getModules()
Get a list of modules to include in the page.
getGBBorders()
Get how much extra space the borders around the image takes up.
wrapGalleryText( $galleryText, $thumb)
Add the wrapper html around the thumb's caption.
adjustImageParameters( $thumb, &$imageParameters)
Adjust the image parameters for a thumbnail.
getGBWidthOverwrite( $thumb)
Allows overwriting the computed width of the gallerybox with a string, like '100'.
getThumbDivWidth( $thumbWidth)
Get the width of the inner div that contains the thumbnail in question.