added the state filtering stuff
[spider.git] / perl / Prefix.pm
1 #
2 # prefix handling
3 #
4 # Copyright (c) - Dirk Koopman G1TLH
5 #
6 # $Id$
7 #
8
9 package Prefix;
10
11 use IO::File;
12 use DXVars;
13 use DB_File;
14 use Data::Dumper;
15 use DXDebug;
16 use DXUtil;
17 use USDB;
18 use LRU;
19
20 use strict;
21
22 use vars qw($VERSION $BRANCH);
23 $VERSION = sprintf( "%d.%03d", q$Revision$ =~ /(\d+)\.(\d+)/ );
24 $BRANCH = sprintf( "%d.%03d", q$Revision$ =~ /\d+\.\d+\.(\d+)\.(\d+)/  || (0,0));
25 $main::build += $VERSION;
26 $main::branch += $BRANCH;
27
28 use vars qw($db %prefix_loc %pre $lru $lrusize $misses $hits $matchtotal);
29
30 $db = undef;                                    # the DB_File handle
31 %prefix_loc = ();                               # the meat of the info
32 %pre = ();                                              # the prefix list
33 $hits = $misses = $matchtotal = 1;              # cache stats
34 $lrusize = 2000;                                # size of prefix LRU cache
35
36 $lru = LRU->newbase('Prefix', $lrusize);
37
38 sub load
39 {
40         # untie every thing
41         if ($db) {
42                 undef $db;
43                 untie %pre;
44                 %pre = ();
45                 %prefix_loc = ();
46         }
47
48         # tie the main prefix database
49         $db = tie(%pre, "DB_File", undef, O_RDWR|O_CREAT, 0664, $DB_BTREE) or confess "can't tie \%pre ($!)";  
50         my $out = $@ if $@;
51         do "$main::data/prefix_data.pl" if !$out;
52         $out = $@ if $@;
53
54         return $out;
55 }
56
57 sub store
58 {
59         my ($k, $l);
60         my $fh = new IO::File;
61         my $fn = "$main::data/prefix_data.pl";
62   
63         confess "Prefix system not started" if !$db;
64   
65         # save versions!
66         rename "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
67         rename "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
68         rename "$fn.oo", "$fn.ooo" if -e "$fn.oo";
69         rename "$fn.o", "$fn.oo" if -e "$fn.o";
70         rename "$fn", "$fn.o" if -e "$fn";
71   
72         $fh->open(">$fn") or die "Can't open $fn ($!)";
73
74         # prefix location data
75         $fh->print("%prefix_loc = (\n");
76         foreach $l (sort {$a <=> $b} keys %prefix_loc) {
77                 my $r = $prefix_loc{$l};
78                 $fh->printf("   $l => bless( { name => '%s', dxcc => %d, itu => %d, utcoff => %d, lat => %f, long => %f }, 'Prefix'),\n",
79                                         $r->{name}, $r->{dxcc}, $r->{itu}, $r->{cq}, $r->{utcoff}, $r->{lat}, $r->{long});
80         }
81         $fh->print(");\n\n");
82
83         # prefix data
84         $fh->print("%pre = (\n");
85         foreach $k (sort keys %pre) {
86                 $fh->print("   '$k' => [");
87                 my @list = @{$pre{$k}};
88                 my $l;
89                 my $str;
90                 foreach $l (@list) {
91                         $str .= " $l,";
92                 }
93                 chop $str;  
94                 $fh->print("$str ],\n");
95         }
96         $fh->print(");\n");
97         undef $fh;
98         untie %pre; 
99 }
100
101 # what you get is a list that looks like:-
102
103 # prefix => @list of blessed references to prefix_locs 
104 #
105 # This routine will only do what you ask for, if you wish to be intelligent
106 # then that is YOUR problem!
107 #
108
109 sub get
110 {
111         my $key = shift;
112         my $ref;
113         my $gotkey = $key;
114         return () if $db->seq($gotkey, $ref, R_CURSOR);
115         return () if $key ne substr $gotkey, 0, length $key;
116
117         return ($gotkey,  map { $prefix_loc{$_} } split ',', $ref);
118 }
119
120 #
121 # get the next key that matches, this assumes that you have done a 'get' first
122 #
123
124 sub next
125 {
126         my $key = shift;
127         my $ref;
128         my $gotkey;
129   
130         return () if $db->seq($gotkey, $ref, R_NEXT);
131         return () if $key ne substr $gotkey, 0, length $key;
132   
133         return ($gotkey,  map { $prefix_loc{$_} } split ',', $ref);
134 }
135
136 #
137 # put the key LRU incluing the city state info
138 #
139
140 sub lru_put
141 {
142         my ($call, $ref) = @_;
143         my @s = USDB::get($call);
144         
145         if (@s) {
146                 # this is deep magic, because this is a reference to static data, it
147         # must be copied.
148                 my $h = { %{$ref->[1]} };
149                 bless $h, ref $ref->[1];
150                 $h->{city} = $s[0];
151                 $h->{state} = $s[1];
152                 $ref->[1] = $h;
153         } else {
154                 $ref->[1]->{city} = $ref->[1]->{state} = "" unless exists $ref->[1]->{state};
155         }
156         
157         dbg("Prefix::lru_put $call -> ($ref->[1]->{city}, $ref->[1]->{state})") if isdbg('prefix');
158         $lru->put($call, $ref);
159 }
160
161
162 # search for the nearest match of a prefix string (starting
163 # from the RH end of the string passed)
164 #
165
166 sub matchprefix
167 {
168         my $pref = shift;
169         my @partials;
170
171         for (my $i = length $pref; $i; $i--) {
172                 $matchtotal++;
173                 my $s = substr($pref, 0, $i);
174                 push @partials, $s;
175                 my $p = $lru->get($s);
176                 if ($p) {
177                         $hits++;
178                         if (isdbg('prefix')) {
179                                 my $percent = sprintf "%.1f", $hits * 100 / $misses;
180                                 dbg("Partial Prefix Cache Hit: $s Hits: $hits/$misses of $matchtotal = $percent\%");
181                         }
182                         lru_put($_, $p) for @partials;
183                         return @$p;
184                 } else {
185                         $misses++;
186                         my @out = get($s);
187                         if (isdbg('prefix')) {
188                                 my $part = $out[0] || "*";
189                                 $part .= '*' unless $part eq '*' || $part eq $s;
190                                 dbg("Partial prefix: $pref $s $part" );
191                         } 
192                         if (@out && $out[0] eq $s) {
193                                 return @out;
194                         } 
195                 }
196         }
197         return ();
198 }
199
200 #
201 # extract a 'prefix' from a callsign, in other words the largest entity that will
202 # obtain a result from the prefix table.
203 #
204 # This is done by repeated probing, callsigns of the type VO1/G1TLH or
205 # G1TLH/VO1 (should) return VO1
206 #
207
208 sub extract
209 {
210         my $calls = uc shift;
211         my @out;
212         my $p;
213         my @parts;
214         my ($call, $sp, $i);
215
216 LM:     foreach $call (split /,/, $calls) {
217
218                 # first check if the whole thing succeeds either because it is cached
219                 # or because it simply is a stored prefix as callsign (or even a prefix)
220                 $matchtotal++;
221                 $call =~ s/-\d+$//;             # ignore SSIDs
222                 my $p = $lru->get($call);
223                 my @nout;
224                 if ($p) {
225                         $hits++;
226                         if (isdbg('prefix')) {
227                                 my $percent = sprintf "%.1f", $hits * 100 / $misses;
228                                 dbg("Prefix Cache Hit: $call Hits: $hits/$misses of $matchtotal = $percent\%");
229                         }
230                         push @out, @$p;
231                         next;
232                 } else {
233                         
234                         # is it in the USDB, force a matchprefix to match?
235                         my @s = USDB::get($call);
236                         if (@s) {
237                                 @nout = get($call);
238                                 @nout = matchprefix($call) unless @nout;
239                                 $nout[0] = $call if @nout;
240                         } else {
241                                 @nout =  get($call);
242                         }
243
244                         # now store it
245                         if (@nout && $nout[0] eq $call) {
246                                 $misses++;
247                                 lru_put($call, \@nout);
248                                 dbg("got exact prefix: $nout[0]") if isdbg('prefix');
249                                 push @out, @nout;
250                                 next;
251                         }
252                 }
253
254                 # now split the call into parts if required
255                 @parts = ($call =~ '/') ? split('/', $call) : ($call);
256                 dbg("Parts: $call = " . join(' ', @parts))      if isdbg('prefix');
257
258                 # remove any /0-9 /P /A /M /MM /AM suffixes etc
259                 if (@parts > 1) {
260                         @parts = grep { !/^\d+$/ && !/^[PABM]$/ && !/^(?:|AM|MM|BCN|JOTA|SIX|WEB|NET|Q\w+)$/; } @parts;
261
262                         # can we resolve them by direct lookup
263                         my $s = join('/', @parts); 
264                         @nout = get($s);
265                         if (@nout && $nout[0] eq $s) {
266                                 dbg("got exact multipart prefix: $call $s") if isdbg('prefix');
267                                 $misses++;
268                                 lru_put($call, \@nout);
269                                 push @out, @nout;
270                                 next;
271                         }
272                 }
273                 dbg("Parts now: $call = " . join(' ', @parts))  if isdbg('prefix');
274   
275                 # at this point we should have two or three parts
276                 # if it is three parts then join the first and last parts together
277                 # to get an answer
278
279                 # first deal with prefix/x00xx/single letter things
280                 if (@parts == 3 && length $parts[0] <= length $parts[1]) {
281                         @nout = matchprefix($parts[0]);
282                         if (@nout) {
283                                 my $s = join('/', $nout[0], $parts[2]);
284                                 my @try = get($s);
285                                 if (@try && $try[0] eq $s) {
286                                         dbg("got 3 part prefix: $call $s") if isdbg('prefix');
287                                         $misses++;
288                                         lru_put($call, \@try);
289                                         push @out, @try;
290                                         next;
291                                 }
292                                 
293                                 # if the second part is a callsign and the last part is one letter
294                                 if (is_callsign($parts[1]) && length $parts[2] == 1) {
295                                         pop @parts;
296                                 }
297                         }
298                 }
299
300                 # if it is a two parter 
301                 if (@parts == 2) {
302
303                         # try it as it is as compound, taking the first part as the prefix
304                         @nout = matchprefix($parts[0]);
305                         if (@nout) {
306                                 my $s = join('/', $nout[0], $parts[1]);
307                                 my @try = get($s);
308                                 if (@try && $try[0] eq $s) {
309                                         dbg("got 2 part prefix: $call $s") if isdbg('prefix');
310                                         $misses++;
311                                         lru_put($call, \@try);
312                                         push @out, @try;
313                                         next;
314                                 }
315                         }
316                 }
317
318                 # remove the problematic /J suffix
319                 pop @parts if @parts > 1 && $parts[$#parts] eq 'J';
320
321                 # single parter
322                 if (@parts == 1) {
323                         @nout = matchprefix($parts[0]);
324                         if (@nout) {
325                                 dbg("got prefix: $call = $nout[0]") if isdbg('prefix');
326                                 $misses++;
327                                 lru_put($call, \@nout);
328                                 push @out, @nout;
329                                 next;
330                         }
331                 }
332
333                 # try ALL the parts
334         my @checked;
335                 my $n;
336 L1:             for ($n = 0; $n < @parts; $n++) {
337                         my $sp = '';
338                         my ($k, $i);
339                         for ($i = $k = 0; $i < @parts; $i++) {
340                                 next if $checked[$i];
341                                 my $p = $parts[$i];
342                                 if (!$sp || length $p < length $sp) {
343                                         dbg("try part: $p") if isdbg('prefix');
344                                         $k = $i;
345                                         $sp = $p;
346                                 }
347                         }
348                         $checked[$k] = 1;
349                         $sp =~ s/-\d+$//;     # remove any SSID
350                         
351                         # now start to resolve it from the right hand end
352                         @nout = matchprefix($sp);
353                         
354                         # try and search for it in the descriptions as
355                         # a whole callsign if it has multiple parts and the output
356                         # is more two long, this should catch things like
357                         # FR5DX/T without having to explicitly stick it into
358                         # the prefix table.
359                         
360                         if (@nout) {
361                                 if (@parts > 1) {
362                                         $parts[$k] = $nout[0];
363                                         my $try = join('/', @parts);
364                                         my @try = get($try);
365                                         if (isdbg('prefix')) {
366                                                 my $part = $try[0] || "*";
367                                                 $part .= '*' unless $part eq '*' || $part eq $try;
368                                                 dbg("Compound prefix: $try $part" );
369                                         }
370                                         if (@try && $try eq $try[0]) {
371                                                 $misses++;
372                                                 lru_put($call, \@try);
373                                                 push @out, @try;
374                                         } else {
375                                                 $misses++;
376                                                 lru_put($call, \@nout);
377                                                 push @out, @nout;
378                                         }
379                                 } else {
380                                         $misses++;
381                                         lru_put($call, \@nout);
382                                         push @out, @nout;
383                                 }
384                                 next LM;
385                         }
386                 }
387
388                 # we are a pirate!
389                 @nout = matchprefix('Q');
390                 $misses++;
391                 lru_put($call, \@nout);
392                 push @out, @nout;
393         }
394         
395         if (isdbg('prefixdata')) {
396                 my $dd = new Data::Dumper([ \@out ], [qw(@out)]);
397                 dbg($dd->Dumpxs);
398         }
399         return @out;
400 }
401
402 #
403 # turn a list of prefixes / dxcc numbers into a list of dxcc/itu/zone numbers
404 #
405 # nc = dxcc
406 # ni = itu
407 # nz = zone
408 # ns = state
409 #
410
411 sub to_ciz
412 {
413         my $cmd = shift;
414         my @out;
415         
416         foreach my $v (@_) {
417                 if ($cmd ne 'ns' && $v =~ /^\d+$/) {    
418                         push @out, $v unless grep $_ eq $v, @out;
419                 } else {
420                         if ($cmd eq 'ns' && $v =~ /^[A-Z][A-Z]$/i) {
421                                 push @out, uc $v unless grep $_ eq uc $v, @out;
422                         } else {
423                                 my @pre = Prefix::extract($v);
424                                 if (@pre) {
425                                         shift @pre;
426                                         foreach my $p (@pre) {
427                                                 my $n = $p->dxcc if $cmd eq 'nc' ;
428                                                 $n = $p->itu if $cmd eq 'ni' ;
429                                                 $n = $p->cq if $cmd eq 'nz' ;
430                                                 $n = $p->state if $cmd eq 'ns';
431                                                 push @out, $n unless grep $_ eq $n, @out;
432                                         }
433                                 }
434                         }                       
435                 }
436         }
437         return @out;
438 }
439
440 my %valid = (
441                          lat => '0,Latitude,slat',
442                          long => '0,Longitude,slong',
443                          dxcc => '0,DXCC',
444                          name => '0,Name',
445                          itu => '0,ITU',
446                          cq => '0,CQ',
447                          state => '0,State',
448                          city => '0,City',
449                          utcoff => '0,UTC offset',
450                          cont => '0,Continent',
451                         );
452
453 sub AUTOLOAD
454 {
455         my $self = shift;
456         no strict;
457         my $name = $AUTOLOAD;
458   
459         return if $name =~ /::DESTROY$/;
460         $name =~ s/^.*:://o;
461   
462         confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
463         # this clever line of code creates a subroutine which takes over from autoload
464         # from OO Perl - Conway
465         *$AUTOLOAD = sub {@_ > 1 ? $_[0]->{$name} = $_[1] : $_[0]->{$name}} ;
466         &$AUTOLOAD($self, @_);
467 }
468
469 #
470 # return a prompt for a field
471 #
472
473 sub field_prompt
474
475         my ($self, $ele) = @_;
476         return $valid{$ele};
477 }
478 1;
479
480 __END__