2 # various utilities which are exported globally
4 # Copyright (c) 1998 - Dirk Koopman G1TLH
16 use Time::HiRes qw(gettimeofday tv_interval);
20 use vars qw(@month %patmap $pi $d2r $r2d @ISA @EXPORT);
24 @EXPORT = qw(atime ztime cldate cldatetime slat slong yesno promptf
25 parray parraypairs phex phash shellregex readfilestr writefilestr
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 _diffus difft parraydifft is_ztime basecall
31 normalise_call is_numeric
35 @month = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
49 # our $enable_ptonok = 0;
53 # if ($enable_ptonok && !$main::is_win) {
54 # eval {require Socket; Socket->import(qw(AF_INET6 AF_INET inet_pton)); };
56 # $ptonok = !defined inet_pton(AF_INET, '016.17.184.1')
57 # && !defined inet_pton(AF_INET6, '2067::1:')
58 # # Some old versions of Socket are hopelessly broken
59 # && length(inet_pton(AF_INET, '1.1.1.1')) == 4;
66 # a full time for logging and other purposes
70 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime((defined $t) ? $t : time);
72 my $buf = sprintf "%02d%s%04d\@%02d:%02d:%02d", $mday, $month[$mon], $year, $hour, $min, $sec;
76 # get a zulu time in cluster format (2300Z)
80 $t = defined $t ? $t : time;
82 my ($sec,$min,$hour) = $dst ? localtime($t): gmtime($t);
83 my $buf = sprintf "%02d%02d%s", $hour, $min, ($dst) ? '' : 'Z';
87 # get a cluster format date (23-Jun-1998)
91 $t = defined $t ? $t : time;
93 my ($sec,$min,$hour,$mday,$mon,$year) = $dst ? localtime($t) : gmtime($t);
95 my $buf = sprintf "%2d-%s-%04d", $mday, $month[$mon], $year;
99 # return a cluster style date time
104 my $date = cldate($t, $dst);
105 my $time = ztime($t, $dst);
106 return "$date $time";
109 # return a unix date from a cluster date and time
114 my ($thisyear) = (gmtime)[5] + 1900;
116 return 0 unless $date =~ /^\s*(\d+)-(\w\w\w)-([12][90]\d\d)$/;
117 return 0 if $3 > 2036;
118 return 0 unless abs($thisyear-$3) <= 1;
120 return 0 unless $time =~ /^([012]\d)([012345]\d)Z$/;
121 $time = "$1:$2 +0000";
122 my $r = str2time("$date $time");
124 return $r == -1 ? undef : $r;
127 # turn a latitude in degrees into a string
131 my ($deg, $min, $let);
132 $let = $n >= 0 ? 'N' : 'S';
135 $min = int ((($n - $deg) * 60) + 0.5);
136 return "$deg $min $let";
139 # turn a longitude in degrees into a string
143 my ($deg, $min, $let);
144 $let = $n >= 0 ? 'E' : 'W';
147 $min = int ((($n - $deg) * 60) + 0.5);
148 return "$deg $min $let";
151 # turn a true into 'yes' and false into 'no'
155 return $n ? $main::yes : $main::no;
158 # provide a data dumpered version of the object passed
162 my $dd = new Data::Dumper([$value]);
165 $dd->Quotekeys($] < 5.005 ? 1 : 0);
166 $value = $dd->Dumpxs;
167 $value =~ s/([\r\n\t])/sprintf("%%%02X", ord($1))/eg;
168 $value =~ s/^\s*\[//;
169 $value =~ s/\]\s*$//;
174 # format a prompt with its current value and return it with its privilege
177 my ($line, $value, $promptl) = @_;
178 my ($priv, $prompt, $action) = split ',', $line;
180 # if there is an action treat it as a subroutine and replace $value
182 my $q = qq{\$value = $action(\$value)};
184 } elsif (ref $value) {
188 $prompt = sprintf "%${promptl}s: %s", $prompt, $value;
189 return ($priv, $prompt);
192 # turn a hex field into printed hex
196 return sprintf '%X', $val;
199 # take an arg as a hash of call=>time pairs and print it
204 for (sort keys %$ref) {
205 $out .= "$_=" . atime($ref->{$_}) . ", ";
212 # take an arg as an array list and print it
216 return ref $ref ? join(', ', sort @{$ref}) : $ref;
219 # take the arg as an array reference and print as a list of pairs
226 for ($i = 0; $i < @$ref; $i += 2) {
228 my $r2 = @$ref[$i+1];
231 chop $out; # remove last space
232 chop $out; # remove last comma
236 # take the arg as a hash reference and print it out as such
242 foreach my $k (sort keys %$ref) {
243 $out .= "${k}=>$ref->{$k}, ";
245 $out =~ s/, $// if $out;
252 my @a = split /,/, $ref->field_prompt(shift);
253 my @b = split /,/, $ref->field_prompt(shift);
254 return lc $a[1] cmp lc $b[1];
257 # print all the fields for a record according to privilege
259 # The prompt record is of the format '<priv>,<prompt>[,<action>'
260 # and is expanded by promptf above
264 my $self = shift; # is a dxchan
265 my $ref = shift; # is a thingy with field_prompt and fields methods defined
267 my @fields = $ref->fields;
269 my $width = $self->width - 1;
273 # find the maximum length of the prompt
274 foreach $field (@fields) {
275 if (defined $ref->{$field}) {
276 my (undef, $prompt, undef) = split ',', $ref->field_prompt($field);
277 $promptl = length $prompt if length $prompt > $promptl;
282 foreach $field (sort {_sort_fields($ref, $a, $b)} @fields) {
283 if (defined $ref->{$field}) {
284 my ($priv, $ans) = promptf($ref->field_prompt($field), $ref->{$field}, $promptl);
286 if (length $ans > $width) {
287 $Text::Wrap::columns = $width-2;
288 my ($p, $a) = split /: /, $ans, 2;
289 @tmp = split/\n/, Text::Wrap::wrap("$p: ", (' ' x $promptl) . ': ', $a);
293 push @out, @tmp if ($self->priv >= $priv);
299 # generate a regex from a shell type expression
300 # see 'perl cookbook' 6.9
304 $in =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
306 return '^' . $in . "\$";
309 # read in a file into a string and return it.
310 # the filename can be split into a dir and file and the
311 # file can be in upper or lower case.
312 # there can also be a suffix
315 my ($dir, $file, $suffix) = @_;
320 $fn = "$dir/$f.$suffix";
323 $fn = "$dir/$file.$suffix";
336 my $fh = new IO::File $fn;
346 # write out a file in the format required for reading
347 # in via readfilestr, it expects the same arguments
348 # and a reference to an object
358 confess('no object to write in writefilestr') unless $obj;
359 confess('object not a reference in writefilestr') unless ref $obj;
363 $fn = "$dir/$f.$suffix";
366 $fn = "$dir/$file.$suffix";
379 my $fh = new IO::File ">$fn";
381 my $dd = new Data::Dumper([ $obj ]);
385 # $fh->print(@_) if @_ > 0; # any header comments, lines etc
386 $fh->print($dd->Dumpxs);
393 copy(@_) or return $!;
396 # remove leading and trailing spaces from an input string
405 # check that a field only has callsign characters in it
409 (?:\d?[A-Z]{1,2}\d{0,2}/)? # out of area prefix /
410 (?:\d?[A-Z]{1,2}\d{1,5}) # main prefix one (required) - lengthened for special calls
411 [A-Z]{1,8} # callsign letters (required)
412 (?:-(?:\d{1,2}))? # - nn possibly (eg G8BPQ-8)
413 (?:/[0-9A-Z]{1,7})? # / another prefix, callsign or special label (including /MM, /P as well as /EURO or /LGT) possibly
414 (?:/(?:AM?|MM?|P))? # finally /A /AM /M /MM /P
417 # longest callign allowed is 1X11/1Y11XXXXX-11/XXXXXXX/MM
422 return $_[0] =~ m!^(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}}\d+)!x # basic prefix
426 # check that a PC protocol field is valid text
429 return undef unless length $_[0];
430 return undef if $_[0] =~ /[\x00-\x08\x0a-\x1f\x80-\x9f]/;
434 # check that a PC prot flag is fairly valid (doesn't check the difference between 1/0 and */-)
437 return $_[0] =~ /^[01\*\-]+$/;
440 # check that a thing is a frequency
443 return $_[0] =~ /^\d+(?:\.\d+)?$/;
446 # check that a thing is just digits
449 return $_[0] =~ /^[\d]+$/;
452 # does it look like a qra locator?
455 return unless length $_[0] == 4 || length $_[0] == 6;
456 return $_[0] =~ /^[A-Ra-r][A-Ra-r]\d\d(?:[A-Xa-x][A-Xa-x])?$/;
459 # does it look like a valid lat/long
462 return $_[0] =~ /^\s*\d{1,2}\s+\d{1,2}\s*[NnSs]\s+1?\d{1,2}\s+\d{1,2}\s*[EeWw]\s*$/;
465 # is it an ip address?
470 # if ($_[0] =~ /:/) {
471 # if (inet_pton(AF_INET6, $_[0])) {
472 # return ($_[0] =~ /([:0-9a-f]+)/);
475 # if (inet_pton(AF_INET, $_[0])) {
476 # return ($_[0] =~ /([\.\d]+)/);
481 return ($_[0] =~ /^((?:\:?\:?[0-9a-f]{0,4}){1,8}\:?\:?)$/i);
483 return ($_[0] =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
489 # is it a zulu time hhmmZ
492 return $_[0] =~ /^(?:(?:2[0-3])|(?:[01][0-9]))[0-5][0-9]Z$/;
495 # insert an item into a list if it isn't already there returns 1 if there 0 if not
501 return 1 if grep {$_ eq $item } @$list;
506 # delete an item from a list if it is there returns no deleted
513 @$list = grep {$_ ne $item } @$list;
517 # find the correct local_data directory
518 # basically, if there is a local_data directory with this filename and it is younger than the
519 # equivalent one in the (system) data directory then return that name rather than the system one
523 my $lfn = "$main::local_data/$ifn";
524 my $dfn = "$main::data/$ifn";
526 if (-e "$main::local_data") {
527 if ((-e $dfn) && (-e $lfn)) {
528 $lfn = $dfn if -M $dfn < -M $lfn;
530 $lfn = $dfn if -e $dfn;
539 # move a file or a directory from data -> local_data if isn't there already
543 if (-e "$main::data/$ifn" ) {
544 unless (-e "$main::local_data/$ifn") {
545 move("$main::data/$ifn", "$main::local_data/$ifn") or die "localdata_mv: cannot move $ifn from '$main::data' -> '$main::local_data' $!\n";
550 # measure the time taken for something to happen; use Time::HiRes qw(gettimeofday tv_interval);
554 my $tb = shift || [gettimeofday];
555 my $a = int($ta->[0] * 1000) + int($ta->[1] / 1000);
556 my $b = int($tb->[0] * 1000) + int($tb->[1] / 1000);
560 # and in microseconds
564 my $tb = shift || [gettimeofday];
565 my $a = int($ta->[0] * 1000000) + int($ta->[1]);
566 my $b = int($tb->[0] * 1000000) + int($tb->[1]);
577 my $msecs = _diffms($ta, $tb);
580 my $s = "subprocess stats cmd: '$line' $call ${msecs}mS";
581 $s .= " $no lines" if $no;
585 # expects either an array reference or two times (in the correct order [start, end])
589 my $adds = shift // 0;
592 if (ref $b eq 'ARRAY') {
593 $t = $b->[1] - $b->[0];
595 if ($adds && $adds =~ /^\d+$/ && $adds >= $b) {
599 $t = $main::systime - $b;
602 return '-(ve)' if $t < 0;
605 $y = int $t / (86400*365);
606 $out .= sprintf ("%s${y}y", $adds?' ':'') if $y;
607 $t -= $y * 86400 * 365;
609 $out .= sprintf ("%s${d}d", $adds?' ':'') if $d;
612 $out .= sprintf ("%s${h}h", $adds?' ':'') if $h;
615 $out .= sprintf ("%s${m}m", $adds?' ':'') if $m;
616 if (($d == 0 && $adds) || (int $adds && $adds == 2)) {
618 $out .= sprintf ("%s${s}s", $adds?' ':'') if $s;
619 $out ||= sprintf ("%s0s", $adds?' ':'');
621 $out = '0s' unless length $out;
625 # print an array ref of difft refs
631 my $s = $_->[2] ? "($_->[2])" : '';
632 $out .= sprintf "%s=%s$s, ", atime($_->[0]), difft($_->[0], $_->[1]);
640 my ($r) = $_[0] =~ m{^((?:[\w\d]+/)?[\w\d]+(?:/[\w\d]+)*)(?:-\d+)?(?:-\#)?$};
646 my ($c, $ssid) = $_[0] =~ m|^((?:[\w\d]+/)?[\d\w]+(?:/[\w\d]+)*)(?:-(\d+))?(?:-\#)?$|;
649 $ncall .= "-$ssid" if $ssid;
655 return $_[0] =~ /^[\.\d]+$/;