| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914 |
- <?php
- Lib::loadClass('Api_WfsNs');
- Lib::loadClass('Api_WfsException');
- Lib::loadClass('User');
- Lib::loadClass('Core_AclHelper');
- Lib::loadClass('ACL');
- // TODO: replace every methods using $idZasob to use $fieldName
- /* TODO: fetch ACL from acl tables:
- @example for TestPerms [13051]:
- SELECT * FROM `CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW` WHERE `ID_TABLE` =13051; -- fetch id proces to $csvIdProces
- SELECT * FROM `CRM_PROCES_idx_USER_to_PROCES_VIEW` WHERE `ADM_ACCOUNT` = '{$userLogin}' and `ID_PROCES` in({$csvIdProces});
- */
- class Core_AclBase {
- public $_zasobID = 0;
- public $_db = 0; // database id zasobu
- public $_rootTableName = null;
- public function getNamespace() { throw new HttpException("Acl::getNamespace() Not implemented", 501); }
- public function getSourceName() { throw new HttpException("Acl::getSourceName() Not implemented", 501); }
- public function getName() { throw new HttpException("Acl::getName() Not implemented", 501); }
- public function getRootTableName() { throw new HttpException("Acl::getRootTableName() Not implemented", 501); }
- public function getXsdTypes() { throw new HttpException("Acl::getXsdTypes() Not implemented", 501); } // @returns [ fieldName => xsdType, ... ]
- public function getXsdFieldType($fieldName) { throw new HttpException("Acl::getXsdFieldType() Not implemented", 501); }
- public function hasSimpleSchema() { return false; }
- public function getSimpleSchema() { throw new HttpException("Acl::getSimpleSchema() Not implemented", 501); }
- // TODO: get more xsd restrictions like minOccurs, maxOccurs, nillable and restrictions
- public function getID() { return $this->_zasobID; }
- public function getDatabaseID() { return $this->_db; }
- public function init($force = false) { throw new HttpException("Acl::init() Not implemented", 501); }
- public function isInitialized() { throw new HttpException("Acl::isInitialized() Not implemented", 501); }
- public function hasField($fieldName) {// TODO: fix use Core_AclFields or ACL::getObjectFields($namespace) - use cache - one place to store structure
- foreach ($this->getFields() as $field) {
- if ($fieldName === $field['name']) return true;
- }
- return false;
- }
- public function getFields() {// @returns array - $this->_fields // TODO: mved to getFieldListByIdZasob
- /*
- $field = array();
- $field['name'] = $name;
- $field['perms'] = '';
- $field['opis'] = $opis;
- $field['sort_prio'] = $sort_prio;
- $field['label'] = $label;
- $this->_fields[$fieldID] = $field;
- */
- throw new HttpException("Acl::getFields() Not implemented", 501);
- }
- public function getFieldLabel($fieldName) {
- // DBG::log($this->getFields(), 'array', "DBG getFieldLabel({$fieldName})");
- foreach ($this->getFields() as $field) {
- if (empty($field['name']) && !empty($field['fieldNamespace'])) {
- if ($fieldName != $field['fieldNamespace']) continue;
- } else if (!empty($field['name'])) {
- if ($fieldName != $field['name']) continue;
- } else {
- continue; // skip unknown field name
- }
- return V::get('label', $fieldName, $field);
- }
- return $fieldName;
- }
- public function getFieldOpis($fieldName) {
- foreach ($this->getFields() as $field) {
- if (empty($field['name']) && !empty($field['fieldNamespace'])) {
- if ($fieldName != $field['fieldNamespace']) continue;
- } else if (!empty($field['name'])) {
- if ($fieldName != $field['name']) continue;
- } else {
- continue; // skip unknown field name
- }
- return V::get('opis', $fieldName, $field);
- }
- return $fieldName;
- }
- public function getFieldListByIdZasob() { throw new HttpException("Acl::getFieldListByIdZasob() Not implemented", 501); }// TODO: RMME - one field list function
- public function getLocalFieldList() { throw new HttpException("Acl::getLocalFieldList() Not implemented", 501); }// TODO: RMME - one field list function
- public function getRealFieldListByIdZasob() { throw new HttpException("Acl::getRealFieldListByIdZasob() Not implemented", 501); }// TODO: RMME - one field list function
- public function getVirtualFieldListByIdZasob() { throw new HttpException("Acl::getVirtualFieldListByIdZasob() Not implemented", 501); }// TODO: RMME - one field list function
- // TODO: public function getFieldList(); // @retuns array of field names
- public function isIntegerField($fieldName) { return ('xsd:integer' == $this->getXsdFieldType($fieldName)); }
- public function isDecimalField($fieldName) { throw new HttpException("Acl::isDecimalField() Not implemented", 501); }
- public function isGeomField($fieldName) { throw new HttpException("Acl::isGeomField() Not implemented", 501); }
- public function isDateField($fieldName) { throw new HttpException("Acl::isDateField() Not implemented", 501); }
- public function isDateTimeField($fieldName) { throw new HttpException("Acl::isDateTimeField() Not implemented", 501); }
- public function isTimeField($fieldName) { throw new HttpException("Acl::isTimeField() Not implemented", 501); }
- public function isStringField($fieldName) { throw new HttpException("Acl::isStringField() Not implemented", 501); }
- public function isTextField($fieldName) { throw new HttpException("Acl::isTextField() Not implemented", 501); }
- public function isBinaryField($fieldName) { throw new HttpException("Acl::isBinaryField() Not implemented", 501); }
- public function isEnumerationField($fieldName) { throw new HttpException("Acl::isEnumerationField() Not implemented", 501); }
- public function getEnumerations($fieldName) { throw new HttpException("Acl::getEnumerations() Not implemented", 501); }
- public function getFieldType($fieldName) { throw new HttpException("Acl::getFieldType() Not implemented", 501); }
- public function getFieldIdByName($fieldName) { throw new HttpException("Acl::getFieldIdByName() Not implemented", 501); }// TODO: legacy
- public function isAllowed($idZasob, $taskPerm, $record = null) { throw new HttpException("Acl::isAllowed() Not implemented", 501); }// TODO: legacy
- public function hasFieldPerm($idZasob, $taskPerm) { throw new HttpException("Acl::hasFieldPerm() Not implemented", 501); }// TODO: legacy
- // TODO: replace isAllowed, hasFieldPerm, getFieldIdByName
- public function canCreateField($fieldName) { throw new HttpException("Acl::canCreateField() Not implemented", 501); }
- public function canReadField($fieldName) { throw new HttpException("Acl::canReadField() Not implemented", 501); }
- public function canReadObjectField($fieldName, $record) { throw new HttpException("Acl::canReadObjectField() Not implemented", 501); }
- public function canWriteField($fieldName) { throw new HttpException("Acl::canWriteField() Not implemented", 501); }
- public function canWriteObjectField($fieldName, $record) { throw new HttpException("Acl::canWriteObjectField() Not implemented", 501); }
- public function canWriteRecord($record) {// TODO: AclHelper?
- $record = (array)$record;
- $dbgArr = array();
- $dbgArr['record_owner'] = (isset($record['L_APPOITMENT_USER']))? $record['L_APPOITMENT_USER'] : '';
- $dbgArr['record_write'] = (isset($record['A_ADM_COMPANY']))? $record['A_ADM_COMPANY'] : '';
- $dbgArr['record_read'] = (isset($record['A_CLASSIFIED']))? $record['A_CLASSIFIED'] : '';
- $dbgArr['user_groups'] = User::getLdapGroupsNames();
- 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>';}
- if ($dbgArr['record_owner'] && $dbgArr['record_owner'] == User::getLogin()) {
- if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo '<p>true - is record owner</p>';}
- return true;
- }
- if ($dbgArr['record_write']) {
- if (in_array($dbgArr['record_write'], $dbgArr['user_groups'])) {
- if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo '<p>true - has group write</p>';}
- return true;
- }
- } else {
- if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo '<p>true - group write not set</p>';}
- return true;
- }
- return false;
- }
- public function canReadRecord($record) {// TODO: AclHelper?
- $record = (array)$record;
- $dbgArr = array();
- $dbgArr['record_owner'] = (isset($record['L_APPOITMENT_USER']))? $record['L_APPOITMENT_USER'] : '';
- $dbgArr['record_write'] = (isset($record['A_ADM_COMPANY']))? $record['A_ADM_COMPANY'] : '';
- $dbgArr['record_read'] = (isset($record['A_CLASSIFIED']))? $record['A_CLASSIFIED'] : '';
- $dbgArr['user_groups'] = User::getLdapGroupsNames();
- 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>';}
- if ($dbgArr['record_owner'] && $dbgArr['record_owner'] == User::getLogin()) {
- if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo '<p>true - is record owner</p>';}
- return true;
- }
- if ($dbgArr['record_read']) {
- if (in_array($dbgArr['record_read'], $dbgArr['user_groups'])) {
- if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo '<p>true - has group read</p>';}
- return true;
- }
- } else {
- if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo '<p>true - group read not set</p>';}
- return true;
- }
- return false;
- }
- public function showFormItem($taskPerm, $fieldID, $fName, $fValue, $params = array(), $record = null) {
- $fields = $this->getFields();
- $fieldName = null;
- if (!empty($fields[$fieldID]) && !empty($fields[$fieldID]['name'])) $fieldName = $fields[$fieldID]['name'];
- if (!$fieldName || !$this->canReadField($fieldName)) {
- return '<div style="padding-top:7px" title="Brak dostępu do odczytu tego pola">*****</div>';
- }
- if ($record && !$this->canReadObjectField($fieldName, $record)) {
- return '<div style="padding-top:7px" title="Brak dostępu do odczytu tego pola">*****</div>';
- }
- // echo '<pre style="padding-top:7px">';print_r($fValue);echo'</pre>';// TODO: RMME TEST
- $out = '<div style="padding-top:7px">';
- $xsdTypeEx = explode(':', $this->getXsdFieldType($fieldName));
- if ('ref' == $xsdTypeEx[0] || 'alias_ref' == $xsdTypeEx[0]) {
- if (!empty($fValue)) {
- if (is_array($fValue)) {
- foreach ($fValue as $val) {
- if (!empty($val['xlink'])) {
- // p5_objects:AccessOwner.4517
- $typeNameEx = explode(':', $val['xlink']);
- $link = Api_WfsNs::getNsUri($xsdTypeEx[1]) . '#' . $typeNameEx[1];
- if (!preg_match('/^([a-zA-Z0-9_]+)\:([a-zA-Z0-9_]+)\.([0-9]+)$/', $val['xlink'], $matches)) {
- $out .= "Wrong xlink format <!-- ({$val['xlink']}) -->";
- } else {
- // [0] => p5_objects:File.46
- // [1] => p5_objects
- // [2] => File
- // [3] => 46
- $nsPrefixRemote = $matches[1];
- $typeRemote = $matches[2];
- $idRemote = $matches[3];
- // TODO: validate nsPrefix and type with xsdFieldType
- $editLink = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $nsPrefixRemote . '/' . $typeRemote . '#EDIT/' . $idRemote;
- $out .= '<a href="' . $editLink . '">' . $link . '</a><br>';
- }
- } else {
- // TODO: BUG missing xlink
- }
- }
- } else if (is_scalar($fValue)) {
- $out .= $fValue;
- } else {
- $out .= '???';
- }
- }
- } else {
- $out .= $fValue;
- }
- $out .= '</div>';
- return $out;
- }
- public function getRawLabel($posLimit = 20) { return substr($this->getName(), 0, $posLimit); }
- public function buildQuery($params = array()) {
- Lib::loadClass('AclQueryFeatures');
- return new AclQueryFeatures($this, $params, $legacyMode = true);
- }
- public function getItems($params = array()) { throw new HttpException("Acl::getItems() Not implemented", 501); }// TODO: use ParseOgcQuery
- public function getTotal($params = array()) { throw new HttpException("Acl::getTotal() Not implemented", 501); }// TODO: use ParseOgcQuery
- public function getItem($primaryKey, $params = []) { throw new HttpException("Acl::getItem() Not implemented", 501); }
- public function itemsFetchRefs(&$items) {
- $DBG = V::get('DBG_DS', 0, $_GET, 'int');
- $refs = array();// fieldName => namespace
- foreach ($this->getRealFieldListByIdZasob() as $id => $fieldName) {
- $fieldType = $this->getXsdFieldType($fieldName);
- if ('ref:' == substr($fieldType, 0, 4)) $refs[$fieldName] = substr($fieldType, 4);
- else if ('alias_ref:' == substr($fieldType, 0, 10)) $refs[$fieldName] = substr($fieldType, 10);
- // if ('ref:' == substr($fieldType, 0, 4)) $refs[$fieldName] = str_replace(':', '/', substr($fieldType, 4));
- // else if ('alias_ref:' == substr($fieldType, 0, 10)) $refs[$fieldName] = str_replace(':', '/', substr($fieldType, 10));
- // else if ('ref_uri:' == substr($fieldType, 0, 8)) $refs[$fieldName] = substr($fieldType, 8);
- }
- if (empty($refs)) return $items;
- $pkList = array_keys($items);
- $sqlPk = array(); foreach ($pkList as $pk) { $sqlPk[] = DB::getPDO()->quote($pk, PDO::PARAM_STR); } $sqlPk = implode(", ", $sqlPk);
- $refRows = array();// $fieldName => [ pk, ... ]
- foreach ($refs as $fieldName => $childNs) {
- $acl = Core_AclHelper::getAclByTypeName($childNs);
- // TODO: Core_AclBase->fetchRefs($fieldName, $pkList = array());// $refPk[$fieldName] = $this->fetchRefs($fieldName, $pkList);
- $refTableName = Core_AclHelper::getRefTable($this->getName(), $fieldName);
- $refRows[$fieldName] = DB::getPDO()->fetchAllByKey("
- select r.*
- from `{$refTableName}` r
- where r.PRIMARY_KEY in({$sqlPk})
- and r.A_STATUS != 'DELETED'
- ", $key = 'PRIMARY_KEY');
- if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems loop(\$fieldName:{$fieldName}) \$refTableName:({$refTableName}), \$refRows[$fieldName]";print_r($refRows[$fieldName]);echo"\n";}
- }
- foreach ($refRows as $fieldName => $refList) {
- foreach ($refList as $pk => $ref) {
- $items[ $pk ][ $fieldName ][] = array('xlink' => "{$refs[$fieldName]}.{$ref['REMOTE_PRIMARY_KEY']}");
- }
- }
- return $items;
- }
- public function addItem($todoItem) { throw new HttpException("Acl::addItem() Not implemented", 501); }
- public function updateItem($itemPatch) { throw new HttpException("Acl::updateItem() Not implemented", 501); }
- public function getGeomFieldType($fieldName) { throw new HttpException("Acl::getGeomFieldType() Not implemented", 501); }
- public function getPrimaryKeyField() { throw new HttpException("Acl::getPrimaryKeyField() Not implemented", 501); }
- public function getAttributesFromZasoby() { throw new HttpException("Acl::getAttributesFromZasoby() Not implemented", 501); }
- public function validateDeleteXml($action) {// @returns action tags, throws Exceptions
- $DBG = V::get('DBG_XML', 0, $_GET, 'int');
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Delete action \$action:";print_r($action);echo "\n";}
- if (empty($action['tags'])) throw new Exception("Error Processing Delete Request - wrong Delete tag format");
- if ('open' != $action['tags'][0]['type']) throw new Exception("Error Processing Delete Request - wrong Delete tag format");
- if ('Filter' != $action['tags'][0]['tag']) throw new Exception("Error Processing Delete Request - wrong Delete tag format");
- $filterLvl = $action['tags'][0]['level'];
- array_shift($action['tags']);// remove first openig tag Filter
- array_pop($action['tags']);// remove last closing tag Filter
- if (empty($action['tags'])) throw new Exception("Error Processing Delete Request - missing FeatureId in Delete tag");
- $action['Filter'] = array();
- $featureName = $this->getName();
- foreach ($action['tags'] as $idx => $tag) {
- if ($tag['level'] <= $filterLvl) throw new Exception("Error Processing Delete Request - wrong Delete tag format Delete/Filter/{$tag['tag']}[{$idx}]");
- if ('FeatureId' != $tag['tag']) throw new Exception("Error Processing Delete Request - wrong Delete tag format - expected 'FeatureId' but '{$tag['tag']}' found");
- if (empty($tag['attributes'])) throw new Exception("Error Processing Delete Request - missing attributes in Delete/Filter/FeatureId[{$idx}]");
- if (empty($tag['attributes']['fid'])) throw new Exception("Error Processing Delete Request - missing @fid attribute in Delete/Filter/FeatureId[{$idx}]");
- $idFeature = $tag['attributes']['fid'];
- if ("{$featureName}." != substr($idFeature, 0, strlen("{$featureName}."))) throw new Exception("Error Processing Delete Request - wrong typeName in Delete/Filter/FeatureId[{$idx}]/@fid");
- $idFeature = substr($idFeature, strlen("{$featureName}."));
- if (!$this->checkPrimaryKeyFormat($idFeature)) throw new Exception("Error Processing Delete Request - wrong primary key format in Delete/Filter/FeatureId[{$idx}]/@fid");
- $action['Filter'][] = $idFeature;
- }
- $action['fields'] = array();
- $action['fields']['the_geom'] = array();
- $action['fields']['the_geom'][] = array('type'=>'complete', 'value'=>'NULL');
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Delete action validate return \$action:";print_r($action);echo "\n";}
- return $action;
- }
- public function validateUpdateXml($action) {// @returns action tags, throws Exceptions
- $DBG = V::get('DBG_XML', 0, $_GET, 'int');
- // split Update tag to Property and Filter
- $fieldsLvl = $action['tags'][0]['level'];
- $totalTags = count($action['tags']);
- $tagsToSplice = array();// args for splice(offset, length to remove, new values)
- for ($i = 0, $cnt = $totalTags, $lastIdxToSplice = 0; $i < $cnt; $i++) {
- $tag = $action['tags'][$i];
- 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";}
- if ($fieldsLvl == $tag['level'] && 'complete' == $tag['type']) {// field - flat value
- } else if ($fieldsLvl == $tag['level'] && 'open' == $tag['type']) {// field - nested - start
- $lastIdxToSplice = $i;
- $tagsToSplice[$lastIdxToSplice] = $tag;
- $tagsToSplice[$lastIdxToSplice]['action'] = 'Insert -- TODO: L.' . __LINE__;
- $tagsToSplice[$lastIdxToSplice]['tags'] = array();
- $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
- } else if (null !== $lastIdxToSplice && $fieldsLvl == $tag['level'] && 'close' == $tag['type']) {// field - nested - end
- $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
- $lastIdxToSplice = null;
- } else if (null !== $lastIdxToSplice) {
- $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
- } else {
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " BUG: Update to flat fields loop({$i}) \$tag('{$tag['tag']}', '{$tag['type']}', '{$tag['level']}')"."\n";}
- throw new Exception("Error Processing Update Request at Update tag for type '{$action['typeName']}'");
- }
- }
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . ' TODO: FIX $action:';print_r($action);echo "\n";}
- if (empty($tagsToSplice)) throw new Exception("Error Processing Update Request - missing Property or Filter tags");
- if (!empty($tagsToSplice)) {// Update
- // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Insert to flat fields \$tagsToSplice:";print_r($tagsToSplice);echo "\n";}
- $tagsToSplice = array_reverse($tagsToSplice, $preserve_keys = true);
- foreach ($tagsToSplice as $offset => $childTag) {
- $toRemove = count($childTag['tags']);
- array_pop($childTag['tags']);// remove last closing tag
- $tag = array_shift($childTag['tags']);
- $childTag['typeName'] = $action['typeName'];
- $childTag['action'] = 'Update -- TODO L.' . __LINE__;
- array_splice($action['tags'], $offset, $toRemove, array($childTag));
- }
- // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Insert to flat fields \$action:";print_r($action);echo "\n";}
- }
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Update action after first split \$action:";print_r($action);echo "\n";}
- if (count($action['tags']) < 2) throw new Exception("Error Processing Update Request - missing Property or Filter tags");
- $filterTag = array_pop($action['tags']);
- $action['Filter'] = $this->validateUpdateFilterTag($filterTag);
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Update action after validate Filter \$action['Filter']:";print_r($action['Filter']);echo "\n";}
- $action['fields'] = $this->validateUpdatePropertyTags($action['tags']);
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Update action after validate Property \$action['fields']:";print_r($action['fields']);echo "\n";}
- foreach ($action['fields'] as $fieldName => $propertyTag) {
- if (!$this->canWriteField($fieldName)) throw new Api_WfsException("Access Denied to Update field '{$fieldName}' in object '{$action['typeName']}'", __LINE__, null, 'MissingFieldPermWrite', 'request');
- $value = $propertyTag['value'];
- $this->validateFieldRestrictions($fieldName, $value);
- }
- return $action;
- }
- public function validateUpdateFilterTag($filterTag) {// @returns Filter tag (feature id), throws Exceptions
- // TODO: allow ogc filter for update multiple rows
- $DBG = V::get('DBG_XML', 0, $_GET, 'int');
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Update validateUpdateFilterTag \$filterTag:";print_r($filterTag);echo "\n";}
- if ('Filter' != $filterTag['tag']) throw new Exception("Error Processing Update Request - missing Filter tag");
- $idFeature = null;
- if (empty($filterTag['tags'])) throw new Exception("Error Processing Update Request - wrong Filter tag format");
- if ('FeatureId' != $filterTag['tags'][0]['tag']) throw new Exception("Error Processing Update Request - wrong Filter tag format");
- if (empty($filterTag['tags'][0]['attributes']['fid'])) throw new Exception("Error Processing Update Request - missing Filter tag @fid");
- $idFeature = $filterTag['tags'][0]['attributes']['fid'];
- $featureName = $this->getName();
- if ("{$featureName}." != substr($idFeature, 0, strlen("{$featureName}."))) throw new Exception("Error Processing Update Request - wrong typeName in Filter/@fid");
- $idFeature = substr($idFeature, strlen("{$featureName}."));
- if (!$this->checkPrimaryKeyFormat($idFeature)) throw new Exception("Error Processing Update Request - wrong primary key format in Filter/@fid");
- return $idFeature;
- }
- public function checkPrimaryKeyFormat($idFeature) {// @returns bool
- return ((string)$idFeature === (string)intval($idFeature));
- }
- public function validateUpdatePropertyTags($tags) {// @returns Property tags (fields), throws Exceptions
- $DBG = V::get('DBG_XML', 0, $_GET, 'int');
- $fields = array();
- if($DBG>3){echo 'C.'.get_class($this).' L.' . __LINE__ . " Update validateUpdatePropertyTags \$fields:";print_r($tags);echo "\n";}
- foreach ($tags as $idx => $tag) {
- if ('Property' != $tag['tag']) throw new Exception("Error Processing Update Request - tag '{$tag['tag']}' is not allowed in Update tag");
- if (count($tag['tags']) < 2) throw new Exception("Error Processing Update Request - wrong format in Update/Property[{$idx}]");
- $tagName = array_shift($tag['tags']);
- if ('Name' != $tagName['tag']) throw new Exception("Error Processing Update Request - missing Name tag in Update/Property[{$idx}]");
- if (empty($tagName['value'])) throw new Exception("Error Processing Update Request - empty field name in Update/Property[{$idx}]");
- if (false !== strpos($tagName['value'], '/')) throw new Exception("Error Processing Update Request - xpath in Update/Property[{$idx}] field name not implemented", 501);
- // TODO: check field name as xpath, eg. File/content
- $fieldName = $tagName['value'];
- $tagValue = array_shift($tag['tags']);
- $fieldType = $this->getXsdFieldType($fieldName);
- if ('Value' != $tagValue['tag']) throw new Exception("Error Processing Update Request - missing Value tag in Update/Property[{$idx}]");
- if ('open' == $tagValue['type']) {
- array_pop($tag['tags']);
- $tagValue['tags'] = $tag['tags'];
- if (empty($tagValue['tags'])) throw new Exception("Error Processing Update Request - wrong Value tag format in Update/Property[{$idx}]");
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." validate fields loop({$idx}) loop({$fieldName}) \$fieldType({$fieldType})"."\n";}
- if ('gml:' == substr($fieldType, 0, 4)) {
- $tagValue['value'] = $this->convertGmlTagsToWkt($fieldType, $tagValue['tags']);
- } else if ('ref:' == substr($fieldType, 0, 4)) {
- if (1 == count($tagValue['tags'])) {
- $tagValue['value'] = $tagValue['tags'][0]['attributes']['xlink:href'];// https://biuro.biall-net.pl/wfs/default_objects#AccessGroupRead.27
- } else {
- throw new Exception("Error Processing Update Request - wrong Value tag format for field '{$fieldName}' (Update/Property[{$idx}])");
- }
- } else {
- throw new Exception("Error Processing Update Request - wrong Value tag format for field '{$fieldName}' (Update/Property[{$idx}])");
- }
- } else if ('complete' == $tagValue['type']) {
- if (!empty($tag['tags'])) throw new Exception("Error Processing Update Request - wrong Value tag format in Update/Property[{$idx}]");
- } else throw new Exception("Error Processing Update Request - missing Value tag in Update/Property[{$idx}]");
- $value = V::get('value', '', $tagValue);
- $fields[$fieldName][] = array('type'=>'complete', 'value'=>$value);
- }
- return $fields;
- }
- public function validateInsertXml($action) {// @returns action tag, throws Exceptions
- $DBG = V::get('DBG_XML', 0, $_GET, 'int');
- // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " TODO: F.".__FUNCTION__." \$action:";print_r($action);echo "\n";}
- // split Insert tags by first level fields - nested structures like gml (the_geom)
- $fieldsLvl = $action['tags'][0]['level'];
- $totalTags = count($action['tags']);
- $tagsToSplice = array();// args for splice(offset, length to remove, new values)
- $namespaceUri = Api_WfsNs::getNsUri($this->getSourceName());
- for ($i = 0; $i < $totalTags; $i++) {// fix missing namespace
- $tag = $action['tags'][$i];
- if (!V::get('xmlns', '', $tag['attributes'])) {
- $action['tags'][$i]['attributes']['xmlns'] = $namespaceUri;
- }
- }
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Insert to flat fields \$action";print_r($action);echo"\n";}
- for ($i = 0, $cnt = $totalTags, $lastIdxToSplice = 0; $i < $cnt; $i++) {
- $tag = $action['tags'][$i];
- 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";}
- if ($fieldsLvl == $tag['level'] && 'complete' == $tag['type']) {// field - flat value
- } else if ($fieldsLvl == $tag['level'] && 'open' == $tag['type']) {// field - nested - start
- $lastIdxToSplice = $i;
- $tagsToSplice[$lastIdxToSplice] = $tag;
- $tagsToSplice[$lastIdxToSplice]['action'] = 'Insert';
- $tagsToSplice[$lastIdxToSplice]['tags'] = array();
- $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
- } else if (null !== $lastIdxToSplice && $fieldsLvl == $tag['level'] && 'close' == $tag['type']) {// field - nested - end
- $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
- $lastIdxToSplice = null;
- } else if (null !== $lastIdxToSplice) {
- $tagsToSplice[$lastIdxToSplice]['tags'][] = $tag;
- } else {
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " BUG: Insert to flat fields loop({$i}) \$tag('{$tag['tag']}', '{$tag['type']}', '{$tag['level']}')"."\n";}
- throw new Exception("Error Processing Request at Insert tag for type '{$action['typeName']}'");
- }
- }
- // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . ' TODO: FIX $action:';print_r($action);echo "\n";}
- if (!empty($tagsToSplice)) {// Insert deep object
- // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Insert to flat fields \$tagsToSplice:";print_r($tagsToSplice);echo "\n";}
- $tagsToSplice = array_reverse($tagsToSplice, $preserve_keys = true);
- foreach ($tagsToSplice as $offset => $childTag) {
- $toRemove = count($childTag['tags']);
- array_pop($childTag['tags']);// remove last closing tag
- $tag = array_shift($childTag['tags']);
- $childTag['action'] = 'Insert';
- {// TODO: duplicate code - get prefix for typeName
- $typeName = $tag['tag'];
- if (false === strpos($typeName, ':')) {
- $nsType = V::get('xmlns', '', $tag['attributes']);
- if (!$nsType) throw new Exception("Error Processing Request - Missing object namespace '{$tag['tag']}'");
- $prefix = Api_WfsNs::getNsPrefix($nsType);
- if (!$prefix) {
- if ($typeName == substr(rtrim($nsType, '/'), -1 * strlen($typeName))) {// typeName may be added to ns uri
- $nsBaseForType = substr(rtrim($nsType, '/'), 0, -1 * strlen($typeName) - 1);
- $prefix = Api_WfsNs::getNsPrefix($nsBaseForType);
- }
- }
- if (!$prefix) throw new Exception("Error Processing Request - Unrecognized namespace uri '{$nsType}' for object '{$tag['tag']}'");
- $typeName = "{$prefix}:{$typeName}";
- }
- $childTag['typeName'] = $typeName;
- }
- array_splice($action['tags'], $offset, $toRemove, array($childTag));
- $action['isDeepObject'] = true;
- }
- // if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " Insert to flat fields \$action:";print_r($action);echo "\n";}
- }
- // TODO: validate sequence order from schema - needed?
- // validate fields
- $action['fields'] = array();
- foreach ($action['tags'] as $idx => $tag) {
- $fieldName = $tag['tag'];
- if (false !== strpos($fieldName, ':')) $fieldName = substr($fieldName, strpos($fieldName, ':') + 1);
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." validate fields loop({$idx}) \$fieldName:";print_r($fieldName);echo "\n";}
- $field = array();
- $field['tag'] = $tag['tag'];
- $field['type'] = $tag['type'];
- if (!empty($tag['typeName'])) $field['typeName'] = $tag['typeName'];
- if (!empty($tag['action'])) $field['action'] = $tag['action'];
- if (!empty($tag['value']) || '0' === $tag['value'] || 0 === $tag['value']) $field['value'] = $tag['value'];
- if (!empty($tag['tags'])) $field['tags'] = $tag['tags'];
- $action['fields'][$fieldName][] = $field;
- }
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." validate fields loop({$idx}) \$action['fields']:";print_r($action['fields']);echo "\n";}
- foreach ($action['fields'] as $fieldName => $childFields) {
- foreach ($childFields as $idx => $field) {
- // TODO: validate minOccurs, maxOccurs
- }
- }
- $fieldPK = $this->getPrimaryKeyField();
- foreach ($action['fields'] as $fieldName => $childFields) {
- if ($fieldName == $fieldPK) continue;
- foreach ($childFields as $idx => $field) {
- if (!$this->canCreateField($fieldName)) throw new Api_WfsException("Access Denied to Create field '{$fieldName}' in object '{$action['typeName']}'", __LINE__, null, 'MissingFieldPermCreate', 'request');
- if ('open' == $field['type']) {
- $fieldType = $this->getXsdFieldType($fieldName);
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." validate fields loop({$idx}) loop({$fieldName}) \$fieldType({$fieldType})"."\n";}
- if ('gml:' == substr($fieldType, 0, 4)) {
- $action['fields'][$fieldName][$idx]['value'] = $this->convertGmlTagsToWkt($fieldType, $field['tags']);
- unset($action['fields'][$fieldName][$idx]['tags']);
- unset($action['fields'][$fieldName][$idx]['typeName']);
- unset($action['fields'][$fieldName][$idx]['action']);
- $action['fields'][$fieldName][$idx]['type'] = 'complete';
- } else if ('p5_objects:' == substr($fieldType, 0, 11)) {
- // TODO: read value recursive? (like geom?)
- } else if ('ref:p5_objects:' == substr($fieldType, 0, 15)) {
- // TODO: read value recursive? - validate recursive
- } else if ('default_objects:' == substr($fieldType, 0, 16)) {
- // TODO: read value recursive? (like geom?)
- } else if ('ref:default_objects:' == substr($fieldType, 0, 20)) {
- // TODO: read value recursive? - validate recursive
- }
- }
- $this->validateFieldRestrictions($fieldName, $value);
- }
- }
- // TODO: validate nillable
- // TODO: validate recursive fields with type 'p5_objects:*' (without 'value')
- foreach ($action['fields'] as $fieldName => $childFields) {
- foreach ($childFields as $idx => $field) {
- if ('open' == $field['type']) {
- $fieldType = $this->getXsdFieldType($fieldName);
- if ('ref:p5_objects:' == substr($fieldType, 0, 15)) {
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." TODO: -------> validateInsertXml(\$field) \$field:";print_r($field);echo "\n";}
- $acl = Core_AclHelper::getAclByTypeName(substr($fieldType, 4));
- $action['fields'][$fieldName][$idx] = $acl->validateInsertXml($field);
- }
- }
- }
- }
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." return ============ \$action:";print_r($action);echo "\n";}
- return $action;
- }
- public function validateFieldRestrictions($fieldName, $value) {// @returns null, throws Exceptions
- // TODO: restrictions
- }
- public function checkFieldRestrictions($fieldName, $value) {// @returns array of error msgs
- // TODO: restrictions
- }
- // like Api_WfsGeomTypeConverter::convertGmlCoordinatesToWkt($gmlCoordinates) where $gmlCoordinates is from converted wfs request
- public function convertGmlTagsToWkt($fieldType, $tags) {
- $DBG = V::get('DBG_XML', 0, $_GET, 'int');
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " TODO: F.".__FUNCTION__." \$fieldType({$fieldType}) \$tags:";print_r($tags);echo "\n";}
- $cs = ','; $ts = ' '; $value = null; $wktType = null;
- if ('gml:LineStringPropertyType' == $fieldType) {
- // <gml:LineString srsName="EPSG:4326">
- // <gml:coordinates cs="," ts=" ">18.25240580856418049,54.48879768607960017 18.27014261382555915,54.46219247818753217</gml:coordinates>
- // </gml:LineString>
- if (3 != count($tags)) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
- if ('gml:LineString' !== $tags[0]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
- if ('open' !== $tags[0]['type']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
- // if (empty($tags[1]['attributes']['cs'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
- // if (empty($tags[1]['attributes']['ts'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
- if (empty($tags[1]['value'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:LineString'");
- $cs = (!empty($tags[1]['attributes']['cs'])) ? $tags[1]['attributes']['cs'] : ',';
- $ts = (!empty($tags[1]['attributes']['ts'])) ? $tags[1]['attributes']['ts'] : ' ';
- $value = $tags[1]['value'];
- $wktType = 'LINESTRING';
- } else if ('gml:PointPropertyType' == $fieldType) {
- // <gml:Point srsDimension="1" srsName="http://www.opengis.net/gml/srs/epsg.xml#3857">
- // <gml:coordinates decimal="." cs="," ts=" ">-33.7291,-56.3353820</gml:coordinates>
- // </gml:Point>
- // TODO: @decimal
- if (3 != count($tags)) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
- if ('gml:Point' !== $tags[0]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
- if ('open' !== $tags[0]['type']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
- // if (empty($tags[1]['attributes']['cs'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
- // if (empty($tags[1]['attributes']['ts'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
- if (empty($tags[1]['value'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Point'");
- $cs = (!empty($tags[1]['attributes']['cs'])) ? $tags[1]['attributes']['cs'] : ',';
- $ts = (!empty($tags[1]['attributes']['ts'])) ? $tags[1]['attributes']['ts'] : ' ';
- $value = $tags[1]['value'];
- $wktType = 'POINT';
- } else if ('gml:PolygonPropertyType' == $fieldType) {
- if (7 != count($tags)) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
- if ('gml:Polygon' !== $tags[0]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
- if ('open' !== $tags[0]['type']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
- if ('gml:outerBoundaryIs' !== $tags[1]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
- if ('gml:LinearRing' !== $tags[2]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
- if ('gml:coordinates' !== $tags[3]['tag']) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
- // if (empty($tags[3]['attributes']['cs'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
- // if (empty($tags[3]['attributes']['ts'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
- if (empty($tags[3]['value'])) throw new Exception("#L".__LINE__." Error Processing Request - expected type 'gml:Polygon'");
- $cs = (!empty($tags[3]['attributes']['cs'])) ? $tags[3]['attributes']['cs'] : ',';
- $ts = (!empty($tags[3]['attributes']['ts'])) ? $tags[3]['attributes']['ts'] : ' ';
- $value = $tags[3]['value'];
- $wktType = 'POLYGON';
- } else {
- throw new Exception("Error Processing Request - type '{$fieldType}' not supported");
- }
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " TODO: F.".__FUNCTION__." \$fieldType({$fieldType}) TODO \$value:";print_r($value);echo "\n";}
- return self::convertGmlCoordsToWkt($wktType, $value, ['cs'=>$cs, 'ts'=>$ts]);
- }
- /**
- * @param $wktType: 'POLYGON', 'POINT', 'LINESTRING'
- * @param $params: array(decimal="." cs="," ts="whitespace")
- * decimal - decimal separator (default '.')
- * cs - coordinate values separator (default ',')
- * ts - tuple separator (a single space by default)
- *
- * @example:
- * <gml:coordinates cs="," ts=" ">18.25240580856418049,54.48879768607960017 18.27014261382555915,54.46219247818753217</gml:coordinates>
- * Core_AclBase::convertGmlCoordsToWkt('18.25240580856418049,54.48879768607960017 18.27014261382555915,54.46219247818753217', ['cs'=>',', 'ts'=>' '])
- */
- public static function convertGmlCoordsToWkt($wktType, $coords, $params = array()) {
- $cs = V::get('cs', ',', $params);
- $decimal = V::get('decimal', '.', $params);
- $ts = V::get('ts', ' ', $params);
- $gmlNumber = '(\-?\d+\\' . $decimal . '?\d*)';
- $gmlPoint = '(' . $gmlNumber . $cs . $gmlNumber . ')';
- $gmlPoints = $gmlPoint . '(' . $ts . $gmlPoint . ')+';
- switch ($wktType) {
- case 'POINT': $regex = '/^' . "{$gmlPoint}" . '$/'; break;
- case 'LINESTRING': $regex = '/^' . "{$gmlPoints}" . '$/'; break;
- case 'POLYGON': $regex = '/^' . "{$gmlPoints}" . '$/'; break;
- default: throw new Exception("Unsupported geometry type '{$wktType}'");
- }
- if (!preg_match($regex, $coords, $matches)) {
- throw new Exception("Wrong coordinates format for type '{$wktType}'");
- }
- $wkt = $coords;
- $wkt = str_replace(array($cs, $ts), array('#cs#', '#ts#'), $wkt);
- $wkt = str_replace(array('#cs#', '#ts#'), array(' ', ','), $wkt);
- 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))
- return "{$wktType}({$wkt})";
- }
- public function insertXml($action) {// @param $action = [ 'typeName' => '*:*', 'fields'=>[ `name`=>[`fld`, `fld`, ...], ... ] ]
- $DBG = V::get('DBG_XML', 0, $_GET, 'int');
- if (empty($action['typeName'])) throw new Exception("Error Processing Request - missing typeName", 500);
- if (empty($action['fields'])) throw new Exception("Error Processing Request - missing fields for type '{$action['typeName']}'", 500);
- {// Insert with primaryKey -> Update
- $fieldPK = $this->getPrimaryKeyField();
- if (array_key_exists($fieldPK, $action['fields'])) {
- $pk = $action['fields'][$fieldPK][0]['value'];
- $action['Filter'] = $pk;
- $affected = $this->updateXml($action);
- return ($affected >= 0) ? $pk : -1;
- }
- }
- $sqlInsert = array();
- $sqlChildInsert = array();
- foreach ($action['fields'] as $fieldName => $childFields) {
- foreach ($childFields as $idx => $field) {
- if ('complete' == $field['type']) {
- $sqlInsert[$fieldName][$idx] = $field['value'];
- } else if ('open' == $field['type']) {
- $childAcl = Core_AclHelper::getAclByTypeName($field['typeName']);// TODO: or $fieldType = $this->getXsdFieldType($fieldName);// TODO: ref:p5_objects:File
- $sqlChildInsert[$fieldName][$idx] = $childAcl->insertXml($field);
- } else throw new Exception("Error Processing Request - BUG Unrecognized type '{$field['type']}'", 500);
- }
- }
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." \$sqlInsert:";print_r($sqlInsert);echo "\n";}
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." \$sqlChildInsert:";print_r($sqlChildInsert);echo "\n";}
- $sqlObj = array();
- foreach ($sqlInsert as $fieldName => $childFields) {
- $value = $childFields[0];
- // foreach ($childFields as $idx => $value) // TODO: check maxOcures
- if ($this->isGeomField($fieldName)) $value = "GeomFromText('{$value}')";
- $sqlObj["{$fieldName}"] = $value;
- }
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " F.".__FUNCTION__." addItem(\$sqlObj) \$sqlObj:";print_r($sqlObj);echo "\n";}
- $insertedId = $this->addItem($sqlObj);
- foreach ($sqlChildInsert as $fieldName => $childFields) {
- foreach ($childFields as $idx => $childInsertedId) {
- $childAcl = Core_AclHelper::getAclByTypeName($action['fields'][$fieldName][$idx]['typeName']);// TODO: or $fieldType = $this->getXsdFieldType($fieldName);// TODO: ref:p5_objects:File
- // $this->insertRef($this->getRootTableName(), $childAcl->getRootTableName(), $insertedId, $childInsertedId);
- $this->insertRef($fieldName, $insertedId, $childInsertedId);
- }
- }
- return $insertedId;
- }
- public function insertRef($childName, $pk, $childPk) {// TODO: $idTransaction
- $refTable = ACL::getRefTable($this->getNamespace(), $childName);
- DB::getPDO()->insert($refTable, [
- 'PRIMARY_KEY' => $pk,
- 'REMOTE_PRIMARY_KEY' => $childPk
- // TODO: 'REMOTE_TYPENAME' =>
- ]);
- // TODO: REMOVE legacy code below:
- $refTable = Core_AclHelper::getRefTable($this->getName(), $childName);
- $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
- $sqlChildPk = DB::getPDO()->quote($childPk, PDO::PARAM_STR);
- DB::getPDO()->exec("
- insert into `{$refTable}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`)
- values ({$sqlPk}, {$sqlChildPk})
- ");
- }
- public function cleanRefs($childName, $pk) {// TODO: $idTransaction
- $refTable = ACL::getRefTable($this->getNamespace(), $childName);
- DB::getPDO()->update($refTable, 'PRIMARY_KEY', $pk, [
- 'A_STATUS' => 'DELETED',
- ]);
- // TODO: REMOVE legacy code below:
- $refTable = Core_AclHelper::getRefTable($this->getName(), $childName);
- $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
- DB::getPDO()->exec("
- update `{$refTable}` set `A_STATUS` = 'DELETED'
- where `PRIMARY_KEY` = {$sqlPk}
- ");
- }
- public function removeRef($childName, $pk, $refPk) {// TODO: $idTransaction
- $refTable = ACL::getRefTable($this->getNamespace(), $childName);
- $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
- $sqlRefPk = DB::getPDO()->quote($refPk, PDO::PARAM_STR);
- DB::getPDO()->exec("
- update `{$refTable}` set A_STATUS = 'DELETED'
- where PRIMARY_KEY = {$sqlPk}
- and REMOTE_PRIMARY_KEY = {$sqlRefPk}
- ");
- // TODO: REMOVE legacy code below:
- $refTable = Core_AclHelper::getRefTable($this->getName(), $childName);
- DB::getPDO()->exec("
- update `{$refTable}` set A_STATUS = 'DELETED'
- where PRIMARY_KEY = {$sqlPk}
- and REMOTE_PRIMARY_KEY = {$sqlRefPk}
- ");
- }
- public function getChildHistTable($childName) {
- throw new Exception("Not implemented getChildHistTable in AclBase - only SimpleSchema is supported");
- // return Core_AclHelper::getChildHistTable($this->getRootTableName(), $childName, $schema);
- }
- public function updateXml($action) {// @param $action = [ 'typeName' => '*:*', 'Filter'=>int, 'fields'=>[ `name`=>[`fld`, `fld`, ...], ... ] ]
- $DBG = V::get('DBG_XML', 0, $_GET, 'int');
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " updateXml action \$action:";print_r($action);echo "\n";}
- if (empty($action['typeName'])) throw new Exception("Error Processing Request - missing typeName", 500);
- if (empty($action['Filter'])) throw new Exception("Error Processing Request - missing Filter for type '{$action['typeName']}'", 500);
- if (!$this->checkPrimaryKeyFormat($action['Filter'])) throw new Exception("Error Processing Request - wrong Filter format for type '{$action['typeName']}'", 501);
- if (empty($action['fields'])) throw new Exception("Error Processing Request - missing Property for type '{$action['typeName']}'", 500);
- // TODO: check acl user to update record ID = $action['Filter']
- $itemPatch = array();
- $refPatch = array();
- foreach ($action['fields'] as $fieldName => $childFields) {
- $fieldType = $this->getXsdFieldType($fieldName);
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " \$fieldType:";print_r($fieldType);echo "\n";}// ref:default_objects:AccessGroupRead
- foreach ($childFields as $idx => $field) {
- if ('complete' != $field['type']) continue;// skip child nodes, REF
- $value = $field['value'];
- if ($this->isGeomField($fieldName)) $value = "GeomFromText('{$value}')";
- if ('ref:' == substr($fieldType, 0, 4)) {
- $refPatch[$fieldName][$idx] = $value;
- } else {
- $itemPatch[$fieldName] = $value;
- }
- }
- }
- $id = $itemPatch[$this->getPrimaryKeyField()] = $action['Filter'];
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " updateXml action \$itemPatch({$id}):";print_r($itemPatch);echo "\n";}
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " updateXml action \$refPatch:";print_r($refPatch);echo "\n";}
- {
- foreach ($refPatch as $fieldName => $childValues) {
- $this->cleanRefs($fieldName, $id);
- foreach ($childValues as $idx => $value) {
- list($nsUrl, $featureId) = explode('#', $value, 2);// https://biuro.biall-net.pl/wfs/default_objects#AccessGroupRead.27
- list($featureName, $primaryKey) = explode('.', $featureId, 2);
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " \$featureId: ";print_r($featureId);echo "\n";}// AccessGroupRead.27
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " \$featureName: ";print_r($featureName);echo "\n";}// AccessGroupRead
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " \$primaryKey: ";print_r($primaryKey);echo "\n";}// 27
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " \$nsUrl: ";print_r($nsUrl);echo "\n";}// https://biuro.biall-net.pl/wfs/default_objects
- $refAcl = Core_AclHelper::getAclByNamespace("{$nsUrl}/{$featureName}");
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " \$refAcl: ";print_r($refAcl);echo "\n";}
- $remoteItem = $refAcl->getItem($primaryKey);
- if (!$remoteItem) throw new Exception("Brak dostępu do obiektu: {$value}");
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " \$remoteItem: ";print_r($remoteItem);echo "\n";}
- // TODO: validate
- $this->insertRef($fieldName, $id, $primaryKey);
- }
- }
- }
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " updateXml action \$refPatch:";print_r($refPatch);echo "\n";}
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " updateXml action \$itemPatch:";print_r($itemPatch);echo "\n";}
- if($DBG){die();}
- $affected = $this->updateItem($itemPatch);
- // TODO: update/insert child nodes, REF
- return $affected;
- }
- public function deleteXml($action) {// @param $action = [ 'typeName' => '*:*', 'Filter'=>[int, ...], 'fields'=>[ `name`=>[`fld`, `fld`, ...], ... ] ]
- $DBG = V::get('DBG_XML', 0, $_GET, 'int');
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " updateXml action \$action:";print_r($action);echo "\n";}
- if (empty($action['typeName'])) throw new Exception("Error Processing Request - missing typeName", 500);
- if (!is_array($action['Filter']) || empty($action['Filter'])) throw new Exception("Error Processing Request - missing Filter for type '{$action['typeName']}'", 500);
- foreach ($action['Filter'] as $fid) {
- if (!$this->checkPrimaryKeyFormat($fid)) throw new Exception("Error Processing Request - wrong Filter format for type '{$action['typeName']}'", 501);
- }
- if (empty($action['fields'])) throw new Exception("Error Processing Request - missing Property for type '{$action['typeName']}'", 500);
- // TODO: check acl user to update record ID = $action['Filter']
- $itemPatch = array();
- foreach ($action['fields'] as $fieldName => $childFields) {
- foreach ($childFields as $idx => $field) {
- if ('complete' != $field['type']) continue;// skip child nodes, REF
- $value = $field['value'];
- if ($this->isGeomField($fieldName)) $value = "GeomFromText('{$value}')";
- $itemPatch[$fieldName] = $value;
- }
- }
- $fieldPK = $this->getPrimaryKeyField();
- $deleted = 0;
- foreach ($action['Filter'] as $fid) {
- $itemPatch[$fieldPK] = $fid;
- if($DBG){echo 'C.'.get_class($this).' L.' . __LINE__ . " updateXml action \$itemPatch:";print_r($itemPatch);echo "\n";}
- $affected = $this->updateItem($itemPatch);
- if ($affected >= 0) $deleted += 1;
- }
- // TODO: update/insert child nodes, REF
- return $deleted;
- }
- public function getSqlFieldName($childName) { throw new Exception("Unimplemented - TODO: " . get_class($this) . "::" . __FUNCTION__); }
- public function getHistItems($primaryKey) { throw new Exception("Unimplemented - TODO: " . get_class($this) . "::" . __FUNCTION__); }
- public function lastUpdateDate() {
- try {
- if (!$this->_rootTableName) throw new Exception("Missing rootTableName in (" . get_class($this) . ", " . $this->getNamespace() . ")");
- $lastUpdateDate = DB::getPDO()->fetchValue("
- 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
- from `{$this->_rootTableName}_HIST`
- order by ID DESC
- limit 1
- ");
- if ($lastUpdateDate) {// convert to xsd format '2002-05-30T09:00:00'
- $xsdLastUpdate = '';
- if (preg_match('/^\d\d\d\d\-\d\d\-\d\d\-\d\d:\d\d$/', $lastUpdateDate)) { // 'Y-m-d-H:i'
- $xsdLastUpdate = substr($lastUpdateDate, 0, 10) . "T" . substr($lastUpdateDate, 11) . ":00";
- } 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'
- $xsdLastUpdate = substr($lastUpdateDate, 0, 10) . "T" . substr($lastUpdateDate, 11);
- } else if (preg_match('/^\d\d\d\d\-\d\d\-\d\d\ \d\d:\d\d:\d\d$/', $lastUpdateDate)) {
- $xsdLastUpdate = substr($lastUpdateDate, 0, 10) . "T" . substr($lastUpdateDate, 11);
- }
- return $xsdLastUpdate;
- }
- } catch (Exception $e) {
- DBG::log($e);
- }
- return '';
- }
- public function getOpis() { return ''; } // $this->_opis; } // TODO: legacy
- public function getRawOpis() { return ''; // TODO: legacy
- // $opis = $this->_opis;
- // if (!$opis) return $this->getRawLabel(100);
- // $opis = strip_tags($opis);
- // return $opis;
- }
- public function getLongRawLabel($posLimit = 30) { // TODO: legacy
- return $this->getNamespace();
- // $longLabel = $this->getRawLabel($posLimit);
- // $opis = $this->_opis;
- // if ($longLabel != $this->_name) {
- // $longLabel .= ' ' . $this->_name;
- // }
- // return $longLabel;
- }
- public function getLongLabel($posLimit = 30) { // TODO: RMME, legacy
- return $this->getNamespace();
- // $longLabel = $this->getRawLabel($posLimit);
- // $opis = $this->_opis;
- // if ($longLabel != $this->_name) {
- // $longLabel .= ' <em>' . $this->_name . '</em>';
- // }
- //
- // $longLabel = '<span title="' . htmlspecialchars($opis) . '">' . $longLabel . '</span>';
- // return $longLabel;
- }
- }
|