Middle initial removed from CSV; AM/PM in HTML; comments
[tpope-extra.git] / perl / schedproc
1 #!/usr/bin/perl -w
2 # $Id$
3 # -*- perl -*- vim: ft=perl sw=4 sts=4
4
5 # Brief usage instructions:
6 # Create a ~/.schedprocrc that has schedule=/path/to/schedule.xml and
7 # grades=/path/to/grades.xml.  HTTP URLs are acceptable
8
9 use strict;
10 use Date::Calc::Object qw(Day_of_Week Decode_Day_of_Week Decode_Month Week_of_Year Monday_of_Week Day_of_Week_Abbreviation Delta_Days Add_Delta_Days Nth_Weekday_of_Month_Year Gmtime Mktime);
11 use Date::Calendar::Profiles qw($Profiles);
12 use Date::Calendar::Year;
13 use LWP::UserAgent;
14 use XML::Simple;
15 use vars qw(%opts %faculty);
16
17 my ($response);
18
19 my $config = $ENV{HOME} . "/.schedprocrc";
20 if (($ARGV[0] || "") eq '-F') {
21     shift;
22     $config = shift;
23 }
24
25 my $arg = "";
26 $arg = shift if (defined($ARGV[0]) && $ARGV[0] =~ /^-\w$/);
27
28 if (-r $config) {
29     open CONFIG, $config;
30     while(<CONFIG>) {
31         s/\#.*//;
32         next unless m/^([^=]*)=(.*)/;
33         $opts{$1}=$2;
34     }
35     close CONFIG;
36 }
37 my $schedurl = $ENV{HOME} . "/schedule.xml";
38 $schedurl = $opts{'schedule'} if(defined($opts{'schedule'}));
39 my $gradeurl = $ENV{HOME} . "/grades.xml";
40 $gradeurl = $opts{'grades'} if(defined($opts{'schedule'}));
41
42 sub generate_id {
43     my ($section, $number) = split("-", shift);
44     my $id = 0;
45     foreach (split //, $section) {$id=26*$id+(ord($_)-1)%32;}
46     $id=10000*$id+$number;
47     return $id;
48 }
49
50 sub next_class {
51     my %class = @_;
52     $class{'duration'} =~ /(\d\d\d\d)(\d\d)(\d\d)-(\d\d\d\d)(\d\d)(\d\d)/;
53     my $days = Delta_Days($1,$2,$3,$4,$5,$6);
54     my $firstday = Date::Calc->new($1,$2,$3);
55     my $lastday = Date::Calc->new($4,$5,$6);
56     my $today = Date::Calc->new(Date::Calc->localtime(time+3600*6)->date);
57     my @days=();
58     foreach(split(" ",$class{'days'})) {
59         push @days, Decode_Day_of_Week($_);
60     }
61     my @off = ();
62     @off = @{$class{'off'}} if ($class{'off'});
63     for($today = ($today > $firstday ? $today : $firstday); $today < $lastday; $today++) {
64         next unless(grep($_ == Day_of_Week($today->date), @days));
65         next if(grep($_ == "$today", @off));
66         return $today;
67     }
68     $today = Date::Calc->new(Date::Calc->gmtime->date);
69     for($today = ($today < $lastday ? $today : $lastday); $today > $firstday; $today--) {
70         next unless(grep($_ == Day_of_Week($today->date), @days));
71         next if(grep($_ == "$today", @off));
72         return $today;
73     }
74     return undef;
75 }
76
77 sub capitalize {
78     local $_ = shift || "";
79     s/ +$//;
80     s/\b([A-Z])([A-Z]*)\b/$1\L$2/g;
81     s/\b(I)(i*)\b/$1\U$2/g;
82     s/\bUs\b/US/g;
83     s/ (And|For|Of|Or|The|To|With) / \l$1 /g;
84     s/\b(Mc)([a-z])/$1\u$2/g;
85     s/\b(Tcp\/Ip|Pc|Tba)\b/\U$&/g;
86     s/\bThru\b/Through/g;
87     s/\bAcct\b/Accounting/g;
88     s/\bAmer\b/American/g;
89     s/\bChem\b/Chemistry/g;
90     s/\bComp\b/Composition/g;
91     s/\bFed\b/Federal/g;
92     s/\bGen\b/General/g;
93     s/\bIntro\b/Introduction/g;
94     s/\bPrgm\b/Programming/g;
95     s/\bOp Sys\b/Operating System/g;
96     #s/\bGovt\b/Government/g;
97     s/\bLit\b/Literature/g;
98     s/\bPrin\b/Principles/g;
99     s/\bBus\b/Business/g;
100     s/\bSyst\b/Sys/g;
101     return $_;
102 }
103
104 sub get_schedule {
105     my $content;
106     if($schedurl =~ /:\/\//) {
107         my $ua = LWP::UserAgent->new;
108         $ua->timeout(10);
109         $ua->env_proxy;
110 #       $ua->cookie_jar( {} );
111         $response = $ua->get("$schedurl") or die "$!";
112         die $response->status_line unless $response->is_success;
113         $content = $response->content;
114     } else {
115         open(F,$schedurl) || die "$!";
116         $content = join ("", <F>);
117         close F;
118     }
119     my $ref = XMLin($content, ForceArray => [ 'class', 'off' ], KeyAttr => "");
120     return @{$ref->{'class'}};
121 }
122
123 sub get_grades {
124     my $content;
125     if($gradeurl =~ /:\/\//) {
126         my $ua = LWP::UserAgent->new;
127         $ua->timeout(10);
128         $ua->env_proxy;
129 #       $ua->cookie_jar( {} );
130         $response = $ua->get("$gradeurl") or die "$!";
131         die $response->status_line unless $response->is_success;
132         $content = $response->content;
133     } else {
134         open(F,$gradeurl) || die "$!";
135         $content = join ("", <F>);
136         close F;
137     }
138     my $ref = XMLin($content, ForceArray => [ 'class', 'cumulative' ], KeyAttr => "");
139     return $ref;
140 }
141
142 sub do_html_grades {
143     my $grades;
144     my @showheaders = ("Section ID", "Course Title", "Grade", "Earned<br />Hours", "Quality<br />Hours", "Quality<br />Points");
145     #$file = shift unless (!defined $_[0] or $_[0] =~ /^\d/);
146     $grades = get_grades(@_);
147     my ($row);
148     my $shade = "dark";
149     print '<table id="grades" cellpadding="3" cellspacing="0">'."\n<tr>";
150     print '<th align="left" class="sectionid">', $showheaders[0];
151     print '</th><th align="left" class="coursetitle">', $showheaders[1];
152     print '</th><th align="center" class="grade">';
153     print join('</th><th align="center" class="right-number">',@showheaders[2 .. 5]);
154     print "</th></tr>\n";
155     foreach my $ts ($grades->{'class'}) {
156         foreach my $row (@$ts) {
157             print '<tr class="'.$shade.'">';
158             $shade = ($shade eq "dark"?"light":"dark");
159             print '<td align="left" class="sectionid">', $row->{'id'}, '</td>';
160             print '<td align="left" class="coursetitle">', $row->{'title'}, '</td>';
161             print '<td align="center" class="grade">';
162             #print join('</td><td>', @$row[0 .. 1]);
163             print join('</td><td align="right" class="right-number">', ($row->{'grade'},$row->{'earned'},$row->{'hours'},$row->{'points'}));
164             print "</td></tr>\n";
165         }
166     }
167     my $lastrow = $grades->{'cumulative'}->[scalar @{$grades->{'cumulative'}}-1];
168     print '<tr class="cumulative '.$shade.'"><td id="cumulative" colspan="2">Cumulative: through ', capitalize($lastrow->{'term'});
169     print '</td><td align="center" id="gpa" class="grade">';
170     print $lastrow->{'gpa'};
171     print '</td><td align="right" class="right-number">';
172     print join('</td><td align="right" class="right-number">', ($lastrow->{'earned'}, $lastrow->{'hours'}, $lastrow->{'points'}));
173     print "</td></tr>\n";
174     print "</table>\n";
175 }
176
177 sub get_faculty_email {
178     my ($name, $school, $email);
179     if((-f $ENV{'HOME'} . "/public_html/faculty.csv") && ! %faculty) {
180         open INS, $ENV{'HOME'} . "/public_html/faculty.csv";
181         while($_ = <INS>) {
182             chomp;
183             m/"([^"]*)",([^,]*),([^,]*)/; # "
184             ($name, $email, $school) = ($1, $2, $3);
185             $name =~ s/ [A-Z]\.//g;
186             $name = lc $name;
187             $name =~ s/\W//g;
188             $faculty{$name} = $email;
189         }
190     }
191     $name = shift;
192     $name =~ s/ [A-Z]r?\.//g;
193     $name = lc $name;
194     $name =~ s/\W//g;
195     return $faculty{$name};
196 }
197
198 sub get_mhc_header {
199 return (
200 "X-SC-Subject: New Years Day\nX-SC-Category: Holiday\nX-SC-Cond: 1 Jan\nX-SC-Duration: 00010101-\nX-SC-Record-Id: <New_Years_Day\@from.sctweb>\n",
201 "X-SC-Subject: Martin Luther King, Jr. Day\nX-SC-Category: Holiday\nX-SC-Cond: 3rd Mon Jan\nX-SC-Duration: 19870119-\nX-SC-Record-Id: <Martin_Luther_King_Jr_Day\@from.sctweb>\n",
202 "X-SC-Subject: Presidents Day\nX-SC-Category: Holiday\nX-SC-Cond: 3rd Mon Feb\nX-SC-Duration: 19710515-\nX-SC-Record-Id: <Presidents_Day\@from.sctweb>\n",
203 "X-SC-Subject: Memorial Day\nX-SC-Category: Holiday\nX-SC-Cond: Last Mon May\nX-SC-Duration: 19710531-\nX-SC-Record-Id: <Memorial_Day\@from.sctweb>\n",
204 "X-SC-Subject: Independence Day\nX-SC-Category: Holiday\nX-SC-Cond: 4 Jul\nX-SC-Duration: 17760704-\nX-SC-Record-Id: <Independence_Day\@from.sctweb>\n",
205 "X-SC-Subject: Labor Day\nX-SC-Category: Holiday\nX-SC-Cond: 1st Mon Sep\nX-SC-Duration: 18840901-\nX-SC-Record-Id: <Labor_Day\@from.sctweb>\n",
206 "X-SC-Subject: Columbus Day\nX-SC-Category: Holiday\nX-SC-Cond: 2nd Mon Oct\nX-SC-Duration: 19711011-\nX-SC-Record-Id: <Columbus_Day\@from.sctweb>\n",
207 "X-SC-Subject: Veterans Day\nX-SC-Category: Holiday\nX-SC-Cond: 11 Nov\nX-SC-Duration: 19261111-\nX-SC-Record-Id: <Veterans_Day\@from.sctweb>\n",
208 "X-SC-Subject: Thanksgiving\nX-SC-Category: Holiday\nX-SC-Cond: 4th Thu Nov\nX-SC-Duration: 14921122-\nX-SC-Record-Id: <Thanksgiving\@from.sctweb>\n",
209 "X-SC-Subject: Christmas\nX-SC-Category: Holiday\nX-SC-Cond: 25 Dec\nX-SC-Duration: 00011225-\nX-SC-Record-Id: <Christmas\@from.sctweb>\n",
210 );
211 }
212
213 sub do_mhc_schedule {
214     $| = 1;
215     my %days = (M => "Mon", T => "Tue", W => "Wed", R => "Thu", F => "Fri", S => "Sat", U => "SU");
216     my @mon = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
217     my ($file, $current, @mhc, @schedule);
218     $file = shift unless (!defined $_[0] or $_[0] =~ /^\d/);
219     @schedule = get_schedule(@_);
220     @mhc = get_mhc_header;
221     if(defined($file) && (-d $file)) {
222         my @mhc2;
223         foreach (@mhc) {
224             $_ =~ s/X-SC-Subject: ([^\n]*)/X-SC-Subject: $1\nSubject: $1/;
225             $_ =~ s/X-SC-Category: ([^\n]*)/X-SC-Category: $1\nFrom: $1/;
226             $_ =~ s/X-SC-Duration: (\d\d\d\d)(\d\d)(\d\d)-/"X-SC-Duration: $1$2$3-\nDate: $3 " . $mon[$2-1] . " 1970 12:00:00 +0000"/e;
227             push @mhc2, $_;
228         }
229         @mhc = @mhc2;
230     }
231     foreach my $row (@schedule) {
232         map {s/\n/-/g if defined; $_} %$row;
233         my $id=generate_id($row->{'id'});
234         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
235         $row->{'days'} =~ s/^ //;
236         #$row->{'duration'} =~ s/(\d\d)-(\d\d)-(\d\d)/20$3$1$2/g;
237         my @day = ();
238         @day = map { "!" . $_ } (@{$row->{'off'}}) if ($row->{'off'});
239         $current = "";
240         #print "# $id\n";
241         $current .= "X-SC-Subject: " . $row->{'title'} . "\n";
242         $current .= "X-SC-Location: " . $row->{'location'} . "\n";
243         $current .= "X-SC-Category: School\n";
244         $current .= "X-SC-Cond: " . $row->{'days'} . "\n";
245         $current .= "X-SC-Time: ".$row->{'begin'}."-".$row->{'end'}."\n";
246         $current .= "X-SC-Duration: " . $row->{'duration'} . "\n";
247         $current .= "X-SC-Day: @day\n" if(exists $day[0]);
248         $current .= "X-SC-Alarm: 15 minutes\n";
249         $current .= "X-SC-Record-Id: <".$row->{'id'}."\@from.sctweb>\n";
250         if(defined($file) && (-d $file)) {
251             my $email = get_faculty_email $row->{'instructor'};
252             $row->{'instructor'} = '"' . $row->{'instructor'} . '" <'. ($email || ($1 || "unknown") . "\@from.sctweb") . ">";
253             $row->{'duration'} =~ /^(\d\d\d\d)(\d\d)(\d\d)-\d{8}$/;
254             $row->{'begin'} =~ /^(\d\d):(\d\d)$/;
255             my $next = next_class(%$row);
256             my @date = Gmtime(Mktime($next->date,$1,$2,0));
257             $current .= sprintf "Date: %s, %2d %s %4d %02d:%02d:00 +0000\n", Day_of_Week_Abbreviation($date[7]), $date[2], $mon[$date[1]-1], $date[0], $date[3], $date[4], $date[5];
258             $current .= "Subject: " . $row->{'title'} . "\n";
259             $current .= "From: " . $row->{'instructor'} . "\n";
260         }
261         #print "\n$current";
262         push @mhc, $current;
263     }
264     if(defined($file) && (-d $file)) {
265         my @lines;
266         foreach my $name (<$file/[1-9]*>) {
267             next unless $name =~ /^$file\/[1-9][0-9]*$/;
268             open FH, $name;
269             @lines = <FH>;
270             close FH;
271             foreach (@lines) {
272                 unlink $name if /^X-SC-Record-Id: <.*\@from.sctweb>/;
273             }
274         }
275         my $i=0;
276         foreach (@mhc) {
277             while(-f ++$i) {}
278             open FH, ">$file/$i" or die $!;
279             print FH $_;
280             close FH;
281         }
282     } else {
283         open(STDOUT, ">" . $file) if(defined($file));
284         print "# MHC school schedule\n# Autogenerated by sctweb ".localtime()."\n\n";
285         print join("\n", @mhc);
286     }
287 }
288
289 sub do_csv_schedule {
290     $| = 1;
291     my %days = (M => "Mon", T => "Tue", W => "Wed", R => "Thu", F => "Fri", S => "Sat", U => "SU");
292     my @mon = qw(Jan. Feb. Mar. Apr. May June July Aug. Sept. Oct. Nov. Dec.);
293     my (@terms, $file, $current, @mhc, @schedule);
294     $file = shift unless (!defined $_[0] or $_[0] =~ /^\d/);
295     @schedule = get_schedule(@_);
296     open(STDOUT, ">" . $file) if(defined($file));
297     foreach my $row (@schedule) {
298         map {s/\n/-/g if defined; $_} %$row;
299         my $id=generate_id($row->{'id'});
300         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
301         $row->{'days'} =~ s/^ //;
302         my $next = next_class(%$row);
303         $current = "";
304         #print "# $id\n";
305         $current .= $row->{'id'} . ",";
306         $current .= $row->{'title'} . ",";
307         my $instructor = $row->{'instructor'};
308         $instructor =~ s/ [A-Z. ]* / /;
309         $current .= '"' . $instructor . '",';
310         $next =~ /^(\d\d\d\d)(\d\d)(\d\d)$/;
311         $current .= $1 . "-". $2 ."-" . $3 . "\n";
312         print $current;
313     }
314 }
315
316 sub do_vcalendar_schedule {
317     $| = 1;
318     my %days = (M => "MO", T => "TU", W => "WE", R => "TH", F => "FR", S => "SA", U => "SU");
319     my $file = shift if (defined $_[0] and $_[0] !~ /^\d/);
320     my @schedule = get_schedule(@_);
321     open(STDOUT, ">>" . $file) if(defined($file) && (! -d $file));
322     open(STDOUT, ">/dev/null") if(defined($file) && (-d $file));
323     print "BEGIN:VCALENDAR\r\nVERSION:1.0\r\n";
324     foreach my $row (@schedule) {
325         map { s/\n/-/g; $_} %$row;
326         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
327         $row->{'days'} =~ s/^ //;
328         my @day = ();
329         @day = @{$row->{'off'}} if ($row->{'off'});
330         my $day = "";
331         if(exists($day[0])) {
332             $day = join(";", @day);
333             $day =~ s/\b(\d{8})\b/$1T000000/g;
334         }
335         my ($starttime, $stoptime)=($row->{'begin'}, $row->{'end'});
336         my ($startdate, $stopdate)=split(/-/, $row->{'duration'});
337         $starttime =~ s/://;
338         $stoptime =~ s/://;
339         if(defined($file) && (-d $file)) {
340             open FH, ">$file/" . $row->{'id'} . ".vcs" or die "$!";
341             select FH;
342             print "BEGIN:VCALENDAR\r\nVERSION:1.0\r\n";
343         }
344         print "BEGIN:VEVENT\r\n";
345         print "SUMMARY:", $row->{'title'}, "\r\n";
346         print "DESCRIPTION:", $row->{'id'}, "\r\n";
347         print "LOCATION:", $row->{'location'}, "\r\n";
348         print "CATEGORIES:Education\r\n";
349         print "DTSTART:", $startdate."T".$starttime, "00\r\n";
350         print "DTEND:", $startdate."T".$stoptime, "00\r\n";
351         print "RRULE:W1 ", $row->{'days'} . " $stopdate", "T000000\r\n";
352         print("EXDATE:$day\r\n") if($day);
353         print "ATTENDEE;ROLE=OWNER;STATUS=CONFIRMED:", $opts{'name'}, "\r\n" if(defined($opts{'name'}));
354         print "ATTENDEE;ROLE=ORGANIZER;STATUS=CONFIRMED:", $row->{'instructor'}, " <" . (get_faculty_email($row->{'instructor'}) || "fake\@ddress"), ">\r\n";
355         print "END:VEVENT\r\n";
356         if(defined($file) && (-d $file)) {
357             print "END:VCALENDAR\r\n";
358             close FH;
359             select STDOUT;
360         }
361     }
362     print "END:VCALENDAR\r\n";
363 }
364
365 sub do_xml_schedule {
366     my $file = shift if (defined $_[0] and $_[0] !~ /^\d/);
367     my $schedule = { class => [ get_schedule(@_) ] };
368     my $xml = XMLout($schedule, NoAttr => 1, RootName => 'schedule');
369     if($file) {
370         open FH, ">$file";
371         print FH $xml;
372         close FH;
373     } else {
374         print $xml;
375     }
376 }
377
378 sub do_html_schedule {
379     my @showheaders = ("Section ID/Title", "Instructor", "Days", "Time", "Duration", "Location");
380     my $shade = "dark";
381     my @schedule = get_schedule(@_);
382     print '<table id="schedule" cellpadding="3" cellspacing="0">'."\n<tr><th>";
383     print join("</th><th>",@showheaders);
384     print "</th></tr>\n";
385         foreach my $row (@schedule) {
386             map { s/\n/<br \/>/g; $_} %$row;
387             $row->{'duration'} =~ s/-/<br \/>/g;
388             $row->{'duration'} =~ s/\d\d(\d\d)(\d\d)(\d\d)/$2-$3-$1/g;
389             print '<tr class="'.$shade.'">';
390             $shade = ($shade eq "dark"?"light":"dark");
391             print '<td class="idtitle">';
392             print '<span class="sectionid">' .$row->{'id'}. '</span><br />';
393             print '<span class="coursetitle">' .$row->{'title'}. '</span></td>';
394             my $instructor = $row->{'instructor'};
395             #$instructor =~ s/ [A-Z. ]* / /;
396             my $email = get_faculty_email($row->{'instructor'});
397             #if($email) {
398                 #print '<td><a href="mailto:' . $email . '">'
399                 #. $row->{'instructor'} . "</a></td>";
400             # } else {
401             print "<td>" . $instructor . "</td>";
402             #}
403             print "<td>" . $row->{'days'} . "</td>";
404             my ($a,$b) = ($row->{'begin'}, $row->{'end'});
405             $b .= "AM";
406             $a=~s/(1[3-9]|2\d|00):(\d\d)/sprintf "%d:%02d",abs $1-12,$2/e;
407             $b=~s/(1[3-9]|2\d|00):(\d\d)AM/sprintf "%d:%02dPM",abs $1-12,$2/e;
408             print "<td>$a-<wbr />$b</td>";
409             print "<td>" . $row->{'duration'} . "</td>";
410             print "<td>" . $row->{'location'} . "</td>";
411             print "</tr>\n";
412         }
413     print "</table>\n";
414 }
415
416 if ($arg eq "-s" || $arg eq "-h") {
417     do_html_schedule(@ARGV);
418 } elsif ($arg eq "-m") {
419     do_mhc_schedule(@ARGV);
420 } elsif ($arg eq "-c") {
421     do_csv_schedule(@ARGV);
422 } elsif ($arg eq "-v") {
423     do_vcalendar_schedule(@ARGV);
424 } elsif ($arg eq "-x") {
425     do_xml_schedule(@ARGV);
426 } elsif ($arg eq "-g") {
427     do_html_grades(@ARGV);
428 }
429