/
xmlpoiconnector.class.php
executable file
·595 lines (552 loc) · 18.3 KB
/
xmlpoiconnector.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
<?php
/*
* PorPOISe
* Copyright 2009 SURFnet BV
* Released under a permissive license (see LICENSE)
*
* Acknowledgments:
* Guillaume Danielou of kew.org for the XSL transformation
*/
/**
* POI connector from XML files
*
* @package PorPOISe
*/
/**
* POI connector from XML files
*
* @package PorPOISe
*/
class XMLPOIConnector extends POIConnector {
const EMPTY_DOCUMENT = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<layer><pois/></layer>";
/** @var string */
protected $source;
/** @var string */
protected $styleSheetPath = "";
/** @var SimpleXMLElement Loaded XML for the layer; do not reference directly but use getSimpleXMLFromSource() */
protected $simpleXMLElement;
/**
* Constructor
*
* The field separator can be configured by modifying the public
* member $separator.
*
* @param string $source Filename of the POI file
*/
public function __construct($source) {
$this->source = $source;
}
/**
* Set the path of an XSL style sheet to transform the input XML
*
* @param string $styleSheetPath
* @return void
*/
public function setStyleSheet($styleSheetPath) {
$this->styleSheetPath = $styleSheetPath;
}
protected function getSimpleXMLFromSource() {
if (empty($this->simpleXML)) {
if(!empty($this->styleSheetPath)) {
$this->simpleXML = new SimpleXMLElement($this->transformXML(), 0, FALSE);
} else {
$this->simpleXML = new SimpleXMLElement($this->source, 0, TRUE);
}
if (empty($this->simpleXML)) {
throw new Exception("Failed to load data");
}
}
return $this->simpleXML;
}
/**
* Return a Layar response
*
* @param Filter $filter
*
* @return LayarResponse
*/
public function getLayarResponse(Filter $filter = NULL) {
$libxmlErrorHandlingState = libxml_use_internal_errors(TRUE);
$simpleXML = $this->getSimpleXMLFromSource();
$result = new LayarResponse();
$layerNodes = $simpleXML->xpath("/layer");
if (count($layerNodes) > 0) { // when 0, this is an old style PorPOISe XML file
$layerNode = $layerNodes[0]; // always pick first <layer> element, multiples are ignored
foreach($layerNode->children() as $childNode) {
$name = $childNode->getName();
switch($name) {
case "refreshInterval":
case "refreshDistance":
$result->$name = (int)$childNode;
break;
case "fullRefresh":
$result->$name = (bool)((string)$childNode);
break;
case "showMessage":
case "biwStyle":
$result->$name = (string)$childNode;
break;
case "action":
$result->actions[] = new Action($childNode);
break;
case "animation":
if (in_array((string)$childNode, array("drop", "spin", "grow"))) {
$result->animations = (string)$childNode;
} else {
$events = (string)$childNode["events"];
if (!empty($events)) {
foreach (array("onCreate", "onUpdate", "onDelete", "onFocus", "onClick") as $event) {
if (strpos($events, $event) !== FALSE) {
$result->animations[$event][] = new Animation($childNode);
}
}
}
}
break;
default:
// not relevant
break;
}
}
}
$result->hotspots = $this->getPOIs($filter);
libxml_use_internal_errors($libxmlErrorHandlingState);
return $result;
}
/**
* Provides an XPath query for finding POIs in the source file.
*
* For relative queries, the context node is the root element.
* This method can be overridden to use a different query.
*
* @param Filter $filter
*
* @return string
*/
public function buildQuery(Filter $filter = NULL) {
return "//pois/poi";
}
/**
* Get POIs
*
* @param Filter $filter
*
* @return POI[]
*
* @throws Exception
*/
public function getPOIs(Filter $filter = NULL) {
$libxmlErrorHandlingState = libxml_use_internal_errors(TRUE);
$lat = $filter->lat;
$lon = $filter->lon;
$radius = $filter->radius;
$accuracy = $filter->accuracy;
// calculate here to prevent recalculation on each foreach loop later
$dlat = GeoUtil::getLatitudinalDistance(($radius + $accuracy) * 1.25, $lat);
$dlon = GeoUtil::getLongitudinalDistance(($radius + $accuracy) * 1.25, $lat);
$simpleXML = $this->getSimpleXMLFromSource();
$result = array();
$requestedPOI = NULL;
$xpathQuery = $this->buildQuery($filter);
foreach ($simpleXML->xpath($xpathQuery) as $poiData) {
$poi = new POI();
foreach ($poiData->children() as $child) {
$nodeName = $child->getName();
if ($nodeName == "action") {
$poi->actions[] = new POIAction($child);
} else if ($nodeName == "anchor") {
$poi->anchor = new POIAnchor($child);
} else if ($nodeName == "icon") {
$poi->icon = new POIIcon($child);
} else if ($nodeName == "object") {
$poi->object = new POIObject($child);
} else if ($nodeName == "text") {
$poi->text = new POIText($child);
} else if ($nodeName == "transform") {
$poi->transform = new POITransform($child);
} else if ($nodeName == "animation") {
if (in_array((string)$child, array("drop", "spin", "grow"))) {
$poi->animations = (string)$child;
} else {
$events = (string)$child["events"];
if (!empty($events)) {
foreach (array("onCreate", "onUpdate", "onDelete", "onFocus", "onClick") as $event) {
if (strpos($events, $event) !== FALSE) {
$poi->animations[$event][] = new Animation($child);
}
}
}
}
} else {
switch($nodeName) {
case "dimension":
case "type":
case "relativeAlt":
$value = (int)$child;
break;
case "showSmallBiw":
case "showBiwOnClick":
case "doNotIndex":
$value = (bool)(string)$child;
break;
default:
$value = (string)$child;
break;
}
$poi->$nodeName = $value;
}
}
if (empty($filter)) {
$result[] = $poi;
} else {
if (!empty($filter->requestedPoiId) && $filter->requestedPoiId == $poi->id) {
// always return the requested POI at the top of the list to
// prevent cutoff by the 50 POI response limit
$poi->distance = GeoUtil::getGreatCircleDistance(deg2rad($lat), deg2rad($lon), deg2rad($poi->anchor->geolocation['lat']), deg2rad($poi->anchor->geolocation['lon']));
$requestedPOI = $poi;
} else if ($this->passesFilter($poi, $filter)) {
if (empty($radius)) {
$poi->distance = GeoUtil::getGreatCircleDistance(deg2rad($lat), deg2rad($lon), deg2rad($poi->anchor->geolocation['lat']), deg2rad($poi->anchor->geolocation['lon']));
$result[] = $poi;
} else {
// verify if POI falls in bounding box (with 25% margin)
/** @todo handle wraparound */
if (isset($poi->anchor->referenceImage)) {
$result[] = $poi;
} elseif ((float)$poi->anchor->geolocation['lat'] >= $lat - $dlat && $poi->anchor->geolocation['lat'] <= $lat + $dlat && $poi->anchor->geolocation['lon'] >= $lon - $dlon && $poi->anchor->geolocation['lon'] <= $lon + $dlon) {
$poi->distance = GeoUtil::getGreatCircleDistance(deg2rad($lat), deg2rad($lon), deg2rad($poi->anchor->geolocation['lat']), deg2rad($poi->anchor->geolocation['lon']));
// filter passed, see if radius allows for inclusion
if ($poi->distance < $radius + $accuracy) {
$result[] = $poi;
}
}
}
}
}
}
libxml_use_internal_errors($libxmlErrorHandlingState);
if (!empty($filter)) {
// sort if filter is set
$result = objectSort("distance", $result);
}
if (!empty($requestedPOI)) {
// always make sure that the requested POI is the first to be returned
array_unshift($result, $requestedPOI);
}
return $result;
}
/**
* Store POIs
*
* Builds up an XML and writes it to the source file with which this
* XMLPOIConnector was created. Note that there is no way to do
* "reverse XSL" so any stylesheet is ignored and native PorPOISe XML
* is written to the source file. If this file is not writable, this
* method will return FALSE.
*
* @param POI[] $pois
* @param string $mode "update" or "replace"
* @param bool $asString Return XML as string instead of writing it to file
* @return mixed FALSE on failure, TRUE or a string on success
*/
public function storePOIs(array $pois, $mode = "update", $asString = FALSE) {
$libxmlErrorHandlingState = libxml_use_internal_errors(TRUE);
// keep track of the highest id
$maxID = 0;
// initialize result XML
if ($mode == "update") {
$simpleXML = $this->getSimpleXMLFromSource();
// look for highest id in current set
$idNodes = $simpleXML->xpath("//poi/id");
foreach ($idNodes as $idNode) {
$id = (int)$idNode;
if ($id > $maxID) {
$maxID = $id;
}
}
} else if ($mode == "replace") {
$simpleXML = new SimpleXMLElement(self::EMPTY_DOCUMENT);
// $maxID stays at 0 for now
}
$domXML = dom_import_simplexml($simpleXML);
$simpleXMLPOIsElements = $simpleXML->xpath("//pois");
if (count($simpleXMLPOIsElements) == 0) {
throw new Exception("XML file is corrupt");
}
$domXMLPOIsElement = dom_import_simplexml($simpleXMLPOIsElements[0]);
// look for high id in new set, see if it's higher than $maxID
foreach ($pois as $poi) {
//print_r($poi);
if ($poi->id > $maxID) {
$maxID = $poi->id;
}
}
// add POIs to result
foreach($pois as $poi) {
// see if POI is old or new
if (empty($poi->id)) {
// assign new id
$poi->id = $maxID + 1;
$maxID = $poi->id;
$oldSimpleXMLElements = array();
} else {
// look for existing POI with this id
$oldSimpleXMLElements = $simpleXML->xpath("//poi[id=" . $poi->id . "]");
}
// build element and convert to DOM
//$simpleXMLElement = self::arrayToSimpleXMLElement("poi", $poi->toArray());
$simpleXMLElement = self::poiToSimpleXMLElement($poi);
$domElement = $domXML->ownerDocument->importNode(dom_import_simplexml($simpleXMLElement), TRUE);
if (empty($oldSimpleXMLElements)) {
$domXMLPOIsElement->appendChild($domElement);
} else {
$domXMLPOIsElement->replaceChild($domElement, dom_import_simplexml($oldSimpleXMLElements[0]));
}
}
if ($asString) {
return $simpleXML->asXML();
} else {
// write new dataset to file
return file_put_contents($this->source, $simpleXML->asXML()) > 0 ;
}
libxml_use_internal_errors($libxmlErrorHandlingState);
}
/**
* Delete a POI
*
* @param string $poiID ID of the POI to delete
*
* @return void
*
* @throws Exception If the source is invalid or the POI could not be deleted
*/
public function deletePOI($poiID) {
$libxmlErrorHandlingState = libxml_use_internal_errors(TRUE);
$dom = new DOMDocument();
$dom->load($this->source);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query(sprintf("//poi[id='%s']", $poiID));
if ($nodes->length == 0) {
throw new Exception(sprintf("Could not delete POI: no POI found with ID %s", $poiID));
}
$nodesToRemove = array();
for ($i = 0; $i < $nodes->length; $i++) {
$nodesToRemove[] = $nodes->item($i);
}
foreach ($nodesToRemove as $node) {
$node->parentNode->removeChild($node);
}
$dom->save($this->source);
libxml_use_internal_errors($libxmlErrorHandlingState);
}
/**
* Save layer properties
*
* Note: uses LayarResponse as transport for properties but will not
* save the contents of $properties->hotspots. Use storePOIs for that
*
* @param LayarResponse $properties
* @param bool $asString
*
* @return mixed FALSE on failure, XML string or TRUE on success
*
* @throws Exception
*/
public function storeLayerProperties(LayarResponse $response, $asString = FALSE) {
$libxmlErrorHandlingState = libxml_use_internal_errors(TRUE);
$simpleXML = $this->getSimpleXMLFromSource();
if ($simpleXML->getName() == "pois") {
// older version XML file, time to fix that
$poisSimpleXML = $simpleXML;
$simpleXML = new SimpleXMLElement(self::EMPTY_DOCUMENT);
unset($simpleXML->pois);
$dom = dom_import_simplexml($simpleXML);
$poisDom = $dom->ownerDocument->importNode(dom_import_simplexml($poisSimpleXML), TRUE);
$dom->appendChild($poisDom);
}
unset($simpleXML->action);
unset($simpleXML->animation);
$relevantFields = array("refreshInterval", "refreshDistance", "fullRefresh", "showMessage");
foreach ($relevantFields as $fieldName) {
$simpleXML->$fieldName = $response->$fieldName;
}
foreach ($response->actions as $action) {
if (empty($simpleXML->action)) {
$i = 0;
} else {
$i = count($simpleXML->action);
}
$actionFields = array("label", "uri", "method", "contentType", "activityType", "params", "showActivity", "activityMessage");
foreach ($actionFields as $actionField) {
if ($actionField == "params") {
$simpleXML->action[$i]->$actionField = implode(",", $action->$actionField);
} else {
$simpleXML->action[$i]->$actionField = $action->$actionField;
}
}
}
foreach ($response->animations as $event => $animations) {
foreach ($animations as $animation) {
$animationElement = $simpleXML->addChild("animation");
$animationElement["events"] = $event;
foreach ($animation as $animationName => $animationValue) {
if ($animationName == "axis") {
$animationValue = $animation->axisString();
}
$animationElement->addChild($animationName, str_replace("&", "&", $animationValue));
}
}
}
libxml_use_internal_errors($libxmlErrorHandlingState);
if ($asString) {
return $simpleXML->asXML();
} else {
return file_put_contents($this->source, $simpleXML->asXML()) > 0;
}
}
/**
* Convert an array to a SimpleXMLElement
*
* Converts $array to a SimpleXMLElement by mapping they array's keys
* to node names and values to values. Traverses sub-arrays.
*
* @param string $rootName The name of the root element
* @param array $array The array to convert
* @return SimpleXMLElement
*/
public static function arrayToSimpleXMLElement($rootName, array $array) {
$result = new SimpleXMLElement(sprintf("<%s/>", $rootName));
self::addArrayToSimpleXMLElement($result, $array);
return $result;
}
/**
* Recursive helper method for arrayToSimpleXMLElement
*
* @param SimpleXMLElement $element
* @param array $array
*
* @return void
*/
public static function addArrayToSimpleXMLElement(SimpleXMLElement $element, array $array) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$child = $element->addChild($key);
self::addArrayToSimpleXMLElement($child, $value);
} else {
$element->addChild($key, $value);
}
}
}
/**
* Create a SimpleXMLElement representation of a POI
*
* @param POI $poi
* @return SimpleXMLElement
*/
public static function poiToSimpleXMLElement(POI $poi) {
$poiElement = new SimpleXMLElement("<" . "?xml version=\"1.0\" encoding=\"UTF-8\"?" . ">\n<poi/>");
foreach ($poi as $key => $value) {
if ($key == "actions") {
foreach ($value as $action) {
$actionElement = $poiElement->addChild("action");
foreach ($action as $actionName => $actionValue) {
if ($actionName == "params") {
$actionValue = implode(",", $actionValue);
}
$actionElement->addChild($actionName, str_replace("&", "&", $actionValue));
}
}
} else if ($key == "animations") {
foreach ($value as $event => $animations) {
foreach ($animations as $animation) {
$animationElement = $poiElement->addChild("animation");
$animationElement["events"] = $event;
foreach ($animation as $animationName => $animationValue) {
if ($animationName == "axis") {
$animationValue = $animation->axisString();
}
$animationElement->addChild($animationName, str_replace("&", "&", $animationValue));
}
}
}
} else if ($key == "transform") {
$transformElement = $poiElement->addChild("transform");
$rotateElement = $transformElement->addChild('rotate');
$rotateElement->addChild('rel', $poi->transform->rotate['rel']);
$axisElement = $rotateElement->addChild('axis');
foreach(array('x','y','z') as $elementName) {
$axisElement->addChild($elementName, $poi->transform->rotate['axis'][$elementName]);
}
$rotateElement->addChild('angle', $poi->transform->rotate['angle']);
$translateElement = $transformElement->addChild('translate');
foreach(array('x','y','z') as $elementName) {
$translateElement->addChild($elementName, $poi->transform->translate[$elementName]);
}
$transformElement->addChild('scale', $poi->transform->scale);
} else if ($key == "object") {
$objectElement = $poiElement->addChild("object");
foreach(array("url", "reducedURL", "contentType", "size") as $elementName) {
$objectElement->addChild($elementName, str_replace("&", "&", $poi->object->$elementName));
}
} else if ($key == 'anchor') {
$anchorElement = $poiElement->addChild("anchor");
$anchorElement->addChild('referenceImage', $poi->anchor->referenceImage);
$geolocationElement = $anchorElement->addChild('geolocation');
foreach (array('lat','lon','alt') as $elementName){
$geolocationElement->addChild($elementName, $poi->anchor->geolocation[$elementName]);
}
} else if ($key == 'text') {
$textElement = $poiElement->addChild("text");
foreach (array('description','footnote','title') as $elementName){
$textElement->addChild($elementName, $poi->text->$elementName);
}
} else if ($key == 'icon') {
$iconElement = $poiElement->addChild("icon");
foreach (array('url','type') as $elementName){
$iconElement->addChild($elementName, $poi->icon->$elementName);
}
} else {
$poiElement->addChild($key, str_replace("&", "&", $value));
}
}
return $poiElement;
}
/**
* Transform the input source using the set XSL stylesheet
*
* @return string The resulting XML
*/
public function transformXML() {
$xslProcessor = new XSLTProcessor();
$xsl = new DOMDocument();
if ($xsl->load($this->styleSheetPath) == FALSE) {
throw new Exception("transformXML - Failed to load stylesheet");
}
$xslProcessor->importStyleSheet($xsl);
$xml = new DOMDocument();
if ($xml->load($this->source) == FALSE) {
throw new Exception("transformXML - Failed to load xml");
}
return $xslProcessor->transformToXml($xml);
}
/**
* Set an option
*
* XMLPOIConnector supports one option, "stylesheet"
*
* @param string $optionName
* @param string $optionValue
*
* @return void
*/
public function setOption($optionName, $optionValue) {
switch ($optionName) {
case "stylesheet":
$this->setStyleSheet($optionValue);
break;
default:
parent::setOption($optionName, $optionValue);
break;
}
}
}