AclBase.php 38 KB

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