WfsDataServer.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. <?php
  2. Lib::loadClass('Api_WfsServerBase');
  3. Lib::loadClass('Api_WfsException');
  4. Lib::loadClass('Api_WfsGeomTypeConverter');
  5. Lib::loadClass('Api_WfsNs');
  6. Lib::loadClass('DBG');
  7. class Api_WfsDataServer extends Api_WfsServerBase {
  8. public function run($request) {
  9. $document = '';
  10. if ('WFS' != V::get('SERVICE', '', $request->query) && ('WFS' != V::get('service', '', $request->query))) {
  11. throw new Api_WfsException("Only WFS Service is allowed");
  12. }
  13. $req = V::get('REQUEST', '', $request->query);
  14. if (!empty($req)) {
  15. $methodName = "{$req}Action";
  16. if (!method_exists($this, $methodName)) {
  17. throw new Api_WfsException("Not Implemented " . htmlspecialchars($req), 501);
  18. }
  19. $this->DBG("WfsServer->{$methodName}() ...", __LINE__);
  20. $document = $this->$methodName($urlQuery);
  21. }
  22. else {
  23. $this->DBG("WfsServer->parseXMLRequest() ...", __LINE__);
  24. $document = $this->parseXMLRequest();
  25. header('Content-type: application/xml');
  26. echo '<?xml version="1.0" encoding="UTF-8"?>';
  27. echo $document; exit;// TODO: return $document;
  28. }
  29. IF(V::get('DBG','',$_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$document (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($document);echo'</pre>';}
  30. if ('raw' == V::get('outputFormat', '', $request->query)) {
  31. header('Content-type: text/plain; charset=utf-8');
  32. echo $document;
  33. } else {
  34. header('Content-type: application/xml');
  35. echo $document;
  36. }
  37. }
  38. public function parseXMLRequest() {
  39. $data = array();
  40. $reqContent = Request::getRequestBody();
  41. if (empty($reqContent)) {
  42. throw new Exception("Empty request");
  43. }
  44. $parserXml = xml_parser_create();
  45. xml_parser_set_option($parserXml, XML_OPTION_CASE_FOLDING, 0);
  46. xml_parser_set_option($parserXml, XML_OPTION_SKIP_WHITE, 1);
  47. if (0 == xml_parse_into_struct($parserXml, $reqContent, $tags)) {
  48. throw new Exception("Error parsing xml");
  49. }
  50. xml_parser_free($parserXml);
  51. if (empty($tags)) {
  52. throw new Exception("Empty structure from request");
  53. }
  54. $rootTagName = V::get('tag', '', $tags[0]);
  55. if ('Transaction' == $rootTagName) return $this->_parseTransactionXmlStruct($reqContent, $tags);
  56. throw new Api_WfsException("Not implemented '{$rootTagName}' #L." . __LINE__, 501);
  57. }
  58. public function getFeatureAction() {
  59. $args = $this->parseGetFeatureArgsFromRequest();
  60. if ('hits' == $args['resultType']) {
  61. return $this->getTotalFeatures($args, $simple = true);
  62. } else {
  63. return $this->getFeatures($args, $simple = true);
  64. }
  65. }
  66. public function getFeatureAdvancedAction() {
  67. $args = $this->parseGetFeatureArgsFromRequest();
  68. if ('hits' == $args['resultType']) {
  69. return $this->getTotalFeatures($args, $simple = false);
  70. } else {
  71. return $this->getFeatures($args, $simple = false);
  72. }
  73. }
  74. public function testOgcFilterAction() {
  75. $type = V::get('TYPENAME', '', $_REQUEST);
  76. $typeEx = explode(':', $type);
  77. $maxFeatures = V::get('MAXFEATURES', '10000', $_REQUEST, 'int');// TODO: Set Deafult Limit
  78. $ogcFilter = V::get('Filter', '', $_REQUEST);
  79. $srsname = V::get('SRSNAME', '', $_REQUEST);// eg. EPSG:4326
  80. if (count($typeEx) == 2) {
  81. Lib::loadClass('ParseOgcFilter');
  82. $parser = new ParseOgcFilter();
  83. $parser->loadOgcFilter($ogcFilter);
  84. $queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
  85. echo $queryWhereBuilder->getQueryWhere('t');
  86. } else {
  87. throw new HttpException("Wrong param TYPENAME", 400);
  88. }
  89. }
  90. public function getTotalFeatures($args, $simple = true) {
  91. DBG::log("typeName({$args['xsd:type']})");
  92. $acl = $this->getAclFromTypeName($args['xsd:type']);
  93. DBG::log([ 'msg'=>"typeName({$args['xsd:type']}) - acl(".get_class($acl).")", '$acl'=>$acl ]);
  94. $fldList = $this->_getFieldListFromAcl($acl);
  95. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  96. $rootWfsNs = 'p5';
  97. $rootWfsNsUri = "{$baseNsUri}";
  98. $wfsNs = $args['typePrefix'];
  99. $wfsNsUri = "{$baseNsUri}/" . substr($args['typePrefix'], 3);
  100. $featureTypeUri = $this->getBaseUri() . "?SERVICE=WFS&VERSION=1.0.0&TYPENAME={$args['xsd:type']}&REQUEST=DescribeFeatureType";
  101. // get BBox from geom_field (only one geom fld is allowed)
  102. $geomFld = null;
  103. {
  104. foreach ($fldList as $fldName) {
  105. if ($acl->isGeomField($fldName)) {
  106. $geomFld = $fldName;
  107. }
  108. }
  109. }
  110. DBG::log("ogcFilter(" . strlen($args['ogc:filter']) . "): {$args['ogc:filter']}");
  111. $searchParams = array();
  112. $searchParams['limit'] = $args['limit'];
  113. $searchParams['limitstart'] = $args['offset'];
  114. if (!empty($args['sortBy'])) {
  115. $searchParams['sortBy'] = $args['sortBy'];
  116. } else {
  117. $searchParams['order_by'] = $acl->getPrimaryKeyField();
  118. $searchParams['order_dir'] = 'DESC';
  119. }
  120. if (strlen($args['ogc:filter']) > 0) $searchParams['ogc:Filter'] = $args['ogc:filter'];
  121. if (!empty($args['filterFields'])) $searchParams['cols'] = $args['filterFields'];// propertyName
  122. if (!empty($args['primaryKey'])) $searchParams['primaryKey'] = $args['primaryKey'];// featureID
  123. if (!empty($args['bbox'])) $searchParams['f_the_geom'] = "BBOX:{$args['bbox']}";
  124. DBG::log([ 'msg'=>"getTotal() - searchParams", '$searchParams'=>$searchParams ]);
  125. $totalItems = $acl->getTotal($searchParams);
  126. DBG::log([ 'msg'=>"getTotal() - total", '$totalItems'=>$totalItems ]);
  127. $xmlWriter = new XMLWriter();
  128. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  129. $xmlWriter->openUri('php://output');
  130. $xmlWriter->setIndent(true);
  131. $xmlWriter->startDocument('1.0','UTF-8');
  132. $xmlWriter->startElement('wfs:FeatureCollection');
  133. $xmlWriter->writeAttribute('xmlns:wfs', 'http://www.opengis.net/wfs/2.0');
  134. $xmlWriter->writeAttribute('xmlns', 'http://www.opengis.net/wfs/2.0');
  135. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  136. $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  137. // $xmlWriter->writeAttribute('xsi:schemaLocation', "{$wfsNsUri} {$featureTypeUri}");
  138. $xmlWriter->writeAttribute('numberMatched', $totalItems);
  139. $xmlWriter->writeAttribute('numberReturned', 0);
  140. // $xmlWriter->writeAttribute('timeStamp', "TODO: timestamp like '2011-12-09T11:30:16'");
  141. $xmlWriter->endElement();// wfs:FeatureCollection
  142. $xmlWriter->endDocument();
  143. exit;
  144. }
  145. public function getFeatures($args, $simple = true) {
  146. $type = $args['typeName'];
  147. DBG::log("typeName({$args['xsd:type']})");
  148. $acl = $this->getAclFromTypeName($args['xsd:type']);
  149. DBG::log([ 'msg'=>"typeName({$args['xsd:type']}) - acl(".get_class($acl).")", '$acl'=>$acl ]);
  150. $fldList = $this->_getFieldListFromAcl($acl);
  151. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  152. $rootWfsNs = 'p5';
  153. $rootWfsNsUri = "{$baseNsUri}";
  154. $wfsNs = $args['typePrefix'];
  155. $wfsNsUri = "{$baseNsUri}/" . substr($args['typePrefix'], 3);
  156. $featureTypeUri = $this->getBaseUri() . "?SERVICE=WFS&VERSION=1.0.0&TYPENAME={$args['xsd:type']}&REQUEST=DescribeFeatureType";
  157. // get BBox from geom_field (only one geom fld is allowed)
  158. $geomFld = null;
  159. {
  160. foreach ($fldList as $fldName) {
  161. if ($acl->isGeomField($fldName)) {
  162. $geomFld = $fldName;
  163. }
  164. }
  165. }
  166. DBG::log("ogcFilter(" . strlen($args['ogc:filter']) . "): {$args['ogc:filter']}");
  167. $searchParams = array();
  168. $searchParams['limit'] = $args['limit'];
  169. $searchParams['limitstart'] = $args['offset'];
  170. if (!empty($args['sortBy'])) {
  171. $searchParams['sortBy'] = $args['sortBy'];
  172. } else {
  173. $searchParams['order_by'] = $acl->getPrimaryKeyField();
  174. $searchParams['order_dir'] = 'DESC';
  175. }
  176. if (strlen($args['ogc:filter']) > 0) $searchParams['ogc:Filter'] = $args['ogc:filter'];
  177. if (!empty($args['filterFields'])) $searchParams['cols'] = $args['filterFields'];// PropertyName
  178. if (!empty($args['primaryKey'])) $searchParams['primaryKey'] = $args['primaryKey'];// featureID
  179. if (!empty($args['bbox'])) $searchParams['f_the_geom'] = "BBOX:{$args['bbox']}";
  180. DBG::log([ 'msg'=>'getItems - $searchParams', '$searchParams'=>$searchParams ]);
  181. $items = $acl->getItems($searchParams);
  182. DBG::log([ 'msg'=>'getItems - $items', '$items'=>$items ]);
  183. header('Content-type: application/xml; charset=utf-8');
  184. $xmlWriter = new XMLWriter();
  185. $xmlWriter->openUri('php://output');
  186. // $xmlWriter->openMemory();// DBG
  187. $xmlWriter->setIndent(true);
  188. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  189. $xmlWriter->startDocument('1.0','UTF-8');
  190. //$xmlWriter->startElementNS('wfs', 'FeatureCollection', 'http://www.opengis.net/wfs');
  191. $xmlWriter->startElement('wfs:FeatureCollection');
  192. // $xmlWriter->writeAttributeNS('xmlns', 'wfs', 'http://www.w3.org/2000/xmlns/', 'http://www.opengis.net/wfs');
  193. $xmlWriter->writeAttribute('xmlns:wfs', 'http://www.opengis.net/wfs');
  194. $xmlWriter->writeAttribute('xmlns', 'http://www.opengis.net/wfs');
  195. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  196. $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  197. $xmlWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
  198. $xmlWriter->writeAttribute("xmlns:{$wfsNs}", $wfsNsUri);
  199. if (!$simple) $xmlWriter->writeAttribute("xmlns:{$rootWfsNs}", $rootWfsNsUri);
  200. $xmlWriter->writeAttribute('xsi:schemaLocation', "{$wfsNsUri} {$featureTypeUri}");
  201. DBG::log([ 'msg'=>'$geomFld - getFieldType', 'getFieldType'=>$acl->getFieldType($geomFld) ]);
  202. $tblName = $acl->getName();
  203. foreach ($items as $itemKey => $item) {
  204. if (!is_array($item)) $item = (array)$item;
  205. if (!empty($geomFld)) DBG::log(['msg'=>"item[{$itemKey}] ({$geomFld})isEmpty(".empty($item[$geomFld])."):", '$item['.$geomFld.']'=>$item[$geomFld]]);
  206. DBG::log([ 'msg'=>">>> loop({$itemKey})", '$item'=>$item ]);
  207. $xmlWriter->startElement('gml:featureMember');
  208. $xmlWriter->startElement("{$wfsNs}:{$type}");
  209. $xmlWriter->writeAttribute('fid', "{$type}.{$itemKey}");
  210. if (!$simple) $xmlWriter->writeAttribute("{$rootWfsNs}:web_link", Request::getPathUri() . "index.php?_route=ViewTableAjax&namespace=" . $acl->getNamespace() . "#EDIT/{$itemKey}");
  211. foreach ($fldList as $idZasob => $fldName) {
  212. DBG::log([ 'msg'=>">>> loop({$itemKey}) item({$item['ID']}) fld({$fldName})", '$item'=>$item[$fldName] ]);
  213. $fldType = $acl->getXsdFieldType($fldName);
  214. if (!$acl->canReadObjectField($fldName, (object)$item)) continue;
  215. if ($geomFld != null && $fldName == $geomFld) {
  216. $xmlWriter->startElement("{$wfsNs}:{$fldName}");
  217. if (!$simple && !$acl->canReadObjectField($fldName, (object)$item)) {
  218. $xmlWriter->writeAttribute("{$rootWfsNs}:allow_read", "false");
  219. }
  220. if (!$simple && !$acl->canWriteObjectField($fldName, (object)$item)) {
  221. $xmlWriter->writeAttribute("{$rootWfsNs}:allow_write", "true");
  222. }
  223. $this->_typeConverter->createGmlFromWkt_xmlWriter($item[$fldName], $xmlWriter);
  224. $xmlWriter->endElement();// {$wfsNs}:{$fldName}
  225. } else if (is_array($item[$fldName])) {// TODO: by struct - REF field
  226. DBG::log([ 'msg'=>">>> loop({$itemKey}) REF item[{$itemKey}][{$fldName}]", '$item'=>$item[$fldName] ]);
  227. if (1 == count($item[$fldName])) {
  228. $xlink = $item[$fldName][0]['xlink'];
  229. $xlinkParts = explode(':', $xlink);
  230. if (2 != count($xlinkParts)) throw new Exception("Error Processing Request - wrong xlink format for ".$acl->getName().".{$itemKey}/{$fldName}");
  231. $xlinkParts[0] = Api_WfsNs::getNsUri($xlinkParts[0]);
  232. $xlink = implode('#', $xlinkParts);
  233. $xmlWriter->startElement("{$wfsNs}:{$fldName}");
  234. if (!$simple && !$acl->canReadObjectField($fldName, (object)$item)) {
  235. $xmlWriter->writeAttribute("{$rootWfsNs}:allow_read", "false");
  236. }
  237. if (!$simple && !$acl->canWriteObjectField($fldName, (object)$item)) {
  238. $xmlWriter->writeAttribute("{$rootWfsNs}:allow_write", "true");
  239. }
  240. $xmlWriter->writeAttribute('xlink:href', $xlink);
  241. $xmlWriter->endElement();// {$wfsNs}:{$fldName}
  242. } else {
  243. throw new Exception("Error Processing Request - too many refs for ".$acl->getName().".{$itemKey}/{$fldName}");
  244. }
  245. } else {
  246. $value = str_replace('&', '&amp;', $item[$fldName]);
  247. if (empty($value) && '0' !== $value) {
  248. continue;
  249. } else {
  250. $xmlWriter->startElement("{$wfsNs}:{$fldName}");
  251. if (!$simple && !$acl->canReadObjectField($fldName, (object)$item)) {
  252. $xmlWriter->writeAttribute("{$rootWfsNs}:allow_read", "false");
  253. }
  254. if (!$simple && !$acl->canWriteObjectField($fldName, (object)$item)) {
  255. $xmlWriter->writeAttribute("{$rootWfsNs}:allow_write", "true");
  256. }
  257. $xmlWriter->text($value);
  258. $xmlWriter->endElement();// {$wfsNs}:{$fldName}
  259. }
  260. }
  261. }
  262. $xmlWriter->endElement();// {$wfsNs}:{$type}
  263. $xmlWriter->endElement();// gml:featureMember
  264. }
  265. $xmlWriter->endElement();// wfs:FeatureCollection
  266. $xmlWriter->endDocument();
  267. exit;
  268. }
  269. public function describeFeatureTypeAction() {
  270. $type = V::get('TYPENAME', '', $_REQUEST);
  271. if (empty($type)) {
  272. $reqContent = Request::getRequestBody();
  273. if (!empty($reqContent)) {
  274. return $this->_parseDescribeFeatureTypeRequest($reqContent);
  275. } else {
  276. return $this->_getDescribeFeatureAllTypes();
  277. }
  278. //throw new HttpException("Wrong param TYPENAME", 400);
  279. }
  280. $typeEx = explode(':', $type);
  281. if (count($typeEx) != 2) throw new HttpException("Wrong param TYPENAME", 400);
  282. return $this->_getDescribeFeatureType($typeEx[0], $typeEx[1]);
  283. }
  284. public function describeFeatureTypeAdvancedAction() {
  285. $type = V::get('TYPENAME', '', $_REQUEST);
  286. if (empty($type)) {
  287. $reqContent = Request::getRequestBody();
  288. if (!empty($reqContent)) {
  289. return $this->_parseDescribeFeatureTypeRequest($reqContent, $simple = false);
  290. } else {
  291. return $this->_getDescribeFeatureAllTypes($simple = false);
  292. }
  293. //throw new HttpException("Wrong param TYPENAME", 400);
  294. }
  295. $typeEx = explode(':', $type);
  296. if (count($typeEx) != 2) throw new HttpException("Wrong param TYPENAME", 400);
  297. return $this->_getDescribeFeatureType($typeEx[0], $typeEx[1], $simple = false);
  298. }
  299. public function getCapabilitiesAction() {
  300. $wfsServerUrl = $this->getBaseUri();
  301. $serviceTitle = "Web Feature Service";
  302. $serviceDescription = "This is the reference implementation of WFS 1.0.0 and WFS 1.1.0, supports all WFS operations including Transaction.";
  303. //header('Content-type: application/xml; charset="utf-8"');
  304. header('Content-type: application/xml');
  305. $this->_getCapabilities($wfsServerUrl, $serviceTitle, $serviceDescription);
  306. }
  307. }