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