WfsDataServer.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. <?php
  2. Lib::loadClass('Api_WfsServerBase');
  3. Lib::loadClass('Api_WfsException');
  4. Lib::loadClass('Api_WfsGeomTypeConverter');
  5. Lib::loadClass('Api_WfsNs');
  6. class Api_WfsDataServer extends Api_WfsServerBase {
  7. public function parseXMLRequest() {
  8. $data = array();
  9. $reqContent = Request::getRequestBody();
  10. if (empty($reqContent)) {
  11. throw new Exception("Empty request");
  12. }
  13. $parserXml = xml_parser_create();
  14. xml_parser_set_option($parserXml, XML_OPTION_CASE_FOLDING, 0);
  15. xml_parser_set_option($parserXml, XML_OPTION_SKIP_WHITE, 1);
  16. if (0 == xml_parse_into_struct($parserXml, $reqContent, $tags)) {
  17. throw new Exception("Error parsing xml");
  18. }
  19. xml_parser_free($parserXml);
  20. if (empty($tags)) {
  21. throw new Exception("Empty structure from request");
  22. }
  23. $rootTagName = V::get('tag', '', $tags[0]);
  24. if ('Transaction' == $rootTagName) {
  25. return $this->_parseTransactionXmlStruct($reqContent, $tags);
  26. }
  27. throw new Api_WfsException("TODO ... L." . __LINE__, 501);
  28. $xml = new SimpleXMLElement($reqContent);
  29. $namespaces = $xml->getNameSpaces(true);
  30. if ('Transaction' == $xml->getName()) {
  31. $this->_parseTransactionXml($xml);
  32. }
  33. else {
  34. throw new Api_WfsException("Not Implemented " . htmlspecialchars($xml->getName()), 501);
  35. }
  36. }
  37. public function getFeatureAction() {
  38. $type = V::get('TYPENAME', '', $_REQUEST);
  39. $typeEx = explode(':', $type);
  40. $maxFeatures = '10000';// TODO: Set Deafult Limit
  41. $maxFeatures = V::get('MAXFEATURES', $maxFeatures, $_REQUEST, 'int');
  42. $maxFeatures = V::get('maxFeatures', $maxFeatures, $_REQUEST, 'int');
  43. $maxFeatures = V::get('count', $maxFeatures, $_REQUEST, 'int');
  44. $startIndex = V::get('startIndex', 0, $_REQUEST, 'int');// sql offset
  45. $ogcFilter = V::get('Filter', '', $_REQUEST);
  46. $sortBy = V::get('sortBy', '', $_REQUEST);
  47. $propertyName = V::get('propertyName', '', $_REQUEST);
  48. $propertyName = trim($propertyName);
  49. $srsname = V::get('SRSNAME', '', $_REQUEST);// eg. EPSG:4326
  50. if (count($typeEx) != 2) throw new HttpException("Wrong param TYPENAME", 400);
  51. if (empty($ogcFilter)) {// read ogc:Filter from POST body if not defined in GET
  52. $reqBody = Request::getRequestBody();
  53. if (!empty($reqBody)) {
  54. $ogcFilter = $this->convertOgcFilterFromRequestBody($reqBody);
  55. if (empty($ogcFilter)) throw new Api_WfsException("Error Processing ogc:Filter", 501);
  56. }
  57. }
  58. if ('hits' == V::get('resultType', '', $_REQUEST)) {// resultType=hits
  59. return $this->getTotalFeatures($typeEx[0], $typeEx[1], $maxFeatures, $srsname, $ogcFilter, $sortBy, $startIndex, $propertyName, $simple = true);
  60. } else {
  61. return $this->getFeatures($typeEx[0], $typeEx[1], $maxFeatures, $srsname, $ogcFilter, $sortBy, $startIndex, $propertyName, $simple = true);
  62. }
  63. }
  64. public function getFeatureAdvancedAction() {
  65. $type = V::get('TYPENAME', '', $_REQUEST);
  66. $typeEx = explode(':', $type);
  67. $maxFeatures = '10000';// TODO: Set Deafult Limit
  68. $maxFeatures = V::get('MAXFEATURES', $maxFeatures, $_REQUEST, 'int');
  69. $maxFeatures = V::get('maxFeatures', $maxFeatures, $_REQUEST, 'int');
  70. $maxFeatures = V::get('count', $maxFeatures, $_REQUEST, 'int');
  71. $startIndex = V::get('startIndex', 0, $_REQUEST, 'int');// sql offset
  72. $ogcFilter = V::get('Filter', '', $_REQUEST);
  73. $sortBy = V::get('sortBy', '', $_REQUEST);
  74. $propertyName = V::get('propertyName', '', $_REQUEST);
  75. $propertyName = trim($propertyName);
  76. $srsname = V::get('SRSNAME', '', $_REQUEST);// eg. EPSG:4326
  77. if (count($typeEx) != 2) throw new HttpException("Wrong param TYPENAME", 400);
  78. if (empty($ogcFilter)) {// read ogc:Filter from POST body if not defined in GET
  79. $reqBody = Request::getRequestBody();
  80. if (!empty($reqBody)) {
  81. $ogcFilter = $this->convertOgcFilterFromRequestBody($reqBody);
  82. }
  83. }
  84. if ('hits' == V::get('resultType', '', $_REQUEST)) {// resultType=hits
  85. return $this->getTotalFeatures($typeEx[0], $typeEx[1], $maxFeatures, $srsname, $ogcFilter, $sortBy, $startIndex, $propertyName, $simple = false);
  86. } else {
  87. return $this->getFeatures($typeEx[0], $typeEx[1], $maxFeatures, $srsname, $ogcFilter, $sortBy, $startIndex, $propertyName, $simple = false);
  88. }
  89. }
  90. public function testOgcFilterAction() {
  91. $type = V::get('TYPENAME', '', $_REQUEST);
  92. $typeEx = explode(':', $type);
  93. $maxFeatures = V::get('MAXFEATURES', '10000', $_REQUEST, 'int');// TODO: Set Deafult Limit
  94. $ogcFilter = V::get('Filter', '', $_REQUEST);
  95. $srsname = V::get('SRSNAME', '', $_REQUEST);// eg. EPSG:4326
  96. if (count($typeEx) == 2) {
  97. Lib::loadClass('ParseOgcFilter');
  98. $parser = new ParseOgcFilter();
  99. $parser->loadOgcFilter($ogcFilter);
  100. $queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
  101. echo $queryWhereBuilder->getQueryWhere('t');
  102. } else {
  103. throw new HttpException("Wrong param TYPENAME", 400);
  104. }
  105. }
  106. public function getTotalFeatures($nsPrefix, $type, $maxFeatures, $srsname, $ogcFilter = '', $sortBy = '', $startIndex = 0, $propertyName = '', $simple = true) {
  107. $DBG = (V::get('DBG_GEO', '', $_GET) > 0);// TODO: Profiler
  108. $typeName = "{$nsPrefix}:{$type}";
  109. if($DBG){echo "typeName($typeName})\n";}
  110. $acl = $this->getAclFromTypeName($typeName);
  111. $fldList = $this->_getFieldListFromAcl($acl);
  112. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  113. $rootWfsNs = 'p5';
  114. $rootWfsNsUri = "{$baseNsUri}";
  115. //$wfsNs = 'p5_default_db_' . $type;//$nsPrefix;
  116. $wfsNs = $nsPrefix;//'p5_default_db';
  117. $wfsNsUri = "{$baseNsUri}/" . substr($nsPrefix, 3);
  118. $featureTypeUri = $this->getBaseUri() . "?SERVICE=WFS&VERSION=1.0.0&TYPENAME={$typeName}&REQUEST=DescribeFeatureType";
  119. // get BBox from geom_field (only one geom fld is allowed)
  120. $geomFld = null;
  121. {
  122. foreach ($fldList as $idZasob => $fldName) {
  123. if ($acl->isGeomField($fldName)) {
  124. $geomFld = $fldName;
  125. }
  126. }
  127. }
  128. if($DBG){echo "ogcFilter(" . strlen($ogcFilter) . "): {$ogcFilter}\n";}
  129. $searchParams = array();
  130. $searchParams['limit'] = $maxFeatures;
  131. $searchParams['limitstart'] = $startIndex;
  132. if (!empty($sortBy)) {
  133. $searchParams['sortBy'] = $sortBy;
  134. } else {
  135. $searchParams['order_by'] = $acl->getPrimaryKeyField();
  136. $searchParams['order_dir'] = 'DESC';
  137. }
  138. if (strlen($ogcFilter) > 0) $searchParams['ogc:Filter'] = $ogcFilter;
  139. if (strlen($propertyName) > 0) {
  140. $propertyNamesEx = explode(',', $propertyName);
  141. $onlyCols = array();
  142. foreach ($propertyNamesEx as $colName) {
  143. $colName = trim($colName);
  144. $onlyCols[] = $colName;
  145. }
  146. if (!empty($onlyCols)) $searchParams['cols'] = $onlyCols;
  147. }
  148. {// BBOX
  149. // 54.26931096743426,18.48242909824306,54.26738118403914,18.478738378639246
  150. $bbox = V::get('BBOX', '', $_GET);
  151. if (!empty($bbox)) {
  152. if (preg_match("/^\d+(.\d+)?,\d+(.\d+)?,\d+(.\d+)?,\d+(.\d+)?$/", $bbox, $matches)) {
  153. $searchParams['f_the_geom'] = "BBOX:{$bbox}";
  154. } else {
  155. // throw new Exception("Error Processing Request", 1);// ?
  156. }
  157. }
  158. }
  159. if($DBG){echo 'getItems() searchParams:';print_r($searchParams);echo "\n";}
  160. $totalItems = $acl->getTotal($searchParams);
  161. if($DBG){echo 'totalItems:';print_r($totalItems);echo "\n";}
  162. $xmlWriter = new XMLWriter();
  163. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  164. $xmlWriter->openUri('php://output');
  165. $xmlWriter->setIndent(true);
  166. $xmlWriter->startDocument('1.0','UTF-8');
  167. $xmlWriter->startElement('wfs:FeatureCollection');
  168. $xmlWriter->writeAttribute('xmlns:wfs', 'http://www.opengis.net/wfs/2.0');
  169. $xmlWriter->writeAttribute('xmlns', 'http://www.opengis.net/wfs/2.0');
  170. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  171. $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  172. // $xmlWriter->writeAttribute('xsi:schemaLocation', "{$wfsNsUri} {$featureTypeUri}");
  173. $xmlWriter->writeAttribute('numberMatched', $totalItems);
  174. $xmlWriter->writeAttribute('numberReturned', 0);
  175. // $xmlWriter->writeAttribute('timeStamp', "TODO: timestamp like '2011-12-09T11:30:16'");
  176. $xmlWriter->endElement();// wfs:FeatureCollection
  177. $xmlWriter->endDocument();
  178. exit;
  179. }
  180. public function getFeatures($nsPrefix, $type, $maxFeatures, $srsname, $ogcFilter = '', $sortBy = '', $startIndex = 0, $propertyName = '', $simple = true) {
  181. $DBG = (V::get('DBG_GEO', '', $_GET) > 0);// TODO: Profiler
  182. $DBG_DS = V::get('DBG_DS', 0, $_GET, 'int');
  183. $typeName = "{$nsPrefix}:{$type}";
  184. if($DBG){echo "typeName($typeName})\n";}
  185. $acl = $this->getAclFromTypeName($typeName);
  186. $fldList = $this->_getFieldListFromAcl($acl);
  187. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  188. $rootWfsNs = 'p5';
  189. $rootWfsNsUri = "{$baseNsUri}";
  190. //$wfsNs = 'p5_default_db_' . $type;//$nsPrefix;
  191. $wfsNs = $nsPrefix;//'p5_default_db';
  192. $wfsNsUri = "{$baseNsUri}/" . substr($nsPrefix, 3);
  193. $featureTypeUri = $this->getBaseUri() . "?SERVICE=WFS&VERSION=1.0.0&TYPENAME={$typeName}&REQUEST=DescribeFeatureType";
  194. // get BBox from geom_field (only one geom fld is allowed)
  195. $geomFld = null;
  196. {
  197. foreach ($fldList as $idZasob => $fldName) {
  198. if ($acl->isGeomField($fldName)) {
  199. $geomFld = $fldName;
  200. }
  201. }
  202. }
  203. if($DBG){echo "ogcFilter(" . strlen($ogcFilter) . "): {$ogcFilter}\n";}
  204. $searchParams = array();
  205. $searchParams['limit'] = $maxFeatures;
  206. $searchParams['limitstart'] = $startIndex;
  207. if (!empty($sortBy)) {
  208. $searchParams['sortBy'] = $sortBy;
  209. } else {
  210. $searchParams['order_by'] = $acl->getPrimaryKeyField();
  211. $searchParams['order_dir'] = 'DESC';
  212. }
  213. if (strlen($ogcFilter) > 0) $searchParams['ogc:Filter'] = $ogcFilter;
  214. if (strlen($propertyName) > 0) {
  215. $propertyNamesEx = explode(',', $propertyName);
  216. $onlyCols = array();
  217. foreach ($propertyNamesEx as $colName) {
  218. $colName = trim($colName);
  219. $onlyCols[] = $colName;
  220. }
  221. if (!empty($onlyCols)) $searchParams['cols'] = $onlyCols;
  222. }
  223. {// BBOX
  224. // 54.26931096743426,18.48242909824306,54.26738118403914,18.478738378639246
  225. $bbox = V::get('BBOX', '', $_GET);
  226. if (!empty($bbox)) {
  227. if (preg_match("/^\d+(.\d+)?,\d+(.\d+)?,\d+(.\d+)?,\d+(.\d+)?$/", $bbox, $matches)) {
  228. $searchParams['f_the_geom'] = "BBOX:{$bbox}";
  229. } else {
  230. // throw new Exception("Error Processing Request", 1);// ?
  231. }
  232. }
  233. }
  234. if($DBG){echo 'getItems:';print_r($searchParams);echo "\n";}
  235. $items = $acl->getItems($searchParams);
  236. $dom = new DOMDocument('1.0', 'utf-8');
  237. $dom->formatOutput = true;
  238. $dom->preserveWhiteSpace = false;
  239. $rootNode = $dom->createElementNS('http://www.opengis.net/wfs', 'wfs:FeatureCollection');
  240. $dom->appendChild($rootNode);
  241. $rootNode->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', 'http://www.opengis.net/wfs');
  242. $rootNode->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:wfs', 'http://www.opengis.net/wfs');
  243. $rootNode->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:gml', 'http://www.opengis.net/gml');
  244. $rootNode->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  245. $rootNode->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:' . $wfsNs, $wfsNsUri);
  246. if (!$simple) $rootNode->setAttributeNS('http://www.w3.org/2000/xmlns/', "xmlns:{$rootWfsNs}", $rootWfsNsUri);
  247. //$rootNode->setAttribute('xsi:schemaLocation', 'http://www.opengis.net/wfs');
  248. $rootNode->setAttribute('xsi:schemaLocation', "{$wfsNsUri} {$featureTypeUri}");
  249. if($DBG){echo '(geomFld: '.$geomFld.'):';print_r($acl->getFieldType($geomFld));echo "\n";}
  250. if (empty($items)) {
  251. $pKeyField = $acl->getPrimaryKeyField();
  252. $fakeItem = new stdClass();
  253. $fakeItem->{$pKeyField} = 0;
  254. $items[0] = $fakeItem;
  255. }
  256. $sourceName = $acl->getSourceName();
  257. $tblName = $acl->getName();
  258. foreach ($items as $itemKey => $item) {
  259. if (!is_array($item)) $item = (array)$item;
  260. if($DBG && !empty($geomFld)){echo 'item['.$itemKey.'] ('.$geomFld.')isEmpty('.empty($item[$geomFld]).'):';print_r($item[$geomFld]);echo "\n";}
  261. if($DBG_DS){echo ">>> loop({$itemKey}) item: ";print_r($item);echo "\n";}
  262. $featureMemberNode = $dom->createElementNS('http://www.opengis.net/gml', 'gml:featureMember');
  263. $rootNode->appendChild($featureMemberNode);
  264. $featureNode = $dom->createElementNS($wfsNsUri, "{$wfsNs}:{$type}");
  265. $featureMemberNode->appendChild($featureNode);
  266. $featureNode->setAttribute('fid', "{$type}.{$itemKey}");
  267. if (!$simple) $featureNode->setAttributeNS($rootWfsNsUri, "{$rootWfsNs}:web_link", Request::getPathUri() . "index.php?_route=ViewTableAjax&typeName=p5_{$sourceName}:{$tblName}#EDIT/{$itemKey}");
  268. foreach ($fldList as $idZasob => $fldName) {
  269. $featureFldNode = $dom->createElementNS($wfsNsUri, "{$wfsNs}:{$fldName}");
  270. if($DBG_DS){echo">>> acl->validateFieldAction('{$fldName}', 'R', \$item) ...\n";}
  271. if ($acl->validateFieldAction($fldName, 'R', (object)$item)) {
  272. if ($geomFld != null && $geomFld == $fldName) {
  273. $geomNode = $this->_typeConverter->createGmlFromWkt($item[$fldName], $dom);
  274. if (!$geomNode) continue;
  275. $featureFldNode->appendChild($geomNode);
  276. } else if (is_array($item[$fldName])) {// TODO: by struct - REF field
  277. if($DBG_DS){echo">>> TODO({$fldName}) REF item[{$itemKey}][{$fldName}]: ";print_r($item[$fldName]);echo "\n";}
  278. if (1 == count($item[$fldName])) {
  279. $xlink = $item[$fldName][0]['xlink'];
  280. $xlinkParts = explode(':', $xlink);
  281. if (2 != count($xlinkParts)) throw new Exception("Error Processing Reques - wrong xlink format for ".$acl->getName().".{$itemKey}/{$fldName}");
  282. $xlinkParts[0] = Api_WfsNs::getNsUri($xlinkParts[0]);
  283. $xlink = implode('#', $xlinkParts);
  284. $featureFldNode->setAttribute('xlink:href', $xlink);
  285. } else {
  286. throw new Exception("Error Processing Request - too many refs for ".$acl->getName().".{$itemKey}/{$fldName}");
  287. }
  288. // foreach ($item[$fldName] as $ref) {
  289. // $refNode = $dom->createElementNS($wfsNsUri, "{$wfsNs}:{$fldName}");
  290. // $featureFldNode->appendChild($refNode);
  291. // }
  292. } else {
  293. $featureFldNode->nodeValue = str_replace('&', '&amp;', $item[$fldName]);
  294. if (empty($featureFldNode->nodeValue) && '0' !== $featureFldNode->nodeValue) {
  295. continue;
  296. }
  297. }
  298. }
  299. if (!$simple) {
  300. if (!$acl->validateFieldAction($fldName, 'R', (object)$item)) {
  301. $featureFldNode->setAttributeNS($rootWfsNsUri, "{$rootWfsNs}:allow_read", "false");
  302. }
  303. if ($acl->validateFieldAction($fldName, 'W', (object)$item)) {
  304. $featureFldNode->setAttributeNS($rootWfsNsUri, "{$rootWfsNs}:allow_write", "true");
  305. }
  306. }
  307. $featureNode->appendChild($featureFldNode);
  308. }
  309. }
  310. return $dom->saveXml();
  311. }
  312. public function describeFeatureTypeAction() {
  313. $type = V::get('TYPENAME', '', $_REQUEST);
  314. if (empty($type)) {
  315. $reqContent = Request::getRequestBody();
  316. if (!empty($reqContent)) {
  317. return $this->_parseDescribeFeatureTypeRequest($reqContent);
  318. } else {
  319. return $this->_getDescribeFeatureAllTypes();
  320. }
  321. //throw new HttpException("Wrong param TYPENAME", 400);
  322. }
  323. $typeEx = explode(':', $type);
  324. if (count($typeEx) != 2) throw new HttpException("Wrong param TYPENAME", 400);
  325. return $this->_getDescribeFeatureType($typeEx[0], $typeEx[1]);
  326. }
  327. public function describeFeatureTypeAdvancedAction() {
  328. $type = V::get('TYPENAME', '', $_REQUEST);
  329. if (empty($type)) {
  330. $reqContent = Request::getRequestBody();
  331. if (!empty($reqContent)) {
  332. return $this->_parseDescribeFeatureTypeRequest($reqContent, $simple = false);
  333. } else {
  334. return $this->_getDescribeFeatureAllTypes($simple = false);
  335. }
  336. //throw new HttpException("Wrong param TYPENAME", 400);
  337. }
  338. $typeEx = explode(':', $type);
  339. if (count($typeEx) != 2) throw new HttpException("Wrong param TYPENAME", 400);
  340. return $this->_getDescribeFeatureType($typeEx[0], $typeEx[1], $simple = false);
  341. }
  342. public function getCapabilitiesAction() {
  343. $wfsServerUrl = $this->getBaseUri();
  344. $serviceTitle = "Web Feature Service";
  345. $serviceDescription = "This is the reference implementation of WFS 1.0.0 and WFS 1.1.0, supports all WFS operations including Transaction.";
  346. //header('Content-type: application/xml; charset="utf-8"');
  347. header('Content-type: application/xml');
  348. $this->_getCapabilities($wfsServerUrl, $serviceTitle, $serviceDescription);
  349. }
  350. }