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