remove Prot.pm, sort %valid fields
[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         $call =~ s/^=//;
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                 $matchtotal++;
250                 $call =~ s/-\d+$//;             # ignore SSIDs
251                 my @nout;
252                 my $ecall = "=$call";
253
254                 # first check if this is a call (by prefixing it with an = sign)
255                 my $p = $lru->get($ecall);
256                 if ($p) {
257                         $hits++;
258                         if (isdbg('prefix')) {
259                                 my $percent = sprintf "%.1f", $hits * 100 / $misses;
260                                 dbg("Prefix Exact Cache Hit: $call Hits: $hits/$misses of $matchtotal = $percent\%");
261                         }
262                         push @out, @$p;
263                         next;
264                 }
265
266                 # then check if the whole thing succeeds either because it is cached
267                 # or because it simply is a stored prefix as callsign (or even a prefix)
268                 $p = $lru->get($call);
269                 if ($p) {
270                         $hits++;
271                         if (isdbg('prefix')) {
272                                 my $percent = sprintf "%.1f", $hits * 100 / $misses;
273                                 dbg("Prefix Cache Hit: $call Hits: $hits/$misses of $matchtotal = $percent\%");
274                         }
275                         push @out, @$p;
276                         next;
277                 }
278
279                 # is it in the USDB, force a matchprefix to match?
280                 my @s = USDB::get($call);
281                 if (@s) {
282                         @nout = get($call);
283                         @nout = matchprefix($call) unless @nout;
284                         $nout[0] = $ecall if @nout;
285                 } else {
286
287                         # try a straight get for an exact callsign
288                         @nout = get($ecall);
289                 }
290
291                 # now store the exact prefix if it has been found
292                 if (@nout && $nout[0] eq $ecall) {
293                         $misses++;
294                         $nout[0] = $call;
295                         lru_put("=$call", \@nout);
296                         dbg("got exact prefix: $nout[0]") if isdbg('prefix');
297                         push @out, @nout;
298                         next;
299                 }
300
301                 # now try a non-exact call/prefix
302                 if ((@nout = get($call)) && $nout[0] eq $call) {
303                         $misses++;
304                         lru_put($call, \@nout);
305                         dbg("got exact prefix: $nout[0]") if isdbg('prefix');
306                         push @out, @nout;
307                         next;
308                 }
309
310                 # now split the call into parts if required
311                 @parts = ($call =~ '/') ? split('/', $call) : ($call);
312                 dbg("Parts: $call = " . join(' ', @parts))      if isdbg('prefix');
313
314                 # remove any /0-9 /P /A /M /MM /AM suffixes etc
315                 if (@parts > 1) {
316                         @parts = grep { !/^\d+$/ && !/^[PABM]$/ && !/^(?:|AM|MM|BCN|JOTA|SIX|WEB|NET|Q\w+)$/; } @parts;
317
318                         # can we resolve them by direct lookup
319                         my $s = join('/', @parts); 
320                         @nout = get($s);
321                         if (@nout && $nout[0] eq $s) {
322                                 dbg("got exact multipart prefix: $call $s") if isdbg('prefix');
323                                 $misses++;
324                                 lru_put($call, \@nout);
325                                 push @out, @nout;
326                                 next;
327                         }
328                 }
329                 dbg("Parts now: $call = " . join(' ', @parts))  if isdbg('prefix');
330   
331                 # at this point we should have two or three parts
332                 # if it is three parts then join the first and last parts together
333                 # to get an answer
334
335                 # first deal with prefix/x00xx/single letter things
336                 if (@parts == 3 && length $parts[0] <= length $parts[1]) {
337                         @nout = matchprefix($parts[0]);
338                         if (@nout) {
339                                 my $s = join('/', $nout[0], $parts[2]);
340                                 my @try = get($s);
341                                 if (@try && $try[0] eq $s) {
342                                         dbg("got 3 part prefix: $call $s") if isdbg('prefix');
343                                         $misses++;
344                                         lru_put($call, \@try);
345                                         push @out, @try;
346                                         next;
347                                 }
348                                 
349                                 # if the second part is a callsign and the last part is one letter
350                                 if (is_callsign($parts[1]) && length $parts[2] == 1) {
351                                         pop @parts;
352                                 }
353                         }
354                 }
355
356                 # if it is a two parter 
357                 if (@parts == 2) {
358
359                         # try it as it is as compound, taking the first part as the prefix
360                         @nout = matchprefix($parts[0]);
361                         if (@nout) {
362                                 my $s = join('/', $nout[0], $parts[1]);
363                                 my @try = get($s);
364                                 if (@try && $try[0] eq $s) {
365                                         dbg("got 2 part prefix: $call $s") if isdbg('prefix');
366                                         $misses++;
367                                         lru_put($call, \@try);
368                                         push @out, @try;
369                                         next;
370                                 }
371                         }
372                 }
373
374                 # remove the problematic /J suffix
375                 pop @parts if @parts > 1 && $parts[$#parts] eq 'J';
376
377                 # single parter
378                 if (@parts == 1) {
379                         @nout = matchprefix($parts[0]);
380                         if (@nout) {
381                                 dbg("got prefix: $call = $nout[0]") if isdbg('prefix');
382                                 $misses++;
383                                 lru_put($call, \@nout);
384                                 push @out, @nout;
385                                 next;
386                         }
387                 }
388
389                 # try ALL the parts
390         my @checked;
391                 my $n;
392 L1:             for ($n = 0; $n < @parts; $n++) {
393                         my $sp = '';
394                         my ($k, $i);
395                         for ($i = $k = 0; $i < @parts; $i++) {
396                                 next if $checked[$i];
397                                 my $p = $parts[$i];
398                                 if (!$sp || length $p < length $sp) {
399                                         dbg("try part: $p") if isdbg('prefix');
400                                         $k = $i;
401                                         $sp = $p;
402                                 }
403                         }
404                         $checked[$k] = 1;
405                         $sp =~ s/-\d+$//;     # remove any SSID
406                         
407                         # now start to resolve it from the right hand end
408                         @nout = matchprefix($sp);
409                         
410                         # try and search for it in the descriptions as
411                         # a whole callsign if it has multiple parts and the output
412                         # is more two long, this should catch things like
413                         # FR5DX/T without having to explicitly stick it into
414                         # the prefix table.
415                         
416                         if (@nout) {
417                                 if (@parts > 1) {
418                                         $parts[$k] = $nout[0];
419                                         my $try = join('/', @parts);
420                                         my @try = get($try);
421                                         if (isdbg('prefix')) {
422                                                 my $part = $try[0] || "*";
423                                                 $part .= '*' unless $part eq '*' || $part eq $try;
424                                                 dbg("Compound prefix: $try $part" );
425                                         }
426                                         if (@try && $try eq $try[0]) {
427                                                 $misses++;
428                                                 lru_put($call, \@try);
429                                                 push @out, @try;
430                                         } else {
431                                                 $misses++;
432                                                 lru_put($call, \@nout);
433                                                 push @out, @nout;
434                                         }
435                                 } else {
436                                         $misses++;
437                                         lru_put($call, \@nout);
438                                         push @out, @nout;
439                                 }
440                                 next LM;
441                         }
442                 }
443
444                 # we are a pirate!
445                 @nout = matchprefix('QQ');
446                 $misses++;
447                 lru_put($call, \@nout);
448                 push @out, @nout;
449         }
450         
451         if (isdbg('prefixdata')) {
452                 my $dd = new Data::Dumper([ \@out ], [qw(@out)]);
453                 dbg($dd->Dumpxs);
454         }
455         return @out;
456 }
457
458 #
459 # turn a list of prefixes / dxcc numbers into a list of dxcc/itu/zone numbers
460 #
461 # nc = dxcc
462 # ni = itu
463 # nz = zone
464 # ns = state
465 #
466
467 sub to_ciz
468 {
469         my $cmd = shift;
470         my @out;
471         
472         foreach my $v (@_) {
473                 if ($cmd ne 'ns' && $v =~ /^\d+$/) {    
474                         push @out, $v unless grep $_ eq $v, @out;
475                 } else {
476                         if ($cmd eq 'ns' && $v =~ /^[A-Z][A-Z]$/i) {
477                                 push @out, uc $v unless grep $_ eq uc $v, @out;
478                         } else {
479                                 my @pre = Prefix::extract($v);
480                                 if (@pre) {
481                                         shift @pre;
482                                         foreach my $p (@pre) {
483                                                 my $n = $p->dxcc if $cmd eq 'nc' ;
484                                                 $n = $p->itu if $cmd eq 'ni' ;
485                                                 $n = $p->cq if $cmd eq 'nz' ;
486                                                 $n = $p->state if $cmd eq 'ns';
487                                                 push @out, $n unless grep $_ eq $n, @out;
488                                         }
489                                 }
490                         }                       
491                 }
492         }
493         return @out;
494 }
495
496 # get the full country data (dxcc, itu, cq, state, city) as a list
497 # from a callsign. 
498 sub cty_data
499 {
500         my $call = shift;
501         
502         my @dxcc = extract($call);
503         if (@dxcc) {
504                 my $state = $dxcc[1]->state || '';
505                 my $city = $dxcc[1]->city || '';
506                 my $name = $dxcc[1]->name || '';
507                 
508                 return ($dxcc[1]->dxcc, $dxcc[1]->itu, $dxcc[1]->cq, $state, $city, $name);
509         }
510         return (666,0,0,'','','Pirate-Country-QQ');             
511 }
512
513 my %valid = (
514                          city => '0,City',
515                          cont => '0,Continent',
516                          cq => '0,CQ',
517                          dxcc => '0,DXCC',
518                          itu => '0,ITU',
519                          lat => '0,Latitude,slat',
520                          long => '0,Longitude,slong',
521                          name => '0,Name',
522                          state => '0,State',
523                          utcoff => '0,UTC offset',
524                         );
525
526 sub AUTOLOAD
527 {
528         no strict;
529         my $name = $AUTOLOAD;
530   
531         return if $name =~ /::DESTROY$/;
532         $name =~ s/^.*:://o;
533   
534         confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
535         # this clever line of code creates a subroutine which takes over from autoload
536         # from OO Perl - Conway
537         *$AUTOLOAD = sub {@_ > 1 ? $_[0]->{$name} = $_[1] : $_[0]->{$name}} ;
538        goto &$AUTOLOAD;
539 }
540
541 #
542 # return a prompt for a field
543 #
544
545 sub field_prompt
546
547         my ($self, $ele) = @_;
548         return $valid{$ele};
549 }
550 1;
551
552 __END__