WfsDataServer.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. Lib::loadClass('Api_WfsServerBase');
  3. Lib::loadClass('Api_WfsException');
  4. Lib::loadClass('Api_WfsGeomTypeConverter');
  5. Lib::loadClass('Api_WfsNs');
  6. Lib::loadClass('Core_XmlWriter');
  7. Lib::loadClass('DBG');
  8. Lib::loadClass('Api_Wfs_GetCapabilities');
  9. class Api_WfsDataServer extends Api_WfsServerBase {
  10. public function run($request) {
  11. $document = '';
  12. if ('WFS' != V::get('SERVICE', '', $request->query) && ('WFS' != V::get('service', '', $request->query))) {
  13. throw new Api_WfsException("Only WFS Service is allowed");
  14. }
  15. $req = V::get('REQUEST', '', $request->query);
  16. if (!empty($req)) {
  17. $methodName = "{$req}Action";
  18. if (!method_exists($this, $methodName)) {
  19. throw new Api_WfsException("Not Implemented " . htmlspecialchars($req), 501);
  20. }
  21. $this->DBG("WfsServer->{$methodName}() ...", __LINE__);
  22. $document = $this->$methodName($urlQuery);
  23. }
  24. else {
  25. $this->DBG("WfsServer->parseXMLRequest() ...", __LINE__);
  26. $document = $this->parseXMLRequest();
  27. header('Content-type: application/xml');
  28. echo '<?xml version="1.0" encoding="UTF-8"?>';
  29. echo $document; exit;// TODO: return $document;
  30. }
  31. IF(V::get('DBG','',$_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$document (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($document);echo'</pre>';}
  32. if ('raw' == V::get('outputFormat', '', $request->query)) {
  33. header('Content-type: text/plain; charset=utf-8');
  34. echo $document;
  35. } else {
  36. header('Content-type: application/xml');
  37. echo $document;
  38. }
  39. }
  40. public function parseXMLRequest() {
  41. $data = array();
  42. $reqContent = Request::getRequestBody();
  43. if (empty($reqContent)) {
  44. throw new Exception("Empty request");
  45. }
  46. $parserXml = xml_parser_create();
  47. xml_parser_set_option($parserXml, XML_OPTION_CASE_FOLDING, 0);
  48. xml_parser_set_option($parserXml, XML_OPTION_SKIP_WHITE, 1);
  49. if (0 == xml_parse_into_struct($parserXml, $reqContent, $tags)) {
  50. throw new Exception("Error parsing xml");
  51. }
  52. xml_parser_free($parserXml);
  53. if (empty($tags)) {
  54. throw new Exception("Empty structure from request");
  55. }
  56. $rootTagName = V::get('tag', '', $tags[0]);
  57. if ('Transaction' == $rootTagName) return $this->_parseTransactionXmlStruct($reqContent, $tags);
  58. throw new Api_WfsException("Not implemented '{$rootTagName}' #L." . __LINE__, 501);
  59. }
  60. public function getFeatureAction() {
  61. $args = $this->parseGetFeatureArgsFromRequest();
  62. if ('hits' == $args['resultType']) {
  63. return $this->getTotalFeatures($args, $simple = true);
  64. } else {
  65. return $this->getFeatures($args, $simple = true);
  66. }
  67. }
  68. public function getFeatureAdvancedAction() {
  69. $args = $this->parseGetFeatureArgsFromRequest();
  70. if ('hits' == $args['resultType']) {
  71. return $this->getTotalFeatures($args, $simple = false);
  72. } else {
  73. if ('/@instance' == strtolower(substr($args['typeName'], -1 * strlen('/@instance')))) {
  74. return $this->getInstanceFeatures(substr($args['typeName'], 0, -1 * strlen('/@instance')), $args);
  75. }
  76. return $this->getFeatures($args, $simple = false);
  77. }
  78. }
  79. public function testOgcFilterAction() {
  80. $type = V::get('TYPENAME', '', $_REQUEST);
  81. $typeEx = explode(':', $type);
  82. $maxFeatures = V::get('MAXFEATURES', '10000', $_REQUEST, 'int');// TODO: Set Deafult Limit
  83. $ogcFilter = V::get('Filter', '', $_REQUEST);
  84. $srsname = V::get('SRSNAME', '', $_REQUEST);// eg. EPSG:4326
  85. if (count($typeEx) == 2) {
  86. Lib::loadClass('ParseOgcFilter');
  87. $parser = new ParseOgcFilter();
  88. $parser->loadOgcFilter($ogcFilter);
  89. $queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
  90. echo $queryWhereBuilder->getQueryWhere('t');
  91. } else {
  92. throw new HttpException("Wrong param TYPENAME", 400);
  93. }
  94. }
  95. public function getTotalFeatures($args, $simple = true) {
  96. DBG::log("typeName({$args['xsd:type']})");
  97. $acl = $this->getAclFromTypeName($args['xsd:type']);
  98. DBG::log([ 'msg'=>"typeName({$args['xsd:type']}) - acl(".get_class($acl).")", '$acl'=>$acl ]);
  99. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  100. $rootWfsNs = 'p5';
  101. $rootWfsNsUri = "{$baseNsUri}";
  102. $wfsNs = $args['typePrefix'];
  103. $wfsNsUri = "{$baseNsUri}/" . ('p5_' == substr($args['typePrefix'], 0, 3)) ? substr($args['typePrefix'], 3) : $args['typePrefix'];
  104. $featureTypeUri = $this->getBaseUri() . "?SERVICE=WFS&VERSION=1.0.0&TYPENAME={$args['xsd:type']}&REQUEST=DescribeFeatureType";
  105. DBG::log("ogcFilter(" . strlen($args['ogc:filter']) . "): {$args['ogc:filter']}");
  106. $searchParams = array();
  107. $searchParams['limit'] = $args['limit'];
  108. $searchParams['limitstart'] = $args['offset'];
  109. if (!empty($args['sortBy'])) {
  110. $searchParams['sortBy'] = $args['sortBy'];
  111. } else {
  112. $searchParams['order_by'] = $acl->getPrimaryKeyField();
  113. $searchParams['order_dir'] = 'DESC';
  114. }
  115. if (strlen($args['ogc:filter']) > 0) $searchParams['ogc:Filter'] = $args['ogc:filter'];
  116. if (!empty($args['filterFields'])) $searchParams['cols'] = $args['filterFields'];// propertyName
  117. if (!empty($args['primaryKey'])) $searchParams['primaryKey'] = $args['primaryKey'];// featureID
  118. if (!empty($args['bbox'])) $searchParams['f_the_geom'] = "BBOX:{$args['bbox']}";
  119. $queryFeatures = $acl->buildQuery($searchParams);
  120. $totalItems = $queryFeatures->getTotal();
  121. $xmlWriter = new XMLWriter();
  122. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  123. $xmlWriter->openUri('php://output');
  124. $xmlWriter->setIndent(true);
  125. $xmlWriter->startDocument('1.0','UTF-8');
  126. $xmlWriter->startElement('wfs:FeatureCollection');
  127. $xmlWriter->writeAttribute('xmlns:wfs', 'http://www.opengis.net/wfs/2.0');
  128. $xmlWriter->writeAttribute('xmlns', 'http://www.opengis.net/wfs/2.0');
  129. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  130. $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  131. // $xmlWriter->writeAttribute('xsi:schemaLocation', "{$wfsNsUri} {$featureTypeUri}");
  132. $xmlWriter->writeAttribute('numberMatched', $totalItems);
  133. $xmlWriter->writeAttribute('numberReturned', 0);
  134. // $xmlWriter->writeAttribute('timeStamp', "TODO: timestamp like '2011-12-09T11:30:16'");
  135. $xmlWriter->endElement();// wfs:FeatureCollection
  136. $xmlWriter->endDocument();
  137. exit;
  138. }
  139. public function getFeatures($args, $simple = true) {
  140. $type = $args['typeName'];
  141. DBG::log("typeName({$args['xsd:type']})");
  142. $acl = $this->getAclFromTypeName($args['xsd:type']);
  143. DBG::log([ 'msg'=>"typeName({$args['xsd:type']}) - acl(".get_class($acl).")", '$acl'=>$acl ]);
  144. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  145. $rootWfsNs = 'p5';
  146. $rootWfsNsUri = "{$baseNsUri}";
  147. $wfsNs = $args['typePrefix'];
  148. $wfsNsUri = "{$baseNsUri}/" . str_replace('__x3A__', '/', ('p5_' === substr($args['typePrefix'], 0, 3) ? substr($args['typePrefix'], 3) : $args['typePrefix']));
  149. $featureTypeUri = $this->getBaseUri() . "?SERVICE=WFS&VERSION=1.0.0&TYPENAME={$args['xsd:type']}&REQUEST=DescribeFeatureType";
  150. DBG::log("ogcFilter(" . strlen($args['ogc:filter']) . "): {$args['ogc:filter']}");
  151. $searchParams = array();
  152. $searchParams['limit'] = $args['limit'];
  153. $searchParams['limitstart'] = $args['offset'];
  154. if (!empty($args['sortBy'])) {
  155. $searchParams['sortBy'] = $args['sortBy'];
  156. } else {
  157. $searchParams['order_by'] = $acl->getPrimaryKeyField();
  158. $searchParams['order_dir'] = 'DESC';
  159. }
  160. if (strlen($args['ogc:filter']) > 0) $searchParams['ogc:Filter'] = $args['ogc:filter'];
  161. if (!empty($args['filterFields'])) $searchParams['cols'] = $args['filterFields']; // PropertyName
  162. if (!empty($args['primaryKey'])) $searchParams['primaryKey'] = $args['primaryKey'];
  163. if (!empty($args['xlink'])) {
  164. $expectedUrl = Api_WfsNs::getBaseWfsUri() . "/" . $acl->getNamespace() . ".";
  165. if ($expectedUrl !== substr($args['xlink'], 0, strlen($expectedUrl))) throw new Exception("Wrong xlink url");
  166. $primaryKey = substr($args['xlink'], strlen($expectedUrl));
  167. $searchParams['primaryKey'] = $primaryKey;
  168. }
  169. if (!empty($args['bbox'])) $searchParams['f_the_geom'] = "BBOX:{$args['bbox']}";
  170. DBG::log($args, 'array', "\$args");
  171. $schemaCache = array();
  172. Lib::loadClass('Api_Wfs_GetFeature');
  173. try {
  174. $searchParams['cols'] = Api_Wfs_GetFeature::convertOgcPropertyListToFeatureQueryCols($schemaCache, $args['filterFields'], $acl); // convert $args['filterFields'] to field list
  175. } catch (Exception $e) {
  176. DBG::log($e);
  177. throw $e;
  178. }
  179. DBG::log($searchParams, 'string', 'getItems - $searchParams');
  180. $queryFeatures = $acl->buildQuery($searchParams);
  181. $items = $queryFeatures->getItems();
  182. DBG::log($items, 'array', 'getItems - $items');
  183. header('Content-type: application/xml; charset=utf-8');
  184. // echo "\$args['filterFields']: ";print_r($args['filterFields']);echo "\$searchParams['cols']: ";print_r($searchParams['cols']);die("");
  185. $xmlWriter = new Core_XmlWriter();
  186. $xmlWriter->openUri('php://output');
  187. // $xmlWriter->openMemory();// DBG
  188. $xmlWriter->setIndent(true);
  189. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  190. $xmlWriter->startDocument('1.0','UTF-8');
  191. //$xmlWriter->startElementNS('wfs', 'FeatureCollection', 'http://www.opengis.net/wfs');
  192. $xmlWriter->startElement('wfs:FeatureCollection');
  193. // $xmlWriter->writeAttributeNS('xmlns', 'wfs', 'http://www.w3.org/2000/xmlns/', 'http://www.opengis.net/wfs');
  194. $xmlWriter->writeAttribute('xmlns:wfs', 'http://www.opengis.net/wfs');
  195. $xmlWriter->writeAttribute('xmlns', 'http://www.opengis.net/wfs');
  196. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  197. $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  198. $xmlWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
  199. $xlmns = [];
  200. $xlmns[ $wfsNs ] = $wfsNsUri;
  201. if (!$simple) $xlmns[ $rootWfsNs ] = $rootWfsNsUri; // $xmlWriter->writeAttribute('xmlns:p5', Api_WfsNs::getBaseWfsUri());
  202. foreach ($schemaCache as $childSchema) {
  203. $xlmns[ $childSchema['nsPrefix'] ] = "{$rootWfsNsUri}/" . str_replace('__x3A__', '/', $childSchema['nsPrefix']);
  204. }
  205. foreach ($xlmns as $prefixXmlns => $urlXmlns) {
  206. $xmlWriter->writeAttribute("xmlns:{$prefixXmlns}", $urlXmlns);
  207. }
  208. $xmlWriter->writeAttribute('xsi:schemaLocation', "{$wfsNsUri} {$featureTypeUri}"); // TODO: BUG $wfsNsUri
  209. $xmlWriter->writeAttribute('numberMatched', 'unknown'); // TODO: return total items if simple query (without prefix, small total number, maxFeatures set, etc.)
  210. // NOTE: for client: if numberMatched == 'unknown' then request with resultType = 'hits'
  211. $xmlWriter->writeAttribute('numberReturned', count($items));
  212. $tblName = $acl->getName();
  213. $primaryKeyField = $acl->getPrimaryKeyField();
  214. foreach ($items as $item) {
  215. $itemKey = V::get($primaryKeyField, '', $item);
  216. if (!is_array($item)) $item = (array)$item;
  217. if (!empty($geomFld)) DBG::log($item[$geomFld], 'array', "item[{$itemKey}] ({$geomFld})isEmpty(".empty($item[$geomFld])."):");
  218. DBG::log($item, 'array' , ">>> loop({$itemKey})");
  219. DBG::log($searchParams['cols'], 'array' , "\$searchParams['cols']");
  220. $xmlWriter->startElement('gml:featureMember');
  221. Api_Wfs_GetFeature::printXmlFeatureRecurse($xmlWriter, $acl, $item, [
  222. 'fields' => $searchParams['cols'],
  223. 'tagName' => "{$wfsNs}:{$type}",
  224. 'xsdAttributes' => array_merge(
  225. [ 'fid' => "{$type}.{$itemKey}" ],
  226. (!$simple)
  227. ? [ "{$rootWfsNs}:web_link" => Request::getPathUri() . "index.php?_route=ViewTableAjax&namespace=" . $acl->getNamespace() . "#EDIT/{$itemKey}" ]
  228. : []
  229. ),
  230. 'showAdvancedAttrs' => !$simple,
  231. 'outputBlobFormat' => $args['outputBlobFormat'],
  232. ], $schemaCache);
  233. $xmlWriter->endElement();// gml:featureMember
  234. }
  235. $xmlWriter->endElement();// wfs:FeatureCollection
  236. $xmlWriter->endDocument();
  237. exit;
  238. }
  239. public function describeFeatureTypeAction() {
  240. $type = V::get('TYPENAME', '', $_REQUEST);
  241. if (empty($type)) {
  242. $reqContent = Request::getRequestBody();
  243. if (!empty($reqContent)) {
  244. return $this->_parseDescribeFeatureTypeRequest($reqContent);
  245. } else {
  246. return $this->_getDescribeFeatureAllTypes();
  247. }
  248. //throw new HttpException("Wrong param TYPENAME", 400);
  249. }
  250. $typeEx = explode(':', $type);
  251. if (count($typeEx) != 2) throw new HttpException("Wrong param TYPENAME", 400);
  252. return $this->_getDescribeFeatureType($typeEx[0], $typeEx[1]);
  253. }
  254. public function describeFeatureTypeAdvancedAction() {
  255. $typeName = V::geti('TYPENAME', '', $_REQUEST);
  256. if (empty($typeName)) {
  257. $reqContent = Request::getRequestBody();
  258. if (!empty($reqContent)) {
  259. return $this->_parseDescribeFeatureTypeRequest($reqContent, $simple = false);
  260. } else {
  261. return $this->_getDescribeFeatureAllTypes($simple = false);
  262. }
  263. //throw new HttpException("Wrong param TYPENAME", 400);
  264. }
  265. if (false === strpos($typeName, ':')) throw new HttpException("Wrong param TYPENAME", 400);
  266. list($nsPrefix, $name) = explode(':', $typeName);
  267. if ('/@instance' == strtolower(substr($name, -1 * strlen('/@instance')))) {
  268. return $this->_describeInstanceAttributeTable($nsPrefix, substr($name, 0, -1 * strlen('/@instance')));
  269. }
  270. return $this->_getDescribeFeatureType($nsPrefix, $name, $simple = false);
  271. }
  272. public function getCapabilitiesAction() {
  273. $wfsServerUrl = $this->getBaseUri();
  274. $serviceTitle = "Web Feature Service";
  275. $serviceDescription = "This is the reference implementation of WFS 1.0.0 and WFS 1.1.0, supports all WFS operations including Transaction.";
  276. $idDefaultDB = DB::getPDO()->getZasobId();
  277. $aclList = array_filter($this->_usrAcl->getTablesAcl(), function ($acl) use ($idDefaultDB) {
  278. // // $dataSourceName = 'default_db';// TODO: getSourceName
  279. // // $tblName = $tblAcl->getName();
  280. // // try {
  281. // // $acl = $this->getAclFromTypeName($typeName = "p5_{$dataSourceName}:{$tblName}");
  282. // // } catch (Exception $e) {
  283. // // // echo "Error for table({$tblName}): " . $e->getMessage() . "\n";
  284. // // }
  285. // // if (!$acl) {
  286. // // // TODO: error log msg
  287. // // return false;
  288. // // }
  289. return ($idDefaultDB == $acl->getDB()); // hide non default_db tables
  290. });
  291. switch (V::get('outputFormat', 'xml', $_GET)) {
  292. case 'csv': {
  293. (new Api_Wfs_GetCapabilities)->getCapabilitiesCsv($wfsServerUrl, $serviceTitle, $serviceDescription, $aclList);
  294. } break;
  295. case 'xml': {
  296. (new Api_Wfs_GetCapabilities)->getCapabilitiesXml($wfsServerUrl, $serviceTitle, $serviceDescription, $aclList);
  297. } break;
  298. default: throw new Api_WfsException("Not Implemented outputFormat", 501); // , null, 'NotImplemented', 'request');
  299. }
  300. exit;
  301. }
  302. public function GetBlobAction() {
  303. $namespace = V::get('namespace', '', $_GET);
  304. if (!$namespace) throw new Exception("Missing namespace");
  305. $primaryKey = V::get('primaryKey', 0, $_GET, 'int');
  306. if ($primaryKey < 0) throw new Exception("Missing primaryKey");
  307. $fieldName = V::get('fieldName', '', $_GET);
  308. if (!$fieldName) throw new Exception("Missing fieldName");
  309. $acl = Core_AclHelper::getAclByNamespace($namespace);
  310. $idDatabase = $acl->getDatabaseID();
  311. $rootTableName = $acl->getRootTableName();
  312. $sqlFieldName = $acl->getSqlFieldName($fieldName);
  313. $sqlPkField = $acl->getSqlPrimaryKeyField();
  314. $item = $acl->getItem($primaryKey);
  315. if (!$item) throw new Exception("Record not exists '{$primaryKey}'");
  316. if (!$acl->canReadObjectField($fieldName, $item)) throw new Exception("Access Denied for field '{$fieldName}'");
  317. $content = DB::getPDO($idDatabase)->getBlob($rootTableName, $sqlFieldName, $sqlPkField, $primaryKey);
  318. if (empty($content)) throw new Exception("Brak danych");
  319. $finfo = finfo_open(FILEINFO_MIME);
  320. $mime = finfo_buffer($finfo, $content);
  321. // $mime = "application/octet-stream";
  322. header("Content-type: {$mime}");
  323. // header("Content-Disposition: attachment; filename=\"{$fileName}\";" );
  324. // header("Content-Transfer-Encoding: binary");
  325. // header("Content-Length: ".strlen($content));
  326. print $content;
  327. exit;
  328. }
  329. }