typo
[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;
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
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         }
153         $prompt = sprintf "%15s: %s", $prompt, $value;
154         return ($priv, $prompt);
155 }
156
157 # turn a hex field into printed hex
158 sub phex
159 {
160         my $val = shift;
161         return sprintf '%X', $val;
162 }
163
164 # take an arg as an array list and print it
165 sub parray
166 {
167         my $ref = shift;
168         return ref $ref ? join(', ', @{$ref}) : $ref;
169 }
170
171 # take the arg as an array reference and print as a list of pairs
172 sub parraypairs
173 {
174         my $ref = shift;
175         my $i;
176         my $out;
177   
178         for ($i = 0; $i < @$ref; $i += 2) {
179                 my $r1 = @$ref[$i];
180                 my $r2 = @$ref[$i+1];
181                 $out .= "$r1-$r2, ";
182         }
183         chop $out;                                      # remove last space
184         chop $out;                                      # remove last comma
185         return $out;
186 }
187
188 sub _sort_fields
189 {
190         my $ref = shift;
191         my @a = split /,/, $ref->field_prompt(shift); 
192         my @b = split /,/, $ref->field_prompt(shift); 
193         return lc $a[1] cmp lc $b[1];
194 }
195
196 # print all the fields for a record according to privilege
197 #
198 # The prompt record is of the format '<priv>,<prompt>[,<action>'
199 # and is expanded by promptf above
200 #
201 sub print_all_fields
202 {
203         my $self = shift;                       # is a dxchan
204         my $ref = shift;                        # is a thingy with field_prompt and fields methods defined
205         my @out;
206         my @fields = $ref->fields;
207         my $field;
208         my $width = $self->width - 1;
209         $width ||= 80;
210
211         foreach $field (sort {_sort_fields($ref, $a, $b)} @fields) {
212                 if (defined $ref->{$field}) {
213                         my ($priv, $ans) = promptf($ref->field_prompt($field), $ref->{$field});
214                         my @tmp;
215                         if (length $ans > $width) {
216                                 my ($p, $a) = split /: /, $ans, 2;
217                                 my $l = (length $p) + 2;
218                                 my $al = ($width - 1) - $l;
219                                 my $bit;
220                                 while (length $a > $al ) {
221                                         ($bit, $a) = unpack "A$al A*", $a;
222                                         push @tmp, "$p: $bit";
223                                         $p = ' ' x ($l - 2);
224                                 }
225                                 push @tmp, "$p: $a" if length $a;
226                         } else {
227                                 push @tmp, $ans;
228                         }
229                         push @out, @tmp if ($self->priv >= $priv);
230                 }
231         }
232         return @out;
233 }
234
235 # generate a regex from a shell type expression 
236 # see 'perl cookbook' 6.9
237 sub shellregex
238 {
239         my $in = shift;
240         $in =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
241         return '^' . $in . "\$";
242 }
243
244 # read in a file into a string and return it. 
245 # the filename can be split into a dir and file and the 
246 # file can be in upper or lower case.
247 # there can also be a suffix
248 sub readfilestr
249 {
250         my ($dir, $file, $suffix) = @_;
251         my $fn;
252         my $f;
253         if ($suffix) {
254                 $f = uc $file;
255                 $fn = "$dir/$f.$suffix";
256                 unless (-e $fn) {
257                         $f = lc $file;
258                         $fn = "$dir/$file.$suffix";
259                 }
260         } elsif ($file) {
261                 $f = uc $file;
262                 $fn = "$dir/$file";
263                 unless (-e $fn) {
264                         $f = lc $file;
265                         $fn = "$dir/$file";
266                 }
267         } else {
268                 $fn = $dir;
269         }
270
271         my $fh = new IO::File $fn;
272         my $s = undef;
273         if ($fh) {
274                 local $/ = undef;
275                 $s = <$fh>;
276                 $fh->close;
277         }
278         return $s;
279 }
280
281 # write out a file in the format required for reading
282 # in via readfilestr, it expects the same arguments 
283 # and a reference to an object
284 sub writefilestr
285 {
286         my $dir = shift;
287         my $file = shift;
288         my $suffix = shift;
289         my $obj = shift;
290         my $fn;
291         my $f;
292         
293         confess('no object to write in writefilestr') unless $obj;
294         confess('object not a reference in writefilestr') unless ref $obj;
295         
296         if ($suffix) {
297                 $f = uc $file;
298                 $fn = "$dir/$f.$suffix";
299                 unless (-e $fn) {
300                         $f = lc $file;
301                         $fn = "$dir/$file.$suffix";
302                 }
303         } elsif ($file) {
304                 $f = uc $file;
305                 $fn = "$dir/$file";
306                 unless (-e $fn) {
307                         $f = lc $file;
308                         $fn = "$dir/$file";
309                 }
310         } else {
311                 $fn = $dir;
312         }
313
314         my $fh = new IO::File ">$fn";
315         if ($fh) {
316                 my $dd = new Data::Dumper([ $obj ]);
317                 $dd->Indent(1);
318                 $dd->Terse(1);
319                 $dd->Quotekeys(0);
320                 #       $fh->print(@_) if @_ > 0;     # any header comments, lines etc
321                 $fh->print($dd->Dumpxs);
322                 $fh->close;
323         }
324 }
325
326 sub filecopy
327 {
328         copy(@_) or return $!;
329 }
330
331 # remove leading and trailing spaces from an input string
332 sub unpad
333 {
334         my $s = shift;
335         $s =~ s/\s+$//;
336         $s =~ s/^\s+//;
337         return $s;
338 }
339
340 # check that a field only has callsign characters in it
341 sub is_callsign
342 {
343         return $_[0] =~ /^(?:[A-Z]{1,2}\d+|\d[A-Z]{1,2}\d+)[A-Z]{1,3}(?:-\d{1,2}|\/(?:[A-Z]{1,2}\d{0,2}|\d[A-Z]\d{0,2}))?$/;
344 }
345
346 # check that a PC protocol field is valid text
347 sub is_pctext
348 {
349         return undef if $_[0] =~ /[\x00-\x08\x0a-\x1f\x80-\x9f]/;
350         return $_[0];
351 }
352
353 # check that a PC prot flag is fairly valid (doesn't check the difference between 1/0 and */-)
354 sub is_pcflag
355 {
356         return $_[0] =~ /^[01\*\-]+$/;
357 }
358
359 # check that a thing is a frequency
360 sub is_freq
361 {
362         return $_[0] =~ /^\d+(?:\.\d+)?$/;
363 }
364
365 # check that a thing is just digits
366 sub is_digits
367 {
368         return $_[0] =~ /^[\d]+$/;
369 }
370
371 # does it look like a qra locator?
372 sub is_qra
373 {
374         return $_[0] =~ /^[A-Ra-r][A-Ra-r]\d\d[A-Xa-x][A-Xa-x]$/;
375 }
376
377 # does it look like a valid lat/long
378 sub is_latlong
379 {
380         return $_[0] =~ /^\s*\d{1,2}\s+\d{1,2}\s*[NnSs]\s+\d{1,2}\s+\d{1,2}\s*[EeWw]\s*$/;
381 }
382
383 # insert an item into a list if it isn't already there returns 1 if there 0 if not
384 sub insertitem
385 {
386         my $list = shift;
387         my $item = shift;
388         
389         return 1 if grep {$_ eq $item } @$list;
390         push @$list, $item;
391         return 0;
392 }
393
394 # delete an item from a list if it is there returns no deleted 
395 sub deleteitem
396 {
397         my $list = shift;
398         my $item = shift;
399         my $n = @$list;
400         
401         @$list = grep {$_ ne $item } @$list;
402         return $n - @$list;
403 }