put dx.pl into an explicit handle sub
[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
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             );
31
32
33 @month = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
34 %patmap = (
35                    '*' => '.*',
36                    '?' => '.',
37                    '[' => '[',
38                    ']' => ']'
39 );
40
41 $pi = 3.141592653589;
42 $d2r = ($pi/180);
43 $r2d = (180/$pi);
44
45
46 # a full time for logging and other purposes
47 sub atime
48 {
49         my $t = shift;
50         my ($sec,$min,$hour,$mday,$mon,$year) = gmtime((defined $t) ? $t : time);
51         $year += 1900;
52         my $buf = sprintf "%02d%s%04d\@%02d:%02d:%02d", $mday, $month[$mon], $year, $hour, $min, $sec;
53         return $buf;
54 }
55
56 # get a zulu time in cluster format (2300Z)
57 sub ztime
58 {
59         my $t = shift;
60         $t = defined $t ? $t : time;
61         my $dst = shift;
62         my ($sec,$min,$hour) = $dst ? localtime($t): gmtime($t);
63         my $buf = sprintf "%02d%02d%s", $hour, $min, ($dst) ? '' : 'Z';
64         return $buf;
65 }
66
67 # get a cluster format date (23-Jun-1998)
68 sub cldate
69 {
70         my $t = shift;
71         $t = defined $t ? $t : time;
72         my $dst = shift;
73         my ($sec,$min,$hour,$mday,$mon,$year) = $dst ? localtime($t) : gmtime($t);
74         $year += 1900;
75         my $buf = sprintf "%2d-%s-%04d", $mday, $month[$mon], $year;
76         return $buf;
77 }
78
79 # return a cluster style date time
80 sub cldatetime
81 {
82         my $t = shift;
83         my $dst = shift;
84         my $date = cldate($t, $dst);
85         my $time = ztime($t, $dst);
86         return "$date $time";
87 }
88
89 # return a unix date from a cluster date and time
90 sub cltounix
91 {
92         my $date = shift;
93         my $time = shift;
94         my ($thisyear) = (gmtime)[5] + 1900;
95
96         return 0 unless $date =~ /^\s*(\d+)-(\w\w\w)-([12][90]\d\d)$/;
97         return 0 if $3 > 2036;
98         return 0 unless abs($thisyear-$3) <= 1;
99         $date = "$1 $2 $3";
100         return 0 unless $time =~ /^([012]\d)([012345]\d)Z$/;
101         $time = "$1:$2 +0000";
102         my $r = str2time("$date $time");
103         return $r unless $r;
104         return $r == -1 ? undef : $r;
105 }
106
107 # turn a latitude in degrees into a string
108 sub slat
109 {
110         my $n = shift;
111         my ($deg, $min, $let);
112         $let = $n >= 0 ? 'N' : 'S';
113         $n = abs $n;
114         $deg = int $n;
115         $min = int ((($n - $deg) * 60) + 0.5);
116         return "$deg $min $let";
117 }
118
119 # turn a longitude in degrees into a string
120 sub slong
121 {
122         my $n = shift;
123         my ($deg, $min, $let);
124         $let = $n >= 0 ? 'E' : 'W';
125         $n = abs $n;
126         $deg = int $n;
127         $min = int ((($n - $deg) * 60) + 0.5);
128         return "$deg $min $let";
129 }
130
131 # turn a true into 'yes' and false into 'no'
132 sub yesno
133 {
134         my $n = shift;
135         return $n ? $main::yes : $main::no;
136 }
137
138 # provide a data dumpered version of the object passed
139 sub dd
140 {
141         my $value = shift;
142         my $dd = new Data::Dumper([$value]);
143         $dd->Indent(0);
144         $dd->Terse(1);
145     $dd->Quotekeys($] < 5.005 ? 1 : 0);
146         $value = $dd->Dumpxs;
147         $value =~ s/([\r\n\t])/sprintf("%%%02X", ord($1))/eg;
148         $value =~ s/^\s*\[//;
149     $value =~ s/\]\s*$//;
150         
151         return $value;
152 }
153
154 # format a prompt with its current value and return it with its privilege
155 sub promptf
156 {
157         my ($line, $value) = @_;
158         my ($priv, $prompt, $action) = split ',', $line;
159
160         # if there is an action treat it as a subroutine and replace $value
161         if ($action) {
162                 my $q = qq{\$value = $action(\$value)};
163                 eval $q;
164         } elsif (ref $value) {
165                 $value = dd($value);
166         }
167         $prompt = sprintf "%15s: %s", $prompt, $value;
168         return ($priv, $prompt);
169 }
170
171 # turn a hex field into printed hex
172 sub phex
173 {
174         my $val = shift;
175         return sprintf '%X', $val;
176 }
177
178 # take an arg as a hash of call=>time pairs and print it
179 sub ptimelist
180 {
181         my $ref = shift;
182         my $out;
183         for (sort keys %$ref) {
184                 $out .= "$_=$ref->{$_}, ";
185         }
186         chop $out;
187         chop $out;
188         return $out;    
189 }
190
191 # take an arg as an array list and print it
192 sub parray
193 {
194         my $ref = shift;
195         return ref $ref ? join(', ', @{$ref}) : $ref;
196 }
197
198 # take the arg as an array reference and print as a list of pairs
199 sub parraypairs
200 {
201         my $ref = shift;
202         my $i;
203         my $out;
204
205         for ($i = 0; $i < @$ref; $i += 2) {
206                 my $r1 = @$ref[$i];
207                 my $r2 = @$ref[$i+1];
208                 $out .= "$r1-$r2, ";
209         }
210         chop $out;                                      # remove last space
211         chop $out;                                      # remove last comma
212         return $out;
213 }
214
215 # take the arg as a hash reference and print it out as such
216 sub phash
217 {
218         my $ref = shift;
219         my $out;
220
221         while (my ($k,$v) = each %$ref) {
222                 $out .= "${k}=>$v, ";
223         }
224         chop $out;                                      # remove last space
225         chop $out;                                      # remove last comma
226         return $out;
227 }
228
229 sub _sort_fields
230 {
231         my $ref = shift;
232         my @a = split /,/, $ref->field_prompt(shift); 
233         my @b = split /,/, $ref->field_prompt(shift); 
234         return lc $a[1] cmp lc $b[1];
235 }
236
237 # print all the fields for a record according to privilege
238 #
239 # The prompt record is of the format '<priv>,<prompt>[,<action>'
240 # and is expanded by promptf above
241 #
242 sub print_all_fields
243 {
244         my $self = shift;                       # is a dxchan
245         my $ref = shift;                        # is a thingy with field_prompt and fields methods defined
246         my @out;
247         my @fields = $ref->fields;
248         my $field;
249         my $width = $self->width - 1;
250         $width ||= 80;
251
252         foreach $field (sort {_sort_fields($ref, $a, $b)} @fields) {
253                 if (defined $ref->{$field}) {
254                         my ($priv, $ans) = promptf($ref->field_prompt($field), $ref->{$field});
255                         my @tmp;
256                         if (length $ans > $width) {
257                                 my ($p, $a) = split /: /, $ans, 2;
258                                 my $l = (length $p) + 2;
259                                 my $al = ($width - 1) - $l;
260                                 my $bit;
261                                 while (length $a > $al ) {
262                                         ($bit, $a) = unpack "A$al A*", $a;
263                                         push @tmp, "$p: $bit";
264                                         $p = ' ' x ($l - 2);
265                                 }
266                                 push @tmp, "$p: $a" if length $a;
267                         } else {
268                                 push @tmp, $ans;
269                         }
270                         push @out, @tmp if ($self->priv >= $priv);
271                 }
272         }
273         return @out;
274 }
275
276 # generate a regex from a shell type expression 
277 # see 'perl cookbook' 6.9
278 sub shellregex
279 {
280         my $in = shift;
281         $in =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
282         return '^' . $in . "\$";
283 }
284
285 # read in a file into a string and return it. 
286 # the filename can be split into a dir and file and the 
287 # file can be in upper or lower case.
288 # there can also be a suffix
289 sub readfilestr
290 {
291         my ($dir, $file, $suffix) = @_;
292         my $fn;
293         my $f;
294         if ($suffix) {
295                 $f = uc $file;
296                 $fn = "$dir/$f.$suffix";
297                 unless (-e $fn) {
298                         $f = lc $file;
299                         $fn = "$dir/$file.$suffix";
300                 }
301         } elsif ($file) {
302                 $f = uc $file;
303                 $fn = "$dir/$file";
304                 unless (-e $fn) {
305                         $f = lc $file;
306                         $fn = "$dir/$file";
307                 }
308         } else {
309                 $fn = $dir;
310         }
311
312         my $fh = new IO::File $fn;
313         my $s = undef;
314         if ($fh) {
315                 local $/ = undef;
316                 $s = <$fh>;
317                 $fh->close;
318         }
319         return $s;
320 }
321
322 # write out a file in the format required for reading
323 # in via readfilestr, it expects the same arguments 
324 # and a reference to an object
325 sub writefilestr
326 {
327         my $dir = shift;
328         my $file = shift;
329         my $suffix = shift;
330         my $obj = shift;
331         my $fn;
332         my $f;
333         
334         confess('no object to write in writefilestr') unless $obj;
335         confess('object not a reference in writefilestr') unless ref $obj;
336         
337         if ($suffix) {
338                 $f = uc $file;
339                 $fn = "$dir/$f.$suffix";
340                 unless (-e $fn) {
341                         $f = lc $file;
342                         $fn = "$dir/$file.$suffix";
343                 }
344         } elsif ($file) {
345                 $f = uc $file;
346                 $fn = "$dir/$file";
347                 unless (-e $fn) {
348                         $f = lc $file;
349                         $fn = "$dir/$file";
350                 }
351         } else {
352                 $fn = $dir;
353         }
354
355         my $fh = new IO::File ">$fn";
356         if ($fh) {
357                 my $dd = new Data::Dumper([ $obj ]);
358                 $dd->Indent(1);
359                 $dd->Terse(1);
360                 $dd->Quotekeys(0);
361                 #       $fh->print(@_) if @_ > 0;     # any header comments, lines etc
362                 $fh->print($dd->Dumpxs);
363                 $fh->close;
364         }
365 }
366
367 sub filecopy
368 {
369         copy(@_) or return $!;
370 }
371
372 # remove leading and trailing spaces from an input string
373 sub unpad
374 {
375         my $s = shift;
376         $s =~ s/\s+$//;
377         $s =~ s/^\s+//;
378         return $s;
379 }
380
381 # check that a field only has callsign characters in it
382 sub is_callsign
383 {
384         return $_[0] =~ m!^
385                                           (?:\d?[A-Z]{1,2}\d*/)?    # out of area prefix /  
386                                           (?:\d?[A-Z]{1,2}\d+)      # main prefix one (required) 
387                                           [A-Z]{1,5}                # callsign letters (required)
388                                           (?:-(?:\d{1,2}|\#))?      # - nn possibly (eg G8BPQ-8) or -# (an RBN spot) 
389                                           (?:/[0-9A-Z]{1,7})?       # / another prefix, callsign or special label (including /MM, /P as well as /EURO or /LGT) possibly
390                                           $!x;
391
392         # longest callign allowed is 1X11/1Y11XXXXX-11/XXXXXXX
393 }
394
395 sub is_prefix
396 {
397         return $_[0] =~ m!^(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}}\d+)!x        # basic prefix
398 }
399         
400
401 # check that a PC protocol field is valid text
402 sub is_pctext
403 {
404         return undef unless length $_[0];
405         return undef if $_[0] =~ /[\x00-\x08\x0a-\x1f\x80-\x9f]/;
406         return 1;
407 }
408
409 # check that a PC prot flag is fairly valid (doesn't check the difference between 1/0 and */-)
410 sub is_pcflag
411 {
412         return $_[0] =~ /^[01\*\-]+$/;
413 }
414
415 # check that a thing is a frequency
416 sub is_freq
417 {
418         return $_[0] =~ /^\d+(?:\.\d+)?$/;
419 }
420
421 # check that a thing is just digits
422 sub is_digits
423 {
424         return $_[0] =~ /^[\d]+$/;
425 }
426
427 # does it look like a qra locator?
428 sub is_qra
429 {
430         return unless length $_[0] == 4 || length $_[0] == 6;
431         return $_[0] =~ /^[A-Ra-r][A-Ra-r]\d\d(?:[A-Xa-x][A-Xa-x])?$/;
432 }
433
434 # does it look like a valid lat/long
435 sub is_latlong
436 {
437         return $_[0] =~ /^\s*\d{1,2}\s+\d{1,2}\s*[NnSs]\s+1?\d{1,2}\s+\d{1,2}\s*[EeWw]\s*$/;
438 }
439
440 # is it an ip address?
441 sub is_ipaddr
442 {
443     return $_[0] =~ /^\d+\.\d+\.\d+\.\d+$/ || $_[0] =~ /^[0-9a-f:,]+$/;
444 }
445
446 # insert an item into a list if it isn't already there returns 1 if there 0 if not
447 sub insertitem
448 {
449         my $list = shift;
450         my $item = shift;
451         
452         return 1 if grep {$_ eq $item } @$list;
453         push @$list, $item;
454         return 0;
455 }
456
457 # delete an item from a list if it is there returns no deleted 
458 sub deleteitem
459 {
460         my $list = shift;
461         my $item = shift;
462         my $n = @$list;
463         
464         @$list = grep {$_ ne $item } @$list;
465         return $n - @$list;
466 }
467
468 # find the correct local_data directory
469 # basically, if there is a local_data directory with this filename and it is younger than the
470 # equivalent one in the (system) data directory then return that name rather than the system one
471 sub localdata
472 {
473         my $ifn = shift;
474         my $ofn = "$main::data/$ifn";
475         my $tfn;
476         
477         if (-e "$main::local_data") {
478                 $tfn = "$main::local_data/$ifn";
479                 if (-e $tfn && -e $ofn) {
480                         $ofn = $tfn if -M $tfn < -M $ofn;
481                 } elsif (-e $tfn) {
482                         $ofn = $tfn;
483                 }
484         }
485
486         return $ofn;
487 }
488
489 # move a file or a directory from data -> local_data if isn't there already
490 sub localdata_mv
491 {
492         my $ifn = shift;
493         if (-e "$main::data/$ifn" ) {
494                 unless (-e "$main::local_data/$ifn") {
495                         move("$main::data/$ifn", "$main::local_data/$ifn") or die "localdata_mv: cannot move $ifn from '$main::data' -> '$main::local_data' $!\n";
496                 }
497         }
498 }
499