AclBase.php 36 KB

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