WfsServerBase.php 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400
  1. <?php
  2. Lib::loadClass('Api_WfsException');
  3. Lib::loadClass('Api_WfsGeomTypeConverter');
  4. Lib::loadClass('Api_WfsNs');
  5. Lib::loadClass('Request');
  6. Lib::loadClass('Core_AclHelper');
  7. Lib::loadClass('Core_XmlWriter');
  8. class Api_WfsServerBase {
  9. public $_usrAcl;
  10. public $_typeConverter;
  11. public $_apiBaseUri;
  12. protected $_logFile;
  13. public function __construct($usrAcl) {
  14. $this->_usrAcl = $usrAcl;
  15. $this->_typeConverter = new Api_WfsGeomTypeConverter();
  16. $this->_apiBaseUri = '';
  17. }
  18. public function setBaseUri($uri) {
  19. $this->_apiBaseUri = $uri;
  20. }
  21. public function getBaseUri() {// TODO: RMME
  22. return $this->_apiBaseUri;
  23. }
  24. /**
  25. * @param string $typeName - 'p5_default_db:TEST_PERMS'
  26. */
  27. public function getAclFromTypeName($typeName) {
  28. if ('1' == V::get('root', '', $_GET) && User::isAdmin()) {// TODO: check byt CRM_CONFIG where key = 'root_access_acl__{$usrLogin}' and val = '{$namespace}'
  29. $namespace = Api_WfsNs::namespaceFromTypeName($typeName);
  30. DBG::log("getAclFromTypeName({$typeName}): ns='{$namespace}'");
  31. Lib::loadClass('SchemaFactory');
  32. $objectStorage = SchemaFactory::loadDefaultObject('SystemObject');
  33. $item = $objectStorage->getItem($namespace, [
  34. 'propertyName' => '*,field'
  35. ]);
  36. DBG::log($item, 'array', "acl item");
  37. if (!$item['isStructInstalled']) throw new Api_WfsException("WARNING: acl '{$namespace}' has not struct installed - reinstall acl in Storage tool");
  38. if (!$item['idZasob']) throw new Api_WfsException("WARNING: acl '{$namespace}' in not installed in Zasoby - add to Zasoby in Storage tool");
  39. switch ($item['_type']) {
  40. case 'AntAcl': {
  41. Lib::loadClass('AntAclBase');
  42. return AntAclBase::buildInstance($item['idZasob'], $item);
  43. } break;
  44. default: throw new Api_WfsException("WARNING: Not implemented '{$namespace}' type '{$item['_type']}'");
  45. }
  46. }
  47. try { // TODO: use object cache `CRM_#CACHE_ACL_OBJECT`
  48. $namespace = str_replace([':', '__x3A__'], '/', $typeName);
  49. Lib::loadClass('SchemaFactory');
  50. $objItem = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, ['propertyName'=>"*,field"]);
  51. DBG::log($objItem, 'array', "DBG objItem({$namespace})");
  52. if (!$objItem['idZasob']) throw new Exception("Missing idZasob for namespace '{$namespace}'");
  53. if (!in_array($objItem['_type'], [
  54. // 'TableAcl', // TODO: TEST - to replace TableAcl by AntAcl or use object with namespace + '/tableName'?
  55. 'AntAcl',
  56. ])) throw new Exception("Not Implemented acl type '{$objItem['_type']}'");
  57. if (!$objItem['isObjectActive']) {
  58. if (!$objItem['hasStruct']) throw new Exception("namespace has no structure '{$namespace}'");
  59. if (!$objItem['isStructInstalled']) throw new Exception("namespace structure not installed '{$namespace}'");
  60. throw new Exception("namespace is not activated '{$namespace}'");
  61. }
  62. Lib::loadClass('AntAclBase');
  63. $acl = AntAclBase::buildInstance($objItem['idZasob'], $objItem);
  64. return $acl;
  65. } catch (Exception $e) {
  66. DBG::log($e);
  67. }
  68. $typeEx = explode(':', $typeName);
  69. $sourceName = $typeEx[0];
  70. $objName = $typeEx[1];
  71. if (2 != count($typeEx)) throw new Api_WfsException("Could not get acl for '{$typeName}' - syntax error");
  72. if ('p5_' == substr($sourceName, 0, 3)) $sourceName = substr($sourceName, 3);// remove prefix 'p5_'
  73. $acl = $this->_usrAcl->getObjectAcl($sourceName, $objName);
  74. $forceTblAclInit = 0;//('1' == V::get('_force', '', $_GET));
  75. $acl->init($forceTblAclInit);
  76. return $acl;
  77. }
  78. /**
  79. * @param $_GET [ , POST Body - XML file ]
  80. * @return array $args
  81. * TODO: get $acl and check more restrictions
  82. */
  83. public function parseGetFeatureArgsFromRequest() {
  84. $rawArgs = $_GET;// $_REQUEST; ($_POST values not allowed, only xml in post body)
  85. $args = array();
  86. $args['xsd:type'] = null;// @from: TYPENAME, typeName (typename)
  87. $args['typePrefix'] = null;// @from: TYPENAME, typeName (typename)
  88. $args['typeName'] = null;// @from: TYPENAME, typeName (typename)
  89. $args['srsname'] = null;// @from: SRSNAME (srsname)
  90. $args['limit'] = 0;// @from: MAXFEATURES, maxFeatures, COUNT (maxfeatures, count)
  91. $args['offset'] = 0;// @from: startIndex (startindex, count)
  92. $args['ogc:filter'] = null;// @from: FILTER, Filter (filter)
  93. $args['sortBy'] = null;// @from: sortBy (sortby)
  94. $args['wfs:propertyName'] = null;// @from: propertyName (propertyname)
  95. $args['filterFields'] = array();// array of field names to show - @from: propertyName
  96. $args['resultType'] = null;// @from: resultType (resulttype)
  97. $args['bbox'] = null;// @from: BBOX (bbox)
  98. $args['wfs:featureID'] = null;// @from: featureID, featureId (featureid)
  99. $args['primaryKey'] = null;// primaryKey type - @from: featureID or $req[primaryKey]
  100. $args['outputBlobFormat'] = V::get('outputBlobFormat', 'base64', $rawArgs); // how to print blob fields ('base64', 'link') - default base64
  101. $lowerArgs = array(); foreach ($rawArgs as $name => $value) $lowerArgs[ strtolower($name) ] = trim($value);
  102. $args['xsd:type'] = V::get('typename', '', $lowerArgs);
  103. $exType = explode(':', $args['xsd:type']);
  104. if (count($exType) != 2) throw new HttpException("Wrong param TYPENAME", 400);
  105. $args['typePrefix'] = $exType[0];
  106. $args['typeName'] = $exType[1];
  107. $args['srsname'] = V::get('SRSNAME', '', $lowerArgs);// eg. EPSG:4326
  108. $args['limit'] = V::get('maxfeatures', $args['limit'], $lowerArgs, 'int');
  109. $args['limit'] = V::get('count', $args['limit'], $lowerArgs, 'int');
  110. $defaultFeaturesLimit = ('biuro.biall-net.pl' == V::get('SERVER_NAME', '', $_SERVER)) ? 50000 : 10000;
  111. if ($args['limit'] <= 0) $args['limit'] = $defaultFeaturesLimit;// default limit
  112. $args['offset'] = V::get('startindex', 0, $lowerArgs, 'int');
  113. $args['ogc:filter'] = urldecode(V::get('filter', '', $lowerArgs));
  114. if (empty($args['ogc:filter'])) {// read ogc:Filter from POST body if not defined in GET
  115. $reqBody = Request::getRequestBody();
  116. if (!empty($reqBody)) {
  117. $parsedRequest = $this->parseOgcFilterRequest($reqBody);
  118. DBG::log($parsedRequest, 'array', 'parsed ogc query request');
  119. if (!empty($parsedRequest['ogc:Filter'])) $args['ogc:filter'] = $parsedRequest['ogc:Filter'];
  120. if (!empty($parsedRequest['wfs:PropertyName'])) {
  121. foreach ($parsedRequest['wfs:PropertyName'] as $fieldXpath) {
  122. $args['filterFields'][] = $fieldXpath;
  123. }
  124. }
  125. }
  126. }
  127. $args['sortBy'] = V::get('sortby', '', $lowerArgs);// TODO: split to array of array(fieldName, (asc | desc))
  128. $args['wfs:propertyName'] = trim(V::get('propertyname', '', $lowerArgs));// TODO: fields to show - split by ','
  129. if (strlen($args['wfs:propertyName']) > 0) {
  130. $exFields = explode(',', $args['wfs:propertyName']);
  131. foreach ($exFields as $fieldName) {
  132. $fieldName = trim($fieldName);
  133. if (!empty($fieldName)) $args['filterFields'][] = $fieldName;
  134. }
  135. }
  136. $args['resultType'] = V::get('resulttype', '', $lowerArgs);
  137. $args['bbox'] = V::get('bbox', '', $lowerArgs);
  138. if (!empty($args['bbox'])) {
  139. // BBOX may have EPSG at then end - example: ",EPSG:4326"
  140. $num = "\d+.?\d*?";// "\d+(.\d+)?"
  141. if (!preg_match("/^({$num}),({$num}),({$num}),({$num})(\,EPSG:\d+)?$/", $args['bbox'], $matches)) throw new Exception("Illegal BBOX format");
  142. // QGIS send BBOX in correct order: 54.23580872176457,18.46844302390853,54.25220902538883,18.492990600812696
  143. // first number should not be smaller then second
  144. // example $matches:
  145. // [0] => 18.492990600812696,54.23580872176457,18.46844302390853,54.25220902538883
  146. // [1] => 18.492990600812696
  147. // [2] => 54.23580872176457
  148. // [3] => 18.46844302390853
  149. // [4] => 54.25220902538883
  150. // (optional) EPGS
  151. $bboxPoints = ($matches[1] > $matches[2])
  152. ? [ $matches[1], $matches[2], $matches[3], $matches[4] ]
  153. : [ $matches[2], $matches[3], $matches[4], $matches[1] ];
  154. $args['bbox'] = implode(",", $bboxPoints);
  155. }
  156. $args['wfs:featureID'] = V::get('featureid', null, $lowerArgs);// TODO: allow multiply feature id (csv)
  157. if ($args['wfs:featureID']) {
  158. $dotPos = strpos($args['wfs:featureID'], '.');
  159. if (!$dotPos) throw new Exception("Wrong param featureID");
  160. if ($args['typeName'] != substr($args['wfs:featureID'], 0, $dotPos)) throw new Exception("Wrong typeName in param featureID");
  161. $args['primaryKey'] = substr($args['wfs:featureID'], $dotPos + 1);
  162. }
  163. $pk = V::get('primarykey', '', $lowerArgs);
  164. if ($pk) {
  165. $args['primaryKey'] = $pk;
  166. }
  167. if(DBG::isActive() && V::get('DBG', 0, $_GET)){ echo "\$lowerArgs:";print_r($lowerArgs); }
  168. if(DBG::isActive() && V::get('DBG', 0, $_GET)){ echo "\$args:";print_r($args); }
  169. return $args;
  170. }
  171. public function _getXmlSchemaLocation() {
  172. $schemaLocations = array();
  173. //$schemaLocations[] = 'http://www.opengis.net/wfs http://webgis.regione.sardegna.it:80/geoserver/schemas/wfs/1.0.0/WFS-capabilities.xsd';// @from http://webgis.regione.sardegna.it/geoserver/ows?service=WFS&request=GetCapabilities
  174. return (!empty($schemaLocations))? 'xsi:schemaLocation="' . implode(' ', $schemaLocations) . '"' : '';
  175. }
  176. public function _printXmlNamespaceList() {
  177. $listNs = array();
  178. foreach (Api_WfsNs::getNsList() as $uri => $prefix) {
  179. $listNs[] = 'xmlns:' . $prefix . '="' . $uri . '"';
  180. }
  181. return implode("\n", $listNs);
  182. }
  183. public function _getSourceNsList() {
  184. $usrObjList = array();
  185. $tblsAcl = $this->_usrAcl->getTablesAcl();
  186. foreach ($tblsAcl as $tblAcl) {
  187. $dataSourceName = 'default_db';// TODO: getSourceName
  188. $tblName = $tblAcl->getName();
  189. $usrObjList[] = array($dataSourceName, $tblName);
  190. }
  191. $usrObjList[] = array('objects', 'File');
  192. $usrObjList[] = array('objects', 'TestPerms');
  193. $usrObjList[] = array('objects', 'Korespondencja');
  194. return $usrObjList;
  195. }
  196. public function _parseTransactionXmlStruct($requestXml, $requestXmlTags) {
  197. $DBG = V::get('DBG_XML', 0, $_GET, 'int');// TODO: Profiler
  198. $rootTagName = V::get('tag', '', $requestXmlTags[0]);
  199. if ('Transaction' != $rootTagName) throw new Api_WfsException("Parse Request XML Error - Missing Transaction as root xml tag", __LINE__, null, 'TransactionParseError', 'request');
  200. // TODO: special actions if action on nested objects
  201. // 1. convert request: wfs.transaction.convert-wfs-request.xsl
  202. // 2. validate converted request: wfs.transaction-converted-request.xsd
  203. // 3. execute request in data source
  204. // if($DBG){echo 'L.' . __LINE__ . ' $requestXmlTags:';print_r($requestXmlTags);echo "\n";}
  205. /*
  206. <Transaction
  207. xmlns="http://www.opengis.net/wfs"
  208. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  209. version="1.0.0"
  210. service="WFS"
  211. xmlns:p5_objects="https://biuro.biall-net.pl/wfs/objects"
  212. xmlns:gml="http://www.opengis.net/gml">
  213. <Insert xmlns="http://www.opengis.net/wfs">
  214. <TestPerms xmlns="https://biuro.biall-net.pl/wfs/objects">
  215. <plik xmlns="https://biuro.biall-net.pl/wfs/objects">
  216. <p5_objects:File>
  217. <p5_objects:name>blank-wfs.gif</p5_objects:name>
  218. <p5_objects:content>R0lGODlhAQABAIAAAP///////yH+EUNyZWF0ZWQgd2l0aCBHSU1QACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==</p5_objects:content>
  219. </p5_objects:File>
  220. </plik>
  221. </TestPerms>
  222. </Insert>
  223. </Transaction>
  224. */
  225. $actionXmlTags = array();// // [ 0 => [ 'action'=>Insert, 'typeName'=>str, 'tags'=>[] ]
  226. {// split xml for action tags (Insert, Update, Delete)
  227. $tagsCount = count($requestXmlTags);
  228. for ($i = 1, $actionTagName = null, $actionIdx = -1, $tagLvl = 0; $i < $tagsCount - 1; $i++) {// skip Transaction open/close tag
  229. $tag = $requestXmlTags[$i];
  230. if (null == $actionTagName) {
  231. $actionTagName = $tag['tag'];
  232. $tagLvl = $tag['level'];
  233. $actionIdx += 1;
  234. $actionXmlTags[$actionIdx] = array();
  235. $actionXmlTags[$actionIdx]['action'] = $actionTagName;
  236. $actionXmlTags[$actionIdx]['typeName'] = V::get('typeName', '', $tag['attributes']);
  237. $actionXmlTags[$actionIdx]['isDeepObject'] = null;// null - unknown, false - not seed, true - deep
  238. $actionXmlTags[$actionIdx]['tags'] = array();
  239. } else if ($tag['tag'] == $actionTagName && 'close' == $tag['type'] && $tagLvl == $tag['level']) {
  240. $actionTagName = null;
  241. } else {
  242. $actionXmlTags[$actionIdx]['tags'][] = $tag;
  243. }
  244. }
  245. }
  246. {// Validate Request: WFS allow multiple tags inside Insert tag
  247. // TODO: implement multiple tags in Insert tag if reauired. Use array_splice($actionXmlTags, $actionIdx, 0, $insertTags);
  248. {// throw (Not Implemented, 501) if found multiple tags in Insert tag
  249. foreach ($actionXmlTags as $actionIdx => $action) {
  250. if ('Insert' !== $action['action']) continue;
  251. $lvl = $action['tags'][0]['level'];
  252. for ($i = 1, $cnt = count($action['tags']); $i < $cnt - 1; $i++) {
  253. $tag = $action['tags'][$i];
  254. // if($DBG){echo 'L.' . __LINE__ . " actionXmlTags loop({$i}) \$tag:";print_r($tag);echo "\n";}
  255. if ($tag['level'] == $lvl) throw new Exception("Error Processing Request - multiple tags inside Insert tag is not implemented", 501);
  256. }
  257. }
  258. }
  259. }
  260. {// Insert tag - fix typeName from first tag, remove first and last tag - leave only fields
  261. foreach ($actionXmlTags as $actionIdx => $action) {
  262. if ('Insert' !== $action['action']) continue;
  263. array_pop($action['tags']);// remove last tag (close tag)
  264. $tag = array_shift($action['tags']);// remove last tag (close tag)
  265. $typeName = $tag['tag'];// eg. with prefix 'p5_objects:File' or without prefix but with @xmlns
  266. if (false === strpos($typeName, ':')) {
  267. $nsType = V::get('xmlns', '', $tag['attributes']);
  268. if (!$nsType) throw new Exception("Error Processing Request - Missing object namespace '{$tag['tag']}'");
  269. $prefix = Api_WfsNs::getNsPrefix($nsType);
  270. if (!$prefix) {
  271. if ($typeName == substr(rtrim($nsType, '/'), -1 * strlen($typeName))) {// typeName may be added to ns uri
  272. $nsBaseForType = substr(rtrim($nsType, '/'), 0, -1 * strlen($typeName) - 1);
  273. $prefix = Api_WfsNs::getNsPrefix($nsBaseForType);
  274. }
  275. }
  276. if (!$prefix) throw new Exception("Error Processing Request - Unrecognized namespace uri '{$nsType}' for object '{$tag['tag']}'");
  277. $typeName = "{$prefix}:{$typeName}";
  278. }
  279. $action['typeName'] = $typeName;
  280. $actionXmlTags[$actionIdx] = $action;
  281. }
  282. }
  283. {// validate
  284. // if($DBG){echo 'L.' . __LINE__ . ' before validate $actionXmlTags:';print_r($actionXmlTags);echo "\n";}
  285. foreach ($actionXmlTags as $actionIdx => $action) {
  286. if ('Insert' == $action['action']) {
  287. if (empty($action['typeName'])) throw new Exception("Error Processing Request - unknown object typeName to Insert");
  288. $acl = $this->getAclFromTypeName($action['typeName']);
  289. $actionXmlTags[$actionIdx] = $acl->validateInsertXml($action);
  290. } else if ('Update' == $action['action']) {
  291. $acl = $this->getAclFromTypeName($action['typeName']);
  292. $actionXmlTags[$actionIdx] = $acl->validateUpdateXml($action);
  293. } else if ('Delete' == $action['action']) {
  294. if($DBG>1){echo'<pre>$action: ';print_r($action);echo'</pre>';}
  295. $acl = $this->getAclFromTypeName($action['typeName']);
  296. $actionXmlTags[$actionIdx] = $acl->validateDeleteXml($action);
  297. } else {
  298. if($DBG>1){echo'<pre>$action: ';print_r($action);echo'</pre>';}
  299. throw new Exception("{$action['action']} action not implemented", 501);
  300. }
  301. // continue;// TODO: validate all by type
  302. }
  303. }
  304. if ('1' == V::get('DBG_DONT_CHANGE_DB', '', $_REQUEST)) {
  305. echo "----------------- action xml tags: ---------------" . "\n";
  306. print_r($actionXmlTags);
  307. die(".EOF\n");
  308. }
  309. {// execute
  310. $returnIds = array();
  311. $changesList = array();
  312. foreach ($actionXmlTags as $actionIdx => $action) {
  313. if ('Insert' == $action['action']) {
  314. if (empty($action['typeName'])) throw new Exception("Error Processing Request - unknown object typeName to Insert");
  315. $acl = $this->getAclFromTypeName($action['typeName']);
  316. $newId = $acl->insertXml($action);
  317. $returnIds[$actionIdx] = $newId;
  318. $changesList[$actionIdx] = array('Status'=>(($newId > 0)? 'SUCCESS' : 'FAILED'), 'Message'=>"created {$newId}.", 'Action' => $action['action']);
  319. if ($newId > 0) $changesList[$actionIdx]['fid'] = $acl->getName() . '.' . $newId;
  320. } else if ('Update' == $action['action']) {
  321. if($DBG>1){echo'<pre>$action: ';print_r($action);echo'</pre>';}
  322. $acl = $this->getAclFromTypeName($action['typeName']);
  323. $affected = $acl->updateXml($action);
  324. $changesList[$actionIdx] = array('Status'=>(($affected >= 0)? 'SUCCESS' : 'FAILED'), 'Message'=>"affected {$affected}.", 'Action' => $action['action']);
  325. } else if ('Delete' == $action['action']) {
  326. $acl = $this->getAclFromTypeName($action['typeName']);
  327. $affected = $acl->deleteXml($action);
  328. $changesList[$actionIdx] = array('Status'=>(($affected >= 0)? 'SUCCESS' : 'FAILED'), 'Message'=>"deleted {$affected}.", 'Action' => $action['action']);
  329. } else throw new Exception("TODO: {$action['action']} action not implemented", 501);
  330. }
  331. if($DBG){echo 'L.' . __LINE__ . ' $changesList:';print_r($changesList);echo "\n";}
  332. }
  333. return $this->_transactionResponse($changesList);
  334. }
  335. public function _transactionResponse($changesList) {
  336. // <WFS_TransactionResponse>
  337. // <TransactionResult>
  338. // <Status> : SUCCESS / FAILED / PARTIAL
  339. // [<Locator]
  340. // [<Message]
  341. $messageTag = '';
  342. $statusTag = '';
  343. $statusIsFailed = false;
  344. $statusAll = null;
  345. $createdFeatureId = array();
  346. foreach ($changesList as $featureId => $change) {
  347. if ('FAILED' == $change['Status']) {
  348. $statusIsFailed = true;
  349. }
  350. if ('SUCCESS' == $change['Status'] && !empty($change['fid'])) {
  351. $createdFeatureId[] = $change['fid'];
  352. }
  353. // if (!empty($change['Message'])) $messageTag .= "Feature '{$featureId}' {$change['Status']}: {$change['Message']}\n";
  354. }
  355. $statusTag = ($statusIsFailed)? 'FAILED' : 'SUCCESS';
  356. $statusTag = "<wfs:{$statusTag}/>";
  357. $messageTag = '';//"<wfs:Message>{$messageTag}</wfs:Message>";
  358. /* Example:
  359. <?xml version="1.0" encoding="UTF-8"?>
  360. <wfs:WFS_TransactionResponse version="1.0.0" xmlns:wfs="http://www.opengis.net/wfs"
  361. xmlns:ogc="http://www.opengis.net/ogc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  362. xsi:schemaLocation="http://www.opengis.net/wfs http://localhost:8080/geoserver/schemas/wfs/1.0.0/WFS-transaction.xsd">
  363. <wfs:InsertResult>
  364. <ogc:FeatureId fid="archsites.26" />
  365. </wfs:InsertResult>
  366. <wfs:TransactionResult handle="Updating Signature rock label">
  367. <wfs:Status>
  368. <wfs:SUCCESS />
  369. </wfs:Status>
  370. </wfs:TransactionResult>
  371. </wfs:WFS_TransactionResponse>*/
  372. // TODO: build xml by DOMDocument
  373. // TODO: xsi:schemaLocation="http://www.opengis.net/wfs http://localhost:8080/geoserver/schemas/wfs/1.0.0/WFS-transaction.xsd"
  374. $wfsInsertResult = '';
  375. if (!empty($createdFeatureId)) {
  376. $wfsInsertResult = "\n<wfs:InsertResult>\n";
  377. foreach ($createdFeatureId as $fid) {
  378. $wfsInsertResult .= '<ogc:FeatureId fid="' . $fid . '" xmlns:ogc="http://www.opengis.net/ogc"/>' . "\n";
  379. }
  380. $wfsInsertResult .= "\n</wfs:InsertResult>\n";
  381. EOF;
  382. }
  383. $tranRes = <<<EOF
  384. <wfs:WFS_TransactionResponse version="1.0.0"
  385. xmlns:wfs="http://www.opengis.net/wfs"
  386. xmlns:ogc="http://www.opengis.net/ogc"
  387. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  388. {$wfsInsertResult}
  389. <wfs:TransactionResult>
  390. <wfs:Status>{$statusTag}</wfs:Status>
  391. {$messageTag}
  392. </wfs:TransactionResult>
  393. </wfs:WFS_TransactionResponse>
  394. EOF;
  395. return $tranRes;
  396. }
  397. public function _convertTransactionXml($requestXmlString, $sourceNsList) {
  398. $DBG = (V::get('DBG_XSL', '', $_GET) > 0);// TODO: Profiler
  399. if($DBG){echo 'L.' . __LINE__ . ' sourceNsList:';print_r($sourceNsList);echo "\n";}
  400. $updateActionsXsd = array();
  401. $insertActionsXsd = array();
  402. $deleteActionsXsd = array();
  403. //<!-- TODO: create tag Update{X} where X is namespace index -->
  404. foreach ($sourceNsList as $nsInd => $sourceNs) {
  405. // <Update>
  406. $theGeomField = 'the_geom';// TODO: get from fields list
  407. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  408. if($DBG){echo 'L.' . __LINE__ . ' typeName:';print_r($typeName);echo "\n";}
  409. $updateElementName = "UpdateNs{$nsInd}";
  410. $geomCoordsUpdateXpath = "//wfs:Value/*/gml:outerBoundaryIs/gml:LinearRing/gml:coordinates";
  411. $geomCoordsInsertXpath = "//*/gml:outerBoundaryIs/gml:LinearRing/gml:coordinates";
  412. $acl = $this->getAclFromTypeName($typeName);
  413. $geomType = $acl->getGeomFieldType($theGeomField);
  414. if ('polygon' == $geomType) {
  415. $geomCoordsUpdateXpath = ".//wfs:Value/*/gml:outerBoundaryIs/gml:LinearRing/gml:coordinates";
  416. $geomCoordsUpdateXpath = "((<xsl:value-of select=\"{$geomCoordsUpdateXpath}\"/>))";
  417. $geomCoordsInsertXpath = ".//*/gml:outerBoundaryIs/gml:LinearRing/gml:coordinates";
  418. $geomCoordsInsertXpath = "((<xsl:value-of select=\"{$geomCoordsInsertXpath}\"/>))";
  419. } else if ('linestring' == $geomType) {
  420. $geomCoordsUpdateXpath = ".//wfs:Value/*/gml:coordinates";
  421. $geomCoordsUpdateXpath = "(<xsl:value-of select=\"{$geomCoordsUpdateXpath}\"/>)";
  422. $geomCoordsInsertXpath = ".//*/gml:coordinates";
  423. $geomCoordsInsertXpath = "(<xsl:value-of select=\"{$geomCoordsInsertXpath}\"/>)";
  424. } else if ('point' == $geomType) {
  425. $geomCoordsUpdateXpath = ".//wfs:Value/*/gml:coordinates";
  426. $geomCoordsUpdateXpath = "(<xsl:value-of select=\"{$geomCoordsUpdateXpath}\"/>)";
  427. $geomCoordsInsertXpath = ".//*/gml:coordinates";
  428. $geomCoordsInsertXpath = "(<xsl:value-of select=\"{$geomCoordsInsertXpath}\"/>)";
  429. }
  430. $actionXsd = <<<EOF
  431. <xsl:when test="@typeName = '{$typeName}'">
  432. <xsl:element name="{$updateElementName}">
  433. <xsl:attribute name="typeName"><xsl:value-of select="@typeName" /></xsl:attribute>
  434. <xsl:attribute name="featureId"><xsl:value-of select="ogc:Filter/ogc:FeatureId/@fid" /></xsl:attribute>
  435. <xsl:for-each select="wfs:Property">
  436. <xsl:element name="{wfs:Name}">
  437. <xsl:choose>
  438. <xsl:when test="wfs:Name = '{$theGeomField}'"><xsl:value-of select="local-name(//wfs:Value/*[1])"/>{$geomCoordsUpdateXpath}</xsl:when>
  439. <xsl:otherwise><xsl:value-of select="wfs:Value"/></xsl:otherwise>
  440. </xsl:choose>
  441. </xsl:element>
  442. </xsl:for-each>
  443. </xsl:element>
  444. </xsl:when>
  445. EOF;
  446. $updateActionsXsd[] = $actionXsd;
  447. $typeName = "{$sourceNs[1]}";//"p5_{$sourceNs[0]}:{$sourceNs[1]}";
  448. $insertElementName = "InsertNs{$nsInd}";
  449. $actionXsd = <<<EOF
  450. <xsl:when test="local-name() = '{$typeName}'">
  451. <xsl:element name="{$insertElementName}">
  452. <xsl:attribute name="typeName"><xsl:value-of select="local-name()" /></xsl:attribute>
  453. <xsl:attribute name="typeNsUri"><xsl:value-of select="namespace-uri()" /></xsl:attribute>
  454. <xsl:for-each select="*">
  455. <xsl:element name="{local-name()}">
  456. <xsl:choose>
  457. <xsl:when test="local-name() = '{$theGeomField}'"><xsl:value-of select="local-name(*[1])"/>{$geomCoordsInsertXpath}</xsl:when>
  458. <xsl:otherwise><xsl:value-of select="."/></xsl:otherwise>
  459. </xsl:choose>
  460. </xsl:element>
  461. </xsl:for-each>
  462. </xsl:element>
  463. </xsl:when>
  464. EOF;
  465. $insertActionsXsd[] = $actionXsd;
  466. $deleteElementName = "DeleteNs{$nsInd}";
  467. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  468. $actionXsd = <<<EOF
  469. <xsl:when test="@typeName = '{$typeName}'">
  470. <xsl:variable name="typeName" select="@typeName" />
  471. <xsl:for-each select="ogc:Filter/ogc:FeatureId">
  472. <xsl:element name="{$deleteElementName}">
  473. <xsl:attribute name="typeName"><xsl:value-of select="\$typeName" /></xsl:attribute>
  474. <xsl:attribute name="featureId"><xsl:value-of select="@fid" /></xsl:attribute>
  475. </xsl:element>
  476. </xsl:for-each>
  477. </xsl:when>
  478. EOF;
  479. $deleteActionsXsd[] = $actionXsd;
  480. }
  481. if (!empty($updateActionsXsd)) {
  482. $updateActionsXsd = implode("\n", $updateActionsXsd);
  483. $updateActionsXsd = <<<EOF
  484. <xsl:choose>
  485. {$updateActionsXsd}
  486. </xsl:choose>
  487. EOF;
  488. } else {
  489. $updateActionsXsd = '';
  490. }
  491. if (!empty($insertActionsXsd)) {
  492. $insertActionsXsd = implode("\n", $insertActionsXsd);
  493. $insertActionsXsd = <<<EOF
  494. <xsl:choose>
  495. {$insertActionsXsd}
  496. </xsl:choose>
  497. EOF;
  498. } else {
  499. $insertActionsXsd = '';
  500. }
  501. if (!empty($deleteActionsXsd)) {
  502. $deleteActionsXsd = implode("\n", $deleteActionsXsd);
  503. $deleteActionsXsd = <<<EOF
  504. <xsl:choose>
  505. {$deleteActionsXsd}
  506. </xsl:choose>
  507. EOF;
  508. } else {
  509. $deleteActionsXsd = '';
  510. }
  511. $convertTransactionXslString = '<?xml version="1.0"?>';
  512. $convertTransactionXslString .= <<<EOF
  513. <xsl:transform version="1.0"
  514. xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  515. xmlns:wfs="http://www.opengis.net/wfs"
  516. xmlns:ogc="http://www.opengis.net/ogc"
  517. xmlns:gml="http://www.opengis.net/gml">
  518. <xsl:template match="/">
  519. <xsl:for-each select="wfs:Transaction">
  520. <Transaction>
  521. <xsl:attribute name="version"><xsl:value-of select="@version" /></xsl:attribute>
  522. <xsl:attribute name="service"><xsl:value-of select="@service" /></xsl:attribute>
  523. <xsl:for-each select="wfs:Update">
  524. {$updateActionsXsd}
  525. </xsl:for-each>
  526. <xsl:for-each select="wfs:Insert/*">
  527. {$insertActionsXsd}
  528. </xsl:for-each>
  529. <xsl:for-each select="wfs:Delete">
  530. {$deleteActionsXsd}
  531. </xsl:for-each>
  532. <!-- TODO: Native -->
  533. </Transaction>
  534. </xsl:for-each>
  535. </xsl:template>
  536. </xsl:transform>
  537. EOF;
  538. if($DBG){echo 'L.' . __LINE__ . ' $convertTransactionXslString:' . $convertTransactionXslString . "\n";}
  539. $requestXml = new DOMDocument();
  540. $requestXml->loadXml($requestXmlString);
  541. $convertTransactionXsl = new DOMDocument();
  542. $convertTransactionXsl->loadXml($convertTransactionXslString);
  543. $proc = new XSLTProcessor();
  544. $proc->importStylesheet($convertTransactionXsl);
  545. return $proc->transformToXML($requestXml);
  546. }
  547. public function _validateConvertedTransactionXml($convertedTransaction, $sourceNsList) {
  548. $DBG = (V::get('DBG_XSD', '', $_GET) > 0);// TODO: Profiler
  549. if($DBG){echo 'L.' . __LINE__ . ' sourceNsList:';print_r($sourceNsList);echo "\n";}
  550. $dom = new DOMDocument('1.0', 'utf-8');
  551. $dom->formatOutput = true;
  552. $dom->preserveWhiteSpace = false;
  553. $rootNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:schema');
  554. $dom->appendChild($rootNode);
  555. $rootNode->setAttribute('elementFormDefault', 'qualified');
  556. $rootNode->setAttribute('version', '1.0');
  557. {// <xsd:element name="Transaction" type="TransactionType">
  558. $elNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  559. $rootNode->appendChild($elNode);
  560. $elNode->setAttribute('name', 'Transaction');
  561. $elNode->setAttribute('type', 'TransactionType');
  562. $cTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:complexType');
  563. $rootNode->appendChild($cTypeNode);
  564. $cTypeNode->setAttribute('name', 'TransactionType');
  565. $seqNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:sequence');
  566. $cTypeNode->appendChild($seqNode);
  567. $choiceNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:choice');
  568. $seqNode->appendChild($choiceNode);
  569. $choiceNode->setAttribute('minOccurs', '0');
  570. $choiceNode->setAttribute('maxOccurs', 'unbounded');
  571. // <!-- <xsd:element ref="Update"/> -->
  572. foreach ($sourceNsList as $nsInd => $sourceNs) {
  573. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  574. $updateElementName = "UpdateNs{$nsInd}";
  575. $updateElementType = "UpdateNs{$nsInd}ElementType";
  576. $updateElemNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  577. $choiceNode->appendChild($updateElemNode);
  578. $updateElemNode->setAttribute('name', $updateElementName);
  579. $updateElemNode->setAttribute('type', $updateElementType);
  580. }
  581. // <!-- <xsd:element ref="Insert"/> -->
  582. foreach ($sourceNsList as $nsInd => $sourceNs) {
  583. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  584. $insertElementName = "InsertNs{$nsInd}";
  585. $insertElementType = "InsertNs{$nsInd}ElementType";
  586. $insertElemNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  587. $choiceNode->appendChild($insertElemNode);
  588. $insertElemNode->setAttribute('name', $insertElementName);
  589. $insertElemNode->setAttribute('type', $insertElementType);
  590. }
  591. // <!-- <xsd:element ref="Delete"/> -->
  592. foreach ($sourceNsList as $nsInd => $sourceNs) {
  593. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  594. $deleteElementName = "DeleteNs{$nsInd}";
  595. $deleteElementType = "DeleteNs{$nsInd}ElementType";
  596. $deleteElemNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  597. $choiceNode->appendChild($deleteElemNode);
  598. $deleteElemNode->setAttribute('name', $deleteElementName);
  599. $deleteElemNode->setAttribute('type', $deleteElementType);
  600. }
  601. // <!-- <xsd:element ref="Native"/> -->
  602. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  603. $cTypeNode->appendChild($attrNode);
  604. $attrNode->setAttribute('name', 'version');
  605. $attrNode->setAttribute('type', 'xsd:string');
  606. $attrNode->setAttribute('use', 'required');
  607. $attrNode->setAttribute('fixed', '1.0.0');
  608. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  609. $cTypeNode->appendChild($attrNode);
  610. $attrNode->setAttribute('name', 'service');
  611. $attrNode->setAttribute('type', 'xsd:string');
  612. $attrNode->setAttribute('use', 'required');
  613. $attrNode->setAttribute('fixed', 'WFS');
  614. }
  615. foreach ($sourceNsList as $nsInd => $sourceNs) {
  616. $transactionTypesList = array();
  617. $transactionTypesList[] = 'Update';
  618. $transactionTypesList[] = 'Insert';
  619. foreach ($transactionTypesList as $transactionType) {
  620. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  621. if($DBG){echo 'L.' . __LINE__ . ' TODO: get acl typeName:';print_r($typeName);echo "\n";}
  622. $acl = $this->getAclFromTypeName($typeName);
  623. $updateElementName = "{$transactionType}Ns{$nsInd}";
  624. $updateElementType = "{$transactionType}Ns{$nsInd}ElementType";
  625. /*
  626. <xsd:complexType name="{$updateElementType}">
  627. <xsd:sequence>
  628. <xsd:element name="PARENT_ID" minOccurs="0" maxOccurs="1" type="xsd:integer" />
  629. </xsd:sequence>
  630. */
  631. $updateTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:complexType');
  632. $rootNode->appendChild($updateTypeNode);
  633. $updateTypeNode->setAttribute('name', $updateElementType);
  634. {
  635. $seqNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:all');
  636. $updateTypeNode->appendChild($seqNode);
  637. {
  638. $pKeyField = $acl->getPrimaryKeyField();
  639. $fldList = $this->_getFieldListFromAcl($acl);
  640. // fields without geometry fields
  641. foreach ($fldList as $fldName) {
  642. if ($acl->isGeomField($fldName)) continue;
  643. $elNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  644. $seqNode->appendChild($elNode);
  645. $elNode->setAttribute('name', $fldName);
  646. $minOccurs = 0;
  647. if ($pKeyField == $fldName) {
  648. $minOccurs = '1';
  649. } else {
  650. $minOccurs = '0';
  651. }
  652. $elNode->setAttribute('minOccurs', $minOccurs);
  653. $fldType = null;
  654. if ($acl->isIntegerField($fldName)) {
  655. $fldType = 'xsd:integer';
  656. }
  657. else if ($acl->isDecimalField($fldName)) {
  658. $fldType = 'xsd:decimal';
  659. }
  660. else if ($acl->isDateField($fldName)) {
  661. $fldType = 'xsd:date';
  662. }
  663. else if ($acl->isDateTimeField($fldName)) {
  664. // $fldType = 'xsd:dateTime';
  665. $fldType = null;// 'xsd:string';
  666. $patternDataTime = "(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})(:(\d{2}))?";
  667. // <xsd:element name="..." minOccurs="0" nillable="true">
  668. // <xsd:simpleType>
  669. // <xsd:restriction base="xsd:string">
  670. // <xsd:pattern value="[a-zA-Z]+\(\((\-?\d+\.?\d*,\-?\d+\.?\d*)( \-?\d+\.?\d*,\-?\d+\.?\d*)+\)\)"/>
  671. // </xsd:restriction>
  672. // </xsd:simpleType>
  673. // </xsd:element>
  674. $simpleTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:simpleType');
  675. $restrictionNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:restriction');
  676. $patternNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:pattern');
  677. $restrictionNode->setAttribute('base', 'xsd:string');
  678. $patternNode->setAttribute('value', $patternDataTime);
  679. $restrictionNode->appendChild($patternNode);
  680. $simpleTypeNode->appendChild($restrictionNode);
  681. $elNode->appendChild($simpleTypeNode);
  682. // continue;// TODO: ? below added nillable = true, minOccurs = 0, type = $fldType
  683. }
  684. else if ($acl->isBinaryField($fldName)) {
  685. $fldType = 'xsd:base64Binary';
  686. }
  687. else {
  688. $fldType = 'xsd:string';
  689. }
  690. if ($fldType) $elNode->setAttribute('type', $fldType);
  691. $elNode->setAttribute('nillable', 'true');
  692. $elNode->setAttribute('minOccurs', '0');
  693. }
  694. // only geometry fields
  695. foreach ($fldList as $fldName) {
  696. if (!$acl->isGeomField($fldName)) continue;
  697. $elNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  698. $seqNode->appendChild($elNode);
  699. $elNode->setAttribute('name', $fldName);
  700. $minOccurs = 0;
  701. if ($pKeyField == $fldName) {
  702. $minOccurs = '1';
  703. } else {
  704. $minOccurs = '0';
  705. }
  706. $elNode->setAttribute('minOccurs', $minOccurs);
  707. if ($acl->isGeomField($fldName)) {
  708. //$fldType = 'gml:GeometryPropertyType';
  709. // TODO: use geom types from gml to wkt
  710. // TODO: pattern wg atrybutów gml:coordinates decimal="." cs="," ts=" "
  711. $patternWkt = '';// TODO: error if empty - unsupported geom type
  712. $patternNum = '\-?\d+\.?\d*';
  713. $patternPoint = $patternNum . ',' . $patternNum;
  714. $patternPoints = '(' . $patternPoint . ')( ' . $patternPoint . ')+';
  715. $geomType = $acl->getGeomFieldType($fldName);
  716. if ('polygon' == $geomType) {
  717. // [a-zA-Z]+\(\((\-?\d+\.?\d*,\-?\d+\.?\d*)( (\-?\d+\.?\d*,\-?\d+\.?\d*))+\)\)
  718. $patternWkt = '[a-zA-Z]+\(\(' . $patternPoints . '\)\)';
  719. } else if ('linestring' == $geomType) {
  720. // [a-zA-Z]+\((\-?\d+\.?\d*,\-?\d+\.?\d*)( (\-?\d+\.?\d*,\-?\d+\.?\d*))+\)
  721. $patternWkt = '[a-zA-Z]+\(' . $patternPoints . '\)';
  722. } else if ('point' == $geomType) {
  723. // [a-zA-Z]+\(\-?\d\.?\d*,\-?\d\.?\d*\)
  724. $patternWkt = '[a-zA-Z]+\(' . $patternPoint . '\)';
  725. }
  726. $simpleTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:simpleType');
  727. $restrictionNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:restriction');
  728. $patternNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:pattern');
  729. $restrictionNode->setAttribute('base', 'xsd:string');
  730. $patternNode->setAttribute('value', $patternWkt);
  731. $restrictionNode->appendChild($patternNode);
  732. $simpleTypeNode->appendChild($restrictionNode);
  733. $elNode->appendChild($simpleTypeNode);
  734. }
  735. $elNode->setAttribute('nillable', 'true');
  736. $elNode->setAttribute('minOccurs', '0');
  737. }
  738. }
  739. }
  740. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  741. $updateTypeNode->appendChild($attrNode);
  742. $attrNode->setAttribute('name', 'typeName');
  743. $attrNode->setAttribute('type', 'xsd:token');
  744. $attrNode->setAttribute('use', 'required');
  745. if ($transactionType == 'Insert') {
  746. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  747. $updateTypeNode->appendChild($attrNode);
  748. $attrNode->setAttribute('name', 'typeNsUri');
  749. $attrNode->setAttribute('type', 'xsd:anyURI');
  750. $attrNode->setAttribute('use', 'required');
  751. }
  752. if ($transactionType == 'Update') {
  753. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  754. $updateTypeNode->appendChild($attrNode);
  755. $attrNode->setAttribute('name', 'featureId');
  756. $attrNode->setAttribute('use', 'required');
  757. $sTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:simpleType');
  758. $attrNode->appendChild($sTypeNode);
  759. $resNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:restriction');
  760. $sTypeNode->appendChild($resNode);
  761. $resNode->setAttribute('base', 'xsd:string');
  762. $patternNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:pattern');
  763. $resNode->appendChild($patternNode);
  764. $patternNode->setAttribute('value', '[a-zA-Z_][a-zA-Z0-9_]*\.[0-9]*');
  765. }
  766. }
  767. {// 'Delete'
  768. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  769. $acl = $this->getAclFromTypeName($typeName);
  770. $deleteElementType = "DeleteNs{$nsInd}ElementType";
  771. $deleteTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:complexType');
  772. $rootNode->appendChild($deleteTypeNode);
  773. $deleteTypeNode->setAttribute('name', $deleteElementType);
  774. /* <xsd:attribute name="typeName" type="xsd:token" use="required"/> */
  775. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  776. $deleteTypeNode->appendChild($attrNode);
  777. $attrNode->setAttribute('name', 'typeName');
  778. $attrNode->setAttribute('type', 'xsd:token');
  779. $attrNode->setAttribute('use', 'required');
  780. /* <xsd:attribute name="featureId" use="required"> */
  781. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  782. $deleteTypeNode->appendChild($attrNode);
  783. $attrNode->setAttribute('name', 'featureId');
  784. $attrNode->setAttribute('use', 'required');
  785. $sTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:simpleType');
  786. $attrNode->appendChild($sTypeNode);
  787. $resNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:restriction');
  788. $sTypeNode->appendChild($resNode);
  789. $resNode->setAttribute('base', 'xsd:string');
  790. $patternNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:pattern');
  791. $resNode->appendChild($patternNode);
  792. $patternNode->setAttribute('value', '[a-zA-Z_][a-zA-Z0-9_]*\.[0-9]*');
  793. }
  794. }
  795. $validateConvertedTransactionXsdString = $dom->saveXml();
  796. if($DBG){echo 'L.' . __LINE__ . ' $validateConvertedTransactionXsdString:';print_r($validateConvertedTransactionXsdString);echo "\n";}
  797. $reqXml = new DOMDocument();
  798. $reqXml->loadXml($convertedTransaction);
  799. // TODO: fetch PHP Warning: DOMDocument::schemaValidateSource(): Element 'PARENT_ID': 'abc' is not a valid value of the atomic type 'xs:integer'.
  800. return $reqXml->schemaValidateSource($validateConvertedTransactionXsdString);
  801. }
  802. public function getInstanceFeatures($name, $args) {
  803. $acl = $this->getAclFromTypeName("{$args['typePrefix']}:{$name}");
  804. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  805. $rootWfsNs = 'p5';
  806. $rootWfsNsUri = "{$baseNsUri}";
  807. $wfsNs = $args['typePrefix'];
  808. $wfsNsUri = "{$baseNsUri}/" . ('p5_' == substr($args['typePrefix'], 0, 3)) ? substr($args['typePrefix'], 3) : $args['typePrefix'];
  809. $featureTypeUri = $this->getBaseUri() . "?SERVICE=WFS&VERSION=1.0.0&TYPENAME={$args['xsd:type']}&REQUEST=DescribeFeatureType";
  810. header('Content-type: application/xml; charset=utf-8');
  811. $xmlWriter = new Core_XmlWriter();
  812. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  813. $xmlWriter->openUri('php://output');
  814. $xmlWriter->setIndent(true);
  815. $xmlWriter->startDocument('1.0','UTF-8');
  816. $xmlWriter->startElement('wfs:FeatureCollection');
  817. $xmlWriter->writeAttribute('xmlns:wfs', 'http://www.opengis.net/wfs');
  818. $xmlWriter->writeAttribute('xmlns', 'http://www.opengis.net/wfs');
  819. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  820. $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  821. $xmlWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
  822. $xmlWriter->writeAttribute("xmlns:{$wfsNs}", $wfsNsUri);
  823. if (!$simple) $xmlWriter->writeAttribute("xmlns:{$rootWfsNs}", $rootWfsNsUri);
  824. $xmlWriter->writeAttribute('xsi:schemaLocation', "{$wfsNsUri} {$featureTypeUri}");
  825. $xmlWriter->writeComment("INSTANCE TABLE: " . Core_AclHelper::getInstanceTable($acl->getRootTableName()));
  826. // <gml:featureMember>
  827. // <p5_objects:TestPerms fid="TestPerms.64" p5:web_link="https://biuro.biall-net.pl/dev-pl/se-master/index.php?_route=ViewTableAjax&amp;namespace=default_objects/TestPerms#EDIT/64">
  828. // <p5_objects:ID p5:allow_write="true">64</p5_objects:ID>
  829. $xmlWriter->endElement();// wfs:FeatureCollection
  830. $xmlWriter->endDocument();
  831. exit;
  832. }
  833. public function _describeInstanceAttributeTable($nsPrefix, $name) {
  834. $acl = $this->getAclFromTypeName("{$nsPrefix}:{$name}");
  835. header('Content-type: application/xml; charset=utf-8');
  836. $xmlWriter = new Core_XmlWriter();
  837. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  838. $xmlWriter->openUri('php://output');
  839. $xmlWriter->setIndent(true);
  840. $xmlWriter->startDocument('1.0','UTF-8');
  841. $xmlWriter->startElement('xsd:schema');
  842. $xmlWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema');
  843. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  844. foreach (Api_WfsNs::getNsList() as $uri => $prefix) {
  845. $xmlWriter->writeAttribute("xmlns:{$prefix}", $uri);
  846. }
  847. $xmlWriter->writeAttribute('elementFormDefault', 'qualified');
  848. $xsdInstanceType = $acl->getName() . "_instanceType";
  849. $xsdPrimaryKey = "xsd:string";// TODO: get from $acl
  850. $xmlWriter->h('xsd:element', ['name'=>"instance"], [
  851. [ 'xsd:complexType', [
  852. [ 'xsd:sequence', [
  853. [ 'xsd:element', ['name'=>"primaryKey", 'type'=>$xsdPrimaryKey], null ],
  854. [ 'xsd:element', ['name'=>"instance_name", 'type'=>$xsdInstanceType], null ],
  855. [ 'xsd:element', ['name'=>"instance_type", 'type'=>"xsd:string"], null ],// TODO: instance, derived, matching
  856. [ 'xsd:element', ['name'=>"create_author", 'type'=>"xsd:string"], null ],
  857. [ 'xsd:element', ['name'=>"create_date", 'type'=>"xsd:dateTime"], null ],
  858. [ 'xsd:element', ['name'=>"update_author", 'type'=>"xsd:string"], null ],
  859. [ 'xsd:element', ['name'=>"updage_date", 'type'=>"xsd:dateTime"], null ],
  860. [ 'xsd:element', ['name'=>"verified", 'type'=>"xsd:integer"], null ],
  861. ] ]
  862. ] ]
  863. ]);
  864. $instanceList = (method_exists($acl, 'getInstanceList'))
  865. ? array_map(function ($instanceName) {
  866. return [ 'xsd:enumeration', ['value'=>$instanceName], null ];
  867. }, $acl->getInstanceList())
  868. : [ [ 'xsd:enumeration', ['value'=>$acl->getName()], null ] ]
  869. ;
  870. $xmlWriter->h('xsd:simpleType', ['name'=>$xsdInstanceType], [
  871. [ 'xsd:restriction', ['base'=>"xsd:string"], $instanceList ],
  872. ]);
  873. $xmlWriter->endElement();// xsd:schema
  874. $xmlWriter->endDocument();
  875. exit;
  876. }
  877. public function _getDescribeFeatureType($nsPrefix, $type, $simple = true) {
  878. return $this->_getDescribeFeatureTypes(array(array($nsPrefix, $type)), $simple);
  879. }
  880. public function _parseDescribeFeatureTypeRequest($reqContent, $simple = true) {
  881. $parserXml = xml_parser_create();
  882. xml_parser_set_option($parserXml, XML_OPTION_CASE_FOLDING, 0);
  883. xml_parser_set_option($parserXml, XML_OPTION_SKIP_WHITE, 1);
  884. if (0 == xml_parse_into_struct($parserXml, $reqContent, $tags)) {
  885. throw new Exception("Error parsing xml");
  886. }
  887. xml_parser_free($parserXml);
  888. if (empty($tags)) {
  889. throw new Exception("Empty structure from request");
  890. }
  891. $rootTagName = V::get('tag', '', $tags[0]);
  892. if ('DescribeFeatureType' != $rootTagName) {
  893. throw new Api_WfsException("Wrong xml root tag '{$rootTagName}' #" . __LINE__, 501);
  894. }
  895. $requestXmlTags = $tags;
  896. $DBG = (V::get('DBG_XML', '', $_GET) > 0);// TODO: Profiler
  897. $rootTagName = V::get('tag', '', $requestXmlTags[0]);
  898. if ('DescribeFeatureType' != $rootTagName) {
  899. throw new Exception("Parse Request xml error #" . __LINE__);
  900. }
  901. /*[1] => Array(
  902. [tag] => TypeName
  903. [type] => complete
  904. [level] => 2
  905. [value] => p5_default_db:Rozdzielcza_rurociag_wsg84)
  906. */
  907. $typeNames = array();
  908. $totalTypes = count($requestXmlTags) - 1;
  909. for ($i = 1; $i < $totalTypes; $i++) {
  910. if($DBG){echo "TAG[{$i}]:" . json_encode($requestXmlTags[$i]) . "\n";}
  911. $typeNames[] = explode(':', $requestXmlTags[$i]['value'], 2);
  912. }
  913. //echo "typeNames: " . json_encode($typeNames) . "\n";
  914. return $this->_getDescribeFeatureTypes($typeNames, $simple);
  915. }
  916. public function _getDescribeFeatureAllTypes($simple = true) {
  917. $db = DB::getDB();
  918. $idDefaultDB = $db->_zasob_id;
  919. $tblsAcl = $this->_getTableAclList();
  920. foreach ($tblsAcl as $tblAcl) {
  921. $dataSourceName = 'default_db';// TODO: getSourceName
  922. $tblName = $tblAcl->getName();
  923. $typeNames[] = array("p5_{$dataSourceName}", $tblName);
  924. }
  925. return $this->_getDescribeFeatureTypes($typeNames, $simple);
  926. }
  927. // @param $typeNames = array( array( $nsPrefix, $type ) )
  928. public function _getDescribeFeatureTypes($typeNames, $simple = true) {
  929. if (empty($typeNames)) throw new HttpException("Feature Type Names not defined", 400);
  930. $this->DBG("types:" . json_encode($typeNames), __LINE__, __FUNCTION__, __CLASS__);
  931. DBG::log($typeNames, 'array', "DescribeFeatureType \$typeNames");
  932. // TODO: fix namespace BUG for multiple types:
  933. // - fetch namespace for first type
  934. // - if another object has another namespace then -> import tag
  935. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  936. $rootWfsNs = 'p5';
  937. $rootWfsNsUri = "{$baseNsUri}";
  938. $featureTypeUri = Api_WfsNs::getBaseWfsUri() . "?SERVICE=WFS&VERSION=1.0.0&REQUEST=DescribeFeatureType";
  939. header('Content-type: application/xml');
  940. $nsMap = Api_WfsNs::getNsList();// uri => prefix
  941. $xsdTargetNamespace = null;
  942. { // targetNamespace
  943. list($nsPrefix, $objectName) = reset($typeNames);
  944. $typeName = "{$nsPrefix}:{$objectName}";
  945. $acl = $this->getAclFromTypeName($typeName);
  946. $aclNamespaceUri = Api_WfsNs::getNsUri($acl->getSourceName());
  947. $xsdTargetNamespace = $aclNamespaceUri;
  948. if (!array_key_exists($aclNamespaceUri, $nsMap)) $nsMap[$aclNamespaceUri] = $acl->getSourceName();
  949. }
  950. $xmlWriter = new Core_XmlWriter();
  951. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  952. $xmlWriter->openMemory();// openUri('php://output');
  953. $xmlWriter->setIndent(true);
  954. $xmlWriter->startDocument('1.0','UTF-8');
  955. $xmlWriter->startElement('xsd:schema');
  956. $xmlWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema');
  957. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  958. foreach (Api_WfsNs::getNsList() as $uri => $prefix) {
  959. $xmlWriter->writeAttribute("xmlns:{$prefix}", $uri);
  960. }
  961. $xmlWriter->writeAttribute('elementFormDefault', "qualified");
  962. if ($xsdTargetNamespace) $xmlWriter->writeAttribute('targetNamespace', $xsdTargetNamespace);
  963. $schemaLocations = [];
  964. //$schemaLocations[] = 'http://www.opengis.net/wfs http://webgis.regione.sardegna.it:80/geoserver/schemas/wfs/1.0.0/WFS-capabilities.xsd';// @from http://webgis.regione.sardegna.it/geoserver/ows?service=WFS&request=GetCapabilities
  965. if (!empty($schemaLocations)) $xmlWriter->writeAttribute('xsi:schemaLocation', implode(' ', $schemaLocations));
  966. $xmlWriter->writeAttribute('version', "1.0.0");
  967. $xmlWriter->h('xsd:import', [
  968. 'namespace' => "http://www.opengis.net/gml",
  969. 'schemaLocation' => Request::getPathUri() . "schema/gml/2.1.2/feature.xsd"
  970. ], null);
  971. foreach ($typeNames as $typeNameEx) {
  972. list($nsPrefix, $objectName) = $typeNameEx;
  973. $typeName = "{$nsPrefix}:{$objectName}";
  974. $xmlWriter->writeComment("typeName '{$typeName}'");
  975. $acl = $this->getAclFromTypeName($typeName);
  976. $aclNamespaceUri = Api_WfsNs::getNsUri($acl->getSourceName());
  977. if (!array_key_exists($aclNamespaceUri, $nsMap)) $nsMap[$aclNamespaceUri] = $acl->getSourceName();
  978. if ($xsdTargetNamespace != $aclNamespaceUri) {
  979. $xmlWriter->writeComment("TODO: typeName '{$typeName}' by import namespace '{$aclNamespaceUri}'");// TODO: <xsd:import>; continue;
  980. }
  981. DBG::log($acl->hasSimpleSchema(), 'array', "\$acl({$typeName})->hasSimpleSchema()");
  982. if ($acl->hasSimpleSchema()) {
  983. $simpleSchema = $acl->getSimpleSchema();
  984. $xmlWriter->writeComment("TODO: typeName '{$typeName}' hasSimpleSchema L." . __LINE__);
  985. $aliasRefMap = array();// fieldName => namespace uri
  986. foreach ($simpleSchema as $ssName => $schema) {
  987. if ('root' == $ssName) $ssName = $objectName;
  988. foreach ($schema as $fieldName => $field) {
  989. if (is_array($field)
  990. && !empty($field['@ref'])
  991. && false !== strpos($field['@ref'], '/')
  992. ) {// @ref_uri
  993. $aliasRefMap[ "{$ssName}_{$fieldName}" ] = $field['@ref'];
  994. }
  995. }
  996. }
  997. if (!empty($aliasRefMap)) {
  998. foreach ($aliasRefMap as $fieldName => $aliasNsUri) {
  999. list($nsUri, $prefix, $name) = Api_WfsNs::parseObjectNsUri($aliasNsUri);
  1000. if (!array_key_exists($nsUri, $nsMap)) $nsMap[$nsUri] = $prefix;
  1001. $xmlWriter->h('xsd:import', ['namespace' => $nsUri, 'schemaLocation' => "{$nsUri}.xsd"], null); // TODO: real file url -> DescribeFeatureType[Advanced]
  1002. }
  1003. }
  1004. foreach ($simpleSchema as $ssName => $schema) {
  1005. {// code from Code_AclSimpleSchema
  1006. if ('root' == $ssName) $ssName = $objectName;
  1007. // <xsd:complexType name="ZaliczkaPozycjaType">
  1008. // <xsd:complexContent>
  1009. // <xsd:extension base="gml:AbstractFeatureType">
  1010. // <xsd:sequence>
  1011. // <xsd:element minOccurs="0" maxOccurs="1" name="id" type="xsd:integer" nillable="true"/>
  1012. // <xsd:element minOccurs="0" maxOccurs="1" name="created" type="xsd:date" nillable="true"/>
  1013. // <xsd:element minOccurs="0" maxOccurs="1" ref="default_objects/AccessOwner" p5:name="worker"/>
  1014. // <xsd:element minOccurs="0" maxOccurs="1" name="kwota" type="xsd:decimal" nillable="true"/>
  1015. // <xsd:element minOccurs="0" maxOccurs="1" ref="ZaliczkaPozycja" p5:name="pozycja"/>
  1016. // </xsd:sequence>
  1017. // </xsd:extension>
  1018. // </xsd:complexContent>
  1019. // </xsd:complexType>
  1020. $tnsPrefix = $acl->getSourceName();
  1021. $xmlWriter->startElement('xsd:complexType');
  1022. $xmlWriter->writeAttribute('name', "{$ssName}Type");
  1023. $xmlWriter->startElement('xsd:sequence');
  1024. foreach ($schema as $fieldName => $field) {
  1025. // [@namespace] => default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja
  1026. // [id] => xsd:integer
  1027. // [kwota] => xsd:decimal
  1028. // [korespondencja] => [ '@ref' => Korespondencja ]
  1029. // [projekt] => [ '@ref' => Projekt ]
  1030. // TODO: p5:field_name
  1031. if ('@' == substr($fieldName, 0, 1)) continue;// skip tags
  1032. $xmlWriter->startElement('xsd:element');
  1033. if (!is_array($field)) throw new Exception("Error Processing simpleSchema: '{$ssName}/{$fieldName}'");
  1034. if (!empty($field['@type'])) {
  1035. $xmlWriter->writeAttribute('name', $fieldName);
  1036. $xmlWriter->writeAttribute('type', $field['@type']);
  1037. $xmlWriter->writeAttribute('nillable', "true");
  1038. } else if (!empty($field['@ref'])) {
  1039. if (false !== strpos($field['@ref'], '/')) {// @ref_uri
  1040. $xmlWriter->writeAttribute('ref', "{$tnsPrefix}:{$ssName}_{$fieldName}");
  1041. $xmlWriter->writeAttributeNS($rootWfsNs, "name", $rootWfsNsUri, $fieldName);
  1042. } else {
  1043. $xmlWriter->writeAttribute('ref', "{$tnsPrefix}:{$field['@ref']}");
  1044. if ($fieldName != $field['@ref']) {
  1045. $xmlWriter->writeAttributeNS($rootWfsNs, "name", $rootWfsNsUri, $fieldName);
  1046. }
  1047. }
  1048. } else {
  1049. throw new Exception("Error Processing simpleSchema - missing @type or @ref: '{$ssName}/{$fieldName}'");
  1050. }
  1051. if (array_key_exists('@minOccurs', $field)) $xmlWriter->writeAttribute('minOccurs', $field['@minOccurs']);
  1052. if (array_key_exists('@maxOccurs', $field)) $xmlWriter->writeAttribute('maxOccurs', $field['@maxOccurs']);
  1053. $xmlWriter->endElement(); // 'xsd:element'
  1054. }
  1055. $xmlWriter->endElement(); // 'xsd:sequence'
  1056. $xmlWriter->endElement(); // 'xsd:complexType'
  1057. $xmlWriter->startElement('xsd:element');
  1058. $xmlWriter->writeAttribute('name', $ssName);
  1059. $xmlWriter->writeAttribute('type', "{$tnsPrefix}:{$ssName}Type");
  1060. if (!$simple) {
  1061. if (!empty($schema['@namespace'])) {// TODO: @namespace is required?
  1062. list($nsUri, $prefix, $name) = Api_WfsNs::parseObjectNsUri($schema['@namespace']);
  1063. $xmlWriter->writeAttributeNS($rootWfsNs, "namespace", $rootWfsNsUri, "{{$nsUri}}{$name}");
  1064. }
  1065. }
  1066. $xmlWriter->endElement(); // 'xsd:element'
  1067. }
  1068. }
  1069. if (!empty($aliasRefMap)) {
  1070. foreach ($aliasRefMap as $fieldName => $aliasNsUri) {
  1071. list($nsUri, $prefix, $name) = Api_WfsNs::parseObjectNsUri($aliasNsUri);
  1072. $xmlWriter->h('xsd:element', ['name' => $fieldName, 'type' => "{$prefix}:{$name}Type"], null);
  1073. }
  1074. }
  1075. } else {
  1076. $objectXsdName = "{$objectName}Type";
  1077. $xmlWriter->startElement('xsd:complexType');
  1078. $xmlWriter->writeAttribute('name', $objectXsdName);
  1079. // if (!$simple) $xmlWriter->writeAttribute("xlmns:{$rootWfsNs}", $rootWfsNsUri);
  1080. if (!$simple) $xmlWriter->writeAttributeNS($rootWfsNs, "web_link", $rootWfsNsUri, Request::getPathUri() . "index.php?_route=ViewTableAjax&namespace=" . $acl->getNamespace());
  1081. if (!$simple && ($lastUpdateDate = $acl->lastUpdateDate())) $xmlWriter->writeAttributeNS($rootWfsNs, "last_update_date", $rootWfsNsUri, $lastUpdateDate);
  1082. $xmlWriter->startElement('xsd:complexContent');
  1083. $xmlWriter->startElement('xsd:extension');
  1084. $xmlWriter->writeAttribute('base', "gml:AbstractFeatureType");
  1085. $xmlWriter->startElement('xsd:sequence');
  1086. $pKeyField = $acl->getPrimaryKeyField();
  1087. $p5Attributes = ($simple)? array() : $acl->getAttributesFromZasoby();
  1088. $fldList = $this->_getFieldListFromAcl($acl);
  1089. foreach ($fldList as $fldName) {
  1090. $xmlWriter->startElement('xsd:element');
  1091. // TODO: get minOccurs from $acl->xsd()
  1092. $xmlWriter->writeAttribute('minOccurs', (method_exists($acl, 'getXsdMinOccurs'))
  1093. ? $acl->getXsdMinOccurs($fldName)
  1094. : (($pKeyField == $fldName) ? '1' : '0')
  1095. );
  1096. $xmlWriter->writeAttribute('maxOccurs', (method_exists($acl, 'getXsdMaxOccurs'))
  1097. ? $acl->getXsdMaxOccurs($fldName)
  1098. : '1'
  1099. );
  1100. $fldType = $acl->getXsdFieldType($fldName);
  1101. if (!$simple && $acl->isEnumerationField($fldName)) {
  1102. $fldType = $acl->getSourceName() . ":{$fldName}Type";
  1103. }
  1104. if ('ref:' == substr($fldType, 0, 4)) {
  1105. $xmlWriter->writeAttribute("ref", substr($fldType, 4));
  1106. $xmlWriter->writeAttributeNS($rootWfsNs, "name", $rootWfsNsUri, $fldName);
  1107. } else if ('local_ref:' == substr($fldType, 0, 10)) {
  1108. $xmlWriter->writeAttribute("type", "{$fldName}Type");
  1109. $xmlWriter->writeAttributeNS($rootWfsNs, "name", $rootWfsNsUri, $fldName);
  1110. } else if ('alias_ref:' == substr($fldType, 0, 10)) {
  1111. $xmlWriter->writeAttribute("ref", $acl->getSourceName() . ":{$fldName}");
  1112. $xmlWriter->writeAttributeNS($rootWfsNs, "name", $rootWfsNsUri, $fldName);
  1113. } else {
  1114. $xmlWriter->writeAttribute('name', $fldName);
  1115. $xmlWriter->writeAttribute('type', $fldType);
  1116. $xmlWriter->writeAttribute('nillable', 'true');// nillable not allowed in ref
  1117. }
  1118. if (!$simple) {
  1119. if (!empty($p5Attributes[$fldName])) {
  1120. $p5attrs = $p5Attributes[$fldName];
  1121. if (!empty($p5attrs['id_zasob'])) $xmlWriter->writeAttributeNS($rootWfsNs, "id_zasob", $rootWfsNsUri, $p5attrs['id_zasob']);
  1122. if (!empty($p5attrs['label'])) $xmlWriter->writeAttributeNS($rootWfsNs, "label", $rootWfsNsUri, $p5attrs['label']);
  1123. if (!empty($p5attrs['description'])) $xmlWriter->writeAttributeNS($rootWfsNs, "description", $rootWfsNsUri, $p5attrs['description']);
  1124. }
  1125. if ($acl->canWriteField($fldName)) $xmlWriter->writeAttributeNS($rootWfsNs, "allow_write", $rootWfsNsUri, "true");
  1126. if ($acl->canCreateField($fldName)) $xmlWriter->writeAttributeNS($rootWfsNs, "allow_create", $rootWfsNsUri, "true");
  1127. if (!$acl->canReadField($fldName)) $xmlWriter->writeAttributeNS($rootWfsNs, "allow_read", $rootWfsNsUri, "false");
  1128. }
  1129. $xmlWriter->endElement(); // xsd:element
  1130. }
  1131. $xmlWriter->endElement(); // xsd:sequence
  1132. if (!$simple) $xmlWriter->h('xsd:attribute', ['name' => "instance", 'type' => $acl->getSourceName() . ":instanceType"], null);
  1133. $xmlWriter->endElement(); // xsd:extension
  1134. $xmlWriter->endElement(); // xsd:complexContent
  1135. $xmlWriter->endElement(); // xsd:complexType
  1136. if (!$simple) {
  1137. $xsdInstanceList = (method_exists($acl, 'getInstanceList'))
  1138. ? array_map(function ($instanceName) {
  1139. return [ 'xsd:enumeration', ['value'=>$instanceName], null ];
  1140. }, $acl->getInstanceList())
  1141. : [ [ 'xsd:enumeration', ['value'=>$acl->getName()], null ] ]
  1142. ;
  1143. DBG::log($xsdInstanceList, 'array', "\$xsdInstanceList");
  1144. $xmlWriter->h('xsd:simpleType', ['name' => 'instanceType'], [
  1145. [ 'xsd:restriction', ['base' => 'xsd:string'], $xsdInstanceList ]
  1146. ]);
  1147. }
  1148. $xmlWriter->h('xsd:element', ['name' => $objectName, 'type' => $acl->getSourceName() . ':' . $objectXsdName, 'substitutionGroup'=>"gml:_Feature"], null);
  1149. foreach ($fldList as $fldName) {
  1150. $fldType = $acl->getXsdFieldType($fldName);
  1151. if ('alias_ref:' == substr($fldType, 0, 10)) {
  1152. $localRefType = substr($fldType, 10);
  1153. $xmlWriter->h('xsd:element', ['name' => $fldName, 'type' => $localRefType], null);
  1154. } else if ('local_ref:' == substr($fldType, 0, 10)) {
  1155. $localRefType = substr($fldType, 10);
  1156. $xmlWriter->writeComment("TODO:
  1157. <xsd:complexType name=\"produkt_Type\">
  1158. <xsd:sequence>
  1159. <xsd:element name=\"idProd\" type=\"xsd:integer\" />
  1160. <xsd:element name=\"nazwa\" type=\"xsd:string\" />
  1161. <xsd:element name=\"cena\" type=\"xsd:decimal\" />
  1162. </xsd:sequence>
  1163. </xsd:complexType>
  1164. ");
  1165. }
  1166. }
  1167. if (!$simple) {
  1168. foreach ($fldList as $fldName) {
  1169. if (!$acl->isEnumerationField($fldName)) continue;
  1170. $xsdEnumList = [];
  1171. $enum = $acl->getEnumerations($fldName);
  1172. foreach ($enum as $val => $label) {
  1173. $xsdEnum = ['xsd:enumeration', ['value' => $val], null];
  1174. if (!empty($p5Attributes[$fldName]['valuesMap'][$val])) {
  1175. $xsdEnum[1]["xmlns:{$rootWfsNs}"] = $rootWfsNsUri;
  1176. $xsdEnum[1]["{$rootWfsNs}:label"] = $p5Attributes[$fldName]['valuesMap'][$val];
  1177. }
  1178. $xsdEnumList[] = $xsdEnum;
  1179. }
  1180. $xmlWriter->h('xsd:simpleType', ['name' => "{$fldName}Type"], [
  1181. [ 'xsd:restriction', ['base' => "xsd:string"], $xsdEnumList ]
  1182. ]);
  1183. }
  1184. }
  1185. }
  1186. }
  1187. $xmlWriter->endElement(); // 'xsd:schema'
  1188. $xmlWriter->endDocument();
  1189. echo $xmlWriter->outputMemory($flush = true);
  1190. }
  1191. public function _getTableAclList() {// Use only Tables from default_db
  1192. $tblAclList = array();
  1193. $idDefaultDB = DB::getPDO()->getZasobId();
  1194. $fullTblAclList = $this->_usrAcl->getTablesAcl();
  1195. foreach ($fullTblAclList as $tblAcl) {
  1196. if ($idDefaultDB != $tblAcl->getDB()) {// hide non default_db tables
  1197. continue;
  1198. }
  1199. // $dataSourceName = 'default_db';// TODO: getSourceName
  1200. // $tblName = $tblAcl->getName();
  1201. // try {
  1202. // $acl = $this->getAclFromTypeName($typeName = "p5_{$dataSourceName}:{$tblName}");
  1203. // } catch (Exception $e) {
  1204. // // echo "Error for table({$tblName}): " . $e->getMessage() . "\n";
  1205. // }
  1206. // if (!$acl) {
  1207. // // TODO: error log msg
  1208. // continue;
  1209. // }
  1210. $tblAclList[] = $tblAcl;
  1211. }
  1212. return $tblAclList;
  1213. }
  1214. public function _getFieldListFromAcl($acl) {
  1215. $fldList = $acl->getRealFieldListByIdZasob();
  1216. return $fldList;
  1217. }
  1218. public function setLogger($logger) {
  1219. $this->_logger = $logger;
  1220. }
  1221. public function DBG($reqLog, $lineNr = null, $funName = null, $className = null) {
  1222. if (!$this->_logger) return;
  1223. $this->_logger->DBG($reqLog, $lineNr, $funName, $className);
  1224. }
  1225. public function parseOgcFilterRequest($requestOgcFilter) {
  1226. // GetFeature: @maxFeatures, @traverseXlinkDepth, @traverseXlinkExpiry
  1227. // \-- (1..) wfs:Query: @typeName
  1228. // \--- (0..) ---: wfs:PropertyName
  1229. // : wfs:XlinkPropertyName
  1230. // : ogc:Function
  1231. // ogc:Filter
  1232. // ogc:SortBy
  1233. // \--- (1..) ogc:SortProperty
  1234. // \---: ogc:PropertyName
  1235. // : ogc:SortOrder ( DESC / ASC )
  1236. // <ogc:SortBy>
  1237. // <ogc:SortProperty>
  1238. // <ogc:PropertyName>ASTA</ogc:PropertyName>
  1239. // <ogc:SortOrder>ASC</ogc:SortOrder>
  1240. // </ogc:SortProperty>
  1241. // </ogc:SortBy>
  1242. if (empty($requestOgcFilter)) return '';
  1243. $requestXml = new DOMDocument();
  1244. $requestXml->loadXml($requestOgcFilter);
  1245. $rootNode = $requestXml->documentElement;
  1246. // if ($rootNode->getAttribute('resolve'))
  1247. DBG::log([$rootNode->getAttribute('resolve'), $rootNode->getAttribute('resolveDepth')], 'array', "TODO: use wfs:GetFeature @resolve, @resolveDepth");
  1248. $nodesQuery = [];
  1249. foreach ($requestXml->getElementsByTagNameNS('http://www.opengis.net/wfs', 'Query') as $element) {
  1250. DBG::log($element->nodeName, 'array', "main loop - wfs:Query");
  1251. $nodesQuery[] = $element;
  1252. }
  1253. if (empty($nodesQuery)) { // legacy - try to find 'ogc:Filter'
  1254. $tagsFilter = [];
  1255. foreach ($requestXml->getElementsByTagNameNS('http://www.opengis.net/ogc', 'Filter') as $element) {
  1256. DBG::log($element->nodeName, 'array', "loop element (0 * wfs:Query)");
  1257. $tagsFilter[] = $requestXml->saveXML($element);
  1258. }
  1259. DBG::log($tagsFilter, 'array', "\$tagsFilter (0 * wfs:Query)");
  1260. return [
  1261. 'ogc:Filter' => (!empty($tagsFilter))
  1262. ? reset($tagsFilter) // TODO: only one ogc:Filter allowed
  1263. : ''
  1264. ];
  1265. }
  1266. if (1 === count($nodesQuery)) {
  1267. $tagsFilter = [];
  1268. foreach ($requestXml->getElementsByTagNameNS('http://www.opengis.net/ogc', 'Filter') as $element) {
  1269. // DBG::log($element->nodeName, 'array', "loop ogc:Filter (1 * wfs:Query)");
  1270. $tagsFilter[] = $requestXml->saveXML($element);
  1271. }
  1272. DBG::log($tagsFilter, 'array', "\$tagsFilter (1 * wfs:Query)");
  1273. $tagsWfsPropertyName = [];
  1274. foreach ($requestXml->getElementsByTagNameNS('http://www.opengis.net/wfs', 'PropertyName') as $element) {
  1275. // DBG::log($element->nodeValue, 'array', "loop wfs:PropertyName (1 * wfs:Query)");
  1276. if ($element->getAttribute('resolve')) DBG::log([$element->getAttribute('resolve'), $element->getAttribute('resolveDepth'), $element->getAttribute('resolvePath')], 'array', "TODO: use wfs:PropertyName @resolve, @resolveDepth, @resolvePath");
  1277. $value = $element->nodeValue;
  1278. if (in_array($element->getAttribute('resolve'), ['all', 'local', 'remote'])) {
  1279. $depth = $element->getAttribute('resolveDepth');
  1280. if ('*' !== substr($value, -1)) { // TODO: propertyName is not regex
  1281. if ('*' === $depth) $value .= "/**"; // TODO: resolveDepth="*" - resolve all
  1282. else if ((int)$depth > 0) $value .= str_repeat("/*", $depth);
  1283. }
  1284. }
  1285. $tagsWfsPropertyName[] = $value;
  1286. }
  1287. DBG::log($tagsWfsPropertyName, 'array', "\$tagsWfsPropertyName (1 * wfs:Query)");
  1288. return array_filter([
  1289. 'ogc:Filter' => (!empty($tagsFilter))
  1290. ? reset($tagsFilter)
  1291. : '',
  1292. 'wfs:PropertyName' => (!empty($tagsWfsPropertyName))
  1293. ? $tagsWfsPropertyName
  1294. : '',
  1295. ], function ($value) { return !empty($value); });
  1296. }
  1297. throw new Exception("Not imeplemented multiple ogc:Query"); // multiple ogc:Query require ogc:Query/@typeName
  1298. }
  1299. }