AclBase.php 46 KB

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