WfsDataServer.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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('Core_XmlWriter');
  7. Lib::loadClass('DBG');
  8. Lib::loadClass('Api_Wfs_GetCapabilities');
  9. class Api_WfsDataServer extends Api_WfsServerBase {
  10. public function run($request) {
  11. $document = '';
  12. if ('WFS' != V::get('SERVICE', '', $request->query) && ('WFS' != V::get('service', '', $request->query))) {
  13. throw new Api_WfsException("Only WFS Service is allowed");
  14. }
  15. $req = V::get('REQUEST', '', $request->query);
  16. if (!empty($req)) {
  17. $methodName = "{$req}Action";
  18. if (!method_exists($this, $methodName)) {
  19. throw new Api_WfsException("Not Implemented " . htmlspecialchars($req), 501);
  20. }
  21. $this->DBG("WfsServer->{$methodName}() ...", __LINE__);
  22. $document = $this->$methodName($urlQuery);
  23. }
  24. else {
  25. $this->DBG("WfsServer->parseXMLRequest() ...", __LINE__);
  26. $document = $this->parseXMLRequest();
  27. header('Content-type: application/xml');
  28. echo '<?xml version="1.0" encoding="UTF-8"?>';
  29. echo $document; exit;// TODO: return $document;
  30. }
  31. 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>';}
  32. if ('raw' == V::get('outputFormat', '', $request->query)) {
  33. header('Content-type: text/plain; charset=utf-8');
  34. echo $document;
  35. } else {
  36. header('Content-type: application/xml');
  37. echo $document;
  38. }
  39. }
  40. public function parseXMLRequest() {
  41. $data = array();
  42. $reqContent = Request::getRequestBody();
  43. if (empty($reqContent)) {
  44. throw new Exception("Empty request");
  45. }
  46. $parserXml = xml_parser_create();
  47. xml_parser_set_option($parserXml, XML_OPTION_CASE_FOLDING, 0);
  48. xml_parser_set_option($parserXml, XML_OPTION_SKIP_WHITE, 1);
  49. if (0 == xml_parse_into_struct($parserXml, $reqContent, $tags)) {
  50. throw new Exception("Error parsing xml");
  51. }
  52. xml_parser_free($parserXml);
  53. if (empty($tags)) {
  54. throw new Exception("Empty structure from request");
  55. }
  56. $rootTagName = V::get('tag', '', $tags[0]);
  57. if ('Transaction' == $rootTagName) return $this->_parseTransactionXmlStruct($reqContent, $tags);
  58. throw new Api_WfsException("Not implemented '{$rootTagName}' #L." . __LINE__, 501);
  59. }
  60. public function getFeatureAction() {
  61. $args = $this->parseGetFeatureArgsFromRequest();
  62. if ('hits' == $args['resultType']) {
  63. return $this->getTotalFeatures($args, $simple = true);
  64. } else {
  65. return $this->getFeatures($args, $simple = true);
  66. }
  67. }
  68. public function getFeatureAdvancedAction() {
  69. $args = $this->parseGetFeatureArgsFromRequest();
  70. if ('hits' == $args['resultType']) {
  71. return $this->getTotalFeatures($args, $simple = false);
  72. } else {
  73. if ('/@instance' == strtolower(substr($args['typeName'], -1 * strlen('/@instance')))) {
  74. return $this->getInstanceFeatures(substr($args['typeName'], 0, -1 * strlen('/@instance')), $args);
  75. }
  76. return $this->getFeatures($args, $simple = false);
  77. }
  78. }
  79. public function testOgcFilterAction() {
  80. $type = V::get('TYPENAME', '', $_REQUEST);
  81. $typeEx = explode(':', $type);
  82. $maxFeatures = V::get('MAXFEATURES', '10000', $_REQUEST, 'int');// TODO: Set Deafult Limit
  83. $ogcFilter = V::get('Filter', '', $_REQUEST);
  84. $srsname = V::get('SRSNAME', '', $_REQUEST);// eg. EPSG:4326
  85. if (count($typeEx) == 2) {
  86. Lib::loadClass('ParseOgcFilter');
  87. $parser = new ParseOgcFilter();
  88. $parser->loadOgcFilter($ogcFilter);
  89. $queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
  90. echo $queryWhereBuilder->getQueryWhere('t');
  91. } else {
  92. throw new HttpException("Wrong param TYPENAME", 400);
  93. }
  94. }
  95. public function getTotalFeatures($args, $simple = true) {
  96. DBG::log("typeName({$args['xsd:type']})");
  97. $acl = $this->getAclFromTypeName($args['xsd:type']);
  98. DBG::log([ 'msg'=>"typeName({$args['xsd:type']}) - acl(".get_class($acl).")", '$acl'=>$acl ]);
  99. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  100. $rootWfsNs = 'p5';
  101. $rootWfsNsUri = "{$baseNsUri}";
  102. $wfsNs = $args['typePrefix'];
  103. $wfsNsUri = "{$baseNsUri}/" . ('p5_' == substr($args['typePrefix'], 0, 3)) ? substr($args['typePrefix'], 3) : $args['typePrefix'];
  104. $featureTypeUri = $this->getBaseUri() . "?SERVICE=WFS&VERSION=1.0.0&TYPENAME={$args['xsd:type']}&REQUEST=DescribeFeatureType";
  105. DBG::log("ogcFilter(" . strlen($args['ogc:filter']) . "): {$args['ogc:filter']}");
  106. $searchParams = array();
  107. $searchParams['limit'] = $args['limit'];
  108. $searchParams['limitstart'] = $args['offset'];
  109. if (!empty($args['sortBy'])) {
  110. $searchParams['sortBy'] = $args['sortBy'];
  111. } else {
  112. $searchParams['order_by'] = $acl->getPrimaryKeyField();
  113. $searchParams['order_dir'] = 'DESC';
  114. }
  115. if (strlen($args['ogc:filter']) > 0) $searchParams['ogc:Filter'] = $args['ogc:filter'];
  116. if (!empty($args['filterFields'])) $searchParams['cols'] = $args['filterFields'];// propertyName
  117. if (!empty($args['primaryKey'])) $searchParams['primaryKey'] = $args['primaryKey'];// featureID
  118. if (!empty($args['bbox'])) $searchParams['f_the_geom'] = "BBOX:{$args['bbox']}";
  119. $queryFeatures = $acl->buildQuery($searchParams);
  120. $totalItems = $queryFeatures->getTotal();
  121. $xmlWriter = new XMLWriter();
  122. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  123. $xmlWriter->openUri('php://output');
  124. $xmlWriter->setIndent(true);
  125. $xmlWriter->startDocument('1.0','UTF-8');
  126. $xmlWriter->startElement('wfs:FeatureCollection');
  127. $xmlWriter->writeAttribute('xmlns:wfs', 'http://www.opengis.net/wfs/2.0');
  128. $xmlWriter->writeAttribute('xmlns', 'http://www.opengis.net/wfs/2.0');
  129. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  130. $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  131. // $xmlWriter->writeAttribute('xsi:schemaLocation', "{$wfsNsUri} {$featureTypeUri}");
  132. $xmlWriter->writeAttribute('numberMatched', $totalItems);
  133. $xmlWriter->writeAttribute('numberReturned', 0);
  134. // $xmlWriter->writeAttribute('timeStamp', "TODO: timestamp like '2011-12-09T11:30:16'");
  135. $xmlWriter->endElement();// wfs:FeatureCollection
  136. $xmlWriter->endDocument();
  137. exit;
  138. }
  139. public function getFeatures($args, $simple = true) {
  140. $type = $args['typeName'];
  141. DBG::log("typeName({$args['xsd:type']})");
  142. $acl = $this->getAclFromTypeName($args['xsd:type']);
  143. DBG::log([ 'msg'=>"typeName({$args['xsd:type']}) - acl(".get_class($acl).")", '$acl'=>$acl ]);
  144. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  145. $rootWfsNs = 'p5';
  146. $rootWfsNsUri = "{$baseNsUri}";
  147. $wfsNs = $args['typePrefix'];
  148. $wfsNsUri = "{$baseNsUri}/" . str_replace('__x3A__', '/', ('p5_' === substr($args['typePrefix'], 0, 3) ? substr($args['typePrefix'], 3) : $args['typePrefix']));
  149. $featureTypeUri = $this->getBaseUri() . "?SERVICE=WFS&VERSION=1.0.0&TYPENAME={$args['xsd:type']}&REQUEST=DescribeFeatureType";
  150. DBG::log("ogcFilter(" . strlen($args['ogc:filter']) . "): {$args['ogc:filter']}");
  151. $searchParams = array();
  152. $searchParams['limit'] = $args['limit'];
  153. $searchParams['limitstart'] = $args['offset'];
  154. if (!empty($args['sortBy'])) {
  155. $searchParams['sortBy'] = $args['sortBy'];
  156. } else {
  157. $searchParams['order_by'] = $acl->getPrimaryKeyField();
  158. $searchParams['order_dir'] = 'DESC';
  159. }
  160. if (strlen($args['ogc:filter']) > 0) $searchParams['ogc:Filter'] = $args['ogc:filter'];
  161. if (!empty($args['filterFields'])) $searchParams['cols'] = $args['filterFields'];// PropertyName
  162. if (!empty($args['primaryKey'])) $searchParams['primaryKey'] = $args['primaryKey'];// featureID
  163. if (!empty($args['bbox'])) $searchParams['f_the_geom'] = "BBOX:{$args['bbox']}";
  164. DBG::log($args, 'array', "\$args");
  165. $schemaCache = array();
  166. Lib::loadClass('Api_Wfs_GetFeature');
  167. try {
  168. $searchParams['cols'] = Api_Wfs_GetFeature::convertOgcPropertyListToFeatureQueryCols($schemaCache, $args['filterFields'], $acl); // convert $args['filterFields'] to field list
  169. } catch (Exception $e) {
  170. DBG::log($e);
  171. throw $e;
  172. }
  173. DBG::log($searchParams, 'string', 'getItems - $searchParams');
  174. $queryFeatures = $acl->buildQuery($searchParams);
  175. $items = $queryFeatures->getItems();
  176. DBG::log($items, 'array', 'getItems - $items');
  177. header('Content-type: application/xml; charset=utf-8');
  178. $xmlWriter = new Core_XmlWriter();
  179. $xmlWriter->openUri('php://output');
  180. // $xmlWriter->openMemory();// DBG
  181. $xmlWriter->setIndent(true);
  182. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  183. $xmlWriter->startDocument('1.0','UTF-8');
  184. //$xmlWriter->startElementNS('wfs', 'FeatureCollection', 'http://www.opengis.net/wfs');
  185. $xmlWriter->startElement('wfs:FeatureCollection');
  186. // $xmlWriter->writeAttributeNS('xmlns', 'wfs', 'http://www.w3.org/2000/xmlns/', 'http://www.opengis.net/wfs');
  187. $xmlWriter->writeAttribute('xmlns:wfs', 'http://www.opengis.net/wfs');
  188. $xmlWriter->writeAttribute('xmlns', 'http://www.opengis.net/wfs');
  189. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  190. $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  191. $xmlWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
  192. $xlmns = [];
  193. $xlmns[ $wfsNs ] = $wfsNsUri;
  194. if (!$simple) $xlmns[ $rootWfsNs ] = $rootWfsNsUri;
  195. foreach ($schemaCache as $childSchema) {
  196. $xlmns[ $childSchema['nsPrefix'] ] = "{$rootWfsNsUri}/" . str_replace('__x3A__', '/', $childSchema['nsPrefix']);
  197. }
  198. foreach ($xlmns as $prefixXmlns => $urlXmlns) {
  199. $xmlWriter->writeAttribute("xmlns:{$prefixXmlns}", $urlXmlns);
  200. }
  201. $xmlWriter->writeAttribute('xsi:schemaLocation', "{$wfsNsUri} {$featureTypeUri}"); // TODO: BUG $wfsNsUri
  202. $xmlWriter->writeAttribute('numberMatched', 'unknown'); // TODO: return total items if simple query (without prefix, small total number, maxFeatures set, etc.)
  203. // NOTE: for client: if numberMatched == 'unknown' then request with resultType = 'hits'
  204. $xmlWriter->writeAttribute('numberReturned', count($items));
  205. $tblName = $acl->getName();
  206. $primaryKeyField = $acl->getPrimaryKeyField();
  207. foreach ($items as $item) {
  208. $itemKey = V::get($primaryKeyField, '', $item);
  209. if (!is_array($item)) $item = (array)$item;
  210. if (!empty($geomFld)) DBG::log($item[$geomFld], 'array', "item[{$itemKey}] ({$geomFld})isEmpty(".empty($item[$geomFld])."):");
  211. DBG::log($item, 'array' , ">>> loop({$itemKey})");
  212. DBG::log($searchParams['cols'], 'array' , "\$searchParams['cols']");
  213. $xmlWriter->startElement('gml:featureMember');
  214. Api_Wfs_GetFeature::printXmlFeatureRecurse($xmlWriter, $acl, $item, $searchParams['cols'], $tagName = "{$wfsNs}:{$type}", array_merge(
  215. [
  216. 'fid' => "{$type}.{$itemKey}",
  217. ],
  218. (!$simple)
  219. ? [ "{$rootWfsNs}:web_link" => Request::getPathUri() . "index.php?_route=ViewTableAjax&namespace=" . $acl->getNamespace() . "#EDIT/{$itemKey}" ]
  220. : []
  221. ), $showAdvancedAttrs = !$simple, $schemaCache);
  222. $xmlWriter->endElement();// gml:featureMember
  223. }
  224. $xmlWriter->endElement();// wfs:FeatureCollection
  225. $xmlWriter->endDocument();
  226. exit;
  227. }
  228. public function describeFeatureTypeAction() {
  229. $type = V::get('TYPENAME', '', $_REQUEST);
  230. if (empty($type)) {
  231. $reqContent = Request::getRequestBody();
  232. if (!empty($reqContent)) {
  233. return $this->_parseDescribeFeatureTypeRequest($reqContent);
  234. } else {
  235. return $this->_getDescribeFeatureAllTypes();
  236. }
  237. //throw new HttpException("Wrong param TYPENAME", 400);
  238. }
  239. $typeEx = explode(':', $type);
  240. if (count($typeEx) != 2) throw new HttpException("Wrong param TYPENAME", 400);
  241. return $this->_getDescribeFeatureType($typeEx[0], $typeEx[1]);
  242. }
  243. public function describeFeatureTypeAdvancedAction() {
  244. $typeName = V::geti('TYPENAME', '', $_REQUEST);
  245. if (empty($typeName)) {
  246. $reqContent = Request::getRequestBody();
  247. if (!empty($reqContent)) {
  248. return $this->_parseDescribeFeatureTypeRequest($reqContent, $simple = false);
  249. } else {
  250. return $this->_getDescribeFeatureAllTypes($simple = false);
  251. }
  252. //throw new HttpException("Wrong param TYPENAME", 400);
  253. }
  254. if (false === strpos($typeName, ':')) throw new HttpException("Wrong param TYPENAME", 400);
  255. list($nsPrefix, $name) = explode(':', $typeName);
  256. if ('/@instance' == strtolower(substr($name, -1 * strlen('/@instance')))) {
  257. return $this->_describeInstanceAttributeTable($nsPrefix, substr($name, 0, -1 * strlen('/@instance')));
  258. }
  259. return $this->_getDescribeFeatureType($nsPrefix, $name, $simple = false);
  260. }
  261. public function getCapabilitiesAction() {
  262. $wfsServerUrl = $this->getBaseUri();
  263. $serviceTitle = "Web Feature Service";
  264. $serviceDescription = "This is the reference implementation of WFS 1.0.0 and WFS 1.1.0, supports all WFS operations including Transaction.";
  265. $idDefaultDB = DB::getPDO()->getZasobId();
  266. $aclList = array_filter($this->_usrAcl->getTablesAcl(), function ($acl) use ($idDefaultDB) {
  267. // // $dataSourceName = 'default_db';// TODO: getSourceName
  268. // // $tblName = $tblAcl->getName();
  269. // // try {
  270. // // $acl = $this->getAclFromTypeName($typeName = "p5_{$dataSourceName}:{$tblName}");
  271. // // } catch (Exception $e) {
  272. // // // echo "Error for table({$tblName}): " . $e->getMessage() . "\n";
  273. // // }
  274. // // if (!$acl) {
  275. // // // TODO: error log msg
  276. // // return false;
  277. // // }
  278. return ($idDefaultDB == $acl->getDB()); // hide non default_db tables
  279. });
  280. switch (V::get('outputFormat', 'xml', $_GET)) {
  281. case 'csv': {
  282. (new Api_Wfs_GetCapabilities)->getCapabilitiesCsv($wfsServerUrl, $serviceTitle, $serviceDescription, $aclList);
  283. } break;
  284. case 'xml': {
  285. (new Api_Wfs_GetCapabilities)->getCapabilitiesXml($wfsServerUrl, $serviceTitle, $serviceDescription, $aclList);
  286. } break;
  287. default: throw new Api_WfsException("Not Implemented outputFormat", 501); // , null, 'NotImplemented', 'request');
  288. }
  289. exit;
  290. }
  291. }