AclBase.php 51 KB

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