add ip addresses to dxspots emitted as PC61
[spider.git] / perl / DXUtil.pm
1 #
2 # various utilities which are exported globally
3 #
4 # Copyright (c) 1998 - Dirk Koopman G1TLH
5 #
6 #
7 #
8
9 package DXUtil;
10
11 use Date::Parse;
12 use IO::File;
13 use File::Copy;
14 use Data::Dumper;
15
16 use strict;
17
18 use vars qw(@month %patmap @ISA @EXPORT);
19
20 require Exporter;
21 @ISA = qw(Exporter);
22 @EXPORT = qw(atime ztime cldate cldatetime slat slong yesno promptf 
23                          parray parraypairs phex phash shellregex readfilestr writefilestr
24                          filecopy ptimelist
25              print_all_fields cltounix unpad is_callsign is_long_callsign is_latlong
26                          is_qra is_freq is_digits is_pctext is_pcflag insertitem deleteitem
27                          is_prefix dd is_ipaddr
28             );
29
30
31 @month = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
32 %patmap = (
33                    '*' => '.*',
34                    '?' => '.',
35                    '[' => '[',
36                    ']' => ']'
37 );
38
39 # a full time for logging and other purposes
40 sub atime
41 {
42         my $t = shift;
43         my ($sec,$min,$hour,$mday,$mon,$year) = gmtime((defined $t) ? $t : time);
44         $year += 1900;
45         my $buf = sprintf "%02d%s%04d\@%02d:%02d:%02d", $mday, $month[$mon], $year, $hour, $min, $sec;
46         return $buf;
47 }
48
49 # get a zulu time in cluster format (2300Z)
50 sub ztime
51 {
52         my $t = shift;
53         $t = defined $t ? $t : time;
54         my $dst = shift;
55         my ($sec,$min,$hour) = $dst ? localtime($t): gmtime($t);
56         my $buf = sprintf "%02d%02d%s", $hour, $min, ($dst) ? '' : 'Z';
57         return $buf;
58 }
59
60 # get a cluster format date (23-Jun-1998)
61 sub cldate
62 {
63         my $t = shift;
64         $t = defined $t ? $t : time;
65         my $dst = shift;
66         my ($sec,$min,$hour,$mday,$mon,$year) = $dst ? localtime($t) : gmtime($t);
67         $year += 1900;
68         my $buf = sprintf "%2d-%s-%04d", $mday, $month[$mon], $year;
69         return $buf;
70 }
71
72 # return a cluster style date time
73 sub cldatetime
74 {
75         my $t = shift;
76         my $dst = shift;
77         my $date = cldate($t, $dst);
78         my $time = ztime($t, $dst);
79         return "$date $time";
80 }
81
82 # return a unix date from a cluster date and time
83 sub cltounix
84 {
85         my $date = shift;
86         my $time = shift;
87         my ($thisyear) = (gmtime)[5] + 1900;
88
89         return 0 unless $date =~ /^\s*(\d+)-(\w\w\w)-([12][90]\d\d)$/;
90         return 0 if $3 > 2036;
91         return 0 unless abs($thisyear-$3) <= 1;
92         $date = "$1 $2 $3";
93         return 0 unless $time =~ /^([012]\d)([012345]\d)Z$/;
94         $time = "$1:$2 +0000";
95         my $r = str2time("$date $time");
96         return $r unless $r;
97         return $r == -1 ? undef : $r;
98 }
99
100 # turn a latitude in degrees into a string
101 sub slat
102 {
103         my $n = shift;
104         my ($deg, $min, $let);
105         $let = $n >= 0 ? 'N' : 'S';
106         $n = abs $n;
107         $deg = int $n;
108         $min = int ((($n - $deg) * 60) + 0.5);
109         return "$deg $min $let";
110 }
111
112 # turn a longitude in degrees into a string
113 sub slong
114 {
115         my $n = shift;
116         my ($deg, $min, $let);
117         $let = $n >= 0 ? 'E' : 'W';
118         $n = abs $n;
119         $deg = int $n;
120         $min = int ((($n - $deg) * 60) + 0.5);
121         return "$deg $min $let";
122 }
123
124 # turn a true into 'yes' and false into 'no'
125 sub yesno
126 {
127         my $n = shift;
128         return $n ? $main::yes : $main::no;
129 }
130
131 # provide a data dumpered version of the object passed
132 sub dd
133 {
134         my $value = shift;
135         my $dd = new Data::Dumper([$value]);
136         $dd->Indent(0);
137         $dd->Terse(1);
138     $dd->Quotekeys($] < 5.005 ? 1 : 0);
139         $value = $dd->Dumpxs;
140         $value =~ s/([\r\n\t])/sprintf("%%%02X", ord($1))/eg;
141         $value =~ s/^\s*\[//;
142     $value =~ s/\]\s*$//;
143         
144         return $value;
145 }
146
147 # format a prompt with its current value and return it with its privilege
148 sub promptf
149 {
150         my ($line, $value) = @_;
151         my ($priv, $prompt, $action) = split ',', $line;
152
153         # if there is an action treat it as a subroutine and replace $value
154         if ($action) {
155                 my $q = qq{\$value = $action(\$value)};
156                 eval $q;
157         } elsif (ref $value) {
158                 $value = dd($value);
159         }
160         $prompt = sprintf "%15s: %s", $prompt, $value;
161         return ($priv, $prompt);
162 }
163
164 # turn a hex field into printed hex
165 sub phex
166 {
167         my $val = shift;
168         return sprintf '%X', $val;
169 }
170
171 # take an arg as a hash of call=>time pairs and print it
172 sub ptimelist
173 {
174         my $ref = shift;
175         my $out;
176         for (sort keys %$ref) {
177                 $out .= "$_=$ref->{$_}, ";
178         }
179         chop $out;
180         chop $out;
181         return $out;    
182 }
183
184 # take an arg as an array list and print it
185 sub parray
186 {
187         my $ref = shift;
188         return ref $ref ? join(', ', @{$ref}) : $ref;
189 }
190
191 # take the arg as an array reference and print as a list of pairs
192 sub parraypairs
193 {
194         my $ref = shift;
195         my $i;
196         my $out;
197
198         for ($i = 0; $i < @$ref; $i += 2) {
199                 my $r1 = @$ref[$i];
200                 my $r2 = @$ref[$i+1];
201                 $out .= "$r1-$r2, ";
202         }
203         chop $out;                                      # remove last space
204         chop $out;                                      # remove last comma
205         return $out;
206 }
207
208 # take the arg as a hash reference and print it out as such
209 sub phash
210 {
211         my $ref = shift;
212         my $out;
213
214         while (my ($k,$v) = each %$ref) {
215                 $out .= "${k}=>$v, ";
216         }
217         chop $out;                                      # remove last space
218         chop $out;                                      # remove last comma
219         return $out;
220 }
221
222 sub _sort_fields
223 {
224         my $ref = shift;
225         my @a = split /,/, $ref->field_prompt(shift); 
226         my @b = split /,/, $ref->field_prompt(shift); 
227         return lc $a[1] cmp lc $b[1];
228 }
229
230 # print all the fields for a record according to privilege
231 #
232 # The prompt record is of the format '<priv>,<prompt>[,<action>'
233 # and is expanded by promptf above
234 #
235 sub print_all_fields
236 {
237         my $self = shift;                       # is a dxchan
238         my $ref = shift;                        # is a thingy with field_prompt and fields methods defined
239         my @out;
240         my @fields = $ref->fields;
241         my $field;
242         my $width = $self->width - 1;
243         $width ||= 80;
244
245         foreach $field (sort {_sort_fields($ref, $a, $b)} @fields) {
246                 if (defined $ref->{$field}) {
247                         my ($priv, $ans) = promptf($ref->field_prompt($field), $ref->{$field});
248                         my @tmp;
249                         if (length $ans > $width) {
250                                 my ($p, $a) = split /: /, $ans, 2;
251                                 my $l = (length $p) + 2;
252                                 my $al = ($width - 1) - $l;
253                                 my $bit;
254                                 while (length $a > $al ) {
255                                         ($bit, $a) = unpack "A$al A*", $a;
256                                         push @tmp, "$p: $bit";
257                                         $p = ' ' x ($l - 2);
258                                 }
259                                 push @tmp, "$p: $a" if length $a;
260                         } else {
261                                 push @tmp, $ans;
262                         }
263                         push @out, @tmp if ($self->priv >= $priv);
264                 }
265         }
266         return @out;
267 }
268
269 # generate a regex from a shell type expression 
270 # see 'perl cookbook' 6.9
271 sub shellregex
272 {
273         my $in = shift;
274         $in =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
275         return '^' . $in . "\$";
276 }
277
278 # read in a file into a string and return it. 
279 # the filename can be split into a dir and file and the 
280 # file can be in upper or lower case.
281 # there can also be a suffix
282 sub readfilestr
283 {
284         my ($dir, $file, $suffix) = @_;
285         my $fn;
286         my $f;
287         if ($suffix) {
288                 $f = uc $file;
289                 $fn = "$dir/$f.$suffix";
290                 unless (-e $fn) {
291                         $f = lc $file;
292                         $fn = "$dir/$file.$suffix";
293                 }
294         } elsif ($file) {
295                 $f = uc $file;
296                 $fn = "$dir/$file";
297                 unless (-e $fn) {
298                         $f = lc $file;
299                         $fn = "$dir/$file";
300                 }
301         } else {
302                 $fn = $dir;
303         }
304
305         my $fh = new IO::File $fn;
306         my $s = undef;
307         if ($fh) {
308                 local $/ = undef;
309                 $s = <$fh>;
310                 $fh->close;
311         }
312         return $s;
313 }
314
315 # write out a file in the format required for reading
316 # in via readfilestr, it expects the same arguments 
317 # and a reference to an object
318 sub writefilestr
319 {
320         my $dir = shift;
321         my $file = shift;
322         my $suffix = shift;
323         my $obj = shift;
324         my $fn;
325         my $f;
326         
327         confess('no object to write in writefilestr') unless $obj;
328         confess('object not a reference in writefilestr') unless ref $obj;
329         
330         if ($suffix) {
331                 $f = uc $file;
332                 $fn = "$dir/$f.$suffix";
333                 unless (-e $fn) {
334                         $f = lc $file;
335                         $fn = "$dir/$file.$suffix";
336                 }
337         } elsif ($file) {
338                 $f = uc $file;
339                 $fn = "$dir/$file";
340                 unless (-e $fn) {
341                         $f = lc $file;
342                         $fn = "$dir/$file";
343                 }
344         } else {
345                 $fn = $dir;
346         }
347
348         my $fh = new IO::File ">$fn";
349         if ($fh) {
350                 my $dd = new Data::Dumper([ $obj ]);
351                 $dd->Indent(1);
352                 $dd->Terse(1);
353                 $dd->Quotekeys(0);
354                 #       $fh->print(@_) if @_ > 0;     # any header comments, lines etc
355                 $fh->print($dd->Dumpxs);
356                 $fh->close;
357         }
358 }
359
360 sub filecopy
361 {
362         copy(@_) or return $!;
363 }
364
365 # remove leading and trailing spaces from an input string
366 sub unpad
367 {
368         my $s = shift;
369         $s =~ s/\s+$//;
370         $s =~ s/^\s+//;
371         return $s;
372 }
373
374 # check that a field only has callsign characters in it
375 sub is_callsign
376 {
377         return $_[0] =~ m!^(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}\d+)        # basic prefix
378                        (?:/(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}\d+))?  # / another one (possibly)
379                                            [A-Z]{1,3}                                 # callsign letters
380                                            (?:/(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}\d+))?  # / another prefix possibly
381                        (?:/[0-9A-Z]{1,2})?                        # /0-9A-Z+ possibly
382                                            (?:-\d{1,2})?                              # - nn possibly
383                                          $!x;
384 }
385
386 # check that a field only has callsign characters in it but has more than the standard 3 callsign letters
387 sub is_long_callsign
388 {
389         return $_[0] =~ m!^(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}\d+)        # basic prefix
390                        (?:/(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}\d+))?  # / another one (possibly)
391                                            [A-Z]{1,5}                                 # callsign letters
392                                            (?:/(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}\d+))?  # / another prefix possibly
393                        (?:/[0-9A-Z]{1,2})?                        # /0-9A-Z+ possibly
394                                            (?:-\d{1,2})?                              # - nn possibly
395                                          $!x;
396 }
397
398 sub is_prefix
399 {
400         return $_[0] =~ m!^(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}\d+)!x        # basic prefix
401 }
402         
403
404 # check that a PC protocol field is valid text
405 sub is_pctext
406 {
407         return undef unless length $_[0];
408         return undef if $_[0] =~ /[\x00-\x08\x0a-\x1f\x80-\x9f]/;
409         return 1;
410 }
411
412 # check that a PC prot flag is fairly valid (doesn't check the difference between 1/0 and */-)
413 sub is_pcflag
414 {
415         return $_[0] =~ /^[01\*\-]+$/;
416 }
417
418 # check that a thing is a frequency
419 sub is_freq
420 {
421         return $_[0] =~ /^\d+(?:\.\d+)?$/;
422 }
423
424 # check that a thing is just digits
425 sub is_digits
426 {
427         return $_[0] =~ /^[\d]+$/;
428 }
429
430 # does it look like a qra locator?
431 sub is_qra
432 {
433         return $_[0] =~ /^[A-Ra-r][A-Ra-r]\d\d[A-Xa-x][A-Xa-x]$/;
434 }
435
436 # does it look like a valid lat/long
437 sub is_latlong
438 {
439         return $_[0] =~ /^\s*\d{1,2}\s+\d{1,2}\s*[NnSs]\s+1?\d{1,2}\s+\d{1,2}\s*[EeWw]\s*$/;
440 }
441
442 # is it an ip address?
443 sub is_ipaddr
444 {
445     return $_[0] =~ /^\d+\.\d+\.\d+\.\d+$/ || $_[0] =~ /^[0-9a-f:]+$/;
446 }
447
448 # insert an item into a list if it isn't already there returns 1 if there 0 if not
449 sub insertitem
450 {
451         my $list = shift;
452         my $item = shift;
453         
454         return 1 if grep {$_ eq $item } @$list;
455         push @$list, $item;
456         return 0;
457 }
458
459 # delete an item from a list if it is there returns no deleted 
460 sub deleteitem
461 {
462         my $list = shift;
463         my $item = shift;
464         my $n = @$list;
465         
466         @$list = grep {$_ ne $item } @$list;
467         return $n - @$list;
468 }
469