summaryrefslogtreecommitdiff
path: root/extensions/ImageMap/ImageMap_body.php
blob: 7b53285ec5187bf0d0be534425a4dac5afe27624 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
<?php
/**
 * Main file for extension ImageMap.
 *
 * @file
 * @ingroup Extensions
 *
 * Syntax:
 * <imagemap>
 * Image:Foo.jpg | 100px | picture of a foo
 *
 * rect    0  0  50 50  [[Foo type A]]
 * circle  50 50 20     [[Foo type B]]
 *
 * desc bottom-left
 * </imagemap>
 *
 * Coordinates are relative to the source image, not the thumbnail
 *
 */

class ImageMap {
	static public $id = 0;

	const TOP_RIGHT = 0;
	const BOTTOM_RIGHT = 1;
	const BOTTOM_LEFT = 2;
	const TOP_LEFT = 3;
	const NONE = 4;

	/**
	 * @param $input
	 * @param $params
	 * @param $parser Parser
	 * @return array|mixed|string
	 */
	public static function render( $input, $params, $parser ) {
		global $wgExtensionAssetsPath, $wgUrlProtocols, $wgNoFollowLinks;

		$lines = explode( "\n", $input );

		$first = true;
		$lineNum = 0;
		$mapHTML = '';
		$links = array();

		# Define canonical desc types to allow i18n of 'imagemap_desc_types'
		$descTypesCanonical = 'top-right, bottom-right, bottom-left, top-left, none';
		$descType = self::BOTTOM_RIGHT;
		$defaultLinkAttribs = false;
		$realmap = true;
		$extLinks = array();
		foreach ( $lines as $line ) {
			++$lineNum;
			$externLink = false;

			$line = trim( $line );
			if ( $line == '' || $line[0] == '#' ) {
				continue;
			}

			if ( $first ) {
				$first = false;

				# The first line should have an image specification on it
				# Extract it and render the HTML
				$bits = explode( '|', $line, 2 );
				if ( count( $bits ) == 1 ) {
					$image = $bits[0];
					$options = '';
				} else {
					list( $image, $options ) = $bits;
				}
				$imageTitle = Title::newFromText( $image );
				if ( !$imageTitle || $imageTitle->getNamespace() != NS_IMAGE ) {
					return self::error( 'imagemap_no_image' );
				}
				if ( wfIsBadImage( $imageTitle->getDBkey(), $parser->mTitle ) ) {
					return self::error( 'imagemap_bad_image' );
				}
				// Parse the options so we can use links and the like in the caption
				$parsedOptions = $parser->recursiveTagParse( $options );
				$imageHTML = $parser->makeImage( $imageTitle, $parsedOptions );
				$parser->replaceLinkHolders( $imageHTML );
				$imageHTML = $parser->mStripState->unstripBoth( $imageHTML );
				$imageHTML = Sanitizer::normalizeCharReferences( $imageHTML );

				$domDoc = new DOMDocument();
				wfSuppressWarnings();
				$ok = $domDoc->loadXML( $imageHTML );
				wfRestoreWarnings();
				if ( !$ok ) {
					return self::error( 'imagemap_invalid_image' );
				}
				$xpath = new DOMXPath( $domDoc );
				$imgs = $xpath->query( '//img' );
				if ( !$imgs->length ) {
					return self::error( 'imagemap_invalid_image' );
				}
				$imageNode = $imgs->item( 0 );
				$thumbWidth = $imageNode->getAttribute( 'width' );
				$thumbHeight = $imageNode->getAttribute( 'height' );

				$imageObj = wfFindFile( $imageTitle );
				if ( !$imageObj || !$imageObj->exists() ) {
					return self::error( 'imagemap_invalid_image' );
				}
				# Add the linear dimensions to avoid inaccuracy in the scale
				# factor when one is much larger than the other
				# (sx+sy)/(x+y) = s
				$denominator = $imageObj->getWidth() + $imageObj->getHeight();
				$numerator = $thumbWidth + $thumbHeight;
				if ( $denominator <= 0 || $numerator <= 0 ) {
					return self::error( 'imagemap_invalid_image' );
				}
				$scale = $numerator / $denominator;
				continue;
			}

			# Handle desc spec
			$cmd = strtok( $line, " \t" );
			if ( $cmd == 'desc' ) {
				$typesText = wfMessage( 'imagemap_desc_types' )->inContentLanguage()->text();
				if ( $descTypesCanonical != $typesText ) {
					// i18n desc types exists
					$typesText = $descTypesCanonical . ', ' . $typesText;
				}
				$types = array_map( 'trim', explode( ',', $typesText ) );
				$type = trim( strtok( '' ) );
				$descType = array_search( $type, $types );
				if ( $descType > 4 ) {
					// A localized descType is used. Subtract 5 to reach the canonical desc type.
					$descType = $descType - 5;
				}
				if ( $descType === false || $descType < 0 ) { // <0? In theory never, but paranoia...
					return self::error( 'imagemap_invalid_desc', $typesText );
				}
				continue;
			}

			# Find the link
			$link = trim( strstr( $line, '[' ) );
			$m = array();
			if ( preg_match( '/^ \[\[  ([^|]*+)  \|  ([^\]]*+)  \]\] \w* $ /x', $link, $m ) ) {
				$title = Title::newFromText( $m[1] );
				$alt = trim( $m[2] );
			} elseif ( preg_match( '/^ \[\[  ([^\]]*+) \]\] \w* $ /x', $link, $m ) ) {
				$title = Title::newFromText( $m[1] );
				if ( is_null( $title ) ) {
					return self::error( 'imagemap_invalid_title', $lineNum );
				}
				$alt = $title->getFullText();
			} elseif ( in_array( substr( $link, 1, strpos( $link, '//' ) + 1 ), $wgUrlProtocols ) || in_array( substr( $link, 1, strpos( $link, ':' ) ), $wgUrlProtocols ) ) {
				if ( preg_match( '/^ \[  ([^\s]*+)  \s  ([^\]]*+)  \] \w* $ /x', $link, $m ) ) {
					$title = $m[1];
					$alt = trim( $m[2] );
					$externLink = true;
				} elseif ( preg_match( '/^ \[  ([^\]]*+) \] \w* $ /x', $link, $m ) ) {
					$title = $alt = trim( $m[1] );
					$externLink = true;
				}
			} else {
				return self::error( 'imagemap_no_link', $lineNum );
			}
			if ( !$title ) {
				return self::error( 'imagemap_invalid_title', $lineNum );
			}

			$shapeSpec = substr( $line, 0, -strlen( $link ) );

			# Tokenize shape spec
			$shape = strtok( $shapeSpec, " \t" );
			switch ( $shape ) {
				case 'default':
					$coords = array();
					break;
				case 'rect':
					$coords = self::tokenizeCoords( 4, $lineNum );
					if ( !is_array( $coords ) ) {
						return $coords;
					}
					break;
				case 'circle':
					$coords = self::tokenizeCoords( 3, $lineNum );
					if ( !is_array( $coords ) ) {
						return $coords;
					}
					break;
				case 'poly':
					$coords = array();
					$coord = strtok( " \t" );
					while ( $coord !== false ) {
						$coords[] = $coord;
						$coord = strtok( " \t" );
					}
					if ( !count( $coords ) ) {
						return self::error( 'imagemap_missing_coord', $lineNum );
					}
					if ( count( $coords ) % 2 !== 0 ) {
						return self::error( 'imagemap_poly_odd', $lineNum );
					}
					break;
				default:
					return self::error( 'imagemap_unrecognised_shape', $lineNum );
			}

			# Scale the coords using the size of the source image
			foreach ( $coords as $i => $c ) {
				$coords[$i] = intval( round( $c * $scale ) );
			}

			# Construct the area tag
			$attribs = array();
			if ( $externLink ) {
				$attribs['href'] = $title;
				$attribs['class'] = 'plainlinks';
				if ( $wgNoFollowLinks ) {
					$attribs['rel'] = 'nofollow';
				}
			} elseif ( $title->getFragment() != '' && $title->getPrefixedDBkey() == '' ) {
				# XXX: kluge to handle [[#Fragment]] links, should really fix getLocalURL()
				# in Title.php to return an empty string in this case
				$attribs['href'] = $title->getFragmentForURL();
			} else {
				$attribs['href'] = $title->getLocalURL() . $title->getFragmentForURL();
			}
			if ( $shape != 'default' ) {
				$attribs['shape'] = $shape;
			}
			if ( $coords ) {
				$attribs['coords'] = implode( ',', $coords );
			}
			if ( $alt != '' ) {
				if ( $shape != 'default' ) {
					$attribs['alt'] = $alt;
				}
				$attribs['title'] = $alt;
			}
			if ( $shape == 'default' ) {
				$defaultLinkAttribs = $attribs;
			} else {
				$mapHTML .= Xml::element( 'area', $attribs ) . "\n";
			}
			if ( $externLink ) {
				$extLinks[] = $title;
			} else {
				$links[] = $title;
			}
		}

		if ( $first ) {
			return self::error( 'imagemap_no_image' );
		}

		if ( $mapHTML == '' ) {
			// no areas defined, default only. It's not a real imagemap, so we do not need some tags
			$realmap = false;
		}

		if ( $realmap ) {
			# Construct the map
			# Add random number to avoid breaking cached HTML fragments that are
			# later joined together on the one page (bug 16471)
			$mapName = "ImageMap_" . ++self::$id . '_' . mt_rand( 0, 0x7fffffff );
			$mapHTML = "<map name=\"$mapName\">\n$mapHTML</map>\n";

			# Alter the image tag
			$imageNode->setAttribute( 'usemap', "#$mapName" );
		}

		# Add a surrounding div, remove the default link to the description page
		$anchor = $imageNode->parentNode;
		$parent = $anchor->parentNode;
		$div = $parent->insertBefore( new DOMElement( 'div' ), $anchor );
		$div->setAttribute( 'class', 'noresize' );
		if ( $defaultLinkAttribs ) {
			$defaultAnchor = $div->appendChild( new DOMElement( 'a' ) );
			foreach ( $defaultLinkAttribs as $name => $value ) {
				$defaultAnchor->setAttribute( $name, $value );
			}
			$imageParent = $defaultAnchor;
		} else {
			$imageParent = $div;
		}

		# Add the map HTML to the div
		# We used to add it before the div, but that made tidy unhappy
		if ( $mapHTML != '' ) {
			$mapDoc = new DOMDocument();
			$mapDoc->loadXML( $mapHTML );
			$mapNode = $domDoc->importNode( $mapDoc->documentElement, true );
			$div->appendChild( $mapNode );
		}

		$imageParent->appendChild( $imageNode->cloneNode( true ) );
		$parent->removeChild( $anchor );

		# Determine whether a "magnify" link is present
		$xpath = new DOMXPath( $domDoc );
		$magnify = $xpath->query( '//div[@class="magnify"]' );
		if ( !$magnify->length && $descType != self::NONE ) {
			# Add image description link
			if ( $descType == self::TOP_LEFT || $descType == self::BOTTOM_LEFT ) {
				$marginLeft = 0;
			} else {
				$marginLeft = $thumbWidth - 20;
			}
			if ( $descType == self::TOP_LEFT || $descType == self::TOP_RIGHT ) {
				$marginTop = -$thumbHeight;
				// 1px hack for IE, to stop it poking out the top
				$marginTop += 1;
			} else {
				$marginTop = -20;
			}
			$div->setAttribute( 'style', "height: {$thumbHeight}px; width: {$thumbWidth}px; " );
			$descWrapper = $div->appendChild( new DOMElement( 'div' ) );
			$descWrapper->setAttribute( 'style',
				"margin-left: {$marginLeft}px; " .
					"margin-top: {$marginTop}px; " .
					"text-align: left;"
			);

			$descAnchor = $descWrapper->appendChild( new DOMElement( 'a' ) );
			$descAnchor->setAttribute( 'href', $imageTitle->getLocalURL() );
			$descAnchor->setAttribute(
				'title',
				wfMessage( 'imagemap_description' )->inContentLanguage()->text()
			);
			$descImg = $descAnchor->appendChild( new DOMElement( 'img' ) );
			$descImg->setAttribute(
				'alt',
				wfMessage( 'imagemap_description' )->inContentLanguage()->text()
			);
			$descImg->setAttribute( 'src', "$wgExtensionAssetsPath/ImageMap/desc-20.png" );
			$descImg->setAttribute( 'style', 'border: none;' );
		}

		# Output the result
		# We use saveXML() not saveHTML() because then we get XHTML-compliant output.
		# The disadvantage is that we have to strip out the DTD
		$output = preg_replace( '/<\?xml[^?]*\?>/', '', $domDoc->saveXML() );

		# Register links
		foreach ( $links as $title ) {
			if ( $title->isExternal() || $title->getNamespace() == NS_SPECIAL ) {
				// Don't register special or interwiki links...
			} elseif ( $title->getNamespace() == NS_MEDIA ) {
				// Regular Media: links are recorded as image usages
				$parser->mOutput->addImage( $title->getDBkey() );
			} else {
				// Plain ol' link
				$parser->mOutput->addLink( $title );
			}
		}
		if ( isset( $extLinks ) ) {
			foreach ( $extLinks as $title ) {
				$parser->mOutput->addExternalLink( $title );
			}
		}
		# Armour output against broken parser
		$output = str_replace( "\n", '', $output );
		return $output;
	}

	/**
	 * @param $count int
	 * @param $lineNum int|string
	 * @return array|string
	 */
	static function tokenizeCoords( $count, $lineNum ) {
		$coords = array();
		for ( $i = 0; $i < $count; $i++ ) {
			$coord = strtok( " \t" );
			if ( $coord === false ) {
				return self::error( 'imagemap_missing_coord', $lineNum );
			}
			if ( !is_numeric( $coord ) || $coord > 1e9 || $coord < 0 ) {
				return self::error( 'imagemap_invalid_coord', $lineNum );
			}
			$coords[$i] = $coord;
		}
		return $coords;
	}

	/**
	 * @param $name string
	 * @param $line string|int|bool
	 * @return string
	 */
	static function error( $name, $line = false ) {
		return '<p class="error">' . wfMessage( $name, $line )->text() . '</p>';
	}
}