WfsQgisServer.php 11 KB

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