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