ParseOgcFilter.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. <?php
  2. Lib::loadClass('SqlQueryWhereBuilder');
  3. Lib::loadClass('Api_WfsException');
  4. // WFS 1.1 - traverseXlinkDepth, traverseXlinkExpiry http://docs.opengeospatial.org/is/04-094r1/04-094r1.html#50
  5. // WFS 2.0 - resolve, resolveDepth, resolveTimeout http://docs.opengeospatial.org/is/09-025r2/09-025r2.html#57
  6. // WFS 1.1 traverseXlinkDepth type="string" ('*' or int > 0) - recurse limit ('*' - no limit)
  7. // WFS 1.1 traverseXlinkExpiry type="xsd:positiveInteger" - timeOut in minutes
  8. // WFS 1.1 Note: traverse used in wfs:GetFeature or inside wfs:Query tag wfs:XlinkPropertyName (same like wfs:PropertyName but with @traverse* attributes)
  9. // WFS 2.0 resolve type="wfs:ResolveValueType" default="none" (enum: 'local', 'remote', 'all', 'none')
  10. // - resolve="local" - operation shall only resolve local references
  11. // - resolve="remote" - operation shall only resolve remote resource references
  12. // - resolve="all" - means that an operation shall resolve all resource references
  13. // - resolve="none" - means that an operation shall not resolve any resource references
  14. // WFS 2.0 resolveDepth type="wfs:positiveIntegerWithStar" default="*" ('*' or int > 0) - recurse limit ('*' - no limit)
  15. // WFW 2.0 resolveTimeout type="xsd:positiveInteger" default="300" - timeOut in seconds
  16. // WFS 2.0 Note: resolve used in wfs:GetFeature or inside wfs:Query tag wfs:PropertyName
  17. // in wfs:PropertyName may use resolvePath - @see http://docs.opengeospatial.org/is/09-025r2/09-025r2.html#103
  18. // WFS 2.0 resolve, resolveDepth example http://grepcode.com/file/repo1.maven.org/maven2/org.jvnet.ogc/ogc-schemas/2.2.0/ogc/wfs/2.0/examples/GetFeature/GetFeature_12.xml
  19. /**
  20. * @see wfs 1.0 wfs:GetFeature schema: http://schemas.opengis.net/wfs/1.0.0/WFS-basic.xsd
  21. * @see docs wfs 1.1 http://docs.opengeospatial.org/is/04-094r1/04-094r1.html
  22. * wfs:GetFeature
  23. * wfs:Query [ maxOccurs => "unbounded", typeName [ use => "required" ] ]
  24. * ogc:PropertyName [ maxOccurs => "unbounded" ]
  25. * ogc:Filter [ maxOccurs => "1" ]
  26. * ogc:SortBy [ maxOccurs => "1" ]
  27. */
  28. /* TODO: fetch with recurse by global wfs:GetFeature attributes
  29. * @see "Example 11" in http://docs.opengeospatial.org/is/04-094r1/04-094r1.html
  30. <wfs:GetFeature traverseXlinkDepth="1" traverseXlinkExpiry="1"> ...
  31. */
  32. /* TODO: fetch with recurse by local wfs:XlinkPropertyName
  33. * @see "Example 12" in http://docs.opengeospatial.org/is/04-094r1/04-094r1.html
  34. <wfs:GetFeature>
  35. <wfs:Query typeName="Town">
  36. <wfs:PropertyName>gml:name</wfs:PropertyName>
  37. <wfs:XlinkPropertyName traverseXlinkDepth="2" traverseXlinkExpiry="2">gml:directedNode</wfs:XlinkPropertyName>
  38. */
  39. /* TODO: parse xlink query:
  40. <ogc:PropertyIsEqualTo>
  41. <ogc:PropertyName>File/@xlink:href</ogc:PropertyName>
  42. <ogc:Literal>https://biuro.biall-net.pl/wfs/objects#File.45</ogc:Literal>
  43. </ogc:PropertyIsEqualTo>
  44. * TODO: parse bbox query:
  45. <ogc:Filter xmlns:app="http://www.deegree.org/app" xmlns:gml="http://www.opengis.net/gml" xmlns:ogc="http://www.opengis.net/ogc">
  46. <ogc:BBOX>
  47. <ogc:PropertyName>app:geometry</ogc:PropertyName>
  48. <gml:Envelope>
  49. <gml:coord>
  50. <gml:X>343720</gml:X>
  51. <gml:Y>4374533</gml:Y>
  52. </gml:coord>
  53. <gml:coord>
  54. <gml:X>444136</gml:X>
  55. <gml:Y>4433308</gml:Y>
  56. </gml:coord>
  57. </gml:Envelope>
  58. </ogc:BBOX>
  59. </ogc:Filter>
  60. * TODO: in SqlQueryWhereBuilder split query for main database and join-ed db (right join in ref's)
  61. *
  62. * @usage:
  63. $parser = new ParseOgcFilter();
  64. $parser->loadOgcFilter($ogcFilter);
  65. $queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
  66. $query = $queryWhereBuilder->getQueryWhere('t');
  67. *
  68. * TODO: recurse query ProcesTree only to ProcesInit - skip childrens under ProcesInit
  69. * test xpath: //*[ not( __backRef/ns = 'PROCES_INIT' ) ]
  70. <ogc:Filter>
  71. <ogc:And>
  72. <ogc:Not>
  73. <ogc:PropertyName>//__backRef/namespace</ogc:PropertyName>
  74. <ogc:Literal>default_db/CRM_PROCES/ProcesInit</ogc:Literal>
  75. </ogc:Not>
  76. <ogc:PropertyIsNull>
  77. <ogc:PropertyName>PARENT_ID</ogc:PropertyName>
  78. </ogc:PropertyIsNull>
  79. </ogc:And>
  80. </ogc:Filter>
  81. *
  82. */
  83. class ParseOgcFilter {
  84. public $_ogcFilter = '';
  85. public function __construct() {
  86. }
  87. public function loadOgcFilter($ogcFilter) {
  88. // validate?
  89. $this->_ogcFilter = $ogcFilter;
  90. }
  91. public function convertToSqlQueryWhereBuilder() {
  92. $ogcFilterXmlString = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
  93. $ogcFilterXmlString .= <<<OGC_FILTER_XML_FILE
  94. <filter xmlns="https://biuro.biall-net.pl/SE/version-git/schema/filter.xsd"
  95. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  96. xmlns:ogc="http://www.opengis.net/ogc">
  97. {$this->_ogcFilter}
  98. </filter>
  99. OGC_FILTER_XML_FILE;
  100. $convertedGuiXml = $this->_convertOgcFilterToCmdList($ogcFilterXmlString);
  101. DBG::_('DBG_DS_OGC', '>1', "convertedGuiXml(".strlen($convertedGuiXml).")", $convertedGuiXml, __CLASS__, __FUNCTION__, __LINE__);
  102. $tags = array();
  103. $parserXml = xml_parser_create();
  104. xml_parser_set_option($parserXml, XML_OPTION_CASE_FOLDING, 0);
  105. xml_parser_set_option($parserXml, XML_OPTION_SKIP_WHITE, 1);
  106. if (0 == xml_parse_into_struct($parserXml, $convertedGuiXml, $tags)) {
  107. throw new Exception("Parse Request xml error #" . __LINE__ . ": parse converted transaction failed");
  108. }
  109. xml_parser_free($parserXml);
  110. if (empty($tags)) {
  111. throw new Exception("Parse Request xml error #" . __LINE__ . ": parse converted transaction returns empty structure");
  112. }
  113. $queryWhereBuilder = new SqlQueryWhereBuilder();
  114. foreach ($tags as $tag) {
  115. switch ($tag['tag']) {
  116. case 'filter': {// root tag
  117. }
  118. break;
  119. case 'sql_filter_comparisonFieldToValue': {
  120. $fieldName = V::get('fieldName', '', $tag['attributes']);
  121. $fieldFunction = V::get('fieldFunction', null, $tag['attributes']);
  122. $comparisonSign = V::get('comparisonSign', '', $tag['attributes']);
  123. $value = V::get('value', '', $tag['attributes']);
  124. DBG::_('DBG_DS_OGC', '>3', "sql_filter_comparisonFieldToValue comparisonSign", $comparisonSign, __CLASS__, __FUNCTION__, __LINE__);
  125. if ('like' == $comparisonSign) {
  126. $wildCard = V::get('wildCard', '', $tag['attributes']);
  127. $singleChar = V::get('singleChar', '', $tag['attributes']);
  128. $escapeChar = V::get('escapeChar', '', $tag['attributes']);
  129. $value = $this->_convertIsLikeToSql($value, $wildCard, $singleChar, $escapeChar);
  130. }
  131. DBG::_('DBG_DS_OGC', '>3', "sql_filter_comparisonFieldToValue value({$value})", null, __CLASS__, __FUNCTION__, __LINE__);
  132. if ($fieldFunction) {
  133. $queryWhereBuilder->addComparisonFieldFunToValue($fieldFunction, $fieldName, $comparisonSign, $value);
  134. } else {
  135. $queryWhereBuilder->addComparisonFieldToValue($fieldName, $comparisonSign, $value);
  136. }
  137. }
  138. break;
  139. case 'sql_filter_comparisonFieldIsNull': {
  140. $fieldName = V::get('fieldName', '', $tag['attributes']);
  141. $queryWhereBuilder->sql_filter_comparisonFieldIsNull($fieldName);
  142. }
  143. break;
  144. case 'sql_filter_openBlock': {
  145. $blockType = V::get('type', '', $tag['attributes']);
  146. DBG::_('DBG_DS_OGC', '>2', "sql_filter_openBlock block Type {$blockType} attrs", json_encode($tag), __CLASS__, __FUNCTION__, __LINE__);
  147. $queryWhereBuilder->openBlock($blockType);
  148. }
  149. break;
  150. case 'sql_filter_closeBlock': {
  151. $blockType = V::get('type', '', $tag['attributes']);
  152. $queryWhereBuilder->closeBlock($blockType);
  153. }
  154. break;
  155. case 'not_implemented_tag': {
  156. $tagName = V::get('name', '', $tag['attributes']);
  157. DBG::_('DBG_DS_OGC', '>1', "Not Implemented tag '{$tagName}'", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
  158. throw new Api_WfsException("Not Implemented tag '{$tagName}'", 501, null, 'NotImplementedOgcTag', 'request');
  159. }
  160. break;
  161. default: {
  162. DBG::_('DBG_DS_OGC', '>1', "TODO: tag {$tag['tag']}", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
  163. throw new HttpException("TODO: tag {$tag['tag']}", 501);
  164. }
  165. }
  166. }
  167. $queryWhereBuilder->parseQueryWhere();
  168. DBG::_('DBG_DS_OGC', '>1', "queryWhereBuilder", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
  169. return $queryWhereBuilder;
  170. }
  171. public function _convertIsLikeToSql($value, $wildCard, $singleChar, $escapeChar) {
  172. if (0 === strlen($wildCard)) throw new Exception("Missing wildCard in PropertyIsLike");
  173. if (0 === strlen($singleChar)) throw new Exception("Missing singleChar in PropertyIsLike");
  174. if (0 === strlen($escapeChar)) throw new Exception("Missing escapeChar in PropertyIsLike");
  175. // The <PropertyIsLike> element is intended to encode a character string comparison operator with pattern matching.
  176. // The pattern is defined by a combination of regular characters, the wildCard character, the singleChar character,
  177. // and the escapeChar character.
  178. // - wildCard (sql: '%') - matches zero or more characters
  179. // - singleChar (sql: '_') - matches exactly one character
  180. // - escapeChar (sql: '\') - is used to escape the meaning of the wildCard, singleChar and escapeChar itself
  181. // wildCard="*" singleChar="#" escapeChar="!" => sql: % _ \
  182. // '*ORMA!*' => '%ORMA\*'
  183. // TODO: BUG: singleChar="%23"
  184. // TODO: first replace every escapeChar
  185. $valLength = strlen($value);
  186. $parts = [ $value ];
  187. DBG::log($parts, 'array', "_convertIsLikeToSql('{$value}', '{$wildCard}', '{$singleChar}', '{$escapeChar}') - init");
  188. $parts = array_reduce($parts, function ($ret, $cur) use ($escapeChar, $wildCard) {
  189. if (is_array($cur)) { $ret[] = $cur; return $ret; }// SKIP SQL_...
  190. foreach (explode("{$escapeChar}{$wildCard}", $cur) as $idx => $p) {
  191. if ($idx > 0) $ret[] = [ $wildCard ];
  192. $ret[] = $p;
  193. }
  194. return $ret;
  195. }, []);
  196. DBG::log($parts, 'array', "_convertIsLikeToSql('{$value}', '{$wildCard}', '{$singleChar}', '{$escapeChar}') - pass split escape \$wildCard");
  197. $parts = array_reduce($parts, function ($ret, $cur) use ($escapeChar, $singleChar) {
  198. if (is_array($cur)) { $ret[] = $cur; return $ret; }// SKIP SQL_...
  199. foreach (explode("{$escapeChar}{$singleChar}", $cur) as $idx => $p) {
  200. if ($idx > 0) $ret[] = [ $singleChar ];
  201. $ret[] = $p;
  202. }
  203. return $ret;
  204. }, []);
  205. DBG::log($parts, 'array', "_convertIsLikeToSql('{$value}', '{$wildCard}', '{$singleChar}', '{$escapeChar}') - pass split escape \$singleChar");
  206. $parts = array_reduce($parts, function ($ret, $cur) use ($wildCard) {
  207. if (is_array($cur)) { $ret[] = $cur; return $ret; }// SKIP SQL_...
  208. foreach (explode("{$wildCard}", $cur) as $idx => $p) {
  209. if ($idx > 0) $ret[] = [ '%' ];
  210. $ret[] = $p;
  211. }
  212. return $ret;
  213. }, []);
  214. DBG::log($parts, 'array', "_convertIsLikeToSql('{$value}', '{$wildCard}', '{$singleChar}', '{$escapeChar}') - pass split escape \$wildCard");
  215. $parts = array_reduce($parts, function ($ret, $cur) use ($singleChar) {
  216. if (is_array($cur)) { $ret[] = $cur; return $ret; }// SKIP SQL_...
  217. foreach (explode("{$singleChar}", $cur) as $idx => $p) {
  218. if ($idx > 0) $ret[] = [ '_' ];
  219. $ret[] = $p;
  220. }
  221. return $ret;
  222. }, []);
  223. DBG::log($parts, 'array', "_convertIsLikeToSql('{$value}', '{$wildCard}', '{$singleChar}', '{$escapeChar}') - pass split escape \$singleChar");
  224. foreach ($parts as $idx => $cur) {
  225. if (is_array($cur)) continue;
  226. $parts[$idx] = str_replace('\\', '\\\\', $cur);
  227. }
  228. DBG::log($parts, 'array', "_convertIsLikeToSql('{$value}', '{$wildCard}', '{$singleChar}', '{$escapeChar}') - pass escape sql escape");
  229. foreach ($parts as $idx => $cur) {
  230. if (is_array($cur)) continue;
  231. $parts[$idx] = str_replace('%', '\\%', $cur);
  232. }
  233. DBG::log($parts, 'array', "_convertIsLikeToSql('{$value}', '{$wildCard}', '{$singleChar}', '{$escapeChar}') - pass escape sql wildCard");
  234. foreach ($parts as $idx => $cur) {
  235. if (is_array($cur)) continue;
  236. $parts[$idx] = str_replace('_', '\\_', $cur);
  237. }
  238. DBG::log($parts, 'array', "_convertIsLikeToSql('{$value}', '{$wildCard}', '{$singleChar}', '{$escapeChar}') - pass escape sql singleChar");
  239. foreach ($parts as $idx => $cur) {
  240. if (is_array($cur)) $parts[$idx] = $cur[0];
  241. }
  242. DBG::log(implode('', $parts), 'array', "_convertIsLikeToSql('{$value}', '{$wildCard}', '{$singleChar}', '{$escapeChar}') - END");
  243. return implode('', $parts);
  244. $valCharsAllowReplace = array(); for ($i = 0; $i < $valLength; $i++) $valCharsAllowReplace[] = true;
  245. {// escapeChar
  246. $lastOffset = 0;
  247. while (false !== ($pos = strpos($value, $escapeChar, $lastOffset))) {
  248. DBG::_('DBG_DS_OGC', '>3', "sql_filter_comparisonFieldToValue like value({$value}) escapeChar({$escapeChar}) pos({$pos}) lastOffset({$lastOffset})", null, __CLASS__, __FUNCTION__, __LINE__);
  249. $value[$pos] = '\\';
  250. $valCharsAllowReplace[$pos] = false;
  251. if ($pos + 1 < $valLength) $valCharsAllowReplace[$pos + 1] = false;
  252. $lastOffset = $pos + 1;
  253. }
  254. }
  255. {// singleChar
  256. $lastOffset = 0;
  257. while (false !== ($pos = strpos($value, $singleChar, $lastOffset))) {
  258. DBG::_('DBG_DS_OGC', '>3', "sql_filter_comparisonFieldToValue like value({$value}) singleChar({$singleChar}) pos({$pos}) lastOffset({$lastOffset})", null, __CLASS__, __FUNCTION__, __LINE__);
  259. if ($valCharsAllowReplace[$pos]) {
  260. $value[$pos] = '_';
  261. $valCharsAllowReplace[$pos] = false;
  262. }
  263. $lastOffset = $pos + 1;
  264. }
  265. }
  266. {// wildCard
  267. $lastOffset = 0;
  268. while (false !== ($pos = strpos($value, $wildCard, $lastOffset))) {
  269. DBG::_('DBG_DS_OGC', '>3', "sql_filter_comparisonFieldToValue like value({$value}) wildCard({$wildCard}) pos({$pos}) lastOffset({$lastOffset})", null, __CLASS__, __FUNCTION__, __LINE__);
  270. if ($valCharsAllowReplace[$pos]) {
  271. $value[$pos] = '%';
  272. $valCharsAllowReplace[$pos] = false;
  273. }
  274. $lastOffset = $pos + 1;
  275. }
  276. }
  277. return $value;
  278. }
  279. public function _convertOgcFilterToCmdList($ogcFilterXmlString) {
  280. $convertOgcFilterXslString = @file_get_contents(APP_PATH_SCHEMA . DS . 'wfs' . DS . 'convertOgcFilterToXmlTaskList.xsl');
  281. if (false === $convertOgcFilterXslString) throw new HttpException("Cannot find file 'convertOgcFilter...'", 404);
  282. if (empty($convertOgcFilterXslString)) throw new HttpException("Empty file 'convertOgcFilter...'", 404);
  283. $requestXml = new DOMDocument();
  284. $isFileCorrect = @$requestXml->loadXml($ogcFilterXmlString);
  285. if (false === $isFileCorrect) throw new HttpException("Parse error for ogc filter", 400);
  286. $convertOgcFilterXsl = new DOMDocument();
  287. $isFileCorrect = @$convertOgcFilterXsl->loadXml($convertOgcFilterXslString);
  288. if (false === $isFileCorrect) throw new HttpException("Parse error for file 'convertOgcFilter...'", 500);
  289. $proc = new XSLTProcessor();
  290. $isImported = $proc->importStylesheet($convertOgcFilterXsl);
  291. if (false === $isImported) throw new HttpException("XSLT Parse error for import 'convertOgcFilter...'", 500);
  292. return $proc->transformToXML($requestXml);
  293. }
  294. }