WfsQgisServer.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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 $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. //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:Or>
  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:Or>
  88. </ogc:Filter>
  89. OGC_FILTER;
  90. if($DBG){echo 'getItems:';print_r($searchParams);echo "\n";}
  91. $this->DBG("getItems:" . json_encode($searchParams), __LINE__, __FUNCTION__, __CLASS__);
  92. $items = $acl->getItems($searchParams);
  93. $this->DBG("items(" . count($items) . ")", __LINE__, __FUNCTION__, __CLASS__);
  94. if (true) {//1 == V::get('XML_WRITER', 0, $_GET, 'int')) {
  95. header('Content-type: application/xml; charset=utf-8');
  96. $xmlWriter = new XMLWriter();
  97. $xmlWriter->openUri('php://output');
  98. $xmlWriter->setIndent(true);
  99. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  100. $xmlWriter->startDocument('1.0','UTF-8');
  101. //$xmlWriter->startElementNS('wfs', 'FeatureCollection', 'http://www.opengis.net/wfs');
  102. $xmlWriter->startElement('wfs:FeatureCollection');
  103. // $xmlWriter->writeAttributeNS('xmlns', 'wfs', 'http://www.w3.org/2000/xmlns/', 'http://www.opengis.net/wfs');
  104. $xmlWriter->writeAttribute('xmlns:wfs', 'http://www.opengis.net/wfs');
  105. $xmlWriter->writeAttribute('xmlns', 'http://www.opengis.net/wfs');
  106. // $xmlWriter->writeAttributeNS('xmlns', 'gml', 'http://www.w3.org/2000/xmlns/', 'http://www.opengis.net/gml');
  107. // $xmlWriter->writeAttributeNS('xmlns', 'xsi', 'http://www.w3.org/2000/xmlns/', 'http://www.w3.org/2001/XMLSchema-instance');
  108. // $xmlWriter->writeAttributeNS('xmlns', $wfsNs, 'http://www.w3.org/2000/xmlns/', $wfsNsUri);
  109. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  110. $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  111. $xmlWriter->writeAttribute("xmlns:{$wfsNs}", $wfsNsUri);
  112. $xmlWriter->writeAttribute('xsi:schemaLocation', "{$wfsNsUri} {$featureTypeUri}");
  113. if($DBG){echo '(geomFld: '.$geomFld.'):';print_r($acl->getFieldType($geomFld));echo "\n";}
  114. if (empty($items)) {
  115. $pKeyField = $acl->getPrimaryKeyField();
  116. $fakeItem = new stdClass();
  117. $fakeItem->{$pKeyField} = 0;
  118. if ('polygon' == $dbGeomType) {
  119. $fakeItem->the_geom = "POLYGON(())";
  120. } else if ('linestring' == $dbGeomType) {
  121. $fakeItem->the_geom = "LINESTRING()";
  122. } else if ('point' == $dbGeomType) {
  123. $fakeItem->the_geom = "POINT(0,0)";
  124. }
  125. $items[0] = $fakeItem;
  126. }
  127. $dbgLoop = 0;
  128. foreach ($items as $itemKey => $item) {
  129. if (0 == (++$dbgLoop) % 1000) $this->DBG("items loop:{$dbgLoop}", __LINE__, __FUNCTION__, __CLASS__);
  130. if($DBG){echo 'item['.$itemKey.'] ('.$geomFld.')isEmpty('.empty($item->{$geomFld}).'):';print_r($item->{$geomFld});echo "\n";}
  131. if ($geomFld) {
  132. if (empty($item->{$geomFld})) {
  133. continue;// QGIS crash when WFS contain features with empty geom field
  134. }
  135. }
  136. $xmlWriter->startElement('gml:featureMember');
  137. $xmlWriter->startElement("{$wfsNs}:{$type}");
  138. $xmlWriter->writeAttribute('fid', "{$type}.{$itemKey}");
  139. foreach ($fldList as $fldName) {
  140. if ($acl->isGeomField($fldName)) {
  141. $xmlWriter->startElement("{$wfsNs}:{$fldName}");
  142. $this->_typeConverter->createGmlFromWkt_xmlWriter($item->{$fldName}, $xmlWriter);
  143. $xmlWriter->endElement();// {$wfsNs}:{$fldName}
  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. //'<!-- .EOF -->';
  162. exit;
  163. }
  164. $dom = new DOMDocument('1.0', 'utf-8');
  165. $dom->formatOutput = true;
  166. $dom->preserveWhiteSpace = false;
  167. $rootNode = $dom->createElementNS('http://www.opengis.net/wfs', 'wfs:FeatureCollection');
  168. $dom->appendChild($rootNode);
  169. $rootNode->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', 'http://www.opengis.net/wfs');
  170. $rootNode->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:wfs', 'http://www.opengis.net/wfs');
  171. $rootNode->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:gml', 'http://www.opengis.net/gml');
  172. $rootNode->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  173. $rootNode->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:' . $wfsNs, $wfsNsUri);
  174. $rootNode->setAttribute('xsi:schemaLocation', "{$wfsNsUri} {$featureTypeUri}");
  175. if(0){// TODO: get BBOX for add features
  176. $boundedByNode = $dom->createElementNS('http://www.opengis.net/gml', 'gml:boundedBy');
  177. $rootNode->appendChild($boundedByNode);
  178. $boxNode = $dom->createElementNS('http://www.opengis.net/gml', 'gml:Box');
  179. $boundedByNode->appendChild($boxNode);
  180. $boxNode->setAttribute('srsName', "http://www.opengis.net/gml/srs/epsg.xml#4326");// TODO: EPSG
  181. $coordinatesNode = $dom->createElementNS('http://www.opengis.net/gml', 'gml:coordinates');
  182. $boxNode->appendChild($coordinatesNode);
  183. $coordinatesNode->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:gml', 'http://www.opengis.net/gml');
  184. $coordinatesNode->setAttribute('decimal', '.');
  185. $coordinatesNode->setAttribute('cs', ',');
  186. $coordinatesNode->setAttribute('ts', ' ');
  187. $coordinatesNode->nodeValue = '1544947.6295,4322758.105 1548002.2259,4330464.1001';// TODO: coordinates for all items?
  188. }
  189. if($DBG){echo '(geomFld: '.$geomFld.'):';print_r($acl->getFieldType($geomFld));echo "\n";}
  190. if (empty($items)) {
  191. $pKeyField = $acl->getPrimaryKeyField();
  192. $fakeItem = new stdClass();
  193. $fakeItem->{$pKeyField} = 0;
  194. if ('polygon' == $dbGeomType) {
  195. $fakeItem->the_geom = "POLYGON(())";
  196. } else if ('linestring' == $dbGeomType) {
  197. $fakeItem->the_geom = "LINESTRING()";
  198. } else if ('point' == $dbGeomType) {
  199. $fakeItem->the_geom = "POINT(0,0)";
  200. }
  201. $items[0] = $fakeItem;
  202. }
  203. $dbgLoop = 0;
  204. foreach ($items as $itemKey => $item) {
  205. $dbgLoop++; if (0 == $dbgLoop % 100) $this->DBG("items loop:{$dbgLoop}", __LINE__, __FUNCTION__, __CLASS__);
  206. if($DBG){echo 'item['.$itemKey.'] ('.$geomFld.')isEmpty('.empty($item->{$geomFld}).'):';print_r($item->{$geomFld});echo "\n";}
  207. if ($geomFld) {
  208. if (empty($item->{$geomFld})) {
  209. continue;// QGIS crash when WFS contain features with empty geom field
  210. }
  211. }
  212. $featureMemberNode = $dom->createElementNS('http://www.opengis.net/gml', 'gml:featureMember');
  213. $rootNode->appendChild($featureMemberNode);
  214. $featureNode = $dom->createElementNS($wfsNsUri, "{$wfsNs}:{$type}");
  215. $featureMemberNode->appendChild($featureNode);
  216. $featureNode->setAttribute('fid', "{$type}.{$itemKey}");
  217. if(0){// TODO: get BBOX
  218. $boundedByNode = $dom->createElementNS('http://www.opengis.net/gml', 'gml:boundedBy');
  219. $featureNode->appendChild($boundedByNode);
  220. $boxNode = $dom->createElementNS('http://www.opengis.net/gml', 'gml:Box');
  221. $boundedByNode->appendChild($boxNode);
  222. $boxNode->setAttribute('srsName', "http://www.opengis.net/gml/srs/epsg.xml#4326");// TODO: EPSG
  223. $coordinatesNode = $dom->createElementNS('http://www.opengis.net/gml', 'gml:coordinates');
  224. $boxNode->appendChild($coordinatesNode);
  225. $coordinatesNode->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:gml', 'http://www.opengis.net/gml');
  226. $coordinatesNode->setAttribute('decimal', '.');
  227. $coordinatesNode->setAttribute('cs', ',');
  228. $coordinatesNode->setAttribute('ts', ' ');
  229. $coordinatesNode->nodeValue = '1546472.2363,4328949.5775 1548002.2259,4330464.1001';// TODO: coordinates for item?
  230. }
  231. foreach ($fldList as $fldName) {
  232. $featureFldNode = $dom->createElementNS($wfsNsUri, "{$wfsNs}:{$fldName}");
  233. if ($acl->isGeomField($fldName)) {
  234. $geomNode = $this->_typeConverter->createGmlFromWkt($item->{$fldName}, $dom);
  235. if (!$geomNode) continue;
  236. $featureFldNode->appendChild($geomNode);
  237. } else {
  238. $featureFldNode->nodeValue = str_replace('&', '&amp;', $item->{$fldName});
  239. if (empty($featureFldNode->nodeValue) && '0' !== $featureFldNode->nodeValue) {
  240. continue;
  241. }
  242. }
  243. $featureNode->appendChild($featureFldNode);
  244. }
  245. }
  246. $this->DBG("items loop END", __LINE__, __FUNCTION__, __CLASS__);
  247. return $dom->saveXml();
  248. }
  249. public function describeFeatureTypeAction() {
  250. $type = V::get('TYPENAME', '', $_REQUEST);
  251. if (empty($type)) {
  252. $reqContent = Request::getRequestBody();
  253. if (!empty($reqContent)) {
  254. return $this->_parseDescribeFeatureTypeRequest($reqContent);
  255. } else {
  256. return $this->_getDescribeFeatureAllTypes();
  257. }
  258. //throw new HttpException("Wrong param TYPENAME", 400);
  259. }
  260. $typeEx = explode(':', $type);
  261. if (count($typeEx) != 2) {
  262. throw new HttpException("Wrong param TYPENAME", 400);
  263. }
  264. return $this->_getDescribeFeatureType($typeEx[0], $typeEx[1]);
  265. }
  266. public function getCapabilitiesAction() {
  267. $wfsServerUrl = $this->getBaseUri();
  268. $serviceTitle = "Web Feature Service for QGIS";
  269. $serviceDescription = "This is the reference implementation of WFS 1.0.0 and WFS 1.1.0, supports all WFS operations including Transaction.";
  270. //header('Content-type: application/xml; charset="utf-8"');
  271. header('Content-type: application/xml');
  272. $this->_getCapabilities($wfsServerUrl, $serviceTitle, $serviceDescription);
  273. exit;
  274. }
  275. public function _getTableAclList() {// Use only Tables from default_db with the_geom field
  276. $tblAclList = array();
  277. $db = DB::getDB();
  278. $idDefaultDB = $db->_zasob_id;
  279. $fullTblAclList = $this->_usrAcl->getTablesAcl();
  280. foreach ($fullTblAclList as $tblAcl) {
  281. $dataSourceName = 'default_db';// TODO: getSourceName
  282. $tblName = $tblAcl->getName();
  283. if ($idDefaultDB != $tblAcl->getDB()) {// hide non default_db tables
  284. continue;
  285. }
  286. try {
  287. $acl = $this->getAclFromTypeName($typeName = "p5_{$dataSourceName}:{$tblName}");
  288. } catch (Exception $e) {
  289. // TODO: error log $e->getMessage();
  290. }
  291. if (!$acl) {
  292. // TODO: error log msg
  293. continue;
  294. }
  295. $fldList = $acl->getRealFieldList();
  296. if (!in_array('the_geom', $fldList)) {
  297. continue;
  298. }
  299. $tblAclList[] = $tblAcl;
  300. }
  301. return $tblAclList;
  302. }
  303. public function _getFieldListFromAcl($acl) {
  304. $fldList = $acl->getRealFieldList();
  305. {// mv the_geom to the first place
  306. array_unshift($fldList, 'the_geom');
  307. $fldList = array_unique($fldList);
  308. }
  309. return $fldList;
  310. }
  311. }