WfsDataServer.php 17 KB

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