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