WfsQgisServer.php 10 KB

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