WfsServerBase.php 62 KB

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