fix is_ipaddr? change pc92 A/D default
[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
12 use Date::Parse;
13 use IO::File;
14 use File::Copy;
15 use Data::Dumper;
16 use Time::HiRes qw(gettimeofday tv_interval);
17 use Text::Wrap;
18 use Socket qw(AF_INET6 AF_INET inet_pton);
19
20 use strict;
21
22 use vars qw(@month %patmap $pi $d2r $r2d @ISA @EXPORT);
23
24 require Exporter;
25 @ISA = qw(Exporter);
26 @EXPORT = qw(atime ztime cldate cldatetime slat slong yesno promptf 
27                          parray parraypairs phex phash shellregex readfilestr writefilestr
28                          filecopy ptimelist
29              print_all_fields cltounix unpad is_callsign is_latlong
30                          is_qra is_freq is_digits is_pctext is_pcflag insertitem deleteitem
31                          is_prefix dd is_ipaddr $pi $d2r $r2d localdata localdata_mv
32                          diffms _diffms _diffus difft parraydifft is_ztime basecall
33                          normalise_call is_numeric
34             );
35
36
37 @month = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
38 %patmap = (
39                    '*' => '.*',
40                    '?' => '.',
41                    '[' => '[',
42                    ']' => ']'
43 );
44
45 $pi = 3.141592653589;
46 $d2r = ($pi/180);
47 $r2d = (180/$pi);
48
49
50 # a full time for logging and other purposes
51 sub atime
52 {
53         my $t = shift;
54         my ($sec,$min,$hour,$mday,$mon,$year) = gmtime((defined $t) ? $t : time);
55         $year += 1900;
56         my $buf = sprintf "%02d%s%04d\@%02d:%02d:%02d", $mday, $month[$mon], $year, $hour, $min, $sec;
57         return $buf;
58 }
59
60 # get a zulu time in cluster format (2300Z)
61 sub ztime
62 {
63         my $t = shift;
64         $t = defined $t ? $t : time;
65         my $dst = shift;
66         my ($sec,$min,$hour) = $dst ? localtime($t): gmtime($t);
67         my $buf = sprintf "%02d%02d%s", $hour, $min, ($dst) ? '' : 'Z';
68         return $buf;
69 }
70
71 # get a cluster format date (23-Jun-1998)
72 sub cldate
73 {
74         my $t = shift;
75         $t = defined $t ? $t : time;
76         my $dst = shift;
77         my ($sec,$min,$hour,$mday,$mon,$year) = $dst ? localtime($t) : gmtime($t);
78         $year += 1900;
79         my $buf = sprintf "%2d-%s-%04d", $mday, $month[$mon], $year;
80         return $buf;
81 }
82
83 # return a cluster style date time
84 sub cldatetime
85 {
86         my $t = shift;
87         my $dst = shift;
88         my $date = cldate($t, $dst);
89         my $time = ztime($t, $dst);
90         return "$date $time";
91 }
92
93 # return a unix date from a cluster date and time
94 sub cltounix
95 {
96         my $date = shift;
97         my $time = shift;
98         my ($thisyear) = (gmtime)[5] + 1900;
99
100         return 0 unless $date =~ /^\s*(\d+)-(\w\w\w)-([12][90]\d\d)$/;
101         return 0 if $3 > 2036;
102         return 0 unless abs($thisyear-$3) <= 1;
103         $date = "$1 $2 $3";
104         return 0 unless $time =~ /^([012]\d)([012345]\d)Z$/;
105         $time = "$1:$2 +0000";
106         my $r = str2time("$date $time");
107         return $r unless $r;
108         return $r == -1 ? undef : $r;
109 }
110
111 # turn a latitude in degrees into a string
112 sub slat
113 {
114         my $n = shift;
115         my ($deg, $min, $let);
116         $let = $n >= 0 ? 'N' : 'S';
117         $n = abs $n;
118         $deg = int $n;
119         $min = int ((($n - $deg) * 60) + 0.5);
120         return "$deg $min $let";
121 }
122
123 # turn a longitude in degrees into a string
124 sub slong
125 {
126         my $n = shift;
127         my ($deg, $min, $let);
128         $let = $n >= 0 ? 'E' : 'W';
129         $n = abs $n;
130         $deg = int $n;
131         $min = int ((($n - $deg) * 60) + 0.5);
132         return "$deg $min $let";
133 }
134
135 # turn a true into 'yes' and false into 'no'
136 sub yesno
137 {
138         my $n = shift;
139         return $n ? $main::yes : $main::no;
140 }
141
142 # provide a data dumpered version of the object passed
143 sub dd
144 {
145         my $value = shift;
146         my $dd = new Data::Dumper([$value]);
147         $dd->Indent(0);
148         $dd->Terse(1);
149     $dd->Quotekeys($] < 5.005 ? 1 : 0);
150         $value = $dd->Dumpxs;
151         $value =~ s/([\r\n\t])/sprintf("%%%02X", ord($1))/eg;
152         $value =~ s/^\s*\[//;
153     $value =~ s/\]\s*$//;
154         
155         return $value;
156 }
157
158 # format a prompt with its current value and return it with its privilege
159 sub promptf
160 {
161         my ($line, $value, $promptl) = @_;
162         my ($priv, $prompt, $action) = split ',', $line;
163
164         # if there is an action treat it as a subroutine and replace $value
165         if ($action) {
166                 my $q = qq{\$value = $action(\$value)};
167                 eval $q;
168         } elsif (ref $value) {
169                 $value = dd($value);
170         }
171         $promptl ||= 15;
172         $prompt = sprintf "%${promptl}s: %s", $prompt, $value;
173         return ($priv, $prompt);
174 }
175
176 # turn a hex field into printed hex
177 sub phex
178 {
179         my $val = shift;
180         return sprintf '%X', $val;
181 }
182
183 # take an arg as a hash of call=>time pairs and print it
184 sub ptimelist
185 {
186         my $ref = shift;
187         my $out;
188         for (sort keys %$ref) {
189                 $out .= "$_=" . atime($ref->{$_}) . ", ";
190         }
191         chop $out;
192         chop $out;
193         return $out;    
194 }
195
196 # take an arg as an array list and print it
197 sub parray
198 {
199         my $ref = shift;
200         return ref $ref ? join(', ', sort @{$ref}) : $ref;
201 }
202
203 # take the arg as an array reference and print as a list of pairs
204 sub parraypairs
205 {
206         my $ref = shift;
207         my $i;
208         my $out;
209
210         for ($i = 0; $i < @$ref; $i += 2) {
211                 my $r1 = @$ref[$i];
212                 my $r2 = @$ref[$i+1];
213                 $out .= "$r1-$r2, ";
214         }
215         chop $out;                                      # remove last space
216         chop $out;                                      # remove last comma
217         return $out;
218 }
219
220 # take the arg as a hash reference and print it out as such
221 sub phash
222 {
223         my $ref = shift;
224         my $out;
225
226         foreach my $k (sort keys %$ref) {
227                 $out .= "${k}=>$ref->{$k}, ";
228         }
229         $out =~ s/, $// if $out;
230         return $out;
231 }
232
233 sub _sort_fields
234 {
235         my $ref = shift;
236         my @a = split /,/, $ref->field_prompt(shift); 
237         my @b = split /,/, $ref->field_prompt(shift); 
238         return lc $a[1] cmp lc $b[1];
239 }
240
241 # print all the fields for a record according to privilege
242 #
243 # The prompt record is of the format '<priv>,<prompt>[,<action>'
244 # and is expanded by promptf above
245 #
246 sub print_all_fields
247 {
248         my $self = shift;                       # is a dxchan
249         my $ref = shift;                        # is a thingy with field_prompt and fields methods defined
250         my @out;
251         my @fields = $ref->fields;
252         my $field;
253         my $width = $self->width - 1;
254         my $promptl = 0;
255         $width ||= 80;
256
257         # find the maximum length of the prompt
258         foreach $field (@fields) {
259                 if (defined $ref->{$field}) {
260                         my (undef, $prompt, undef) = split ',', $ref->field_prompt($field);
261                         $promptl = length $prompt if length $prompt > $promptl;
262                 }
263         }
264
265         # now do print
266         foreach $field (sort {_sort_fields($ref, $a, $b)} @fields) {
267                 if (defined $ref->{$field}) {
268                         my ($priv, $ans) = promptf($ref->field_prompt($field), $ref->{$field}, $promptl);
269                         my @tmp;
270                         if (length $ans > $width) {
271                                 $Text::Wrap::columns = $width-2;
272                                 my ($p, $a) = split /: /, $ans, 2;
273                                 @tmp = split/\n/, Text::Wrap::wrap("$p: ", (' ' x $promptl) . ': ', $a);
274                         } else {
275                                 push @tmp, $ans;
276                         }
277                         push @out, @tmp if ($self->priv >= $priv);
278                 }
279         }
280         return @out;
281 }
282
283 # generate a regex from a shell type expression 
284 # see 'perl cookbook' 6.9
285 sub shellregex
286 {
287         my $in = shift;
288         $in =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
289         $in =~ s|\\/|/|g;
290         return '^' . $in . "\$";
291 }
292
293 # read in a file into a string and return it. 
294 # the filename can be split into a dir and file and the 
295 # file can be in upper or lower case.
296 # there can also be a suffix
297 sub readfilestr
298 {
299         my ($dir, $file, $suffix) = @_;
300         my $fn;
301         my $f;
302         if ($suffix) {
303                 $f = uc $file;
304                 $fn = "$dir/$f.$suffix";
305                 unless (-e $fn) {
306                         $f = lc $file;
307                         $fn = "$dir/$file.$suffix";
308                 }
309         } elsif ($file) {
310                 $f = uc $file;
311                 $fn = "$dir/$file";
312                 unless (-e $fn) {
313                         $f = lc $file;
314                         $fn = "$dir/$file";
315                 }
316         } else {
317                 $fn = $dir;
318         }
319
320         my $fh = new IO::File $fn;
321         my $s = undef;
322         if ($fh) {
323                 local $/ = undef;
324                 $s = <$fh>;
325                 $fh->close;
326         }
327         return $s;
328 }
329
330 # write out a file in the format required for reading
331 # in via readfilestr, it expects the same arguments 
332 # and a reference to an object
333 sub writefilestr
334 {
335         my $dir = shift;
336         my $file = shift;
337         my $suffix = shift;
338         my $obj = shift;
339         my $fn;
340         my $f;
341         
342         confess('no object to write in writefilestr') unless $obj;
343         confess('object not a reference in writefilestr') unless ref $obj;
344         
345         if ($suffix) {
346                 $f = uc $file;
347                 $fn = "$dir/$f.$suffix";
348                 unless (-e $fn) {
349                         $f = lc $file;
350                         $fn = "$dir/$file.$suffix";
351                 }
352         } elsif ($file) {
353                 $f = uc $file;
354                 $fn = "$dir/$file";
355                 unless (-e $fn) {
356                         $f = lc $file;
357                         $fn = "$dir/$file";
358                 }
359         } else {
360                 $fn = $dir;
361         }
362
363         my $fh = new IO::File ">$fn";
364         if ($fh) {
365                 my $dd = new Data::Dumper([ $obj ]);
366                 $dd->Indent(1);
367                 $dd->Terse(1);
368                 $dd->Quotekeys(0);
369                 #       $fh->print(@_) if @_ > 0;     # any header comments, lines etc
370                 $fh->print($dd->Dumpxs);
371                 $fh->close;
372         }
373 }
374
375 sub filecopy
376 {
377         copy(@_) or return $!;
378 }
379
380 # remove leading and trailing spaces from an input string
381 sub unpad
382 {
383         my $s = shift;
384         $s =~ s/^\s*//;
385         $s =~ s/\s*$//;
386         return $s;
387 }
388
389 # check that a field only has callsign characters in it
390 sub is_callsign
391 {
392         return $_[0] =~ m!^
393                                           (?:\d?[A-Z]{1,2}\d{0,2}/)?    # out of area prefix /  
394                                           (?:\d?[A-Z]{1,2}\d{1,5})      # main prefix one (required) - lengthened for special calls 
395                                           [A-Z]{1,8}                # callsign letters (required)
396                                           (?:-(?:\d{1,2}))?         # - nn possibly (eg G8BPQ-8)
397                                           (?:/[0-9A-Z]{1,7})?       # / another prefix, callsign or special label (including /MM, /P as well as /EURO or /LGT) possibly
398                                           (?:/(?:AM?|MM?|P))?       # finally /A /AM /M /MM /P 
399                                           $!xo;
400
401         # longest callign allowed is 1X11/1Y11XXXXX-11/XXXXXXX/MM
402 }
403
404 sub is_prefix
405 {
406         return $_[0] =~ m!^(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}}\d+)!x        # basic prefix
407 }
408         
409
410 # check that a PC protocol field is valid text
411 sub is_pctext
412 {
413         return undef unless length $_[0];
414         return undef if $_[0] =~ /[\x00-\x08\x0a-\x1f\x80-\x9f]/;
415         return 1;
416 }
417
418 # check that a PC prot flag is fairly valid (doesn't check the difference between 1/0 and */-)
419 sub is_pcflag
420 {
421         return $_[0] =~ /^[01\*\-]+$/;
422 }
423
424 # check that a thing is a frequency
425 sub is_freq
426 {
427         return $_[0] =~ /^\d+(?:\.\d+)?$/;
428 }
429
430 # check that a thing is just digits
431 sub is_digits
432 {
433         return $_[0] =~ /^[\d]+$/;
434 }
435
436 # does it look like a qra locator?
437 sub is_qra
438 {
439         return unless length $_[0] == 4 || length $_[0] == 6;
440         return $_[0] =~ /^[A-Ra-r][A-Ra-r]\d\d(?:[A-Xa-x][A-Xa-x])?$/;
441 }
442
443 # does it look like a valid lat/long
444 sub is_latlong
445 {
446         return $_[0] =~ /^\s*\d{1,2}\s+\d{1,2}\s*[NnSs]\s+1?\d{1,2}\s+\d{1,2}\s*[EeWw]\s*$/;
447 }
448
449 # is it an ip address?
450 sub is_ipaddr
451 {
452
453         if ($_[0] =~ /:/) {
454                 if (inet_pton(AF_INET6, $_[0])) {
455                         return ($_[0] =~ /([:0-9a-f]+)/);
456                 }
457 #               use re 'debug';
458 #               return ($1) if $_[0] =~ /^(\:?(?:\:?[0-9a-f]{1,4}){1,8}?)$/i;
459 #               no re 'debug';
460         } else {
461                 return ($_[0] =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
462         }
463         return undef;
464 }
465
466 # is it a zulu time hhmmZ
467 sub is_ztime
468 {
469         return $_[0] =~ /^(?:(?:2[0-3])|(?:[01][0-9]))[0-5][0-9]Z$/;
470 }
471
472 # insert an item into a list if it isn't already there returns 1 if there 0 if not
473 sub insertitem
474 {
475         my $list = shift;
476         my $item = shift;
477         
478         return 1 if grep {$_ eq $item } @$list;
479         push @$list, $item;
480         return 0;
481 }
482
483 # delete an item from a list if it is there returns no deleted 
484 sub deleteitem
485 {
486         my $list = shift;
487         my $item = shift;
488         my $n = @$list;
489         
490         @$list = grep {$_ ne $item } @$list;
491         return $n - @$list;
492 }
493
494 # find the correct local_data directory
495 # basically, if there is a local_data directory with this filename and it is younger than the
496 # equivalent one in the (system) data directory then return that name rather than the system one
497 sub localdata
498 {
499         my $ifn = shift;
500         my $lfn = "$main::local_data/$ifn";
501         my $dfn =  "$main::data/$ifn";
502         
503         if (-e "$main::local_data") {
504                 if ((-e $dfn) && (-e $lfn)) {
505                         $lfn = $dfn if -M $dfn < -M $lfn;
506                 } else {
507                         $lfn = $dfn if -e $dfn;
508                 }
509         } else {
510                 $lfn = $dfn;
511         }
512
513         return $lfn;
514 }
515
516 # move a file or a directory from data -> local_data if isn't there already
517 sub localdata_mv
518 {
519         my $ifn = shift;
520         if (-e "$main::data/$ifn" ) {
521                 unless (-e "$main::local_data/$ifn") {
522                         move("$main::data/$ifn", "$main::local_data/$ifn") or die "localdata_mv: cannot move $ifn from '$main::data' -> '$main::local_data' $!\n";
523                 }
524         }
525 }
526
527 # measure the time taken for something to happen; use Time::HiRes qw(gettimeofday tv_interval);
528 sub _diffms
529 {
530         my $ta = shift;
531         my $tb = shift || [gettimeofday];
532         my $a = int($ta->[0] * 1000) + int($ta->[1] / 1000); 
533         my $b = int($tb->[0] * 1000) + int($tb->[1] / 1000);
534         return $b - $a;
535 }
536
537 # and in microseconds
538 sub _diffus
539 {
540         my $ta = shift;
541         my $tb = shift || [gettimeofday];
542         my $a = int($ta->[0] * 1000000) + int($ta->[1]); 
543         my $b = int($tb->[0] * 1000000) + int($tb->[1]);
544         return $b - $a;
545 }
546
547 sub diffms
548 {
549         my $call = shift;
550         my $line = shift;
551         my $ta = shift;
552         my $no = shift;
553         my $tb = shift;
554         my $msecs = _diffms($ta, $tb);
555
556         $line =~ s|\s+$||;
557         my $s = "subprocess stats cmd: '$line' $call ${msecs}mS";
558         $s .= " $no lines" if $no;
559         DXDebug::dbg($s);
560 }
561
562 # expects either an array reference or two times (in the correct order [start, end])
563 sub difft
564 {
565         my $b = shift;
566         my $adds = shift;
567         
568         my $t;
569         if (ref $b eq 'ARRAY') {
570                 $t = $b->[1] - $b->[0];
571         } else {
572                 if ($adds && $adds =~ /^\d+$/ && $adds >= $b) {
573                         $t = $adds - $b;
574                         $adds = shift;
575                 } else {
576                         $t = $main::systime - $b;
577                 }
578         }
579         return '-(ve)' if $t < 0;
580         my ($y,$d,$h,$m,$s);
581         my $out = '';
582         $y = int $t / (86400*365);
583         $out .= sprintf ("%s${y}y", $adds?' ':'') if $y;
584         $t -= $y * 86400 * 365;
585         $d = int $t / 86400;
586         $out .= sprintf ("%s${d}d", $adds?' ':'') if $d;
587         $t -= $d * 86400;
588         $h = int $t / 3600;
589         $out .= sprintf ("%s${h}h", $adds?' ':'') if $h;
590         $t -= $h * 3600;
591         $m = int $t / 60;
592         $out .= sprintf ("%s${m}m", $adds?' ':'') if $m;
593         if (($d == 0 && $adds) || (int $adds && $adds == 2)) {
594                 $s = int $t % 60;
595                 $out .= sprintf ("%s${s}s", $adds?' ':'') if $s;
596                 $out ||= sprintf ("%s0s", $adds?' ':'');
597         }
598         $out = '0s' unless length $out;
599         return $out;
600 }
601
602 # print an array ref of difft refs
603 sub parraydifft
604 {
605         my $r = shift;
606         my $out = '';
607         for (@$r) {
608                 my $s = $_->[2] ? "($_->[2])" : '';
609                 $out .= sprintf "%s=%s$s, ", atime($_->[0]), difft($_->[0], $_->[1]);
610         }
611         $out =~ s/,\s*$//;
612         return $out;
613 }
614
615 sub basecall
616 {
617         my ($r) = $_[0] =~ m{^((?:[\w\d]+/)?[\w\d]+(?:/[\w\d]+)*)(?:-\d+)?(?:-\#)?$};
618         return $r;
619 }
620
621 sub normalise_call
622 {
623         my ($c, $ssid) = $_[0] =~ m|^((?:[\w\d]+/)?[\d\w]+(?:/[\w\d]+)*)(?:-(\d+))?(?:-\#)?$|;
624         my $ncall = $c;
625         $ssid += 0;
626         $ncall .= "-$ssid" if $ssid;
627         return $ncall;
628 }
629
630 sub is_numeric
631 {
632         return $_[0] =~ /^[\.\d]+$/;
633 }