AclBase.php 51 KB

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