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 ahour piplist mindate adate
34 @month = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
47 # a full time for logging and other purposes
51 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime((defined $t) ? $t : time);
53 my $buf = sprintf "%02d%s%04d\@%02d:%02d:%02d", $mday, $month[$mon], $year, $hour, $min, $sec;
61 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime((defined $t) ? $t : time);
62 my $buf = sprintf "%02d:%02d:%02d", $hour, $min, $sec;
69 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime((defined $t) ? $t : time);
71 my $buf = sprintf "%02d%s%04d", $mday, $month[$mon], $year;
75 # get a zulu time in cluster format (2300Z)
79 $t = defined $t ? $t : time;
81 my ($sec,$min,$hour) = $dst ? localtime($t): gmtime($t);
82 my $buf = sprintf "%02d%02d%s", $hour, $min, ($dst) ? '' : 'Z';
86 # get a cluster format date (23-Jun-1998)
90 $t = defined $t ? $t : time;
92 my ($sec,$min,$hour,$mday,$mon,$year) = $dst ? localtime($t) : gmtime($t);
94 my $buf = sprintf "%2d-%s-%04d", $mday, $month[$mon], $year;
98 # return a cluster style date time
103 my $date = cldate($t, $dst);
104 my $time = ztime($t, $dst);
105 return "$date $time";
108 # return a unix date from a cluster date and time
113 my ($thisyear) = (gmtime)[5] + 1900;
115 return 0 unless $date =~ /^\s*(\d+)-(\w\w\w)-([12][90]\d\d)$/;
116 return 0 if $3 > 2036;
117 return 0 unless abs($thisyear-$3) <= 1;
119 return 0 unless $time =~ /^([012]\d)([012345]\d)Z$/;
120 $time = "$1:$2 +0000";
121 my $r = str2time("$date $time");
123 return $r == -1 ? undef : $r;
126 # turn a latitude in degrees into a string
130 my ($deg, $min, $let);
131 $let = $n >= 0 ? 'N' : 'S';
134 $min = int ((($n - $deg) * 60) + 0.5);
135 return "$deg $min $let";
138 # turn a longitude in degrees into a string
142 my ($deg, $min, $let);
143 $let = $n >= 0 ? 'E' : 'W';
146 $min = int ((($n - $deg) * 60) + 0.5);
147 return "$deg $min $let";
150 # turn a true into 'yes' and false into 'no'
154 return $n ? $main::yes : $main::no;
157 # provide a data dumpered version of the object passed
161 my $dd = new Data::Dumper([$value]);
164 $dd->Quotekeys($] < 5.005 ? 1 : 0);
165 $value = $dd->Dumpxs;
166 $value =~ s/([\r\n\t])/sprintf("%%%02X", ord($1))/eg;
167 $value =~ s/^\s*\[//;
168 $value =~ s/\]\s*$//;
173 # format a prompt with its current value and return it with its privilege
176 my ($line, $value) = @_;
177 my ($priv, $prompt, $action) = split ',', $line;
179 # if there is an action treat it as a subroutine and replace $value
181 my $q = qq{\$value = $action(\$value)};
183 } elsif (ref $value) {
186 $prompt = sprintf "%15s: %s", $prompt, $value;
187 return ($priv, $prompt);
190 # turn a hex field into printed hex
194 return sprintf '%X', $val;
197 # take an arg as a hash of call=>time pairs and print it
202 for (sort keys %$ref) {
203 $out .= "$_=$ref->{$_}, ";
210 # take an arg as an array list and print it
214 return ref $ref ? join(',', @{$ref}) : $ref;
217 # take the arg as an array reference and print as a list of pairs
224 for ($i = 0; $i < @$ref; $i += 2) {
226 my $r2 = @$ref[$i+1];
229 chop $out; # remove last space
230 chop $out; # remove last comma
234 # take the arg as a hash reference and print it out as such
240 while (my ($k,$v) = each %$ref) {
241 if (ref $v eq 'ARRAY') {
242 $out = "${k}=>[" . parray($v) . "],";
243 } elsif (ref $v eq 'HASH') {
244 $out = "${k}=>{" . phash($v) . "},";
249 chop $out; # remove last comma
258 if ($main::system-$t < 86400 ) {
260 } elsif ($main::system-$t < 365*86400) {
262 chop $out for (1..4);
263 $out .= ' ' . atime($t);
264 chop $out for (1..3);
272 # like phash but prints dates and times
278 return $ref unless ref $ref;
280 while (my ($k,$v) = each %$ref) {
281 if (ref $v eq 'HASH') {
283 } elsif (ref $v eq 'ARRAY') {
284 $out .= join(',', map { sprintf "$_->[0]@%s", mindate($_->[1]) } ref $v->[0] eq 'ARRAY' ? @$v : $v);
289 $out =~ s/,+$//; # remove last comma
296 my @a = split /,/, $ref->field_prompt(shift);
297 my @b = split /,/, $ref->field_prompt(shift);
298 return lc $a[1] cmp lc $b[1];
301 # print all the fields for a record according to privilege
303 # The prompt record is of the format '<priv>,<prompt>[,<action>'
304 # and is expanded by promptf above
308 my $self = shift; # is a dxchan
309 my $ref = shift; # is a thingy with field_prompt and fields methods defined
311 my @fields = $ref->fields;
313 my $width = $self->width - 1;
316 foreach $field (sort {_sort_fields($ref, $a, $b)} @fields) {
317 if (defined $ref->{$field}) {
318 my ($priv, $ans) = promptf($ref->field_prompt($field), $ref->{$field});
320 if (length $ans > $width) {
321 my ($p, $a) = split /: /, $ans, 2;
322 my $l = (length $p) + 2;
323 my $al = ($width - 1) - $l;
325 while (length $a > $al ) {
326 ($bit, $a) = unpack "A$al A*", $a;
327 push @tmp, "$p: $bit";
330 push @tmp, "$p: $a" if length $a;
334 push @out, @tmp if ($self->priv >= $priv);
340 # generate a regex from a shell type expression
341 # see 'perl cookbook' 6.9
345 $in =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
346 return '^' . $in . "\$";
349 # read in a file into a string and return it.
350 # the filename can be split into a dir and file and the
351 # file can be in upper or lower case.
352 # there can also be a suffix
355 my ($dir, $file, $suffix) = @_;
360 $fn = "$dir/$f.$suffix";
363 $fn = "$dir/$file.$suffix";
376 my $fh = new IO::File $fn;
386 # write out a file in the format required for reading
387 # in via readfilestr, it expects the same arguments
388 # and a reference to an object
398 confess('no object to write in writefilestr') unless $obj;
399 confess('object not a reference in writefilestr') unless ref $obj;
403 $fn = "$dir/$f.$suffix";
406 $fn = "$dir/$file.$suffix";
419 my $fh = new IO::File ">$fn";
421 my $dd = new Data::Dumper([ $obj ]);
425 # $fh->print(@_) if @_ > 0; # any header comments, lines etc
426 $fh->print($dd->Dumpxs);
433 copy(@_) or return $!;
436 # remove leading and trailing spaces from an input string
445 # check that a field only has callsign characters in it
449 (?:\d?[A-Z]{1,2}\d*/)? # out of area prefix /
450 (?:\d?[A-Z]{1,2}\d+) # main prefix one (required)
451 [A-Z]{1,5} # callsign letters (required)
452 (?:-(?:\d{1,2}|\#))? # - nn possibly (eg G8BPQ-8) or -# (an RBN spot)
453 (?:/[0-9A-Z]{1,7})? # / another prefix, callsign or special label (including /MM, /P as well as /EURO or /LGT) possibly
456 # longest callign allowed is 1X11/1Y11XXXXX-11/XXXXXXX
461 return $_[0] =~ m!^(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}}\d+)!x # basic prefix
465 # check that a PC protocol field is valid text
468 return undef unless length $_[0];
469 return undef if $_[0] =~ /[\x00-\x08\x0a-\x1f\x80-\x9f]/;
473 # check that a PC prot flag is fairly valid (doesn't check the difference between 1/0 and */-)
476 return $_[0] =~ /^[01\*\-]+$/;
479 # check that a thing is a frequency
482 return $_[0] =~ /^\d+(?:\.\d+)?$/;
485 # check that a thing is just digits
488 return $_[0] =~ /^[\d]+$/;
491 # does it look like a qra locator?
494 return unless length $_[0] == 4 || length $_[0] == 6;
495 return $_[0] =~ /^[A-Ra-r][A-Ra-r]\d\d(?:[A-Xa-x][A-Xa-x])?$/;
498 # does it look like a valid lat/long
501 return $_[0] =~ /^\s*\d{1,2}\s+\d{1,2}\s*[NnSs]\s+1?\d{1,2}\s+\d{1,2}\s*[EeWw]\s*$/;
504 # is it an ip address?
507 return $_[0] =~ /^\d+\.\d+\.\d+\.\d+$/ || $_[0] =~ /^[0-9a-f:,]+$/;
510 # insert an item into a list if it isn't already there returns 1 if there 0 if not
516 return 1 if grep {$_ eq $item } @$list;
521 # delete an item from a list if it is there returns no deleted
528 @$list = grep {$_ ne $item } @$list;
532 # find the correct local_data directory
533 # basically, if there is a local_data directory with this filename and it is younger than the
534 # equivalent one in the (system) data directory then return that name rather than the system one
538 my $ofn = "$main::local_data/$ifn";
541 if (-e "$main::local_data") {
542 $tfn = "$main::data/$ifn";
543 if ((-e $tfn) && (-e $ofn)) {
544 $ofn = $tfn if -M $ofn < -M $tfn;
546 $ofn = $tfn if -e $tfn;
553 # move a file or a directory from data -> local_data if isn't there already
557 if (-e "$main::data/$ifn" ) {
558 unless (-e "$main::local_data/$ifn") {
559 move("$main::data/$ifn", "$main::local_data/$ifn") or die "localdata_mv: cannot move $ifn from '$main::data' -> '$main::local_data' $!\n";
564 # measure the time taken for something to happen; use Time::HiRes qw(gettimeofday tv_interval);
568 my $tb = shift || [gettimeofday];
569 my $a = int($ta->[0] * 1000) + int($ta->[1] / 1000);
570 my $b = int($tb->[0] * 1000) + int($tb->[1] / 1000);
581 my $msecs = _diffms($ta, $tb);
584 my $s = "subprocess stats cmd: '$line' $call ${msecs}mS";
585 $s .= " $no lines" if $no;