AclBase.php 52 KB

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