AclBase.php 37 KB

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