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