AclBase.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. <?php
  2. Lib::loadClass('Api_WfsNs');
  3. Lib::loadClass('Api_WfsException');
  4. Lib::loadClass('User');
  5. // TODO: replace every methods using $idZasob to use $fieldName
  6. /* TODO: fetch ACL from acl tables:
  7. @example for TestPerms [13051]:
  8. SELECT * FROM `CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW` WHERE `ID_TABLE` =13051; -- fetch id proces to $csvIdProces
  9. SELECT * FROM `CRM_PROCES_idx_USER_to_PROCES_VIEW` WHERE `ADM_ACCOUNT` = '{$userLogin}' and `ID_PROCES` in({$csvIdProces});
  10. */
  11. class Core_AclBase {
  12. public function getNamespace() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  13. public function getSourceName() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  14. public function getName() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  15. public function getRootTableName() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  16. public function getXsdFieldType($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  17. // TODO: get more xsd restrictions like minOccurs, maxOccurs, nillable and restrictions
  18. public function getID() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: Legacy
  19. public function init($force = false) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  20. public function isInitialized() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  21. public function getFields() {// @returns array - $this->_fields // TODO: mved to getFieldListByIdZasob
  22. /*
  23. $field = array();
  24. $field['name'] = $name;
  25. $field['perms'] = '';
  26. $field['opis'] = $opis;
  27. $field['sort_prio'] = $sort_prio;
  28. $field['label'] = $label;
  29. $this->_fields[$fieldID] = $field;
  30. */
  31. throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501);
  32. }
  33. public function getFieldLabel($fieldName) {
  34. foreach ($this->getFields() as $field) {
  35. if ($fieldName != V::get('name', '', $field)) continue;
  36. return V::get('label', $fieldName, $field);
  37. }
  38. return $fieldName;
  39. }
  40. public function getFieldOpis($fieldName) {
  41. foreach ($this->getFields() as $field) {
  42. if ($fieldName != V::get('name', '', $field)) continue;
  43. return V::get('opis', $fieldName, $field);
  44. }
  45. return $fieldName;
  46. }
  47. public function getFieldListByIdZasob() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: RMME - one field list function
  48. public function getRealFieldListByIdZasob() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: RMME - one field list function
  49. public function getVirtualFieldListByIdZasob() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: RMME - one field list function
  50. // TODO: public function getFieldList(); // @retuns array of field names
  51. public function isIntegerField($fieldName) { return ('xsd:integer' == $this->getXsdFieldType($fieldName)); }
  52. public function isDecimalField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  53. public function isGeomField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  54. public function isDateField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  55. public function isDateTimeField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  56. public function isStringField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  57. public function isTextField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  58. public function isBinaryField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  59. public function isEnumerationField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  60. public function getEnumerations($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  61. public function getFieldType($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  62. public function getFieldIdByName($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: legacy
  63. public function isAllowed($idZasob, $taskPerm, $record = null) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: legacy
  64. public function hasFieldPerm($idZasob, $taskPerm) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: legacy
  65. // TODO: replace isAllowed, hasFieldPerm, getFieldIdByName
  66. public function canCreateField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  67. public function canReadField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  68. public function canReadObjectField($fieldName, $record) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  69. public function canWriteField($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  70. public function canWriteObjectField($fieldName, $record) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  71. public function canWriteRecord($record) {// TODO: AclHelper?
  72. $record = (array)$record;
  73. $dbgArr = array();
  74. $dbgArr['record_owner'] = (isset($record['L_APPOITMENT_USER']))? $record['L_APPOITMENT_USER'] : '';
  75. $dbgArr['record_write'] = (isset($record['A_ADM_COMPANY']))? $record['A_ADM_COMPANY'] : '';
  76. $dbgArr['record_read'] = (isset($record['A_CLASSIFIED']))? $record['A_CLASSIFIED'] : '';
  77. $dbgArr['user_groups'] = User::getLdapGroupsNames();
  78. if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">dbgArr (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($dbgArr);echo'</pre>';}
  79. if ($dbgArr['record_owner'] && $dbgArr['record_owner'] == User::getLogin()) {
  80. if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo '<p>true - is record owner</p>';}
  81. return true;
  82. }
  83. if ($dbgArr['record_write']) {
  84. if (in_array($dbgArr['record_write'], $dbgArr['user_groups'])) {
  85. if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo '<p>true - has group write</p>';}
  86. return true;
  87. }
  88. } else {
  89. if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo '<p>true - group write not set</p>';}
  90. return true;
  91. }
  92. return false;
  93. }
  94. public function canReadRecord($record) {// TODO: AclHelper?
  95. $record = (array)$record;
  96. $dbgArr = array();
  97. $dbgArr['record_owner'] = (isset($record['L_APPOITMENT_USER']))? $record['L_APPOITMENT_USER'] : '';
  98. $dbgArr['record_write'] = (isset($record['A_ADM_COMPANY']))? $record['A_ADM_COMPANY'] : '';
  99. $dbgArr['record_read'] = (isset($record['A_CLASSIFIED']))? $record['A_CLASSIFIED'] : '';
  100. $dbgArr['user_groups'] = User::getLdapGroupsNames();
  101. if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">record('.$record['ID'].') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($dbgArr);echo'</pre>';}
  102. if ($dbgArr['record_owner'] && $dbgArr['record_owner'] == User::getLogin()) {
  103. if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo '<p>true - is record owner</p>';}
  104. return true;
  105. }
  106. if ($dbgArr['record_read']) {
  107. if (in_array($dbgArr['record_read'], $dbgArr['user_groups'])) {
  108. if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo '<p>true - has group read</p>';}
  109. return true;
  110. }
  111. } else {
  112. if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo '<p>true - group read not set</p>';}
  113. return true;
  114. }
  115. return false;
  116. }
  117. public function showFormItem($taskPerm, $fieldID, $fName, $fValue, $params = array(), $record = null) {
  118. $fields = $this->getFields();
  119. $fieldName = null;
  120. if (!empty($fields[$fieldID]) && !empty($fields[$fieldID]['name'])) $fieldName = $fields[$fieldID]['name'];
  121. if (!$fieldName || !$this->canReadField($fieldName)) {
  122. return '<div style="padding-top:7px" title="Brak dostępu do odczytu tego pola">*****</div>';
  123. }
  124. if ($record && !$this->canReadObjectField($fieldName, $record)) {
  125. return '<div style="padding-top:7px" title="Brak dostępu do odczytu tego pola">*****</div>';
  126. }
  127. // echo '<pre style="padding-top:7px">';print_r($fValue);echo'</pre>';// TODO: RMME TEST
  128. $out = '<div style="padding-top:7px">';
  129. $xsdTypeEx = explode(':', $this->getXsdFieldType($fieldName));
  130. if ('ref' == $xsdTypeEx[0] || 'alias_ref' == $xsdTypeEx[0]) {
  131. if (!empty($fValue)) {
  132. if (is_array($fValue)) {
  133. foreach ($fValue as $val) {
  134. if (!empty($val['xlink'])) {
  135. // p5_objects:AccessOwner.4517
  136. $typeNameEx = explode(':', $val['xlink']);
  137. $link = Api_WfsNs::getNsUri($xsdTypeEx[1]) . '#' . $typeNameEx[1];
  138. if (!preg_match('/^([a-zA-Z0-9_]+)\:([a-zA-Z0-9_]+)\.([0-9]+)$/', $val['xlink'], $matches)) {
  139. $out .= "Wrong xlink format <!-- ({$val['xlink']}) -->";
  140. } else {
  141. // [0] => p5_objects:File.46
  142. // [1] => p5_objects
  143. // [2] => File
  144. // [3] => 46
  145. $nsPrefixRemote = $matches[1];
  146. $typeRemote = $matches[2];
  147. $idRemote = $matches[3];
  148. // TODO: validate nsPrefix and type with xsdFieldType
  149. $editLink = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $nsPrefixRemote . '/' . $typeRemote . '#EDIT/' . $idRemote;
  150. $out .= '<a href="' . $editLink . '">' . $link . '</a><br>';
  151. }
  152. } else {
  153. // TODO: BUG missing xlink
  154. }
  155. }
  156. } else if (is_scalar($fValue)) {
  157. $out .= $fValue;
  158. } else {
  159. $out .= '???';
  160. }
  161. }
  162. } else {
  163. $out .= $fValue;
  164. }
  165. $out .= '</div>';
  166. return $out;
  167. }
  168. public function getRawLabel($posLimit = 20) { return substr($this->getName(), 0, $posLimit); }
  169. public function getItems($params = array()) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: use ParseOgcQuery
  170. public function getTotal($params = array()) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }// TODO: use ParseOgcQuery
  171. public function getItem($primaryKey) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  172. public function addItem($todoItem) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  173. public function updateItem($itemPatch) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  174. public function getGeomFieldType($fieldName) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  175. public function getPrimaryKeyField() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  176. public function getAttributesFromZasoby() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
  177. public function validateDeleteXml($action) {// @returns action tags, throws Exceptions
  178. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  179. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Delete action \$action:";print_r($action);echo "\n";}
  180. if (empty($action['tags'])) throw new Exception("Error Processing Delete Request - wrong Delete tag format");
  181. if ('open' != $action['tags'][0]['type']) throw new Exception("Error Processing Delete Request - wrong Delete tag format");
  182. if ('Filter' != $action['tags'][0]['tag']) throw new Exception("Error Processing Delete Request - wrong Delete tag format");
  183. $filterLvl = $action['tags'][0]['level'];
  184. array_shift($action['tags']);// remove first openig tag Filter
  185. array_pop($action['tags']);// remove last closing tag Filter
  186. if (empty($action['tags'])) throw new Exception("Error Processing Delete Request - missing FeatureId in Delete tag");
  187. $action['Filter'] = array();
  188. $featureName = $this->getName();
  189. foreach ($action['tags'] as $idx => $tag) {
  190. if ($tag['level'] <= $filterLvl) throw new Exception("Error Processing Delete Request - wrong Delete tag format Delete/Filter/{$tag['tag']}[{$idx}]");
  191. if ('FeatureId' != $tag['tag']) throw new Exception("Error Processing Delete Request - wrong Delete tag format - expected 'FeatureId' but '{$tag['tag']}' found");
  192. if (empty($tag['attributes'])) throw new Exception("Error Processing Delete Request - missing attributes in Delete/Filter/FeatureId[{$idx}]");
  193. if (empty($tag['attributes']['fid'])) throw new Exception("Error Processing Delete Request - missing @fid attribute in Delete/Filter/FeatureId[{$idx}]");
  194. $idFeature = $tag['attributes']['fid'];
  195. if ("{$featureName}." != substr($idFeature, 0, strlen("{$featureName}."))) throw new Exception("Error Processing Delete Request - wrong typeName in Delete/Filter/FeatureId[{$idx}]/@fid");
  196. $idFeature = substr($idFeature, strlen("{$featureName}."));
  197. if (!$this->checkPrimaryKeyFormat($idFeature)) throw new Exception("Error Processing Delete Request - wrong primary key format in Delete/Filter/FeatureId[{$idx}]/@fid");
  198. $action['Filter'][] = $idFeature;
  199. }
  200. $action['fields'] = array();
  201. $action['fields']['the_geom'] = array();
  202. $action['fields']['the_geom'][] = array('type'=>'complete', 'value'=>'NULL');
  203. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Delete action validate return \$action:";print_r($action);echo "\n";}
  204. return $action;
  205. }
  206. public function validateUpdateXml($action) {// @returns action tags, throws Exceptions
  207. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  208. // split Update tag to Property and Filter
  209. $fieldsLvl = $action['tags'][0]['level'];
  210. $totalTags = count($action['tags']);
  211. $tagsToSplice = array();// args for splice(offset, length to remove, new values)
  212. for ($i = 0, $cnt = $totalTags, $lastIdxToSplice = 0; $i < $cnt; $i++) {
  213. $tag = $action['tags'][$i];
  214. 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";}
  215. if ($fieldsLvl == $tag['level'] && 'complete' == $tag['type']) {// field - flat value
  216. } else if ($fieldsLvl == $tag['level'] && 'open' == $tag['type']) {// field - nested - start
  217. $lastIdxToSplice = $i;
  218. $tagsToSplice[$lastIdxToSplice] = $tag;
  219. $tagsToSplice[$lastIdxToSplice]['action'] = 'Insert -- TODO: L.' . __LINE__;
  220. $tagsToSplice[$lastIdxToSplice]['tags'] = array();
  221. $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
  222. } else if (null !== $lastIdxToSplice && $fieldsLvl == $tag['level'] && 'close' == $tag['type']) {// field - nested - end
  223. $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
  224. $lastIdxToSplice = null;
  225. } else if (null !== $lastIdxToSplice) {
  226. $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
  227. } else {
  228. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " BUG: Update to flat fields loop({$i}) \$tag('{$tag['tag']}', '{$tag['type']}', '{$tag['level']}')"."\n";}
  229. throw new Exception("Error Processing Update Request at Update tag for type '{$action['typeName']}'");
  230. }
  231. }
  232. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . ' TODO: FIX $action:';print_r($action);echo "\n";}
  233. if (empty($tagsToSplice)) throw new Exception("Error Processing Update Request - missing Property or Filter tags");
  234. if (!empty($tagsToSplice)) {// Update
  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['typeName'] = $action['typeName'];
  242. $childTag['action'] = 'Update -- TODO L.' . __LINE__;
  243. array_splice($action['tags'], $offset, $toRemove, array($childTag));
  244. }
  245. // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Insert to flat fields \$action:";print_r($action);echo "\n";}
  246. }
  247. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Update action after first split \$action:";print_r($action);echo "\n";}
  248. if (count($action['tags']) < 2) throw new Exception("Error Processing Update Request - missing Property or Filter tags");
  249. $filterTag = array_pop($action['tags']);
  250. $action['Filter'] = $this->validateUpdateFilterTag($filterTag);
  251. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Update action after validate Filter \$action['Filter']:";print_r($action['Filter']);echo "\n";}
  252. $action['fields'] = $this->validateUpdatePropertyTags($action['tags']);
  253. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Update action after validate Property \$action['fields']:";print_r($action['fields']);echo "\n";}
  254. foreach ($action['fields'] as $fieldName => $propertyTag) {
  255. if (!$this->canWriteField($fieldName)) throw new Api_WfsException("Access Denied to Update field '{$fieldName}' in object '{$action['typeName']}'", __LINE__, null, 'MissingFieldPermWrite', 'request');
  256. $value = $propertyTag['value'];
  257. $this->validateFieldRestrictions($fieldName, $value);
  258. }
  259. return $action;
  260. }
  261. public function validateUpdateFilterTag($filterTag) {// @returns Filter tag (feature id), throws Exceptions
  262. // TODO: allow ogc filter for update multiple rows
  263. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  264. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Update validateUpdateFilterTag \$filterTag:";print_r($filterTag);echo "\n";}
  265. if ('Filter' != $filterTag['tag']) throw new Exception("Error Processing Update Request - missing Filter tag");
  266. $idFeature = null;
  267. if (empty($filterTag['tags'])) throw new Exception("Error Processing Update Request - wrong Filter tag format");
  268. if ('FeatureId' != $filterTag['tags'][0]['tag']) throw new Exception("Error Processing Update Request - wrong Filter tag format");
  269. if (empty($filterTag['tags'][0]['attributes']['fid'])) throw new Exception("Error Processing Update Request - missing Filter tag @fid");
  270. $idFeature = $filterTag['tags'][0]['attributes']['fid'];
  271. $featureName = $this->getName();
  272. if ("{$featureName}." != substr($idFeature, 0, strlen("{$featureName}."))) throw new Exception("Error Processing Update Request - wrong typeName in Filter/@fid");
  273. $idFeature = substr($idFeature, strlen("{$featureName}."));
  274. if (!$this->checkPrimaryKeyFormat($idFeature)) throw new Exception("Error Processing Update Request - wrong primary key format in Filter/@fid");
  275. return $idFeature;
  276. }
  277. public function checkPrimaryKeyFormat($idFeature) {// @returns bool
  278. return ((string)$idFeature === (string)intval($idFeature));
  279. }
  280. public function validateUpdatePropertyTags($tags) {// @returns Property tags (fields), throws Exceptions
  281. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  282. $fields = array();
  283. if($DBG>3){echo 'C.'.get_class($this).' L.' . __LINE__ . " Update validateUpdatePropertyTags \$fields:";print_r($tags);echo "\n";}
  284. foreach ($tags as $idx => $tag) {
  285. if ('Property' != $tag['tag']) throw new Exception("Error Processing Update Request - tag '{$tag['tag']}' is not allowed in Update tag");
  286. if (count($tag['tags']) < 2) throw new Exception("Error Processing Update Request - wrong format in Update/Property[{$idx}]");
  287. $tagName = array_shift($tag['tags']);
  288. if ('Name' != $tagName['tag']) throw new Exception("Error Processing Update Request - missing Name tag in Update/Property[{$idx}]");
  289. if (empty($tagName['value'])) throw new Exception("Error Processing Update Request - empty field name in Update/Property[{$idx}]");
  290. if (false !== strpos($tagName['value'], '/')) throw new Exception("Error Processing Update Request - xpath in Update/Property[{$idx}] field name not implemented", 501);
  291. // TODO: check field name as xpath, eg. File/content
  292. $fieldName = $tagName['value'];
  293. $tagValue = array_shift($tag['tags']);
  294. $fieldType = $this->getXsdFieldType($fieldName);
  295. if ('Value' != $tagValue['tag']) throw new Exception("Error Processing Update Request - missing Value tag in Update/Property[{$idx}]");
  296. if ('open' == $tagValue['type']) {
  297. array_pop($tag['tags']);
  298. $tagValue['tags'] = $tag['tags'];
  299. if (empty($tagValue['tags'])) throw new Exception("Error Processing Update Request - wrong Value tag format in Update/Property[{$idx}]");
  300. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." validate fields loop({$idx}) loop({$fieldName}) \$fieldType({$fieldType})"."\n";}
  301. if ('gml:' == substr($fieldType, 0, 4)) {
  302. $tagValue['value'] = $this->convertGmlTagsToWkt($fieldType, $tagValue['tags']);
  303. } else {
  304. // TODO: return $fields[$fieldName][] = array('type'=>'open', 'typeName'=>$fieldType, 'tags'=>...
  305. throw new Exception("Error Processing Update Request - wrong Value tag format for field '{$fieldName}' (Update/Property[{$idx}])");
  306. }
  307. } else if ('complete' == $tagValue['type']) {
  308. if (!empty($tag['tags'])) throw new Exception("Error Processing Update Request - wrong Value tag format in Update/Property[{$idx}]");
  309. } else throw new Exception("Error Processing Update Request - missing Value tag in Update/Property[{$idx}]");
  310. $value = V::get('value', '', $tagValue);
  311. $fields[$fieldName][] = array('type'=>'complete', 'value'=>$value);
  312. }
  313. return $fields;
  314. }
  315. public function validateInsertXml($action) {// @returns action tag, throws Exceptions
  316. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  317. // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " TODO: F.".__FUNCTION__." \$action:";print_r($action);echo "\n";}
  318. // split Insert tags by first level fields - nested structures like gml (the_geom)
  319. $fieldsLvl = $action['tags'][0]['level'];
  320. $totalTags = count($action['tags']);
  321. $tagsToSplice = array();// args for splice(offset, length to remove, new values)
  322. for ($i = 0, $cnt = $totalTags, $lastIdxToSplice = 0; $i < $cnt; $i++) {
  323. $tag = $action['tags'][$i];
  324. 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";}
  325. if ($fieldsLvl == $tag['level'] && 'complete' == $tag['type']) {// field - flat value
  326. } else if ($fieldsLvl == $tag['level'] && 'open' == $tag['type']) {// field - nested - start
  327. $lastIdxToSplice = $i;
  328. $tagsToSplice[$lastIdxToSplice] = $tag;
  329. $tagsToSplice[$lastIdxToSplice]['action'] = 'Insert';
  330. $tagsToSplice[$lastIdxToSplice]['tags'] = array();
  331. $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
  332. } else if (null !== $lastIdxToSplice && $fieldsLvl == $tag['level'] && 'close' == $tag['type']) {// field - nested - end
  333. $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
  334. $lastIdxToSplice = null;
  335. } else if (null !== $lastIdxToSplice) {
  336. $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
  337. } else {
  338. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " BUG: Insert to flat fields loop({$i}) \$tag('{$tag['tag']}', '{$tag['type']}', '{$tag['level']}')"."\n";}
  339. throw new Exception("Error Processing Request at Insert tag for type '{$action['typeName']}'");
  340. }
  341. }
  342. // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . ' TODO: FIX $action:';print_r($action);echo "\n";}
  343. if (!empty($tagsToSplice)) {// Insert deep object
  344. // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Insert to flat fields \$tagsToSplice:";print_r($tagsToSplice);echo "\n";}
  345. $tagsToSplice = array_reverse($tagsToSplice, $preserve_keys = true);
  346. foreach ($tagsToSplice as $offset => $childTag) {
  347. $toRemove = count($childTag['tags']);
  348. array_pop($childTag['tags']);// remove last closing tag
  349. $tag = array_shift($childTag['tags']);
  350. $childTag['action'] = 'Insert';
  351. {// TODO: duplicate code - get prefix for typeName
  352. $typeName = $tag['tag'];
  353. if (false === strpos($typeName, ':')) {
  354. $nsType = V::get('xmlns', '', $tag['attributes']);
  355. if (!$nsType) throw new Exception("Error Processing Request - Missing object namespace '{$tag['tag']}'");
  356. $prefix = Api_WfsNs::getNsPrefix($nsType);
  357. if (!$prefix) {
  358. if ($typeName == substr(rtrim($nsType, '/'), -1 * strlen($typeName))) {// typeName may be added to ns uri
  359. $nsBaseForType = substr(rtrim($nsType, '/'), 0, -1 * strlen($typeName) - 1);
  360. $prefix = Api_WfsNs::getNsPrefix($nsBaseForType);
  361. }
  362. }
  363. if (!$prefix) throw new Exception("Error Processing Request - Unrecognized namespace uri '{$nsType}' for object '{$tag['tag']}'");
  364. $typeName = "{$prefix}:{$typeName}";
  365. }
  366. $childTag['typeName'] = $typeName;
  367. }
  368. array_splice($action['tags'], $offset, $toRemove, array($childTag));
  369. $action['isDeepObject'] = true;
  370. }
  371. // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Insert to flat fields \$action:";print_r($action);echo "\n";}
  372. }
  373. // TODO: validate sequence order from schema - needed?
  374. // validate fields
  375. $action['fields'] = array();
  376. foreach ($action['tags'] as $idx => $tag) {
  377. $fieldName = $tag['tag'];
  378. if (false !== strpos($fieldName, ':')) $fieldName = substr($fieldName, strpos($fieldName, ':') + 1);
  379. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." validate fields loop({$idx}) \$fieldName:";print_r($fieldName);echo "\n";}
  380. $field = array();
  381. $field['tag'] = $tag['tag'];
  382. $field['type'] = $tag['type'];
  383. if (!empty($tag['typeName'])) $field['typeName'] = $tag['typeName'];
  384. if (!empty($tag['action'])) $field['action'] = $tag['action'];
  385. if (!empty($tag['value']) || '0' === $tag['value'] || 0 === $tag['value']) $field['value'] = $tag['value'];
  386. if (!empty($tag['tags'])) $field['tags'] = $tag['tags'];
  387. $action['fields'][$fieldName][] = $field;
  388. }
  389. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." validate fields loop({$idx}) \$action['fields']:";print_r($action['fields']);echo "\n";}
  390. foreach ($action['fields'] as $fieldName => $childFields) {
  391. foreach ($childFields as $idx => $field) {
  392. // TODO: validate minOccurs, maxOccurs
  393. }
  394. }
  395. $fieldPK = $this->getPrimaryKeyField();
  396. foreach ($action['fields'] as $fieldName => $childFields) {
  397. if ($fieldName == $fieldPK) continue;
  398. foreach ($childFields as $idx => $field) {
  399. if (!$this->canCreateField($fieldName)) throw new Api_WfsException("Access Denied to Create field '{$fieldName}' in object '{$action['typeName']}'", __LINE__, null, 'MissingFieldPermCreate', 'request');
  400. if ('open' == $field['type']) {
  401. $fieldType = $this->getXsdFieldType($fieldName);
  402. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." validate fields loop({$idx}) loop({$fieldName}) \$fieldType({$fieldType})"."\n";}
  403. if ('gml:' == substr($fieldType, 0, 4)) {
  404. $action['fields'][$fieldName][$idx]['value'] = $this->convertGmlTagsToWkt($fieldType, $field['tags']);
  405. unset($action['fields'][$fieldName][$idx]['tags']);
  406. unset($action['fields'][$fieldName][$idx]['typeName']);
  407. unset($action['fields'][$fieldName][$idx]['action']);
  408. $action['fields'][$fieldName][$idx]['type'] = 'complete';
  409. } else if ('p5_objects:' == substr($fieldType, 0, 11)) {
  410. // TODO: read value recursive? (like geom?)
  411. } else if ('ref:p5_objects:' == substr($fieldType, 0, 15)) {
  412. // TODO: read value recursive? - validate recursive
  413. }
  414. }
  415. $this->validateFieldRestrictions($fieldName, $value);
  416. }
  417. }
  418. // TODO: validate nillable
  419. // TODO: validate recursive fields with type 'p5_objects:*' (without 'value')
  420. foreach ($action['fields'] as $fieldName => $childFields) {
  421. foreach ($childFields as $idx => $field) {
  422. if ('open' == $field['type']) {
  423. $fieldType = $this->getXsdFieldType($fieldName);
  424. if ('ref:p5_objects:' == substr($fieldType, 0, 15)) {
  425. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." TODO: -------> validateInsertXml(\$field) \$field:";print_r($field);echo "\n";}
  426. $acl = $this->getAclFromTypeName(substr($fieldType, 4));
  427. $action['fields'][$fieldName][$idx] = $acl->validateInsertXml($field);
  428. }
  429. }
  430. }
  431. }
  432. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." return ============ \$action:";print_r($action);echo "\n";}
  433. return $action;
  434. }
  435. public function validateFieldRestrictions($fieldName, $value) {// @returns null, throws Exceptions
  436. // TODO: restrictions
  437. }
  438. public function checkFieldRestrictions($fieldName, $value) {// @returns array of error msgs
  439. // TODO: restrictions
  440. }
  441. // like Api_WfsGeomTypeConverter::convertGmlCoordinatesToWkt($gmlCoordinates) where $gmlCoordinates is from converted wfs request
  442. public function convertGmlTagsToWkt($fieldType, $tags) {
  443. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  444. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " TODO: F.".__FUNCTION__." \$fieldType({$fieldType}) \$tags:";print_r($tags);echo "\n";}
  445. $cs = ','; $ts = ' '; $value = null; $wktType = null;
  446. if ('gml:LineStringPropertyType' == $fieldType) {
  447. // <gml:LineString srsName="EPSG:4326">
  448. // <gml:coordinates cs="," ts=" ">18.25240580856418049,54.48879768607960017 18.27014261382555915,54.46219247818753217</gml:coordinates>
  449. // </gml:LineString>
  450. if (3 != count($tags)) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
  451. if ('gml:LineString' !== $tags[0]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
  452. if ('open' !== $tags[0]['type']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
  453. if (empty($tags[1]['attributes']['cs'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
  454. if (empty($tags[1]['attributes']['ts'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
  455. if (empty($tags[1]['value'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
  456. $cs = $tags[1]['attributes']['cs'];
  457. $ts = $tags[1]['attributes']['ts'];
  458. $value = $tags[1]['value'];
  459. $wktType = 'LINESTRING';
  460. } else if ('gml:PointPropertyType' == $fieldType) {
  461. // <gml:Point srsDimension="1" srsName="http://www.opengis.net/gml/srs/epsg.xml#3857">
  462. // <gml:coordinates decimal="." cs="," ts=" ">-33.7291,-56.3353820</gml:coordinates>
  463. // </gml:Point>
  464. // TODO: @decimal
  465. if (3 != count($tags)) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
  466. if ('gml:Point' !== $tags[0]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
  467. if ('open' !== $tags[0]['type']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
  468. if (empty($tags[1]['attributes']['cs'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
  469. if (empty($tags[1]['attributes']['ts'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
  470. if (empty($tags[1]['value'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
  471. $cs = $tags[1]['attributes']['cs'];
  472. $ts = $tags[1]['attributes']['ts'];
  473. $value = $tags[1]['value'];
  474. $wktType = 'POINT';
  475. } else if ('gml:PolygonPropertyType' == $fieldType) {
  476. if (7 != count($tags)) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  477. if ('gml:Polygon' !== $tags[0]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  478. if ('open' !== $tags[0]['type']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  479. if ('gml:outerBoundaryIs' !== $tags[1]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  480. if ('gml:LinearRing' !== $tags[2]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  481. if ('gml:coordinates' !== $tags[3]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  482. if (empty($tags[3]['attributes']['cs'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  483. if (empty($tags[3]['attributes']['ts'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  484. if (empty($tags[3]['value'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
  485. $cs = $tags[3]['attributes']['cs'];
  486. $ts = $tags[3]['attributes']['ts'];
  487. $value = $tags[3]['value'];
  488. $wktType = 'POLYGON';
  489. } else {
  490. throw new Exception("Error Processing Request - type '{$fieldType}' not supported");
  491. }
  492. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " TODO: F.".__FUNCTION__." \$fieldType({$fieldType}) TODO \$value:";print_r($value);echo "\n";}
  493. return self::convertGmlCoordsToWkt($wktType, $value, ['cs'=>$cs, 'ts'=>$ts]);
  494. }
  495. /**
  496. * @param $wktType: 'POLYGON', 'POINT', 'LINESTRING'
  497. * @param $params: array(decimal="." cs="," ts="whitespace")
  498. * decimal - decimal separator (default '.')
  499. * cs - coordinate values separator (default ',')
  500. * ts - tuple separator (a single space by default)
  501. *
  502. * @example:
  503. * <gml:coordinates cs="," ts=" ">18.25240580856418049,54.48879768607960017 18.27014261382555915,54.46219247818753217</gml:coordinates>
  504. * Core_AclBase::convertGmlCoordsToWkt('18.25240580856418049,54.48879768607960017 18.27014261382555915,54.46219247818753217', ['cs'=>',', 'ts'=>' '])
  505. */
  506. public static function convertGmlCoordsToWkt($wktType, $coords, $params = array()) {
  507. $cs = V::get('cs', ',', $params);
  508. $decimal = V::get('decimal', '.', $params);
  509. $ts = V::get('ts', ' ', $params);
  510. $gmlNumber = '(\-?\d+\\' . $decimal . '?\d*)';
  511. $gmlPoint = '(' . $gmlNumber . $cs . $gmlNumber . ')';
  512. $gmlPoints = $gmlPoint . '(' . $ts . $gmlPoint . ')+';
  513. switch ($wktType) {
  514. case 'POINT': $regex = '/^' . "{$gmlPoint}" . '$/'; break;
  515. case 'LINESTRING': $regex = '/^' . "{$gmlPoints}" . '$/'; break;
  516. case 'POLYGON': $regex = '/^' . "{$gmlPoints}" . '$/'; break;
  517. default: throw new Exception("Unsupported geometry type '{$wktType}'");
  518. }
  519. if (!preg_match($regex, $coords, $matches)) {
  520. throw new Exception("Wrong coordinates format for type '{$wktType}'");
  521. }
  522. $wkt = $coords;
  523. $wkt = str_replace(array($cs, $ts), array('#cs#', '#ts#'), $wkt);
  524. $wkt = str_replace(array('#cs#', '#ts#'), array(' ', ','), $wkt);
  525. 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))
  526. return "{$wktType}({$wkt})";
  527. }
  528. public function getAclFromTypeName($typeName) {// TODO: mv to another class, duplicate from Api_WfsServerBase::getAclFromTypeName($typeName)
  529. $typeEx = explode(':', $typeName);
  530. if (2 != count($typeEx)) throw new Exception("Could not get acl for '{$typeName}' - syntax error");
  531. if ('p5_' != substr($typeEx[0], 0, 3)) throw new Exception("Could not get acl for '{$typeName}' - prefix error");
  532. $sourceName = substr($typeEx[0], 3);
  533. $objName = $typeEx[1];
  534. $acl = User::getAcl()->getObjectAcl($sourceName, $objName);
  535. if (!$acl) throw new Exception("Could not get acl for '{$typeName}'");
  536. $forceTblAclInit = 0;//('1' == V::get('_force', '', $_GET));
  537. $acl->init($forceTblAclInit);
  538. return $acl;
  539. }
  540. public function insertXml($action) {// @param $action = [ 'typeName' => '*:*', 'fields'=>[ `name`=>[`fld`, `fld`, ...], ... ] ]
  541. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  542. if (empty($action['typeName'])) throw new Exception("Error Processing Request - missing typeName", 500);
  543. if (empty($action['fields'])) throw new Exception("Error Processing Request - missing fields for type '{$action['typeName']}'", 500);
  544. {// Insert with primaryKey -> Update
  545. $fieldPK = $this->getPrimaryKeyField();
  546. if (array_key_exists($fieldPK, $action['fields'])) {
  547. $pk = $action['fields'][$fieldPK][0]['value'];
  548. $action['Filter'] = $pk;
  549. $affected = $this->updateXml($action);
  550. return ($affected >= 0) ? $pk : -1;
  551. }
  552. }
  553. $sqlInsert = array();
  554. $sqlChildInsert = array();
  555. foreach ($action['fields'] as $fieldName => $childFields) {
  556. foreach ($childFields as $idx => $field) {
  557. if ('complete' == $field['type']) {
  558. $sqlInsert[$fieldName][$idx] = $field['value'];
  559. } else if ('open' == $field['type']) {
  560. $childAcl = $this->getAclFromTypeName($field['typeName']);// TODO: or $fieldType = $this->getXsdFieldType($fieldName);// TODO: ref:p5_objects:File
  561. $sqlChildInsert[$fieldName][$idx] = $childAcl->insertXml($field);
  562. } else throw new Exception("Error Processing Request - BUG Unrecognized type '{$field['type']}'", 500);
  563. }
  564. }
  565. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." \$sqlInsert:";print_r($sqlInsert);echo "\n";}
  566. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." \$sqlChildInsert:";print_r($sqlChildInsert);echo "\n";}
  567. $sqlObj = array();
  568. foreach ($sqlInsert as $fieldName => $childFields) {
  569. $value = $childFields[0];
  570. // foreach ($childFields as $idx => $value) // TODO: check maxOcures
  571. if ($this->isGeomField($fieldName)) $value = "GeomFromText('{$value}')";
  572. $sqlObj["{$fieldName}"] = $value;
  573. }
  574. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." addItem(\$sqlObj) \$sqlObj:";print_r($sqlObj);echo "\n";}
  575. $insertedId = $this->addItem($sqlObj);
  576. foreach ($sqlChildInsert as $fieldName => $childFields) {
  577. foreach ($childFields as $idx => $childInsertedId) {
  578. $childAcl = $this->getAclFromTypeName($action['fields'][$fieldName][$idx]['typeName']);// TODO: or $fieldType = $this->getXsdFieldType($fieldName);// TODO: ref:p5_objects:File
  579. // $this->_insertRef($this->getRootTableName(), $childAcl->getRootTableName(), $insertedId, $childInsertedId);
  580. $this->_insertRef($fieldName, $insertedId, $childInsertedId);
  581. }
  582. }
  583. return $insertedId;
  584. }
  585. public function _insertRef($childName, $pk, $childPk) {// TODO: $idTransaction
  586. $refTable = $this->createRefTable($childName);
  587. $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
  588. $sqlChildPk = DB::getPDO()->quote($childPk, PDO::PARAM_STR);
  589. DB::getPDO()->exec("
  590. insert into `{$refTable}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`)
  591. values ({$sqlPk}, {$sqlChildPk})
  592. ");
  593. }
  594. public function createRefTable($childName) {// TODO: $idTransaction
  595. static $cacheRefTables = array();
  596. $objectName = $this->getName();
  597. $refTable = "{$objectName}__#REF__{$childName}";
  598. if (in_array($refTable, $cacheRefTables)) return $refTable;
  599. DB::getPDO()->exec("
  600. CREATE TABLE IF NOT EXISTS `{$refTable}` (
  601. `PRIMARY_KEY` int(11) NOT NULL,
  602. `REMOTE_PRIMARY_KEY` int(11) NOT NULL,
  603. -- TODO `TRANACTION_ID` int(11) NOT NULL
  604. KEY `PRIMARY_KEY` (`PRIMARY_KEY`),
  605. KEY `REMOTE_PRIMARY_KEY` (`REMOTE_PRIMARY_KEY`)
  606. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  607. ");
  608. $cacheRefTables[] = $refTable;
  609. return $refTable;
  610. }
  611. public function updateXml($action) {// @param $action = [ 'typeName' => '*:*', 'Filter'=>int, 'fields'=>[ `name`=>[`fld`, `fld`, ...], ... ] ]
  612. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  613. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " updateXml action \$action:";print_r($action);echo "\n";}
  614. if (empty($action['typeName'])) throw new Exception("Error Processing Request - missing typeName", 500);
  615. if (empty($action['Filter'])) throw new Exception("Error Processing Request - missing Filter for type '{$action['typeName']}'", 500);
  616. if (!$this->checkPrimaryKeyFormat($action['Filter'])) throw new Exception("Error Processing Request - wrong Filter format for type '{$action['typeName']}'", 501);
  617. if (empty($action['fields'])) throw new Exception("Error Processing Request - missing Property for type '{$action['typeName']}'", 500);
  618. // TODO: check acl user to update record ID = $action['Filter']
  619. $itemPatch = array();
  620. foreach ($action['fields'] as $fieldName => $childFields) {
  621. foreach ($childFields as $idx => $field) {
  622. if ('complete' != $field['type']) continue;// skip child nodes, REF
  623. $value = $field['value'];
  624. if ($this->isGeomField($fieldName)) $value = "GeomFromText('{$value}')";
  625. $itemPatch[$fieldName] = $value;
  626. }
  627. }
  628. $itemPatch[$this->getPrimaryKeyField()] = $action['Filter'];
  629. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " updateXml action \$itemPatch:";print_r($itemPatch);echo "\n";}
  630. $affected = $this->updateItem($itemPatch);
  631. // TODO: update/insert child nodes, REF
  632. return $affected;
  633. }
  634. public function deleteXml($action) {// @param $action = [ 'typeName' => '*:*', 'Filter'=>[int, ...], 'fields'=>[ `name`=>[`fld`, `fld`, ...], ... ] ]
  635. $DBG = V::get('DBG_XML', 0, $_GET, 'int');
  636. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " updateXml action \$action:";print_r($action);echo "\n";}
  637. if (empty($action['typeName'])) throw new Exception("Error Processing Request - missing typeName", 500);
  638. if (!is_array($action['Filter']) || empty($action['Filter'])) throw new Exception("Error Processing Request - missing Filter for type '{$action['typeName']}'", 500);
  639. foreach ($action['Filter'] as $fid) {
  640. if (!$this->checkPrimaryKeyFormat($fid)) throw new Exception("Error Processing Request - wrong Filter format for type '{$action['typeName']}'", 501);
  641. }
  642. if (empty($action['fields'])) throw new Exception("Error Processing Request - missing Property for type '{$action['typeName']}'", 500);
  643. // TODO: check acl user to update record ID = $action['Filter']
  644. $itemPatch = array();
  645. foreach ($action['fields'] as $fieldName => $childFields) {
  646. foreach ($childFields as $idx => $field) {
  647. if ('complete' != $field['type']) continue;// skip child nodes, REF
  648. $value = $field['value'];
  649. if ($this->isGeomField($fieldName)) $value = "GeomFromText('{$value}')";
  650. $itemPatch[$fieldName] = $value;
  651. }
  652. }
  653. $fieldPK = $this->getPrimaryKeyField();
  654. $deleted = 0;
  655. foreach ($action['Filter'] as $fid) {
  656. $itemPatch[$fieldPK] = $fid;
  657. if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " updateXml action \$itemPatch:";print_r($itemPatch);echo "\n";}
  658. $affected = $this->updateItem($itemPatch);
  659. if ($affected >= 0) $deleted += 1;
  660. }
  661. // TODO: update/insert child nodes, REF
  662. return $deleted;
  663. }
  664. }