xref: /plugin/openlayersmap/syntax/olmap.php (revision ab8cbd2baf29a832ccd9d40f1734e2ba1f0d0649)
1<?php
2/*
3 * Copyright (c) 2008-2014 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			'statusbar' => true,
42			'controls' => true,
43			'poihoverstyle' => false,
44			'baselyr' => 'OpenStreetMap',
45			'gpxfile' => '',
46			'kmlfile' => '',
47			'geojsonfile' => '',
48			'summary' => ''
49	);
50
51	/**
52	 *
53	 * @see DokuWiki_Syntax_Plugin::getType()
54	 */
55	function getType() {
56		return 'substition';
57	}
58
59	/**
60	 *
61	 * @see DokuWiki_Syntax_Plugin::getPType()
62	 */
63	function getPType() {
64		return 'block';
65	}
66
67	/**
68	 *
69	 * @see Doku_Parser_Mode::getSort()
70	 */
71	function getSort() {
72		return 901;
73	}
74
75	/**
76	 *
77	 * @see Doku_Parser_Mode::connectTo()
78	 */
79	function connectTo($mode) {
80		$this->Lexer->addSpecialPattern ( '<olmap ?[^>\n]*>.*?</olmap>', $mode, 'plugin_openlayersmap_olmap' );
81	}
82
83	/**
84	 *
85	 * @see DokuWiki_Syntax_Plugin::handle()
86	 */
87	function handle($match, $state, $pos, &$handler) {
88		// break matched cdata into its components
89		list ( $str_params, $str_points ) = explode ( '>', substr ( $match, 7, - 9 ), 2 );
90		// get the lat/lon for adding them to the metadata (used by geotag)
91		preg_match ( '(lat[:|=]\"-?\d*\.\d*\")', $match, $mainLat );
92		preg_match ( '(lon[:|=]\"-?\d*\.\d*\")', $match, $mainLon );
93		$mainLat = substr ( $mainLat [0], 5, - 1 );
94		$mainLon = substr ( $mainLon [0], 5, - 1 );
95
96		$gmap = $this->_extract_params ( $str_params );
97		$overlay = $this->_extract_points ( $str_points );
98		$_firstimageID = '';
99
100		// choose maptype based on the specified tag
101		$imgUrl = "{{";
102		if (stripos ( $gmap ['baselyr'], 'google' ) !== false) {
103			// use google
104			$imgUrl .= $this->_getGoogle ( $gmap, $overlay );
105			$imgUrl .= "&.png";
106		} elseif (stripos ( $gmap ['baselyr'], 've' ) !== false) {
107			// use bing, note that VE is deprecated
108			$imgUrl .= $this->_getBing ( $gmap, $overlay );
109			$imgUrl .= "&.png";
110		} elseif (stripos ( $gmap ['baselyr'], 'bing' ) !== false) {
111			// use bing
112			$imgUrl .= $this->_getBing ( $gmap, $overlay );
113			$imgUrl .= "&.png";
114		} elseif (stripos ( $gmap ['baselyr'], 'mapquest' ) !== false) {
115			if ($this->getConf ( 'optionStaticMapGenerator' ) == 'remote') {
116				// use mapquest remote
117				$imgUrl .= $this->_getMapQuest ( $gmap, $overlay );
118				$imgUrl .= "&.png";
119			} else {
120				$_firstimageID = $this->_getStaticOSM ( $gmap, $overlay );
121				$imgUrl .= $_firstimageID;
122			}
123		} else {
124			// fall back to OpenStreetMap
125			$_firstimageID = $this->_getStaticOSM ( $gmap, $overlay );
126			$imgUrl .= $_firstimageID;
127			if ($this->getConf ( 'optionStaticMapGenerator' ) == 'remote') {
128				$imgUrl .= "&.png";
129			}
130		}
131
132		// append dw p_render specific params and render
133		$imgUrl .= "?" . str_replace ( "px", "", $gmap ['width'] ) . "x" . str_replace ( "px", "", $gmap ['height'] );
134		$imgUrl .= "&nolink";
135		$imgUrl .= " |" . $gmap ['summary'] . " }}";
136
137		$mapid = $gmap ['id'];
138		// create a javascript parameter string for the map
139		$param = '';
140		foreach ( $gmap as $key => $val ) {
141			$param .= is_numeric ( $val ) ? "$key: $val, " : "$key: '" . hsc ( $val ) . "', ";
142		}
143		if (! empty ( $param )) {
144			$param = substr ( $param, 0, - 2 );
145		}
146		unset ( $gmap ['id'] );
147
148		// create a javascript serialisation of the point data
149		$poi = '';
150		$poitable = '';
151		$rowId = 0;
152		if (! empty ( $overlay )) {
153			foreach ( $overlay as $data ) {
154				list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
155				$rowId ++;
156				$poi .= ", {lat: $lat, lon: $lon, txt: '$text', angle: $angle, opacity: $opacity, img: '$img', rowId: $rowId}";
157				$poitable .= '
158						<tr>
159						<td class="rowId">' . $rowId . '</td>
160						<td class="icon"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/icons/' . $img . '" alt="icon" /></td>
161						<td class="lat" title="' . $this->getLang ( 'olmapPOIlatTitle' ) . '">' . $lat . '</td>
162						<td class="lon" title="' . $this->getLang ( 'olmapPOIlonTitle' ) . '">' . $lon . '</td>
163						<td class="txt">' . $text . '</td>
164						</tr>';
165			}
166			$poi = substr ( $poi, 2 );
167		}
168		if (! empty ( $gmap ['kmlfile'] )) {
169			$poitable .= '
170					<tr>
171					<td class="rowId"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/kml_file.png" alt="KML icon" /></td>
172					<td class="icon"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/kml_line.png" alt="icon" /></td>
173					<td class="txt" colspan="3">KML track: ' . $this->getFileName ( $gmap ['kmlfile'] ) . '</td>
174					</tr>';
175		}
176		if (! empty ( $gmap ['gpxfile'] )) {
177			$poitable .= '
178					<tr>
179					<td class="rowId"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/gpx_file.png" alt="GPX icon" /></td>
180					<td class="icon"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/gpx_line.png" alt="icon" /></td>
181					<td class="txt" colspan="3">GPX track: ' . $this->getFileName ( $gmap ['gpxfile'] ) . '</td>
182					</tr>';
183		}
184		if (! empty ( $gmap ['geojsonfile'] )) {
185			$poitable .= '
186					<tr>
187					<td class="rowId"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/geojson_file.png" alt="KML icon" /></td>
188					<td class="icon"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/geojson_line.png" alt="icon" /></td>
189					<td class="txt" colspan="3">GeoJSON track: ' . $this->getFileName ( $gmap ['geojsonfile'] ) . '</td>
190					</tr>';
191		}
192
193		$js .= "{mapOpts:{" . $param . " },poi:[$poi]};";
194		// unescape the json
195		$poitable = stripslashes ( $poitable );
196
197		return array (
198				$mapid,
199				$js,
200				$mainLat,
201				$mainLon,
202				$poitable,
203				$gmap ['summary'],
204				$imgUrl,
205				$_firstimageID
206		);
207	}
208
209	/**
210	 *
211	 * @see DokuWiki_Syntax_Plugin::render()
212	 */
213	function render($mode, &$renderer, $data) {
214		// set to true after external scripts tags are written
215		static $initialised = false;
216		// incremented for each map tag in the page source so we can keep track of each map in this page
217		static $mapnumber = 0;
218
219		// dbglog($data, 'olmap::render() data.');
220		list ( $mapid, $param, $mainLat, $mainLon, $poitable, $poitabledesc, $staticImgUrl, $_firstimage ) = $data;
221
222		if ($mode == 'xhtml') {
223			$olscript = '';
224			$olEnable = false;
225			$gscript = '';
226			$gEnable = $this->getConf ( 'enableGoogle' );
227			$mqEnable = $this->getConf ( 'enableMapQuest' );
228			$osmEnable = $this->getConf ( 'enableOSM' );
229			$enableBing = $this->getConf ( 'enableBing' );
230
231			$scriptEnable = '';
232			if (! $initialised) {
233				$initialised = true;
234				// render necessary script tags
235				if ($gEnable) {
236					$gscript = '<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.14&amp;sensor=false"></script>';
237				}
238				$olscript = '<script type="text/javascript" src="' . DOKU_BASE . 'lib/plugins/openlayersmap/lib/OpenLayers.js"></script>';
239
240				$scriptEnable = '<script type="text/javascript" charset="utf-8">/*<![CDATA[*/';
241				$scriptEnable .= $olscript ? 'olEnable = true;' : 'olEnable = false;';
242				$scriptEnable .= 'gEnable = ' . ($gEnable ? 'true' : 'false') . ';';
243				$scriptEnable .= 'osmEnable = ' . ($osmEnable ? 'true' : 'false') . ';';
244				$scriptEnable .= 'mqEnable = ' . ($mqEnable ? 'true' : 'false') . ';';
245				$scriptEnable .= 'bEnable = ' . ($enableBing ? 'true' : 'false') . ';';
246				$scriptEnable .= 'bApiKey="' . $this->getConf ( 'bingAPIKey' ) . '";';
247				$scriptEnable .= '/*!]]>*/</script>';
248			}
249			$renderer->doc .= "$gscript\n$olscript\n$scriptEnable";
250			$renderer->doc .= '<div class="olMapHelp">' . $this->locale_xhtml ( "help" ) . '</div>';
251			if ($this->getConf ( 'enableA11y' )) {
252				$renderer->doc .= '<div id="' . $mapid . '-static" class="olStaticMap">' . p_render ( $mode, p_get_instructions ( $staticImgUrl ), $info ) . '</div>';
253			}
254			$renderer->doc .= '<div id="' . $mapid . '-clearer" class="clearer"><p>&nbsp;</p></div>';
255			if ($this->getConf ( 'enableA11y' )) {
256				// render a (initially hidden) table of the POI for the print and a11y presentation
257				$renderer->doc .= '<div class="olPOItableSpan" id="' . $mapid . '-table-span"><table class="olPOItable" id="' . $mapid . '-table" summary="' . $poitabledesc . '" title="' . $this->getLang ( 'olmapPOItitle' ) . '">
258<caption class="olPOITblCaption">' . $this->getLang ( 'olmapPOItitle' ) . '</caption>
259<thead class="olPOITblHeader">
260<tr>
261<th class="rowId" scope="col">id</th>
262<th class="icon" scope="col">' . $this->getLang ( 'olmapPOIicon' ) . '</th>
263<th class="lat" scope="col" title="' . $this->getLang ( 'olmapPOIlatTitle' ) . '">' . $this->getLang ( 'olmapPOIlat' ) . '</th>
264<th class="lon" scope="col" title="' . $this->getLang ( 'olmapPOIlonTitle' ) . '">' . $this->getLang ( 'olmapPOIlon' ) . '</th>
265<th class="txt" scope="col">' . $this->getLang ( 'olmapPOItxt' ) . '</th>
266</tr>
267</thead>';
268				if ($poitabledesc != '') {
269					$renderer->doc .= '<tfoot class="olPOITblFooter"><tr><td colspan="5">' . $poitabledesc . '</td></tr></tfoot>';
270				}
271				$renderer->doc .= '<tbody class="olPOITblBody">' . $poitable . '</tbody>
272						</table></div>';
273			}
274			// render inline mapscript parts
275			$renderer->doc .= '<script type="text/javascript" charset="utf-8">/*<![CDATA[*/';
276			$renderer->doc .= " olMapData[$mapnumber] = $param /*!]]>*/</script>";
277			$mapnumber ++;
278			return true;
279		} elseif ($mode == 'metadata') {
280			if (! (($this->dflt ['lat'] == $mainLat) && ($thisdflt ['lon'] == $mainLon))) {
281				// render geo metadata, unless they are the default
282				$renderer->meta ['geo'] ['lat'] = $mainLat;
283				$renderer->meta ['geo'] ['lon'] = $mainLon;
284				if ($geophp = &plugin_load ( 'helper', 'geophp' )) {
285					// if we have the geoPHP helper, add the geohash
286					// fails with older php versions.. $renderer->meta['geo']['geohash'] = (new Point($mainLon,$mainLat))->out('geohash');
287					$p = new Point ( $mainLon, $mainLat );
288					$renderer->meta ['geo'] ['geohash'] = $p->out ( 'geohash' );
289				}
290			}
291
292			if (($this->getConf ( 'enableA11y' )) && (! empty ( $_firstimage ))) {
293				// add map local image into relation/firstimage if not already filled and when it is a local image
294
295				global $ID;
296				$rel = p_get_metadata ( $ID, 'relation', METADATA_RENDER_USING_CACHE );
297				$img = $rel ['firstimage'];
298				if (empty ( $img ) /* || $img == $_firstimage*/){
299					dbglog ( $_firstimage, 'olmap::render#rendering image relation metadata for _firstimage as $img was empty or the same.' );
300					// This seems to never work; the firstimage entry in the .meta file is empty
301					// $renderer->meta['relation']['firstimage'] = $_firstimage;
302
303					// ... and neither does this; the firstimage entry in the .meta file is empty
304					// $relation = array('relation'=>array('firstimage'=>$_firstimage));
305					// p_set_metadata($ID, $relation, false, false);
306
307					// ... this works
308					$renderer->internalmedia ( $_firstimage, $poitabledesc );
309				}
310			}
311			return true;
312		}
313		return false;
314	}
315
316	/**
317	 * extract parameters for the map from the parameter string
318	 *
319	 * @param string $str_params
320	 *        	string of key="value" pairs
321	 * @return array associative array of parameters key=>value
322	 */
323	private function _extract_params($str_params) {
324		$param = array ();
325		preg_match_all ( '/(\w*)="(.*?)"/us', $str_params, $param, PREG_SET_ORDER );
326		// parse match for instructions, break into key value pairs
327		$gmap = $this->dflt;
328		foreach ( $param as $kvpair ) {
329			list ( $match, $key, $val ) = $kvpair;
330			$key = strtolower ( $key );
331			if (isset ( $gmap [$key] )) {
332				if ($key == 'summary') {
333					// preserve case for summary field
334					$gmap [$key] = $val;
335				} elseif ($key == 'id') {
336					// preserve case for id field
337					$gmap [$key] = $val;
338				} else {
339					$gmap [$key] = strtolower ( $val );
340				}
341			}
342		}
343		return $gmap;
344	}
345
346	/**
347	 * extract overlay points for the map from the wiki syntax data
348	 *
349	 * @param string $str_points
350	 *        	multi-line string of lat,lon,text triplets
351	 * @return array multi-dimensional array of lat,lon,text triplets
352	 */
353	private function _extract_points($str_points) {
354		$point = array ();
355		// preg_match_all('/^([+-]?[0-9].*?),\s*([+-]?[0-9].*?),(.*?),(.*?),(.*?),(.*)$/um', $str_points, $point, PREG_SET_ORDER);
356		/*
357		 * group 1: ([+-]?[0-9]+(?:\.[0-9]*)?) group 2: ([+-]?[0-9]+(?:\.[0-9]*)?) group 3: (.*?) group 4: (.*?) group 5: (.*?) group 6: (.*)
358		 */
359		preg_match_all ( '/^([+-]?[0-9]+(?:\.[0-9]*)?),\s*([+-]?[0-9]+(?:\.[0-9]*)?),(.*?),(.*?),(.*?),(.*)$/um', $str_points, $point, PREG_SET_ORDER );
360		// create poi array
361		$overlay = array ();
362		foreach ( $point as $pt ) {
363			list ( $match, $lat, $lon, $angle, $opacity, $img, $text ) = $pt;
364			$lat = is_numeric ( $lat ) ? $lat : 0;
365			$lon = is_numeric ( $lon ) ? $lon : 0;
366			$angle = is_numeric ( $angle ) ? $angle : 0;
367			$opacity = is_numeric ( $opacity ) ? $opacity : 0.8;
368			// TODO validate using exist & set up default img?
369			$img = trim ( $img );
370			$text = p_get_instructions ( $text );
371			// dbg ( $text );
372			$text = p_render ( "xhtml", $text, $info );
373			// dbg ( $text );
374			$text = addslashes ( str_replace ( "\n", "", $text ) );
375			$overlay [] = array (
376					$lat,
377					$lon,
378					$text,
379					$angle,
380					$opacity,
381					$img
382			);
383		}
384		return $overlay;
385	}
386
387	/**
388	 * Create a MapQuest static map API image url.
389	 *
390	 * @param array $gmap
391	 * @param array $overlay
392	 */
393	private function _getMapQuest($gmap, $overlay) {
394		$sUrl = $this->getConf ( 'iconUrlOverload' );
395		if (! $sUrl) {
396			$sUrl = DOKU_URL;
397		}
398		switch ($gmap ['baselyr']) {
399			case 'mapquest hybrid' :
400				$maptype = 'hyb';
401				break;
402			case 'mapquest sat' :
403				// because sat coverage is very limited use 'hyb' instead of 'sat' so we don't get a blank map
404				$maptype = 'hyb';
405				break;
406			case 'mapquest road' :
407			default :
408				$maptype = 'map';
409				break;
410		}
411		$imgUrl = "http://open.mapquestapi.com/staticmap/v4/getmap?declutter=true&";
412		if (count ( $overlay ) < 1) {
413			$imgUrl .= "?center=" . $gmap ['lat'] . "," . $gmap ['lon'];
414			// max level for mapquest is 16
415			if ($gmap ['zoom'] > 16) {
416				$imgUrl .= "&zoom=16";
417			} else {
418				$imgUrl .= "&zoom=" . $gmap ['zoom'];
419			}
420		}
421		// use bestfit instead of center/zoom, needs upperleft/lowerright corners
422		// $bbox=$this->_calcBBOX($overlay, $gmap['lat'], $gmap['lon']);
423		// $imgUrl .= "bestfit=".$bbox['minlat'].",".$bbox['maxlon'].",".$bbox['maxlat'].",".$bbox['minlon'];
424
425		// TODO declutter option works well for square maps but not for rectangular, maybe compensate for that or compensate the mbr..
426		$imgUrl .= "&size=" . str_replace ( "px", "", $gmap ['width'] ) . "," . str_replace ( "px", "", $gmap ['height'] );
427
428		// TODO mapquest allows using one image url with a multiplier $NUMBER eg:
429		// $NUMBER = 2
430		// $imgUrl .= DOKU_URL."/".DOKU_PLUGIN."/".getPluginName()."/icons/".$img.",$NUMBER,C,".$lat1.",".$lon1.",0,0,0,0,C,".$lat2.",".$lon2.",0,0,0,0";
431		if (! empty ( $overlay )) {
432			$imgUrl .= "&xis=";
433			foreach ( $overlay as $data ) {
434				list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
435				// $imgUrl .= $sUrl."lib/plugins/openlayersmap/icons/".$img.",1,C,".$lat.",".$lon.",0,0,0,0,";
436				$imgUrl .= $sUrl . "lib/plugins/openlayersmap/icons/" . $img . ",1,C," . $lat . "," . $lon . ",";
437			}
438			$imgUrl = substr ( $imgUrl, 0, - 1 );
439		}
440		$imgUrl .= "&imageType=png&type=" . $maptype;
441		// dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getMapQuest: MapQuest image url is:');
442		return $imgUrl;
443	}
444
445	/**
446	 * Create a Google maps static image url w/ the poi.
447	 *
448	 * @param array $gmap
449	 * @param array $overlay
450	 */
451	private function _getGoogle($gmap, $overlay) {
452		$sUrl = $this->getConf ( 'iconUrlOverload' );
453		if (! $sUrl) {
454			$sUrl = DOKU_URL;
455		}
456		switch ($gmap ['baselyr']) {
457			case 'google hybrid' :
458				$maptype = 'hybrid';
459				break;
460			case 'google sat' :
461				$maptype = 'satellite';
462				break;
463			case 'google relief' :
464				$maptype = 'terrain';
465				break;
466			case 'google road' :
467			default :
468				$maptype = 'roadmap';
469				break;
470		}
471		// TODO maybe use viewport / visible instead of center/zoom,
472		// see: https://code.google.com/intl/nl/apis/maps/documentation/staticmaps/#ImplicitPositioning
473		// 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
474		$imgUrl = "http://maps.google.com/maps/api/staticmap?sensor=false";
475		$imgUrl .= "&size=" . str_replace ( "px", "", $gmap ['width'] ) . "x" . str_replace ( "px", "", $gmap ['height'] );
476		$imgUrl .= "&center=" . $gmap ['lat'] . "," . $gmap ['lon'];
477		// max is 21 (== building scale), but that's overkill..
478		if ($gmap ['zoom'] > 17) {
479			$imgUrl .= "&zoom=17";
480		} else {
481			$imgUrl .= "&zoom=" . $gmap ['zoom'];
482		}
483
484		if (! empty ( $overlay )) {
485			$rowId = 0;
486			foreach ( $overlay as $data ) {
487				list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
488				$imgUrl .= "&markers=icon%3a" . $sUrl . "lib/plugins/openlayersmap/icons/" . $img . "%7c" . $lat . "," . $lon . "%7clabel%3a" . ++ $rowId;
489			}
490		}
491		$imgUrl .= "&format=png&maptype=" . $maptype;
492		global $conf;
493		$imgUrl .= "&language=" . $conf ['lang'];
494		// dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getGoogle: Google image url is:');
495		return $imgUrl;
496	}
497
498	/**
499	 * Create a Bing maps static image url w/ the poi.
500	 *
501	 * @param array $gmap
502	 * @param array $overlay
503	 */
504	private function _getBing($gmap, $overlay) {
505		if (! $this->getConf ( 'bingAPIKey' )) {
506			// in case there is no Bing api key we'll use OSM
507			$this->_getStaticOSM ( $gmap, $overlay );
508		}
509		switch ($gmap ['baselyr']) {
510			case 've hybrid' :
511			case 'bing hybrid' :
512				$maptype = 'AerialWithLabels';
513				break;
514			case 've sat' :
515			case 'bing sat' :
516				$maptype = 'Aerial';
517				break;
518			case 've normal' :
519			case 've road' :
520			case 've' :
521			case 'bing road' :
522			default :
523				$maptype = 'Road';
524				break;
525		}
526		$imgUrl = "http://dev.virtualearth.net/REST/v1/Imagery/Map/" . $maptype . "/";
527		if (! $this->getConf ( 'autoZoomMap' )) {
528			$bbox = $this->_calcBBOX ( $overlay, $gmap ['lat'], $gmap ['lon'] );
529			$imgUrl .= "?mapArea=" . $bbox ['minlat'] . "," . $bbox ['minlon'] . "," . $bbox ['maxlat'] . "," . $bbox ['maxlon'];
530			$imgUrl .= "&declutter=1";
531			// or
532			// $imgUrl .= $gmap['lat'].",".$gmap['lon']."/".$gmap['zoom']."?";
533		}
534		if (strpos ( $imgUrl, "?" ) === false)
535			$imgUrl .= "?";
536
537		$imgUrl .= "&ms=" . str_replace ( "px", "", $gmap ['width'] ) . "," . str_replace ( "px", "", $gmap ['height'] );
538		$imgUrl .= "&key=" . $this->getConf ( 'bingAPIKey' );
539		if (! empty ( $overlay )) {
540			$rowId = 0;
541			foreach ( $overlay as $data ) {
542				list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
543				// TODO icon style lookup, see: http://msdn.microsoft.com/en-us/library/ff701719.aspx for iconStyle
544				$iconStyle = 32;
545				$rowId ++;
546				// NOTE: the max number of pushpins is 18! or we have to use POST (http://msdn.microsoft.com/en-us/library/ff701724.aspx)
547				if ($rowId == 18) {
548					break;
549				}
550				$imgUrl .= "&pp=$lat,$lon;$iconStyle;$rowId";
551			}
552		}
553		// dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getBing: bing image url is:');
554		return $imgUrl;
555	}
556
557	/**
558	 * Create a static OSM map image url w/ the poi from http://staticmap.openstreetmap.de (staticMapLite)
559	 * use http://staticmap.openstreetmap.de "staticMapLite" or a local version
560	 *
561	 * @param array $gmap
562	 * @param array $overlay
563	 *
564	 * @todo implementation for http://ojw.dev.openstreetmap.org/StaticMapDev/
565	 */
566	private function _getStaticOSM($gmap, $overlay) {
567		// http://staticmap.openstreetmap.de/staticmap.php?center=47.000622235634,10.117187497601&zoom=5&size=500x350
568		// &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
569		global $conf;
570
571		if ($this->getConf ( 'optionStaticMapGenerator' ) == 'local') {
572			if (! $my = &plugin_load ( 'helper', 'openlayersmap_staticmap' )) {
573				dbglog ( $my, 'syntax_plugin_openlayersmap_olmap::_getStaticOSM: openlayersmap_staticmap plugin is not available.' );
574			}
575			if (! $geophp = &plugin_load ( 'helper', 'geophp' )) {
576				dbglog ( $geophp, 'syntax_plugin_openlayersmap_olmap::_getStaticOSM: geophp plugin is not available.' );
577			}
578			$size = str_replace ( "px", "", $gmap ['width'] ) . "x" . str_replace ( "px", "", $gmap ['height'] );
579
580			$markers = '';
581			if (! empty ( $overlay )) {
582				foreach ( $overlay as $data ) {
583					list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
584					$iconStyle = substr ( $img, 0, strlen ( $img ) - 4 );
585					$markers [] = array (
586							'lat' => $lat,
587							'lon' => $lon,
588							'type' => $iconStyle
589					);
590				}
591			}
592
593			$result = $my->getMap ( $gmap ['lat'], $gmap ['lon'], $gmap ['zoom'], $size, $maptype, $markers, $gmap ['gpxfile'], $gmap ['kmlfile'], $gmap ['geojsonfile'] );
594		} else {
595			// default to external provider
596			$imgUrl = "http://staticmap.openstreetmap.de/staticmap.php";
597			$imgUrl .= "?center=" . $gmap ['lat'] . "," . $gmap ['lon'];
598			$imgUrl .= "&size=" . str_replace ( "px", "", $gmap ['width'] ) . "x" . str_replace ( "px", "", $gmap ['height'] );
599
600			if ($gmap ['zoom'] > 16) {
601				// actually this could even be 18, but that seems overkill
602				$imgUrl .= "&zoom=16";
603			} else {
604				$imgUrl .= "&zoom=" . $gmap ['zoom'];
605			}
606
607			switch ($gmap ['baselyr']) {
608				case 'mapnik' :
609				case 'openstreetmap' :
610					$maptype = 'openstreetmap';
611					break;
612				case 'transport' :
613					$maptype = 'transport';
614					break;
615				case 'landscape' :
616					$maptype = 'landscape';
617					break;
618				case 'cycle map' :
619					$maptype = 'cycle';
620					break;
621				case 'hike and bike map' :
622					$maptype = 'hikeandbike';
623					break;
624				case 'mapquest hybrid' :
625				case 'mapquest road' :
626				case 'mapquest sat' :
627					$maptype = 'mapquest';
628					break;
629				default :
630					$maptype = '';
631					break;
632			}
633			$imgUrl .= "&maptype=" . $maptype;
634
635			if (! empty ( $overlay )) {
636				$rowId = 0;
637				$imgUrl .= "&markers=";
638				foreach ( $overlay as $data ) {
639					list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
640					$rowId ++;
641					$iconStyle = "lightblue$rowId";
642					$imgUrl .= "$lat,$lon,$iconStyle%7c";
643				}
644				$imgUrl = substr ( $imgUrl, 0, - 3 );
645			}
646
647			$result = $imgUrl;
648		}
649
650		// dbglog($result,'syntax_plugin_openlayersmap_olmap::_getStaticOSM: osm image url is:');
651		return $result;
652	}
653
654	/**
655	 * Calculate the minimum bbox for a start location + poi.
656	 *
657	 * @param array $overlay
658	 *        	multi-dimensional array of array($lat, $lon, $text, $angle, $opacity, $img)
659	 * @param float $lat
660	 *        	latitude for map center
661	 * @param float $lon
662	 *        	longitude for map center
663	 * @return multitype:float array describing the mbr and center point
664	 */
665	private function _calcBBOX($overlay, $lat, $lon) {
666		$lats [] = $lat;
667		$lons [] = $lon;
668		foreach ( $overlay as $data ) {
669			list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
670			$lats [] = $lat;
671			$lons [] = $lon;
672		}
673		sort ( $lats );
674		sort ( $lons );
675		// TODO: make edge/wrap around cases work
676		$centerlat = $lats [0] + ($lats [count ( $lats ) - 1] - $lats [0]);
677		$centerlon = $lons [0] + ($lons [count ( $lats ) - 1] - $lons [0]);
678		return array (
679				'minlat' => $lats [0],
680				'minlon' => $lons [0],
681				'maxlat' => $lats [count ( $lats ) - 1],
682				'maxlon' => $lons [count ( $lats ) - 1],
683				'centerlat' => $centerlat,
684				'centerlon' => $centerlon
685		);
686	}
687
688	/**
689	 * Figures out the base filename of a media path.
690	 *
691	 * @param String $mediaLink
692	 */
693	private function getFileName($mediaLink) {
694		$mediaLink = str_replace ( '[[', '', $mediaLink );
695		$mediaLink = str_replace ( ']]', '', $mediaLink );
696		$mediaLink = substr ( $mediaLink, 0, - 4 );
697		$parts = explode ( ':', $mediaLink );
698		$mediaLink = end ( $parts );
699		return str_replace ( '_', ' ', $mediaLink );
700	}
701}