xref: /plugin/openlayersmap/syntax/olmap.php (revision 63037f2187145390666eb2e0cc9e8ca85bb88c3a)
1<?php
2/*
3 * Copyright (c) 2008-2011 Mark C. Prins <mc.prins@gmail.com>
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 */
17
18/**
19 * Plugin OL Maps: Allow Display of a OpenLayers Map in a wiki page.
20 *
21 * @author Mark Prins
22 */
23
24if (!defined('DOKU_INC'))
25define('DOKU_INC', realpath(dirname(__FILE__) . '/../../') . '/');
26if (!defined('DOKU_PLUGIN'))
27define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
28require_once (DOKU_PLUGIN . 'syntax.php');
29
30/**
31 * All DokuWiki plugins to extend the parser/rendering mechanism
32 * need to inherit from this class
33 */
34class syntax_plugin_openlayersmap_olmap extends DokuWiki_Syntax_Plugin {
35	/** defaults of the known attributes of the olmap tag. */
36	private $dflt = array (
37		'id' => 'olmap',
38		'width' => '550px',
39		'height' => '450px',
40		'lat' => 50.0,
41		'lon' => 5.1,
42		'zoom' => 12,
43		'toolbar' => true,
44		'statusbar' => true,
45		'controls' => true,
46		'poihoverstyle' => false,
47		'baselyr'=>'OpenStreetMap',
48	 	'gpxfile' => '',
49 		'kmlfile' => '',
50		'summary'=>''
51		);
52
53		/**
54		 * Return the type of syntax this plugin defines.
55		 * @Override
56		 */
57		function getType() {return 'substition';}
58
59		/**
60		 * Defines how this syntax is handled regarding paragraphs.
61		 * @Override
62		 */
63		function getPType() {return 'block';} //normal block stack
64
65		/**
66		 * Returns a number used to determine in which order modes are added.
67		 * @Override
68		 */
69		function getSort() {return 901;}
70
71		/**
72		 * This function is inherited from Doku_Parser_Mode.
73		 * Here is the place to register the regular expressions needed
74		 * to match your syntax.
75		 * @Override
76		 */
77		function connectTo($mode) {
78			$this->Lexer->addSpecialPattern('<olmap ?[^>\n]*>.*?</olmap>', $mode, 'plugin_openlayersmap_olmap');
79		}
80
81		/**
82		 * handle each olmap tag. prepare the matched syntax for use in the renderer.
83		 * @Override
84		 */
85		function handle($match, $state, $pos, &$handler) {
86			// break matched cdata into its components
87			list ($str_params, $str_points) = explode('>', substr($match, 7, -9), 2);
88			// get the lat/lon for adding them to the metadata (used by geotag)
89			preg_match('(lat[:|=]\"\d*\.\d*\")',$match,$mainLat);
90			preg_match('(lon[:|=]\"\d*\.\d*\")',$match,$mainLon);
91			$mainLat=substr($mainLat[0],5,-1);
92			$mainLon=substr($mainLon[0],5,-1);
93
94			$gmap = $this->_extract_params($str_params);
95			$overlay = $this->_extract_points($str_points);
96
97			$imgUrl = "{{";
98			// choose maptype based on tag
99			if (stripos($gmap['baselyr'],'google')>0){
100				// use google
101				$imgUrl .= $this->_getGoogle($gmap, $overlay);
102			}elseif (stripos($gmap['baselyr'],'ve')>0){
103				// use bing
104				$imgUrl .= $this->_getBing($gmap, $overlay);
105			}elseif (stripos($gmap['baselyr'],'mapquest')>0){
106				// use mapquest
107				$imgUrl .=$this->_getMapQuest($gmap,$overlay);
108			}else {
109				// use http://staticmap.openstreetmap.de
110				$imgUrl .=$this->_getStaticOSM($gmap,$overlay);
111			}
112
113			// append dw specific params
114			$imgUrl .="&.png?".$gmap['width']."x".$gmap['height'];
115			$imgUrl .= "&nolink";
116			$imgUrl .= " |".$gmap['summary']." }} ";
117			// remove 'px'
118			$imgUrl = str_replace("px", "",$imgUrl);
119
120			$imgUrl=p_render("xhtml", p_get_instructions($imgUrl), $info);
121
122			$mapid = $gmap['id'];
123
124			// determine width and height (inline styles) for the map image
125			//if ($gmap['width'] || $gmap['height']) {
126			//	$style = $gmap['width'] ? 'width: ' . $gmap['width'] . ";" : "";
127			//	$style .= $gmap['height'] ? 'height: ' . $gmap['height'] . ";" : "";
128			//	$style = "style='$style'";
129			//} else {
130			//	$style = '';
131			//}
132
133			// unset gmap values for width and height - they don't go into javascript
134			//unset ($gmap['width'], $gmap['height']);
135
136			// create a javascript parameter string for the map
137			$param = '';
138			foreach ($gmap as $key => $val) {
139				$param .= is_numeric($val) ? "$key: $val, " : "$key: '" . hsc($val) . "', ";
140			}
141			if (!empty ($param)) {
142				$param = substr($param, 0, -2);
143			}
144			unset ($gmap['id']);
145
146			// create a javascript serialisation of the point data
147			$poi = '';
148			$poitable='';
149			$rowId=0;
150			if (!empty ($overlay)) {
151				foreach ($overlay as $data) {
152					list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
153					$rowId++;
154					$poi .= ", {lat: $lat, lon: $lon, txt: '$text', angle: $angle, opacity: $opacity, img: '$img', rowId: $rowId}";
155					$poitable .='
156			<tr>
157				<td class="rowId">'.$rowId.'</td>
158				<td class="icon"><img src="'.DOKU_BASE.'/lib/plugins/openlayersmap/icons/'.$img.'" alt="icon" /></td>
159				<td class="lat" title="'.$this->getLang('olmapPOIlatTitle').'">'.$lat.'</td>
160				<td class="lon" title="'.$this->getLang('olmapPOIlonTitle').'">'.$lon.'</td>
161				<td class="txt">'.$text.'</td>
162			</tr>';
163				}
164				$poi = substr($poi, 2);
165			}
166			$js .= "createMap({" . $param . " },[$poi]);";
167			// unescape the json
168			$poitable = stripslashes($poitable);
169
170			return array($mapid,$js,$mainLat,$mainLon,$poitable,$gmap['summary'],$imgUrl);
171		}
172
173		/**
174		 * render html tag/output. render the content.
175		 * @Override
176		 */
177		function render($mode, &$renderer, $data) {
178			static $initialised = false; // set to true after script initialisation
179			list ($mapid, $param, $mainLat, $mainLon, $poitable, $poitabledesc, $staticImgUrl) = $data;
180
181			if ($mode == 'xhtml') {
182				$olscript = '';
183				$olEnable = false;
184				$gscript = '';
185				$gEnable = false;
186				$vscript = '';
187				$vEnable = false;
188				//$yscript = '';
189				//$yEnable = false;
190
191				$scriptEnable = '';
192
193				if (!$initialised) {
194					$initialised = true;
195					// render necessary script tags
196					$gscript = $this->getConf('googleScriptUrl');
197					$gscript = $gscript ? '<script type="text/javascript" src="' . $gscript . '"></script>' : "";
198
199					$vscript = $this->getConf('veScriptUrl');
200					$vscript = $vscript ? '<script type="text/javascript" src="' . $vscript . '"></script>' : "";
201
202					//$yscript = $this->getConf('yahooScriptUrl');
203					//$yscript = $yscript ? '<script type="text/javascript" src="' . $yscript . '"></script>' : "";
204
205					$olscript = $this->getConf('olScriptUrl');
206					$olscript = $olscript ? '<script type="text/javascript" src="' . $olscript . '"></script>' : "";
207					$olscript = str_replace('DOKU_PLUGIN', DOKU_PLUGIN, $olscript);
208
209					$scriptEnable = '<script type="text/javascript">' . "\n" . '<!--//--><![CDATA[//><!--' . "\n";
210					$scriptEnable .= $olscript ? 'olEnable = true;' : 'olEnable = false;';
211					//$scriptEnable .= $yscript ? ' yEnable = true;' : ' yEnable = false;';
212					$scriptEnable .= $vscript ? ' veEnable = true;' : ' veEnable = false;';
213					$scriptEnable .= $gscript ? ' gEnable = true;' : ' gEnable = false;';
214					$scriptEnable .= 'mqEnable = true;';
215					$scriptEnable .= "\n" . '//--><!]]>' . "\n" . '</script>';
216				}
217				$renderer->doc .= "				$olscript
218				$gscript
219				$vscript
220				$scriptEnable";
221
222				$renderer->doc .= "				<div id='$mapid-static' class='olStaticMap'>$staticImgUrl</div>
223			    <div id='$mapid-clearer' class='olClearBoth'></div>";
224
225				// render a (hidden) table of the POI for the print and a11y presentation
226				$renderer->doc .= ' 	<div class="olPOItableSpan" id="'.$mapid.'-table-span"><table class="olPOItable" id="'.$mapid.'-table" summary="'.$poitabledesc.'" title="'.$this->getLang('olmapPOItitle').'">
227		<caption class="olPOITblCaption">'.$this->getLang('olmapPOItitle').'</caption>
228		<thead class="olPOITblHeader">
229			<tr>
230				<th class="rowId" scope="col">id</th>
231				<th class="icon" scope="col">'.$this->getLang('olmapPOIicon').'</th>
232				<th class="lat" scope="col" title="'.$this->getLang('olmapPOIlatTitle').'">'.$this->getLang('olmapPOIlat').'</th>
233				<th class="lon" scope="col" title="'.$this->getLang('olmapPOIlonTitle').'">'.$this->getLang('olmapPOIlon').'</th>
234				<th class="txt" scope="col">'.$this->getLang('olmapPOItxt').'</th>
235			</tr>
236		</thead>
237		<tfoot class="olPOITblFooter"><tr><td colspan="5">'.$poitabledesc.'</td></tr></tfoot>
238		<tbody class="olPOITblBody">'.$poitable.'</tbody>
239	</table></div>';
240				//TODO no tfoot when $poitabledesc is empty
241
242				// render inline mapscript
243				$renderer->doc .="				<script type='text/javascript'><!--//--><![CDATA[//><!--
244			    var $mapid = $param
245			   //--><!]]></script>";
246
247			} elseif ($mode == 'metadata') {
248				// render metadata if available
249				if (!(($this->dflt['lat']==$mainLat)||($thisdflt['lon']==$mainLon))){
250					// unless they are the default
251					$renderer->meta['geo']['lat'] = $mainLat;
252					$renderer->meta['geo']['lon'] = $mainLon;
253				}
254				return true;
255			}
256			return false;
257		}
258
259		/**
260		 * extract parameters for the map from the parameter string
261		 *
262		 * @param   string    $str_params   string of key="value" pairs
263		 * @return  array                   associative array of parameters key=>value
264		 */
265		private function _extract_params($str_params) {
266			$param = array ();
267			preg_match_all('/(\w*)="(.*?)"/us', $str_params, $param, PREG_SET_ORDER);
268			// parse match for instructions, break into key value pairs
269			$gmap = $this->dflt;
270			foreach ($param as $kvpair) {
271				list ($match, $key, $val) = $kvpair;
272				$key = strtolower($key);
273				if (isset ($gmap[$key])){
274					if ($key == 'summary'){
275						// preserve case for summary field
276						$gmap[$key] = $val;
277					}else {
278						$gmap[$key] = strtolower($val);
279					}
280				}
281			}
282			return $gmap;
283		}
284
285		/**
286		 * extract overlay points for the map from the wiki syntax data
287		 *
288		 * @param   string    $str_points   multi-line string of lat,lon,text triplets
289		 * @return  array                   multi-dimensional array of lat,lon,text triplets
290		 */
291		private function _extract_points($str_points) {
292			$point = array ();
293			//preg_match_all('/^([+-]?[0-9].*?),\s*([+-]?[0-9].*?),(.*?),(.*?),(.*?),(.*)$/um', $str_points, $point, PREG_SET_ORDER);
294			/*
295			group 1: ([+-]?[0-9]+(?:\.[0-9]*)?)
296			group 2: ([+-]?[0-9]+(?:\.[0-9]*)?)
297			group 3: (.*?)
298			group 4: (.*?)
299			group 5: (.*?)
300			group 6: (.*)
301			*/
302			preg_match_all('/^([+-]?[0-9]+(?:\.[0-9]*)?),\s*([+-]?[0-9]+(?:\.[0-9]*)?),(.*?),(.*?),(.*?),(.*)$/um', $str_points, $point, PREG_SET_ORDER);
303			// create poi array
304			$overlay = array ();
305			foreach ($point as $pt) {
306				list ($match, $lat, $lon, $angle, $opacity, $img, $text) = $pt;
307				$lat = is_numeric($lat) ? $lat : 0;
308				$lon = is_numeric($lon) ? $lon : 0;
309				$angle = is_numeric($angle) ? $angle : 0;
310				$opacity = is_numeric($opacity) ? $opacity : 0.8;
311				$img = trim($img);
312				// TODO validate using exist & set up default img?
313				$text = addslashes(str_replace("\n", "", p_render("xhtml", p_get_instructions($text), $info)));
314				$overlay[] = array($lat, $lon, $text, $angle, $opacity, $img);
315			}
316			return $overlay;
317		}
318
319		/**
320		 * Create a MapQuest static map API image url.
321		 * @param array $gmap
322		 * @param array $overlay
323		 */
324		private function _getMapQuest($gmap,$overlay) {
325			$sUrl=$this->getConf('iconUrlOverload');
326			if (!$sUrl){
327				$sUrl=DOKU_URL;
328			}
329			switch ($gmap['baselyr']){
330				case 'mq hybrid':
331					$maptype='hyb (Hybrid)';
332					break;
333				case 'mq sat':
334					$maptype='sat (Satellite)';
335					break;
336				case 'mq normal':
337				default:
338					$maptype='map';
339					break;
340			}
341
342
343			$imgUrl = "http://open.mapquestapi.com/staticmap/v3/getmap";
344			$imgUrl .= "?center=".$gmap['lat'].",".$gmap['lon'];
345			$imgUrl .= "&size=".str_replace("px", "",$gmap['width']).",".str_replace("px", "",$gmap['height']);
346			// max level for mapquest is 16
347			if ($gmap['zoom']>16) {
348				$imgUrl .= "&zoom=16";
349			} else			{
350				$imgUrl .= "&zoom=".$gmap['zoom'];
351			}
352			// TODO mapquest allows using one image url with a multiplier $NUMBER eg:
353			// $NUMBER = 2
354			// $imgUrl .= DOKU_URL."/".DOKU_PLUGIN."/".getPluginName()."/icons/".$img.",$NUMBER,C,".$lat1.",".$lon1.",0,0,0,0,C,".$lat2.",".$lon2.",0,0,0,0";
355			if (!empty ($overlay)) {
356				$imgUrl .= "&xis=";
357				foreach ($overlay as $data) {
358					list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
359					$imgUrl .= $sUrl."lib/plugins/openlayersmap/icons/".$img.",1,C,".$lat.",".$lon.",0,0,0,0,";
360				}
361				$imgUrl = substr($imgUrl,0,-1);
362			}
363			$imgUrl .= "&imageType=png&type=".$maptype;
364			dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getMapQuest: MapQuest image url is:');
365			return $imgUrl;
366		}
367
368		private function _getGoogle($gmap, $overlay){
369			$sUrl=$this->getConf('iconUrlOverload');
370			if (!$sUrl){
371				$sUrl=DOKU_URL;
372			}
373			switch ($gmap['baselyr']){
374				case 'google hybrid':
375					$maptype='hybrid';
376					break;
377				case 'google sat':
378					$maptype='satellite';
379					break;
380				case 'google relief':
381					$maptype='terrain';
382					break;
383				case 'google normal':
384				default:
385					$maptype='roadmap';
386					break;
387			}
388
389			//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
390			$imgUrl = "http://maps.google.com/maps/api/staticmap";
391			$imgUrl .= "?center=".$gmap['lat'].",".$gmap['lon'];
392			$imgUrl .= "&size=".str_replace("px", "",$gmap['width'])."x".str_replace("px", "",$gmap['height']);
393			// don't need this anymore $imgUrl .= "&key=".$this->getConf('googleAPIKey');
394			// max is 21 (== building scale), but that's overkill..
395			if ($gmap['zoom']>16) {
396				$imgUrl .= "&zoom=16";
397			} else			{
398				$imgUrl .= "&zoom=".$gmap['zoom'];
399			}
400
401			if (!empty ($overlay)) {
402				$rowId=0;
403				foreach ($overlay as $data) {
404					list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
405					$imgUrl .= "&markers=icon%3a".$sUrl."lib/plugins/openlayersmap/icons/".$img."%7c".$lat.",".$lon."%7clabel%3a".++$rowId;
406				}
407			}
408			$imgUrl .= "&format=png&maptype=".$maptype."&sensor=false";
409			global $conf;
410			$imgUrl .= "&language=".$conf['lang'];
411			dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getGoogle: Google image url is:');
412			return $imgUrl;
413		}
414
415		/**
416		 *
417		 * Create a bing maps static image url w/ the poi.
418		 * @param array $gmap
419		 * @param array $overlay
420		 */
421		private function _getBing($gmap, $overlay){
422			switch ($gmap['baselyr']){
423				case 've hybrid':
424					$maptype='AerialWithLabels';
425					break;
426				case 've sat':
427					$maptype='Aerial';
428					break;
429				case 've normal':
430				case 've':
431				default:
432					$maptype='Road';
433					break;
434			}
435
436			// TODO since bing does not provide declutter or autozoom/fit we need to determine the bbox based on the poi and lat/lon ourselves
437			//http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/51.56573,5.45690/12?mapSize=400,400&key=Agm4PJzDOGz4Oy9CYKPlV-UtgmsfL2-zeSyfYjRhf57OQB_oj87j5pncKZSay5qY
438			$imgUrl = "http://dev.virtualearth.net/REST/v1/Imagery/Map/".$maptype."/".$gmap['lat'].",".$gmap['lon']."/".$gmap['zoom'];
439			$imgUrl .= "?ms=".str_replace("px", "",$gmap['width']).",".str_replace("px", "",$gmap['height']);
440			// create a bing api key at https://www.bingmapsportal.com/application
441			$imgUrl .= "&key=".$this->getConf('bingAPIKey');
442			if (!empty ($overlay)) {
443				$rowId=0;
444				foreach ($overlay as $data) {
445					list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
446					// TODO icon style lookup, see: http://msdn.microsoft.com/en-us/library/ff701719.aspx for iconStyle
447					// NOTE: the max number of pushpins is 18!
448					$iconStyle=32;
449					$rowId++;
450					$imgUrl .= "&pp=$lat,$lon;$iconStyle;$rowId";
451				}
452			}
453			dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getBing: bing image url is:');
454			return $imgUrl;
455		}
456
457		/**
458		 *
459		 * Create a static OSM map image url w/ the poi from http://staticmap.openstreetmap.de (staticMapLite)
460		 * @param array $gmap
461		 * @param array $overlay
462		 */
463		private function _getStaticOSM($gmap, $overlay){
464			//http://staticmap.openstreetmap.de/staticmap.php?center=47.000622235634,10.117187497601&zoom=5&size=500x350
465			// &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
466			$imgUrl = "http://staticmap.openstreetmap.de/staticmap.php";
467			$imgUrl .= "?center=".$gmap['lat'].",".$gmap['lon'];
468			$imgUrl .= "&size=".str_replace("px", "",$gmap['width'])."x".str_replace("px", "",$gmap['height']);
469			if ($gmap['zoom']>16) {
470				$imgUrl .= "&zoom=16";
471			} else			{
472				$imgUrl .= "&zoom=".$gmap['zoom'];
473			}
474
475			if (!empty ($overlay)) {
476				$rowId=0;
477				$imgUrl .= "&markers=";
478				foreach ($overlay as $data) {
479					list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
480					$rowId++;
481					$iconStyle = "lightblue$rowId";
482					$imgUrl .= "$lat,$lon,$iconStyle%7c";
483				}
484				$imgUrl = substr($imgUrl,0,-3);
485			}
486
487			dbglog($imgUrl,'syntax_plugin_openlayersmap_olmap::_getStaticOSM: bing image url is:');
488			return $imgUrl;
489
490		}
491}