WfsDataServer.php 16 KB

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