WfsQgisServer.php 9.8 KB

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