AclBase.php 38 KB

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