AclBase.php 48 KB

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