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