AclBase.php 47 KB

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