AclBase.php 43 KB

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