WFS.pm untested

filter: Statementstmt 0.0% 0 / 706 Branchbran 0.0% 0 / 226 Conditioncond 0.0% 0 / 114 MC/DCmcdc 0.0% 0 / 65 Subroutinesub 0.0% 0 / 44 Podpod 0.0% 0 / 26 totaltotal 0.0% 0 / 1181 CC 114 SCAR 53.6
CC
114
Cov
0%
GetFeature
462.0
feature_types_in_data_source
462.0
transaction_sql
420.0
CRAP 212.1
1 =pod
2  
3 =head1 NAME
4  
5 Geo::OGC::Service::WFS - Perl extension for geospatial web feature services
6  
7 =head1 SYNOPSIS
8  
9 The process_request method of this module is called by the
10 Geo::OGC::Service framework.
11  
12 =head1 DESCRIPTION
13  
14 This module aims to provide the operations defined by the Open
15 Geospatial Consortium's Web Feature Service standard. These are (in
16 the version 2.0 of the standard)
17  
18 GetCapabilities (discovery operation) (*)
19 DescribeFeatureType (discovery operation) (*)
20 GetPropertyValue (query operation)
21 GetFeature (query operation) (*)
22 GetFeatureWithLock (query & locking operation)
23 LockFeature (locking operation)
24 Transaction (transaction operation) (*)
25 CreateStoredQuery (stored query operation)
26 DropStoredQuery (stored query operation)
27 ListStoredQueries (stored query operation)
28 DescribeStoredQueries (stored query operation)
29  
30 (*) are at least somehow implemented.
31  
32 This module is a plugin for the Geo::OGC::Service framework.
33  
34 =head2 EXPORT
35  
36 None by default.
37  
38 =head2 METHODS
39  
40 =cut
41  
42 package Geo::OGC::Service::WFS;
43  
44 use 5.010000; # say // and //=
45 use feature "switch";
46 use utf8;
47 use Carp;
48 use File::Basename;
49 use Modern::Perl;
50 use Capture::Tiny ':all';
51 use Clone 'clone';
52 use JSON;
53 use DBI;
54 use Geo::GDAL;
55 use HTTP::Date;
56 use File::MkTemp;
57  
58 use Data::Dumper;
59 use XML::LibXML::PrettyPrint;
60  
61 use Geo::OGC::Service;
62 use Geo::OGC::Service::Filter ':all';
63 use vars qw(@ISA);
64 push @ISA, qw(Geo::OGC::Service::Filter);
65  
66 our $VERSION = '0.11';
67  
68 # GDAL and PostgreSQL data type to XML data type
69 our %type_map = (
70 Short => "xs:short",
71 Integer => "xs:integer",
72 Integer64 => "xs:long",
73 Real => "xs:double",
74 integer => "xs:integer",
75 int => "xs:integer",
76 bigint => "xs:long",
77 decimal => "xs:decimal",
78 numeric => "xs:decimal",
79 real => "xs:float",
80 double => "xs:double",
81 "double precision" => "xs:decimal",
82 timestamp => "xs:date",
83 "timestamp with time zone" => "xs:date",
84 date => "xs:date",
85 time => "xs:time",
86 "time with time zone" => "xs:time",
87 boolean => "xs:boolean",
88 );
89  
90 our %well_known_w3_ns = (
91 'xmlns:xlink' => "http://www.w3.org/1999/xlink",
92 'xmlns:xs' => "http://www.w3.org/2001/XMLSchema",
93 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
94 );
95  
96 our %wfs_1_1_0_ns = (
97 %well_known_w3_ns,
98 xmlns => "http://www.opengis.net/wfs",
99 'xmlns:wfs' => "http://www.opengis.net/wfs",
100 'xmlns:gml' => "http://www.opengis.net/gml",
101 'xmlns:ows' => "http://www.opengis.net/ows",
102 'xmlns:ogc' => "http://www.opengis.net/ogc",
103 'xsi:schemaLocation' => "http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"
104 );
105  
106 our %wfs_2_0_0_ns = (
107 %well_known_w3_ns,
108 xmlns => "http://www.opengis.net/wfs/2.0",
109 'xmlns:wfs' => "http://www.opengis.net/wfs/2.0",
110 'xmlns:gml' => "http://schemas.opengis.net/gml",
111 'xmlns:ows' => "http://www.opengis.net/ows/1.1",
112 'xmlns:fes' => "http://www.opengis.net/fes/2.0",
113 'xmlns:srv' => "http://schemas.opengis.net/iso/19139/20060504/srv/srv.xsd",
114 'xmlns:gmd' => "http://schemas.opengis.net/iso/19139/20060504/gmd/gmd.xsd",
115 'xmlns:gco' => "http://schemas.opengis.net/iso/19139/20060504/gco/gco.xsd",
116 'xsi:schemaLocation' => "http://www.opengis.net/wfs/2.0 http://schemas.opengis.net/wfs/2.0/wfs.xsd"
117 );
118  
119 # Value in request => GDAL GML creation option
120 our %OutputFormats = (
121 'XMLSCHEMA' => 'GML2',
122 'text/xml; subtype=gml/2.1.2' => 'GML2',
123 'text/xml; subtype=gml/3.1.1' => 'GML3',
124 'text/xml; subtype=gml/3.2' => 'GML3.2',
125 'GML3Deegree' => 'GML3Deegree',
126 'application/gml+xml; version=3.2' => 'GML3.2',
127 'application/json' => 'GeoJSON',
128 );
129  
130 our @GDAL_GML_Creation_options = (qw/XSISCHEMAURI XSISCHEMA PREFIX
131 STRIP_PREFIX TARGET_NAMESPACE FORMAT GML3_LONGSRS SRSNAME_FORMAT
132 SRSDIMENSION_LOC WRITE_FEATURE_BOUNDED_BY SPACE_INDENTATION GML_ID
133 NAME DESCRIPTION/);
134  
135 =pod
136  
137 =head3 process_request
138  
139 The entry method into this service. Fails unless the request is well known.
140  
141 =cut
142  
143 sub process_request {
144 my ($self, $responder) = @_;
145 $self->parse_request;
146 $self->{debug} = $self->{parameters}{debug} // $self->{config}{debug} // 0;
147 $self->{responder} = $responder;
148 if ($self->{debug}) {
149 $self->log({ request => $self->{request}, parameters => $self->{parameters} });
150 my $parser = XML::LibXML->new(no_blanks => 1);
151 my $pp = XML::LibXML::PrettyPrint->new(indent_string => " ");
152 if ($self->{posted}) {
153 my $dom = $parser->load_xml(string => $self->{posted});
154 $pp->pretty_print($dom); # modified in-place
155 say STDERR "posted:\n",$dom->toString;
156 }
157 if ($self->{filter}) {
158 my $dom = $parser->load_xml(string => $self->{filter});
159 $pp->pretty_print($dom); # modified in-place
160 say STDERR "filter:\n",$dom->toString;
161 }
162 }
163 for ($self->{request}{request} // '') {
164 if (/^GetCapabilities/ or /^capabilities/) { $self->GetCapabilities() }
165 elsif (/^DescribeFeatureType/) { $self->DescribeFeatureType() }
166 elsif (/^GetFeature/) { $self->GetFeature() }
167 elsif (/^Transaction/) { $self->Transaction() }
168 elsif (/^$/) {
169 $self->error({ exceptionCode => 'MissingParameterValue',
170 locator => 'request' }) }
171 else {
172 $self->error({ exceptionCode => 'InvalidParameterValue',
173 locator => 'request',
174 ExceptionText => "$self->{parameters}{request} is not a known request" }) }
175 }
176 }
177  
178 =pod
179  
180 =head3 GetCapabilities
181  
182 Service the GetCapabilities request. The configuration JSON is used to
183 control the contents of the reply. The config contains root keys, which
184 are either simple or complex. The simple root keys are
185  
186 Key Default Comment
187 --- ------- -------
188 version 2.0.0
189 Title WFS Server
190 resource required
191 ServiceTypeVersion
192 AcceptVersions 2.0.0,1.1.0,1.0.0
193 Transaction optional
194  
195 FeatureTypeList is a root key, which is a list of FeatureType
196 hashes. A FeatureType defines one layer (key Layer exists) or a group
197 of layers (key Layer does not exist). The key DataSource is required -
198 it is a GDAL data source string. Currently only PostGIS layers are
199 supported.
200  
201 If Layer is specified, then also keys Name, Title, Abstract, and
202 DefaultSRS are required, and LowerCorner is optional.
203  
204 For PostGIS groups the default is open. The names of the layers are
205 constructed from a prefix, which is a required key, name of the table
206 or view, and the name of the geometry column, e.g.,
207 prefix.table.geom. The listed layers can be restricted with keys
208 TABLE_TYPE, TABLE_PREFIX, deny, and allow. TABLE_TYPE, deny, and allow
209 are, if exist, hashes. The keys of the first are table types as DBI
210 reports them, and the keys of the deny and allow are layer names (the
211 prefix can be left out). TABLE_PREFIX is a string that sets a
212 requirement for the table/view names for to be listed.
213  
214 =cut
215  
216 sub GetCapabilities {
217 my ($self) = @_;
218 my $writer = Geo::OGC::Service::XMLWriter::Caching->new();
219 my %ns;
220 if ($self->{version} eq '2.0.0') {
221 %ns = (%wfs_2_0_0_ns);
222 # updateSequence="260" ?
223 } else {
224 %ns = (%wfs_1_1_0_ns);
225 }
226 $ns{version} = $self->{version};
227 $writer->open_element('wfs:WFS_Capabilities', \%ns);
228 $self->DescribeService($writer);
229 $self->OperationsMetadata($writer);
230 $self->FeatureTypeList($writer);
231 $self->Filter_Capabilities($writer);
232 $writer->close_element;
233 $writer->stream($self->{responder});
234 }
235  
236 sub OperationsMetadata {
237 my ($self, $writer) = @_;
238 $writer->open_element('ows:OperationsMetadata');
239 my @versions = split /,/, $self->{config}{AcceptVersions} // '2.0.0,1.1.0,1.0.0';
240 $self->Operation($writer, 'GetCapabilities',
241 { Get => 1, Post => 1 },
242 [{service => ['WFS']},
243 {AcceptVersions => \@versions},
244 {AcceptFormats => ['text/xml']}]);
245 $self->Operation($writer, 'DescribeFeatureType',
246 { Get => 1, Post => 1 },
247 [{outputFormat => [sort keys %OutputFormats]}]);
248 $self->Operation($writer, 'GetFeature',
249 { Get => 1, Post => 1 },
250 [{resultType => ['results']}, {outputFormat => [sort keys %OutputFormats]}]);
251 $self->Operation($writer, 'Transaction',
252 { Get => 1, Post => 1 },
253 [{inputFormat => ['text/xml; subtype=gml/3.1.1']},
254 {idgen => ['GenerateNew','UseExisting','ReplaceDuplicate']},
255 {releaseAction => ['ALL','SOME']}
256 ]);
257 # constraints
258 my %constraints = (
259 ImplementsBasicWFS => 1,
260 ImplementsTransactionalWFS => 1,
261 ImplementsLockingWFS => 0,
262 KVPEncoding => 1,
263 XMLEncoding => 1,
264 SOAPEncoding => 0,
265 ImplementsInheritance => 0,
266 ImplementsRemoteResolve => 0,
267 ImplementsResultPaging => 0,
268 ImplementsStandardJoins => 1,
269 ImplementsSpatialJoins => 1,
270 ImplementsTemporalJoins => 1,
271 ImplementsFeatureVersioning => 0,
272 ManageStoredQueries => 0,
273 PagingIsTransactionSafe => 1,
274 );
275 for my $key (keys %constraints) {
276 $writer->element('ows:Constraint', {name => $key},
277 [['ows:NoValues'],
278 ['ows:DefaultValue' => $constraints{$key} ? 'TRUE' : 'FALSE']]);
279 }
280 $writer->element('ows:Constraint', {name => 'QueryExpressions'},
281 ['ows:AllowedValues' => ['ows:Value' => 'wfs:Query']]);
282 $writer->close_element;
283 }
284  
285 sub FeatureTypeList {
286 my ($self, $writer) = @_;
287 $writer->open_element('wfs:FeatureTypeList');
288 my $operations = $self->{config}{Operations} // 'Query';
289 my @operations = list2element('wfs:Operation', $operations);
290 $writer->element('wfs:Operations', \@operations);
291  
292 my $list_layer = sub {
293 my ($type) = @_;
294 # should we test that the layer is really available?
295 my @formats;
296 for my $format (sort keys %OutputFormats) {
297 push @formats, ['wfs:Format', $format];
298 }
299 my @FeatureType = (
300 ['wfs:Name', $type->{Name}],
301 ['wfs:Title', $type->{Title}],
302 ['wfs:Abstract', $type->{Abstract}],
303 ['wfs:DefaultSRS', $type->{DefaultSRS}],
304 ['wfs:OtherSRS', 'EPSG:3857'],
305 ['wfs:OutputFormats', \@formats]
306 );
307 push @FeatureType, [
308 'ows:WGS84BoundingBox', {dimensions => 2}, [
309 ['ows:LowerCorner',$type->{LowerCorner}],
310 ['ows:UpperCorner',$type->{UpperCorner}]
311 ]
312 ] if exists $type->{LowerCorner};
313 push @FeatureType, [
314 'wfs:Operations', [
315 list2element('wfs:Operation', $type->{Operations})
316 ]
317 ] if $type->{Operations};
318 $writer->element('wfs:FeatureType', \@FeatureType);
319 };
320  
321 eval {
322 $self->read_feature_type_list;
323 for my $type (@{$self->{feature_types}}) {
324 for my $t (@$type) {
325 $list_layer->($t);
326 }
327 }
328 };
329 say STDERR $@ if $@;
330 $writer->close_element;
331 }
332  
333 =pod
334  
335 =head3 DescribeFeatureType
336  
337 Service the DescribeFeatureType request.
338  
339 =cut
340  
341 sub DescribeFeatureType {
342 my ($self) = @_;
343  
344 my @typenames;
345 for my $query (@{$self->{request}{queries}}) {
346 push @typenames, split(/\s*,\s*/, $query->{typename});
347 }
348  
349 unless (@typenames) {
350 $self->error({ exceptionCode => 'MissingParameterValue',
351 locator => 'typeName' },
352 [$self->CORS]);
353 return;
354 }
355
356 my %types;
357  
358 for my $name (@typenames) {
359 eval {
360 $types{$name} = $self->get_feature_type($name);
361 };
362 unless ($types{$name}) {
363 $@ =~ s/ at \/.*//;
364 $self->error({ exceptionCode => 'InvalidParameterValue',
365 locator => 'typeName',
366 ExceptionText => $@ },
367 [$self->CORS]);
368 return;
369 }
370 }
371  
372 my $writer = Geo::OGC::Service::XMLWriter::Caching->new();
373
374 $writer->open_element(schema => {
375 targetNamespace => $self->{config}{targetNamespace},
376 xmlns => "http://www.w3.org/2001/XMLSchema",
377 'xmlns:gml' => "http://schemas.opengis.net/gml",
378 elementFormDefault => "qualified",
379 attributeFormDefault => "unqualified" });
380
381 $writer->element(import => {
382 namespace => "http://www.opengis.net/gml",
383 schemaLocation => "http://schemas.opengis.net/gml/2.1.2/feature.xsd" });
384  
385 for my $name (sort keys %types) {
386 my $type = $types{$name};
387  
388 # to do: geometry and primary key
389  
390 my ($pseudo_credentials) = pseudo_credentials($type);
391 my @elements;
392 for my $property (keys %{$type->{columns}}) {
393  
394 next if $pseudo_credentials->{$property};
395  
396 my $minOccurs = 0;
397 push @elements, ['element', {
398 name => $type->{columns}{$property}{out_name},
399 type => $type->{columns}{$property}{out_type},
400 minOccurs => "$minOccurs",
401 maxOccurs => "1"
402 }];
403
404 }
405 $writer->element(
406 'complexType',
407 {name => $type->{Name}.'Type'},
408 ['complexContent',
409 ['extension', { base => 'gml:AbstractFeatureType' },
410 ['sequence', \@elements
411 ]]]
412 );
413 $writer->element(
414 'element', { name => $type->{Name},
415 type => 'ogr:'.$type->{Name}.'Type',
416 substitutionGroup => 'gml:_Feature' } );
417 }
418
419 $writer->close_element();
420 $writer->stream($self->{responder});
421 }
422  
423 =pod
424  
425 =head3 GetPropertyValue
426  
427 Not yet implemented.
428  
429 =cut
430  
431 sub GetPropertyValue {
432 }
433  
434 =pod
435  
436 =head3 GetFeature
437  
438 Service the GetFeature request. The response is generated with the GML
439 driver of GDAL using options TARGET_NAMESPACE, PREFIX, and
440 FORMAT. They are from the root of the configuration (TARGET_NAMESPACE
441 from FeatureType falling back to root) falling back to default ones
442 "http://www.opengis.net/wfs", "wfs", and "GML3.2". The content type of
443 the reponse is from configuration (root key 'Content-Type') falling
444 back to default "text/xml".
445  
446 The "gml:id" attribute of the features is GDAL generated or from a
447 field defined by the key "gml:id" in the configuration (in the hash
448 with layer name falling back to FeatureType).
449  
450 =cut
451  
452 sub GetFeature {
453 my ($self) = @_;
454  
455 my $query = $self->{request}{queries}[0]; # actually we should loop through all queries?
456 my ($typename) = split(/\s*,\s*/, $query->{typename});
457
458 unless ($typename) {
459 $self->error({ exceptionCode => 'MissingParameterValue',
460 locator => 'typeName' },
461 [$self->CORS]);
462 return;
463 }
464  
465 my $type;
466 eval {
467 $type = $self->get_feature_type($typename);
468 };
469 unless ($type) {
470 $@ =~ s/ at \/.*//;
471 $self->error({ exceptionCode => 'InvalidParameterValue',
472 locator => 'typeName',
473 ExceptionText => $@ },
474 [$self->CORS]);
475 return;
476 }
477  
478 my $ds = Geo::OGR::Open($type->{DataSource});
479 my $layer;
480 my $epsg = $query->{EPSG} // $type->{SRID};
481  
482 my @bbox;
483 my $bbox_crs;
484 if ($query->{BBOX}) {
485 @bbox = @{$query->{BBOX}};
486 $bbox_crs = 4326; # WFS 1.1.0 14.3.3
487 if (@bbox == 5) {
488 $bbox_crs = epsg_number(pop @bbox);
489 }
490 }
491  
492 my $filter = filter2sql($query->{filter}, $type) // '';
493  
494 # pseudo_credentials: these fields are required to be in the filter and they are not included as attributes
495 my ($pseudo_credentials, @pseudo_credentials) = pseudo_credentials($type);
496 if (@pseudo_credentials) {
497 # test for pseudo credentials in filter
498 my $pat1 = "\\(\\(\"$pseudo_credentials[0]\" = '.+?'\\) AND \\(\"$pseudo_credentials[1]\" = '.+?'\\)\\)";
499 my $pat2 = "\\(\\(\"$pseudo_credentials[1]\" = '.+?'\\) AND \\(\"$pseudo_credentials[0]\" = '.+?'\\)\\)";
500 my $n = join(' and ', @pseudo_credentials);
501 unless ($filter and ($filter =~ /$pat1/ or $filter =~ /$pat2/)) {
502 $self->error({ exceptionCode => 'InvalidParameterValue',
503 locator => 'filter',
504 ExceptionText => "Not authorized. Please provide '$n' in filter." });
505 return;
506 }
507 }
508  
509 my @columns = ("$type->{'gml:id'} as gml_id");
510 # reverse the field names
511 for my $column (keys %{$type->{columns}}) {
512 next if $pseudo_credentials->{$column};
513 my $name = $type->{columns}{$column}{out_name};
514 next if $query->{properties} && not $query->{properties}{$name};
515
516 $filter =~ s/$name/$column/g if $filter;
517 push @columns, "\"$column\" as \"$name\"";
518 }
519 my $Geometry = $type->{GeometryColumn};
520 push @columns, "ST_Transform($Geometry,$epsg) as geometryProperty";
521
522 my $sql = "SELECT ".join(',',@columns)." FROM $type->{Table} WHERE ST_IsValid($Geometry)";
523
524 if ($filter) {
525 $filter =~ s/GeometryColumn/$Geometry/g;
526 $sql .= " AND $filter";
527 }
528
529 if (@bbox) {
530 my $bbox = join(",", @bbox);
531 $sql .= " AND (ST_Transform($Geometry,$epsg) && ST_Transform(ST_MakeEnvelope($bbox,$bbox_crs),$epsg))";
532 }
533
534 print STDERR "$sql\n" if $self->{debug};
535 eval {
536 $layer = $ds->ExecuteSQL($sql);
537 };
538 unless ($layer) {
539 say STDERR $sql,"\n",$@;
540 $self->error({ exceptionCode => 'Error',
541 ExceptionText => 'Internal error' });
542 return;
543 }
544  
545 my $i = 0;
546 my $count = min($query->{count}, $self->{config}{max_count}, 1000000);
547 my $result_type = $query->{resulttype} // 'results'; # real data instead of number of features
548 my ($content_type, $driver);
549  
550 # for GML creation options see http://www.gdal.org/drv_gml.html
551 # for GeoJSON creation options see http://www.gdal.org/drv_geojson.html
552  
553 # the FORMAT, TARGET_NAMESPACE, and PREFIX need to be set for OpenLayers
554 # the following has worked
555 # OpenLayers 2: FORMAT (not set), TARGET_NAMESPACE (http://ogr.maptools.org/), and PREFIX (ogr)
556 # OpenLayers 4: FORMAT (GML3), TARGET_NAMESPACE (http://www.opengis.net/gml), and PREFIX (ogr)
557  
558 # tweaked GML is for getting transactions to work with OpenLayers v4
559  
560 my %creation_options;
561 $creation_options{FORMAT} = $self->{request}{outputformat} // $self->{config}{FORMAT} // $type->{FORMAT} // 'GML2';
562 for my $format ($creation_options{FORMAT}) {
563 # convert some known values to those understood by GDAL
564 $format = $OutputFormats{$format} if $format && $OutputFormats{$format};
565 if ($format =~ /GML/) {
566 for my $key (@GDAL_GML_Creation_options) {
567 next if $key eq 'FORMAT';
568 next unless exists $type->{$key} || exists $self->{config}{$key};
569 $creation_options{$key} = $type->{$key} // $self->{config}{$key};
570 }
571 $content_type = $self->{config}{'Content-Type'} // 'text/xml; charset=utf-8';
572 $driver = Geo::OGR::Driver('GML');
573 } elsif ($format =~ /JSON/) {
574 $content_type = 'application/json; charset=utf-8';
575 $driver = Geo::OGR::Driver('GeoJSON');
576 } else {
577 $self->error({ exceptionCode => 'Error',
578 locator => 'outputFormat',
579 ExceptionText => "Format '$format' is not supported." });
580 return;
581 }
582 }
583  
584 my $writer = $self->{responder}->([200, [ 'Content-Type' => $content_type, $self->CORS ]]);
585 my $output = $driver->Create($writer, \%creation_options );
586
587 my $l2 = $output->CreateLayer($type->{Name});
588 my $d = $layer->GetLayerDefn;
589 for (0..$d->GetFieldCount-1) {
590 my $f = $d->GetFieldDefn($_);
591 $l2->CreateField($f);
592 }
593 $layer->ResetReading;
594 while (my $f = $layer->GetNextFeature) {
595 $l2->CreateFeature($f);
596 $i++;
597 last if defined $count and $i >= $count;
598 }
599
600 print STDERR "$i features served, max is $count\n" if $self->{debug};
601 }
602  
603 =pod
604  
605 =head3 GetFeatureWithLock
606  
607 Not yet implemented.
608  
609 =cut
610  
611 sub GetFeatureWithLock {
612 }
613  
614 =pod
615  
616 =head3 LockFeature
617  
618 Not yet implemented.
619  
620 =cut
621  
622 sub LockFeature {
623 }
624  
625 =pod
626  
627 =head3 Transaction
628  
629 Service the Transaction request. Transaction support is only
630 implemented for PostgreSQL data sources. "Replace" operations
631 are not yet supported.
632  
633 =cut
634  
635 sub Transaction {
636 my ($self) = @_;
637 my $dbisql;
638 eval {
639 $dbisql = $self->transaction_sql;
640 };
641 unless ($dbisql) {
642 $@ =~ s/ at \/.*//;
643 $self->error({ exceptionCode => 'Error building transaction SQL',
644 ExceptionText => $@ });
645 return;
646 }
647 my %rows = (
648 Insert => 0,
649 Update => 0,
650 Replace => 0,
651 Delete => 0
652 );
653 my %results = (
654 Insert => [],
655 Update => [],
656 Replace => [],
657 Delete => []
658 );
659 my $version2 = $self->{version} =~ /^2/;
660 for my $dbi (keys %$dbisql) {
661 my ($db, $user, $pass) = split / /, $dbi;
662 my $dbh = DBI->connect($db, $user, $pass);
663 if ($dbh) {
664 my $error;
665 try:
666 for my $op (keys %{$dbisql->{$dbi}}) {
667 for my $i (0..$#{$dbisql->{$dbi}{$op}{SQL}}) {
668 my $sql = $dbisql->{$dbi}{$op}{SQL}[$i];
669 my $type = $dbisql->{$dbi}{$op}{type}[$i];
670 my $rows = $dbh->do($sql);
671 if ($rows) {
672 my $id = '';
673 $id = $dbh->last_insert_id(undef, $type->{schema}, $type->{table}, undef) if $op eq 'Insert';
674 my @id = $version2 ? ('fes:ResourceId' => {rid => $id}) : ('ogc:FeatureId' => {fid => $id});
675 push @{$results{$op}}, ['wfs:Feature', [\@id]];
676 $rows{$op} += ($rows == 0) ? 1 : $rows;
677 } else {
678 $error .= $dbh->errstr;
679 last try;
680 }
681 }
682 }
683 if ($error) {
684 $self->error({ exceptionCode => 'Error executing transaction SQL',
685 ExceptionText => $error });
686 last;
687 }
688 } else {
689 $self->error({ exceptionCode => 'Database connection error',
690 ExceptionText => "Can't connect to database '$db'" });
691 }
692 }
693
694 my $writer = Geo::OGC::Service::XMLWriter::Caching->new([$self->CORS]);
695 my %ns = $version2 ? (%wfs_2_0_0_ns) : (%wfs_1_1_0_ns);
696 $ns{version} = $self->{version};
697 $writer->open_element('wfs:TransactionResponse' => \%ns);
698 $writer->element('wfs:TransactionSummary',
699 [['wfs:totalInserted' => $rows{Insert}],
700 ['wfs:totalUpdated' => $rows{Update}],
701 ['wfs:totalReplaced' => $rows{Replace}],
702 ['wfs:totalDeleted' => $rows{Delete}]
703 ]);
704 for my $op (keys %results) {
705 $writer->element('wfs:'.$op.'Results', $results{$op}) if @{$results{$op}};
706 }
707 $writer->close_element;
708 $writer->stream($self->{responder});
709 }
710  
711 =pod
712  
713 =head3 CreateStoredQuery
714  
715 Not yet implemented.
716  
717 =cut
718  
719 sub CreateStoredQuery {
720 }
721  
722 =pod
723  
724 =head3 DropStoredQuery
725  
726 Not yet implemented.
727  
728 =cut
729  
730 sub DropStoredQuery {
731 }
732  
733 =pod
734  
735 =head3 ListStoredQueries
736  
737 Not yet implemented.
738  
739 =cut
740  
741 sub ListStoredQueries {
742 }
743  
744 =pod
745  
746 =head3 DescribeStoredQueries
747  
748 Not yet implemented.
749  
750 =cut
751  
752 sub DescribeStoredQueries {
753 }
754  
755 # "private" methods below, these may use croak
756  
757 # parse request from posted, parameters, config
758 # into version, request
759 # filter is not parsed because type object is not available
760 sub parse_request {
761 my $self = shift;
762 my @queries;
763 if ($self->{posted}) {
764 $self->{request} = ogc_request($self->{posted});
765 } elsif ($self->{parameters}) {
766 $self->{request} = {
767 request => $self->{parameters}{request},
768 version => $self->{parameters}{version},
769 outputformat => $self->{parameters}{outputformat},
770 queries => [
771 {
772 # typenames is WFS 2, and can be a space separated list
773 typename => ($self->{parameters}{typename} // $self->{parameters}{typenames}),
774 filter => $self->{filter},
775 EPSG => epsg_number($self->{parameters}{srsname}),
776 count => get_integer($self->{parameters}{count}, $self->{parameters}{maxfeatures}),
777 BBOX => split_to_listref($self->{parameters}{bbox})
778 }
779 ]
780 };
781 $self->{request}{outputformat} = 'GML2' if $self->{request}{version} && $self->{request}{version} eq '1.0.0';
782 }
783  
784 my %defaults = (
785 version => '2.0.0',
786 Title => 'WFS Server',
787 );
788 for my $key (keys %defaults) {
789 $self->{config}{$key} //= $defaults{$key};
790 }
791 for my $key (qw/resource ServiceTypeVersion/) {
792 $self->{config}{$key} //= '';
793 }
794 # version negotiation
795 $self->{version} =
796 latest_version($self->{parameters}{acceptversions}) // # not in standard, QGIS WFS 2.0 Client uses
797 $self->{request}{version} //
798 $self->{config}{version};
799 }
800  
801 sub get_feature_type {
802 my ($self, $typename) = @_;
803 $typename =~ s/^\w+://; # remove possible namespace
804 $self->read_feature_type_list unless $self->{feature_types} && @{$self->{feature_types}};
805 for my $t (@{$self->{feature_types}}) {
806 for my $t2 (@$t) {
807 if ($t2->{Name} eq $typename) {
808 return $t2;
809 }
810 }
811 }
812 croak "Feature type '$typename' is not available.";
813 }
814  
815 # read FeatureTypeList from config and create
816 # feature_types as an array of arrays of feature_types
817 # a feature_type should contain information for
818 # operations (GetCapabilities etc)
819 # this sub parses the FeatureTypeList of config
820 # TO DO: make this boot time thing
821 sub read_feature_type_list {
822 my $self = shift;
823  
824 # to do: basic config
825 $self->{config}{targetNamespace} //= $self->{config}{resource};
826
827 $self->{feature_types} = [];
828 for my $type (@{$self->{config}{FeatureTypeList}}) {
829 if ($type->{require_user}) {
830 # simple test now
831 # also, this should probably be runtime check
832 next unless $self->{env}{REMOTE_USER} eq $type->{require_user};
833 }
834 if (exists $type->{DataSource} and $type->{DataSource} =~ /^pg:/i) {
835 push @{$self->{feature_types}}, $self->feature_types_in_data_source($type);
836 } else {
837 carp "Only PostgreSQL data sources supported in FeatureTypeList.";
838 }
839 }
840 for my $type (@{$self->{feature_types}}) {
841 for my $t (@$type) {
842 for my $in_name (keys %{$t->{columns}}) {
843 my $in_type = $t->{columns}{$in_name}{in_type};
844 my $out_type = $type_map{$in_type} // 'xs:string';
845 my $out_name = $in_name;
846  
847 # field name adjustments as GDAL does them
848 $out_name =~ s/[ -] /_/g;
849
850 # extra name adjustments, maybe needed by old QGIS?
851 if ($self->{config}{no_scands_in_names}) {
852 $out_name =~ s/[åö]/o/g;
853 $out_name =~ s/ä/a/g;
854 $out_name =~ s/[ÅÖ]/O/g;
855 $out_name =~ s/Ä/A/g;
856 }
857  
858 $t->{columns}{$in_name}{out_name} = $out_name;
859 $t->{columns}{$in_name}{out_type} = $out_type;
860 }
861 }
862 }
863 }
864  
865 sub feature_types_in_data_source {
866 my ($self, $type) = @_;
867 my @types;
868 my $ds = $type->{DataSource};
869 my $dbi = DataSource2dbi($ds);
870 my ($db, $user, $pass) = split / /, $dbi;
871 my $dbh = DBI->connect($db, $user, $pass, {PrintError => 0}) or return;
872 # SCHEMA and TABLE are search patterns or not set, for example: "FOO%"
873 my $schema = $type->{SCHEMA} // 'public';
874 # TABLE_TYPE is a Perl DBI attribute
875 my $table = $type->{TABLE};
876 my $table_type = $type->{TABLE_TYPE} // "'TABLE','VIEW'";
877 my $sth = $dbh->table_info('', $schema, $table, $table_type);
878 my @tables;
879 while (my $data = $sth->fetchrow_hashref) {
880 my $schema = $data->{TABLE_SCHEM};
881 my $table = $data->{TABLE_NAME};
882 for ($schema, $table) {
883 s/^"//;
884 s/"$//;
885 }
886 my $name = "\"$schema\".\"$table\"";
887 push @tables, [$schema, $table, $name, "$schema.$table"];
888 }
889 my %pk_type = (
890 smallint => 1,
891 integer => 1,
892 bigint => 1
893 );
894 for my $table (@tables) {
895 # require a readable table with single integer pk and geometry column(s) with SRS
896 my %columns;
897 my %geometries;
898 my @pk;
899 # setting gml:id is a way to include views
900 if ($type->{'gml:id'}) {
901 @pk = ($type->{'gml:id'});
902 } else {
903 @pk = $dbh->primary_key('', @$table[0,1]);
904 }
905 if (@pk == 1) {
906 $pk[0] =~ s/^"//;
907 $pk[0] =~ s/"$//;
908 my $pk_exists = 0;
909 $sth = $dbh->column_info('', @$table[0,1], '');
910 while (my $data = $sth->fetchrow_hashref) {
911 my $col = $data->{COLUMN_NAME};
912 $col =~ s/^"//;
913 $col =~ s/"$//;
914 if ($col eq $pk[0]) {
915 if ($pk_type{$data->{TYPE_NAME}}) {
916 $pk_exists = 1;
917 } else {
918 if ($self->{debug} > 3) {
919 say STDERR "$table->[3]: PK is not integer";
920 }
921 %geometries = ();
922 last;
923 }
924 } elsif ($data->{TYPE_NAME} eq 'geometry') {
925 $geometries{$col} = 1;
926 } else {
927 $columns{$col}{in_type} = $data->{TYPE_NAME};
928 }
929 }
930 unless ($pk_exists) {
931 if ($self->{debug} > 3) {
932 say STDERR "$table->[3]: 'gml:id ($pk[0]) does not exist in the table";
933 }
934 %geometries = ();
935 }
936 } elsif ($self->{debug} > 3) {
937 say STDERR "$table->[3] does not have single PK, maybe use gml:id in config?";
938 }
939 for my $geom (keys %geometries) {
940 my $ok;
941 my $sql = "select auth_name,auth_srid from $table->[2] ".
942 "join spatial_ref_sys on spatial_ref_sys.srid=st_srid(\"$geom\") ".
943 "limit 1";
944 $sth = $dbh->prepare($sql);
945 if ($sth) {
946 my $rv = $sth->execute;
947 if ($rv) {
948 my ($auth_name, $auth_srid) = $sth->fetchrow_array;
949 $auth_name //= 'undef';
950 $auth_srid //= 'undef';
951 $geometries{$geom} = [$auth_name, $auth_srid];
952 if ($auth_name eq 'EPSG' && $auth_srid) {
953 $ok = 1;
954 } elsif ($self->{debug} > 3) {
955 say STDERR "$table->[3]: auth of $geom is $auth_name:$auth_srid (is it empty?)";
956 }
957 } elsif ($self->{debug} > 3) {
958 say STDERR "$table->[3]: no permission";
959 }
960 }
961 delete $geometries{$geom} unless $ok;
962 }
963 unless (%geometries) {
964 if ($self->{debug} > 2) {
965 say STDERR "$table->[3]: is not readable with single integer pk and geometry column(s) with EPSG SRS";
966 }
967 next;
968 }
969  
970 for my $geom (keys %geometries) {
971
972 my $name = $table->[3].'.'.$geom;
973 $name =~ s/ /_/g; # XML layer names can't have spaces
974  
975 my $feature_type = {
976 Name => $name,
977 Title => $name,
978 Abstract => "Layer from $table->[1] in $table->[0] using column $geom.",
979 DefaultSRS => $geometries{$geom}[0].":".$geometries{$geom}[1],
980 SRID => $geometries{$geom}[1],
981 DataSource => $ds,
982 Table => $table->[2], # full quoted name with schema
983 GeometryColumn => '"'.$geom.'"',
984 columns => \%columns,
985 'gml:id' => $pk[0],
986 Operations => $type->{Operations}, # $self->{config}{Operations} is the default
987 require_user => $type->{require_user} // $self->{config}{require_user}, # operation dependent?
988 pseudo_credentials => $type->{pseudo_credentials},
989 # to do: these in ows:WGS84BoundingBox, GetCapabilities
990 #LowerCorner
991 #UpperCorner
992 };
993 for my $o (@GDAL_GML_Creation_options) {
994 $feature_type->{$o} = $type->{$o} if exists $type->{$o};
995 }
996  
997 my ($h, @c) = pseudo_credentials($feature_type);
998 my $ok = 1;
999 for my $c (@c) {
1000 unless ($feature_type->{columns}{$c}) {
1001 carp "pseudo credential column '$c' not in table.\n";
1002 $ok = 0;
1003 next;
1004 }
1005 }
1006 next unless $ok;
1007 push @types, $feature_type;
1008 }
1009 }
1010 #print STDERR Dumper \@types;
1011 return \@types;
1012 }
1013  
1014 # return WFS request in a hash
1015 # this function is written according to WFS 1.1.0 / 2.0.0
1016 sub ogc_request {
1017 my ($node) = @_;
1018 my ($ns, $name) = parse_tag($node);
1019 if ($name eq 'GetCapabilities') {
1020 return { service => $node->getAttribute('service'),
1021 request => $name,
1022 version => $node->getAttribute('version') };
1023  
1024 } elsif ($name eq 'DescribeFeatureType') {
1025 my $request = { service => $node->getAttribute('service'),
1026 request => $name,
1027 version => $node->getAttribute('version') };
1028 $request->{queries} = [];
1029 for ($node = $node->firstChild; $node; $node = $node->nextSibling) {
1030 my ($ns, $name) = parse_tag($node);
1031 if ($name eq 'TypeName') {
1032 push @{$request->{queries}}, { typename => $node->textContent };
1033 }
1034 }
1035 return $request;
1036  
1037 } elsif ($name eq 'GetFeature') {
1038 my $request = { request => 'GetFeature' };
1039 for my $a (qw/service version resultType outputFormat count maxFeatures/) {
1040 my %map = (maxFeatures => 'count');
1041 my $key = $map{$a} // $a;
1042 my $b = $node->getAttribute($a);
1043 $request->{lc($key)} = $b if $b;
1044 }
1045 $request->{queries} = [];
1046 for ($node = $node->firstChild; $node; $node = $node->nextSibling) {
1047 push @{$request->{queries}}, ogc_request($node);
1048 }
1049 return $request;
1050  
1051 } elsif ($name eq 'Transaction') {
1052 my $request = { request => 'Transaction' };
1053 for my $a (qw/service version/) {
1054 my $b = $node->getAttribute($a);
1055 $request->{$a} = $b if $b;
1056 }
1057 for ($node = $node->firstChild; $node; $node = $node->nextSibling) {
1058 my $name = $node->nodeName;
1059 $name =~ s/^wfs://;
1060 $request->{$name} = [] unless $request->{$name};
1061 if ($name eq 'Insert') {
1062 for (my $n = $node->firstChild; $n; $n = $n->nextSibling) {
1063 push @{$request->{$name}}, $n;
1064 }
1065 } else {
1066 push @{$request->{$name}}, $node;
1067 }
1068 }
1069 return $request;
1070  
1071 } elsif ($name eq 'Query') {
1072 my $query = {};
1073 for my $a (qw/typeName typeNames srsName/) {
1074 my %map = (typeNames => 'typeName');
1075 my $key = $map{$a} // $a;
1076 my $b = $node->getAttribute($a);
1077 $query->{lc($key)} = $b if $b;
1078 }
1079 if (defined $query->{srsname}) {
1080 $query->{EPSG} = epsg_number($query->{srsname});
1081 }
1082 for my $property ($node->getChildrenByTagNameNS('*', 'PropertyName')) {
1083 $query->{properties} = {} unless $query->{properties};
1084 $query->{properties}{strip($property->textContent)} = 1;
1085 }
1086 for my $filter ($node->getChildrenByTagNameNS('*', 'Filter')) {
1087 $query->{filter} = $filter; # there is only one filter
1088 }
1089 return $query;
1090  
1091 }
1092 return {};
1093 }
1094  
1095 # convert OGC Transaction XML to SQL
1096 sub transaction_sql {
1097 my ($self) = @_;
1098 my $get_type = sub {
1099 my $name = shift;
1100 my $type = $self->get_feature_type($name);
1101 my $dbi = DataSource2dbi($type->{DataSource});
1102 return ($name, $type, $dbi);
1103 };
1104 my $get_filter = sub {
1105 my ($node, $type) = @_;
1106 my $where = '';
1107 for my $filter ($node->getChildrenByTagNameNS('*', 'Filter')) {
1108 $where = filter2sql($filter, $type);
1109 }
1110 return $where;
1111 };
1112 my %dbisql;
1113 for my $node (@{$self->{request}{Insert}}) {
1114 my ($type_name, $type, $dbi) = $get_type->($node->nodeName);
1115 next unless $type_name;
1116 my @cols;
1117 my @vals;
1118 for (my $field = $node->firstChild; $field; $field = $field->nextSibling) {
1119 my ($ns, $name) = parse_tag($field);
1120 my $col;
1121 my $val;
1122 if ($name eq 'geometry' or $name eq 'geometryProperty' or $name eq 'null') {
1123 $col = $type->{GeometryColumn};
1124 $val = node2sql($field->firstChild);
1125 } else {
1126 for my $c (keys %{$type->{columns}}) {
1127 $col = $c if $name eq $type->{columns}{$c}{out_name};
1128 }
1129 next unless $col;
1130 $col = '"'.$col.'"';
1131 $val = $field->firstChild->data;
1132 $val = "'".$val."'";
1133 }
1134 unless ($col) {
1135 say STDERR "Can't find column name for property '$name'.";
1136 next;
1137 }
1138 push @cols, $col;
1139 push @vals, $val;
1140 }
1141 my $cols = join(',',@cols);
1142 my $vals = join(',',@vals);
1143 say STDERR "Insert: ($cols) VALUES ($vals)" if $self->{debug} > 1;
1144 push @{$dbisql{$dbi}{Insert}{SQL}}, "INSERT INTO $type->{Table} ($cols) VALUES ($vals)";
1145 push @{$dbisql{$dbi}{Insert}{type}}, $type;
1146 }
1147 for my $node (@{$self->{request}{Update}}) {
1148 my ($type_name, $type, $dbi) = $get_type->($node->getAttribute('typeName'));
1149 next unless $type_name;
1150 my $set;
1151 for my $property ($node->getChildrenByTagNameNS('*', 'Property')) {
1152 # 1.1 Name and Value
1153 # 2.0 ValueReference and Value
1154 my $col;
1155 my @name = $property->getChildrenByTagNameNS('*', 'Name');
1156 @name = $property->getChildrenByTagNameNS('*', 'ValueReference') unless @name;
1157 unless (@name) {
1158 say STDERR "Can't find Name nor ValueReference.";
1159 next;
1160 }
1161 my $name = $name[0]->textContent();
1162 $name =~ s/^\w+://; # remove namespace
1163 $name =~ s/^\w+\///; # remove type name
1164 next if $name eq $type->{"gml:id"};
1165 my @val = $property->getChildrenByTagNameNS('*', 'Value');
1166 my $val;
1167 if ($name eq 'geometry' or $name eq 'geometryProperty' or $name eq 'null') {
1168 $col = $type->{GeometryColumn};
1169 $val = @val ? node2sql($val[0]->firstChild) : 'NULL';
1170 } else {
1171 for my $c (keys %{$type->{columns}}) {
1172 $col = $c if $name eq $type->{columns}{$c}{out_name};
1173 }
1174 $col = '"'.$col.'"' if $col;
1175 $val = @val ? "'".$val[0]->textContent()."'" : 'NULL';
1176 }
1177 unless ($col) {
1178 say STDERR "Can't find column name for property '$name'.";
1179 next;
1180 }
1181 $set .= "$col = $val, ";
1182 }
1183 $set =~ s/, $//;
1184 my $where = $get_filter->($node, $type);
1185 say STDERR "Update: SET $set WHERE $where" if $self->{debug} > 1;
1186 push @{$dbisql{$dbi}{Update}{SQL}}, "UPDATE $type->{Table} SET $set WHERE $where";
1187 push @{$dbisql{$dbi}{Update}{type}}, $type;
1188 }
1189 for my $node (@{$self->{request}{Delete}}) {
1190 my ($type_name, $type, $dbi) = $get_type->($node->getAttribute('typeName'));
1191 next unless $type_name;
1192 my $where = $get_filter->($node, $type);
1193 say STDERR "Delete: $where" if $self->{debug} > 1;
1194 push @{$dbisql{$dbi}{Delete}{SQL}}, "DELETE FROM $type->{Table} WHERE $where";
1195 push @{$dbisql{$dbi}{Delete}{type}}, $type;
1196 }
1197 return \%dbisql;
1198 }
1199  
1200 # determine the EPSG number
1201 sub epsg_number {
1202 my $str = shift;
1203 return undef unless $str;
1204 my ($epsg) = $str =~ /^EPSG:(\d+)$/;
1205 return $epsg if $epsg;
1206 }
1207  
1208 sub DataSource2dbi {
1209 my $DataSource = shift;
1210 my $dbi = $DataSource;
1211 $dbi =~ s/^pg/Pg/i;
1212 $dbi =~ s/ host/;host/;
1213 $dbi =~ s/ port/;port/;
1214 $dbi =~ s/ options/;options/;
1215 $dbi =~ s/user=//;
1216 $dbi =~ s/password=//;
1217 return 'dbi:'.$dbi;
1218 }
1219  
1220 sub split_to_listref {
1221 my $s = shift;
1222 return undef unless $s;
1223 return [split /\s*,\s*/, $s];
1224 }
1225  
1226 sub list2element {
1227 my ($tag, $list) = @_;
1228 my @element;
1229 my @t = split /\s*,\s*/, $list;
1230 for my $t (@t) {
1231 push @element, [$tag, $t];
1232 }
1233 return @element;
1234 }
1235  
1236 sub pseudo_credentials {
1237 my $type = shift;
1238 my $c = $type->{pseudo_credentials};
1239 return ({}) unless $c;
1240 my($c1,$c2) = $c =~ /(\w+),(\w+)/;
1241 return ({$c1 => 1,$c2 => 1},$c1,$c2);
1242 }
1243  
1244 sub min {
1245 my $retval = shift;
1246 for my $x (@_) {
1247 next unless defined $x;
1248 $retval = $x unless defined $retval;
1249 $retval = $x if $x < $retval;
1250 }
1251 return $retval;
1252 }
1253  
1254 1;
1255 __END__