WfsServerBase.php 62 KB

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