ParseOgcFilter.php 13 KB

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