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