WfsServerBase.php 53 KB

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