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