xref: /plugin/openlayersmap/syntax/olmap.php (revision 787a5195b91bca60f913c3d8074ae47274e4289c)
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';}
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
98			// use mapquest
99			// $imgUrl = "{{".$this->_getMapQuest($gmap,$overlay);
100			// use bing
101			// $imgUrl = "{{".$this->_getBing($gmap, $overlay);
102			// use google
103			$imgUrl = "{{".$this->_getGoogle($gmap, $overlay);
104
105			// dw specific params
106			$imgUrl .="&.png?".$gmap['width']."x".$gmap['height'];
107			//$imgUrl .= "&nolink";
108			$imgUrl .= "|".$gmap['summary']." }}";
109			// remove 'px'
110			$imgUrl = str_replace("px", "",$imgUrl);
111
112			$imgUrl=p_render("xhtml", p_get_instructions($imgUrl), $info);
113
114			$mapid = $gmap['id'];
115
116			// determine width and height (inline styles) for the map image
117			if ($gmap['width'] || $gmap['height']) {
118				$style = $gmap['width'] ? 'width: ' . $gmap['width'] . ";" : "";
119				$style .= $gmap['height'] ? 'height: ' . $gmap['height'] . ";" : "";
120				$style = "style='$style'";
121			} else {
122				$style = '';
123			}
124
125			// unset gmap values for width and height - they don't go into javascript
126			unset ($gmap['width'], $gmap['height']);
127
128			// create a javascript parameter string for the map
129			$param = '';
130			foreach ($gmap as $key => $val) {
131				$param .= is_numeric($val) ? "$key: $val, " : "$key: '" . hsc($val) . "', ";
132			}
133			if (!empty ($param)) {
134				$param = substr($param, 0, -2);
135			}
136			unset ($gmap['id']);
137
138			// create a javascript serialisation of the point data
139			$poi = '';
140			$poitable='';
141			$rowId=0;
142			if (!empty ($overlay)) {
143				foreach ($overlay as $data) {
144					list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
145					$rowId++;
146					$poi .= ", {lat: $lat, lon: $lon, txt: '$text', angle: $angle, opacity: $opacity, img: '$img', rowId: $rowId}";
147					$poitable .='<tr>'."\n".'<td class="rowId">'.$rowId.'</td>
148							<td class="icon"><img src="/lib/plugins/openlayersmap/icons/'.$img.'" alt="icon"></td>
149							<td class="lat" title="'.$this->getLang('olmapPOIlatTitle').'">'.$lat.'</td>
150							<td class="lon" title="'.$this->getLang('olmapPOIlonTitle').'">'.$lon.'</td>
151							<td class="txt">'.$text.'</td>'."\n".'</tr>';
152				}
153				$poi = substr($poi, 2);
154			}
155			$js .= "createMap({" . $param . " },[$poi]);";
156
157			return array($mapid,$style,$js,$mainLat,$mainLon,$poitable,$gmap['summary'],$imgUrl);
158		}
159
160		/**
161		 * render html tag/output. render the content.
162		 * @Override
163		 */
164		function render($mode, &$renderer, $data) {
165			static $initialised = false; // set to true after script initialisation
166			list ($mapid, $style, $param, $mainLat, $mainLon, $poitable, $poitabledesc, $staticImgUrl) = $data;
167
168			if ($mode == 'xhtml') {
169				$olscript = '';
170				$olEnable = false;
171				$gscript = '';
172				$gEnable = false;
173				$vscript = '';
174				$vEnable = false;
175				$yscript = '';
176				$yEnable = false;
177
178				$scriptEnable = '';
179
180				if (!$initialised) {
181					$initialised = true;
182					// render necessary script tags
183					$gscript = $this->getConf('googleScriptUrl');
184					$gscript = $gscript ? '<script type="text/javascript" src="' . $gscript . '"></script>' : "";
185
186					$vscript = $this->getConf('veScriptUrl');
187					$vscript = $vscript ? '<script type="text/javascript" src="' . $vscript . '"></script>' : "";
188
189					$yscript = $this->getConf('yahooScriptUrl');
190					$yscript = $yscript ? '<script type="text/javascript" src="' . $yscript . '"></script>' : "";
191
192					$olscript = $this->getConf('olScriptUrl');
193					$olscript = $olscript ? '<script type="text/javascript" src="' . $olscript . '"></script>' : "";
194					$olscript = str_replace('DOKU_PLUGIN', DOKU_PLUGIN, $olscript);
195
196					$scriptEnable = '<script type="text/javascript">' . "\n" . '<!--//--><![CDATA[//><!--' . "\n";
197					$scriptEnable .= $olscript ? 'olEnable = true;' : 'olEnable = false;';
198					$scriptEnable .= $yscript ? ' yEnable = true;' : ' yEnable = false;';
199					$scriptEnable .= $vscript ? ' veEnable = true;' : ' veEnable = false;';
200					$scriptEnable .= $gscript ? ' gEnable = true;' : ' gEnable = false;';
201					$scriptEnable .= "\n" . '//--><!]]>' . "\n" . '</script>';
202				}
203				$renderer->doc .= "
204				$olscript
205				$gscript
206				$vscript
207				$yscript
208				$scriptEnable
209			    <span id='$mapid-static' class='olStaticMap'>$staticImgUrl</span>
210				<div id='olContainer' class='olContainer'>
211				<div id='$mapid-olToolbar' class='olToolbar'></div>
212			        <div style='clear:both;'></div>
213			        <div id='$mapid' $style ></div>
214			        <div id='$mapid-olStatusBar' class='olStatusBarContainer'>
215			            <div id='$mapid-statusbar-scale' class='olStatusBar olStatusBarScale'>scale</div>
216			            <div id='$mapid-statusbar-link' class='olStatusBar olStatusBarPermalink'>
217			                <a href='' id='$mapid-statusbar-link-ref'>map link</a>
218			            </div>
219			            <div id='$mapid-statusbar-mouseposition' class='olStatusBar olStatusBarMouseposition'></div>
220			            <div id='$mapid-statusbar-projection' class='olStatusBar olStatusBarProjection'>proj</div>
221			            <div id='$mapid-statusbar-text' class='olStatusBar olStatusBarText'>txt</div>
222			        </div>
223			    </div>
224			    <p>&nbsp;</p>
225			    <script type='text/javascript'><!--//--><![CDATA[//><!--
226			    var $mapid = $param
227			   //--><!]]></script>";
228
229				// render a (hidden) table of the POI for the print and a11y presentation
230				$renderer->doc .= '
231 	<table class="olPOItable inline" id="'.$mapid.'-table" summary="'.$poitabledesc.'" title="'.$this->getLang('olmapPOItitle').'">
232		<caption class="olPOITblCaption">'.$this->getLang('olmapPOItitle').'</caption>
233		<thead class="olPOITblHeader">
234			<tr>
235				<th class="rowId" scope="col">id</th>
236				<th class="icon" scope="col">'.$this->getLang('olmapPOIicon').'</th>
237				<th class="lat" scope="col" title="'.$this->getLang('olmapPOIlatTitle').'">'.$this->getLang('olmapPOIlat').'</th>
238				<th class="lon" scope="col" title="'.$this->getLang('olmapPOIlonTitle').'">'.$this->getLang('olmapPOIlon').'</th>
239				<th class="txt" scope="col">'.$this->getLang('olmapPOItxt').'</th>
240			</tr>
241		</thead>
242		<tbody class="olPOITblBody">'.$poitable.'</tbody>
243		<tfoot class="olPOITblFooter"><tr><td colspan="5">'.$poitabledesc.'</td></tr></tfoot>
244	</table>';
245				//TODO no tfoot when $poitabledesc is empty
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 & 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
330			$imgUrl = "http://open.mapquestapi.com/staticmap/v3/getmap";
331			$imgUrl .= "?center=".$gmap['lat'].",".$gmap['lon'];
332			$imgUrl .= "&size=".str_replace("px", "",$gmap['width']).",".str_replace("px", "",$gmap['height']);
333			// max level for mapquest is 16
334			if ($gmap['zoom']>16) {
335				$imgUrl .= "&zoom=16";
336			} else			{
337				$imgUrl .= "&zoom=".$gmap['zoom'];
338			}
339			// TODO mapquest allows using one image url with a multiplier $NUMBER eg:
340			// $NUMBER = 2
341			// $imgUrl .= DOKU_URL."/".DOKU_PLUGIN."/".getPluginName()."/icons/".$img.",$NUMBER,C,".$lat1.",".$lon1.",0,0,0,0,C,".$lat2.",".$lon2.",0,0,0,0";
342			if (!empty ($overlay)) {
343				$imgUrl .= "&xis=";
344				foreach ($overlay as $data) {
345					list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
346					$imgUrl .= $sUrl."lib/plugins/openlayersmap/icons/".$img.",1,C,".$lat.",".$lon.",0,0,0,0,";
347				}
348				$imgUrl = substr($imgUrl,0,-1);
349			}
350			$imgUrl .= "&imageType=png&type=map";
351			dbglog($imgUrl,'olmap::_getMapQuest: MapQuest image url is:');
352			return $imgUrl;
353		}
354
355		private function _getGoogle($gmap, $overlay){
356			$sUrl=$this->getConf('iconUrlOverload');
357			if (!$sUrl){
358				$sUrl=DOKU_URL;
359			}
360
361			//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
362			$imgUrl = "http://maps.google.com/maps/api/staticmap";
363			$imgUrl .= "?center=".$gmap['lat'].",".$gmap['lon'];
364			$imgUrl .= "&size=".str_replace("px", "",$gmap['width'])."x".str_replace("px", "",$gmap['height']);
365			// don't need this $imgUrl .= "&key=".$this->getConf('googleAPIKey');
366			// max is 21 (== building scale), but that's overkill..
367			if ($gmap['zoom']>16) {
368				$imgUrl .= "&zoom=16";
369			} else			{
370				$imgUrl .= "&zoom=".$gmap['zoom'];
371			}
372
373			if (!empty ($overlay)) {
374				$rowId=0;
375				foreach ($overlay as $data) {
376					list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
377					//$imgUrl .= "&markers=icon:".DOKU_URL."lib/plugins/openlayersmap/icons/".$img."|".$lat.",".$lon."|label:".++$rowId;
378					$imgUrl .= "&markers=icon%3a".$sUrl."lib/plugins/openlayersmap/icons/".$img."%7c".$lat.",".$lon."%7clabel%3a".++$rowId;
379				}
380			}
381			$imgUrl .= "&format=png&maptype=roadmap&sensor=false";
382			global $conf;
383			$imgUrl .= "&language=".$conf['lang'];
384			dbglog($imgUrl,'olmap::_getGoogle: Google image url is:');
385			return $imgUrl;
386		}
387
388		/**
389		 *
390		 * Create a bing maps static image url w/ the poi.
391		 * @param array $gmap
392		 * @param array $overlay
393		 */
394		private function _getBing($gmap, $overlay){
395			// TODO since bing does not provide declutter or autozoom/fit we need to determine the bbox based on the poi and lat/lon ourselves
396			//http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/51.56573,5.45690/12?mapSize=400,400&key=Agm4PJzDOGz4Oy9CYKPlV-UtgmsfL2-zeSyfYjRhf57OQB_oj87j5pncKZSay5qY
397			$imgUrl = "http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/".$gmap['lat'].",".$gmap['lon']."/".$gmap['zoom'];
398			$imgUrl .= "?ms=".str_replace("px", "",$gmap['width']).",".str_replace("px", "",$gmap['height']);
399			// create a bing api key at https://www.bingmapsportal.com/application
400			$imgUrl .= "&key=".$this->getConf('bingAPIKey');
401			if (!empty ($overlay)) {
402				$rowId=0;
403				foreach ($overlay as $data) {
404					list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
405					// // TODO icon style lookup, see: http://msdn.microsoft.com/en-us/library/ff701719.aspx for iconStyle
406					$iconStyle=32;
407					$rowId++;
408					$imgUrl .= "&pp=$lat,$lon;$iconStyle;$rowId";
409				}
410			}
411			dbglog($imgUrl,'olmap::_getBing: bing image url is:');
412			return $imgUrl;
413		}
414}