AclBase.php 51 KB

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