Debian Codegraph @

extensions/ImageMap/includes/ImageMap.php

raw symbols SCIP
1 <?php
2 /**
3 * Main file for extension ImageMap.
4 *
5 * @file
6 * @ingroup Extensions
7 *
8 * Syntax:
9 * <imagemap>
10 * Image:Foo.jpg | 100px | picture of a foo
11 *
12 * rect 0 0 50 50 [[Foo type A]]
13 * circle 50 50 20 [[Foo type B]]
14 *
15 * desc bottom-left
16 * </imagemap>
17 *
18 * Coordinates are relative to the source image, not the thumbnail.
19 */
20
21 namespace MediaWiki\Extension\ImageMap;
22
23 use DOMDocumentFragment;
24 use DOMElement;
25 use MediaWiki\Hook\ParserFirstCallInitHook;
26 use MediaWiki\MediaWikiServices;
27 use MediaWiki\Output\OutputPage;
28 use MediaWiki\Parser\Parser;
29 use MediaWiki\Parser\Sanitizer;
30 use MediaWiki\Title\Title;
31 use MediaWiki\Xml\Xml;
32 use Wikimedia\Assert\Assert;
33 use Wikimedia\Parsoid\Ext\WTUtils;
34 use Wikimedia\Parsoid\Utils\DOMCompat;
35 use Wikimedia\Parsoid\Utils\DOMUtils;
36
37 class ImageMap implements ParserFirstCallInitHook {
38
39 private const TOP_RIGHT = 0;
40 private const BOTTOM_RIGHT = 1;
41 private const BOTTOM_LEFT = 2;
42 private const TOP_LEFT = 3;
43 private const NONE = 4;
44
45 private const DESC_TYPE_MAP = [
46 'top-right', 'bottom-right', 'bottom-left', 'top-left'
47 ];
48
49 /**
50 * @param Parser $parser
51 */
52 public function onParserFirstCallInit( $parser ) {
53 $parser->setHook( 'imagemap', [ $this, 'render' ] );
54 }
55
56 /**
57 * @param string|null $input
58 * @param array $params
59 * @param Parser $parser
60 * @return string HTML (Image map, or error message)
61 */
62 public function render( $input, $params, Parser $parser ) {
63 if ( $input === null ) {
64 return '';
65 }
66
67 global $wgUrlProtocols;
68 $config = MediaWikiServices::getInstance()->getMainConfig();
69 $enableLegacyMediaDOM = $config->get( 'ParserEnableLegacyMediaDOM' );
70
71 $lines = explode( "\n", $input );
72
73 $first = true;
74 $scale = 1;
75 $imageNode = null;
76 $domDoc = DOMCompat::newDocument( true );
77 $domFragment = null;
78 $thumbWidth = 0;
79 $thumbHeight = 0;
80 $imageTitle = null;
81 $mapHTML = '';
82 $links = [];
83 $explicitNone = false;
84
85 // Define canonical desc types to allow i18n of 'imagemap_desc_types'
86 $descTypesCanonical = 'top-right, bottom-right, bottom-left, top-left, none';
87 $descType = self::BOTTOM_RIGHT;
88 $defaultLinkAttribs = false;
89 $realMap = true;
90 $extLinks = [];
91 $services = MediaWikiServices::getInstance();
92 $repoGroup = $services->getRepoGroup();
93 $badFileLookup = $services->getBadFileLookup();
94 foreach ( $lines as $lineNum => $line ) {
95 $lineNum++;
96 $externLink = false;
97
98 $line = trim( $line );
99 if ( $line === '' || $line[0] === '#' ) {
100 continue;
101 }
102
103 if ( $first ) {
104 $first = false;
105
106 // The first line should have an image specification on it
107 // Extract it and render the HTML
108 $bits = explode( '|', $line, 2 );
109 $image = $bits[0];
110 $options = $bits[1] ?? '';
111 $imageTitle = Title::newFromText( $image );
112 if ( !$imageTitle || !$imageTitle->inNamespace( NS_FILE ) ) {
113 return $this->error( 'imagemap_no_image' );
114 }
115 if ( $badFileLookup->isBadFile( $imageTitle->getDBkey(), $parser->getTitle() ) ) {
116 return $this->error( 'imagemap_bad_image' );
117 }
118 // Parse the options so we can use links and the like in the caption
119 $parsedOptions = $options === '' ? '' : $parser->recursiveTagParse( $options );
120
121 if ( !$enableLegacyMediaDOM ) {
122 $explicitNone = preg_match( '/(^|\|)none(\||$)/D', $parsedOptions );
123 if ( !$explicitNone ) {
124 $parsedOptions .= '|none';
125 }
126 }
127
128 $imageHTML = $parser->makeImage( $imageTitle, $parsedOptions );
129 $parser->replaceLinkHolders( $imageHTML );
130 $imageHTML = $parser->getStripState()->unstripBoth( $imageHTML );
131 $imageHTML = Sanitizer::normalizeCharReferences( $imageHTML );
132
133 $domFragment = $domDoc->createDocumentFragment();
134 DOMUtils::setFragmentInnerHTML( $domFragment, $imageHTML );
135 $imageNode = DOMCompat::querySelector( $domFragment, 'img' );
136 if ( !$imageNode ) {
137 return $this->error( 'imagemap_invalid_image' );
138 }
139 $thumbWidth = (int)$imageNode->getAttribute( 'width' );
140 $thumbHeight = (int)$imageNode->getAttribute( 'height' );
141
142 $imageObj = $repoGroup->findFile( $imageTitle );
143 if ( !$imageObj || !$imageObj->exists() ) {
144 return $this->error( 'imagemap_invalid_image' );
145 }
146 // Add the linear dimensions to avoid inaccuracy in the scale
147 // factor when one is much larger than the other
148 // (sx+sy)/(x+y) = s
149 $denominator = $imageObj->getWidth() + $imageObj->getHeight();
150 $numerator = $thumbWidth + $thumbHeight;
151 if ( $denominator <= 0 || $numerator <= 0 ) {
152 return $this->error( 'imagemap_invalid_image' );
153 }
154 $scale = $numerator / $denominator;
155 continue;
156 }
157
158 // Handle desc spec
159 $cmd = strtok( $line, " \t" );
160 if ( $cmd === 'desc' ) {
161 $typesText = wfMessage( 'imagemap_desc_types' )->inContentLanguage()->text();
162 if ( $descTypesCanonical !== $typesText ) {
163 // i18n desc types exists
164 $typesText = $descTypesCanonical . ', ' . $typesText;
165 }
166 $types = array_map( 'trim', explode( ',', $typesText ) );
167 $type = trim( strtok( '' ) ?: '' );
168 $descType = array_search( $type, $types );
169 if ( $descType > 4 ) {
170 // A localized descType is used. Subtract 5 to reach the canonical desc type.
171 $descType -= 5;
172 }
173 // <0? In theory never, but paranoia...
174 if ( $descType === false || $descType < 0 ) {
175 return $this->error( 'imagemap_invalid_desc', $typesText );
176 }
177 continue;
178 }
179
180 $title = false;
181 $alt = '';
182 // Find the link
183 $link = trim( strstr( $line, '[' ) );
184 $m = [];
185 if ( preg_match( '/^ \[\[ ([^|]*+) \| ([^\]]*+) \]\] \w* $ /x', $link, $m ) ) {
186 $title = Title::newFromText( $m[1] );
187 $alt = trim( $m[2] );
188 } elseif ( preg_match( '/^ \[\[ ([^\]]*+) \]\] \w* $ /x', $link, $m ) ) {
189 $title = Title::newFromText( $m[1] );
190 if ( $title === null ) {
191 return $this->error( 'imagemap_invalid_title', $lineNum );
192 }
193 $alt = $title->getFullText();
194 } elseif ( in_array( substr( $link, 1, strpos( $link, '//' ) + 1 ), $wgUrlProtocols )
195 || in_array( substr( $link, 1, strpos( $link, ':' ) ), $wgUrlProtocols )
196 ) {
197 if ( preg_match( '/^ \[ ([^\s]*+) \s ([^\]]*+) \] \w* $ /x', $link, $m ) ) {
198 $title = $m[1];
199 $alt = trim( $m[2] );
200 $externLink = true;
201 } elseif ( preg_match( '/^ \[ ([^\]]*+) \] \w* $ /x', $link, $m ) ) {
202 $title = $alt = trim( $m[1] );
203 $externLink = true;
204 }
205 } else {
206 return $this->error( 'imagemap_no_link', $lineNum );
207 }
208 if ( !$title ) {
209 return $this->error( 'imagemap_invalid_title', $lineNum );
210 }
211
212 $shapeSpec = substr( $line, 0, -strlen( $link ) );
213
214 // Tokenize shape spec
215 $shape = strtok( $shapeSpec, " \t" );
216 switch ( $shape ) {
217 case 'default':
218 $coords = [];
219 break;
220 case 'rect':
221 $coords = $this->tokenizeCoords( $lineNum, 4 );
222 if ( !is_array( $coords ) ) {
223 return $coords;
224 }
225 break;
226 case 'circle':
227 $coords = $this->tokenizeCoords( $lineNum, 3 );
228 if ( !is_array( $coords ) ) {
229 return $coords;
230 }
231 break;
232 case 'poly':
233 $coords = $this->tokenizeCoords( $lineNum, 1, true );
234 if ( !is_array( $coords ) ) {
235 return $coords;
236 }
237 if ( count( $coords ) % 2 !== 0 ) {
238 return $this->error( 'imagemap_poly_odd', $lineNum );
239 }
240 break;
241 default:
242 return $this->error( 'imagemap_unrecognised_shape', $lineNum );
243 }
244
245 // Scale the coords using the size of the source image
246 foreach ( $coords as $i => $c ) {
247 $coords[$i] = (int)round( $c * $scale );
248 }
249
250 // Construct the area tag
251 $attribs = [];
252 if ( $externLink ) {
253 // Get the 'target' and 'rel' attributes for external link.
254 $attribs = $parser->getExternalLinkAttribs( $title );
255
256 $attribs['href'] = $title;
257 $attribs['class'] = 'plainlinks';
258 } elseif ( $title->getFragment() !== '' && $title->getPrefixedDBkey() === '' ) {
259 // XXX: kluge to handle [[#Fragment]] links, should really fix getLocalURL()
260 // in Title.php to return an empty string in this case
261 $attribs['href'] = $title->getFragmentForURL();
262 } else {
263 $attribs['href'] = $title->getLocalURL() . $title->getFragmentForURL();
264 }
265 if ( $shape !== 'default' ) {
266 $attribs['shape'] = $shape;
267 }
268 if ( $coords ) {
269 $attribs['coords'] = implode( ',', $coords );
270 }
271 if ( $alt !== '' ) {
272 if ( $shape !== 'default' ) {
273 $attribs['alt'] = $alt;
274 }
275 $attribs['title'] = $alt;
276 }
277 if ( $shape === 'default' ) {
278 $defaultLinkAttribs = $attribs;
279 } else {
280 // @phan-suppress-next-line SecurityCheck-DoubleEscaped
281 $mapHTML .= Xml::element( 'area', $attribs ) . "\n";
282 }
283 if ( $externLink ) {
284 $extLinks[] = $title;
285 } else {
286 $links[] = $title;
287 }
288 }
289
290 if ( !$imageNode || !$domFragment ) {
291 return $this->error( 'imagemap_no_image' );
292 }
293
294 if ( $mapHTML === '' ) {
295 // no areas defined, default only. It's not a real imagemap, so we do not need some tags
296 $realMap = false;
297 }
298
299 if ( $realMap ) {
300 // Construct the map
301 // Add a hash of the map HTML to avoid breaking cached HTML fragments that are
302 // later joined together on the one page (T18471).
303 // The only way these hashes can clash is if the map is identical, in which
304 // case it wouldn't matter that the "wrong" map was used.
305 $mapName = 'ImageMap_' . substr( md5( $mapHTML ), 0, 16 );
306 $mapHTML = "<map name=\"$mapName\">\n$mapHTML</map>\n";
307
308 // Alter the image tag
309 $imageNode->setAttribute( 'usemap', "#$mapName" );
310 }
311
312 if ( $mapHTML !== '' ) {
313 $mapFragment = $domDoc->createDocumentFragment();
314 DOMUtils::setFragmentInnerHTML( $mapFragment, $mapHTML );
315 $mapNode = $mapFragment->firstChild;
316 }
317
318 $div = null;
319
320 if ( $enableLegacyMediaDOM ) {
321 // Add a surrounding div, remove the default link to the description page
322 $anchor = $imageNode->parentNode;
323 $parent = $anchor->parentNode;
324 '@phan-var DOMElement $anchor';
325
326 // Handle cases where there are no anchors, like `|link=`
327 if ( $anchor instanceof DOMDocumentFragment ) {
328 $parent = $anchor;
329 $anchor = $imageNode;
330 }
331
332 $div = $domDoc->createElement( 'div' );
333 $parent->insertBefore( $div, $anchor );
334 $div->setAttribute( 'class', 'noresize' );
335 if ( $defaultLinkAttribs ) {
336 $defaultAnchor = $domDoc->createElement( 'a' );
337 $div->appendChild( $defaultAnchor );
338 foreach ( $defaultLinkAttribs as $name => $value ) {
339 $defaultAnchor->setAttribute( $name, $value );
340 }
341 $imageParent = $defaultAnchor;
342 } else {
343 $imageParent = $div;
344 }
345
346 // Add the map HTML to the div
347 if ( isset( $mapNode ) ) {
348 $div->appendChild( $mapNode );
349 }
350
351 $imageParent->appendChild( $imageNode->cloneNode( true ) );
352 $parent->removeChild( $anchor );
353 } else {
354 $anchor = $imageNode->parentNode;
355 $wrapper = $anchor->parentNode;
356 Assert::precondition( $wrapper instanceof DOMElement, 'Anchor node has a parent' );
357 '@phan-var DOMElement $anchor';
358
359 $classes = $wrapper->getAttribute( 'class' );
360
361 // For T22030
362 $classes .= ( $classes ? ' ' : '' ) . 'noresize';
363
364 // Remove that class if it was only added while forcing a block
365 if ( !$explicitNone ) {
366 $classes = trim( preg_replace( '/ ?mw-halign-none/', '', $classes ) );
367 }
368
369 $wrapper->setAttribute( 'class', $classes );
370
371 if ( $defaultLinkAttribs ) {
372 $imageParent = $domDoc->createElement( 'a' );
373 foreach ( $defaultLinkAttribs as $name => $value ) {
374 $imageParent->setAttribute( $name, $value );
375 }
376 } else {
377 $imageParent = $domDoc->createElement( 'span' );
378 }
379 $wrapper->insertBefore( $imageParent, $anchor );
380
381 if ( !WTUtils::hasVisibleCaption( $wrapper ) ) {
382 $caption = DOMCompat::querySelector( $domFragment, 'figcaption' );
383 $captionText = trim( WTUtils::textContentFromCaption( $caption ) );
384 if ( $captionText ) {
385 $imageParent->setAttribute( 'title', $captionText );
386 }
387 }
388
389 if ( isset( $mapNode ) ) {
390 $wrapper->insertBefore( $mapNode, $anchor );
391 }
392
393 $imageParent->appendChild( $imageNode->cloneNode( true ) );
394 $wrapper->removeChild( $anchor );
395 }
396
397 $parserOutput = $parser->getOutput();
398
399 if ( $enableLegacyMediaDOM ) {
400 // Determine whether a "magnify" link is present
401 $magnify = DOMCompat::querySelector( $domFragment, '.magnify' );
402 if ( !$magnify && $descType !== self::NONE ) {
403 // Add image description link
404 if ( $descType === self::TOP_LEFT || $descType === self::BOTTOM_LEFT ) {
405 $marginLeft = 0;
406 } else {
407 $marginLeft = $thumbWidth - 20;
408 }
409 if ( $descType === self::TOP_LEFT || $descType === self::TOP_RIGHT ) {
410 $marginTop = -$thumbHeight;
411 // 1px hack for IE, to stop it poking out the top
412 $marginTop++;
413 } else {
414 $marginTop = -20;
415 }
416 $div->setAttribute( 'style', "height: {$thumbHeight}px; width: {$thumbWidth}px; " );
417 $descWrapper = $domDoc->createElement( 'div' );
418 $div->appendChild( $descWrapper );
419 $descWrapper->setAttribute( 'style',
420 "margin-left: {$marginLeft}px; " .
421 "margin-top: {$marginTop}px; " .
422 "text-align: left;"
423 );
424
425 $descAnchor = $domDoc->createElement( 'a' );
426 $descWrapper->appendChild( $descAnchor );
427 $descAnchor->setAttribute( 'href', $imageTitle->getLocalURL() );
428 $descAnchor->setAttribute(
429 'title',
430 wfMessage( 'imagemap_description' )->inContentLanguage()->text()
431 );
432 $descImg = $domDoc->createElement( 'img' );
433 $descAnchor->appendChild( $descImg );
434 $descImg->setAttribute(
435 'alt',
436 wfMessage( 'imagemap_description' )->inContentLanguage()->text()
437 );
438 $url = $config->get( 'ExtensionAssetsPath' ) . '/ImageMap/resources/desc-20.png';
439 $descImg->setAttribute(
440 'src',
441 OutputPage::transformResourcePath( $config, $url )
442 );
443 $descImg->setAttribute( 'style', 'border: none;' );
444 }
445 } else {
446 '@phan-var DOMElement $wrapper';
447 $typeOf = $wrapper->getAttribute( 'typeof' );
448 if ( preg_match( '#\bmw:File/Thumb\b#', $typeOf ) ) {
449 // $imageNode was cloned above
450 $img = $imageParent->firstChild;
451 '@phan-var DOMElement $img';
452 if ( !$img->hasAttribute( 'resource' ) ) {
453 $img->setAttribute( 'resource', $imageTitle->getLocalURL() );
454 }
455 } elseif ( $descType !== self::NONE ) {
456 // The following classes are used here:
457 // * mw-ext-imagemap-desc-top-right
458 // * mw-ext-imagemap-desc-bottom-right
459 // * mw-ext-imagemap-desc-bottom-left
460 // * mw-ext-imagemap-desc-top-left
461 DOMCompat::getClassList( $wrapper )->add(
462 'mw-ext-imagemap-desc-' . self::DESC_TYPE_MAP[$descType]
463 );
464 // $imageNode was cloned above
465 $img = $imageParent->firstChild;
466 '@phan-var DOMElement $img';
467 if ( !$img->hasAttribute( 'resource' ) ) {
468 $img->setAttribute( 'resource', $imageTitle->getLocalURL() );
469 }
470 $parserOutput->addModules( [ 'ext.imagemap' ] );
471 $parserOutput->addModuleStyles( [ 'ext.imagemap.styles' ] );
472 }
473 }
474
475 // Output the result (XHTML-compliant)
476 $output = DOMUtils::getFragmentInnerHTML( $domFragment );
477
478 // Register links
479 foreach ( $links as $title ) {
480 if ( $title->isExternal() || $title->getNamespace() === NS_SPECIAL ) {
481 // Don't register special or interwiki links...
482 } elseif ( $title->getNamespace() === NS_MEDIA ) {
483 // Regular Media: links are recorded as image usages
484 $parserOutput->addImage( $title->getDBkey() );
485 } else {
486 // Plain ol' link
487 $parserOutput->addLink( $title );
488 }
489 }
490 foreach ( $extLinks as $title ) {
491 $parserOutput->addExternalLink( $title );
492 }
493 // Armour output against broken parser
494 return str_replace( "\n", '', $output );
495 }
496
497 /**
498 * @param int|string $lineNum Line number, for error reporting
499 * @param int $minCount Minimum token count
500 * @param bool $allowNegative
501 * @return array|string String with error (HTML), or array of coordinates
502 */
503 private function tokenizeCoords( $lineNum, $minCount = 0, $allowNegative = false ) {
504 $coords = [];
505 $coord = strtok( " \t" );
506 while ( $coord !== false ) {
507 if ( !is_numeric( $coord ) || $coord > 1e9 || ( !$allowNegative && $coord < 0 ) ) {
508 return $this->error( 'imagemap_invalid_coord', $lineNum );
509 }
510 $coords[] = $coord;
511 $coord = strtok( " \t" );
512 }
513 if ( count( $coords ) < $minCount ) {
514 // TODO: Should this also check there aren't too many coords?
515 return $this->error( 'imagemap_missing_coord', $lineNum );
516 }
517 return $coords;
518 }
519
520 /**
521 * @param string $name
522 * @param string|int|bool $line
523 * @return string HTML
524 */
525 private function error( $name, $line = false ) {
526 return '<p class="error">' . wfMessage( $name, $line )->parse() . '</p>';
527 }
528 }