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