xref: /plugin/openlayersmap/syntax/olmap.php (revision c8eb13626ece0cdbb2369662b8c76ea8fa800c3a)
1<?php
2/*
3 * Copyright (c) 2008-2016 Mark C. Prins <mprins@users.sf.net>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17if (! defined ( 'DOKU_INC' ))
18	define ( 'DOKU_INC', realpath ( dirname ( __FILE__ ) . '/../../' ) . '/' );
19if (! defined ( 'DOKU_PLUGIN' ))
20	define ( 'DOKU_PLUGIN', DOKU_INC . 'lib/plugins/' );
21require_once (DOKU_PLUGIN . 'syntax.php');
22
23/**
24 * DokuWiki Plugin openlayersmap (Syntax Component).
25 * Provides for display of an OpenLayers based map in a wiki page.
26 *
27 * @author Mark Prins
28 */
29class syntax_plugin_openlayersmap_olmap extends DokuWiki_Syntax_Plugin {
30
31	/**
32	 * defaults of the known attributes of the olmap tag.
33	 */
34	private $dflt = array (
35			'id' => 'olmap',
36			'width' => '550px',
37			'height' => '450px',
38			'lat' => 50.0,
39			'lon' => 5.1,
40			'zoom' => 12,
41			'autozoom' => 1,
42			'statusbar' => true,
43			'toolbar' => true,
44			'controls' => true,
45			'poihoverstyle' => false,
46			'baselyr' => 'OpenStreetMap',
47			'gpxfile' => '',
48			'kmlfile' => '',
49			'geojsonfile' => '',
50			'summary' => ''
51	);
52
53	/**
54	 *
55	 * @see DokuWiki_Syntax_Plugin::getType()
56	 */
57	function getType() {
58		return 'substition';
59	}
60
61	/**
62	 *
63	 * @see DokuWiki_Syntax_Plugin::getPType()
64	 */
65	function getPType() {
66		return 'block';
67	}
68
69	/**
70	 *
71	 * @see Doku_Parser_Mode::getSort()
72	 */
73	function getSort() {
74		return 901;
75	}
76
77	/**
78	 *
79	 * @see Doku_Parser_Mode::connectTo()
80	 */
81	function connectTo($mode) {
82		$this->Lexer->addSpecialPattern ( '<olmap ?[^>\n]*>.*?</olmap>', $mode, 'plugin_openlayersmap_olmap' );
83	}
84
85	/**
86	 *
87	 * @see DokuWiki_Syntax_Plugin::handle()
88	 */
89	function handle($match, $state, $pos, Doku_Handler $handler) {
90		// break matched cdata into its components
91		list ( $str_params, $str_points ) = explode ( '>', substr ( $match, 7, - 9 ), 2 );
92		// get the lat/lon for adding them to the metadata (used by geotag)
93		preg_match ( '(lat[:|=]\"-?\d*\.?\d*\")', $match, $mainLat );
94		preg_match ( '(lon[:|=]\"-?\d*\.?\d*\")', $match, $mainLon );
95		$mainLat = substr ( $mainLat [0], 5, - 1 );
96		$mainLon = substr ( $mainLon [0], 5, - 1 );
97		if (!is_numeric($mainLat)) {
98			$mainLat = $this->dflt ['lat'];
99		}
100		if (!is_numeric($mainLon)) {
101			$mainLon = $this->dflt ['lon'];
102		}
103
104		$gmap = $this->_extract_params ( $str_params );
105		$overlay = $this->_extract_points ( $str_points );
106		$_firstimageID = '';
107
108		$_nocache = false;
109		// choose maptype based on the specified tag
110		$imgUrl = "{{";
111		if (stripos ( $gmap ['baselyr'], 'google' ) !== false) {
112			// Google
113			$imgUrl .= $this->_getGoogle ( $gmap, $overlay );
114			$imgUrl .= "&.png";
115		} elseif (stripos ( $gmap ['baselyr'], 'bing' ) !== false) {
116			// Bing
117			if (! $this->getConf ( 'bingAPIKey' )) {
118				// in case there is no Bing api key we'll use OSM
119				$_firstimageID = $this->_getStaticOSM ( $gmap, $overlay );
120				$imgUrl .= $_firstimageID;
121				if ($this->getConf ( 'optionStaticMapGenerator' ) == 'remote') {
122					$imgUrl .= "&.png";
123				}
124			} else {
125				// seems that Bing doesn't like the DW client, turn off caching
126				$_nocache = true;
127				$imgUrl .= $this->_getBing ( $gmap, $overlay ) . "&.png";
128			}
129		} /* elseif (stripos ( $gmap ['baselyr'], 'mapquest' ) !== false) {
130			// MapQuest
131			if (! $this->getConf ( 'mapquestAPIKey' )) {
132				// no API key for MapQuest, use OSM
133				$_firstimageID = $this->_getStaticOSM ( $gmap, $overlay );
134				$imgUrl .= $_firstimageID;
135				if ($this->getConf ( 'optionStaticMapGenerator' ) == 'remote') {
136					$imgUrl .= "&.png";
137				}
138			} else {
139				$imgUrl .= $this->_getMapQuest ( $gmap, $overlay );
140				$imgUrl .= "&.png";
141			}
142		} */ else {
143			// default OSM
144			$_firstimageID = $this->_getStaticOSM ( $gmap, $overlay );
145			$imgUrl .= $_firstimageID;
146			if ($this->getConf ( 'optionStaticMapGenerator' ) == 'remote') {
147				$imgUrl .= "&.png";
148			}
149		}
150
151		// append dw p_render specific params and render
152		$imgUrl .= "?" . str_replace ( "px", "", $gmap ['width'] ) . "x" . str_replace ( "px", "", $gmap ['height'] );
153		$imgUrl .= "&nolink";
154
155		// add nocache option for selected services
156		if ($_nocache) {
157			$imgUrl .= "&nocache";
158		}
159
160		$imgUrl .= " |".$gmap ['summary'] . " }}";
161
162		// dbglog($imgUrl,"complete image tags is:");
163
164		$mapid = $gmap ['id'];
165		// create a javascript parameter string for the map
166		$param = '';
167		foreach ( $gmap as $key => $val ) {
168			$param .= is_numeric ( $val ) ? "$key: $val, " : "$key: '" . hsc ( $val ) . "', ";
169		}
170		if (! empty ( $param )) {
171			$param = substr ( $param, 0, - 2 );
172		}
173		unset ( $gmap ['id'] );
174
175		// create a javascript serialisation of the point data
176		$poi = '';
177		$poitable = '';
178		$rowId = 0;
179		if (! empty ( $overlay )) {
180			foreach ( $overlay as $data ) {
181				list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
182				$rowId ++;
183				$poi .= ", {lat: $lat, lon: $lon, txt: '$text', angle: $angle, opacity: $opacity, img: '$img', rowId: $rowId}";
184
185				if ($this->getConf ( 'displayformat' ) === 'DMS') {
186					$lat = $this->convertLat ( $lat );
187					$lon = $this->convertLon ( $lon );
188				} else {
189					$lat .= 'º';
190					$lon .= 'º';
191				}
192
193				$poitable .= '
194					<tr>
195					<td class="rowId">' . $rowId . '</td>
196					<td class="icon"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/icons/' . $img . '" alt="'. substr($img, 0, -4) . $this->getlang('alt_legend_poi').' " /></td>
197					<td class="lat" title="' . $this->getLang ( 'olmapPOIlatTitle' ) . '">' . $lat . '</td>
198					<td class="lon" title="' . $this->getLang ( 'olmapPOIlonTitle' ) . '">' . $lon . '</td>
199					<td class="txt">' . $text . '</td>
200					</tr>';
201			}
202			$poi = substr ( $poi, 2 );
203		}
204		if (! empty ( $gmap ['kmlfile'] )) {
205			$poitable .= '
206					<tr>
207					<td class="rowId"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/kml_file.png" alt="KML file" /></td>
208					<td class="icon"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/kml_line.png" alt="' . $this->getlang('alt_legend_kml') .'" /></td>
209					<td class="txt" colspan="3">KML track: ' . $this->getFileName ( $gmap ['kmlfile'] ) . '</td>
210					</tr>';
211		}
212		if (! empty ( $gmap ['gpxfile'] )) {
213			$poitable .= '
214					<tr>
215					<td class="rowId"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/gpx_file.png" alt="GPX file" /></td>
216					<td class="icon"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/gpx_line.png" alt="' . $this->getlang('alt_legend_gpx') .'" /></td>
217					<td class="txt" colspan="3">GPX track: ' . $this->getFileName ( $gmap ['gpxfile'] ) . '</td>
218					</tr>';
219		}
220		if (! empty ( $gmap ['geojsonfile'] )) {
221			$poitable .= '
222					<tr>
223					<td class="rowId"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/geojson_file.png" alt="GeoJSON file" /></td>
224					<td class="icon"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/geojson_line.png" alt="' . $this->getlang('alt_legend_geojson') .'" /></td>
225					<td class="txt" colspan="3">GeoJSON track: ' . $this->getFileName ( $gmap ['geojsonfile'] ) . '</td>
226					</tr>';
227		}
228
229		$autozoom = empty ( $gmap ['autozoom'] ) ? $this->getConf ( 'autoZoomMap' ) : $gmap ['autozoom'];
230		$js .= "{mapOpts: {" . $param . ", displayformat: '" . $this->getConf ( 'displayformat' ) . "', autozoom: " . $autozoom . "}, poi: [$poi]};";
231		// unescape the json
232		$poitable = stripslashes ( $poitable );
233
234		return array (
235				$mapid,
236				$js,
237				$mainLat,
238				$mainLon,
239				$poitable,
240				$gmap ['summary'],
241				$imgUrl,
242				$_firstimageID
243		);
244	}
245
246	/**
247	 *
248	 * @see DokuWiki_Syntax_Plugin::render()
249	 */
250	function render($mode, Doku_Renderer $renderer, $data) {
251		// set to true after external scripts tags are written
252		static $initialised = false;
253		// incremented for each map tag in the page source so we can keep track of each map in this page
254		static $mapnumber = 0;
255
256		// dbglog($data, 'olmap::render() data.');
257		list ( $mapid, $param, $mainLat, $mainLon, $poitable, $poitabledesc, $staticImgUrl, $_firstimage ) = $data;
258
259		if ($mode == 'xhtml') {
260			$olscript = '';
261			$olEnable = false;
262			$gscript = '';
263			$gEnable = $this->getConf ( 'enableGoogle' );
264			$stamenEnable = $this->getConf ( 'enableStamen' );
265			$osmEnable = $this->getConf ( 'enableOSM' );
266			$enableBing = $this->getConf ( 'enableBing' );
267
268			$scriptEnable = '';
269			if (! $initialised) {
270				$initialised = true;
271				// render necessary script tags
272				if ($gEnable) {
273					$gscript = '<script type="text/javascript" src="//maps.google.com/maps/api/js?v=3.29&amp;key='.$this->getConf ( 'googleAPIkey' ).'"></script>';
274				}
275				$olscript = '<script type="text/javascript" src="' . DOKU_BASE . 'lib/plugins/openlayersmap/lib/OpenLayers.js"></script>';
276
277				$scriptEnable = '<script type="text/javascript">/*<![CDATA[*/';
278				$scriptEnable .= $olscript ? 'olEnable = true;' : 'olEnable = false;';
279				$scriptEnable .= 'gEnable = ' . ($gEnable ? 'true' : 'false') . ';';
280				$scriptEnable .= 'osmEnable = ' . ($osmEnable ? 'true' : 'false') . ';';
281				$scriptEnable .= 'stamenEnable = ' . ($stamenEnable ? 'true' : 'false') . ';';
282				$scriptEnable .= 'bEnable = ' . ($enableBing ? 'true' : 'false') . ';';
283				$scriptEnable .= 'bApiKey="' . $this->getConf ( 'bingAPIKey' ) . '";';
284				$scriptEnable .= 'tfApiKey="' . $this->getConf ( 'tfApiKey' ) . '";';
285				$scriptEnable .= 'gApiKey="' . $this->getConf ( 'googleAPIkey' ) . '";';
286				$scriptEnable .= '/*!]]>*/</script>';
287			}
288			$renderer->doc .= "$gscript\n$olscript\n$scriptEnable";
289			$renderer->doc .= '<div class="olMapHelp">' . $this->locale_xhtml ( "help" ) . '</div>';
290			if ($this->getConf ( 'enableA11y' )) {
291				$renderer->doc .= '<div id="' . $mapid . '-static" class="olStaticMap">' . p_render ( $mode, p_get_instructions ( $staticImgUrl ), $info ) . '</div>';
292			}
293			$renderer->doc .= '<div id="' . $mapid . '-clearer" class="clearer"><p>&nbsp;</p></div>';
294			if ($this->getConf ( 'enableA11y' )) {
295				// render a table of the POI for the print and a11y presentation, it is hidden using javascript
296				$renderer->doc .= '<div class="olPOItableSpan" id="' . $mapid . '-table-span">
297					<table class="olPOItable" id="' . $mapid . '-table">
298					<caption class="olPOITblCaption">' . $this->getLang ( 'olmapPOItitle' ) . '</caption>
299					<thead class="olPOITblHeader">
300					<tr>
301					<th class="rowId" scope="col">id</th>
302					<th class="icon" scope="col">' . $this->getLang ( 'olmapPOIicon' ) . '</th>
303					<th class="lat" scope="col" title="' . $this->getLang ( 'olmapPOIlatTitle' ) . '">' . $this->getLang ( 'olmapPOIlat' ) . '</th>
304					<th class="lon" scope="col" title="' . $this->getLang ( 'olmapPOIlonTitle' ) . '">' . $this->getLang ( 'olmapPOIlon' ) . '</th>
305					<th class="txt" scope="col">' . $this->getLang ( 'olmapPOItxt' ) . '</th>
306					</tr>
307					</thead>';
308				if ($poitabledesc != '') {
309					$renderer->doc .= '<tfoot class="olPOITblFooter"><tr><td colspan="5">' . $poitabledesc . '</td></tr></tfoot>';
310				}
311				$renderer->doc .= '<tbody class="olPOITblBody">' . $poitable . '</tbody>
312					</table></div>';
313			}
314			// render inline mapscript parts
315			$renderer->doc .= '<script type="text/javascript">/*<![CDATA[*/';
316			$renderer->doc .= " olMapData[$mapnumber] = $param /*!]]>*/</script>";
317			$mapnumber ++;
318			return true;
319		} elseif ($mode == 'metadata') {
320			if (! (($this->dflt ['lat'] == $mainLat) && ($this->dflt ['lon'] == $mainLon))) {
321				// render geo metadata, unless they are the default
322				$renderer->meta ['geo'] ['lat'] = $mainLat;
323				$renderer->meta ['geo'] ['lon'] = $mainLon;
324				if ($geophp = &plugin_load ( 'helper', 'geophp' )) {
325					// if we have the geoPHP helper, add the geohash
326					// fails with older php versions.. $renderer->meta['geo']['geohash'] = (new Point($mainLon,$mainLat))->out('geohash');
327					$p = new Point ( $mainLon, $mainLat );
328					$renderer->meta ['geo'] ['geohash'] = $p->out ( 'geohash' );
329				}
330			}
331
332			if (($this->getConf ( 'enableA11y' )) && (! empty ( $_firstimage ))) {
333				// add map local image into relation/firstimage if not already filled and when it is a local image
334
335				global $ID;
336				$rel = p_get_metadata ( $ID, 'relation', METADATA_RENDER_USING_CACHE );
337				$img = $rel ['firstimage'];
338				if (empty ( $img ) /* || $img == $_firstimage*/){
339					//dbglog ( $_firstimage, 'olmap::render#rendering image relation metadata for _firstimage as $img was empty or the same.' );
340					// This seems to never work; the firstimage entry in the .meta file is empty
341					// $renderer->meta['relation']['firstimage'] = $_firstimage;
342
343					// ... and neither does this; the firstimage entry in the .meta file is empty
344					// $relation = array('relation'=>array('firstimage'=>$_firstimage));
345					// p_set_metadata($ID, $relation, false, false);
346
347					// ... this works
348					$renderer->internalmedia ( $_firstimage, $poitabledesc );
349				}
350			}
351			return true;
352		}
353		return false;
354	}
355
356	/**
357	 * extract parameters for the map from the parameter string
358	 *
359	 * @param string $str_params
360	 *        	string of key="value" pairs
361	 * @return array associative array of parameters key=>value
362	 */
363	private function _extract_params($str_params) {
364		$param = array ();
365		preg_match_all ( '/(\w*)="(.*?)"/us', $str_params, $param, PREG_SET_ORDER );
366		// parse match for instructions, break into key value pairs
367		$gmap = $this->dflt;
368		foreach ( $gmap as $key => &$value ) {
369			$defval = $this->getConf ( 'default_' . $key );
370			if ($defval !== '') {
371				$value = $defval;
372			}
373		}
374		unset ( $value );
375		foreach ( $param as $kvpair ) {
376			list ( $match, $key, $val ) = $kvpair;
377			$key = strtolower ( $key );
378			if (isset ( $gmap [$key] )) {
379				if ($key == 'summary') {
380					// preserve case for summary field
381					$gmap [$key] = $val;
382				} elseif ($key == 'id') {
383					// preserve case for id field
384					$gmap [$key] = $val;
385				} else {
386					$gmap [$key] = strtolower ( $val );
387				}
388			}
389		}
390		return $gmap;
391	}
392
393	/**
394	 * extract overlay points for the map from the wiki syntax data
395	 *
396	 * @param string $str_points
397	 *        	multi-line string of lat,lon,text triplets
398	 * @return array multi-dimensional array of lat,lon,text triplets
399	 */
400	private function _extract_points($str_points) {
401		$point = array ();
402		// preg_match_all('/^([+-]?[0-9].*?),\s*([+-]?[0-9].*?),(.*?),(.*?),(.*?),(.*)$/um', $str_points, $point, PREG_SET_ORDER);
403		/*
404		 * group 1: ([+-]?[0-9]+(?:\.[0-9]*)?) group 2: ([+-]?[0-9]+(?:\.[0-9]*)?) group 3: (.*?) group 4: (.*?) group 5: (.*?) group 6: (.*)
405		 */
406		preg_match_all ( '/^([+-]?[0-9]+(?:\.[0-9]*)?),\s*([+-]?[0-9]+(?:\.[0-9]*)?),(.*?),(.*?),(.*?),(.*)$/um', $str_points, $point, PREG_SET_ORDER );
407		// create poi array
408		$overlay = array ();
409		foreach ( $point as $pt ) {
410			list ( $match, $lat, $lon, $angle, $opacity, $img, $text ) = $pt;
411			$lat = is_numeric ( $lat ) ? $lat : 0;
412			$lon = is_numeric ( $lon ) ? $lon : 0;
413			$angle = is_numeric ( $angle ) ? $angle : 0;
414			$opacity = is_numeric ( $opacity ) ? $opacity : 0.8;
415			// TODO validate using exist & set up default img?
416			$img = trim ( $img );
417			$text = p_get_instructions ( $text );
418			// dbg ( $text );
419			$text = p_render ( "xhtml", $text, $info );
420			// dbg ( $text );
421			$text = addslashes ( str_replace ( "\n", "", $text ) );
422			$overlay [] = array (
423					$lat,
424					$lon,
425					$text,
426					$angle,
427					$opacity,
428					$img
429			);
430		}
431		return $overlay;
432	}
433
434	/**
435	 * Create a MapQuest static map API image url.
436	 *
437	 * @param array $gmap
438	 * @param array $overlay
439	 */
440	 /*
441	private function _getMapQuest($gmap, $overlay) {
442		$sUrl = $this->getConf ( 'iconUrlOverload' );
443		if (! $sUrl) {
444			$sUrl = DOKU_URL;
445		}
446		switch ($gmap ['baselyr']) {
447			case 'mapquest hybrid' :
448				$maptype = 'hyb';
449				break;
450			case 'mapquest sat' :
451				// because sat coverage is very limited use 'hyb' instead of 'sat' so we don't get a blank map
452				$maptype = 'hyb';
453				break;
454			case 'mapquest road' :
455			default :
456				$maptype = 'map';
457				break;
458		}
459		$imgUrl = "http://open.mapquestapi.com/staticmap/v4/getmap?declutter=true&";
460		if (count ( $overlay ) < 1) {
461			$imgUrl .= "?center=" . $gmap ['lat'] . "," . $gmap ['lon'];
462			// max level for mapquest is 16
463			if ($gmap ['zoom'] > 16) {
464				$imgUrl .= "&zoom=16";
465			} else {
466				$imgUrl .= "&zoom=" . $gmap ['zoom'];
467			}
468		}
469		// use bestfit instead of center/zoom, needs upperleft/lowerright corners
470		// $bbox=$this->_calcBBOX($overlay, $gmap['lat'], $gmap['lon']);
471		// $imgUrl .= "bestfit=".$bbox['minlat'].",".$bbox['maxlon'].",".$bbox['maxlat'].",".$bbox['minlon'];
472
473		// TODO declutter option works well for square maps but not for rectangular, maybe compensate for that or compensate the mbr..
474		$imgUrl .= "&size=" . str_replace ( "px", "", $gmap ['width'] ) . "," . str_replace ( "px", "", $gmap ['height'] );
475
476		// TODO mapquest allows using one image url with a multiplier $NUMBER eg:
477		// $NUMBER = 2
478		// $imgUrl .= DOKU_URL."/".DOKU_PLUGIN."/".getPluginName()."/icons/".$img.",$NUMBER,C,".$lat1.",".$lon1.",0,0,0,0,C,".$lat2.",".$lon2.",0,0,0,0";
479		if (! empty ( $overlay )) {
480			$imgUrl .= "&xis=";
481			foreach ( $overlay as $data ) {
482				list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
483				// $imgUrl .= $sUrl."lib/plugins/openlayersmap/icons/".$img.",1,C,".$lat.",".$lon.",0,0,0,0,";
484				$imgUrl .= $sUrl . "lib/plugins/openlayersmap/icons/" . $img . ",1,C," . $lat . "," . $lon . ",";
485			}
486			$imgUrl = substr ( $imgUrl, 0, - 1 );
487		}
488		$imgUrl .= "&imageType=png&type=" . $maptype;
489		$imgUrl .= "&key=".$this->getConf ( 'mapquestAPIKey' );
490		// dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getMapQuest: MapQuest image url is:');
491		return $imgUrl;
492	}
493	*/
494
495	/**
496	 * Create a Google maps static image url w/ the poi.
497	 *
498	 * @param array $gmap
499	 * @param array $overlay
500	 */
501	private function _getGoogle($gmap, $overlay) {
502		$sUrl = $this->getConf ( 'iconUrlOverload' );
503		if (! $sUrl) {
504			$sUrl = DOKU_URL;
505		}
506		switch ($gmap ['baselyr']) {
507			case 'google hybrid' :
508				$maptype = 'hybrid';
509				break;
510			case 'google sat' :
511				$maptype = 'satellite';
512				break;
513			case 'terrain' :
514			case 'google relief' :
515				$maptype = 'terrain';
516				break;
517			case 'google road' :
518			default :
519				$maptype = 'roadmap';
520				break;
521		}
522		// TODO maybe use viewport / visible instead of center/zoom,
523		// see: https://developers.google.com/maps/documentation/staticmaps/index#Viewports
524		// http://maps.google.com/maps/api/staticmap?center=51.565690,5.456756&zoom=16&size=600x400&markers=icon:http://wild-water.nl/dokuwiki/lib/plugins/openlayersmap/icons/marker.png|label:1|51.565690,5.456756&markers=icon:http://wild-water.nl/dokuwiki/lib/plugins/openlayersmap/icons/marker-blue.png|51.566197,5.458966|label:2&markers=icon:http://wild-water.nl/dokuwiki/lib/plugins/openlayersmap/icons/parking.png|51.567177,5.457909|label:3&markers=icon:http://wild-water.nl/dokuwiki/lib/plugins/openlayersmap/icons/parking.png|51.566283,5.457330|label:4&markers=icon:http://wild-water.nl/dokuwiki/lib/plugins/openlayersmap/icons/parking.png|51.565630,5.457695|label:5&sensor=false&format=png&maptype=roadmap
525		$imgUrl = "http://maps.googleapis.com/maps/api/staticmap?";
526		$imgUrl .= "&size=" . str_replace ( "px", "", $gmap ['width'] ) . "x" . str_replace ( "px", "", $gmap ['height'] );
527		//if (!$this->getConf( 'autoZoomMap')) { // no need for center & zoom params }
528		$imgUrl .= "&center=" . $gmap ['lat'] . "," . $gmap ['lon'];
529		// max is 21 (== building scale), but that's overkill..
530		if ($gmap ['zoom'] > 17) {
531			$imgUrl .= "&zoom=17";
532		} else {
533			$imgUrl .= "&zoom=" . $gmap ['zoom'];
534		}
535		if (! empty ( $overlay )) {
536			$rowId = 0;
537			foreach ( $overlay as $data ) {
538				list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
539				$imgUrl .= "&markers=icon%3a" . $sUrl . "lib/plugins/openlayersmap/icons/" . $img . "%7c" . $lat . "," . $lon . "%7clabel%3a" . ++ $rowId;
540			}
541		}
542		$imgUrl .= "&format=png&maptype=" . $maptype;
543		global $conf;
544		$imgUrl .= "&language=" . $conf ['lang'];
545		if ($this->getConf( 'googleAPIkey' )) {
546			$imgUrl .= "&key=" . $this->getConf( 'googleAPIkey' );
547		}
548		// dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getGoogle: Google image url is:');
549		return $imgUrl;
550	}
551
552	/**
553	 * Create a Bing maps static image url w/ the poi.
554	 *
555	 * @param array $gmap
556	 * @param array $overlay
557	 */
558	private function _getBing($gmap, $overlay) {
559		switch ($gmap ['baselyr']) {
560			case 've hybrid' :
561			case 'bing hybrid' :
562				$maptype = 'AerialWithLabels';
563				break;
564			case 've sat' :
565			case 'bing sat' :
566				$maptype = 'Aerial';
567				break;
568			case 've normal' :
569			case 've road' :
570			case 've' :
571			case 'bing road' :
572			default :
573				$maptype = 'Road';
574				break;
575		}
576		$imgUrl = "http://dev.virtualearth.net/REST/v1/Imagery/Map/" . $maptype;// . "/";
577		if ($this->getConf ( 'autoZoomMap' )) {
578			$bbox = $this->_calcBBOX ( $overlay, $gmap ['lat'], $gmap ['lon'] );
579			//$imgUrl .= "?ma=" . $bbox ['minlat'] . "," . $bbox ['minlon'] . "," . $bbox ['maxlat'] . "," . $bbox ['maxlon'];
580			$imgUrl .= "?ma=" . $bbox ['minlat'] . "%2C" . $bbox ['minlon'] . "%2C" . $bbox ['maxlat'] . "%2C" . $bbox ['maxlon'];
581			$imgUrl .= "&dcl=1";
582		}
583		if (strpos ( $imgUrl, "?" ) === false)
584			$imgUrl .= "?";
585
586		//$imgUrl .= "&ms=" . str_replace ( "px", "", $gmap ['width'] ) . "," . str_replace ( "px", "", $gmap ['height'] );
587		$imgUrl .= "&ms=" . str_replace ( "px", "", $gmap ['width'] ) . "%2C" . str_replace ( "px", "", $gmap ['height'] );
588		$imgUrl .= "&key=" . $this->getConf ( 'bingAPIKey' );
589		if (! empty ( $overlay )) {
590			$rowId = 0;
591			foreach ( $overlay as $data ) {
592				list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
593				// TODO icon style lookup, see: http://msdn.microsoft.com/en-us/library/ff701719.aspx for iconStyle
594				$iconStyle = 32;
595				$rowId ++;
596				// NOTE: the max number of pushpins is 18! or we have to use POST (http://msdn.microsoft.com/en-us/library/ff701724.aspx)
597				if ($rowId == 18) {
598					break;
599				}
600				//$imgUrl .= "&pp=$lat,$lon;$iconStyle;$rowId";
601				$imgUrl .= "&pp=$lat%2C$lon%3B$iconStyle%3B$rowId";
602
603			}
604		}
605		global $conf;
606		$imgUrl .= "&fmt=png";
607		$imgUrl .= "&c=" . $conf ['lang'];
608		// dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getBing: bing image url is:');
609		return $imgUrl;
610	}
611
612	/**
613	 * Create a static OSM map image url w/ the poi from http://staticmap.openstreetmap.de (staticMapLite)
614	 * use http://staticmap.openstreetmap.de "staticMapLite" or a local version
615	 *
616	 * @param array $gmap
617	 * @param array $overlay
618	 *
619	 * @todo implementation for http://ojw.dev.openstreetmap.org/StaticMapDev/
620	 */
621	private function _getStaticOSM($gmap, $overlay) {
622		global $conf;
623
624		if ($this->getConf ( 'optionStaticMapGenerator' ) == 'local') {
625			// using local basemap composer
626			if (! $myMap = &plugin_load ( 'helper', 'openlayersmap_staticmap' )) {
627				dbglog ( $myMap, 'syntax_plugin_openlayersmap_olmap::_getStaticOSM: openlayersmap_staticmap plugin is not available.' );
628			}
629			if (! $geophp = &plugin_load ( 'helper', 'geophp' )) {
630				dbglog ( $geophp, 'syntax_plugin_openlayersmap_olmap::_getStaticOSM: geophp plugin is not available.' );
631			}
632			$size = str_replace ( "px", "", $gmap ['width'] ) . "x" . str_replace ( "px", "", $gmap ['height'] );
633
634			$markers = array();
635			if (! empty ( $overlay )) {
636				foreach ( $overlay as $data ) {
637					list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
638					$iconStyle = substr ( $img, 0, strlen ( $img ) - 4 );
639					$markers [] = array (
640							'lat' => $lat,
641							'lon' => $lon,
642							'type' => $iconStyle
643					);
644				}
645			}
646
647			$apikey = '';
648			switch ($gmap ['baselyr']) {
649				case 'mapnik' :
650				case 'openstreetmap' :
651					$maptype = 'openstreetmap';
652					break;
653				case 'transport' :
654					$maptype = 'transport';
655					$apikey = $this->getConf ( 'tfApiKey' );
656					break;
657				case 'landscape' :
658					$maptype = 'landscape';
659					$apikey = $this->getConf ( 'tfApiKey' );
660					break;
661				case 'outdoors' :
662					$maptype = 'outdoors';
663					$apikey = $this->getConf ( 'tfApiKey' );
664					break;
665				case 'cycle map' :
666					$maptype = 'cycle';
667					$apikey = $this->getConf ( 'tfApiKey' );
668					break;
669				case 'hike and bike map' :
670					$maptype = 'hikeandbike';
671					break;
672				case 'mapquest hybrid' :
673				case 'mapquest road' :
674				case 'mapquest sat' :
675					$maptype = 'mapquest';
676					break;
677				default :
678					$maptype = '';
679					break;
680			}
681
682			$result = $myMap->getMap ( $gmap ['lat'], $gmap ['lon'], $gmap ['zoom'], $size, $maptype, $markers, $gmap ['gpxfile'], $gmap ['kmlfile'], $gmap ['geojsonfile'] );
683		} else {
684			// using external basemap composer
685
686			// http://staticmap.openstreetmap.de/staticmap.php?center=47.000622235634,10.117187497601&zoom=5&size=500x350
687			// &markers=48.999812532766,8.3593749976708,lightblue1|43.154850037315,17.499999997306,lightblue1|49.487527053077,10.820312497573,ltblu-pushpin|47.951071133739,15.917968747369,ol-marker|47.921629720114,18.027343747285,ol-marker-gold|47.951071133739,19.257812497236,ol-marker-blue|47.180141361692,19.257812497236,ol-marker-green
688			$imgUrl = "http://staticmap.openstreetmap.de/staticmap.php";
689			$imgUrl .= "?center=" . $gmap ['lat'] . "," . $gmap ['lon'];
690			$imgUrl .= "&size=" . str_replace ( "px", "", $gmap ['width'] ) . "x" . str_replace ( "px", "", $gmap ['height'] );
691
692			if ($gmap ['zoom'] > 16) {
693				// actually this could even be 18, but that seems overkill
694				$imgUrl .= "&zoom=16";
695			} else {
696				$imgUrl .= "&zoom=" . $gmap ['zoom'];
697			}
698
699			if (! empty ( $overlay )) {
700				$rowId = 0;
701				$imgUrl .= "&markers=";
702				foreach ( $overlay as $data ) {
703					list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
704					$rowId ++;
705					$iconStyle = "lightblue$rowId";
706					$imgUrl .= "$lat,$lon,$iconStyle%7c";
707				}
708				$imgUrl = substr ( $imgUrl, 0, - 3 );
709			}
710
711			$result = $imgUrl;
712		}
713		// dbglog ( $result, 'syntax_plugin_openlayersmap_olmap::_getStaticOSM: osm image url is:' );
714		return $result;
715	}
716
717	/**
718	 * Calculate the minimum bbox for a start location + poi.
719	 *
720	 * @param array $overlay
721	 *        	multi-dimensional array of array($lat, $lon, $text, $angle, $opacity, $img)
722	 * @param float $lat
723	 *        	latitude for map center
724	 * @param float $lon
725	 *        	longitude for map center
726	 * @return multitype:float array describing the mbr and center point
727	 */
728	private function _calcBBOX($overlay, $lat, $lon) {
729		$lats = array($lat);
730		$lons = array($lon);
731		foreach ( $overlay as $data ) {
732			list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
733			$lats [] = $lat;
734			$lons [] = $lon;
735		}
736		sort ( $lats );
737		sort ( $lons );
738		// TODO: make edge/wrap around cases work
739		$centerlat = $lats [0] + ($lats [count ( $lats ) - 1] - $lats [0]);
740		$centerlon = $lons [0] + ($lons [count ( $lats ) - 1] - $lons [0]);
741		return array (
742				'minlat' => $lats [0],
743				'minlon' => $lons [0],
744				'maxlat' => $lats [count ( $lats ) - 1],
745				'maxlon' => $lons [count ( $lats ) - 1],
746				'centerlat' => $centerlat,
747				'centerlon' => $centerlon
748		);
749	}
750
751	/**
752	 * Figures out the base filename of a media path.
753	 *
754	 * @param String $mediaLink
755	 */
756	private function getFileName($mediaLink) {
757		$mediaLink = str_replace ( '[[', '', $mediaLink );
758		$mediaLink = str_replace ( ']]', '', $mediaLink );
759		$mediaLink = substr ( $mediaLink, 0, - 4 );
760		$parts = explode ( ':', $mediaLink );
761		$mediaLink = end ( $parts );
762		return str_replace ( '_', ' ', $mediaLink );
763	}
764
765	/**
766	 * Convert decimal degrees to degrees, minutes, seconds format
767	 *
768	 * @todo move this into a shared library
769	 * @param float $decimaldegrees
770	 * @return string dms
771	 */
772	private function _convertDDtoDMS($decimaldegrees) {
773		$dms = floor ( $decimaldegrees );
774		$secs = ($decimaldegrees - $dms) * 3600;
775		$min = floor ( $secs / 60 );
776		$sec = round ( $secs - ($min * 60), 3 );
777		$dms .= 'º' . $min . '\'' . $sec . '"';
778		return $dms;
779	}
780
781	/**
782	 * convert latitude in decimal degrees to DMS+hemisphere.
783	 *
784	 * @todo move this into a shared library
785	 * @param float $decimaldegrees
786	 * @return string
787	 */
788	private function convertLat($decimaldegrees) {
789		if (strpos ( $decimaldegrees, '-' ) !== false) {
790			$latPos = "S";
791		} else {
792			$latPos = "N";
793		}
794		$dms = $this->_convertDDtoDMS ( abs ( floatval ( $decimaldegrees ) ) );
795		return hsc ( $dms . $latPos );
796	}
797
798	/**
799	 * convert longitude in decimal degrees to DMS+hemisphere.
800	 *
801	 * @todo move this into a shared library
802	 * @param float $decimaldegrees
803	 * @return string
804	 */
805	private function convertLon($decimaldegrees) {
806		if (strpos ( $decimaldegrees, '-' ) !== false) {
807			$lonPos = "W";
808		} else {
809			$lonPos = "E";
810		}
811		$dms = $this->_convertDDtoDMS ( abs ( floatval ( $decimaldegrees ) ) );
812		return hsc ( $dms . $lonPos );
813	}
814}
815