ServerBase.php 57 KB

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