WfsDataServer.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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'];// featureID
  163. if (!empty($args['bbox'])) $searchParams['f_the_geom'] = "BBOX:{$args['bbox']}";
  164. DBG::log($args, 'array', "\$args");
  165. $schemaCache = array();
  166. Lib::loadClass('Api_Wfs_GetFeature');
  167. try {
  168. $searchParams['cols'] = Api_Wfs_GetFeature::convertOgcPropertyListToFeatureQueryCols($schemaCache, $args['filterFields'], $acl); // convert $args['filterFields'] to field list
  169. } catch (Exception $e) {
  170. DBG::log($e);
  171. throw $e;
  172. }
  173. DBG::log($searchParams, 'string', 'getItems - $searchParams');
  174. $queryFeatures = $acl->buildQuery($searchParams);
  175. $items = $queryFeatures->getItems();
  176. DBG::log($items, 'array', 'getItems - $items');
  177. header('Content-type: application/xml; charset=utf-8');
  178. // echo "\$args['filterFields']: ";print_r($args['filterFields']);echo "\$searchParams['cols']: ";print_r($searchParams['cols']);die("");
  179. $xmlWriter = new Core_XmlWriter();
  180. $xmlWriter->openUri('php://output');
  181. // $xmlWriter->openMemory();// DBG
  182. $xmlWriter->setIndent(true);
  183. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  184. $xmlWriter->startDocument('1.0','UTF-8');
  185. //$xmlWriter->startElementNS('wfs', 'FeatureCollection', 'http://www.opengis.net/wfs');
  186. $xmlWriter->startElement('wfs:FeatureCollection');
  187. // $xmlWriter->writeAttributeNS('xmlns', 'wfs', 'http://www.w3.org/2000/xmlns/', 'http://www.opengis.net/wfs');
  188. $xmlWriter->writeAttribute('xmlns:wfs', 'http://www.opengis.net/wfs');
  189. $xmlWriter->writeAttribute('xmlns', 'http://www.opengis.net/wfs');
  190. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  191. $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  192. $xmlWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
  193. $xlmns = [];
  194. $xlmns[ $wfsNs ] = $wfsNsUri;
  195. if (!$simple) $xlmns[ $rootWfsNs ] = $rootWfsNsUri; // $xmlWriter->writeAttribute('xmlns:p5', Api_WfsNs::getBaseWfsUri());
  196. foreach ($schemaCache as $childSchema) {
  197. $xlmns[ $childSchema['nsPrefix'] ] = "{$rootWfsNsUri}/" . str_replace('__x3A__', '/', $childSchema['nsPrefix']);
  198. }
  199. foreach ($xlmns as $prefixXmlns => $urlXmlns) {
  200. $xmlWriter->writeAttribute("xmlns:{$prefixXmlns}", $urlXmlns);
  201. }
  202. $xmlWriter->writeAttribute('xsi:schemaLocation', "{$wfsNsUri} {$featureTypeUri}"); // TODO: BUG $wfsNsUri
  203. $xmlWriter->writeAttribute('numberMatched', 'unknown'); // TODO: return total items if simple query (without prefix, small total number, maxFeatures set, etc.)
  204. // NOTE: for client: if numberMatched == 'unknown' then request with resultType = 'hits'
  205. $xmlWriter->writeAttribute('numberReturned', count($items));
  206. $tblName = $acl->getName();
  207. $primaryKeyField = $acl->getPrimaryKeyField();
  208. foreach ($items as $item) {
  209. $itemKey = V::get($primaryKeyField, '', $item);
  210. if (!is_array($item)) $item = (array)$item;
  211. if (!empty($geomFld)) DBG::log($item[$geomFld], 'array', "item[{$itemKey}] ({$geomFld})isEmpty(".empty($item[$geomFld])."):");
  212. DBG::log($item, 'array' , ">>> loop({$itemKey})");
  213. DBG::log($searchParams['cols'], 'array' , "\$searchParams['cols']");
  214. $xmlWriter->startElement('gml:featureMember');
  215. Api_Wfs_GetFeature::printXmlFeatureRecurse($xmlWriter, $acl, $item, [
  216. 'fields' => $searchParams['cols'],
  217. 'tagName' => "{$wfsNs}:{$type}",
  218. 'xsdAttributes' => array_merge(
  219. [ 'fid' => "{$type}.{$itemKey}" ],
  220. (!$simple)
  221. ? [ "{$rootWfsNs}:web_link" => Request::getPathUri() . "index.php?_route=ViewTableAjax&namespace=" . $acl->getNamespace() . "#EDIT/{$itemKey}" ]
  222. : []
  223. ),
  224. 'showAdvancedAttrs' => !$simple,
  225. 'outputBlobFormat' => $args['outputBlobFormat'],
  226. ], $schemaCache);
  227. $xmlWriter->endElement();// gml:featureMember
  228. }
  229. $xmlWriter->endElement();// wfs:FeatureCollection
  230. $xmlWriter->endDocument();
  231. exit;
  232. }
  233. public function describeFeatureTypeAction() {
  234. $type = V::get('TYPENAME', '', $_REQUEST);
  235. if (empty($type)) {
  236. $reqContent = Request::getRequestBody();
  237. if (!empty($reqContent)) {
  238. return $this->_parseDescribeFeatureTypeRequest($reqContent);
  239. } else {
  240. return $this->_getDescribeFeatureAllTypes();
  241. }
  242. //throw new HttpException("Wrong param TYPENAME", 400);
  243. }
  244. $typeEx = explode(':', $type);
  245. if (count($typeEx) != 2) throw new HttpException("Wrong param TYPENAME", 400);
  246. return $this->_getDescribeFeatureType($typeEx[0], $typeEx[1]);
  247. }
  248. public function describeFeatureTypeAdvancedAction() {
  249. $typeName = V::geti('TYPENAME', '', $_REQUEST);
  250. if (empty($typeName)) {
  251. $reqContent = Request::getRequestBody();
  252. if (!empty($reqContent)) {
  253. return $this->_parseDescribeFeatureTypeRequest($reqContent, $simple = false);
  254. } else {
  255. return $this->_getDescribeFeatureAllTypes($simple = false);
  256. }
  257. //throw new HttpException("Wrong param TYPENAME", 400);
  258. }
  259. if (false === strpos($typeName, ':')) throw new HttpException("Wrong param TYPENAME", 400);
  260. list($nsPrefix, $name) = explode(':', $typeName);
  261. if ('/@instance' == strtolower(substr($name, -1 * strlen('/@instance')))) {
  262. return $this->_describeInstanceAttributeTable($nsPrefix, substr($name, 0, -1 * strlen('/@instance')));
  263. }
  264. return $this->_getDescribeFeatureType($nsPrefix, $name, $simple = false);
  265. }
  266. public function getCapabilitiesAction() {
  267. $wfsServerUrl = $this->getBaseUri();
  268. $serviceTitle = "Web Feature Service";
  269. $serviceDescription = "This is the reference implementation of WFS 1.0.0 and WFS 1.1.0, supports all WFS operations including Transaction.";
  270. $idDefaultDB = DB::getPDO()->getZasobId();
  271. $aclList = array_filter($this->_usrAcl->getTablesAcl(), function ($acl) use ($idDefaultDB) {
  272. // // $dataSourceName = 'default_db';// TODO: getSourceName
  273. // // $tblName = $tblAcl->getName();
  274. // // try {
  275. // // $acl = $this->getAclFromTypeName($typeName = "p5_{$dataSourceName}:{$tblName}");
  276. // // } catch (Exception $e) {
  277. // // // echo "Error for table({$tblName}): " . $e->getMessage() . "\n";
  278. // // }
  279. // // if (!$acl) {
  280. // // // TODO: error log msg
  281. // // return false;
  282. // // }
  283. return ($idDefaultDB == $acl->getDB()); // hide non default_db tables
  284. });
  285. switch (V::get('outputFormat', 'xml', $_GET)) {
  286. case 'csv': {
  287. (new Api_Wfs_GetCapabilities)->getCapabilitiesCsv($wfsServerUrl, $serviceTitle, $serviceDescription, $aclList);
  288. } break;
  289. case 'xml': {
  290. (new Api_Wfs_GetCapabilities)->getCapabilitiesXml($wfsServerUrl, $serviceTitle, $serviceDescription, $aclList);
  291. } break;
  292. default: throw new Api_WfsException("Not Implemented outputFormat", 501); // , null, 'NotImplemented', 'request');
  293. }
  294. exit;
  295. }
  296. public function GetBlobAction() {
  297. $namespace = V::get('namespace', '', $_GET);
  298. if (!$namespace) throw new Exception("Missing namespace");
  299. $primaryKey = V::get('primaryKey', 0, $_GET, 'int');
  300. if ($primaryKey < 0) throw new Exception("Missing primaryKey");
  301. $fieldName = V::get('fieldName', '', $_GET);
  302. if (!$fieldName) throw new Exception("Missing fieldName");
  303. $acl = Core_AclHelper::getAclByNamespace($namespace);
  304. $idDatabase = $acl->getDatabaseID();
  305. $rootTableName = $acl->getRootTableName();
  306. $sqlFieldName = $acl->getSqlFieldName($fieldName);
  307. $sqlPkField = $acl->getSqlPrimaryKeyField();
  308. $item = $acl->getItem($primaryKey);
  309. if (!$item) throw new Exception("Record not exists '{$primaryKey}'");
  310. if (!$acl->canReadObjectField($fieldName, $item)) throw new Exception("Access Denied for field '{$fieldName}'");
  311. $content = DB::getPDO($idDatabase)->getBlob($rootTableName, $sqlFieldName, $sqlPkField, $primaryKey);
  312. if (empty($content)) throw new Exception("Brak danych");
  313. $finfo = finfo_open(FILEINFO_MIME);
  314. $mime = finfo_buffer($finfo, $content);
  315. // $mime = "application/octet-stream";
  316. header("Content-type: {$mime}");
  317. // header("Content-Disposition: attachment; filename=\"{$fileName}\";" );
  318. // header("Content-Transfer-Encoding: binary");
  319. // header("Content-Length: ".strlen($content));
  320. print $content;
  321. exit;
  322. }
  323. }