WfsServerBase.php 63 KB

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