added Investigate and believing
[spider.git] / perl / DXUtil.pm
1 #
2 # various utilities which are exported globally
3 #
4 # Copyright (c) 1998 - Dirk Koopman G1TLH
5 #
6 # $Id$
7 #
8
9 package DXUtil;
10
11 use Date::Parse;
12 use IO::File;
13 use File::Copy;
14 use Data::Dumper;
15
16 use strict;
17
18 use vars qw($VERSION $BRANCH);
19 $VERSION = sprintf( "%d.%03d", q$Revision$ =~ /(\d+)\.(\d+)/ );
20 $BRANCH = sprintf( "%d.%03d", q$Revision$ =~ /\d+\.\d+\.(\d+)\.(\d+)/  || (0,0));
21 $main::build += $VERSION;
22 $main::branch += $BRANCH;
23
24 use vars qw(@month %patmap @ISA @EXPORT);
25
26 require Exporter;
27 @ISA = qw(Exporter);
28 @EXPORT = qw(atime ztime cldate cldatetime slat slong yesno promptf 
29                          parray parraypairs phex shellregex readfilestr writefilestr
30                          filecopy ptimelist
31              print_all_fields cltounix unpad is_callsign is_latlong
32                          is_qra is_freq is_digits is_pctext is_pcflag insertitem deleteitem
33             );
34
35
36 @month = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
37 %patmap = (
38                    '*' => '.*',
39                    '?' => '.',
40                    '[' => '[',
41                    ']' => ']'
42 );
43
44 # a full time for logging and other purposes
45 sub atime
46 {
47         my $t = shift;
48         my ($sec,$min,$hour,$mday,$mon,$year) = gmtime((defined $t) ? $t : time);
49         $year += 1900;
50         my $buf = sprintf "%02d%s%04d\@%02d:%02d:%02d", $mday, $month[$mon], $year, $hour, $min, $sec;
51         return $buf;
52 }
53
54 # get a zulu time in cluster format (2300Z)
55 sub ztime
56 {
57         my $t = shift;
58         $t = defined $t ? $t : time;
59         my $dst = shift;
60         my ($sec,$min,$hour) = $dst ? localtime($t): gmtime($t);
61         my $buf = sprintf "%02d%02d%s", $hour, $min, ($dst) ? '' : 'Z';
62         return $buf;
63 }
64
65 # get a cluster format date (23-Jun-1998)
66 sub cldate
67 {
68         my $t = shift;
69         $t = defined $t ? $t : time;
70         my $dst = shift;
71         my ($sec,$min,$hour,$mday,$mon,$year) = $dst ? localtime($t) : gmtime($t);
72         $year += 1900;
73         my $buf = sprintf "%2d-%s-%04d", $mday, $month[$mon], $year;
74         return $buf;
75 }
76
77 # return a cluster style date time
78 sub cldatetime
79 {
80         my $t = shift;
81         my $dst = shift;
82         my $date = cldate($t, $dst);
83         my $time = ztime($t, $dst);
84         return "$date $time";
85 }
86
87 # return a unix date from a cluster date and time
88 sub cltounix
89 {
90         my $date = shift;
91         my $time = shift;
92         my ($thisyear) = (gmtime)[5] + 1900;
93
94         return 0 unless $date =~ /^\s*(\d+)-(\w\w\w)-([12][90]\d\d)$/;
95         return 0 if $3 > 2036;
96         return 0 unless abs($thisyear-$3) <= 1;
97         $date = "$1 $2 $3";
98         return 0 unless $time =~ /^([012]\d)([012345]\d)Z$/;
99         $time = "$1:$2 +0000";
100         my $r = str2time("$date $time");
101         return $r unless $r;
102         return $r == -1 ? undef : $r;
103 }
104
105 # turn a latitude in degrees into a string
106 sub slat
107 {
108         my $n = shift;
109         my ($deg, $min, $let);
110         $let = $n >= 0 ? 'N' : 'S';
111         $n = abs $n;
112         $deg = int $n;
113         $min = int ((($n - $deg) * 60) + 0.5);
114         return "$deg $min $let";
115 }
116
117 # turn a longitude in degrees into a string
118 sub slong
119 {
120         my $n = shift;
121         my ($deg, $min, $let);
122         $let = $n >= 0 ? 'E' : 'W';
123         $n = abs $n;
124         $deg = int $n;
125         $min = int ((($n - $deg) * 60) + 0.5);
126         return "$deg $min $let";
127 }
128
129 # turn a true into 'yes' and false into 'no'
130 sub yesno
131 {
132         my $n = shift;
133         return $n ? $main::yes : $main::no;
134 }
135
136 # format a prompt with its current value and return it with its privilege
137 sub promptf
138 {
139         my ($line, $value) = @_;
140         my ($priv, $prompt, $action) = split ',', $line;
141
142         # if there is an action treat it as a subroutine and replace $value
143         if ($action) {
144                 my $q = qq{\$value = $action(\$value)};
145                 eval $q;
146         } elsif (ref $value) {
147                 my $dd = new Data::Dumper([$value]);
148                 $dd->Indent(0);
149                 $dd->Terse(1);
150                 $dd->Quotekeys(0);
151                 $value = $dd->Dumpxs;
152                 $value =~ s/([\r\n\t])/sprintf("%%%02X", ord($1))/eg;
153         }
154         $prompt = sprintf "%15s: %s", $prompt, $value;
155         return ($priv, $prompt);
156 }
157
158 # turn a hex field into printed hex
159 sub phex
160 {
161         my $val = shift;
162         return sprintf '%X', $val;
163 }
164
165 # take an arg as a hash of call=>time pairs and print it
166 sub ptimelist
167 {
168         my $ref = shift;
169         my $out;
170         for (sort keys %$ref) {
171                 $out .= "$_=$ref->{$_}, ";
172         }
173         chop $out;
174         chop $out;
175         return $out;    
176 }
177
178 # take an arg as an array list and print it
179 sub parray
180 {
181         my $ref = shift;
182         return ref $ref ? join(', ', @{$ref}) : $ref;
183 }
184
185 # take the arg as an array reference and print as a list of pairs
186 sub parraypairs
187 {
188         my $ref = shift;
189         my $i;
190         my $out;
191   
192         for ($i = 0; $i < @$ref; $i += 2) {
193                 my $r1 = @$ref[$i];
194                 my $r2 = @$ref[$i+1];
195                 $out .= "$r1-$r2, ";
196         }
197         chop $out;                                      # remove last space
198         chop $out;                                      # remove last comma
199         return $out;
200 }
201
202 sub _sort_fields
203 {
204         my $ref = shift;
205         my @a = split /,/, $ref->field_prompt(shift); 
206         my @b = split /,/, $ref->field_prompt(shift); 
207         return lc $a[1] cmp lc $b[1];
208 }
209
210 # print all the fields for a record according to privilege
211 #
212 # The prompt record is of the format '<priv>,<prompt>[,<action>'
213 # and is expanded by promptf above
214 #
215 sub print_all_fields
216 {
217         my $self = shift;                       # is a dxchan
218         my $ref = shift;                        # is a thingy with field_prompt and fields methods defined
219         my @out;
220         my @fields = $ref->fields;
221         my $field;
222         my $width = $self->width - 1;
223         $width ||= 80;
224
225         foreach $field (sort {_sort_fields($ref, $a, $b)} @fields) {
226                 if (defined $ref->{$field}) {
227                         my ($priv, $ans) = promptf($ref->field_prompt($field), $ref->{$field});
228                         my @tmp;
229                         if (length $ans > $width) {
230                                 my ($p, $a) = split /: /, $ans, 2;
231                                 my $l = (length $p) + 2;
232                                 my $al = ($width - 1) - $l;
233                                 my $bit;
234                                 while (length $a > $al ) {
235                                         ($bit, $a) = unpack "A$al A*", $a;
236                                         push @tmp, "$p: $bit";
237                                         $p = ' ' x ($l - 2);
238                                 }
239                                 push @tmp, "$p: $a" if length $a;
240                         } else {
241                                 push @tmp, $ans;
242                         }
243                         push @out, @tmp if ($self->priv >= $priv);
244                 }
245         }
246         return @out;
247 }
248
249 # generate a regex from a shell type expression 
250 # see 'perl cookbook' 6.9
251 sub shellregex
252 {
253         my $in = shift;
254         $in =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
255         return '^' . $in . "\$";
256 }
257
258 # read in a file into a string and return it. 
259 # the filename can be split into a dir and file and the 
260 # file can be in upper or lower case.
261 # there can also be a suffix
262 sub readfilestr
263 {
264         my ($dir, $file, $suffix) = @_;
265         my $fn;
266         my $f;
267         if ($suffix) {
268                 $f = uc $file;
269                 $fn = "$dir/$f.$suffix";
270                 unless (-e $fn) {
271                         $f = lc $file;
272                         $fn = "$dir/$file.$suffix";
273                 }
274         } elsif ($file) {
275                 $f = uc $file;
276                 $fn = "$dir/$file";
277                 unless (-e $fn) {
278                         $f = lc $file;
279                         $fn = "$dir/$file";
280                 }
281         } else {
282                 $fn = $dir;
283         }
284
285         my $fh = new IO::File $fn;
286         my $s = undef;
287         if ($fh) {
288                 local $/ = undef;
289                 $s = <$fh>;
290                 $fh->close;
291         }
292         return $s;
293 }
294
295 # write out a file in the format required for reading
296 # in via readfilestr, it expects the same arguments 
297 # and a reference to an object
298 sub writefilestr
299 {
300         my $dir = shift;
301         my $file = shift;
302         my $suffix = shift;
303         my $obj = shift;
304         my $fn;
305         my $f;
306         
307         confess('no object to write in writefilestr') unless $obj;
308         confess('object not a reference in writefilestr') unless ref $obj;
309         
310         if ($suffix) {
311                 $f = uc $file;
312                 $fn = "$dir/$f.$suffix";
313                 unless (-e $fn) {
314                         $f = lc $file;
315                         $fn = "$dir/$file.$suffix";
316                 }
317         } elsif ($file) {
318                 $f = uc $file;
319                 $fn = "$dir/$file";
320                 unless (-e $fn) {
321                         $f = lc $file;
322                         $fn = "$dir/$file";
323                 }
324         } else {
325                 $fn = $dir;
326         }
327
328         my $fh = new IO::File ">$fn";
329         if ($fh) {
330                 my $dd = new Data::Dumper([ $obj ]);
331                 $dd->Indent(1);
332                 $dd->Terse(1);
333                 $dd->Quotekeys(0);
334                 #       $fh->print(@_) if @_ > 0;     # any header comments, lines etc
335                 $fh->print($dd->Dumpxs);
336                 $fh->close;
337         }
338 }
339
340 sub filecopy
341 {
342         copy(@_) or return $!;
343 }
344
345 # remove leading and trailing spaces from an input string
346 sub unpad
347 {
348         my $s = shift;
349         $s =~ s/\s+$//;
350         $s =~ s/^\s+//;
351         return $s;
352 }
353
354 # check that a field only has callsign characters in it
355 sub is_callsign
356 {
357         return $_[0] =~ m!^(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}\d+)        # basic prefix
358                        (?:/(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}\d+))?  # / another one (possibly)
359                                            [A-Z]{1,3}                                 # callsign letters
360                                            (?:/(?:[A-Z]{1,2}\d+ | \d[A-Z]{1,2}\d+))?  # / another prefix possibly
361                        (?:/[0-9A-Z]{1,2})?                        # /0-9A-Z+ possibly
362                                            (?:-\d{1,2})?                              # - nn possibly
363                                          $!x;
364 }
365
366 # check that a PC protocol field is valid text
367 sub is_pctext
368 {
369         return undef unless length $_[0];
370         return undef if $_[0] =~ /[\x00-\x08\x0a-\x1f\x80-\x9f]/;
371         return 1;
372 }
373
374 # check that a PC prot flag is fairly valid (doesn't check the difference between 1/0 and */-)
375 sub is_pcflag
376 {
377         return $_[0] =~ /^[01\*\-]+$/;
378 }
379
380 # check that a thing is a frequency
381 sub is_freq
382 {
383         return $_[0] =~ /^\d+(?:\.\d+)?$/;
384 }
385
386 # check that a thing is just digits
387 sub is_digits
388 {
389         return $_[0] =~ /^[\d]+$/;
390 }
391
392 # does it look like a qra locator?
393 sub is_qra
394 {
395         return $_[0] =~ /^[A-Ra-r][A-Ra-r]\d\d[A-Xa-x][A-Xa-x]$/;
396 }
397
398 # does it look like a valid lat/long
399 sub is_latlong
400 {
401         return $_[0] =~ /^\s*\d{1,2}\s+\d{1,2}\s*[NnSs]\s+1?\d{1,2}\s+\d{1,2}\s*[EeWw]\s*$/;
402 }
403
404 # insert an item into a list if it isn't already there returns 1 if there 0 if not
405 sub insertitem
406 {
407         my $list = shift;
408         my $item = shift;
409         
410         return 1 if grep {$_ eq $item } @$list;
411         push @$list, $item;
412         return 0;
413 }
414
415 # delete an item from a list if it is there returns no deleted 
416 sub deleteitem
417 {
418         my $list = shift;
419         my $item = shift;
420         my $n = @$list;
421         
422         @$list = grep {$_ ne $item } @$list;
423         return $n - @$list;
424 }