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