AclBase.php 53 KB

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