AclBase.php 53 KB

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