AclBase.php 54 KB

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