WfsServerBase.php 62 KB

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