summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/Maps/src/SemanticMW/ResultPrinters/MapPrinter.php
blob: d3b17adb6ab93a7f5a3c687c0ad25387528c7e23 (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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
<?php

namespace Maps\SemanticMW\ResultPrinters;

use FormatJson;
use Html;
use Linker;
use Maps\Elements\BaseElement;
use Maps\Elements\Location;
use Maps\FileUrlFinder;
use Maps\MappingService;
use Maps\MapsFunctions;
use Maps\Presentation\ElementJsonSerializer;
use Maps\Presentation\WikitextParser;
use Maps\Presentation\WikitextParsers\LocationParser;
use ParamProcessor\ParamDefinition;
use Parser;
use SMW\Query\ResultPrinters\ResultPrinter;
use SMWOutputs;
use SMWQueryResult;
use Title;

/**
 * @licence GNU GPL v2+
 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
 * @author Peter Grassberger < petertheone@gmail.com >
 */
class MapPrinter extends ResultPrinter {

	private static $services = [];

	/**
	 * @var LocationParser
	 */
	private $locationParser;

	/**
	 * @var FileUrlFinder
	 */
	private $fileUrlFinder;

	/**
	 * @var MappingService
	 */
	private $service;

	/**
	 * @var WikitextParser
	 */
	private $wikitextParser;

	/**
	 * @var ElementJsonSerializer
	 */
	private $elementSerializer;

	/**
	 * @var string|boolean
	 */
	private $fatalErrorMsg = false;

	/**
	 * @param string $format
	 * @param bool $inline
	 */
	public function __construct( $format, $inline = true ) {
		$this->service = self::$services[$format];

		parent::__construct( $format, $inline );
	}

	/**
	 * @since 3.4
	 * FIXME: this is a temporary hack that should be replaced when SMW allows for dependency
	 * injection in query printers.
	 *
	 * @param MappingService $service
	 */
	public static function registerService( MappingService $service ) {
		self::$services[$service->getName()] = $service;
	}

	public static function registerDefaultService( $serviceName ) {
		self::$services['map'] = self::$services[$serviceName];
	}

	private function getParser(): Parser {
		$parser = $GLOBALS['wgParser'];

		if ( $parser instanceof \StubObject ) {
			return $parser->_newObject();
		}

		return $parser;
	}

	private function getParserClone(): Parser {
		$parser = $this->getParser();
		return clone $parser;
	}

	/**
	 * Builds up and returns the HTML for the map, with the queried coordinate data on it.
	 *
	 * @param SMWQueryResult $res
	 * @param int $outputMode
	 *
	 * @return string
	 */
	public final function getResultText( SMWQueryResult $res, $outputMode ) {
		if ( $this->fatalErrorMsg !== false ) {
			return $this->fatalErrorMsg;
		}

		$factory = \Maps\MapsFactory::newDefault();
		$this->locationParser = $factory->newLocationParser();
		$this->fileUrlFinder = $factory->getFileUrlFinder();

		$this->wikitextParser = new WikitextParser( $this->getParserClone() );
		$this->elementSerializer = new ElementJsonSerializer( $this->wikitextParser );

		$this->addTrackingCategoryIfNeeded();

		$params = $this->params;

		$queryHandler = new QueryHandler( $res, $outputMode );
		$queryHandler->setLinkStyle( $params['link'] );
		$queryHandler->setHeaderStyle( $params['headers'] );
		$queryHandler->setShowSubject( $params['showtitle'] );
		$queryHandler->setTemplate( $params['template'] );
		$queryHandler->setUserParam( $params['userparam'] );
		$queryHandler->setHideNamespace( $params['hidenamespace'] );
		$queryHandler->setActiveIcon( $params['activeicon'] );

		$this->handleMarkerData( $params, $queryHandler );

		$params['lines'] = $this->elementsToJson( $params['lines'] );
		$params['polygons'] = $this->elementsToJson( $params['polygons'] );
		$params['circles'] = $this->elementsToJson( $params['circles'] );
		$params['rectangles'] = $this->elementsToJson( $params['rectangles'] );

		$params['ajaxquery'] = urlencode( $params['ajaxquery'] );

		if ( $params['locations'] === [] ) {
			return $params['default'];
		}

		// We can only take care of the zoom defaulting here,
		// as not all locations are available in whats passed to Validator.
		if ( $this->fullParams['zoom']->wasSetToDefault() && count( $params['locations'] ) > 1 ) {
			$params['zoom'] = false;
		}

		$mapName = $this->service->newMapId();

		SMWOutputs::requireHeadItem(
			$mapName,
			$this->service->getDependencyHtml( $params )
		);

		foreach ( $this->service->getResourceModules() as $resourceModule ) {
			SMWOutputs::requireResource( $resourceModule );
		}

		if ( array_key_exists( 'source', $params ) ) {
			unset( $params['source'] );
		}

		return $this->getMapHTML( $params, $mapName );
	}

	private function elementsToJson( array $elements ) {
		return array_map(
			function( BaseElement $element ) {
				return $this->elementSerializer->elementToJson( $element );
			},
			$elements
		);
	}

	private function addTrackingCategoryIfNeeded() {
		/**
		 * @var Parser $wgParser
		 */
		global $wgParser;

		if ( $GLOBALS['egMapsEnableCategory'] && $wgParser->getOutput() !== null ) {
			$wgParser->addTrackingCategory( 'maps-tracking-category' );
		}
	}

	/**
	 * Converts the data in the coordinates parameter to JSON-ready objects.
	 * These get stored in the locations parameter, and the coordinates on gets deleted.
	 *
	 * @param array &$params
	 * @param QueryHandler $queryHandler
	 */
	private function handleMarkerData( array &$params, QueryHandler $queryHandler ) {
		$params['centre'] = $this->getCenter( $params['centre'] );

		$iconUrl = $this->fileUrlFinder->getUrlForFileName( $params['icon'] );
		$visitedIconUrl = $this->fileUrlFinder->getUrlForFileName( $params['visitedicon'] );

		$params['locations'] = $this->getJsonForStaticLocations(
			$params['staticlocations'],
			$params,
			$iconUrl,
			$visitedIconUrl
		);

		unset( $params['staticlocations'] );

		$params['locations'] = array_merge(
			$params['locations'],
			$this->getJsonForLocations(
				$queryHandler->getLocations(),
				$params,
				$iconUrl,
				$visitedIconUrl
			)
		);
	}

	private function getCenter( $coordinatesOrAddress ) {
		if ( $coordinatesOrAddress === false ) {
			return false;
		}

		try {
			// FIXME: a Location makes no sense here, since the non-coordinate data is not used
			$location = $this->locationParser->parse( $coordinatesOrAddress );
		}
		catch ( \Exception $ex ) {
			// TODO: somehow report this to the user
			return false;
		}

		return $location->getJSONObject();
	}

	private function getJsonForStaticLocations( array $staticLocations, array $params, $iconUrl, $visitedIconUrl ) {
		$locationsJson = [];

		foreach ( $staticLocations as $location ) {
			$locationsJson[] = $this->getJsonForStaticLocation(
				$location,
				$params,
				$iconUrl,
				$visitedIconUrl
			);
		}

		return $locationsJson;
	}

	private function getJsonForStaticLocation( Location $location, array $params, $iconUrl, $visitedIconUrl ) {
		$jsonObj = $location->getJSONObject( $params['title'], $params['label'], $iconUrl, '', '', $visitedIconUrl );

		$this->elementSerializer->titleAndText( $jsonObj );

		if ( $params['pagelabel'] ) {
			$jsonObj['inlineLabel'] = Linker::link( Title::newFromText( $jsonObj['title'] ) );
		}

		return $jsonObj;
	}

	/**
	 * @param Location[] $locations
	 * @param array $params
	 * @param string $iconUrl
	 * @param string $visitedIconUrl
	 *
	 * @return array
	 */
	private function getJsonForLocations( iterable $locations, array $params, string $iconUrl, string $visitedIconUrl ): array {
		$locationsJson = [];

		foreach ( $locations as $location ) {
			$jsonObj = $location->getJSONObject(
				$params['title'],
				$params['label'],
				$iconUrl,
				'',
				'',
				$visitedIconUrl
			);

			$jsonObj['title'] = strip_tags( $jsonObj['title'] );

			$locationsJson[] = $jsonObj;
		}

		return $locationsJson;
	}

	/**
	 * Returns the HTML to display the map.
	 *
	 * @param array $params
	 * @param string $mapName
	 *
	 * @return string
	 */
	private function getMapHTML( array $params, string $mapName ): string {
		return Html::rawElement(
			'div',
			[
				'id' => $mapName,
				'style' => "width: {$params['width']}; height: {$params['height']}; background-color: #cccccc; overflow: hidden;",
				'class' => 'maps-map maps-' . $this->service->getName()
			],
			wfMessage( 'maps-loading-map' )->inContentLanguage()->escaped() .
			Html::element(
				'div',
				[ 'style' => 'display:none', 'class' => 'mapdata' ],
				FormatJson::encode( $params )
			)
		);
	}

	/**
	 * Returns the internationalized name of the mapping service.
	 *
	 * @return string
	 */
	public final function getName() {
		return wfMessage( 'maps_' . $this->service->getName() )->text();
	}

	/**
	 * Returns a list of parameter information, for usage by Special:Ask and others.
	 *
	 * @return array
	 */
	public function getParameters() {
		$params = parent::getParameters();
		$paramInfo = $this->getParameterInfo();

		// Do not display this as an option, as the format already determines it
		// TODO: this can probably be done cleaner with some changes in Maps
		unset( $paramInfo['mappingservice'] );

		$params = array_merge( $params, $paramInfo );

		return $params;
	}

	/**
	 * Returns an array containing the parameter info.
	 *
	 * @return array
	 */
	private function getParameterInfo() {
		global $smgQPShowTitle, $smgQPTemplate, $smgQPHideNamespace;

		$params = array_merge(
			ParamDefinition::getCleanDefinitions( MapsFunctions::getCommonParameters() ),
			$this->service->getParameterInfo()
		);

		$params['staticlocations'] = [
			'type' => 'mapslocation',
			'aliases' => [ 'locations', 'points' ],
			'default' => [],
			'islist' => true,
			'delimiter' => ';',
			'message' => 'semanticmaps-par-staticlocations',
		];

		$params['showtitle'] = [
			'type' => 'boolean',
			'aliases' => 'show title',
			'default' => $smgQPShowTitle,
		];

		$params['hidenamespace'] = [
			'type' => 'boolean',
			'aliases' => 'hide namespace',
			'default' => $smgQPHideNamespace,
		];

		$params['template'] = [
			'default' => $smgQPTemplate,
		];

		$params['userparam'] = [
			'default' => '',
		];

		$params['activeicon'] = [
			'type' => 'string',
			'default' => '',
		];

		$params['pagelabel'] = [
			'type' => 'boolean',
			'default' => false,
		];

		$params['ajaxcoordproperty'] = [
			'default' => '',
		];

		$params['ajaxquery'] = [
			'default' => '',
			'type' => 'string'
		];

		// Messages:
		// semanticmaps-par-staticlocations, semanticmaps-par-showtitle, semanticmaps-par-hidenamespace,
		// semanticmaps-par-template, semanticmaps-par-userparam, semanticmaps-par-activeicon,
		// semanticmaps-par-pagelabel, semanticmaps-par-ajaxcoordproperty semanticmaps-par-ajaxquery
		foreach ( $params as $name => &$data ) {
			if ( is_array( $data ) && !array_key_exists( 'message', $data ) ) {
				$data['message'] = 'semanticmaps-par-' . $name;
			}
		}

		return $params;
	}
}