2 # various utilities which are exported globally
4 # Copyright (c) 1998 - Dirk Koopman G1TLH
16 use Time::HiRes qw(gettimeofday tv_interval);
18 use Socket qw(AF_INET6 AF_INET inet_pton);
22 use vars qw(@month %patmap $pi $d2r $r2d @ISA @EXPORT);
26 @EXPORT = qw(atime ztime cldate cldatetime slat slong yesno promptf
27 parray parraypairs phex phash shellregex readfilestr writefilestr
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
37 @month = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
50 # a full time for logging and other purposes
54 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime((defined $t) ? $t : time);
56 my $buf = sprintf "%02d%s%04d\@%02d:%02d:%02d", $mday, $month[$mon], $year, $hour, $min, $sec;
60 # get a zulu time in cluster format (2300Z)
64 $t = defined $t ? $t : time;
66 my ($sec,$min,$hour) = $dst ? localtime($t): gmtime($t);
67 my $buf = sprintf "%02d%02d%s", $hour, $min, ($dst) ? '' : 'Z';
71 # get a cluster format date (23-Jun-1998)
75 $t = defined $t ? $t : time;
77 my ($sec,$min,$hour,$mday,$mon,$year) = $dst ? localtime($t) : gmtime($t);
79 my $buf = sprintf "%2d-%s-%04d", $mday, $month[$mon], $year;
83 # return a cluster style date time
88 my $date = cldate($t, $dst);
89 my $time = ztime($t, $dst);
93 # return a unix date from a cluster date and time
98 my ($thisyear) = (gmtime)[5] + 1900;
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;
104 return 0 unless $time =~ /^([012]\d)([012345]\d)Z$/;
105 $time = "$1:$2 +0000";
106 my $r = str2time("$date $time");
108 return $r == -1 ? undef : $r;
111 # turn a latitude in degrees into a string
115 my ($deg, $min, $let);
116 $let = $n >= 0 ? 'N' : 'S';
119 $min = int ((($n - $deg) * 60) + 0.5);
120 return "$deg $min $let";
123 # turn a longitude in degrees into a string
127 my ($deg, $min, $let);
128 $let = $n >= 0 ? 'E' : 'W';
131 $min = int ((($n - $deg) * 60) + 0.5);
132 return "$deg $min $let";
135 # turn a true into 'yes' and false into 'no'
139 return $n ? $main::yes : $main::no;
142 # provide a data dumpered version of the object passed
146 my $dd = new Data::Dumper([$value]);
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*$//;
158 # format a prompt with its current value and return it with its privilege
161 my ($line, $value, $promptl) = @_;
162 my ($priv, $prompt, $action) = split ',', $line;
164 # if there is an action treat it as a subroutine and replace $value
166 my $q = qq{\$value = $action(\$value)};
168 } elsif (ref $value) {
172 $prompt = sprintf "%${promptl}s: %s", $prompt, $value;
173 return ($priv, $prompt);
176 # turn a hex field into printed hex
180 return sprintf '%X', $val;
183 # take an arg as a hash of call=>time pairs and print it
188 for (sort keys %$ref) {
189 $out .= "$_=" . atime($ref->{$_}) . ", ";
196 # take an arg as an array list and print it
200 return ref $ref ? join(', ', sort @{$ref}) : $ref;
203 # take the arg as an array reference and print as a list of pairs
210 for ($i = 0; $i < @$ref; $i += 2) {
212 my $r2 = @$ref[$i+1];
215 chop $out; # remove last space
216 chop $out; # remove last comma
220 # take the arg as a hash reference and print it out as such
226 foreach my $k (sort keys %$ref) {
227 $out .= "${k}=>$ref->{$k}, ";
229 $out =~ s/, $// if $out;
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];
241 # print all the fields for a record according to privilege
243 # The prompt record is of the format '<priv>,<prompt>[,<action>'
244 # and is expanded by promptf above
248 my $self = shift; # is a dxchan
249 my $ref = shift; # is a thingy with field_prompt and fields methods defined
251 my @fields = $ref->fields;
253 my $width = $self->width - 1;
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;
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);
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);
277 push @out, @tmp if ($self->priv >= $priv);
283 # generate a regex from a shell type expression
284 # see 'perl cookbook' 6.9
288 $in =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
290 return '^' . $in . "\$";
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
299 my ($dir, $file, $suffix) = @_;
304 $fn = "$dir/$f.$suffix";
307 $fn = "$dir/$file.$suffix";
320 my $fh = new IO::File $fn;
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
342 confess('no object to write in writefilestr') unless $obj;
343 confess('object not a reference in writefilestr') unless ref $obj;
347 $fn = "$dir/$f.$suffix";
350 $fn = "$dir/$file.$suffix";
363 my $fh = new IO::File ">$fn";
365 my $dd = new Data::Dumper([ $obj ]);
369 # $fh->print(@_) if @_ > 0; # any header comments, lines etc
370 $fh->print($dd->Dumpxs);
377 copy(@_) or return $!;
380 # remove leading and trailing spaces from an input string
389 # check that a field only has callsign characters in it
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
401 # longest callign allowed is 1X11/1Y11XXXXX-11/XXXXXXX/MM
406 return $_[0] =~ m!^(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}}\d+)!x # basic prefix
410 # check that a PC protocol field is valid text
413 return undef unless length $_[0];
414 return undef if $_[0] =~ /[\x00-\x08\x0a-\x1f\x80-\x9f]/;
418 # check that a PC prot flag is fairly valid (doesn't check the difference between 1/0 and */-)
421 return $_[0] =~ /^[01\*\-]+$/;
424 # check that a thing is a frequency
427 return $_[0] =~ /^\d+(?:\.\d+)?$/;
430 # check that a thing is just digits
433 return $_[0] =~ /^[\d]+$/;
436 # does it look like a qra locator?
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])?$/;
443 # does it look like a valid lat/long
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*$/;
449 # is it an ip address?
454 if (inet_pton(AF_INET6, $_[0])) {
455 return ($_[0] =~ /([:0-9a-f]+)/);
458 # return ($1) if $_[0] =~ /^(\:?(?:\:?[0-9a-f]{1,4}){1,8}?)$/i;
461 return ($_[0] =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
466 # is it a zulu time hhmmZ
469 return $_[0] =~ /^(?:(?:2[0-3])|(?:[01][0-9]))[0-5][0-9]Z$/;
472 # insert an item into a list if it isn't already there returns 1 if there 0 if not
478 return 1 if grep {$_ eq $item } @$list;
483 # delete an item from a list if it is there returns no deleted
490 @$list = grep {$_ ne $item } @$list;
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
500 my $lfn = "$main::local_data/$ifn";
501 my $dfn = "$main::data/$ifn";
503 if (-e "$main::local_data") {
504 if ((-e $dfn) && (-e $lfn)) {
505 $lfn = $dfn if -M $dfn < -M $lfn;
507 $lfn = $dfn if -e $dfn;
516 # move a file or a directory from data -> local_data if isn't there already
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";
527 # measure the time taken for something to happen; use Time::HiRes qw(gettimeofday tv_interval);
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);
537 # and in microseconds
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]);
554 my $msecs = _diffms($ta, $tb);
557 my $s = "subprocess stats cmd: '$line' $call ${msecs}mS";
558 $s .= " $no lines" if $no;
562 # expects either an array reference or two times (in the correct order [start, end])
569 if (ref $b eq 'ARRAY') {
570 $t = $b->[1] - $b->[0];
572 if ($adds && $adds =~ /^\d+$/ && $adds >= $b) {
576 $t = $main::systime - $b;
579 return '-(ve)' if $t < 0;
582 $y = int $t / (86400*365);
583 $out .= sprintf ("%s${y}y", $adds?' ':'') if $y;
584 $t -= $y * 86400 * 365;
586 $out .= sprintf ("%s${d}d", $adds?' ':'') if $d;
589 $out .= sprintf ("%s${h}h", $adds?' ':'') if $h;
592 $out .= sprintf ("%s${m}m", $adds?' ':'') if $m;
593 if (($d == 0 && $adds) || (int $adds && $adds == 2)) {
595 $out .= sprintf ("%s${s}s", $adds?' ':'') if $s;
596 $out ||= sprintf ("%s0s", $adds?' ':'');
598 $out = '0s' unless length $out;
602 # print an array ref of difft refs
608 my $s = $_->[2] ? "($_->[2])" : '';
609 $out .= sprintf "%s=%s$s, ", atime($_->[0]), difft($_->[0], $_->[1]);
617 my ($r) = $_[0] =~ m{^((?:[\w\d]+/)?[\w\d]+(?:/[\w\d]+)*)(?:-\d+)?(?:-\#)?$};
623 my ($c, $ssid) = $_[0] =~ m|^((?:[\w\d]+/)?[\d\w]+(?:/[\w\d]+)*)(?:-(\d+))?(?:-\#)?$|;
626 $ncall .= "-$ssid" if $ssid;
632 return $_[0] =~ /^[\.\d]+$/;