WfsQgisServer.php 14 KB

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