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