2 # various utilities which are exported globally
4 # Copyright (c) 1998 - Dirk Koopman G1TLH
16 use Time::HiRes qw(gettimeofday tv_interval);
21 use vars qw(@month %patmap $pi $d2r $r2d @ISA @EXPORT);
25 @EXPORT = qw(atime ztime cldate cldatetime slat slong yesno promptf
26 parray parraypairs phex phash shellregex readfilestr writefilestr
28 print_all_fields cltounix unpad is_callsign is_latlong
29 is_qra is_freq is_digits is_pctext is_pcflag insertitem deleteitem
30 is_prefix dd is_ipaddr $pi $d2r $r2d localdata localdata_mv
31 diffms _diffms _diffus difft parraydifft is_ztime basecall
36 @month = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
49 # a full time for logging and other purposes
53 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime((defined $t) ? $t : time);
55 my $buf = sprintf "%02d%s%04d\@%02d:%02d:%02d", $mday, $month[$mon], $year, $hour, $min, $sec;
59 # get a zulu time in cluster format (2300Z)
63 $t = defined $t ? $t : time;
65 my ($sec,$min,$hour) = $dst ? localtime($t): gmtime($t);
66 my $buf = sprintf "%02d%02d%s", $hour, $min, ($dst) ? '' : 'Z';
70 # get a cluster format date (23-Jun-1998)
74 $t = defined $t ? $t : time;
76 my ($sec,$min,$hour,$mday,$mon,$year) = $dst ? localtime($t) : gmtime($t);
78 my $buf = sprintf "%2d-%s-%04d", $mday, $month[$mon], $year;
82 # return a cluster style date time
87 my $date = cldate($t, $dst);
88 my $time = ztime($t, $dst);
92 # return a unix date from a cluster date and time
97 my ($thisyear) = (gmtime)[5] + 1900;
99 return 0 unless $date =~ /^\s*(\d+)-(\w\w\w)-([12][90]\d\d)$/;
100 return 0 if $3 > 2036;
101 return 0 unless abs($thisyear-$3) <= 1;
103 return 0 unless $time =~ /^([012]\d)([012345]\d)Z$/;
104 $time = "$1:$2 +0000";
105 my $r = str2time("$date $time");
107 return $r == -1 ? undef : $r;
110 # turn a latitude in degrees into a string
114 my ($deg, $min, $let);
115 $let = $n >= 0 ? 'N' : 'S';
118 $min = int ((($n - $deg) * 60) + 0.5);
119 return "$deg $min $let";
122 # turn a longitude in degrees into a string
126 my ($deg, $min, $let);
127 $let = $n >= 0 ? 'E' : 'W';
130 $min = int ((($n - $deg) * 60) + 0.5);
131 return "$deg $min $let";
134 # turn a true into 'yes' and false into 'no'
138 return $n ? $main::yes : $main::no;
141 # provide a data dumpered version of the object passed
145 my $dd = new Data::Dumper([$value]);
148 $dd->Quotekeys($] < 5.005 ? 1 : 0);
149 $value = $dd->Dumpxs;
150 $value =~ s/([\r\n\t])/sprintf("%%%02X", ord($1))/eg;
151 $value =~ s/^\s*\[//;
152 $value =~ s/\]\s*$//;
157 # format a prompt with its current value and return it with its privilege
160 my ($line, $value, $promptl) = @_;
161 my ($priv, $prompt, $action) = split ',', $line;
163 # if there is an action treat it as a subroutine and replace $value
165 my $q = qq{\$value = $action(\$value)};
167 } elsif (ref $value) {
171 $prompt = sprintf "%${promptl}s: %s", $prompt, $value;
172 return ($priv, $prompt);
175 # turn a hex field into printed hex
179 return sprintf '%X', $val;
182 # take an arg as a hash of call=>time pairs and print it
187 for (sort keys %$ref) {
188 $out .= "$_=" . atime($ref->{$_}) . ", ";
195 # take an arg as an array list and print it
199 return ref $ref ? join(', ', sort @{$ref}) : $ref;
202 # take the arg as an array reference and print as a list of pairs
209 for ($i = 0; $i < @$ref; $i += 2) {
211 my $r2 = @$ref[$i+1];
214 chop $out; # remove last space
215 chop $out; # remove last comma
219 # take the arg as a hash reference and print it out as such
225 foreach my $k (sort keys %$ref) {
226 $out .= "${k}=>$ref->{$k}, ";
228 $out =~ s/, $// if $out;
235 my @a = split /,/, $ref->field_prompt(shift);
236 my @b = split /,/, $ref->field_prompt(shift);
237 return lc $a[1] cmp lc $b[1];
240 # print all the fields for a record according to privilege
242 # The prompt record is of the format '<priv>,<prompt>[,<action>'
243 # and is expanded by promptf above
247 my $self = shift; # is a dxchan
248 my $ref = shift; # is a thingy with field_prompt and fields methods defined
250 my @fields = $ref->fields;
252 my $width = $self->width - 1;
256 # find the maximum length of the prompt
257 foreach $field (@fields) {
258 if (defined $ref->{$field}) {
259 my (undef, $prompt, undef) = split ',', $ref->field_prompt($field);
260 $promptl = length $prompt if length $prompt > $promptl;
265 foreach $field (sort {_sort_fields($ref, $a, $b)} @fields) {
266 if (defined $ref->{$field}) {
267 my ($priv, $ans) = promptf($ref->field_prompt($field), $ref->{$field}, $promptl);
269 if (length $ans > $width) {
270 $Text::Wrap::columns = $width-2;
271 my ($p, $a) = split /: /, $ans, 2;
272 @tmp = split/\n/, Text::Wrap::wrap("$p: ", (' ' x $promptl) . ': ', $a);
276 push @out, @tmp if ($self->priv >= $priv);
282 # generate a regex from a shell type expression
283 # see 'perl cookbook' 6.9
287 $in =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
289 return '^' . $in . "\$";
292 # read in a file into a string and return it.
293 # the filename can be split into a dir and file and the
294 # file can be in upper or lower case.
295 # there can also be a suffix
298 my ($dir, $file, $suffix) = @_;
303 $fn = "$dir/$f.$suffix";
306 $fn = "$dir/$file.$suffix";
319 my $fh = new IO::File $fn;
329 # write out a file in the format required for reading
330 # in via readfilestr, it expects the same arguments
331 # and a reference to an object
341 confess('no object to write in writefilestr') unless $obj;
342 confess('object not a reference in writefilestr') unless ref $obj;
346 $fn = "$dir/$f.$suffix";
349 $fn = "$dir/$file.$suffix";
362 my $fh = new IO::File ">$fn";
364 my $dd = new Data::Dumper([ $obj ]);
368 # $fh->print(@_) if @_ > 0; # any header comments, lines etc
369 $fh->print($dd->Dumpxs);
376 copy(@_) or return $!;
379 # remove leading and trailing spaces from an input string
388 # check that a field only has callsign characters in it
392 (?:\d?[A-Z]{1,2}\d{0,2}/)? # out of area prefix /
393 (?:\d?[A-Z]{1,2}\d{1,5}) # main prefix one (required) - lengthened for special calls
394 [A-Z]{1,8} # callsign letters (required)
395 (?:-(?:\d{1,2}))? # - nn possibly (eg G8BPQ-8)
396 (?:/[0-9A-Z]{1,7})? # / another prefix, callsign or special label (including /MM, /P as well as /EURO or /LGT) possibly
397 (?:/(?:AM?|MM?|P))? # finally /A /AM /M /MM /P
400 # longest callign allowed is 1X11/1Y11XXXXX-11/XXXXXXX/MM
405 return $_[0] =~ m!^(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}}\d+)!x # basic prefix
409 # check that a PC protocol field is valid text
412 return undef unless length $_[0];
413 return undef if $_[0] =~ /[\x00-\x08\x0a-\x1f\x80-\x9f]/;
417 # check that a PC prot flag is fairly valid (doesn't check the difference between 1/0 and */-)
420 return $_[0] =~ /^[01\*\-]+$/;
423 # check that a thing is a frequency
426 return $_[0] =~ /^\d+(?:\.\d+)?$/;
429 # check that a thing is just digits
432 return $_[0] =~ /^[\d]+$/;
435 # does it look like a qra locator?
438 return unless length $_[0] == 4 || length $_[0] == 6;
439 return $_[0] =~ /^[A-Ra-r][A-Ra-r]\d\d(?:[A-Xa-x][A-Xa-x])?$/;
442 # does it look like a valid lat/long
445 return $_[0] =~ /^\s*\d{1,2}\s+\d{1,2}\s*[NnSs]\s+1?\d{1,2}\s+\d{1,2}\s*[EeWw]\s*$/;
448 # is it an ip address?
451 return $_[0] =~ /^\d+\.\d+\.\d+\.\d+$/ || $_[0] =~ /^[0-9a-f:,]+$/;
454 # is it a zulu time hhmmZ
457 return $_[0] =~ /^(?:(?:2[0-3])|(?:[01][0-9]))[0-5][0-9]Z$/;
460 # insert an item into a list if it isn't already there returns 1 if there 0 if not
466 return 1 if grep {$_ eq $item } @$list;
471 # delete an item from a list if it is there returns no deleted
478 @$list = grep {$_ ne $item } @$list;
482 # find the correct local_data directory
483 # basically, if there is a local_data directory with this filename and it is younger than the
484 # equivalent one in the (system) data directory then return that name rather than the system one
488 my $lfn = "$main::local_data/$ifn";
489 my $dfn = "$main::data/$ifn";
491 if (-e "$main::local_data") {
492 if ((-e $dfn) && (-e $lfn)) {
493 $lfn = $dfn if -M $dfn < -M $lfn;
495 $lfn = $dfn if -e $dfn;
504 # move a file or a directory from data -> local_data if isn't there already
508 if (-e "$main::data/$ifn" ) {
509 unless (-e "$main::local_data/$ifn") {
510 move("$main::data/$ifn", "$main::local_data/$ifn") or die "localdata_mv: cannot move $ifn from '$main::data' -> '$main::local_data' $!\n";
515 # measure the time taken for something to happen; use Time::HiRes qw(gettimeofday tv_interval);
519 my $tb = shift || [gettimeofday];
520 my $a = int($ta->[0] * 1000) + int($ta->[1] / 1000);
521 my $b = int($tb->[0] * 1000) + int($tb->[1] / 1000);
525 # and in microseconds
529 my $tb = shift || [gettimeofday];
530 my $a = int($ta->[0] * 1000000) + int($ta->[1]);
531 my $b = int($tb->[0] * 1000000) + int($tb->[1]);
542 my $msecs = _diffms($ta, $tb);
545 my $s = "subprocess stats cmd: '$line' $call ${msecs}mS";
546 $s .= " $no lines" if $no;
550 # expects either an array reference or two times (in the correct order [start, end])
557 if (ref $b eq 'ARRAY') {
558 $t = $b->[1] - $b->[0];
560 if ($adds && $adds =~ /^\d+$/ && $adds >= $b) {
564 $t = $main::systime - $b;
567 return '-(ve)' if $t < 0;
570 $y = int $t / (86400*365);
571 $out .= sprintf ("%s${y}y", $adds?' ':'') if $y;
572 $t -= $y * 86400 * 365;
574 $out .= sprintf ("%s${d}d", $adds?' ':'') if $d;
577 $out .= sprintf ("%s${h}h", $adds?' ':'') if $h;
580 $out .= sprintf ("%s${m}m", $adds?' ':'') if $m;
581 if ($d == 0 && $adds || $adds == 2) {
583 $out .= sprintf ("%s${s}s", $adds?' ':'') if $s;
584 $out ||= sprintf ("%s0s", $adds?' ':'');
586 $out = '0s' unless length $out;
590 # print an array ref of difft refs
596 my $s = $_->[2] ? "($_->[2])" : '';
597 $out .= sprintf "%s=%s$s, ", atime($_->[0]), difft($_->[0], $_->[1]);
605 my ($r) = $_[0] =~ m{^((?:[\w\d]+/)?[\w\d]+(?:/[\w\d]+)*)(?:-\d+)?(?:-\#)?$};
611 my ($c, $ssid) = $_[0] =~ m|^((?:[\w\d]+/)?[\d\w]+(?:/[\w\d]+)*)(?:-(\d+))?(?:-\#)?$|;
614 $ncall .= "-$ssid" if $ssid;