change build number calculation to be more accurate
[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 # print all the fields for a record according to privilege
187 #
188 # The prompt record is of the format '<priv>,<prompt>[,<action>'
189 # and is expanded by promptf above
190 #
191 sub print_all_fields
192 {
193         my $self = shift;                       # is a dxchan
194         my $ref = shift;                        # is a thingy with field_prompt and fields methods defined
195         my @out;
196         my @fields = $ref->fields;
197         my $field;
198
199         foreach $field (sort {$ref->field_prompt($a) cmp $ref->field_prompt($b)} @fields) {
200                 if (defined $ref->{$field}) {
201                         my ($priv, $ans) = promptf($ref->field_prompt($field), $ref->{$field});
202                         my @tmp;
203                         if (length $ans > 79) {
204                                 my ($p, $a) = split /: /, $ans, 2;
205                                 my $l = (length $p) + 2;
206                                 my $al = 79 - $l;
207                                 my $bit;
208                                 while (length $a > $al ) {
209                                         ($bit, $a) = unpack "A$al A*", $a;
210                                         push @tmp, "$p: $bit";
211                                         $p = ' ' x ($l - 2);
212                                 }
213                                 push @tmp, "$p: $a" if length $a;
214                         } else {
215                                 push @tmp, $ans;
216                         }
217                         push @out, @tmp if ($self->priv >= $priv);
218                 }
219         }
220         return @out;
221 }
222
223 # generate a regex from a shell type expression 
224 # see 'perl cookbook' 6.9
225 sub shellregex
226 {
227         my $in = shift;
228         $in =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
229         return '^' . $in . "\$";
230 }
231
232 # read in a file into a string and return it. 
233 # the filename can be split into a dir and file and the 
234 # file can be in upper or lower case.
235 # there can also be a suffix
236 sub readfilestr
237 {
238         my ($dir, $file, $suffix) = @_;
239         my $fn;
240         my $f;
241         if ($suffix) {
242                 $f = uc $file;
243                 $fn = "$dir/$f.$suffix";
244                 unless (-e $fn) {
245                         $f = lc $file;
246                         $fn = "$dir/$file.$suffix";
247                 }
248         } elsif ($file) {
249                 $f = uc $file;
250                 $fn = "$dir/$file";
251                 unless (-e $fn) {
252                         $f = lc $file;
253                         $fn = "$dir/$file";
254                 }
255         } else {
256                 $fn = $dir;
257         }
258
259         my $fh = new IO::File $fn;
260         my $s = undef;
261         if ($fh) {
262                 local $/ = undef;
263                 $s = <$fh>;
264                 $fh->close;
265         }
266         return $s;
267 }
268
269 # write out a file in the format required for reading
270 # in via readfilestr, it expects the same arguments 
271 # and a reference to an object
272 sub writefilestr
273 {
274         my $dir = shift;
275         my $file = shift;
276         my $suffix = shift;
277         my $obj = shift;
278         my $fn;
279         my $f;
280         
281         confess('no object to write in writefilestr') unless $obj;
282         confess('object not a reference in writefilestr') unless ref $obj;
283         
284         if ($suffix) {
285                 $f = uc $file;
286                 $fn = "$dir/$f.$suffix";
287                 unless (-e $fn) {
288                         $f = lc $file;
289                         $fn = "$dir/$file.$suffix";
290                 }
291         } elsif ($file) {
292                 $f = uc $file;
293                 $fn = "$dir/$file";
294                 unless (-e $fn) {
295                         $f = lc $file;
296                         $fn = "$dir/$file";
297                 }
298         } else {
299                 $fn = $dir;
300         }
301
302         my $fh = new IO::File ">$fn";
303         if ($fh) {
304                 my $dd = new Data::Dumper([ $obj ]);
305                 $dd->Indent(1);
306                 $dd->Terse(1);
307                 $dd->Quotekeys(0);
308                 #       $fh->print(@_) if @_ > 0;     # any header comments, lines etc
309                 $fh->print($dd->Dumpxs);
310                 $fh->close;
311         }
312 }
313
314 # remove leading and trailing spaces from an input string
315 sub unpad
316 {
317         my $s = shift;
318         $s =~ s/\s+$//;
319         $s =~ s/^\s+//;
320         return $s;
321 }
322
323 # check that a field only has callsign characters in it
324 sub is_callsign
325 {
326         return $_[0] =~ /^(?:[A-Z]{1,2}\d+|\d[A-Z]\d+)[A-Z]+(?:-\d{1,2}|\/[A-Z0-9]+)?$/;
327 }
328
329 # check that a PC protocol field is valid text
330 sub is_pctext
331 {
332         return $_[0] =~ /^[\x09\x20-\xFF]+$/;
333 }
334
335 # check that a PC prot flag is fairly valid (doesn't check the difference between 1/0 and */-)
336 sub is_pcflag
337 {
338         return $_[0] =~ /^[01\*\-]+$/;
339 }
340
341 # check that a thing is a frequency
342 sub is_freq
343 {
344         return $_[0] =~ /^[\d\.]+$/;
345 }
346
347 # check that a thing is just digits
348 sub is_digits
349 {
350         return $_[0] =~ /^[\d]+$/;
351 }
352
353 # does it look like a qra locator?
354 sub is_qra
355 {
356         return $_[0] =~ /^[A-Za-z][A-Za-z]\d\d[A-Za-z][A-Za-z]$/o;
357 }
358
359 # does it look like a valid lat/long
360 sub is_latlong
361 {
362         return $_[0] =~ /^\s*\d{1,2}\s+\d{1,2}\s*[NnSs]\s+\d{1,2}\s+\d{1,2}\s*[EeWw]\s*$/;
363 }
364
365 # insert an item into a list if it isn't already there returns 1 if there 0 if not
366 sub insertitem
367 {
368         my $list = shift;
369         my $item = shift;
370         
371         return 1 if grep {$_ eq $item } @$list;
372         push @$list, $item;
373         return 0;
374 }
375
376 # delete an item from a list if it is there returns no deleted 
377 sub deleteitem
378 {
379         my $list = shift;
380         my $item = shift;
381         my $n = @$list;
382         
383         @$list = grep {$_ ne $item } @$list;
384         return $n - @$list;
385 }