AclBase.php 52 KB

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