WfsServerBase.php 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  1. <?php
  2. Lib::loadClass('Api_WfsException');
  3. Lib::loadClass('Api_WfsGeomTypeConverter');
  4. Lib::loadClass('Api_WfsNs');
  5. Lib::loadClass('Request');
  6. Lib::loadClass('Core_AclHelper');
  7. Lib::loadClass('Core_XmlWriter');
  8. class Api_WfsServerBase {
  9. public $_usrAcl;
  10. public $_typeConverter;
  11. public $_apiBaseUri;
  12. protected $_logFile;
  13. public function __construct($usrAcl) {
  14. $this->_usrAcl = $usrAcl;
  15. $this->_typeConverter = new Api_WfsGeomTypeConverter();
  16. $this->_apiBaseUri = '';
  17. }
  18. public function setBaseUri($uri) {
  19. $this->_apiBaseUri = $uri;
  20. }
  21. public function getBaseUri() {// TODO: RMME
  22. return $this->_apiBaseUri;
  23. }
  24. /**
  25. * @param string $typeName - 'p5_default_db:TEST_PERMS'
  26. */
  27. public function getAclFromTypeName($typeName) {
  28. try { // TODO: use object cache `CRM_#CACHE_ACL_OBJECT`
  29. $namespace = str_replace([':', '__x3A__'], '/', $typeName);
  30. if ('p5_' === substr($namespace, 0, 3)) $namespace = substr($namespace, 3);
  31. Lib::loadClass('SchemaFactory');
  32. $objItem = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, ['propertyName'=>"*,field"]);
  33. DBG::log($objItem, 'array', "DBG objItem({$namespace})");
  34. if (!$objItem['idZasob']) throw new Exception("Missing idZasob for namespace '{$namespace}'");
  35. if (!in_array($objItem['_type'], [
  36. // 'TableAcl', // TODO: TEST - to replace TableAcl by AntAcl or use object with namespace + '/tableName'?
  37. 'AntAcl',
  38. ])) throw new Exception("Not Implemented acl type '{$objItem['_type']}'");
  39. if (!$objItem['isObjectActive']) {
  40. if (!$objItem['hasStruct']) throw new Exception("namespace has no structure '{$namespace}'");
  41. if (!$objItem['isStructInstalled']) throw new Exception("namespace structure not installed '{$namespace}'");
  42. throw new Exception("namespace is not activated '{$namespace}'");
  43. }
  44. Lib::loadClass('AntAclBase');
  45. $acl = AntAclBase::buildInstance($objItem['idZasob'], $objItem);
  46. return $acl;
  47. } catch (Exception $e) {
  48. DBG::log($e);
  49. }
  50. $typeEx = explode(':', $typeName);
  51. $sourceName = $typeEx[0];
  52. $objName = $typeEx[1];
  53. if (2 != count($typeEx)) throw new Api_WfsException("Could not get acl for '{$typeName}' - syntax error");
  54. if ('p5_' == substr($sourceName, 0, 3)) $sourceName = substr($sourceName, 3);// remove prefix 'p5_'
  55. $acl = $this->_usrAcl->getObjectAcl($sourceName, $objName);
  56. $forceTblAclInit = 0;//('1' == V::get('_force', '', $_GET));
  57. $acl->init($forceTblAclInit);
  58. return $acl;
  59. }
  60. public function _getXmlSchemaLocation() {
  61. $schemaLocations = array();
  62. //$schemaLocations[] = 'http://www.opengis.net/wfs http://webgis.regione.sardegna.it:80/geoserver/schemas/wfs/1.0.0/WFS-capabilities.xsd';// @from http://webgis.regione.sardegna.it/geoserver/ows?service=WFS&request=GetCapabilities
  63. return (!empty($schemaLocations))? 'xsi:schemaLocation="' . implode(' ', $schemaLocations) . '"' : '';
  64. }
  65. public function _printXmlNamespaceList() {
  66. $listNs = array();
  67. foreach (Api_WfsNs::getNsList() as $uri => $prefix) {
  68. $listNs[] = 'xmlns:' . $prefix . '="' . $uri . '"';
  69. }
  70. return implode("\n", $listNs);
  71. }
  72. public function _getSourceNsList() {
  73. $usrObjList = array();
  74. $tblsAcl = $this->_usrAcl->getTablesAcl();
  75. foreach ($tblsAcl as $tblAcl) {
  76. $dataSourceName = 'default_db';// TODO: getSourceName
  77. $tblName = $tblAcl->getName();
  78. $usrObjList[] = array($dataSourceName, $tblName);
  79. }
  80. $usrObjList[] = array('objects', 'File');
  81. $usrObjList[] = array('objects', 'TestPerms');
  82. $usrObjList[] = array('objects', 'Korespondencja');
  83. return $usrObjList;
  84. }
  85. public function _parseTransactionXmlStruct($requestXml, $requestXmlTags) {
  86. $DBG = V::get('DBG_XML', 0, $_GET, 'int');// TODO: Profiler
  87. $rootTagName = V::get('tag', '', $requestXmlTags[0]);
  88. if ('Transaction' != $rootTagName) throw new Api_WfsException("Parse Request XML Error - Missing Transaction as root xml tag", __LINE__, null, 'TransactionParseError', 'request');
  89. // TODO: special actions if action on nested objects
  90. // 1. convert request: wfs.transaction.convert-wfs-request.xsl
  91. // 2. validate converted request: wfs.transaction-converted-request.xsd
  92. // 3. execute request in data source
  93. // if($DBG){echo 'L.' . __LINE__ . ' $requestXmlTags:';print_r($requestXmlTags);echo "\n";}
  94. /*
  95. <Transaction
  96. xmlns="http://www.opengis.net/wfs"
  97. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  98. version="1.0.0"
  99. service="WFS"
  100. xmlns:p5_objects="https://biuro.biall-net.pl/wfs/objects"
  101. xmlns:gml="http://www.opengis.net/gml">
  102. <Insert xmlns="http://www.opengis.net/wfs">
  103. <TestPerms xmlns="https://biuro.biall-net.pl/wfs/objects">
  104. <plik xmlns="https://biuro.biall-net.pl/wfs/objects">
  105. <p5_objects:File>
  106. <p5_objects:name>blank-wfs.gif</p5_objects:name>
  107. <p5_objects:content>R0lGODlhAQABAIAAAP///////yH+EUNyZWF0ZWQgd2l0aCBHSU1QACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==</p5_objects:content>
  108. </p5_objects:File>
  109. </plik>
  110. </TestPerms>
  111. </Insert>
  112. </Transaction>
  113. */
  114. $actionXmlTags = array();// // [ 0 => [ 'action'=>Insert, 'typeName'=>str, 'tags'=>[] ]
  115. {// split xml for action tags (Insert, Update, Delete)
  116. $tagsCount = count($requestXmlTags);
  117. for ($i = 1, $actionTagName = null, $actionIdx = -1, $tagLvl = 0; $i < $tagsCount - 1; $i++) {// skip Transaction open/close tag
  118. $tag = $requestXmlTags[$i];
  119. if (null == $actionTagName) {
  120. $actionTagName = $tag['tag'];
  121. $tagLvl = $tag['level'];
  122. $actionIdx += 1;
  123. $actionXmlTags[$actionIdx] = array();
  124. $actionXmlTags[$actionIdx]['action'] = $actionTagName;
  125. $actionXmlTags[$actionIdx]['typeName'] = V::get('typeName', '', $tag['attributes']);
  126. $actionXmlTags[$actionIdx]['isDeepObject'] = null;// null - unknown, false - not seed, true - deep
  127. $actionXmlTags[$actionIdx]['tags'] = array();
  128. } else if ($tag['tag'] == $actionTagName && 'close' == $tag['type'] && $tagLvl == $tag['level']) {
  129. $actionTagName = null;
  130. } else {
  131. $actionXmlTags[$actionIdx]['tags'][] = $tag;
  132. }
  133. }
  134. }
  135. {// Validate Request: WFS allow multiple tags inside Insert tag
  136. // TODO: implement multiple tags in Insert tag if reauired. Use array_splice($actionXmlTags, $actionIdx, 0, $insertTags);
  137. {// throw (Not Implemented, 501) if found multiple tags in Insert tag
  138. foreach ($actionXmlTags as $actionIdx => $action) {
  139. if ('Insert' !== $action['action']) continue;
  140. $lvl = $action['tags'][0]['level'];
  141. for ($i = 1, $cnt = count($action['tags']); $i < $cnt - 1; $i++) {
  142. $tag = $action['tags'][$i];
  143. // if($DBG){echo 'L.' . __LINE__ . " actionXmlTags loop({$i}) \$tag:";print_r($tag);echo "\n";}
  144. if ($tag['level'] == $lvl) throw new Exception("Error Processing Request - multiple tags inside Insert tag is not implemented", 501);
  145. }
  146. }
  147. }
  148. }
  149. {// Insert tag - fix typeName from first tag, remove first and last tag - leave only fields
  150. foreach ($actionXmlTags as $actionIdx => $action) {
  151. if ('Insert' !== $action['action']) continue;
  152. array_pop($action['tags']);// remove last tag (close tag)
  153. $tag = array_shift($action['tags']);// remove last tag (close tag)
  154. $typeName = $tag['tag'];// eg. with prefix 'p5_objects:File' or without prefix but with @xmlns
  155. if (false === strpos($typeName, ':')) {
  156. $nsType = V::get('xmlns', '', $tag['attributes']);
  157. if (!$nsType) throw new Exception("Error Processing Request - Missing object namespace '{$tag['tag']}'");
  158. $prefix = Api_WfsNs::getNsPrefix($nsType);
  159. if (!$prefix) {
  160. if ($typeName == substr(rtrim($nsType, '/'), -1 * strlen($typeName))) {// typeName may be added to ns uri
  161. $nsBaseForType = substr(rtrim($nsType, '/'), 0, -1 * strlen($typeName) - 1);
  162. $prefix = Api_WfsNs::getNsPrefix($nsBaseForType);
  163. }
  164. }
  165. if (!$prefix) throw new Exception("Error Processing Request - Unrecognized namespace uri '{$nsType}' for object '{$tag['tag']}'");
  166. $typeName = "{$prefix}:{$typeName}";
  167. }
  168. $action['typeName'] = $typeName;
  169. $actionXmlTags[$actionIdx] = $action;
  170. }
  171. }
  172. {// validate
  173. // if($DBG){echo 'L.' . __LINE__ . ' before validate $actionXmlTags:';print_r($actionXmlTags);echo "\n";}
  174. foreach ($actionXmlTags as $actionIdx => $action) {
  175. if ('Insert' == $action['action']) {
  176. if (empty($action['typeName'])) throw new Exception("Error Processing Request - unknown object typeName to Insert");
  177. $acl = $this->getAclFromTypeName($action['typeName']);
  178. $actionXmlTags[$actionIdx] = $acl->validateInsertXml($action);
  179. } else if ('Update' == $action['action']) {
  180. $acl = $this->getAclFromTypeName($action['typeName']);
  181. $actionXmlTags[$actionIdx] = $acl->validateUpdateXml($action);
  182. } else if ('Delete' == $action['action']) {
  183. if($DBG>1){echo'<pre>$action: ';print_r($action);echo'</pre>';}
  184. $acl = $this->getAclFromTypeName($action['typeName']);
  185. $actionXmlTags[$actionIdx] = $acl->validateDeleteXml($action);
  186. } else {
  187. if($DBG>1){echo'<pre>$action: ';print_r($action);echo'</pre>';}
  188. throw new Exception("{$action['action']} action not implemented", 501);
  189. }
  190. // continue;// TODO: validate all by type
  191. }
  192. }
  193. if ('1' == V::get('DBG_DONT_CHANGE_DB', '', $_REQUEST)) {
  194. echo "----------------- action xml tags: ---------------" . "\n";
  195. print_r($actionXmlTags);
  196. die(".EOF\n");
  197. }
  198. {// execute
  199. $returnIds = array();
  200. $changesList = array();
  201. foreach ($actionXmlTags as $actionIdx => $action) {
  202. if ('Insert' == $action['action']) {
  203. if (empty($action['typeName'])) throw new Exception("Error Processing Request - unknown object typeName to Insert");
  204. $acl = $this->getAclFromTypeName($action['typeName']);
  205. $newId = $acl->insertXml($action);
  206. $returnIds[$actionIdx] = $newId;
  207. $changesList[$actionIdx] = array('Status'=>(($newId > 0)? 'SUCCESS' : 'FAILED'), 'Message'=>"created {$newId}.", 'Action' => $action['action']);
  208. if ($newId > 0) $changesList[$actionIdx]['fid'] = $acl->getName() . '.' . $newId;
  209. } else if ('Update' == $action['action']) {
  210. if($DBG>1){echo'<pre>$action: ';print_r($action);echo'</pre>';}
  211. $acl = $this->getAclFromTypeName($action['typeName']);
  212. $affected = $acl->updateXml($action);
  213. $changesList[$actionIdx] = array('Status'=>(($affected >= 0)? 'SUCCESS' : 'FAILED'), 'Message'=>"affected {$affected}.", 'Action' => $action['action']);
  214. } else if ('Delete' == $action['action']) {
  215. $acl = $this->getAclFromTypeName($action['typeName']);
  216. $affected = $acl->deleteXml($action);
  217. $changesList[$actionIdx] = array('Status'=>(($affected >= 0)? 'SUCCESS' : 'FAILED'), 'Message'=>"deleted {$affected}.", 'Action' => $action['action']);
  218. } else throw new Exception("TODO: {$action['action']} action not implemented", 501);
  219. }
  220. if($DBG){echo 'L.' . __LINE__ . ' $changesList:';print_r($changesList);echo "\n";}
  221. }
  222. return $this->_transactionResponse($changesList);
  223. }
  224. public function _transactionResponse($changesList) {
  225. // <WFS_TransactionResponse>
  226. // <TransactionResult>
  227. // <Status> : SUCCESS / FAILED / PARTIAL
  228. // [<Locator]
  229. // [<Message]
  230. $messageTag = '';
  231. $statusTag = '';
  232. $statusIsFailed = false;
  233. $statusAll = null;
  234. $createdFeatureId = array();
  235. foreach ($changesList as $featureId => $change) {
  236. if ('FAILED' == $change['Status']) {
  237. $statusIsFailed = true;
  238. }
  239. if ('SUCCESS' == $change['Status'] && !empty($change['fid'])) {
  240. $createdFeatureId[] = $change['fid'];
  241. }
  242. // if (!empty($change['Message'])) $messageTag .= "Feature '{$featureId}' {$change['Status']}: {$change['Message']}\n";
  243. }
  244. $statusTag = ($statusIsFailed)? 'FAILED' : 'SUCCESS';
  245. $statusTag = "<wfs:{$statusTag}/>";
  246. $messageTag = '';//"<wfs:Message>{$messageTag}</wfs:Message>";
  247. /* Example:
  248. <?xml version="1.0" encoding="UTF-8"?>
  249. <wfs:WFS_TransactionResponse version="1.0.0" xmlns:wfs="http://www.opengis.net/wfs"
  250. xmlns:ogc="http://www.opengis.net/ogc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  251. xsi:schemaLocation="http://www.opengis.net/wfs http://localhost:8080/geoserver/schemas/wfs/1.0.0/WFS-transaction.xsd">
  252. <wfs:InsertResult>
  253. <ogc:FeatureId fid="archsites.26" />
  254. </wfs:InsertResult>
  255. <wfs:TransactionResult handle="Updating Signature rock label">
  256. <wfs:Status>
  257. <wfs:SUCCESS />
  258. </wfs:Status>
  259. </wfs:TransactionResult>
  260. </wfs:WFS_TransactionResponse>*/
  261. // TODO: build xml by DOMDocument
  262. // TODO: xsi:schemaLocation="http://www.opengis.net/wfs http://localhost:8080/geoserver/schemas/wfs/1.0.0/WFS-transaction.xsd"
  263. $wfsInsertResult = '';
  264. if (!empty($createdFeatureId)) {
  265. $wfsInsertResult = "\n<wfs:InsertResult>\n";
  266. foreach ($createdFeatureId as $fid) {
  267. $wfsInsertResult .= '<ogc:FeatureId fid="' . $fid . '" xmlns:ogc="http://www.opengis.net/ogc"/>' . "\n";
  268. }
  269. $wfsInsertResult .= "\n</wfs:InsertResult>\n";
  270. EOF;
  271. }
  272. $tranRes = <<<EOF
  273. <wfs:WFS_TransactionResponse version="1.0.0"
  274. xmlns:wfs="http://www.opengis.net/wfs"
  275. xmlns:ogc="http://www.opengis.net/ogc"
  276. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  277. {$wfsInsertResult}
  278. <wfs:TransactionResult>
  279. <wfs:Status>{$statusTag}</wfs:Status>
  280. {$messageTag}
  281. </wfs:TransactionResult>
  282. </wfs:WFS_TransactionResponse>
  283. EOF;
  284. return $tranRes;
  285. }
  286. public function _convertTransactionXml($requestXmlString, $sourceNsList) {
  287. $DBG = (V::get('DBG_XSL', '', $_GET) > 0);// TODO: Profiler
  288. if($DBG){echo 'L.' . __LINE__ . ' sourceNsList:';print_r($sourceNsList);echo "\n";}
  289. $updateActionsXsd = array();
  290. $insertActionsXsd = array();
  291. $deleteActionsXsd = array();
  292. //<!-- TODO: create tag Update{X} where X is namespace index -->
  293. foreach ($sourceNsList as $nsInd => $sourceNs) {
  294. // <Update>
  295. $theGeomField = 'the_geom';// TODO: get from fields list
  296. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  297. if($DBG){echo 'L.' . __LINE__ . ' typeName:';print_r($typeName);echo "\n";}
  298. $updateElementName = "UpdateNs{$nsInd}";
  299. $geomCoordsUpdateXpath = "//wfs:Value/*/gml:outerBoundaryIs/gml:LinearRing/gml:coordinates";
  300. $geomCoordsInsertXpath = "//*/gml:outerBoundaryIs/gml:LinearRing/gml:coordinates";
  301. $acl = $this->getAclFromTypeName($typeName);
  302. $geomType = $acl->getGeomFieldType($theGeomField);
  303. if ('polygon' == $geomType) {
  304. $geomCoordsUpdateXpath = ".//wfs:Value/*/gml:outerBoundaryIs/gml:LinearRing/gml:coordinates";
  305. $geomCoordsUpdateXpath = "((<xsl:value-of select=\"{$geomCoordsUpdateXpath}\"/>))";
  306. $geomCoordsInsertXpath = ".//*/gml:outerBoundaryIs/gml:LinearRing/gml:coordinates";
  307. $geomCoordsInsertXpath = "((<xsl:value-of select=\"{$geomCoordsInsertXpath}\"/>))";
  308. } else if ('linestring' == $geomType) {
  309. $geomCoordsUpdateXpath = ".//wfs:Value/*/gml:coordinates";
  310. $geomCoordsUpdateXpath = "(<xsl:value-of select=\"{$geomCoordsUpdateXpath}\"/>)";
  311. $geomCoordsInsertXpath = ".//*/gml:coordinates";
  312. $geomCoordsInsertXpath = "(<xsl:value-of select=\"{$geomCoordsInsertXpath}\"/>)";
  313. } else if ('point' == $geomType) {
  314. $geomCoordsUpdateXpath = ".//wfs:Value/*/gml:coordinates";
  315. $geomCoordsUpdateXpath = "(<xsl:value-of select=\"{$geomCoordsUpdateXpath}\"/>)";
  316. $geomCoordsInsertXpath = ".//*/gml:coordinates";
  317. $geomCoordsInsertXpath = "(<xsl:value-of select=\"{$geomCoordsInsertXpath}\"/>)";
  318. }
  319. $actionXsd = <<<EOF
  320. <xsl:when test="@typeName = '{$typeName}'">
  321. <xsl:element name="{$updateElementName}">
  322. <xsl:attribute name="typeName"><xsl:value-of select="@typeName" /></xsl:attribute>
  323. <xsl:attribute name="featureId"><xsl:value-of select="ogc:Filter/ogc:FeatureId/@fid" /></xsl:attribute>
  324. <xsl:for-each select="wfs:Property">
  325. <xsl:element name="{wfs:Name}">
  326. <xsl:choose>
  327. <xsl:when test="wfs:Name = '{$theGeomField}'"><xsl:value-of select="local-name(//wfs:Value/*[1])"/>{$geomCoordsUpdateXpath}</xsl:when>
  328. <xsl:otherwise><xsl:value-of select="wfs:Value"/></xsl:otherwise>
  329. </xsl:choose>
  330. </xsl:element>
  331. </xsl:for-each>
  332. </xsl:element>
  333. </xsl:when>
  334. EOF;
  335. $updateActionsXsd[] = $actionXsd;
  336. $typeName = "{$sourceNs[1]}";//"p5_{$sourceNs[0]}:{$sourceNs[1]}";
  337. $insertElementName = "InsertNs{$nsInd}";
  338. $actionXsd = <<<EOF
  339. <xsl:when test="local-name() = '{$typeName}'">
  340. <xsl:element name="{$insertElementName}">
  341. <xsl:attribute name="typeName"><xsl:value-of select="local-name()" /></xsl:attribute>
  342. <xsl:attribute name="typeNsUri"><xsl:value-of select="namespace-uri()" /></xsl:attribute>
  343. <xsl:for-each select="*">
  344. <xsl:element name="{local-name()}">
  345. <xsl:choose>
  346. <xsl:when test="local-name() = '{$theGeomField}'"><xsl:value-of select="local-name(*[1])"/>{$geomCoordsInsertXpath}</xsl:when>
  347. <xsl:otherwise><xsl:value-of select="."/></xsl:otherwise>
  348. </xsl:choose>
  349. </xsl:element>
  350. </xsl:for-each>
  351. </xsl:element>
  352. </xsl:when>
  353. EOF;
  354. $insertActionsXsd[] = $actionXsd;
  355. $deleteElementName = "DeleteNs{$nsInd}";
  356. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  357. $actionXsd = <<<EOF
  358. <xsl:when test="@typeName = '{$typeName}'">
  359. <xsl:variable name="typeName" select="@typeName" />
  360. <xsl:for-each select="ogc:Filter/ogc:FeatureId">
  361. <xsl:element name="{$deleteElementName}">
  362. <xsl:attribute name="typeName"><xsl:value-of select="\$typeName" /></xsl:attribute>
  363. <xsl:attribute name="featureId"><xsl:value-of select="@fid" /></xsl:attribute>
  364. </xsl:element>
  365. </xsl:for-each>
  366. </xsl:when>
  367. EOF;
  368. $deleteActionsXsd[] = $actionXsd;
  369. }
  370. if (!empty($updateActionsXsd)) {
  371. $updateActionsXsd = implode("\n", $updateActionsXsd);
  372. $updateActionsXsd = <<<EOF
  373. <xsl:choose>
  374. {$updateActionsXsd}
  375. </xsl:choose>
  376. EOF;
  377. } else {
  378. $updateActionsXsd = '';
  379. }
  380. if (!empty($insertActionsXsd)) {
  381. $insertActionsXsd = implode("\n", $insertActionsXsd);
  382. $insertActionsXsd = <<<EOF
  383. <xsl:choose>
  384. {$insertActionsXsd}
  385. </xsl:choose>
  386. EOF;
  387. } else {
  388. $insertActionsXsd = '';
  389. }
  390. if (!empty($deleteActionsXsd)) {
  391. $deleteActionsXsd = implode("\n", $deleteActionsXsd);
  392. $deleteActionsXsd = <<<EOF
  393. <xsl:choose>
  394. {$deleteActionsXsd}
  395. </xsl:choose>
  396. EOF;
  397. } else {
  398. $deleteActionsXsd = '';
  399. }
  400. $convertTransactionXslString = '<?xml version="1.0"?>';
  401. $convertTransactionXslString .= <<<EOF
  402. <xsl:transform version="1.0"
  403. xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  404. xmlns:wfs="http://www.opengis.net/wfs"
  405. xmlns:ogc="http://www.opengis.net/ogc"
  406. xmlns:gml="http://www.opengis.net/gml">
  407. <xsl:template match="/">
  408. <xsl:for-each select="wfs:Transaction">
  409. <Transaction>
  410. <xsl:attribute name="version"><xsl:value-of select="@version" /></xsl:attribute>
  411. <xsl:attribute name="service"><xsl:value-of select="@service" /></xsl:attribute>
  412. <xsl:for-each select="wfs:Update">
  413. {$updateActionsXsd}
  414. </xsl:for-each>
  415. <xsl:for-each select="wfs:Insert/*">
  416. {$insertActionsXsd}
  417. </xsl:for-each>
  418. <xsl:for-each select="wfs:Delete">
  419. {$deleteActionsXsd}
  420. </xsl:for-each>
  421. <!-- TODO: Native -->
  422. </Transaction>
  423. </xsl:for-each>
  424. </xsl:template>
  425. </xsl:transform>
  426. EOF;
  427. if($DBG){echo 'L.' . __LINE__ . ' $convertTransactionXslString:' . $convertTransactionXslString . "\n";}
  428. $requestXml = new DOMDocument();
  429. $requestXml->loadXml($requestXmlString);
  430. $convertTransactionXsl = new DOMDocument();
  431. $convertTransactionXsl->loadXml($convertTransactionXslString);
  432. $proc = new XSLTProcessor();
  433. $proc->importStylesheet($convertTransactionXsl);
  434. return $proc->transformToXML($requestXml);
  435. }
  436. public function _validateConvertedTransactionXml($convertedTransaction, $sourceNsList) {
  437. $DBG = (V::get('DBG_XSD', '', $_GET) > 0);// TODO: Profiler
  438. if($DBG){echo 'L.' . __LINE__ . ' sourceNsList:';print_r($sourceNsList);echo "\n";}
  439. $dom = new DOMDocument('1.0', 'utf-8');
  440. $dom->formatOutput = true;
  441. $dom->preserveWhiteSpace = false;
  442. $rootNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:schema');
  443. $dom->appendChild($rootNode);
  444. $rootNode->setAttribute('elementFormDefault', 'qualified');
  445. $rootNode->setAttribute('version', '1.0');
  446. {// <xsd:element name="Transaction" type="TransactionType">
  447. $elNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  448. $rootNode->appendChild($elNode);
  449. $elNode->setAttribute('name', 'Transaction');
  450. $elNode->setAttribute('type', 'TransactionType');
  451. $cTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:complexType');
  452. $rootNode->appendChild($cTypeNode);
  453. $cTypeNode->setAttribute('name', 'TransactionType');
  454. $seqNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:sequence');
  455. $cTypeNode->appendChild($seqNode);
  456. $choiceNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:choice');
  457. $seqNode->appendChild($choiceNode);
  458. $choiceNode->setAttribute('minOccurs', '0');
  459. $choiceNode->setAttribute('maxOccurs', 'unbounded');
  460. // <!-- <xsd:element ref="Update"/> -->
  461. foreach ($sourceNsList as $nsInd => $sourceNs) {
  462. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  463. $updateElementName = "UpdateNs{$nsInd}";
  464. $updateElementType = "UpdateNs{$nsInd}ElementType";
  465. $updateElemNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  466. $choiceNode->appendChild($updateElemNode);
  467. $updateElemNode->setAttribute('name', $updateElementName);
  468. $updateElemNode->setAttribute('type', $updateElementType);
  469. }
  470. // <!-- <xsd:element ref="Insert"/> -->
  471. foreach ($sourceNsList as $nsInd => $sourceNs) {
  472. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  473. $insertElementName = "InsertNs{$nsInd}";
  474. $insertElementType = "InsertNs{$nsInd}ElementType";
  475. $insertElemNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  476. $choiceNode->appendChild($insertElemNode);
  477. $insertElemNode->setAttribute('name', $insertElementName);
  478. $insertElemNode->setAttribute('type', $insertElementType);
  479. }
  480. // <!-- <xsd:element ref="Delete"/> -->
  481. foreach ($sourceNsList as $nsInd => $sourceNs) {
  482. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  483. $deleteElementName = "DeleteNs{$nsInd}";
  484. $deleteElementType = "DeleteNs{$nsInd}ElementType";
  485. $deleteElemNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  486. $choiceNode->appendChild($deleteElemNode);
  487. $deleteElemNode->setAttribute('name', $deleteElementName);
  488. $deleteElemNode->setAttribute('type', $deleteElementType);
  489. }
  490. // <!-- <xsd:element ref="Native"/> -->
  491. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  492. $cTypeNode->appendChild($attrNode);
  493. $attrNode->setAttribute('name', 'version');
  494. $attrNode->setAttribute('type', 'xsd:string');
  495. $attrNode->setAttribute('use', 'required');
  496. $attrNode->setAttribute('fixed', '1.0.0');
  497. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  498. $cTypeNode->appendChild($attrNode);
  499. $attrNode->setAttribute('name', 'service');
  500. $attrNode->setAttribute('type', 'xsd:string');
  501. $attrNode->setAttribute('use', 'required');
  502. $attrNode->setAttribute('fixed', 'WFS');
  503. }
  504. foreach ($sourceNsList as $nsInd => $sourceNs) {
  505. $transactionTypesList = array();
  506. $transactionTypesList[] = 'Update';
  507. $transactionTypesList[] = 'Insert';
  508. foreach ($transactionTypesList as $transactionType) {
  509. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  510. if($DBG){echo 'L.' . __LINE__ . ' TODO: get acl typeName:';print_r($typeName);echo "\n";}
  511. $acl = $this->getAclFromTypeName($typeName);
  512. $updateElementName = "{$transactionType}Ns{$nsInd}";
  513. $updateElementType = "{$transactionType}Ns{$nsInd}ElementType";
  514. /*
  515. <xsd:complexType name="{$updateElementType}">
  516. <xsd:sequence>
  517. <xsd:element name="PARENT_ID" minOccurs="0" maxOccurs="1" type="xsd:integer" />
  518. </xsd:sequence>
  519. */
  520. $updateTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:complexType');
  521. $rootNode->appendChild($updateTypeNode);
  522. $updateTypeNode->setAttribute('name', $updateElementType);
  523. {
  524. $seqNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:all');
  525. $updateTypeNode->appendChild($seqNode);
  526. {
  527. $pKeyField = $acl->getPrimaryKeyField();
  528. $fldList = $this->_getFieldListFromAcl($acl);
  529. // fields without geometry fields
  530. foreach ($fldList as $fldName) {
  531. if ($acl->isGeomField($fldName)) continue;
  532. $elNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  533. $seqNode->appendChild($elNode);
  534. $elNode->setAttribute('name', $fldName);
  535. $minOccurs = 0;
  536. if ($pKeyField == $fldName) {
  537. $minOccurs = '1';
  538. } else {
  539. $minOccurs = '0';
  540. }
  541. $elNode->setAttribute('minOccurs', $minOccurs);
  542. $fldType = null;
  543. if ($acl->isIntegerField($fldName)) {
  544. $fldType = 'xsd:integer';
  545. }
  546. else if ($acl->isDecimalField($fldName)) {
  547. $fldType = 'xsd:decimal';
  548. }
  549. else if ($acl->isDateField($fldName)) {
  550. $fldType = 'xsd:date';
  551. }
  552. else if ($acl->isDateTimeField($fldName)) {
  553. // $fldType = 'xsd:dateTime';
  554. $fldType = null;// 'xsd:string';
  555. $patternDataTime = "(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})(:(\d{2}))?";
  556. // <xsd:element name="..." minOccurs="0" nillable="true">
  557. // <xsd:simpleType>
  558. // <xsd:restriction base="xsd:string">
  559. // <xsd:pattern value="[a-zA-Z]+\(\((\-?\d+\.?\d*,\-?\d+\.?\d*)( \-?\d+\.?\d*,\-?\d+\.?\d*)+\)\)"/>
  560. // </xsd:restriction>
  561. // </xsd:simpleType>
  562. // </xsd:element>
  563. $simpleTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:simpleType');
  564. $restrictionNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:restriction');
  565. $patternNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:pattern');
  566. $restrictionNode->setAttribute('base', 'xsd:string');
  567. $patternNode->setAttribute('value', $patternDataTime);
  568. $restrictionNode->appendChild($patternNode);
  569. $simpleTypeNode->appendChild($restrictionNode);
  570. $elNode->appendChild($simpleTypeNode);
  571. // continue;// TODO: ? below added nillable = true, minOccurs = 0, type = $fldType
  572. }
  573. else if ($acl->isBinaryField($fldName)) {
  574. $fldType = 'xsd:base64Binary';
  575. }
  576. else {
  577. $fldType = 'xsd:string';
  578. }
  579. if ($fldType) $elNode->setAttribute('type', $fldType);
  580. $elNode->setAttribute('nillable', 'true');
  581. $elNode->setAttribute('minOccurs', '0');
  582. }
  583. // only geometry fields
  584. foreach ($fldList as $fldName) {
  585. if (!$acl->isGeomField($fldName)) continue;
  586. $elNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  587. $seqNode->appendChild($elNode);
  588. $elNode->setAttribute('name', $fldName);
  589. $minOccurs = 0;
  590. if ($pKeyField == $fldName) {
  591. $minOccurs = '1';
  592. } else {
  593. $minOccurs = '0';
  594. }
  595. $elNode->setAttribute('minOccurs', $minOccurs);
  596. if ($acl->isGeomField($fldName)) {
  597. //$fldType = 'gml:GeometryPropertyType';
  598. // TODO: use geom types from gml to wkt
  599. // TODO: pattern wg atrybutów gml:coordinates decimal="." cs="," ts=" "
  600. $patternWkt = '';// TODO: error if empty - unsupported geom type
  601. $patternNum = '\-?\d+\.?\d*';
  602. $patternPoint = $patternNum . ',' . $patternNum;
  603. $patternPoints = '(' . $patternPoint . ')( ' . $patternPoint . ')+';
  604. $geomType = $acl->getGeomFieldType($fldName);
  605. if ('polygon' == $geomType) {
  606. // [a-zA-Z]+\(\((\-?\d+\.?\d*,\-?\d+\.?\d*)( (\-?\d+\.?\d*,\-?\d+\.?\d*))+\)\)
  607. $patternWkt = '[a-zA-Z]+\(\(' . $patternPoints . '\)\)';
  608. } else if ('linestring' == $geomType) {
  609. // [a-zA-Z]+\((\-?\d+\.?\d*,\-?\d+\.?\d*)( (\-?\d+\.?\d*,\-?\d+\.?\d*))+\)
  610. $patternWkt = '[a-zA-Z]+\(' . $patternPoints . '\)';
  611. } else if ('point' == $geomType) {
  612. // [a-zA-Z]+\(\-?\d\.?\d*,\-?\d\.?\d*\)
  613. $patternWkt = '[a-zA-Z]+\(' . $patternPoint . '\)';
  614. }
  615. $simpleTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:simpleType');
  616. $restrictionNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:restriction');
  617. $patternNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:pattern');
  618. $restrictionNode->setAttribute('base', 'xsd:string');
  619. $patternNode->setAttribute('value', $patternWkt);
  620. $restrictionNode->appendChild($patternNode);
  621. $simpleTypeNode->appendChild($restrictionNode);
  622. $elNode->appendChild($simpleTypeNode);
  623. }
  624. $elNode->setAttribute('nillable', 'true');
  625. $elNode->setAttribute('minOccurs', '0');
  626. }
  627. }
  628. }
  629. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  630. $updateTypeNode->appendChild($attrNode);
  631. $attrNode->setAttribute('name', 'typeName');
  632. $attrNode->setAttribute('type', 'xsd:token');
  633. $attrNode->setAttribute('use', 'required');
  634. if ($transactionType == 'Insert') {
  635. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  636. $updateTypeNode->appendChild($attrNode);
  637. $attrNode->setAttribute('name', 'typeNsUri');
  638. $attrNode->setAttribute('type', 'xsd:anyURI');
  639. $attrNode->setAttribute('use', 'required');
  640. }
  641. if ($transactionType == 'Update') {
  642. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  643. $updateTypeNode->appendChild($attrNode);
  644. $attrNode->setAttribute('name', 'featureId');
  645. $attrNode->setAttribute('use', 'required');
  646. $sTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:simpleType');
  647. $attrNode->appendChild($sTypeNode);
  648. $resNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:restriction');
  649. $sTypeNode->appendChild($resNode);
  650. $resNode->setAttribute('base', 'xsd:string');
  651. $patternNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:pattern');
  652. $resNode->appendChild($patternNode);
  653. $patternNode->setAttribute('value', '[a-zA-Z_][a-zA-Z0-9_]*\.[0-9]*');
  654. }
  655. }
  656. {// 'Delete'
  657. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  658. $acl = $this->getAclFromTypeName($typeName);
  659. $deleteElementType = "DeleteNs{$nsInd}ElementType";
  660. $deleteTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:complexType');
  661. $rootNode->appendChild($deleteTypeNode);
  662. $deleteTypeNode->setAttribute('name', $deleteElementType);
  663. /* <xsd:attribute name="typeName" type="xsd:token" use="required"/> */
  664. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  665. $deleteTypeNode->appendChild($attrNode);
  666. $attrNode->setAttribute('name', 'typeName');
  667. $attrNode->setAttribute('type', 'xsd:token');
  668. $attrNode->setAttribute('use', 'required');
  669. /* <xsd:attribute name="featureId" use="required"> */
  670. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  671. $deleteTypeNode->appendChild($attrNode);
  672. $attrNode->setAttribute('name', 'featureId');
  673. $attrNode->setAttribute('use', 'required');
  674. $sTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:simpleType');
  675. $attrNode->appendChild($sTypeNode);
  676. $resNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:restriction');
  677. $sTypeNode->appendChild($resNode);
  678. $resNode->setAttribute('base', 'xsd:string');
  679. $patternNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:pattern');
  680. $resNode->appendChild($patternNode);
  681. $patternNode->setAttribute('value', '[a-zA-Z_][a-zA-Z0-9_]*\.[0-9]*');
  682. }
  683. }
  684. $validateConvertedTransactionXsdString = $dom->saveXml();
  685. if($DBG){echo 'L.' . __LINE__ . ' $validateConvertedTransactionXsdString:';print_r($validateConvertedTransactionXsdString);echo "\n";}
  686. $reqXml = new DOMDocument();
  687. $reqXml->loadXml($convertedTransaction);
  688. // TODO: fetch PHP Warning: DOMDocument::schemaValidateSource(): Element 'PARENT_ID': 'abc' is not a valid value of the atomic type 'xs:integer'.
  689. return $reqXml->schemaValidateSource($validateConvertedTransactionXsdString);
  690. }
  691. public function getInstanceFeatures($name, $args) {
  692. $acl = $this->getAclFromTypeName("{$args['typePrefix']}:{$name}");
  693. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  694. $rootWfsNs = 'p5';
  695. $rootWfsNsUri = "{$baseNsUri}";
  696. $wfsNs = $args['typePrefix'];
  697. $wfsNsUri = "{$baseNsUri}/" . ('p5_' == substr($args['typePrefix'], 0, 3)) ? substr($args['typePrefix'], 3) : $args['typePrefix'];
  698. $featureTypeUri = $this->getBaseUri() . "?SERVICE=WFS&VERSION=1.0.0&TYPENAME={$args['xsd:type']}&REQUEST=DescribeFeatureType";
  699. header('Content-type: application/xml; charset=utf-8');
  700. $xmlWriter = new Core_XmlWriter();
  701. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  702. $xmlWriter->openUri('php://output');
  703. $xmlWriter->setIndent(true);
  704. $xmlWriter->startDocument('1.0','UTF-8');
  705. $xmlWriter->startElement('wfs:FeatureCollection');
  706. $xmlWriter->writeAttribute('xmlns:wfs', 'http://www.opengis.net/wfs');
  707. $xmlWriter->writeAttribute('xmlns', 'http://www.opengis.net/wfs');
  708. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  709. $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  710. $xmlWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
  711. $xmlWriter->writeAttribute("xmlns:{$wfsNs}", $wfsNsUri);
  712. if (!$simple) $xmlWriter->writeAttribute("xmlns:{$rootWfsNs}", $rootWfsNsUri);
  713. $xmlWriter->writeAttribute('xsi:schemaLocation', "{$wfsNsUri} {$featureTypeUri}");
  714. $xmlWriter->writeComment("INSTANCE TABLE: " . Core_AclHelper::getInstanceTable($acl->getRootTableName()));
  715. // <gml:featureMember>
  716. // <p5_objects:TestPerms fid="TestPerms.64" p5:web_link="https://biuro.biall-net.pl/dev-pl/se-master/index.php?_route=ViewTableAjax&amp;namespace=default_objects/TestPerms#EDIT/64">
  717. // <p5_objects:ID p5:allow_write="true">64</p5_objects:ID>
  718. $xmlWriter->endElement();// wfs:FeatureCollection
  719. $xmlWriter->endDocument();
  720. exit;
  721. }
  722. public function _describeInstanceAttributeTable($nsPrefix, $name) {
  723. $acl = $this->getAclFromTypeName("{$nsPrefix}:{$name}");
  724. header('Content-type: application/xml; charset=utf-8');
  725. $xmlWriter = new Core_XmlWriter();
  726. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  727. $xmlWriter->openUri('php://output');
  728. $xmlWriter->setIndent(true);
  729. $xmlWriter->startDocument('1.0','UTF-8');
  730. $xmlWriter->startElement('xsd:schema');
  731. $xmlWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema');
  732. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  733. foreach (Api_WfsNs::getNsList() as $uri => $prefix) {
  734. $xmlWriter->writeAttribute("xmlns:{$prefix}", $uri);
  735. }
  736. $xmlWriter->writeAttribute('elementFormDefault', 'qualified');
  737. $xsdInstanceType = $acl->getName() . "_instanceType";
  738. $xsdPrimaryKey = "xsd:string";// TODO: get from $acl
  739. $xmlWriter->h('xsd:element', ['name'=>"instance"], [
  740. [ 'xsd:complexType', [
  741. [ 'xsd:sequence', [
  742. [ 'xsd:element', ['name'=>"primaryKey", 'type'=>$xsdPrimaryKey], null ],
  743. [ 'xsd:element', ['name'=>"instance_name", 'type'=>$xsdInstanceType], null ],
  744. [ 'xsd:element', ['name'=>"instance_type", 'type'=>"xsd:string"], null ],// TODO: instance, derived, matching
  745. [ 'xsd:element', ['name'=>"create_author", 'type'=>"xsd:string"], null ],
  746. [ 'xsd:element', ['name'=>"create_date", 'type'=>"xsd:dateTime"], null ],
  747. [ 'xsd:element', ['name'=>"update_author", 'type'=>"xsd:string"], null ],
  748. [ 'xsd:element', ['name'=>"updage_date", 'type'=>"xsd:dateTime"], null ],
  749. [ 'xsd:element', ['name'=>"verified", 'type'=>"xsd:integer"], null ],
  750. ] ]
  751. ] ]
  752. ]);
  753. $instanceList = (method_exists($acl, 'getInstanceList'))
  754. ? array_map(function ($instanceName) {
  755. return [ 'xsd:enumeration', ['value'=>$instanceName], null ];
  756. }, $acl->getInstanceList())
  757. : [ [ 'xsd:enumeration', ['value'=>$acl->getName()], null ] ]
  758. ;
  759. $xmlWriter->h('xsd:simpleType', ['name'=>$xsdInstanceType], [
  760. [ 'xsd:restriction', ['base'=>"xsd:string"], $instanceList ],
  761. ]);
  762. $xmlWriter->endElement();// xsd:schema
  763. $xmlWriter->endDocument();
  764. exit;
  765. }
  766. public function _getDescribeFeatureType($nsPrefix, $type, $simple = true) {
  767. return $this->_getDescribeFeatureTypes(array(array($nsPrefix, $type)), $simple);
  768. }
  769. public function _parseDescribeFeatureTypeRequest($reqContent, $simple = true) {
  770. $parserXml = xml_parser_create();
  771. xml_parser_set_option($parserXml, XML_OPTION_CASE_FOLDING, 0);
  772. xml_parser_set_option($parserXml, XML_OPTION_SKIP_WHITE, 1);
  773. if (0 == xml_parse_into_struct($parserXml, $reqContent, $tags)) {
  774. throw new Exception("Error parsing xml");
  775. }
  776. xml_parser_free($parserXml);
  777. if (empty($tags)) {
  778. throw new Exception("Empty structure from request");
  779. }
  780. $rootTagName = V::get('tag', '', $tags[0]);
  781. if ('DescribeFeatureType' != $rootTagName) {
  782. throw new Api_WfsException("Wrong xml root tag '{$rootTagName}' #" . __LINE__, 501);
  783. }
  784. $requestXmlTags = $tags;
  785. $DBG = (V::get('DBG_XML', '', $_GET) > 0);// TODO: Profiler
  786. $rootTagName = V::get('tag', '', $requestXmlTags[0]);
  787. if ('DescribeFeatureType' != $rootTagName) {
  788. throw new Exception("Parse Request xml error #" . __LINE__);
  789. }
  790. /*[1] => Array(
  791. [tag] => TypeName
  792. [type] => complete
  793. [level] => 2
  794. [value] => p5_default_db:Rozdzielcza_rurociag_wsg84)
  795. */
  796. $typeNames = array();
  797. $totalTypes = count($requestXmlTags) - 1;
  798. for ($i = 1; $i < $totalTypes; $i++) {
  799. if($DBG){echo "TAG[{$i}]:" . json_encode($requestXmlTags[$i]) . "\n";}
  800. $typeNames[] = explode(':', $requestXmlTags[$i]['value'], 2);
  801. }
  802. //echo "typeNames: " . json_encode($typeNames) . "\n";
  803. return $this->_getDescribeFeatureTypes($typeNames, $simple);
  804. }
  805. public function _getDescribeFeatureAllTypes($simple = true) {
  806. $db = DB::getDB();
  807. $idDefaultDB = $db->_zasob_id;
  808. $tblsAcl = $this->_getTableAclList();
  809. foreach ($tblsAcl as $tblAcl) {
  810. $dataSourceName = 'default_db';// TODO: getSourceName
  811. $tblName = $tblAcl->getName();
  812. $typeNames[] = array("p5_{$dataSourceName}", $tblName);
  813. }
  814. return $this->_getDescribeFeatureTypes($typeNames, $simple);
  815. }
  816. // @param $typeNames = array( array( $nsPrefix, $type ) )
  817. public function _getDescribeFeatureTypes($typeNames, $simple = true) {
  818. if (empty($typeNames)) throw new HttpException("Feature Type Names not defined", 400);
  819. $this->DBG("types:" . json_encode($typeNames), __LINE__, __FUNCTION__, __CLASS__);
  820. DBG::log($typeNames, 'array', "DescribeFeatureType \$typeNames");
  821. // TODO: fix namespace BUG for multiple types:
  822. // - fetch namespace for first type
  823. // - if another object has another namespace then -> import tag
  824. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  825. $rootWfsNs = 'p5';
  826. $rootWfsNsUri = "{$baseNsUri}";
  827. $featureTypeUri = Api_WfsNs::getBaseWfsUri() . "?SERVICE=WFS&VERSION=1.0.0&REQUEST=DescribeFeatureType";
  828. header('Content-type: application/xml');
  829. $nsMap = Api_WfsNs::getNsList();// uri => prefix
  830. $xsdTargetNamespace = null;
  831. { // targetNamespace
  832. list($nsPrefix, $objectName) = reset($typeNames);
  833. $typeName = "{$nsPrefix}:{$objectName}";
  834. $acl = $this->getAclFromTypeName($typeName);
  835. $aclNamespaceUri = Api_WfsNs::getNsUri($acl->getSourceName());
  836. $xsdTargetNamespace = $aclNamespaceUri;
  837. if (!array_key_exists($aclNamespaceUri, $nsMap)) $nsMap[$aclNamespaceUri] = $acl->getSourceName();
  838. }
  839. $xmlWriter = new Core_XmlWriter();
  840. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  841. $xmlWriter->openMemory();// openUri('php://output');
  842. $xmlWriter->setIndent(true);
  843. $xmlWriter->startDocument('1.0','UTF-8');
  844. $xmlWriter->startElement('xsd:schema');
  845. $xmlWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema');
  846. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  847. foreach (Api_WfsNs::getNsList() as $uri => $prefix) {
  848. $xmlWriter->writeAttribute("xmlns:{$prefix}", $uri);
  849. }
  850. $xmlWriter->writeAttribute('elementFormDefault', "qualified");
  851. if ($xsdTargetNamespace) $xmlWriter->writeAttribute('targetNamespace', $xsdTargetNamespace);
  852. $schemaLocations = [];
  853. //$schemaLocations[] = 'http://www.opengis.net/wfs http://webgis.regione.sardegna.it:80/geoserver/schemas/wfs/1.0.0/WFS-capabilities.xsd';// @from http://webgis.regione.sardegna.it/geoserver/ows?service=WFS&request=GetCapabilities
  854. if (!empty($schemaLocations)) $xmlWriter->writeAttribute('xsi:schemaLocation', implode(' ', $schemaLocations));
  855. $xmlWriter->writeAttribute('version', "1.0.0");
  856. $xmlWriter->h('xsd:import', [
  857. 'namespace' => "http://www.opengis.net/gml",
  858. 'schemaLocation' => Request::getPathUri() . "schema/gml/2.1.2/feature.xsd"
  859. ], null);
  860. foreach ($typeNames as $typeNameEx) {
  861. list($nsPrefix, $objectName) = $typeNameEx;
  862. $typeName = "{$nsPrefix}:{$objectName}";
  863. $xmlWriter->writeComment("typeName '{$typeName}'");
  864. $acl = $this->getAclFromTypeName($typeName);
  865. $aclNamespaceUri = Api_WfsNs::getNsUri($acl->getSourceName());
  866. if (!array_key_exists($aclNamespaceUri, $nsMap)) $nsMap[$aclNamespaceUri] = $acl->getSourceName();
  867. if ($xsdTargetNamespace != $aclNamespaceUri) {
  868. $xmlWriter->writeComment("TODO: typeName '{$typeName}' by import namespace '{$aclNamespaceUri}'");// TODO: <xsd:import>; continue;
  869. }
  870. DBG::log($acl->hasSimpleSchema(), 'array', "\$acl({$typeName})->hasSimpleSchema()");
  871. if ($acl->hasSimpleSchema()) {
  872. $simpleSchema = $acl->getSimpleSchema();
  873. $xmlWriter->writeComment("TODO: typeName '{$typeName}' hasSimpleSchema L." . __LINE__);
  874. $aliasRefMap = array();// fieldName => namespace uri
  875. foreach ($simpleSchema as $ssName => $schema) {
  876. if ('root' == $ssName) $ssName = $objectName;
  877. foreach ($schema as $fieldName => $field) {
  878. if (is_array($field)
  879. && !empty($field['@ref'])
  880. && false !== strpos($field['@ref'], '/')
  881. ) {// @ref_uri
  882. $aliasRefMap[ "{$ssName}_{$fieldName}" ] = $field['@ref'];
  883. }
  884. }
  885. }
  886. if (!empty($aliasRefMap)) {
  887. foreach ($aliasRefMap as $fieldName => $aliasNsUri) {
  888. list($nsUri, $prefix, $name) = Api_WfsNs::parseObjectNsUri($aliasNsUri);
  889. if (!array_key_exists($nsUri, $nsMap)) $nsMap[$nsUri] = $prefix;
  890. $xmlWriter->h('xsd:import', ['namespace' => $nsUri, 'schemaLocation' => "{$nsUri}.xsd"], null); // TODO: real file url -> DescribeFeatureType[Advanced]
  891. }
  892. }
  893. foreach ($simpleSchema as $ssName => $schema) {
  894. {// code from Code_AclSimpleSchema
  895. if ('root' == $ssName) $ssName = $objectName;
  896. // <xsd:complexType name="ZaliczkaPozycjaType">
  897. // <xsd:complexContent>
  898. // <xsd:extension base="gml:AbstractFeatureType">
  899. // <xsd:sequence>
  900. // <xsd:element minOccurs="0" maxOccurs="1" name="id" type="xsd:integer" nillable="true"/>
  901. // <xsd:element minOccurs="0" maxOccurs="1" name="created" type="xsd:date" nillable="true"/>
  902. // <xsd:element minOccurs="0" maxOccurs="1" ref="default_objects/AccessOwner" p5:name="worker"/>
  903. // <xsd:element minOccurs="0" maxOccurs="1" name="kwota" type="xsd:decimal" nillable="true"/>
  904. // <xsd:element minOccurs="0" maxOccurs="1" ref="ZaliczkaPozycja" p5:name="pozycja"/>
  905. // </xsd:sequence>
  906. // </xsd:extension>
  907. // </xsd:complexContent>
  908. // </xsd:complexType>
  909. $tnsPrefix = $acl->getSourceName();
  910. $xmlWriter->startElement('xsd:complexType');
  911. $xmlWriter->writeAttribute('name', "{$ssName}Type");
  912. $xmlWriter->startElement('xsd:sequence');
  913. foreach ($schema as $fieldName => $field) {
  914. // [@namespace] => default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja
  915. // [id] => xsd:integer
  916. // [kwota] => xsd:decimal
  917. // [korespondencja] => [ '@ref' => Korespondencja ]
  918. // [projekt] => [ '@ref' => Projekt ]
  919. // TODO: p5:field_name
  920. if ('@' == substr($fieldName, 0, 1)) continue;// skip tags
  921. $xmlWriter->startElement('xsd:element');
  922. if (!is_array($field)) throw new Exception("Error Processing simpleSchema: '{$ssName}/{$fieldName}'");
  923. if (!empty($field['@type'])) {
  924. $xmlWriter->writeAttribute('name', $fieldName);
  925. $xmlWriter->writeAttribute('type', $field['@type']);
  926. $xmlWriter->writeAttribute('nillable', "true");
  927. } else if (!empty($field['@ref'])) {
  928. if (false !== strpos($field['@ref'], '/')) {// @ref_uri
  929. $xmlWriter->writeAttribute('ref', "{$tnsPrefix}:{$ssName}_{$fieldName}");
  930. $xmlWriter->writeAttributeNS($rootWfsNs, "name", $rootWfsNsUri, $fieldName);
  931. } else {
  932. $xmlWriter->writeAttribute('ref', "{$tnsPrefix}:{$field['@ref']}");
  933. if ($fieldName != $field['@ref']) {
  934. $xmlWriter->writeAttributeNS($rootWfsNs, "name", $rootWfsNsUri, $fieldName);
  935. }
  936. }
  937. } else {
  938. throw new Exception("Error Processing simpleSchema - missing @type or @ref: '{$ssName}/{$fieldName}'");
  939. }
  940. if (array_key_exists('@minOccurs', $field)) $xmlWriter->writeAttribute('minOccurs', $field['@minOccurs']);
  941. if (array_key_exists('@maxOccurs', $field)) $xmlWriter->writeAttribute('maxOccurs', $field['@maxOccurs']);
  942. $xmlWriter->endElement(); // 'xsd:element'
  943. }
  944. $xmlWriter->endElement(); // 'xsd:sequence'
  945. $xmlWriter->endElement(); // 'xsd:complexType'
  946. $xmlWriter->startElement('xsd:element');
  947. $xmlWriter->writeAttribute('name', $ssName);
  948. $xmlWriter->writeAttribute('type', "{$tnsPrefix}:{$ssName}Type");
  949. if (!$simple) {
  950. if (!empty($schema['@namespace'])) {// TODO: @namespace is required?
  951. list($nsUri, $prefix, $name) = Api_WfsNs::parseObjectNsUri($schema['@namespace']);
  952. $xmlWriter->writeAttributeNS($rootWfsNs, "namespace", $rootWfsNsUri, "{{$nsUri}}{$name}");
  953. }
  954. }
  955. $xmlWriter->endElement(); // 'xsd:element'
  956. }
  957. }
  958. if (!empty($aliasRefMap)) {
  959. foreach ($aliasRefMap as $fieldName => $aliasNsUri) {
  960. list($nsUri, $prefix, $name) = Api_WfsNs::parseObjectNsUri($aliasNsUri);
  961. $xmlWriter->h('xsd:element', ['name' => $fieldName, 'type' => "{$prefix}:{$name}Type"], null);
  962. }
  963. }
  964. } else {
  965. $objectXsdName = "{$objectName}Type";
  966. $xmlWriter->startElement('xsd:complexType');
  967. $xmlWriter->writeAttribute('name', $objectXsdName);
  968. // if (!$simple) $xmlWriter->writeAttribute("xlmns:{$rootWfsNs}", $rootWfsNsUri);
  969. if (!$simple) $xmlWriter->writeAttributeNS($rootWfsNs, "web_link", $rootWfsNsUri, Request::getPathUri() . "index.php?_route=ViewTableAjax&namespace=" . $acl->getNamespace());
  970. if (!$simple && ($lastUpdateDate = $acl->lastUpdateDate())) $xmlWriter->writeAttributeNS($rootWfsNs, "last_update_date", $rootWfsNsUri, $lastUpdateDate);
  971. $xmlWriter->startElement('xsd:complexContent');
  972. $xmlWriter->startElement('xsd:extension');
  973. $xmlWriter->writeAttribute('base', "gml:AbstractFeatureType");
  974. $xmlWriter->startElement('xsd:sequence');
  975. $pKeyField = $acl->getPrimaryKeyField();
  976. $p5Attributes = ($simple)? array() : $acl->getAttributesFromZasoby();
  977. $fldList = $this->_getFieldListFromAcl($acl);
  978. foreach ($fldList as $fldName) {
  979. $xmlWriter->startElement('xsd:element');
  980. // TODO: get minOccurs from $acl->xsd()
  981. $xmlWriter->writeAttribute('minOccurs', (method_exists($acl, 'getXsdMinOccurs'))
  982. ? $acl->getXsdMinOccurs($fldName)
  983. : (($pKeyField == $fldName) ? '1' : '0')
  984. );
  985. $xmlWriter->writeAttribute('maxOccurs', (method_exists($acl, 'getXsdMaxOccurs'))
  986. ? $acl->getXsdMaxOccurs($fldName)
  987. : '1'
  988. );
  989. $fldType = $acl->getXsdFieldType($fldName);
  990. if (!$simple && $acl->isEnumerationField($fldName)) {
  991. $fldType = $acl->getSourceName() . ":{$fldName}Type";
  992. }
  993. if ('ref:' == substr($fldType, 0, 4)) {
  994. $xmlWriter->writeAttribute("ref", substr($fldType, 4));
  995. $xmlWriter->writeAttributeNS($rootWfsNs, "name", $rootWfsNsUri, $fldName);
  996. } else if ('local_ref:' == substr($fldType, 0, 10)) {
  997. $xmlWriter->writeAttribute("type", "{$fldName}Type");
  998. $xmlWriter->writeAttributeNS($rootWfsNs, "name", $rootWfsNsUri, $fldName);
  999. } else if ('alias_ref:' == substr($fldType, 0, 10)) {
  1000. $xmlWriter->writeAttribute("ref", $acl->getSourceName() . ":{$fldName}");
  1001. $xmlWriter->writeAttributeNS($rootWfsNs, "name", $rootWfsNsUri, $fldName);
  1002. } else {
  1003. $xmlWriter->writeAttribute('name', $fldName);
  1004. $xmlWriter->writeAttribute('type', $fldType);
  1005. $xmlWriter->writeAttribute('nillable', 'true');// nillable not allowed in ref
  1006. }
  1007. if (!$simple) {
  1008. if (!empty($p5Attributes[$fldName])) {
  1009. $p5attrs = $p5Attributes[$fldName];
  1010. if (!empty($p5attrs['id_zasob'])) $xmlWriter->writeAttributeNS($rootWfsNs, "id_zasob", $rootWfsNsUri, $p5attrs['id_zasob']);
  1011. if (!empty($p5attrs['label'])) $xmlWriter->writeAttributeNS($rootWfsNs, "label", $rootWfsNsUri, $p5attrs['label']);
  1012. if (!empty($p5attrs['description'])) $xmlWriter->writeAttributeNS($rootWfsNs, "description", $rootWfsNsUri, $p5attrs['description']);
  1013. }
  1014. if ($acl->canWriteField($fldName)) $xmlWriter->writeAttributeNS($rootWfsNs, "allow_write", $rootWfsNsUri, "true");
  1015. if ($acl->canCreateField($fldName)) $xmlWriter->writeAttributeNS($rootWfsNs, "allow_create", $rootWfsNsUri, "true");
  1016. if (!$acl->canReadField($fldName)) $xmlWriter->writeAttributeNS($rootWfsNs, "allow_read", $rootWfsNsUri, "false");
  1017. }
  1018. $xmlWriter->endElement(); // xsd:element
  1019. }
  1020. $xmlWriter->endElement(); // xsd:sequence
  1021. if (!$simple) $xmlWriter->h('xsd:attribute', ['name' => "instance", 'type' => $acl->getSourceName() . ":instanceType"], null);
  1022. $xmlWriter->endElement(); // xsd:extension
  1023. $xmlWriter->endElement(); // xsd:complexContent
  1024. $xmlWriter->endElement(); // xsd:complexType
  1025. if (!$simple) {
  1026. $xsdInstanceList = (method_exists($acl, 'getInstanceList'))
  1027. ? array_map(function ($instanceName) {
  1028. return [ 'xsd:enumeration', ['value'=>$instanceName], null ];
  1029. }, $acl->getInstanceList())
  1030. : [ [ 'xsd:enumeration', ['value'=>$acl->getName()], null ] ]
  1031. ;
  1032. DBG::log($xsdInstanceList, 'array', "\$xsdInstanceList");
  1033. $xmlWriter->h('xsd:simpleType', ['name' => 'instanceType'], [
  1034. [ 'xsd:restriction', ['base' => 'xsd:string'], $xsdInstanceList ]
  1035. ]);
  1036. }
  1037. $xmlWriter->h('xsd:element', ['name' => $objectName, 'type' => $acl->getSourceName() . ':' . $objectXsdName, 'substitutionGroup'=>"gml:_Feature"], null);
  1038. foreach ($fldList as $fldName) {
  1039. $fldType = $acl->getXsdFieldType($fldName);
  1040. if ('alias_ref:' == substr($fldType, 0, 10)) {
  1041. $localRefType = substr($fldType, 10);
  1042. $xmlWriter->h('xsd:element', ['name' => $fldName, 'type' => $localRefType], null);
  1043. } else if ('local_ref:' == substr($fldType, 0, 10)) {
  1044. $localRefType = substr($fldType, 10);
  1045. $xmlWriter->writeComment("TODO:
  1046. <xsd:complexType name=\"produkt_Type\">
  1047. <xsd:sequence>
  1048. <xsd:element name=\"idProd\" type=\"xsd:integer\" />
  1049. <xsd:element name=\"nazwa\" type=\"xsd:string\" />
  1050. <xsd:element name=\"cena\" type=\"xsd:decimal\" />
  1051. </xsd:sequence>
  1052. </xsd:complexType>
  1053. ");
  1054. }
  1055. }
  1056. if (!$simple) {
  1057. foreach ($fldList as $fldName) {
  1058. if (!$acl->isEnumerationField($fldName)) continue;
  1059. $xsdEnumList = [];
  1060. $enum = $acl->getEnumerations($fldName);
  1061. foreach ($enum as $val => $label) {
  1062. $xsdEnum = ['xsd:enumeration', ['value' => $val], null];
  1063. if (!empty($p5Attributes[$fldName]['valuesMap'][$val])) {
  1064. $xsdEnum[1]["xmlns:{$rootWfsNs}"] = $rootWfsNsUri;
  1065. $xsdEnum[1]["{$rootWfsNs}:label"] = $p5Attributes[$fldName]['valuesMap'][$val];
  1066. }
  1067. $xsdEnumList[] = $xsdEnum;
  1068. }
  1069. $xmlWriter->h('xsd:simpleType', ['name' => "{$fldName}Type"], [
  1070. [ 'xsd:restriction', ['base' => "xsd:string"], $xsdEnumList ]
  1071. ]);
  1072. }
  1073. }
  1074. }
  1075. }
  1076. $xmlWriter->endElement(); // 'xsd:schema'
  1077. $xmlWriter->endDocument();
  1078. echo $xmlWriter->outputMemory($flush = true);
  1079. }
  1080. public function _getTableAclList() {// Use only Tables from default_db
  1081. $tblAclList = array();
  1082. $idDefaultDB = DB::getPDO()->getZasobId();
  1083. $fullTblAclList = $this->_usrAcl->getTablesAcl();
  1084. foreach ($fullTblAclList as $tblAcl) {
  1085. if ($idDefaultDB != $tblAcl->getDB()) {// hide non default_db tables
  1086. continue;
  1087. }
  1088. // $dataSourceName = 'default_db';// TODO: getSourceName
  1089. // $tblName = $tblAcl->getName();
  1090. // try {
  1091. // $acl = $this->getAclFromTypeName($typeName = "p5_{$dataSourceName}:{$tblName}");
  1092. // } catch (Exception $e) {
  1093. // // echo "Error for table({$tblName}): " . $e->getMessage() . "\n";
  1094. // }
  1095. // if (!$acl) {
  1096. // // TODO: error log msg
  1097. // continue;
  1098. // }
  1099. $tblAclList[] = $tblAcl;
  1100. }
  1101. return $tblAclList;
  1102. }
  1103. public function _getFieldListFromAcl($acl) {
  1104. $fldList = $acl->getRealFieldListByIdZasob();
  1105. return $fldList;
  1106. }
  1107. public function setLogger($logger) {
  1108. $this->_logger = $logger;
  1109. }
  1110. public function DBG($reqLog, $lineNr = null, $funName = null, $className = null) {
  1111. if (!$this->_logger) return;
  1112. $this->_logger->DBG($reqLog, $lineNr, $funName, $className);
  1113. }
  1114. }