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