WfsServerBase.php 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810
  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. $lowerArgs = array(); foreach ($rawArgs as $name => $value) $lowerArgs[ strtolower($name) ] = trim($value);
  101. $args['xsd:type'] = V::get('typename', '', $lowerArgs);
  102. $exType = explode(':', $args['xsd:type']);
  103. if (count($exType) != 2) throw new HttpException("Wrong param TYPENAME", 400);
  104. $args['typePrefix'] = $exType[0];
  105. $args['typeName'] = $exType[1];
  106. $args['srsname'] = V::get('SRSNAME', '', $lowerArgs);// eg. EPSG:4326
  107. $args['limit'] = V::get('maxfeatures', $args['limit'], $lowerArgs, 'int');
  108. $args['limit'] = V::get('count', $args['limit'], $lowerArgs, 'int');
  109. $defaultFeaturesLimit = ('biuro.biall-net.pl' == V::get('SERVER_NAME', '', $_SERVER)) ? 50000 : 10000;
  110. if ($args['limit'] <= 0) $args['limit'] = $defaultFeaturesLimit;// default limit
  111. $args['offset'] = V::get('startindex', 0, $lowerArgs, 'int');
  112. $args['ogc:filter'] = urldecode(V::get('filter', '', $lowerArgs));
  113. if (empty($args['ogc:filter'])) {// read ogc:Filter from POST body if not defined in GET
  114. $reqBody = Request::getRequestBody();
  115. if (!empty($reqBody)) {
  116. $parsedRequest = $this->parseOgcFilterRequest($reqBody);
  117. DBG::log($parsedRequest, 'array', 'parsed ogc query request');
  118. if (!empty($parsedRequest['ogc:Filter'])) $args['ogc:filter'] = $parsedRequest['ogc:Filter'];
  119. if (!empty($parsedRequest['wfs:PropertyName'])) {
  120. foreach ($parsedRequest['wfs:PropertyName'] as $fieldXpath) {
  121. $args['filterFields'][] = $fieldXpath;
  122. }
  123. }
  124. }
  125. }
  126. $args['sortBy'] = V::get('sortby', '', $lowerArgs);// TODO: split to array of array(fieldName, (asc | desc))
  127. $args['wfs:propertyName'] = trim(V::get('propertyname', '', $lowerArgs));// TODO: fields to show - split by ','
  128. if (strlen($args['wfs:propertyName']) > 0) {
  129. $exFields = explode(',', $args['wfs:propertyName']);
  130. foreach ($exFields as $fieldName) {
  131. $fieldName = trim($fieldName);
  132. if (!empty($fieldName)) $args['filterFields'][] = $fieldName;
  133. }
  134. }
  135. $args['resultType'] = V::get('resulttype', '', $lowerArgs);
  136. $args['bbox'] = V::get('bbox', '', $lowerArgs);
  137. if (!empty($args['bbox'])) {
  138. // BBOX may have EPSG at then end - example: ",EPSG:4326"
  139. $num = "\d+.?\d*?";// "\d+(.\d+)?"
  140. if (!preg_match("/^({$num}),({$num}),({$num}),({$num})(\,EPSG:\d+)?$/", $args['bbox'], $matches)) throw new Exception("Illegal BBOX format");
  141. // QGIS send BBOX in correct order: 54.23580872176457,18.46844302390853,54.25220902538883,18.492990600812696
  142. // first number should not be smaller then second
  143. // example $matches:
  144. // [0] => 18.492990600812696,54.23580872176457,18.46844302390853,54.25220902538883
  145. // [1] => 18.492990600812696
  146. // [2] => 54.23580872176457
  147. // [3] => 18.46844302390853
  148. // [4] => 54.25220902538883
  149. // (optional) EPGS
  150. $bboxPoints = ($matches[1] > $matches[2])
  151. ? [ $matches[1], $matches[2], $matches[3], $matches[4] ]
  152. : [ $matches[2], $matches[3], $matches[4], $matches[1] ];
  153. $args['bbox'] = implode(",", $bboxPoints);
  154. }
  155. $args['wfs:featureID'] = V::get('featureid', null, $lowerArgs);// TODO: allow multiply feature id (csv)
  156. if ($args['wfs:featureID']) {
  157. $dotPos = strpos($args['wfs:featureID'], '.');
  158. if (!$dotPos) throw new Exception("Wrong param featureID");
  159. if ($args['typeName'] != substr($args['wfs:featureID'], 0, $dotPos)) throw new Exception("Wrong typeName in param featureID");
  160. $args['primaryKey'] = substr($args['wfs:featureID'], $dotPos + 1);
  161. }
  162. $pk = V::get('primarykey', '', $lowerArgs);
  163. if ($pk) {
  164. $args['primaryKey'] = $pk;
  165. }
  166. if(DBG::isActive() && V::get('DBG', 0, $_GET)){ echo "\$lowerArgs:";print_r($lowerArgs); }
  167. if(DBG::isActive() && V::get('DBG', 0, $_GET)){ echo "\$args:";print_r($args); }
  168. return $args;
  169. }
  170. public function _getCapabilities($wfsServerUrl, $serviceTitle, $serviceDescription) {
  171. if (V::get('DBG_ACL', '', $_GET)) {
  172. {
  173. echo "Core_AclHelper::getCustomAclList = [" . "\n";
  174. foreach (Core_AclHelper::getCustomAclList() as $typeName) {
  175. echo "|\t{$typeName}" . "\n";
  176. }
  177. echo "]// .EOF Core_AclHelper::getCustomAclList" . "\n";
  178. }
  179. $fullTblAclList = $this->_usrAcl->getTablesAcl();
  180. print_r($fullTblAclList);
  181. die("\n" . '.EOF - DBG_ACL');
  182. }
  183. header('Content-type: application/xml; charset=utf-8');
  184. $xmlWriter = new Core_XmlWriter();
  185. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  186. $xmlWriter->openUri('php://output');
  187. $xmlWriter->setIndent(true);
  188. $xmlWriter->startDocument('1.0','UTF-8');
  189. $xmlWriter->startElement('WFS_Capabilities');
  190. $xmlWriter->writeAttribute('xmlns', 'http://www.opengis.net/wfs');
  191. $xmlWriter->writeAttribute('xmlns:ogc', 'http://www.opengis.net/ogc');
  192. $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  193. foreach (Api_WfsNs::getNsList() as $uri => $prefix) {
  194. $xmlWriter->writeAttribute("xmlns:{$prefix}", $uri);
  195. }
  196. $schemaLocations = [];
  197. //$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
  198. if (!empty($schemaLocations)) $xmlWriter->writeAttribute('xsi:schemaLocation', implode(' ', $schemaLocations));
  199. $xmlWriter->writeAttribute('version', "1.0.0");
  200. $xmlWriter->h('Service', [
  201. ['Name', "WFS"],
  202. ['Title', $serviceTitle],
  203. ['Abstract', $serviceDescription],
  204. ['Keywords', "WFS, WMS"],
  205. ['OnlineResource', $wfsServerUrl],
  206. ['Fees', "NONE"],
  207. ['AccessConstraints', "NONE"],
  208. ]);
  209. $xmlWriter->h('Capability', [
  210. [ 'Request', [
  211. [ 'GetCapabilities', [
  212. [ 'DCPType', [
  213. [ 'HTTP', [
  214. [ 'Get', [ 'onlineResource' => "{$wfsServerUrl}?REQUEST=GetCapabilities" ], null ]
  215. ] ]
  216. ] ],
  217. [ 'DCPType', [
  218. [ 'HTTP', [
  219. [ 'Post', [ 'onlineResource' => "{$wfsServerUrl}" ], null ]
  220. ] ]
  221. ] ],
  222. ] ]
  223. ] ]
  224. ]);
  225. $xmlWriter->h('DescribeFeatureType', [
  226. [ 'SchemaDescriptionLanguage', [
  227. [ 'XMLSCHEMA', null ]
  228. ] ],
  229. [ 'DCPType', [
  230. [ 'HTTP', [
  231. [ 'Get', ['onlineResource' => "{$wfsServerUrl}?REQUEST=DescribeFeatureType"], null ]
  232. ] ]
  233. ] ],
  234. [ 'DCPType', [
  235. [ 'HTTP', [
  236. [ 'Post', ['onlineResource' => "{$wfsServerUrl}"], null ]
  237. ] ]
  238. ] ],
  239. ]);
  240. $xmlWriter->h('GetFeature', [// $this->_printGetFeatureXml($wfsServerUrl);
  241. [ 'ResultFormat', [
  242. 'WFSKMLOutputFormat',
  243. 'GML2',
  244. 'GML3',
  245. 'SHAPE-ZIP',
  246. 'CSV',
  247. 'JSON',
  248. ] ],
  249. [ 'DCPType', [
  250. [ 'HTTP', [
  251. [ 'Get', ['onlineResource' => "{$wfsServerUrl}?REQUEST=GetFeature"], null ]
  252. ] ]
  253. ] ],
  254. [ 'DCPType', [
  255. [ 'HTTP', [
  256. [ 'Post', ['onlineResource' => "{$wfsServerUrl}"], null ]
  257. ] ]
  258. ] ],
  259. ]);
  260. $xmlWriter->h('Transaction', [
  261. [ 'DCPType', [
  262. [ 'HTTP', [
  263. [ 'Get', ['onlineResource' => "{$wfsServerUrl}?REQUEST=Transaction"], null ]
  264. ] ]
  265. ] ],
  266. [ 'DCPType', [
  267. [ 'HTTP', [
  268. [ 'Post', ['onlineResource' => "{$wfsServerUrl}"], null ]
  269. ] ]
  270. ] ],
  271. ]);
  272. $xmlWriter->h('LockFeature', [
  273. [ 'DCPType', [
  274. [ 'HTTP', [
  275. [ 'Get', ['onlineResource' => "{$wfsServerUrl}?REQUEST=LockFeature"], null ]
  276. ] ]
  277. ] ],
  278. [ 'DCPType', [
  279. [ 'HTTP', [
  280. [ 'Post', ['onlineResource' => "{$wfsServerUrl}"], null ]
  281. ] ]
  282. ] ],
  283. ]);
  284. $xmlWriter->h('GetFeatureWithLock', [
  285. [ 'ResultFormat', [
  286. 'GML2'
  287. ] ],
  288. [ 'DCPType', [
  289. [ 'HTTP', [
  290. [ 'Get', ['onlineResource' => "{$wfsServerUrl}?REQUEST=GetFeatureWithLock"], null ]
  291. ] ]
  292. ] ],
  293. [ 'DCPType', [
  294. [ 'HTTP', [
  295. [ 'Post', ['onlineResource' => "{$wfsServerUrl}"], null ]
  296. ] ]
  297. ] ],
  298. ]);
  299. $featureTypeNodes = [];
  300. foreach ($this->_getTableAclList() as $tblAcl) {
  301. $ns = Core_AclHelper::parseNamespaceUrl($tblAcl->getNamespace());
  302. DBG::log(['ns'=>$ns, 'acl_ns'=>$tblAcl->getNamespace(), 'cls'=>get_class($tblAcl)], 'array', "tblAcl [".$tblAcl->getID()."]");
  303. $dataSourceName = 'default_db';// TODO: $tblAcl->getSourceName()
  304. $prefix = "p5_{$dataSourceName}";
  305. $featureTypeNodes[] = [ 'FeatureType', [ "xmlns:{$prefix}" => Api_WfsNs::getNsUri($prefix) ], [
  306. [ 'Name', "p5_" . "{$ns['prefix']}:{$ns['name']}" ], // TODO: remove 'p5_' prefix
  307. [ 'Title', $tblAcl->getRawLabel() ],
  308. [ 'Abstract', $tblAcl->getRawOpis() ],
  309. [ 'Keywords', implode(', ', [ $tblAcl->getID(), $tblAcl->getName(), $tblAcl->getRawLabel() ]) ],
  310. [ 'SRS', 'EPSG:4326' ],
  311. [ 'LatLongBoundingBox', [
  312. 'minx' => "8.12328509871721",
  313. 'miny' => "38.8575126897477",
  314. 'maxx' => "9.838674658246807",
  315. 'maxy' => "41.31378404137082"], null ]
  316. ] ];
  317. }
  318. foreach (Core_AclHelper::getCustomAclList() as $typeName) {
  319. list($prefix, $name) = explode(':', $typeName);
  320. $featureTypeNodes[] = [ 'FeatureType', [ "xmlns:{$prefix}" => Api_WfsNs::getNsUri($prefix) ], [
  321. [ 'Name', "{$prefix}:{$name}" ],
  322. [ 'Title', $name ],
  323. [ 'Abstract', $name ],
  324. [ 'Keywords', $name ],
  325. [ 'SRS', 'EPSG:4326' ],
  326. ] ];
  327. }
  328. $xmlWriter->startElement('FeatureTypeList');
  329. $xmlWriter->h('Operations', ['Query', 'Insert', 'Update', 'Delete', 'Lock']);
  330. if (DBG::isActive()) {
  331. DBG::log(array_map(function ($feature) {
  332. return "{$feature[2][0][1]}, ".array_values($feature[1])[0];
  333. }, $featureTypeNodes), 'array', "\$featureTypeNodes");
  334. }
  335. foreach ($featureTypeNodes as $node) {
  336. $xmlWriter->h($node);
  337. }
  338. $xmlWriter->endElement();// FeatureTypeList
  339. $xmlWriter->h('ogc:Filter_Capabilities', [
  340. [ 'ogc:Spatial_Capabilities', [
  341. [ 'ogc:Spatial_Operators', [
  342. 'ogc:Disjoint',
  343. 'ogc:Equals',
  344. 'ogc:DWithin',
  345. 'ogc:Beyond',
  346. 'ogc:Intersect',
  347. 'ogc:Touches',
  348. 'ogc:Crosses',
  349. 'ogc:Within',
  350. 'ogc:Contains',
  351. 'ogc:Overlaps',
  352. 'ogc:BBOX',
  353. ] ]
  354. ] ],
  355. [ 'ogc:Scalar_Capabilities', [
  356. 'ogc:Logical_Operators',
  357. [ 'ogc:Comparison_Operators', [
  358. 'ogc:Simple_Comparisons',
  359. 'ogc:Between',
  360. 'ogc:Like',
  361. 'ogc:NullCheck',
  362. ] ],
  363. [ 'ogc:Arithmetic_Operators', [
  364. 'ogc:Simple_Arithmetic',
  365. [ 'ogc:Functions', [
  366. [ 'ogc:Function_Names', [
  367. [ 'ogc:Function_Name', ['nArgs'=>"1"], "abs" ],
  368. [ 'ogc:Function_Name', ['nArgs'=>"1"], "abs_2" ],
  369. [ 'ogc:Function_Name', ['nArgs'=>"1"], "abs_3" ],
  370. [ 'ogc:Function_Name', ['nArgs'=>"1"], "abs_4" ],
  371. [ 'ogc:Function_Name', ['nArgs'=>"1"], "acos" ],
  372. [ 'ogc:Function_Name', ['nArgs'=>"2"], "AddCoverages" ],
  373. [ 'ogc:Function_Name', ['nArgs'=>"4"], "Aggregate" ],
  374. [ 'ogc:Function_Name', ['nArgs'=>"1"], "Area" ],
  375. [ 'ogc:Function_Name', ['nArgs'=>"1"], "area2" ],
  376. [ 'ogc:Function_Name', ['nArgs'=>"3"], "AreaGrid" ],
  377. [ 'ogc:Function_Name', ['nArgs'=>"1"], "asin" ],
  378. [ 'ogc:Function_Name', ['nArgs'=>"1"], "atan" ],
  379. [ 'ogc:Function_Name', ['nArgs'=>"2"], "atan2" ],
  380. [ 'ogc:Function_Name', ['nArgs'=>"14"], "BarnesSurface" ],
  381. [ 'ogc:Function_Name', ['nArgs'=>"3"], "between" ],
  382. [ 'ogc:Function_Name', ['nArgs'=>"1"], "boundary" ],
  383. [ 'ogc:Function_Name', ['nArgs'=>"1"], "boundaryDimension" ],
  384. [ 'ogc:Function_Name', ['nArgs'=>"1"], "Bounds" ],
  385. [ 'ogc:Function_Name', ['nArgs'=>"2"], "buffer" ],
  386. [ 'ogc:Function_Name', ['nArgs'=>"3"], "BufferFeatureCollection" ],
  387. [ 'ogc:Function_Name', ['nArgs'=>"3"], "bufferWithSegments" ],
  388. [ 'ogc:Function_Name', ['nArgs'=>"7"], "Categorize" ],
  389. [ 'ogc:Function_Name', ['nArgs'=>"1"], "ceil" ],
  390. [ 'ogc:Function_Name', ['nArgs'=>"1"], "Centroid" ],
  391. [ 'ogc:Function_Name', ['nArgs'=>"2"], "classify" ],
  392. [ 'ogc:Function_Name', ['nArgs'=>"2"], "Clip" ],
  393. [ 'ogc:Function_Name', ['nArgs'=>"1"], "CollectGeometries" ],
  394. [ 'ogc:Function_Name', ['nArgs'=>"1"], "Collection_Average" ],
  395. [ 'ogc:Function_Name', ['nArgs'=>"1"], "Collection_Bounds" ],
  396. [ 'ogc:Function_Name', ['nArgs'=>"0"], "Collection_Count" ],
  397. [ 'ogc:Function_Name', ['nArgs'=>"1"], "Collection_Max" ],
  398. [ 'ogc:Function_Name', ['nArgs'=>"1"], "Collection_Median" ],
  399. [ 'ogc:Function_Name', ['nArgs'=>"1"], "Collection_Min" ],
  400. [ 'ogc:Function_Name', ['nArgs'=>"1"], "Collection_Sum" ],
  401. [ 'ogc:Function_Name', ['nArgs'=>"1"], "Collection_Unique" ],
  402. [ 'ogc:Function_Name', ['nArgs'=>"1"], "Concatenate" ],
  403. [ 'ogc:Function_Name', ['nArgs'=>"2"], "contains" ],
  404. [ 'ogc:Function_Name', ['nArgs'=>"7"], "Contour" ],
  405. [ 'ogc:Function_Name', ['nArgs'=>"2"], "convert" ],
  406. [ 'ogc:Function_Name', ['nArgs'=>"1"], "convexHull" ],
  407. [ 'ogc:Function_Name', ['nArgs'=>"1"], "cos" ],
  408. [ 'ogc:Function_Name', ['nArgs'=>"1"], "Count" ],
  409. [ 'ogc:Function_Name', ['nArgs'=>"2"], "CropCoverage" ],
  410. [ 'ogc:Function_Name', ['nArgs'=>"2"], "crosses" ],
  411. [ 'ogc:Function_Name', ['nArgs'=>"2"], "dateFormat" ],
  412. [ 'ogc:Function_Name', ['nArgs'=>"2"], "dateParse" ],
  413. [ 'ogc:Function_Name', ['nArgs'=>"2"], "difference" ],
  414. [ 'ogc:Function_Name', ['nArgs'=>"1"], "dimension" ],
  415. [ 'ogc:Function_Name', ['nArgs'=>"2"], "disjoint" ],
  416. [ 'ogc:Function_Name', ['nArgs'=>"2"], "disjoint3D" ],
  417. [ 'ogc:Function_Name', ['nArgs'=>"2"], "distance" ],
  418. [ 'ogc:Function_Name', ['nArgs'=>"2"], "distance3D" ],
  419. [ 'ogc:Function_Name', ['nArgs'=>"1"], "double2bool" ],
  420. [ 'ogc:Function_Name', ['nArgs'=>"1"], "endAngle" ],
  421. [ 'ogc:Function_Name', ['nArgs'=>"1"], "endPoint" ],
  422. [ 'ogc:Function_Name', ['nArgs'=>"1"], "env" ],
  423. [ 'ogc:Function_Name', ['nArgs'=>"1"], "envelope" ],
  424. [ 'ogc:Function_Name', ['nArgs'=>"2"], "EqualInterval" ],
  425. [ 'ogc:Function_Name', ['nArgs'=>"2"], "equalsExact" ],
  426. [ 'ogc:Function_Name', ['nArgs'=>"3"], "equalsExactTolerance" ],
  427. [ 'ogc:Function_Name', ['nArgs'=>"2"], "equalTo" ],
  428. [ 'ogc:Function_Name', ['nArgs'=>"1"], "exp" ],
  429. [ 'ogc:Function_Name', ['nArgs'=>"1"], "exteriorRing" ],
  430. [ 'ogc:Function_Name', ['nArgs'=>"3"], "Feature" ],
  431. [ 'ogc:Function_Name', ['nArgs'=>"1"], "floor" ],
  432. [ 'ogc:Function_Name', ['nArgs'=>"1"], "geometryType" ],
  433. [ 'ogc:Function_Name', ['nArgs'=>"1"], "geomFromWKT" ],
  434. [ 'ogc:Function_Name', ['nArgs'=>"1"], "geomLength" ],
  435. [ 'ogc:Function_Name', ['nArgs'=>"2"], "getGeometryN" ],
  436. [ 'ogc:Function_Name', ['nArgs'=>"1"], "getX" ],
  437. [ 'ogc:Function_Name', ['nArgs'=>"1"], "getY" ],
  438. [ 'ogc:Function_Name', ['nArgs'=>"1"], "getz" ],
  439. [ 'ogc:Function_Name', ['nArgs'=>"2"], "greaterEqualThan" ],
  440. [ 'ogc:Function_Name', ['nArgs'=>"2"], "greaterThan" ],
  441. [ 'ogc:Function_Name', ['nArgs'=>"5"], "Grid" ],
  442. [ 'ogc:Function_Name', ['nArgs'=>"7"], "Heatmap" ],
  443. [ 'ogc:Function_Name', ['nArgs'=>"0"], "id" ],
  444. [ 'ogc:Function_Name', ['nArgs'=>"2"], "IEEEremainder" ],
  445. [ 'ogc:Function_Name', ['nArgs'=>"3"], "if_then_else" ],
  446. [ 'ogc:Function_Name', ['nArgs'=>"11"], "in10" ],
  447. [ 'ogc:Function_Name', ['nArgs'=>"3"], "in2" ],
  448. [ 'ogc:Function_Name', ['nArgs'=>"4"], "in3" ],
  449. [ 'ogc:Function_Name', ['nArgs'=>"5"], "in4" ],
  450. [ 'ogc:Function_Name', ['nArgs'=>"6"], "in5" ],
  451. [ 'ogc:Function_Name', ['nArgs'=>"7"], "in6" ],
  452. [ 'ogc:Function_Name', ['nArgs'=>"8"], "in7" ],
  453. [ 'ogc:Function_Name', ['nArgs'=>"9"], "in8" ],
  454. [ 'ogc:Function_Name', ['nArgs'=>"10"], "in9" ],
  455. [ 'ogc:Function_Name', ['nArgs'=>"2"], "InclusionFeatureCollection" ],
  456. [ 'ogc:Function_Name', ['nArgs'=>"1"], "int2bbool" ],
  457. [ 'ogc:Function_Name', ['nArgs'=>"1"], "int2ddouble" ],
  458. [ 'ogc:Function_Name', ['nArgs'=>"1"], "interiorPoint" ],
  459. [ 'ogc:Function_Name', ['nArgs'=>"2"], "interiorRingN" ],
  460. [ 'ogc:Function_Name', ['nArgs'=>"3"], "Interpolate" ],
  461. [ 'ogc:Function_Name', ['nArgs'=>"2"], "intersection" ],
  462. [ 'ogc:Function_Name', ['nArgs'=>"7"], "IntersectionFeatureCollection" ],
  463. [ 'ogc:Function_Name', ['nArgs'=>"2"], "intersects" ],
  464. [ 'ogc:Function_Name', ['nArgs'=>"2"], "intersects3D" ],
  465. [ 'ogc:Function_Name', ['nArgs'=>"1"], "isClosed" ],
  466. [ 'ogc:Function_Name', ['nArgs'=>"0"], "isCoverage" ],
  467. [ 'ogc:Function_Name', ['nArgs'=>"1"], "isEmpty" ],
  468. [ 'ogc:Function_Name', ['nArgs'=>"2"], "isLike" ],
  469. [ 'ogc:Function_Name', ['nArgs'=>"1"], "isNull" ],
  470. [ 'ogc:Function_Name', ['nArgs'=>"2"], "isometric" ],
  471. [ 'ogc:Function_Name', ['nArgs'=>"1"], "isRing" ],
  472. [ 'ogc:Function_Name', ['nArgs'=>"1"], "isSimple" ],
  473. [ 'ogc:Function_Name', ['nArgs'=>"1"], "isValid" ],
  474. [ 'ogc:Function_Name', ['nArgs'=>"3"], "isWithinDistance" ],
  475. [ 'ogc:Function_Name', ['nArgs'=>"3"], "isWithinDistance3D" ],
  476. [ 'ogc:Function_Name', ['nArgs'=>"2"], "Jenks" ],
  477. [ 'ogc:Function_Name', ['nArgs'=>"1"], "length" ],
  478. [ 'ogc:Function_Name', ['nArgs'=>"2"], "lessEqualThan" ],
  479. [ 'ogc:Function_Name', ['nArgs'=>"2"], "lessThan" ],
  480. [ 'ogc:Function_Name', ['nArgs'=>"1"], "list" ],
  481. [ 'ogc:Function_Name', ['nArgs'=>"1"], "log" ],
  482. [ 'ogc:Function_Name', ['nArgs'=>"4"], "LRSGeocode" ],
  483. [ 'ogc:Function_Name', ['nArgs'=>"5"], "LRSMeasure" ],
  484. [ 'ogc:Function_Name', ['nArgs'=>"5"], "LRSSegment" ],
  485. [ 'ogc:Function_Name', ['nArgs'=>"2"], "max" ],
  486. [ 'ogc:Function_Name', ['nArgs'=>"2"], "max_2" ],
  487. [ 'ogc:Function_Name', ['nArgs'=>"2"], "max_3" ],
  488. [ 'ogc:Function_Name', ['nArgs'=>"2"], "max_4" ],
  489. [ 'ogc:Function_Name', ['nArgs'=>"2"], "min" ],
  490. [ 'ogc:Function_Name', ['nArgs'=>"2"], "min_2" ],
  491. [ 'ogc:Function_Name', ['nArgs'=>"2"], "min_3" ],
  492. [ 'ogc:Function_Name', ['nArgs'=>"2"], "min_4" ],
  493. [ 'ogc:Function_Name', ['nArgs'=>"1"], "mincircle" ],
  494. [ 'ogc:Function_Name', ['nArgs'=>"1"], "minimumdiameter" ],
  495. [ 'ogc:Function_Name', ['nArgs'=>"1"], "minrectangle" ],
  496. [ 'ogc:Function_Name', ['nArgs'=>"2"], "modulo" ],
  497. [ 'ogc:Function_Name', ['nArgs'=>"2"], "MultiplyCoverages" ],
  498. [ 'ogc:Function_Name', ['nArgs'=>"3"], "Nearest" ],
  499. [ 'ogc:Function_Name', ['nArgs'=>"1"], "not" ],
  500. [ 'ogc:Function_Name', ['nArgs'=>"2"], "notEqualTo" ],
  501. [ 'ogc:Function_Name', ['nArgs'=>"2"], "numberFormat" ],
  502. [ 'ogc:Function_Name', ['nArgs'=>"5"], "numberFormat2" ],
  503. [ 'ogc:Function_Name', ['nArgs'=>"1"], "numGeometries" ],
  504. [ 'ogc:Function_Name', ['nArgs'=>"1"], "numInteriorRing" ],
  505. [ 'ogc:Function_Name', ['nArgs'=>"1"], "numPoints" ],
  506. [ 'ogc:Function_Name', ['nArgs'=>"1"], "octagonalenvelope" ],
  507. [ 'ogc:Function_Name', ['nArgs'=>"3"], "offset" ],
  508. [ 'ogc:Function_Name', ['nArgs'=>"2"], "overlaps" ],
  509. [ 'ogc:Function_Name', ['nArgs'=>"1"], "parameter" ],
  510. [ 'ogc:Function_Name', ['nArgs'=>"1"], "parseBoolean" ],
  511. [ 'ogc:Function_Name', ['nArgs'=>"1"], "parseDouble" ],
  512. [ 'ogc:Function_Name', ['nArgs'=>"1"], "parseInt" ],
  513. [ 'ogc:Function_Name', ['nArgs'=>"1"], "parseLong" ],
  514. [ 'ogc:Function_Name', ['nArgs'=>"0"], "pi" ],
  515. [ 'ogc:Function_Name', ['nArgs'=>"4"], "PointBuffers" ],
  516. [ 'ogc:Function_Name', ['nArgs'=>"2"], "pointN" ],
  517. [ 'ogc:Function_Name', ['nArgs'=>"7"], "PointStacker" ],
  518. [ 'ogc:Function_Name', ['nArgs'=>"6"], "PolygonExtraction" ],
  519. [ 'ogc:Function_Name', ['nArgs'=>"2"], "pow" ],
  520. [ 'ogc:Function_Name', ['nArgs'=>"1"], "property" ],
  521. [ 'ogc:Function_Name', ['nArgs'=>"1"], "PropertyExists" ],
  522. [ 'ogc:Function_Name', ['nArgs'=>"2"], "Quantile" ],
  523. [ 'ogc:Function_Name', ['nArgs'=>"3"], "Query" ],
  524. [ 'ogc:Function_Name', ['nArgs'=>"0"], "random" ],
  525. [ 'ogc:Function_Name', ['nArgs'=>"5"], "RangeLookup" ],
  526. [ 'ogc:Function_Name', ['nArgs'=>"1"], "RasterAsPointCollection" ],
  527. [ 'ogc:Function_Name', ['nArgs'=>"4"], "RasterZonalStatistics" ],
  528. [ 'ogc:Function_Name', ['nArgs'=>"5"], "Recode" ],
  529. [ 'ogc:Function_Name', ['nArgs'=>"2"], "RectangularClip" ],
  530. [ 'ogc:Function_Name', ['nArgs'=>"2"], "relate" ],
  531. [ 'ogc:Function_Name', ['nArgs'=>"3"], "relatePattern" ],
  532. [ 'ogc:Function_Name', ['nArgs'=>"3"], "Reproject" ],
  533. [ 'ogc:Function_Name', ['nArgs'=>"1"], "rint" ],
  534. [ 'ogc:Function_Name', ['nArgs'=>"1"], "round" ],
  535. [ 'ogc:Function_Name', ['nArgs'=>"1"], "round_2" ],
  536. [ 'ogc:Function_Name', ['nArgs'=>"1"], "roundDouble" ],
  537. [ 'ogc:Function_Name', ['nArgs'=>"6"], "ScaleCoverage" ],
  538. [ 'ogc:Function_Name', ['nArgs'=>"4"], "sdo_nn" ],
  539. [ 'ogc:Function_Name', ['nArgs'=>"2"], "setCRS" ],
  540. [ 'ogc:Function_Name', ['nArgs'=>"3"], "Simplify" ],
  541. [ 'ogc:Function_Name', ['nArgs'=>"1"], "sin" ],
  542. [ 'ogc:Function_Name', ['nArgs'=>"3"], "Snap" ],
  543. [ 'ogc:Function_Name', ['nArgs'=>"1"], "sqrt" ],
  544. [ 'ogc:Function_Name', ['nArgs'=>"2"], "StandardDeviation" ],
  545. [ 'ogc:Function_Name', ['nArgs'=>"1"], "startAngle" ],
  546. [ 'ogc:Function_Name', ['nArgs'=>"1"], "startPoint" ],
  547. [ 'ogc:Function_Name', ['nArgs'=>"1"], "strCapitalize" ],
  548. [ 'ogc:Function_Name', ['nArgs'=>"2"], "strConcat" ],
  549. [ 'ogc:Function_Name', ['nArgs'=>"2"], "strEndsWith" ],
  550. [ 'ogc:Function_Name', ['nArgs'=>"2"], "strEqualsIgnoreCase" ],
  551. [ 'ogc:Function_Name', ['nArgs'=>"2"], "strIndexOf" ],
  552. [ 'ogc:Function_Name', ['nArgs'=>"2"], "strLastIndexOf" ],
  553. [ 'ogc:Function_Name', ['nArgs'=>"1"], "strLength" ],
  554. [ 'ogc:Function_Name', ['nArgs'=>"2"], "strMatches" ],
  555. [ 'ogc:Function_Name', ['nArgs'=>"3"], "strPosition" ],
  556. [ 'ogc:Function_Name', ['nArgs'=>"4"], "strReplace" ],
  557. [ 'ogc:Function_Name', ['nArgs'=>"2"], "strStartsWith" ],
  558. [ 'ogc:Function_Name', ['nArgs'=>"3"], "strSubstring" ],
  559. [ 'ogc:Function_Name', ['nArgs'=>"2"], "strSubstringStart" ],
  560. [ 'ogc:Function_Name', ['nArgs'=>"1"], "strToLowerCase" ],
  561. [ 'ogc:Function_Name', ['nArgs'=>"1"], "strToUpperCase" ],
  562. [ 'ogc:Function_Name', ['nArgs'=>"1"], "strTrim" ],
  563. [ 'ogc:Function_Name', ['nArgs'=>"3"], "strTrim2" ],
  564. [ 'ogc:Function_Name', ['nArgs'=>"2"], "StyleCoverage" ],
  565. [ 'ogc:Function_Name', ['nArgs'=>"2"], "symDifference" ],
  566. [ 'ogc:Function_Name', ['nArgs'=>"1"], "tan" ],
  567. [ 'ogc:Function_Name', ['nArgs'=>"1"], "toDegrees" ],
  568. [ 'ogc:Function_Name', ['nArgs'=>"1"], "toRadians" ],
  569. [ 'ogc:Function_Name', ['nArgs'=>"2"], "touches" ],
  570. [ 'ogc:Function_Name', ['nArgs'=>"1"], "toWKT" ],
  571. [ 'ogc:Function_Name', ['nArgs'=>"2"], "Transform" ],
  572. [ 'ogc:Function_Name', ['nArgs'=>"2"], "union" ],
  573. [ 'ogc:Function_Name', ['nArgs'=>"2"], "UnionFeatureCollection" ],
  574. [ 'ogc:Function_Name', ['nArgs'=>"2"], "Unique" ],
  575. [ 'ogc:Function_Name', ['nArgs'=>"2"], "UniqueInterval" ],
  576. [ 'ogc:Function_Name', ['nArgs'=>"6"], "VectorToRaster" ],
  577. [ 'ogc:Function_Name', ['nArgs'=>"3"], "VectorZonalStatistics" ],
  578. [ 'ogc:Function_Name', ['nArgs'=>"1"], "vertices" ],
  579. [ 'ogc:Function_Name', ['nArgs'=>"2"], "within" ],
  580. ] ],
  581. ] ],
  582. ] ],
  583. ] ],
  584. ]);
  585. $xmlWriter->endElement();// WFS_Capabilities
  586. $xmlWriter->endDocument();
  587. exit;
  588. }
  589. public function _getXmlSchemaLocation() {
  590. $schemaLocations = array();
  591. //$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
  592. return (!empty($schemaLocations))? 'xsi:schemaLocation="' . implode(' ', $schemaLocations) . '"' : '';
  593. }
  594. public function _printXmlNamespaceList() {
  595. $listNs = array();
  596. foreach (Api_WfsNs::getNsList() as $uri => $prefix) {
  597. $listNs[] = 'xmlns:' . $prefix . '="' . $uri . '"';
  598. }
  599. return implode("\n", $listNs);
  600. }
  601. public function _getSourceNsList() {
  602. $usrObjList = array();
  603. $tblsAcl = $this->_usrAcl->getTablesAcl();
  604. foreach ($tblsAcl as $tblAcl) {
  605. $dataSourceName = 'default_db';// TODO: getSourceName
  606. $tblName = $tblAcl->getName();
  607. $usrObjList[] = array($dataSourceName, $tblName);
  608. }
  609. $usrObjList[] = array('objects', 'File');
  610. $usrObjList[] = array('objects', 'TestPerms');
  611. $usrObjList[] = array('objects', 'Korespondencja');
  612. return $usrObjList;
  613. }
  614. public function _parseTransactionXmlStruct($requestXml, $requestXmlTags) {
  615. $DBG = V::get('DBG_XML', 0, $_GET, 'int');// TODO: Profiler
  616. $rootTagName = V::get('tag', '', $requestXmlTags[0]);
  617. if ('Transaction' != $rootTagName) throw new Api_WfsException("Parse Request XML Error - Missing Transaction as root xml tag", __LINE__, null, 'TransactionParseError', 'request');
  618. // TODO: special actions if action on nested objects
  619. // 1. convert request: wfs.transaction.convert-wfs-request.xsl
  620. // 2. validate converted request: wfs.transaction-converted-request.xsd
  621. // 3. execute request in data source
  622. // if($DBG){echo 'L.' . __LINE__ . ' $requestXmlTags:';print_r($requestXmlTags);echo "\n";}
  623. /*
  624. <Transaction
  625. xmlns="http://www.opengis.net/wfs"
  626. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  627. version="1.0.0"
  628. service="WFS"
  629. xmlns:p5_objects="https://biuro.biall-net.pl/wfs/objects"
  630. xmlns:gml="http://www.opengis.net/gml">
  631. <Insert xmlns="http://www.opengis.net/wfs">
  632. <TestPerms xmlns="https://biuro.biall-net.pl/wfs/objects">
  633. <plik xmlns="https://biuro.biall-net.pl/wfs/objects">
  634. <p5_objects:File>
  635. <p5_objects:name>blank-wfs.gif</p5_objects:name>
  636. <p5_objects:content>R0lGODlhAQABAIAAAP///////yH+EUNyZWF0ZWQgd2l0aCBHSU1QACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==</p5_objects:content>
  637. </p5_objects:File>
  638. </plik>
  639. </TestPerms>
  640. </Insert>
  641. </Transaction>
  642. */
  643. $actionXmlTags = array();// // [ 0 => [ 'action'=>Insert, 'typeName'=>str, 'tags'=>[] ]
  644. {// split xml for action tags (Insert, Update, Delete)
  645. $tagsCount = count($requestXmlTags);
  646. for ($i = 1, $actionTagName = null, $actionIdx = -1, $tagLvl = 0; $i < $tagsCount - 1; $i++) {// skip Transaction open/close tag
  647. $tag = $requestXmlTags[$i];
  648. if (null == $actionTagName) {
  649. $actionTagName = $tag['tag'];
  650. $tagLvl = $tag['level'];
  651. $actionIdx += 1;
  652. $actionXmlTags[$actionIdx] = array();
  653. $actionXmlTags[$actionIdx]['action'] = $actionTagName;
  654. $actionXmlTags[$actionIdx]['typeName'] = V::get('typeName', '', $tag['attributes']);
  655. $actionXmlTags[$actionIdx]['isDeepObject'] = null;// null - unknown, false - not seed, true - deep
  656. $actionXmlTags[$actionIdx]['tags'] = array();
  657. } else if ($tag['tag'] == $actionTagName && 'close' == $tag['type'] && $tagLvl == $tag['level']) {
  658. $actionTagName = null;
  659. } else {
  660. $actionXmlTags[$actionIdx]['tags'][] = $tag;
  661. }
  662. }
  663. }
  664. {// Validate Request: WFS allow multiple tags inside Insert tag
  665. // TODO: implement multiple tags in Insert tag if reauired. Use array_splice($actionXmlTags, $actionIdx, 0, $insertTags);
  666. {// throw (Not Implemented, 501) if found multiple tags in Insert tag
  667. foreach ($actionXmlTags as $actionIdx => $action) {
  668. if ('Insert' !== $action['action']) continue;
  669. $lvl = $action['tags'][0]['level'];
  670. for ($i = 1, $cnt = count($action['tags']); $i < $cnt - 1; $i++) {
  671. $tag = $action['tags'][$i];
  672. // if($DBG){echo 'L.' . __LINE__ . " actionXmlTags loop({$i}) \$tag:";print_r($tag);echo "\n";}
  673. if ($tag['level'] == $lvl) throw new Exception("Error Processing Request - multiple tags inside Insert tag is not implemented", 501);
  674. }
  675. }
  676. }
  677. }
  678. {// Insert tag - fix typeName from first tag, remove first and last tag - leave only fields
  679. foreach ($actionXmlTags as $actionIdx => $action) {
  680. if ('Insert' !== $action['action']) continue;
  681. array_pop($action['tags']);// remove last tag (close tag)
  682. $tag = array_shift($action['tags']);// remove last tag (close tag)
  683. $typeName = $tag['tag'];// eg. with prefix 'p5_objects:File' or without prefix but with @xmlns
  684. if (false === strpos($typeName, ':')) {
  685. $nsType = V::get('xmlns', '', $tag['attributes']);
  686. if (!$nsType) throw new Exception("Error Processing Request - Missing object namespace '{$tag['tag']}'");
  687. $prefix = Api_WfsNs::getNsPrefix($nsType);
  688. if (!$prefix) {
  689. if ($typeName == substr(rtrim($nsType, '/'), -1 * strlen($typeName))) {// typeName may be added to ns uri
  690. $nsBaseForType = substr(rtrim($nsType, '/'), 0, -1 * strlen($typeName) - 1);
  691. $prefix = Api_WfsNs::getNsPrefix($nsBaseForType);
  692. }
  693. }
  694. if (!$prefix) throw new Exception("Error Processing Request - Unrecognized namespace uri '{$nsType}' for object '{$tag['tag']}'");
  695. $typeName = "{$prefix}:{$typeName}";
  696. }
  697. $action['typeName'] = $typeName;
  698. $actionXmlTags[$actionIdx] = $action;
  699. }
  700. }
  701. {// validate
  702. // if($DBG){echo 'L.' . __LINE__ . ' before validate $actionXmlTags:';print_r($actionXmlTags);echo "\n";}
  703. foreach ($actionXmlTags as $actionIdx => $action) {
  704. if ('Insert' == $action['action']) {
  705. if (empty($action['typeName'])) throw new Exception("Error Processing Request - unknown object typeName to Insert");
  706. $acl = $this->getAclFromTypeName($action['typeName']);
  707. $actionXmlTags[$actionIdx] = $acl->validateInsertXml($action);
  708. } else if ('Update' == $action['action']) {
  709. $acl = $this->getAclFromTypeName($action['typeName']);
  710. $actionXmlTags[$actionIdx] = $acl->validateUpdateXml($action);
  711. } else if ('Delete' == $action['action']) {
  712. if($DBG>1){echo'<pre>$action: ';print_r($action);echo'</pre>';}
  713. $acl = $this->getAclFromTypeName($action['typeName']);
  714. $actionXmlTags[$actionIdx] = $acl->validateDeleteXml($action);
  715. } else {
  716. if($DBG>1){echo'<pre>$action: ';print_r($action);echo'</pre>';}
  717. throw new Exception("{$action['action']} action not implemented", 501);
  718. }
  719. // continue;// TODO: validate all by type
  720. }
  721. }
  722. if ('1' == V::get('DBG_DONT_CHANGE_DB', '', $_REQUEST)) {
  723. echo "----------------- action xml tags: ---------------" . "\n";
  724. print_r($actionXmlTags);
  725. die(".EOF\n");
  726. }
  727. {// execute
  728. $returnIds = array();
  729. $changesList = array();
  730. foreach ($actionXmlTags as $actionIdx => $action) {
  731. if ('Insert' == $action['action']) {
  732. if (empty($action['typeName'])) throw new Exception("Error Processing Request - unknown object typeName to Insert");
  733. $acl = $this->getAclFromTypeName($action['typeName']);
  734. $newId = $acl->insertXml($action);
  735. $returnIds[$actionIdx] = $newId;
  736. $changesList[$actionIdx] = array('Status'=>(($newId > 0)? 'SUCCESS' : 'FAILED'), 'Message'=>"created {$newId}.", 'Action' => $action['action']);
  737. if ($newId > 0) $changesList[$actionIdx]['fid'] = $acl->getName() . '.' . $newId;
  738. } else if ('Update' == $action['action']) {
  739. if($DBG>1){echo'<pre>$action: ';print_r($action);echo'</pre>';}
  740. $acl = $this->getAclFromTypeName($action['typeName']);
  741. $affected = $acl->updateXml($action);
  742. $changesList[$actionIdx] = array('Status'=>(($affected >= 0)? 'SUCCESS' : 'FAILED'), 'Message'=>"affected {$affected}.", 'Action' => $action['action']);
  743. } else if ('Delete' == $action['action']) {
  744. $acl = $this->getAclFromTypeName($action['typeName']);
  745. $affected = $acl->deleteXml($action);
  746. $changesList[$actionIdx] = array('Status'=>(($affected >= 0)? 'SUCCESS' : 'FAILED'), 'Message'=>"deleted {$affected}.", 'Action' => $action['action']);
  747. } else throw new Exception("TODO: {$action['action']} action not implemented", 501);
  748. }
  749. if($DBG){echo 'L.' . __LINE__ . ' $changesList:';print_r($changesList);echo "\n";}
  750. }
  751. return $this->_transactionResponse($changesList);
  752. }
  753. public function _transactionResponse($changesList) {
  754. // <WFS_TransactionResponse>
  755. // <TransactionResult>
  756. // <Status> : SUCCESS / FAILED / PARTIAL
  757. // [<Locator]
  758. // [<Message]
  759. $messageTag = '';
  760. $statusTag = '';
  761. $statusIsFailed = false;
  762. $statusAll = null;
  763. $createdFeatureId = array();
  764. foreach ($changesList as $featureId => $change) {
  765. if ('FAILED' == $change['Status']) {
  766. $statusIsFailed = true;
  767. }
  768. if ('SUCCESS' == $change['Status'] && !empty($change['fid'])) {
  769. $createdFeatureId[] = $change['fid'];
  770. }
  771. // if (!empty($change['Message'])) $messageTag .= "Feature '{$featureId}' {$change['Status']}: {$change['Message']}\n";
  772. }
  773. $statusTag = ($statusIsFailed)? 'FAILED' : 'SUCCESS';
  774. $statusTag = "<wfs:{$statusTag}/>";
  775. $messageTag = '';//"<wfs:Message>{$messageTag}</wfs:Message>";
  776. /* Example:
  777. <?xml version="1.0" encoding="UTF-8"?>
  778. <wfs:WFS_TransactionResponse version="1.0.0" xmlns:wfs="http://www.opengis.net/wfs"
  779. xmlns:ogc="http://www.opengis.net/ogc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  780. xsi:schemaLocation="http://www.opengis.net/wfs http://localhost:8080/geoserver/schemas/wfs/1.0.0/WFS-transaction.xsd">
  781. <wfs:InsertResult>
  782. <ogc:FeatureId fid="archsites.26" />
  783. </wfs:InsertResult>
  784. <wfs:TransactionResult handle="Updating Signature rock label">
  785. <wfs:Status>
  786. <wfs:SUCCESS />
  787. </wfs:Status>
  788. </wfs:TransactionResult>
  789. </wfs:WFS_TransactionResponse>*/
  790. // TODO: build xml by DOMDocument
  791. // TODO: xsi:schemaLocation="http://www.opengis.net/wfs http://localhost:8080/geoserver/schemas/wfs/1.0.0/WFS-transaction.xsd"
  792. $wfsInsertResult = '';
  793. if (!empty($createdFeatureId)) {
  794. $wfsInsertResult = "\n<wfs:InsertResult>\n";
  795. foreach ($createdFeatureId as $fid) {
  796. $wfsInsertResult .= '<ogc:FeatureId fid="' . $fid . '" xmlns:ogc="http://www.opengis.net/ogc"/>' . "\n";
  797. }
  798. $wfsInsertResult .= "\n</wfs:InsertResult>\n";
  799. EOF;
  800. }
  801. $tranRes = <<<EOF
  802. <wfs:WFS_TransactionResponse version="1.0.0"
  803. xmlns:wfs="http://www.opengis.net/wfs"
  804. xmlns:ogc="http://www.opengis.net/ogc"
  805. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  806. {$wfsInsertResult}
  807. <wfs:TransactionResult>
  808. <wfs:Status>{$statusTag}</wfs:Status>
  809. {$messageTag}
  810. </wfs:TransactionResult>
  811. </wfs:WFS_TransactionResponse>
  812. EOF;
  813. return $tranRes;
  814. }
  815. public function _convertTransactionXml($requestXmlString, $sourceNsList) {
  816. $DBG = (V::get('DBG_XSL', '', $_GET) > 0);// TODO: Profiler
  817. if($DBG){echo 'L.' . __LINE__ . ' sourceNsList:';print_r($sourceNsList);echo "\n";}
  818. $updateActionsXsd = array();
  819. $insertActionsXsd = array();
  820. $deleteActionsXsd = array();
  821. //<!-- TODO: create tag Update{X} where X is namespace index -->
  822. foreach ($sourceNsList as $nsInd => $sourceNs) {
  823. // <Update>
  824. $theGeomField = 'the_geom';// TODO: get from fields list
  825. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  826. if($DBG){echo 'L.' . __LINE__ . ' typeName:';print_r($typeName);echo "\n";}
  827. $updateElementName = "UpdateNs{$nsInd}";
  828. $geomCoordsUpdateXpath = "//wfs:Value/*/gml:outerBoundaryIs/gml:LinearRing/gml:coordinates";
  829. $geomCoordsInsertXpath = "//*/gml:outerBoundaryIs/gml:LinearRing/gml:coordinates";
  830. $acl = $this->getAclFromTypeName($typeName);
  831. $geomType = $acl->getGeomFieldType($theGeomField);
  832. if ('polygon' == $geomType) {
  833. $geomCoordsUpdateXpath = ".//wfs:Value/*/gml:outerBoundaryIs/gml:LinearRing/gml:coordinates";
  834. $geomCoordsUpdateXpath = "((<xsl:value-of select=\"{$geomCoordsUpdateXpath}\"/>))";
  835. $geomCoordsInsertXpath = ".//*/gml:outerBoundaryIs/gml:LinearRing/gml:coordinates";
  836. $geomCoordsInsertXpath = "((<xsl:value-of select=\"{$geomCoordsInsertXpath}\"/>))";
  837. } else if ('linestring' == $geomType) {
  838. $geomCoordsUpdateXpath = ".//wfs:Value/*/gml:coordinates";
  839. $geomCoordsUpdateXpath = "(<xsl:value-of select=\"{$geomCoordsUpdateXpath}\"/>)";
  840. $geomCoordsInsertXpath = ".//*/gml:coordinates";
  841. $geomCoordsInsertXpath = "(<xsl:value-of select=\"{$geomCoordsInsertXpath}\"/>)";
  842. } else if ('point' == $geomType) {
  843. $geomCoordsUpdateXpath = ".//wfs:Value/*/gml:coordinates";
  844. $geomCoordsUpdateXpath = "(<xsl:value-of select=\"{$geomCoordsUpdateXpath}\"/>)";
  845. $geomCoordsInsertXpath = ".//*/gml:coordinates";
  846. $geomCoordsInsertXpath = "(<xsl:value-of select=\"{$geomCoordsInsertXpath}\"/>)";
  847. }
  848. $actionXsd = <<<EOF
  849. <xsl:when test="@typeName = '{$typeName}'">
  850. <xsl:element name="{$updateElementName}">
  851. <xsl:attribute name="typeName"><xsl:value-of select="@typeName" /></xsl:attribute>
  852. <xsl:attribute name="featureId"><xsl:value-of select="ogc:Filter/ogc:FeatureId/@fid" /></xsl:attribute>
  853. <xsl:for-each select="wfs:Property">
  854. <xsl:element name="{wfs:Name}">
  855. <xsl:choose>
  856. <xsl:when test="wfs:Name = '{$theGeomField}'"><xsl:value-of select="local-name(//wfs:Value/*[1])"/>{$geomCoordsUpdateXpath}</xsl:when>
  857. <xsl:otherwise><xsl:value-of select="wfs:Value"/></xsl:otherwise>
  858. </xsl:choose>
  859. </xsl:element>
  860. </xsl:for-each>
  861. </xsl:element>
  862. </xsl:when>
  863. EOF;
  864. $updateActionsXsd[] = $actionXsd;
  865. $typeName = "{$sourceNs[1]}";//"p5_{$sourceNs[0]}:{$sourceNs[1]}";
  866. $insertElementName = "InsertNs{$nsInd}";
  867. $actionXsd = <<<EOF
  868. <xsl:when test="local-name() = '{$typeName}'">
  869. <xsl:element name="{$insertElementName}">
  870. <xsl:attribute name="typeName"><xsl:value-of select="local-name()" /></xsl:attribute>
  871. <xsl:attribute name="typeNsUri"><xsl:value-of select="namespace-uri()" /></xsl:attribute>
  872. <xsl:for-each select="*">
  873. <xsl:element name="{local-name()}">
  874. <xsl:choose>
  875. <xsl:when test="local-name() = '{$theGeomField}'"><xsl:value-of select="local-name(*[1])"/>{$geomCoordsInsertXpath}</xsl:when>
  876. <xsl:otherwise><xsl:value-of select="."/></xsl:otherwise>
  877. </xsl:choose>
  878. </xsl:element>
  879. </xsl:for-each>
  880. </xsl:element>
  881. </xsl:when>
  882. EOF;
  883. $insertActionsXsd[] = $actionXsd;
  884. $deleteElementName = "DeleteNs{$nsInd}";
  885. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  886. $actionXsd = <<<EOF
  887. <xsl:when test="@typeName = '{$typeName}'">
  888. <xsl:variable name="typeName" select="@typeName" />
  889. <xsl:for-each select="ogc:Filter/ogc:FeatureId">
  890. <xsl:element name="{$deleteElementName}">
  891. <xsl:attribute name="typeName"><xsl:value-of select="\$typeName" /></xsl:attribute>
  892. <xsl:attribute name="featureId"><xsl:value-of select="@fid" /></xsl:attribute>
  893. </xsl:element>
  894. </xsl:for-each>
  895. </xsl:when>
  896. EOF;
  897. $deleteActionsXsd[] = $actionXsd;
  898. }
  899. if (!empty($updateActionsXsd)) {
  900. $updateActionsXsd = implode("\n", $updateActionsXsd);
  901. $updateActionsXsd = <<<EOF
  902. <xsl:choose>
  903. {$updateActionsXsd}
  904. </xsl:choose>
  905. EOF;
  906. } else {
  907. $updateActionsXsd = '';
  908. }
  909. if (!empty($insertActionsXsd)) {
  910. $insertActionsXsd = implode("\n", $insertActionsXsd);
  911. $insertActionsXsd = <<<EOF
  912. <xsl:choose>
  913. {$insertActionsXsd}
  914. </xsl:choose>
  915. EOF;
  916. } else {
  917. $insertActionsXsd = '';
  918. }
  919. if (!empty($deleteActionsXsd)) {
  920. $deleteActionsXsd = implode("\n", $deleteActionsXsd);
  921. $deleteActionsXsd = <<<EOF
  922. <xsl:choose>
  923. {$deleteActionsXsd}
  924. </xsl:choose>
  925. EOF;
  926. } else {
  927. $deleteActionsXsd = '';
  928. }
  929. $convertTransactionXslString = '<?xml version="1.0"?>';
  930. $convertTransactionXslString .= <<<EOF
  931. <xsl:transform version="1.0"
  932. xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  933. xmlns:wfs="http://www.opengis.net/wfs"
  934. xmlns:ogc="http://www.opengis.net/ogc"
  935. xmlns:gml="http://www.opengis.net/gml">
  936. <xsl:template match="/">
  937. <xsl:for-each select="wfs:Transaction">
  938. <Transaction>
  939. <xsl:attribute name="version"><xsl:value-of select="@version" /></xsl:attribute>
  940. <xsl:attribute name="service"><xsl:value-of select="@service" /></xsl:attribute>
  941. <xsl:for-each select="wfs:Update">
  942. {$updateActionsXsd}
  943. </xsl:for-each>
  944. <xsl:for-each select="wfs:Insert/*">
  945. {$insertActionsXsd}
  946. </xsl:for-each>
  947. <xsl:for-each select="wfs:Delete">
  948. {$deleteActionsXsd}
  949. </xsl:for-each>
  950. <!-- TODO: Native -->
  951. </Transaction>
  952. </xsl:for-each>
  953. </xsl:template>
  954. </xsl:transform>
  955. EOF;
  956. if($DBG){echo 'L.' . __LINE__ . ' $convertTransactionXslString:' . $convertTransactionXslString . "\n";}
  957. $requestXml = new DOMDocument();
  958. $requestXml->loadXml($requestXmlString);
  959. $convertTransactionXsl = new DOMDocument();
  960. $convertTransactionXsl->loadXml($convertTransactionXslString);
  961. $proc = new XSLTProcessor();
  962. $proc->importStylesheet($convertTransactionXsl);
  963. return $proc->transformToXML($requestXml);
  964. }
  965. public function _validateConvertedTransactionXml($convertedTransaction, $sourceNsList) {
  966. $DBG = (V::get('DBG_XSD', '', $_GET) > 0);// TODO: Profiler
  967. if($DBG){echo 'L.' . __LINE__ . ' sourceNsList:';print_r($sourceNsList);echo "\n";}
  968. $dom = new DOMDocument('1.0', 'utf-8');
  969. $dom->formatOutput = true;
  970. $dom->preserveWhiteSpace = false;
  971. $rootNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:schema');
  972. $dom->appendChild($rootNode);
  973. $rootNode->setAttribute('elementFormDefault', 'qualified');
  974. $rootNode->setAttribute('version', '1.0');
  975. {// <xsd:element name="Transaction" type="TransactionType">
  976. $elNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  977. $rootNode->appendChild($elNode);
  978. $elNode->setAttribute('name', 'Transaction');
  979. $elNode->setAttribute('type', 'TransactionType');
  980. $cTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:complexType');
  981. $rootNode->appendChild($cTypeNode);
  982. $cTypeNode->setAttribute('name', 'TransactionType');
  983. $seqNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:sequence');
  984. $cTypeNode->appendChild($seqNode);
  985. $choiceNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:choice');
  986. $seqNode->appendChild($choiceNode);
  987. $choiceNode->setAttribute('minOccurs', '0');
  988. $choiceNode->setAttribute('maxOccurs', 'unbounded');
  989. // <!-- <xsd:element ref="Update"/> -->
  990. foreach ($sourceNsList as $nsInd => $sourceNs) {
  991. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  992. $updateElementName = "UpdateNs{$nsInd}";
  993. $updateElementType = "UpdateNs{$nsInd}ElementType";
  994. $updateElemNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  995. $choiceNode->appendChild($updateElemNode);
  996. $updateElemNode->setAttribute('name', $updateElementName);
  997. $updateElemNode->setAttribute('type', $updateElementType);
  998. }
  999. // <!-- <xsd:element ref="Insert"/> -->
  1000. foreach ($sourceNsList as $nsInd => $sourceNs) {
  1001. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  1002. $insertElementName = "InsertNs{$nsInd}";
  1003. $insertElementType = "InsertNs{$nsInd}ElementType";
  1004. $insertElemNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  1005. $choiceNode->appendChild($insertElemNode);
  1006. $insertElemNode->setAttribute('name', $insertElementName);
  1007. $insertElemNode->setAttribute('type', $insertElementType);
  1008. }
  1009. // <!-- <xsd:element ref="Delete"/> -->
  1010. foreach ($sourceNsList as $nsInd => $sourceNs) {
  1011. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  1012. $deleteElementName = "DeleteNs{$nsInd}";
  1013. $deleteElementType = "DeleteNs{$nsInd}ElementType";
  1014. $deleteElemNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  1015. $choiceNode->appendChild($deleteElemNode);
  1016. $deleteElemNode->setAttribute('name', $deleteElementName);
  1017. $deleteElemNode->setAttribute('type', $deleteElementType);
  1018. }
  1019. // <!-- <xsd:element ref="Native"/> -->
  1020. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  1021. $cTypeNode->appendChild($attrNode);
  1022. $attrNode->setAttribute('name', 'version');
  1023. $attrNode->setAttribute('type', 'xsd:string');
  1024. $attrNode->setAttribute('use', 'required');
  1025. $attrNode->setAttribute('fixed', '1.0.0');
  1026. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  1027. $cTypeNode->appendChild($attrNode);
  1028. $attrNode->setAttribute('name', 'service');
  1029. $attrNode->setAttribute('type', 'xsd:string');
  1030. $attrNode->setAttribute('use', 'required');
  1031. $attrNode->setAttribute('fixed', 'WFS');
  1032. }
  1033. foreach ($sourceNsList as $nsInd => $sourceNs) {
  1034. $transactionTypesList = array();
  1035. $transactionTypesList[] = 'Update';
  1036. $transactionTypesList[] = 'Insert';
  1037. foreach ($transactionTypesList as $transactionType) {
  1038. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  1039. if($DBG){echo 'L.' . __LINE__ . ' TODO: get acl typeName:';print_r($typeName);echo "\n";}
  1040. $acl = $this->getAclFromTypeName($typeName);
  1041. $updateElementName = "{$transactionType}Ns{$nsInd}";
  1042. $updateElementType = "{$transactionType}Ns{$nsInd}ElementType";
  1043. /*
  1044. <xsd:complexType name="{$updateElementType}">
  1045. <xsd:sequence>
  1046. <xsd:element name="PARENT_ID" minOccurs="0" maxOccurs="1" type="xsd:integer" />
  1047. </xsd:sequence>
  1048. */
  1049. $updateTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:complexType');
  1050. $rootNode->appendChild($updateTypeNode);
  1051. $updateTypeNode->setAttribute('name', $updateElementType);
  1052. {
  1053. $seqNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:all');
  1054. $updateTypeNode->appendChild($seqNode);
  1055. {
  1056. $pKeyField = $acl->getPrimaryKeyField();
  1057. $fldList = $this->_getFieldListFromAcl($acl);
  1058. // fields without geometry fields
  1059. foreach ($fldList as $fldName) {
  1060. if ($acl->isGeomField($fldName)) continue;
  1061. $elNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  1062. $seqNode->appendChild($elNode);
  1063. $elNode->setAttribute('name', $fldName);
  1064. $minOccurs = 0;
  1065. if ($pKeyField == $fldName) {
  1066. $minOccurs = '1';
  1067. } else {
  1068. $minOccurs = '0';
  1069. }
  1070. $elNode->setAttribute('minOccurs', $minOccurs);
  1071. $fldType = null;
  1072. if ($acl->isIntegerField($fldName)) {
  1073. $fldType = 'xsd:integer';
  1074. }
  1075. else if ($acl->isDecimalField($fldName)) {
  1076. $fldType = 'xsd:decimal';
  1077. }
  1078. else if ($acl->isDateField($fldName)) {
  1079. $fldType = 'xsd:date';
  1080. }
  1081. else if ($acl->isDateTimeField($fldName)) {
  1082. // $fldType = 'xsd:dateTime';
  1083. $fldType = null;// 'xsd:string';
  1084. $patternDataTime = "(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})(:(\d{2}))?";
  1085. // <xsd:element name="..." minOccurs="0" nillable="true">
  1086. // <xsd:simpleType>
  1087. // <xsd:restriction base="xsd:string">
  1088. // <xsd:pattern value="[a-zA-Z]+\(\((\-?\d+\.?\d*,\-?\d+\.?\d*)( \-?\d+\.?\d*,\-?\d+\.?\d*)+\)\)"/>
  1089. // </xsd:restriction>
  1090. // </xsd:simpleType>
  1091. // </xsd:element>
  1092. $simpleTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:simpleType');
  1093. $restrictionNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:restriction');
  1094. $patternNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:pattern');
  1095. $restrictionNode->setAttribute('base', 'xsd:string');
  1096. $patternNode->setAttribute('value', $patternDataTime);
  1097. $restrictionNode->appendChild($patternNode);
  1098. $simpleTypeNode->appendChild($restrictionNode);
  1099. $elNode->appendChild($simpleTypeNode);
  1100. // continue;// TODO: ? below added nillable = true, minOccurs = 0, type = $fldType
  1101. }
  1102. else if ($acl->isBinaryField($fldName)) {
  1103. $fldType = 'xsd:base64Binary';
  1104. }
  1105. else {
  1106. $fldType = 'xsd:string';
  1107. }
  1108. if ($fldType) $elNode->setAttribute('type', $fldType);
  1109. $elNode->setAttribute('nillable', 'true');
  1110. $elNode->setAttribute('minOccurs', '0');
  1111. }
  1112. // only geometry fields
  1113. foreach ($fldList as $fldName) {
  1114. if (!$acl->isGeomField($fldName)) continue;
  1115. $elNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:element');
  1116. $seqNode->appendChild($elNode);
  1117. $elNode->setAttribute('name', $fldName);
  1118. $minOccurs = 0;
  1119. if ($pKeyField == $fldName) {
  1120. $minOccurs = '1';
  1121. } else {
  1122. $minOccurs = '0';
  1123. }
  1124. $elNode->setAttribute('minOccurs', $minOccurs);
  1125. if ($acl->isGeomField($fldName)) {
  1126. //$fldType = 'gml:GeometryPropertyType';
  1127. // TODO: use geom types from gml to wkt
  1128. // TODO: pattern wg atrybutów gml:coordinates decimal="." cs="," ts=" "
  1129. $patternWkt = '';// TODO: error if empty - unsupported geom type
  1130. $patternNum = '\-?\d+\.?\d*';
  1131. $patternPoint = $patternNum . ',' . $patternNum;
  1132. $patternPoints = '(' . $patternPoint . ')( ' . $patternPoint . ')+';
  1133. $geomType = $acl->getGeomFieldType($fldName);
  1134. if ('polygon' == $geomType) {
  1135. // [a-zA-Z]+\(\((\-?\d+\.?\d*,\-?\d+\.?\d*)( (\-?\d+\.?\d*,\-?\d+\.?\d*))+\)\)
  1136. $patternWkt = '[a-zA-Z]+\(\(' . $patternPoints . '\)\)';
  1137. } else if ('linestring' == $geomType) {
  1138. // [a-zA-Z]+\((\-?\d+\.?\d*,\-?\d+\.?\d*)( (\-?\d+\.?\d*,\-?\d+\.?\d*))+\)
  1139. $patternWkt = '[a-zA-Z]+\(' . $patternPoints . '\)';
  1140. } else if ('point' == $geomType) {
  1141. // [a-zA-Z]+\(\-?\d\.?\d*,\-?\d\.?\d*\)
  1142. $patternWkt = '[a-zA-Z]+\(' . $patternPoint . '\)';
  1143. }
  1144. $simpleTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:simpleType');
  1145. $restrictionNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:restriction');
  1146. $patternNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:pattern');
  1147. $restrictionNode->setAttribute('base', 'xsd:string');
  1148. $patternNode->setAttribute('value', $patternWkt);
  1149. $restrictionNode->appendChild($patternNode);
  1150. $simpleTypeNode->appendChild($restrictionNode);
  1151. $elNode->appendChild($simpleTypeNode);
  1152. }
  1153. $elNode->setAttribute('nillable', 'true');
  1154. $elNode->setAttribute('minOccurs', '0');
  1155. }
  1156. }
  1157. }
  1158. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  1159. $updateTypeNode->appendChild($attrNode);
  1160. $attrNode->setAttribute('name', 'typeName');
  1161. $attrNode->setAttribute('type', 'xsd:token');
  1162. $attrNode->setAttribute('use', 'required');
  1163. if ($transactionType == 'Insert') {
  1164. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  1165. $updateTypeNode->appendChild($attrNode);
  1166. $attrNode->setAttribute('name', 'typeNsUri');
  1167. $attrNode->setAttribute('type', 'xsd:anyURI');
  1168. $attrNode->setAttribute('use', 'required');
  1169. }
  1170. if ($transactionType == 'Update') {
  1171. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  1172. $updateTypeNode->appendChild($attrNode);
  1173. $attrNode->setAttribute('name', 'featureId');
  1174. $attrNode->setAttribute('use', 'required');
  1175. $sTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:simpleType');
  1176. $attrNode->appendChild($sTypeNode);
  1177. $resNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:restriction');
  1178. $sTypeNode->appendChild($resNode);
  1179. $resNode->setAttribute('base', 'xsd:string');
  1180. $patternNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:pattern');
  1181. $resNode->appendChild($patternNode);
  1182. $patternNode->setAttribute('value', '[a-zA-Z_][a-zA-Z0-9_]*\.[0-9]*');
  1183. }
  1184. }
  1185. {// 'Delete'
  1186. $typeName = "p5_{$sourceNs[0]}:{$sourceNs[1]}";
  1187. $acl = $this->getAclFromTypeName($typeName);
  1188. $deleteElementType = "DeleteNs{$nsInd}ElementType";
  1189. $deleteTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:complexType');
  1190. $rootNode->appendChild($deleteTypeNode);
  1191. $deleteTypeNode->setAttribute('name', $deleteElementType);
  1192. /* <xsd:attribute name="typeName" type="xsd:token" use="required"/> */
  1193. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  1194. $deleteTypeNode->appendChild($attrNode);
  1195. $attrNode->setAttribute('name', 'typeName');
  1196. $attrNode->setAttribute('type', 'xsd:token');
  1197. $attrNode->setAttribute('use', 'required');
  1198. /* <xsd:attribute name="featureId" use="required"> */
  1199. $attrNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:attribute');
  1200. $deleteTypeNode->appendChild($attrNode);
  1201. $attrNode->setAttribute('name', 'featureId');
  1202. $attrNode->setAttribute('use', 'required');
  1203. $sTypeNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:simpleType');
  1204. $attrNode->appendChild($sTypeNode);
  1205. $resNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:restriction');
  1206. $sTypeNode->appendChild($resNode);
  1207. $resNode->setAttribute('base', 'xsd:string');
  1208. $patternNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xsd:pattern');
  1209. $resNode->appendChild($patternNode);
  1210. $patternNode->setAttribute('value', '[a-zA-Z_][a-zA-Z0-9_]*\.[0-9]*');
  1211. }
  1212. }
  1213. $validateConvertedTransactionXsdString = $dom->saveXml();
  1214. if($DBG){echo 'L.' . __LINE__ . ' $validateConvertedTransactionXsdString:';print_r($validateConvertedTransactionXsdString);echo "\n";}
  1215. $reqXml = new DOMDocument();
  1216. $reqXml->loadXml($convertedTransaction);
  1217. // TODO: fetch PHP Warning: DOMDocument::schemaValidateSource(): Element 'PARENT_ID': 'abc' is not a valid value of the atomic type 'xs:integer'.
  1218. return $reqXml->schemaValidateSource($validateConvertedTransactionXsdString);
  1219. }
  1220. public function getInstanceFeatures($name, $args) {
  1221. $acl = $this->getAclFromTypeName("{$args['typePrefix']}:{$name}");
  1222. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  1223. $rootWfsNs = 'p5';
  1224. $rootWfsNsUri = "{$baseNsUri}";
  1225. $wfsNs = $args['typePrefix'];
  1226. $wfsNsUri = "{$baseNsUri}/" . ('p5_' == substr($args['typePrefix'], 0, 3)) ? substr($args['typePrefix'], 3) : $args['typePrefix'];
  1227. $featureTypeUri = $this->getBaseUri() . "?SERVICE=WFS&VERSION=1.0.0&TYPENAME={$args['xsd:type']}&REQUEST=DescribeFeatureType";
  1228. header('Content-type: application/xml; charset=utf-8');
  1229. $xmlWriter = new Core_XmlWriter();
  1230. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  1231. $xmlWriter->openUri('php://output');
  1232. $xmlWriter->setIndent(true);
  1233. $xmlWriter->startDocument('1.0','UTF-8');
  1234. $xmlWriter->startElement('wfs:FeatureCollection');
  1235. $xmlWriter->writeAttribute('xmlns:wfs', 'http://www.opengis.net/wfs');
  1236. $xmlWriter->writeAttribute('xmlns', 'http://www.opengis.net/wfs');
  1237. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  1238. $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  1239. $xmlWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
  1240. $xmlWriter->writeAttribute("xmlns:{$wfsNs}", $wfsNsUri);
  1241. if (!$simple) $xmlWriter->writeAttribute("xmlns:{$rootWfsNs}", $rootWfsNsUri);
  1242. $xmlWriter->writeAttribute('xsi:schemaLocation', "{$wfsNsUri} {$featureTypeUri}");
  1243. $xmlWriter->writeComment("INSTANCE TABLE: " . Core_AclHelper::getInstanceTable($acl->getRootTableName()));
  1244. // <gml:featureMember>
  1245. // <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">
  1246. // <p5_objects:ID p5:allow_write="true">64</p5_objects:ID>
  1247. $xmlWriter->endElement();// wfs:FeatureCollection
  1248. $xmlWriter->endDocument();
  1249. exit;
  1250. }
  1251. public function _describeInstanceAttributeTable($nsPrefix, $name) {
  1252. $acl = $this->getAclFromTypeName("{$nsPrefix}:{$name}");
  1253. header('Content-type: application/xml; charset=utf-8');
  1254. $xmlWriter = new Core_XmlWriter();
  1255. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  1256. $xmlWriter->openUri('php://output');
  1257. $xmlWriter->setIndent(true);
  1258. $xmlWriter->startDocument('1.0','UTF-8');
  1259. $xmlWriter->startElement('xsd:schema');
  1260. $xmlWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema');
  1261. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  1262. foreach (Api_WfsNs::getNsList() as $uri => $prefix) {
  1263. $xmlWriter->writeAttribute("xmlns:{$prefix}", $uri);
  1264. }
  1265. $xmlWriter->writeAttribute('elementFormDefault', 'qualified');
  1266. $xsdInstanceType = $acl->getName() . "_instanceType";
  1267. $xsdPrimaryKey = "xsd:string";// TODO: get from $acl
  1268. $xmlWriter->h('xsd:element', ['name'=>"instance"], [
  1269. [ 'xsd:complexType', [
  1270. [ 'xsd:sequence', [
  1271. [ 'xsd:element', ['name'=>"primaryKey", 'type'=>$xsdPrimaryKey], null ],
  1272. [ 'xsd:element', ['name'=>"instance_name", 'type'=>$xsdInstanceType], null ],
  1273. [ 'xsd:element', ['name'=>"instance_type", 'type'=>"xsd:string"], null ],// TODO: instance, derived, matching
  1274. [ 'xsd:element', ['name'=>"create_author", 'type'=>"xsd:string"], null ],
  1275. [ 'xsd:element', ['name'=>"create_date", 'type'=>"xsd:dateTime"], null ],
  1276. [ 'xsd:element', ['name'=>"update_author", 'type'=>"xsd:string"], null ],
  1277. [ 'xsd:element', ['name'=>"updage_date", 'type'=>"xsd:dateTime"], null ],
  1278. [ 'xsd:element', ['name'=>"verified", 'type'=>"xsd:integer"], null ],
  1279. ] ]
  1280. ] ]
  1281. ]);
  1282. $instanceList = (method_exists($acl, 'getInstanceList'))
  1283. ? array_map(function ($instanceName) {
  1284. return [ 'xsd:enumeration', ['value'=>$instanceName], null ];
  1285. }, $acl->getInstanceList())
  1286. : [ [ 'xsd:enumeration', ['value'=>$acl->getName()], null ] ]
  1287. ;
  1288. $xmlWriter->h('xsd:simpleType', ['name'=>$xsdInstanceType], [
  1289. [ 'xsd:restriction', ['base'=>"xsd:string"], $instanceList ],
  1290. ]);
  1291. $xmlWriter->endElement();// xsd:schema
  1292. $xmlWriter->endDocument();
  1293. exit;
  1294. }
  1295. public function _getDescribeFeatureType($nsPrefix, $type, $simple = true) {
  1296. return $this->_getDescribeFeatureTypes(array(array($nsPrefix, $type)), $simple);
  1297. }
  1298. public function _parseDescribeFeatureTypeRequest($reqContent, $simple = true) {
  1299. $parserXml = xml_parser_create();
  1300. xml_parser_set_option($parserXml, XML_OPTION_CASE_FOLDING, 0);
  1301. xml_parser_set_option($parserXml, XML_OPTION_SKIP_WHITE, 1);
  1302. if (0 == xml_parse_into_struct($parserXml, $reqContent, $tags)) {
  1303. throw new Exception("Error parsing xml");
  1304. }
  1305. xml_parser_free($parserXml);
  1306. if (empty($tags)) {
  1307. throw new Exception("Empty structure from request");
  1308. }
  1309. $rootTagName = V::get('tag', '', $tags[0]);
  1310. if ('DescribeFeatureType' != $rootTagName) {
  1311. throw new Api_WfsException("Wrong xml root tag '{$rootTagName}' #" . __LINE__, 501);
  1312. }
  1313. $requestXmlTags = $tags;
  1314. $DBG = (V::get('DBG_XML', '', $_GET) > 0);// TODO: Profiler
  1315. $rootTagName = V::get('tag', '', $requestXmlTags[0]);
  1316. if ('DescribeFeatureType' != $rootTagName) {
  1317. throw new Exception("Parse Request xml error #" . __LINE__);
  1318. }
  1319. /*[1] => Array(
  1320. [tag] => TypeName
  1321. [type] => complete
  1322. [level] => 2
  1323. [value] => p5_default_db:Rozdzielcza_rurociag_wsg84)
  1324. */
  1325. $typeNames = array();
  1326. $totalTypes = count($requestXmlTags) - 1;
  1327. for ($i = 1; $i < $totalTypes; $i++) {
  1328. if($DBG){echo "TAG[{$i}]:" . json_encode($requestXmlTags[$i]) . "\n";}
  1329. $typeNames[] = explode(':', $requestXmlTags[$i]['value'], 2);
  1330. }
  1331. //echo "typeNames: " . json_encode($typeNames) . "\n";
  1332. return $this->_getDescribeFeatureTypes($typeNames, $simple);
  1333. }
  1334. public function _getDescribeFeatureAllTypes($simple = true) {
  1335. $db = DB::getDB();
  1336. $idDefaultDB = $db->_zasob_id;
  1337. $tblsAcl = $this->_getTableAclList();
  1338. foreach ($tblsAcl as $tblAcl) {
  1339. $dataSourceName = 'default_db';// TODO: getSourceName
  1340. $tblName = $tblAcl->getName();
  1341. $typeNames[] = array("p5_{$dataSourceName}", $tblName);
  1342. }
  1343. return $this->_getDescribeFeatureTypes($typeNames, $simple);
  1344. }
  1345. // @param $typeNames = array( array( $nsPrefix, $type ) )
  1346. public function _getDescribeFeatureTypes($typeNames, $simple = true) {
  1347. if (empty($typeNames)) throw new HttpException("Feature Type Names not defined", 400);
  1348. $this->DBG("types:" . json_encode($typeNames), __LINE__, __FUNCTION__, __CLASS__);
  1349. DBG::log($typeNames, 'array', "DescribeFeatureType \$typeNames");
  1350. // TODO: fix namespace BUG for multiple types:
  1351. // - fetch namespace for first type
  1352. // - if another object has another namespace then -> import tag
  1353. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  1354. $rootWfsNs = 'p5';
  1355. $rootWfsNsUri = "{$baseNsUri}";
  1356. $featureTypeUri = Api_WfsNs::getBaseWfsUri() . "?SERVICE=WFS&VERSION=1.0.0&REQUEST=DescribeFeatureType";
  1357. header('Content-type: application/xml');
  1358. $nsMap = Api_WfsNs::getNsList();// uri => prefix
  1359. $xsdTargetNamespace = null;
  1360. { // targetNamespace
  1361. list($nsPrefix, $objectName) = reset($typeNames);
  1362. $typeName = "{$nsPrefix}:{$objectName}";
  1363. $acl = $this->getAclFromTypeName($typeName);
  1364. $aclNamespaceUri = Api_WfsNs::getNsUri($acl->getSourceName());
  1365. $xsdTargetNamespace = $aclNamespaceUri;
  1366. if (!array_key_exists($aclNamespaceUri, $nsMap)) $nsMap[$aclNamespaceUri] = $acl->getSourceName();
  1367. }
  1368. $xmlWriter = new Core_XmlWriter();
  1369. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  1370. $xmlWriter->openMemory();// openUri('php://output');
  1371. $xmlWriter->setIndent(true);
  1372. $xmlWriter->startDocument('1.0','UTF-8');
  1373. $xmlWriter->startElement('xsd:schema');
  1374. $xmlWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema');
  1375. $xmlWriter->writeAttribute('xmlns:gml', 'http://www.opengis.net/gml');
  1376. foreach (Api_WfsNs::getNsList() as $uri => $prefix) {
  1377. $xmlWriter->writeAttribute("xmlns:{$prefix}", $uri);
  1378. }
  1379. $xmlWriter->writeAttribute('elementFormDefault', "qualified");
  1380. if ($xsdTargetNamespace) $xmlWriter->writeAttribute('targetNamespace', $xsdTargetNamespace);
  1381. $schemaLocations = [];
  1382. //$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
  1383. if (!empty($schemaLocations)) $xmlWriter->writeAttribute('xsi:schemaLocation', implode(' ', $schemaLocations));
  1384. $xmlWriter->writeAttribute('version', "1.0.0");
  1385. $xmlWriter->h('xsd:import', [
  1386. 'namespace' => "http://www.opengis.net/gml",
  1387. 'schemaLocation' => Request::getPathUri() . "schema/gml/2.1.2/feature.xsd"
  1388. ], null);
  1389. foreach ($typeNames as $typeNameEx) {
  1390. list($nsPrefix, $objectName) = $typeNameEx;
  1391. $typeName = "{$nsPrefix}:{$objectName}";
  1392. $xmlWriter->writeComment("typeName '{$typeName}'");
  1393. $acl = $this->getAclFromTypeName($typeName);
  1394. $aclNamespaceUri = Api_WfsNs::getNsUri($acl->getSourceName());
  1395. if (!array_key_exists($aclNamespaceUri, $nsMap)) $nsMap[$aclNamespaceUri] = $acl->getSourceName();
  1396. if ($xsdTargetNamespace != $aclNamespaceUri) {
  1397. $xmlWriter->writeComment("TODO: typeName '{$typeName}' by import namespace '{$aclNamespaceUri}'");// TODO: <xsd:import>; continue;
  1398. }
  1399. DBG::log($acl->hasSimpleSchema(), 'array', "\$acl({$typeName})->hasSimpleSchema()");
  1400. if ($acl->hasSimpleSchema()) {
  1401. $simpleSchema = $acl->getSimpleSchema();
  1402. $xmlWriter->writeComment("TODO: typeName '{$typeName}' hasSimpleSchema L." . __LINE__);
  1403. $aliasRefMap = array();// fieldName => namespace uri
  1404. foreach ($simpleSchema as $ssName => $schema) {
  1405. if ('root' == $ssName) $ssName = $objectName;
  1406. foreach ($schema as $fieldName => $field) {
  1407. if (is_array($field)
  1408. && !empty($field['@ref'])
  1409. && false !== strpos($field['@ref'], '/')
  1410. ) {// @ref_uri
  1411. $aliasRefMap[ "{$ssName}_{$fieldName}" ] = $field['@ref'];
  1412. }
  1413. }
  1414. }
  1415. if (!empty($aliasRefMap)) {
  1416. foreach ($aliasRefMap as $fieldName => $aliasNsUri) {
  1417. list($nsUri, $prefix, $name) = Api_WfsNs::parseObjectNsUri($aliasNsUri);
  1418. if (!array_key_exists($nsUri, $nsMap)) $nsMap[$nsUri] = $prefix;
  1419. $xmlWriter->h('xsd:import', ['namespace' => $nsUri, 'schemaLocation' => "{$nsUri}.xsd"], null); // TODO: real file url -> DescribeFeatureType[Advanced]
  1420. }
  1421. }
  1422. foreach ($simpleSchema as $ssName => $schema) {
  1423. {// code from Code_AclSimpleSchema
  1424. if ('root' == $ssName) $ssName = $objectName;
  1425. // <xsd:complexType name="ZaliczkaPozycjaType">
  1426. // <xsd:complexContent>
  1427. // <xsd:extension base="gml:AbstractFeatureType">
  1428. // <xsd:sequence>
  1429. // <xsd:element minOccurs="0" maxOccurs="1" name="id" type="xsd:integer" nillable="true"/>
  1430. // <xsd:element minOccurs="0" maxOccurs="1" name="created" type="xsd:date" nillable="true"/>
  1431. // <xsd:element minOccurs="0" maxOccurs="1" ref="default_objects/AccessOwner" p5:name="worker"/>
  1432. // <xsd:element minOccurs="0" maxOccurs="1" name="kwota" type="xsd:decimal" nillable="true"/>
  1433. // <xsd:element minOccurs="0" maxOccurs="1" ref="ZaliczkaPozycja" p5:name="pozycja"/>
  1434. // </xsd:sequence>
  1435. // </xsd:extension>
  1436. // </xsd:complexContent>
  1437. // </xsd:complexType>
  1438. $tnsPrefix = $acl->getSourceName();
  1439. $xmlWriter->startElement('xsd:complexType');
  1440. $xmlWriter->writeAttribute('name', "{$ssName}Type");
  1441. $xmlWriter->startElement('xsd:sequence');
  1442. foreach ($schema as $fieldName => $field) {
  1443. // [@namespace] => default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja
  1444. // [id] => xsd:integer
  1445. // [kwota] => xsd:decimal
  1446. // [korespondencja] => [ '@ref' => Korespondencja ]
  1447. // [projekt] => [ '@ref' => Projekt ]
  1448. // TODO: p5:field_name
  1449. if ('@' == substr($fieldName, 0, 1)) continue;// skip tags
  1450. $xmlWriter->startElement('xsd:element');
  1451. if (!is_array($field)) throw new Exception("Error Processing simpleSchema: '{$ssName}/{$fieldName}'");
  1452. if (!empty($field['@type'])) {
  1453. $xmlWriter->writeAttribute('name', $fieldName);
  1454. $xmlWriter->writeAttribute('type', $field['@type']);
  1455. $xmlWriter->writeAttribute('nillable', "true");
  1456. } else if (!empty($field['@ref'])) {
  1457. if (false !== strpos($field['@ref'], '/')) {// @ref_uri
  1458. $xmlWriter->writeAttribute('ref', "{$tnsPrefix}:{$ssName}_{$fieldName}");
  1459. $xmlWriter->writeAttributeNS($rootWfsNs, "name", $rootWfsNsUri, $fieldName);
  1460. } else {
  1461. $xmlWriter->writeAttribute('ref', "{$tnsPrefix}:{$field['@ref']}");
  1462. if ($fieldName != $field['@ref']) {
  1463. $xmlWriter->writeAttributeNS($rootWfsNs, "name", $rootWfsNsUri, $fieldName);
  1464. }
  1465. }
  1466. } else {
  1467. throw new Exception("Error Processing simpleSchema - missing @type or @ref: '{$ssName}/{$fieldName}'");
  1468. }
  1469. if (array_key_exists('@minOccurs', $field)) $xmlWriter->writeAttribute('minOccurs', $field['@minOccurs']);
  1470. if (array_key_exists('@maxOccurs', $field)) $xmlWriter->writeAttribute('maxOccurs', $field['@maxOccurs']);
  1471. $xmlWriter->endElement(); // 'xsd:element'
  1472. }
  1473. $xmlWriter->endElement(); // 'xsd:sequence'
  1474. $xmlWriter->endElement(); // 'xsd:complexType'
  1475. $xmlWriter->startElement('xsd:element');
  1476. $xmlWriter->writeAttribute('name', $ssName);
  1477. $xmlWriter->writeAttribute('type', "{$tnsPrefix}:{$ssName}Type");
  1478. if (!$simple) {
  1479. if (!empty($schema['@namespace'])) {// TODO: @namespace is required?
  1480. list($nsUri, $prefix, $name) = Api_WfsNs::parseObjectNsUri($schema['@namespace']);
  1481. $xmlWriter->writeAttributeNS($rootWfsNs, "namespace", $rootWfsNsUri, "{{$nsUri}}{$name}");
  1482. }
  1483. }
  1484. $xmlWriter->endElement(); // 'xsd:element'
  1485. }
  1486. }
  1487. if (!empty($aliasRefMap)) {
  1488. foreach ($aliasRefMap as $fieldName => $aliasNsUri) {
  1489. list($nsUri, $prefix, $name) = Api_WfsNs::parseObjectNsUri($aliasNsUri);
  1490. $xmlWriter->h('xsd:element', ['name' => $fieldName, 'type' => "{$prefix}:{$name}Type"], null);
  1491. }
  1492. }
  1493. } else {
  1494. $objectXsdName = "{$objectName}Type";
  1495. $xmlWriter->startElement('xsd:complexType');
  1496. $xmlWriter->writeAttribute('name', $objectXsdName);
  1497. // if (!$simple) $xmlWriter->writeAttribute("xlmns:{$rootWfsNs}", $rootWfsNsUri);
  1498. if (!$simple) $xmlWriter->writeAttributeNS($rootWfsNs, "web_link", $rootWfsNsUri, Request::getPathUri() . "index.php?_route=ViewTableAjax&namespace=" . $acl->getNamespace());
  1499. if (!$simple && ($lastUpdateDate = $acl->lastUpdateDate())) $xmlWriter->writeAttributeNS($rootWfsNs, "last_update_date", $rootWfsNsUri, $lastUpdateDate);
  1500. $xmlWriter->startElement('xsd:complexContent');
  1501. $xmlWriter->startElement('xsd:extension');
  1502. $xmlWriter->writeAttribute('base', "gml:AbstractFeatureType");
  1503. $xmlWriter->startElement('xsd:sequence');
  1504. $pKeyField = $acl->getPrimaryKeyField();
  1505. $p5Attributes = ($simple)? array() : $acl->getAttributesFromZasoby();
  1506. $fldList = $this->_getFieldListFromAcl($acl);
  1507. foreach ($fldList as $fldName) {
  1508. $xmlWriter->startElement('xsd:element');
  1509. // TODO: get minOccurs from $acl->xsd()
  1510. $xmlWriter->writeAttribute('minOccurs', (method_exists($acl, 'getXsdMinOccurs'))
  1511. ? $acl->getXsdMinOccurs($fldName)
  1512. : (($pKeyField == $fldName) ? '1' : '0')
  1513. );
  1514. $xmlWriter->writeAttribute('maxOccurs', (method_exists($acl, 'getXsdMaxOccurs'))
  1515. ? $acl->getXsdMaxOccurs($fldName)
  1516. : '1'
  1517. );
  1518. $fldType = $acl->getXsdFieldType($fldName);
  1519. if (!$simple && $acl->isEnumerationField($fldName)) {
  1520. $fldType = $acl->getSourceName() . ":{$fldName}Type";
  1521. }
  1522. if ('ref:' == substr($fldType, 0, 4)) {
  1523. $xmlWriter->writeAttribute("ref", substr($fldType, 4));
  1524. $xmlWriter->writeAttributeNS($rootWfsNs, "name", $rootWfsNsUri, $fldName);
  1525. } else if ('local_ref:' == substr($fldType, 0, 10)) {
  1526. $xmlWriter->writeAttribute("type", "{$fldName}Type");
  1527. $xmlWriter->writeAttributeNS($rootWfsNs, "name", $rootWfsNsUri, $fldName);
  1528. } else if ('alias_ref:' == substr($fldType, 0, 10)) {
  1529. $xmlWriter->writeAttribute("ref", $acl->getSourceName() . ":{$fldName}");
  1530. $xmlWriter->writeAttributeNS($rootWfsNs, "name", $rootWfsNsUri, $fldName);
  1531. } else {
  1532. $xmlWriter->writeAttribute('name', $fldName);
  1533. $xmlWriter->writeAttribute('type', $fldType);
  1534. $xmlWriter->writeAttribute('nillable', 'true');// nillable not allowed in ref
  1535. }
  1536. if (!$simple) {
  1537. if (!empty($p5Attributes[$fldName])) {
  1538. $p5attrs = $p5Attributes[$fldName];
  1539. if (!empty($p5attrs['id_zasob'])) $xmlWriter->writeAttributeNS($rootWfsNs, "id_zasob", $rootWfsNsUri, $p5attrs['id_zasob']);
  1540. if (!empty($p5attrs['label'])) $xmlWriter->writeAttributeNS($rootWfsNs, "label", $rootWfsNsUri, $p5attrs['label']);
  1541. if (!empty($p5attrs['description'])) $xmlWriter->writeAttributeNS($rootWfsNs, "description", $rootWfsNsUri, $p5attrs['description']);
  1542. }
  1543. if ($acl->canWriteField($fldName)) $xmlWriter->writeAttributeNS($rootWfsNs, "allow_write", $rootWfsNsUri, "true");
  1544. if ($acl->canCreateField($fldName)) $xmlWriter->writeAttributeNS($rootWfsNs, "allow_create", $rootWfsNsUri, "true");
  1545. if (!$acl->canReadField($fldName)) $xmlWriter->writeAttributeNS($rootWfsNs, "allow_read", $rootWfsNsUri, "false");
  1546. }
  1547. $xmlWriter->endElement(); // xsd:element
  1548. }
  1549. $xmlWriter->endElement(); // xsd:sequence
  1550. if (!$simple) $xmlWriter->h('xsd:attribute', ['name' => "instance", 'type' => $acl->getSourceName() . ":instanceType"], null);
  1551. $xmlWriter->endElement(); // xsd:extension
  1552. $xmlWriter->endElement(); // xsd:complexContent
  1553. $xmlWriter->endElement(); // xsd:complexType
  1554. if (!$simple) {
  1555. $xsdInstanceList = (method_exists($acl, 'getInstanceList'))
  1556. ? array_map(function ($instanceName) {
  1557. return [ 'xsd:enumeration', ['value'=>$instanceName], null ];
  1558. }, $acl->getInstanceList())
  1559. : [ [ 'xsd:enumeration', ['value'=>$acl->getName()], null ] ]
  1560. ;
  1561. DBG::log($xsdInstanceList, 'array', "\$xsdInstanceList");
  1562. $xmlWriter->h('xsd:simpleType', ['name' => 'instanceType'], [
  1563. [ 'xsd:restriction', ['base' => 'xsd:string'], $xsdInstanceList ]
  1564. ]);
  1565. }
  1566. $xmlWriter->h('xsd:element', ['name' => $objectName, 'type' => $acl->getSourceName() . ':' . $objectXsdName, 'substitutionGroup'=>"gml:_Feature"], null);
  1567. foreach ($fldList as $fldName) {
  1568. $fldType = $acl->getXsdFieldType($fldName);
  1569. if ('alias_ref:' == substr($fldType, 0, 10)) {
  1570. $localRefType = substr($fldType, 10);
  1571. $xmlWriter->h('xsd:element', ['name' => $fldName, 'type' => $localRefType], null);
  1572. } else if ('local_ref:' == substr($fldType, 0, 10)) {
  1573. $localRefType = substr($fldType, 10);
  1574. $xmlWriter->writeComment("TODO:
  1575. <xsd:complexType name=\"produkt_Type\">
  1576. <xsd:sequence>
  1577. <xsd:element name=\"idProd\" type=\"xsd:integer\" />
  1578. <xsd:element name=\"nazwa\" type=\"xsd:string\" />
  1579. <xsd:element name=\"cena\" type=\"xsd:decimal\" />
  1580. </xsd:sequence>
  1581. </xsd:complexType>
  1582. ");
  1583. }
  1584. }
  1585. if (!$simple) {
  1586. foreach ($fldList as $fldName) {
  1587. if (!$acl->isEnumerationField($fldName)) continue;
  1588. $xsdEnumList = [];
  1589. $enum = $acl->getEnumerations($fldName);
  1590. foreach ($enum as $val => $label) {
  1591. $xsdEnum = ['xsd:enumeration', ['value' => $val], null];
  1592. if (!empty($p5Attributes[$fldName]['valuesMap'][$val])) {
  1593. $xsdEnum[1]["xmlns:{$rootWfsNs}"] = $rootWfsNsUri;
  1594. $xsdEnum[1]["{$rootWfsNs}:label"] = $p5Attributes[$fldName]['valuesMap'][$val];
  1595. }
  1596. $xsdEnumList[] = $xsdEnum;
  1597. }
  1598. $xmlWriter->h('xsd:simpleType', ['name' => "{$fldName}Type"], [
  1599. [ 'xsd:restriction', ['base' => "xsd:string"], $xsdEnumList ]
  1600. ]);
  1601. }
  1602. }
  1603. }
  1604. }
  1605. $xmlWriter->endElement(); // 'xsd:schema'
  1606. $xmlWriter->endDocument();
  1607. echo $xmlWriter->outputMemory($flush = true);
  1608. }
  1609. public function _getTableAclList() {// Use only Tables from default_db
  1610. $tblAclList = array();
  1611. $db = DB::getDB();
  1612. $idDefaultDB = $db->_zasob_id;
  1613. $fullTblAclList = $this->_usrAcl->getTablesAcl();
  1614. foreach ($fullTblAclList as $tblAcl) {
  1615. $dataSourceName = 'default_db';// TODO: getSourceName
  1616. $tblName = $tblAcl->getName();
  1617. if ($idDefaultDB != $tblAcl->getDB()) {// hide non default_db tables
  1618. continue;
  1619. }
  1620. // try {
  1621. // $acl = $this->getAclFromTypeName($typeName = "p5_{$dataSourceName}:{$tblName}");
  1622. // } catch (Exception $e) {
  1623. // // echo "Error for table({$tblName}): " . $e->getMessage() . "\n";
  1624. // }
  1625. // if (!$acl) {
  1626. // // TODO: error log msg
  1627. // continue;
  1628. // }
  1629. $tblAclList[] = $tblAcl;
  1630. }
  1631. return $tblAclList;
  1632. }
  1633. public function _getFieldListFromAcl($acl) {
  1634. $fldList = $acl->getRealFieldListByIdZasob();
  1635. return $fldList;
  1636. }
  1637. public function setLogger($logger) {
  1638. $this->_logger = $logger;
  1639. }
  1640. public function DBG($reqLog, $lineNr = null, $funName = null, $className = null) {
  1641. if (!$this->_logger) return;
  1642. $this->_logger->DBG($reqLog, $lineNr, $funName, $className);
  1643. }
  1644. public function parseOgcFilterRequest($requestOgcFilter) {
  1645. // GetFeature: @maxFeatures, @traverseXlinkDepth, @traverseXlinkExpiry
  1646. // \-- (1..) wfs:Query: @typeName
  1647. // \--- (0..) ---: wfs:PropertyName
  1648. // : wfs:XlinkPropertyName
  1649. // : ogc:Function
  1650. // ogc:Filter
  1651. // ogc:SortBy
  1652. // \--- (1..) ogc:SortProperty
  1653. // \---: ogc:PropertyName
  1654. // : ogc:SortOrder ( DESC / ASC )
  1655. // <ogc:SortBy>
  1656. // <ogc:SortProperty>
  1657. // <ogc:PropertyName>ASTA</ogc:PropertyName>
  1658. // <ogc:SortOrder>ASC</ogc:SortOrder>
  1659. // </ogc:SortProperty>
  1660. // </ogc:SortBy>
  1661. if (empty($requestOgcFilter)) return '';
  1662. $requestXml = new DOMDocument();
  1663. $requestXml->loadXml($requestOgcFilter);
  1664. $nodesQuery = [];
  1665. foreach ($requestXml->getElementsByTagNameNS('http://www.opengis.net/wfs', 'Query') as $element) {
  1666. DBG::log($element->nodeName, 'array', "main loop - wfs:Query");
  1667. $nodesQuery[] = $element;
  1668. }
  1669. if (empty($nodesQuery)) { // legacy - try to find 'ogc:Filter'
  1670. $tagsFilter = [];
  1671. foreach ($requestXml->getElementsByTagNameNS('http://www.opengis.net/ogc', 'Filter') as $element) {
  1672. DBG::log($element->nodeName, 'array', "loop element (0 * wfs:Query)");
  1673. $tagsFilter[] = $requestXml->saveXML($element);
  1674. }
  1675. DBG::log($tagsFilter, 'array', "\$tagsFilter (0 * wfs:Query)");
  1676. return [
  1677. 'ogc:Filter' => (!empty($tagsFilter))
  1678. ? reset($tagsFilter) // TODO: only one ogc:Filter allowed
  1679. : ''
  1680. ];
  1681. }
  1682. if (1 === count($nodesQuery)) {
  1683. $tagsFilter = [];
  1684. foreach ($requestXml->getElementsByTagNameNS('http://www.opengis.net/ogc', 'Filter') as $element) {
  1685. // DBG::log($element->nodeName, 'array', "loop ogc:Filter (1 * wfs:Query)");
  1686. $tagsFilter[] = $requestXml->saveXML($element);
  1687. }
  1688. DBG::log($tagsFilter, 'array', "\$tagsFilter (1 * wfs:Query)");
  1689. $tagsWfsPropertyName = [];
  1690. foreach ($requestXml->getElementsByTagNameNS('http://www.opengis.net/wfs', 'PropertyName') as $element) {
  1691. // DBG::log($element->nodeValue, 'array', "loop wfs:PropertyName (1 * wfs:Query)");
  1692. $tagsWfsPropertyName[] = $element->nodeValue;
  1693. }
  1694. DBG::log($tagsWfsPropertyName, 'array', "\$tagsWfsPropertyName (1 * wfs:Query)");
  1695. return array_filter([
  1696. 'ogc:Filter' => (!empty($tagsFilter))
  1697. ? reset($tagsFilter)
  1698. : '',
  1699. 'wfs:PropertyName' => (!empty($tagsWfsPropertyName))
  1700. ? $tagsWfsPropertyName
  1701. : '',
  1702. ], function ($value) { return !empty($value); });
  1703. }
  1704. throw new Exception("Not imeplemented multiple ogc:Query"); // multiple ogc:Query require ogc:Query/@typeName
  1705. }
  1706. }