AclBase.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. <?php
  2. Lib::loadClass('Api_WfsNs');
  3. Lib::loadClass('Api_WfsException');
  4. // TODO: replace every methods using $idZasob to use $fieldName
  5. /* TODO: fetch ACL from acl tables:
  6. @example for TestPerms [13051]:
  7. SELECT * FROM `CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW` WHERE `ID_TABLE` =13051; -- fetch id proces to $csvIdProces
  8. SELECT * FROM `CRM_PROCES_idx_USER_to_PROCES_VIEW` WHERE `ADM_ACCOUNT` = '{$userLogin}' and `ID_PROCES` in({$csvIdProces});
  9. */
  10. class Core_AclBase {
  11. public function getNamespace() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  12. public function getSourceName() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  13. public function getName() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  14. public function getRootTableName() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  15. public function getXsdFieldType($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  16. // TODO: get more xsd restrictions like minOccurs, maxOccurs, nillable and restrictions
  17. public function getID() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: Legacy
  18. public function init($force = false) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  19. public function isInitialized() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  20. public function getFields() {// @returns array - $this->_fields // TODO: mved to getFieldListByIdZasob
  21. /*
  22. $field = array();
  23. $field['name'] = $name;
  24. $field['perms'] = '';
  25. $field['opis'] = $opis;
  26. $field['sort_prio'] = $sort_prio;
  27. $field['label'] = $label;
  28. $this->_fields[$fieldID] = $field;
  29. */
  30. throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501);
  31. }
  32. public function getFieldLabel($fieldName) {
  33. foreach ($this->getFields() as $field) {
  34. if ($fieldName != $field['name']) continue;
  35. return V::get('label', $fieldName, $field);
  36. }
  37. return $fieldName;
  38. }
  39. public function getFieldOpis($fieldName) {
  40. foreach ($this->getFields() as $field) {
  41. if ($fieldName != $field['name']) continue;
  42. return V::get('opis', $fieldName, $field);
  43. }
  44. return $fieldName;
  45. }
  46. public function getFieldListByIdZasob() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: RMME - one field list function
  47. public function getRealFieldListByIdZasob() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: RMME - one field list function
  48. public function getVirtualFieldListByIdZasob() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: RMME - one field list function
  49. // TODO: public function getFieldList(); // @retuns array of field names
  50. public function isIntegerField($fieldName) { return ('xsd:integer' == $this->getXsdFieldType($fieldName)); }
  51. public function isDecimalField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  52. public function isGeomField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  53. public function isDateField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  54. public function isDateTimeField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  55. public function isStringField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  56. public function isTextField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  57. public function isBinaryField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  58. public function isEnumerationField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  59. public function getEnumerations($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  60. public function getFieldType($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  61. public function getFieldIdByName($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: legacy
  62. public function isAllowed($idZasob, $taskPerm, $record = null) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: legacy
  63. public function hasFieldPerm($idZasob, $taskPerm) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: legacy
  64. // TODO: replace isAllowed, hasFieldPerm, getFieldIdByName
  65. public function canCreateField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  66. public function canReadField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  67. public function canReadObjectField($fieldName, $record) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  68. public function canWriteField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  69. public function canWriteObjectField($fieldName, $record) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  70. public function getRawLabel($posLimit = 20) { return substr($this->getName(), 0, $posLimit); }
  71. public function getItems($params = array()) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: use ParseOgcQuery
  72. public function getTotal($params = array()) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: use ParseOgcQuery
  73. public function addItem($todoItem) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  74. public function updateItem($itemPatch) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  75. public function getGeomFieldType($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  76. public function getPrimaryKeyField() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  77. public function getAttributesFromZasoby() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  78. public function validateDeleteXml($action) {// @returns action tags, throws Exceptions
  79. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  80. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Delete action \$action:";print_r($action);echo "\n";}
  81. if (empty($action['tags'])) throw new Exception("Error Processing Delete Request - wrong Delete tag format");
  82. if ('open' != $action['tags'][0]['type']) throw new Exception("Error Processing Delete Request - wrong Delete tag format");
  83. if ('Filter' != $action['tags'][0]['tag']) throw new Exception("Error Processing Delete Request - wrong Delete tag format");
  84. $filterLvl = $action['tags'][0]['level'];
  85. array_shift($action['tags']);// remove first openig tag Filter
  86. array_pop($action['tags']);// remove last closing tag Filter
  87. if (empty($action['tags'])) throw new Exception("Error Processing Delete Request - missing FeatureId in Delete tag");
  88. $action['Filter'] = array();
  89. $featureName = $this->getName();
  90. foreach ($action['tags'] as $idx => $tag) {
  91. if ($tag['level'] <= $filterLvl) throw new Exception("Error Processing Delete Request - wrong Delete tag format Delete/Filter/{$tag['tag']}[{$idx}]");
  92. if ('FeatureId' != $tag['tag']) throw new Exception("Error Processing Delete Request - wrong Delete tag format - expected 'FeatureId' but '{$tag['tag']}' found");
  93. if (empty($tag['attributes'])) throw new Exception("Error Processing Delete Request - missing attributes in Delete/Filter/FeatureId[{$idx}]");
  94. if (empty($tag['attributes']['fid'])) throw new Exception("Error Processing Delete Request - missing @fid attribute in Delete/Filter/FeatureId[{$idx}]");
  95. $idFeature = $tag['attributes']['fid'];
  96. if ("{$featureName}." != substr($idFeature, 0, strlen("{$featureName}."))) throw new Exception("Error Processing Delete Request - wrong typeName in Delete/Filter/FeatureId[{$idx}]/@fid");
  97. $idFeature = substr($idFeature, strlen("{$featureName}."));
  98. if (!$this->checkPrimaryKeyFormat($idFeature)) throw new Exception("Error Processing Delete Request - wrong primary key format in Delete/Filter/FeatureId[{$idx}]/@fid");
  99. $action['Filter'][] = $idFeature;
  100. }
  101. $action['fields'] = array();
  102. $action['fields']['the_geom'] = array();
  103. $action['fields']['the_geom'][] = array('type'=>'complete', 'value'=>'NULL');
  104. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Delete action validate return \$action:";print_r($action);echo "\n";}
  105. return $action;
  106. }
  107. public function validateUpdateXml($action) {// @returns action tags, throws Exceptions
  108. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  109. // split Update tag to Property and Filter
  110. $fieldsLvl = $action['tags'][0]['level'];
  111. $totalTags = count($action['tags']);
  112. $tagsToSplice = array();// args for splice(offset, length to remove, new values)
  113. for ($i = 0, $cnt = $totalTags, $lastIdxToSplice = 0; $i < $cnt; $i++) {
  114. $tag = $action['tags'][$i];
  115. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Insert to flat fields loop({$i}) \$lastIdxToSplice({$lastIdxToSplice}) \$tag('{$tag['tag']}', '{$tag['type']}', '{$tag['level']}')"."\n";}
  116. if ($fieldsLvl == $tag['level'] && 'complete' == $tag['type']) {// field - flat value
  117. } else if ($fieldsLvl == $tag['level'] && 'open' == $tag['type']) {// field - nested - start
  118. $lastIdxToSplice = $i;
  119. $tagsToSplice[$lastIdxToSplice] = $tag;
  120. $tagsToSplice[$lastIdxToSplice]['action'] = 'Insert -- TODO: L.' . __LINE__;
  121. $tagsToSplice[$lastIdxToSplice]['tags'] = array();
  122. $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
  123. } else if (null !== $lastIdxToSplice && $fieldsLvl == $tag['level'] && 'close' == $tag['type']) {// field - nested - end
  124. $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
  125. $lastIdxToSplice = null;
  126. } else if (null !== $lastIdxToSplice) {
  127. $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
  128. } else {
  129. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " BUG: Update to flat fields loop({$i}) \$tag('{$tag['tag']}', '{$tag['type']}', '{$tag['level']}')"."\n";}
  130. throw new Exception("Error Processing Update Request at Update tag for type '{$action['typeName']}'");
  131. }
  132. }
  133. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . ' TODO: FIX $action:';print_r($action);echo "\n";}
  134. if (empty($tagsToSplice)) throw new Exception("Error Processing Update Request - missing Property or Filter tags");
  135. if (!empty($tagsToSplice)) {// Update
  136. // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Insert to flat fields \$tagsToSplice:";print_r($tagsToSplice);echo "\n";}
  137. $tagsToSplice = array_reverse($tagsToSplice, $preserve_keys = true);
  138. foreach ($tagsToSplice as $offset => $childTag) {
  139. $toRemove = count($childTag['tags']);
  140. array_pop($childTag['tags']);// remove last closing tag
  141. $tag = array_shift($childTag['tags']);
  142. $childTag['typeName'] = $action['typeName'];
  143. $childTag['action'] = 'Update -- TODO L.' . __LINE__;
  144. array_splice($action['tags'], $offset, $toRemove, array($childTag));
  145. }
  146. // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Insert to flat fields \$action:";print_r($action);echo "\n";}
  147. }
  148. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Update action after first split \$action:";print_r($action);echo "\n";}
  149. if (count($action['tags']) < 2) throw new Exception("Error Processing Update Request - missing Property or Filter tags");
  150. $filterTag = array_pop($action['tags']);
  151. $action['Filter'] = $this->validateUpdateFilterTag($filterTag);
  152. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Update action after validate Filter \$action['Filter']:";print_r($action['Filter']);echo "\n";}
  153. $action['fields'] = $this->validateUpdatePropertyTags($action['tags']);
  154. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Update action after validate Property \$action['fields']:";print_r($action['fields']);echo "\n";}
  155. foreach ($action['fields'] as $fieldName => $propertyTag) {
  156. if (!$this->canWriteField($fieldName)) throw new Api_WfsException("Access Denied to Update field '{$fieldName}' in object '{$action['typeName']}'", __LINE__, null, 'MissingFieldPermWrite', 'request');
  157. $value = $propertyTag['value'];
  158. $this->validateFieldRestrictions($fieldName, $value);
  159. }
  160. return $action;
  161. }
  162. public function validateUpdateFilterTag($filterTag) {// @returns Filter tag (feature id), throws Exceptions
  163. // TODO: allow ogc filter for update multiple rows
  164. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  165. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Update validateUpdateFilterTag \$filterTag:";print_r($filterTag);echo "\n";}
  166. if ('Filter' != $filterTag['tag']) throw new Exception("Error Processing Update Request - missing Filter tag");
  167. $idFeature = null;
  168. if (empty($filterTag['tags'])) throw new Exception("Error Processing Update Request - wrong Filter tag format");
  169. if ('FeatureId' != $filterTag['tags'][0]['tag']) throw new Exception("Error Processing Update Request - wrong Filter tag format");
  170. if (empty($filterTag['tags'][0]['attributes']['fid'])) throw new Exception("Error Processing Update Request - missing Filter tag @fid");
  171. $idFeature = $filterTag['tags'][0]['attributes']['fid'];
  172. $featureName = $this->getName();
  173. if ("{$featureName}." != substr($idFeature, 0, strlen("{$featureName}."))) throw new Exception("Error Processing Update Request - wrong typeName in Filter/@fid");
  174. $idFeature = substr($idFeature, strlen("{$featureName}."));
  175. if (!$this->checkPrimaryKeyFormat($idFeature)) throw new Exception("Error Processing Update Request - wrong primary key format in Filter/@fid");
  176. return $idFeature;
  177. }
  178. public function checkPrimaryKeyFormat($idFeature) {// @returns bool
  179. return ((string)$idFeature === (string)intval($idFeature));
  180. }
  181. public function validateUpdatePropertyTags($tags) {// @returns Property tags (fields), throws Exceptions
  182. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  183. $fields = array();
  184. if($DBG>3){echo 'C.'.get_class($this).' L.' . __LINE__ . " Update validateUpdatePropertyTags \$fields:";print_r($tags);echo "\n";}
  185. foreach ($tags as $idx => $tag) {
  186. if ('Property' != $tag['tag']) throw new Exception("Error Processing Update Request - tag '{$tag['tag']}' is not allowed in Update tag");
  187. if (count($tag['tags']) < 2) throw new Exception("Error Processing Update Request - wrong format in Update/Property[{$idx}]");
  188. $tagName = array_shift($tag['tags']);
  189. if ('Name' != $tagName['tag']) throw new Exception("Error Processing Update Request - missing Name tag in Update/Property[{$idx}]");
  190. if (empty($tagName['value'])) throw new Exception("Error Processing Update Request - empty field name in Update/Property[{$idx}]");
  191. if (false !== strpos($tagName['value'], '/')) throw new Exception("Error Processing Update Request - xpath in Update/Property[{$idx}] field name not implemented", 501);
  192. // TODO: check field name as xpath, eg. File/content
  193. $fieldName = $tagName['value'];
  194. $tagValue = array_shift($tag['tags']);
  195. $fieldType = $this->getXsdFieldType($fieldName);
  196. if ('Value' != $tagValue['tag']) throw new Exception("Error Processing Update Request - missing Value tag in Update/Property[{$idx}]");
  197. if ('open' == $tagValue['type']) {
  198. array_pop($tag['tags']);
  199. $tagValue['tags'] = $tag['tags'];
  200. if (empty($tagValue['tags'])) throw new Exception("Error Processing Update Request - wrong Value tag format in Update/Property[{$idx}]");
  201. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." validate fields loop({$idx}) loop({$fieldName}) \$fieldType({$fieldType})"."\n";}
  202. if ('gml:' == substr($fieldType, 0, 4)) {
  203. $tagValue['value'] = $this->convertGmlTagsToWkt($fieldType, $tagValue['tags']);
  204. } else {
  205. // TODO: return $fields[$fieldName][] = array('type'=>'open', 'typeName'=>$fieldType, 'tags'=>...
  206. throw new Exception("Error Processing Update Request - wrong Value tag format for field '{$fieldName}' (Update/Property[{$idx}])");
  207. }
  208. } else if ('complete' == $tagValue['type']) {
  209. if (!empty($tag['tags'])) throw new Exception("Error Processing Update Request - wrong Value tag format in Update/Property[{$idx}]");
  210. } else throw new Exception("Error Processing Update Request - missing Value tag in Update/Property[{$idx}]");
  211. $value = V::get('value', '', $tagValue);
  212. $fields[$fieldName][] = array('type'=>'complete', 'value'=>$value);
  213. }
  214. return $fields;
  215. }
  216. public function validateInsertXml($action) {// @returns action tag, throws Exceptions
  217. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  218. // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " TODO: F.".__FUNCTION__." \$action:";print_r($action);echo "\n";}
  219. // split Insert tags by first level fields - nested structures like gml (the_geom)
  220. $fieldsLvl = $action['tags'][0]['level'];
  221. $totalTags = count($action['tags']);
  222. $tagsToSplice = array();// args for splice(offset, length to remove, new values)
  223. for ($i = 0, $cnt = $totalTags, $lastIdxToSplice = 0; $i < $cnt; $i++) {
  224. $tag = $action['tags'][$i];
  225. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Insert to flat fields loop({$i}) \$lastIdxToSplice({$lastIdxToSplice}) \$tag('{$tag['tag']}', '{$tag['type']}', '{$tag['level']}')"."\n";}
  226. if ($fieldsLvl == $tag['level'] && 'complete' == $tag['type']) {// field - flat value
  227. } else if ($fieldsLvl == $tag['level'] && 'open' == $tag['type']) {// field - nested - start
  228. $lastIdxToSplice = $i;
  229. $tagsToSplice[$lastIdxToSplice] = $tag;
  230. $tagsToSplice[$lastIdxToSplice]['action'] = 'Insert';
  231. $tagsToSplice[$lastIdxToSplice]['tags'] = array();
  232. $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
  233. } else if (null !== $lastIdxToSplice && $fieldsLvl == $tag['level'] && 'close' == $tag['type']) {// field - nested - end
  234. $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
  235. $lastIdxToSplice = null;
  236. } else if (null !== $lastIdxToSplice) {
  237. $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
  238. } else {
  239. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " BUG: Insert to flat fields loop({$i}) \$tag('{$tag['tag']}', '{$tag['type']}', '{$tag['level']}')"."\n";}
  240. throw new Exception("Error Processing Request at Insert tag for type '{$action['typeName']}'");
  241. }
  242. }
  243. // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . ' TODO: FIX $action:';print_r($action);echo "\n";}
  244. if (!empty($tagsToSplice)) {// Insert deep object
  245. // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Insert to flat fields \$tagsToSplice:";print_r($tagsToSplice);echo "\n";}
  246. $tagsToSplice = array_reverse($tagsToSplice, $preserve_keys = true);
  247. foreach ($tagsToSplice as $offset => $childTag) {
  248. $toRemove = count($childTag['tags']);
  249. array_pop($childTag['tags']);// remove last closing tag
  250. $tag = array_shift($childTag['tags']);
  251. $childTag['action'] = 'Insert';
  252. {// TODO: duplicate code - get prefix for typeName
  253. $typeName = $tag['tag'];
  254. if (false === strpos($typeName, ':')) {
  255. $nsType = V::get('xmlns', '', $tag['attributes']);
  256. if (!$nsType) throw new Exception("Error Processing Request - Missing object namespace '{$tag['tag']}'");
  257. $prefix = Api_WfsNs::getNsPrefix($nsType);
  258. if (!$prefix) {
  259. if ($typeName == substr(rtrim($nsType, '/'), -1 * strlen($typeName))) {// typeName may be added to ns uri
  260. $nsBaseForType = substr(rtrim($nsType, '/'), 0, -1 * strlen($typeName) - 1);
  261. $prefix = Api_WfsNs::getNsPrefix($nsBaseForType);
  262. }
  263. }
  264. if (!$prefix) throw new Exception("Error Processing Request - Unrecognized namespace uri '{$nsType}' for object '{$tag['tag']}'");
  265. $typeName = "{$prefix}:{$typeName}";
  266. }
  267. $childTag['typeName'] = $typeName;
  268. }
  269. array_splice($action['tags'], $offset, $toRemove, array($childTag));
  270. $action['isDeepObject'] = true;
  271. }
  272. // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Insert to flat fields \$action:";print_r($action);echo "\n";}
  273. }
  274. // TODO: validate sequence order from schema - needed?
  275. // validate fields
  276. $action['fields'] = array();
  277. foreach ($action['tags'] as $idx => $tag) {
  278. $fieldName = $tag['tag'];
  279. if (false !== strpos($fieldName, ':')) $fieldName = substr($fieldName, strpos($fieldName, ':') + 1);
  280. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." validate fields loop({$idx}) \$fieldName:";print_r($fieldName);echo "\n";}
  281. $field = array();
  282. $field['tag'] = $tag['tag'];
  283. $field['type'] = $tag['type'];
  284. if (!empty($tag['typeName'])) $field['typeName'] = $tag['typeName'];
  285. if (!empty($tag['action'])) $field['action'] = $tag['action'];
  286. if (!empty($tag['value']) || '0' === $tag['value'] || 0 === $tag['value']) $field['value'] = $tag['value'];
  287. if (!empty($tag['tags'])) $field['tags'] = $tag['tags'];
  288. $action['fields'][$fieldName][] = $field;
  289. }
  290. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." validate fields loop({$idx}) \$action['fields']:";print_r($action['fields']);echo "\n";}
  291. foreach ($action['fields'] as $fieldName => $childFields) {
  292. foreach ($childFields as $idx => $field) {
  293. // TODO: validate minOccurs, maxOccurs
  294. }
  295. }
  296. $fieldPK = $this->getPrimaryKeyField();
  297. foreach ($action['fields'] as $fieldName => $childFields) {
  298. if ($fieldName == $fieldPK) continue;
  299. foreach ($childFields as $idx => $field) {
  300. if (!$this->canCreateField($fieldName)) throw new Api_WfsException("Access Denied to Create field '{$fieldName}' in object '{$action['typeName']}'", __LINE__, null, 'MissingFieldPermCreate', 'request');
  301. if ('open' == $field['type']) {
  302. $fieldType = $this->getXsdFieldType($fieldName);
  303. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." validate fields loop({$idx}) loop({$fieldName}) \$fieldType({$fieldType})"."\n";}
  304. if ('gml:' == substr($fieldType, 0, 4)) {
  305. $action['fields'][$fieldName][$idx]['value'] = $this->convertGmlTagsToWkt($fieldType, $field['tags']);
  306. unset($action['fields'][$fieldName][$idx]['tags']);
  307. unset($action['fields'][$fieldName][$idx]['typeName']);
  308. unset($action['fields'][$fieldName][$idx]['action']);
  309. $action['fields'][$fieldName][$idx]['type'] = 'complete';
  310. } else if ('p5_objects:' == substr($fieldType, 0, 11)) {
  311. // TODO: read value recursive? (like geom?)
  312. } else if ('ref:p5_objects:' == substr($fieldType, 0, 15)) {
  313. // TODO: read value recursive? - validate recursive
  314. }
  315. }
  316. $this->validateFieldRestrictions($fieldName, $value);
  317. }
  318. }
  319. // TODO: validate nillable
  320. // TODO: validate recursive fields with type 'p5_objects:*' (without 'value')
  321. foreach ($action['fields'] as $fieldName => $childFields) {
  322. foreach ($childFields as $idx => $field) {
  323. if ('open' == $field['type']) {
  324. $fieldType = $this->getXsdFieldType($fieldName);
  325. if ('ref:p5_objects:' == substr($fieldType, 0, 15)) {
  326. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." TODO: -------> validateInsertXml(\$field) \$field:";print_r($field);echo "\n";}
  327. $acl = $this->getAclFromTypeName(substr($fieldType, 4));
  328. $action['fields'][$fieldName][$idx] = $acl->validateInsertXml($field);
  329. }
  330. }
  331. }
  332. }
  333. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." return ============ \$action:";print_r($action);echo "\n";}
  334. return $action;
  335. }
  336. public function validateFieldRestrictions($fieldName, $value) {// @returns null, throws Exceptions
  337. // TODO: restrictions
  338. }
  339. public function checkFieldRestrictions($fieldName, $value) {// @returns array of error msgs
  340. // TODO: restrictions
  341. }
  342. // like Api_WfsGeomTypeConverter::convertGmlCoordinatesToWkt($gmlCoordinates) where $gmlCoordinates is from converted wfs request
  343. public function convertGmlTagsToWkt($fieldType, $tags) {
  344. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  345. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " TODO: F.".__FUNCTION__." \$fieldType({$fieldType}) \$tags:";print_r($tags);echo "\n";}
  346. $cs = ','; $ts = ' '; $value = null; $wktType = null;
  347. if ('gml:LineStringPropertyType' == $fieldType) {
  348. // <gml:LineString srsName="EPSG:4326">
  349. // <gml:coordinates cs="," ts=" ">18.25240580856418049,54.48879768607960017 18.27014261382555915,54.46219247818753217</gml:coordinates>
  350. // </gml:LineString>
  351. if (3 != count($tags)) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
  352. if ('gml:LineString' !== $tags[0]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
  353. if ('open' !== $tags[0]['type']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
  354. if (empty($tags[1]['attributes']['cs'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
  355. if (empty($tags[1]['attributes']['ts'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
  356. if (empty($tags[1]['value'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
  357. $cs = $tags[1]['attributes']['cs'];
  358. $ts = $tags[1]['attributes']['ts'];
  359. $value = $tags[1]['value'];
  360. $wktType = 'LINESTRING';
  361. } else if ('gml:PointPropertyType' == $fieldType) {
  362. // <gml:Point srsDimension="1" srsName="http://www.opengis.net/gml/srs/epsg.xml#3857">
  363. // <gml:coordinates decimal="." cs="," ts=" ">-33.7291,-56.3353820</gml:coordinates>
  364. // </gml:Point>
  365. // TODO: @decimal
  366. if (3 != count($tags)) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
  367. if ('gml:Point' !== $tags[0]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
  368. if ('open' !== $tags[0]['type']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
  369. if (empty($tags[1]['attributes']['cs'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
  370. if (empty($tags[1]['attributes']['ts'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
  371. if (empty($tags[1]['value'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
  372. $cs = $tags[1]['attributes']['cs'];
  373. $ts = $tags[1]['attributes']['ts'];
  374. $value = $tags[1]['value'];
  375. $wktType = 'POINT';
  376. } else if ('gml:PolygonPropertyType' == $fieldType) {
  377. if (7 != count($tags)) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  378. if ('gml:Polygon' !== $tags[0]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  379. if ('open' !== $tags[0]['type']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  380. if ('gml:outerBoundaryIs' !== $tags[1]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  381. if ('gml:LinearRing' !== $tags[2]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  382. if ('gml:coordinates' !== $tags[3]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  383. if (empty($tags[3]['attributes']['cs'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  384. if (empty($tags[3]['attributes']['ts'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  385. if (empty($tags[3]['value'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  386. $cs = $tags[3]['attributes']['cs'];
  387. $ts = $tags[3]['attributes']['ts'];
  388. $value = $tags[3]['value'];
  389. $wktType = 'POLYGON';
  390. } else {
  391. throw new Exception("Error Processing Request - type '{$fieldType}' not supported");
  392. }
  393. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " TODO: F.".__FUNCTION__." \$fieldType({$fieldType}) TODO \$value:";print_r($value);echo "\n";}
  394. return self::convertGmlCoordsToWkt($wktType, $value, ['cs'=>$cs, 'ts'=>$ts]);
  395. }
  396. /**
  397. * @param $wktType: 'POLYGON', 'POINT', 'LINESTRING'
  398. * @param $params: array(decimal="." cs="," ts="whitespace")
  399. * decimal - decimal separator (default '.')
  400. * cs - coordinate values separator (default ',')
  401. * ts - tuple separator (a single space by default)
  402. *
  403. * @example:
  404. * <gml:coordinates cs="," ts=" ">18.25240580856418049,54.48879768607960017 18.27014261382555915,54.46219247818753217</gml:coordinates>
  405. * Core_AclBase::convertGmlCoordsToWkt('18.25240580856418049,54.48879768607960017 18.27014261382555915,54.46219247818753217', ['cs'=>',', 'ts'=>' '])
  406. */
  407. public static function convertGmlCoordsToWkt($wktType, $coords, $params = array()) {
  408. $cs = V::get('cs', ',', $params);
  409. $decimal = V::get('decimal', '.', $params);
  410. $ts = V::get('ts', ' ', $params);
  411. $gmlNumber = '(\-?\d+\\' . $decimal . '?\d*)';
  412. $gmlPoint = '(' . $gmlNumber . $cs . $gmlNumber . ')';
  413. $gmlPoints = $gmlPoint . '(' . $ts . $gmlPoint . ')+';
  414. switch ($wktType) {
  415. case 'POINT': $regex = '/^' . "{$gmlPoint}" . '$/'; break;
  416. case 'LINESTRING': $regex = '/^' . "{$gmlPoints}" . '$/'; break;
  417. case 'POLYGON': $regex = '/^' . "{$gmlPoints}" . '$/'; break;
  418. default: throw new Exception("Unsupported geometry type '{$wktType}'");
  419. }
  420. if (!preg_match($regex, $coords, $matches)) {
  421. throw new Exception("Wrong coordinates format for type '{$wktType}'");
  422. }
  423. $wkt = $coords;
  424. $wkt = str_replace(array($cs, $ts), array('#cs#', '#ts#'), $wkt);
  425. $wkt = str_replace(array('#cs#', '#ts#'), array(' ', ','), $wkt);
  426. if ('POLYGON' == $wktType) $wkt = "({$wkt})";// POINT(1 1), LINESTRING(0 0,1 1,2 2), POLYGON((0 0,10 0,10 10,0 10,0 0))
  427. return "{$wktType}({$wkt})";
  428. }
  429. public function getAclFromTypeName($typeName) {// TODO: mv to another class, duplicate from Api_WfsServerBase::getAclFromTypeName($typeName)
  430. $typeEx = explode(':', $typeName);
  431. if (2 != count($typeEx)) throw new Exception("Could not get acl for '{$typeName}' - syntax error");
  432. if ('p5_' != substr($typeEx[0], 0, 3)) throw new Exception("Could not get acl for '{$typeName}' - prefix error");
  433. $sourceName = substr($typeEx[0], 3);
  434. $objName = $typeEx[1];
  435. $acl = User::getAcl()->getObjectAcl($sourceName, $objName);
  436. if (!$acl) throw new Exception("Could not get acl for '{$typeName}'");
  437. $forceTblAclInit = 0;//('1' == V::get('_force', '', $_GET));
  438. $acl->init($forceTblAclInit);
  439. return $acl;
  440. }
  441. public function insertXml($action) {// @param $action = [ 'typeName' => '*:*', 'fields'=>[ `name`=>[`fld`, `fld`, ...], ... ] ]
  442. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  443. if (empty($action['typeName'])) throw new Exception("Error Processing Request - missing typeName", 500);
  444. if (empty($action['fields'])) throw new Exception("Error Processing Request - missing fields for type '{$action['typeName']}'", 500);
  445. {// Insert with primaryKey -> Update
  446. $fieldPK = $this->getPrimaryKeyField();
  447. if (array_key_exists($fieldPK, $action['fields'])) {
  448. $pk = $action['fields'][$fieldPK][0]['value'];
  449. $action['Filter'] = $pk;
  450. $affected = $this->updateXml($action);
  451. return ($affected >= 0) ? $pk : -1;
  452. }
  453. }
  454. $sqlInsert = array();
  455. $sqlChildInsert = array();
  456. foreach ($action['fields'] as $fieldName => $childFields) {
  457. foreach ($childFields as $idx => $field) {
  458. if ('complete' == $field['type']) {
  459. $sqlInsert[$fieldName][$idx] = $field['value'];
  460. } else if ('open' == $field['type']) {
  461. $childAcl = $this->getAclFromTypeName($field['typeName']);// TODO: or $fieldType = $this->getXsdFieldType($fieldName);// TODO: ref:p5_objects:File
  462. $sqlChildInsert[$fieldName][$idx] = $childAcl->insertXml($field);
  463. } else throw new Exception("Error Processing Request - BUG Unrecognized type '{$field['type']}'", 500);
  464. }
  465. }
  466. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." \$sqlInsert:";print_r($sqlInsert);echo "\n";}
  467. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." \$sqlChildInsert:";print_r($sqlChildInsert);echo "\n";}
  468. $sqlObj = array();
  469. foreach ($sqlInsert as $fieldName => $childFields) {
  470. $value = $childFields[0];
  471. // foreach ($childFields as $idx => $value) // TODO: check maxOcures
  472. if ($this->isGeomField($fieldName)) $value = "GeomFromText('{$value}')";
  473. $sqlObj["{$fieldName}"] = $value;
  474. }
  475. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." addItem(\$sqlObj) \$sqlObj:";print_r($sqlObj);echo "\n";}
  476. $insertedId = $this->addItem($sqlObj);
  477. foreach ($sqlChildInsert as $fieldName => $childFields) {
  478. foreach ($childFields as $idx => $childInsertedId) {
  479. $childAcl = $this->getAclFromTypeName($action['fields'][$fieldName][$idx]['typeName']);// TODO: or $fieldType = $this->getXsdFieldType($fieldName);// TODO: ref:p5_objects:File
  480. // $this->_insertRef($this->getRootTableName(), $childAcl->getRootTableName(), $insertedId, $childInsertedId);
  481. $this->_insertRef($fieldName, $insertedId, $childInsertedId);
  482. }
  483. }
  484. return $insertedId;
  485. }
  486. public function _insertRef($childName, $pk, $childPk) {// TODO: $idTransaction
  487. $refTable = $this->createRefTable($childName);
  488. $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
  489. $sqlChildPk = DB::getPDO()->quote($childPk, PDO::PARAM_STR);
  490. DB::getPDO()->exec("
  491. insert into `{$refTable}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`)
  492. values ({$sqlPk}, {$sqlChildPk})
  493. ");
  494. }
  495. public function createRefTable($childName) {// TODO: $idTransaction
  496. static $cacheRefTables = array();
  497. $objectName = $this->getName();
  498. $refTable = "{$objectName}__#REF__{$childName}";
  499. if (in_array($refTable, $cacheRefTables)) return $refTable;
  500. DB::getPDO()->exec("
  501. CREATE TABLE IF NOT EXISTS `{$refTable}` (
  502. `PRIMARY_KEY` int(11) NOT NULL,
  503. `REMOTE_PRIMARY_KEY` int(11) NOT NULL,
  504. -- TODO `TRANACTION_ID` int(11) NOT NULL
  505. KEY `PRIMARY_KEY` (`PRIMARY_KEY`),
  506. KEY `REMOTE_PRIMARY_KEY` (`REMOTE_PRIMARY_KEY`)
  507. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  508. ");
  509. $cacheRefTables[] = $refTable;
  510. return $refTable;
  511. }
  512. public function updateXml($action) {// @param $action = [ 'typeName' => '*:*', 'Filter'=>int, 'fields'=>[ `name`=>[`fld`, `fld`, ...], ... ] ]
  513. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  514. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " updateXml action \$action:";print_r($action);echo "\n";}
  515. if (empty($action['typeName'])) throw new Exception("Error Processing Request - missing typeName", 500);
  516. if (empty($action['Filter'])) throw new Exception("Error Processing Request - missing Filter for type '{$action['typeName']}'", 500);
  517. if (!$this->checkPrimaryKeyFormat($action['Filter'])) throw new Exception("Error Processing Request - wrong Filter format for type '{$action['typeName']}'", 501);
  518. if (empty($action['fields'])) throw new Exception("Error Processing Request - missing Property for type '{$action['typeName']}'", 500);
  519. // TODO: check acl user to update record ID = $action['Filter']
  520. $itemPatch = array();
  521. foreach ($action['fields'] as $fieldName => $childFields) {
  522. foreach ($childFields as $idx => $field) {
  523. if ('complete' != $field['type']) continue;// skip child nodes, REF
  524. $value = $field['value'];
  525. if ($this->isGeomField($fieldName)) $value = "GeomFromText('{$value}')";
  526. $itemPatch[$fieldName] = $value;
  527. }
  528. }
  529. $itemPatch[$this->getPrimaryKeyField()] = $action['Filter'];
  530. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " updateXml action \$itemPatch:";print_r($itemPatch);echo "\n";}
  531. $affected = $this->updateItem($itemPatch);
  532. // TODO: update/insert child nodes, REF
  533. return $affected;
  534. }
  535. public function deleteXml($action) {// @param $action = [ 'typeName' => '*:*', 'Filter'=>[int, ...], 'fields'=>[ `name`=>[`fld`, `fld`, ...], ... ] ]
  536. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  537. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " updateXml action \$action:";print_r($action);echo "\n";}
  538. if (empty($action['typeName'])) throw new Exception("Error Processing Request - missing typeName", 500);
  539. if (!is_array($action['Filter']) || empty($action['Filter'])) throw new Exception("Error Processing Request - missing Filter for type '{$action['typeName']}'", 500);
  540. foreach ($action['Filter'] as $fid) {
  541. if (!$this->checkPrimaryKeyFormat($fid)) throw new Exception("Error Processing Request - wrong Filter format for type '{$action['typeName']}'", 501);
  542. }
  543. if (empty($action['fields'])) throw new Exception("Error Processing Request - missing Property for type '{$action['typeName']}'", 500);
  544. // TODO: check acl user to update record ID = $action['Filter']
  545. $itemPatch = array();
  546. foreach ($action['fields'] as $fieldName => $childFields) {
  547. foreach ($childFields as $idx => $field) {
  548. if ('complete' != $field['type']) continue;// skip child nodes, REF
  549. $value = $field['value'];
  550. if ($this->isGeomField($fieldName)) $value = "GeomFromText('{$value}')";
  551. $itemPatch[$fieldName] = $value;
  552. }
  553. }
  554. $fieldPK = $this->getPrimaryKeyField();
  555. $deleted = 0;
  556. foreach ($action['Filter'] as $fid) {
  557. $itemPatch[$fieldPK] = $fid;
  558. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " updateXml action \$itemPatch:";print_r($itemPatch);echo "\n";}
  559. $affected = $this->updateItem($itemPatch);
  560. if ($affected >= 0) $deleted += 1;
  561. }
  562. // TODO: update/insert child nodes, REF
  563. return $deleted;
  564. }
  565. }