WfsQgisServer.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. <?php
  2. Lib::loadClass('Api_WfsServerBase');
  3. Lib::loadClass('Api_WfsException');
  4. Lib::loadClass('Api_WfsGeomTypeConverter');
  5. Lib::loadClass('DBG');
  6. Lib::loadClass('Api_Wfs_GetCapabilities');
  7. Lib::loadClass('Api_Wfs_GetFeature');
  8. class Api_WfsQgisServer extends Api_WfsServerBase {
  9. public function parseXMLRequest() {
  10. $data = array();
  11. $reqContent = Request::getRequestBody();
  12. if (empty($reqContent)) {
  13. throw new Exception("Empty request");
  14. }
  15. $parserXml = xml_parser_create();
  16. xml_parser_set_option($parserXml, XML_OPTION_CASE_FOLDING, 0);
  17. xml_parser_set_option($parserXml, XML_OPTION_SKIP_WHITE, 1);
  18. if (0 == xml_parse_into_struct($parserXml, $reqContent, $tags)) {
  19. throw new Exception("Error parsing xml");
  20. }
  21. xml_parser_free($parserXml);
  22. if (empty($tags)) {
  23. throw new Exception("Empty structure from request");
  24. }
  25. $rootTagName = V::get('tag', '', $tags[0]);
  26. if ('Transaction' == $rootTagName) {
  27. return $this->_parseTransactionXmlStruct($reqContent, $tags);
  28. }
  29. throw new Api_WfsException("TODO ... L." . __LINE__, 501);
  30. $xml = new SimpleXMLElement($reqContent);
  31. $namespaces = $xml->getNameSpaces(true);
  32. if ('Transaction' == $xml->getName()) {
  33. $this->_parseTransactionXml($xml);
  34. }
  35. else {
  36. throw new Api_WfsException("Not Implemented " . htmlspecialchars($xml->getName()), 501);
  37. }
  38. }
  39. public function getFeatureAction() {
  40. $args = Api_Wfs_GetFeature::parseGetFeatureArgsFromRequest();
  41. // TODO: if ('hits' == $args['resultType']) ...
  42. return $this->getFeatures($args);
  43. }
  44. public function getFeatures($args) {
  45. $DBG = (V::get('DBG_GEO', '', $_GET) > 0);// TODO: Profiler
  46. $type = $args['typeName'];
  47. $acl = $this->getAclFromTypeName($args['xsd:type']);
  48. $fldList = $this->_getFieldListFromAcl($acl);
  49. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  50. $wfsNs = 'p5_default_db';//$args['typePrefix'];
  51. $wfsNsUri = "{$baseNsUri}/" . substr($args['typePrefix'], 3);
  52. $featureTypeUri = $this->getBaseUri() . "?SERVICE=WFS&VERSION=1.0.0&TYPENAME={$args['xsd:type']}&REQUEST=DescribeFeatureType";
  53. // https://biuro.biall-net.pl/dev-pl/se-master/wfs-qgis.php/default_db/
  54. // https://biuro.biall-net.pl/dev-pl/se-master/wfs-data.php/default_db/TEST_PERMS/?SERVICE=WFS&VERSION=1.0.0&TYPENAME=p5_default_db:TEST_PERMS&REQUEST=DescribeFeatureType
  55. // get BBox from geom_field (only one geom fld is allowed)
  56. $geomFld = null;
  57. {
  58. foreach ($fldList as $idZasob => $fldName) {
  59. if ($acl->isGeomField($fldName)) {
  60. $geomFld = $fldName;
  61. }
  62. }
  63. }
  64. $dbGeomType = $acl->getGeomFieldType($geomFld);
  65. $searchParams = array();
  66. $searchParams['limit'] = $args['limit'];
  67. $searchParams['order_by'] = $acl->getPrimaryKeyField();
  68. $searchParams['order_dir'] = 'DESC';
  69. if (!empty($args['bbox'])) $searchParams['f_the_geom'] = "BBOX:{$args['bbox']}";
  70. if (!empty($args['primaryKey'])) $searchParams['primaryKey'] = $args['primaryKey'];
  71. //if ($geomFld) $searchParams["f_{$geomFld}"] = 'IS NOT NULL';
  72. //if ($geomFld) $searchParams["f_{$geomFld}"] = 'GeometryType=' . strtoupper($dbGeomType);
  73. $geomType = strtoupper($dbGeomType);
  74. if ($geomFld) $searchParams["ogc:Filter"] = <<<OGC_FILTER
  75. <ogc:Filter>
  76. <ogc:And>
  77. <ogc:Not>
  78. <ogc:PropertyIsNull>
  79. <ogc:PropertyName>{$geomFld}</ogc:PropertyName>
  80. </ogc:PropertyIsNull>
  81. </ogc:Not>
  82. <ogc:PropertyIsEqualTo>
  83. <ogc:Function name="GeometryType">
  84. <ogc:PropertyName>{$geomFld}</ogc:PropertyName>
  85. </ogc:Function>
  86. <ogc:Literal>{$geomType}</ogc:Literal>
  87. </ogc:PropertyIsEqualTo>
  88. </ogc:And>
  89. </ogc:Filter>
  90. OGC_FILTER;
  91. if($DBG){echo 'args:';print_r($args);echo "\n";}
  92. if($DBG){echo 'getItems(params) \$params:';print_r($searchParams);echo "\n";}
  93. $this->DBG("getItems:" . json_encode($searchParams), __LINE__, __FUNCTION__, __CLASS__);
  94. $queryFeatures = $acl->buildQuery($searchParams);
  95. $items = $queryFeatures->getItems();
  96. $this->DBG("items(" . count($items) . ")", __LINE__, __FUNCTION__, __CLASS__);
  97. header('Content-type: application/xml; charset=utf-8');
  98. $xmlWriter = new XMLWriter();
  99. $xmlWriter->openUri('php://output');
  100. // $xmlWriter->openMemory();// DBG
  101. $xmlWriter->setIndent(true);
  102. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  103. $xmlWriter->startDocument('1.0','UTF-8');
  104. //$xmlWriter->startElementNS('wfs', 'FeatureCollection', 'http://www.opengis.net/wfs');
  105. $xmlWriter->startElement('wfs:FeatureCollection');
  106. // $xmlWriter->writeAttributeNS('xmlns', 'wfs', 'http://www.w3.org/2000/xmlns/', 'http://www.opengis.net/wfs');
  107. $xmlWriter->writeAttribute('xmlns:wfs', 'http://www.opengis.net/wfs');
  108. $xmlWriter->writeAttribute('xmlns', 'http://www.opengis.net/wfs');
  109. // $xmlWriter->writeAttributeNS('xmlns', 'gml', 'http://www.w3.org/2000/xmlns/', 'http://www.opengis.net/gml');
  110. // $xmlWriter->writeAttributeNS('xmlns', 'xsi', 'http://www.w3.org/2000/xmlns/', 'http://www.w3.org/2001/XMLSchema-instance');
  111. // $xmlWriter->writeAttributeNS('xmlns', $wfsNs, 'http://www.w3.org/2000/xmlns/', $wfsNsUri);
  112. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  113. $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  114. $xmlWriter->writeAttribute("xmlns:{$wfsNs}", $wfsNsUri);
  115. $xmlWriter->writeAttribute('xsi:schemaLocation', "{$wfsNsUri} {$featureTypeUri}");
  116. $xmlWriter->writeAttribute('numberMatched', 'unknown'); // TODO: return total items if simple query (without prefix, small total number, maxFeatures set, etc.)
  117. // NOTE: for client: if numberMatched == 'unknown' then request with resultType = 'hits'
  118. $xmlWriter->writeAttribute('numberReturned', count($items));
  119. if($DBG){echo '(geomFld: '.$geomFld.'):';print_r($acl->getFieldType($geomFld));echo "\n";}
  120. $dbgLoop = 0;
  121. $this->DBG("before loop...", __LINE__, __FUNCTION__, __CLASS__);
  122. $primaryKeyField = $acl->getPrimaryKeyField();
  123. foreach ($items as $item) {
  124. $itemKey = V::get($primaryKeyField, '', $item);
  125. $item = (array)$item;
  126. if (0 == (++$dbgLoop) % 500) $this->DBG("items loop:{$dbgLoop}", __LINE__, __FUNCTION__, __CLASS__);
  127. if($DBG){echo 'item['.$itemKey.'] ('.$geomFld.')isEmpty('.empty($item[$geomFld]).'):' . var_export($item[$geomFld], true) . "\n";}
  128. if ($geomFld) {
  129. if (empty($item[$geomFld])) {
  130. continue;// QGIS crash when WFS contain features with empty geom field
  131. }
  132. }
  133. $xmlWriter->startElement('gml:featureMember');
  134. $xmlWriter->startElement("{$wfsNs}:{$type}");
  135. $xmlWriter->writeAttribute('fid', "{$type}.{$itemKey}");
  136. foreach ($fldList as $idZasob => $fldName) {
  137. // if (!$acl->isAllowed($idZasob, 'R', $item)) {echo '<!-- '."[{$idZasob}]({$fldName}) not allowed to read: ";print_r($item);echo' -->';}
  138. if (!$acl->canReadObjectField($fldName, (object)$item)) continue;
  139. // if ($acl->isGeomField($fldName)) // BUG: wolno
  140. if ($geomFld != null && $fldName == $geomFld) {
  141. $xmlWriter->startElement("{$wfsNs}:{$fldName}");
  142. $this->_typeConverter->createGmlFromWkt_xmlWriter($item[$fldName], $xmlWriter);
  143. $xmlWriter->endElement();// {$wfsNs}:{$fldName}
  144. } else if (is_array($item[$fldName])) {// TODO: by struct - REF field
  145. // if($DBG_DS){echo">>> TODO({$fldName}) REF item[{$itemKey}][{$fldName}]: ";print_r($item[$fldName]);echo "\n";}
  146. } else {
  147. $value = str_replace('&', '&amp;', $item[$fldName]);
  148. if (empty($value) && '0' !== $value) {
  149. continue;
  150. } else {
  151. $xmlWriter->startElement("{$wfsNs}:{$fldName}");
  152. $xmlWriter->text($value);
  153. $xmlWriter->endElement();// {$wfsNs}:{$fldName}
  154. }
  155. }
  156. }
  157. $xmlWriter->endElement();// {$wfsNs}:{$type}
  158. $xmlWriter->endElement();// gml:featureMember
  159. }
  160. $xmlWriter->endElement();// wfs:FeatureCollection
  161. $xmlWriter->endDocument();
  162. $this->DBG("items loop END", __LINE__, __FUNCTION__, __CLASS__);
  163. exit;
  164. }
  165. public function describeFeatureTypeAction() {
  166. $type = V::get('TYPENAME', '', $_REQUEST);
  167. if (empty($type)) {
  168. $reqContent = Request::getRequestBody();
  169. if (!empty($reqContent)) {
  170. return $this->_parseDescribeFeatureTypeRequest($reqContent);
  171. } else {
  172. return $this->_getDescribeFeatureAllTypes();
  173. }
  174. //throw new HttpException("Wrong param TYPENAME", 400);
  175. }
  176. $typeEx = explode(':', $type);
  177. if (count($typeEx) != 2) {
  178. throw new HttpException("Wrong param TYPENAME", 400);
  179. }
  180. return $this->_getDescribeFeatureType($typeEx[0], $typeEx[1]);
  181. }
  182. public function getCapabilitiesAction() {
  183. $wfsServerUrl = $this->getBaseUri();
  184. $serviceTitle = "Web Feature Service for QGIS";
  185. $serviceDescription = "This is the reference implementation of WFS 1.0.0 and WFS 1.1.0, supports all WFS operations including Transaction.";
  186. $idDefaultDB = DB::getPDO()->getZasobId();
  187. $aclList = array_filter($this->_usrAcl->getTablesAcl(), function ($acl) use ($idDefaultDB) {
  188. // if ($idDefaultDB != $tblAcl->getDB()) {// hide non default_db tables
  189. // return false;
  190. // }
  191. // $dataSourceName = 'default_db';// TODO: getSourceName
  192. // $tblName = $tblAcl->getName();
  193. // try {
  194. // $acl = $this->getAclFromTypeName($typeName = "p5_" . $tblAcl->getSourceName() . ":" . $tblAcl->getName());
  195. // } catch (Exception $e) {
  196. // // TODO: error log $e->getMessage();
  197. // }
  198. // if (!$acl) {
  199. // // TODO: error log msg
  200. // continue;
  201. // }
  202. // $fldList = $acl->getRealFieldList();
  203. // if (!in_array('the_geom', $fldList)) {
  204. // continue;
  205. // }
  206. return ($idDefaultDB == $acl->getDB()); // hide non default_db tables
  207. });
  208. switch (V::get('outputFormat', 'xml', $_GET)) {
  209. case 'csv': {
  210. (new Api_Wfs_GetCapabilities)->getCapabilitiesCsv($wfsServerUrl, $serviceTitle, $serviceDescription, $aclList);
  211. } break;
  212. case 'xml': {
  213. (new Api_Wfs_GetCapabilities)->getCapabilitiesXml($wfsServerUrl, $serviceTitle, $serviceDescription, $aclList);
  214. } break;
  215. default: throw new Api_WfsException("Not Implemented outputFormat", 501); // , null, 'NotImplemented', 'request');
  216. }
  217. exit;
  218. }
  219. public function _getTableAclList() {// Use only Tables from default_db with the_geom field
  220. $tblAclList = array();
  221. $idDefaultDB = DB::getPDO()->getZasobId();
  222. $fullTblAclList = $this->_usrAcl->getTablesAcl();
  223. foreach ($fullTblAclList as $tblAcl) {
  224. if ($idDefaultDB != $tblAcl->getDB()) {// hide non default_db tables
  225. continue;
  226. }
  227. // try {
  228. // $acl = $this->getAclFromTypeName($typeName = "p5_" . $tblAcl->getSourceName() . ":" . $tblAcl->getName());
  229. // } catch (Exception $e) {
  230. // // TODO: error log $e->getMessage();
  231. // }
  232. // if (!$acl) {
  233. // // TODO: error log msg
  234. // continue;
  235. // }
  236. // $fldList = $acl->getRealFieldList();
  237. // if (!in_array('the_geom', $fldList)) {
  238. // continue;
  239. // }
  240. $tblAclList[] = $tblAcl;
  241. }
  242. return $tblAclList;
  243. }
  244. public function _getFieldListFromAcl($acl) {
  245. $fldList = $acl->getRealFieldListByIdZasob();
  246. // mv the_geom to the first place
  247. $orderedFldList = array();
  248. foreach ($fldList as $idZasob => $fldName) {
  249. if ('the_geom' == $fldName) $orderedFldList[$idZasob] = $fldName;
  250. }
  251. foreach ($fldList as $idZasob => $fldName) {
  252. if ('the_geom' == $fldName) continue;
  253. $orderedFldList[$idZasob] = $fldName;
  254. }
  255. return $orderedFldList;
  256. }
  257. }