AclBase.php 40 KB

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