vCalendar fixes
[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 Getopt::Long;
14 use LWP::UserAgent;
15 use XML::Simple;
16 use vars qw(%opts %faculty %facurl);
17
18 $opts{'config'} = $ENV{HOME} . "/.schedprocrc";
19
20 my $arg = $ARGV[0] || "";
21 if($arg eq "-x") {
22     shift;
23     $opts{'format'} = "xml";
24 } elsif($arg eq "-h") {
25     shift;
26     $opts{'format'} = "html";
27 } elsif($arg eq "-m") {
28     shift;
29     $opts{'format'} = "mhc";
30 } elsif($arg eq "-c") {
31     shift;
32     $opts{'format'} = "csv";
33 } elsif($arg eq "-v") {
34     shift;
35     $opts{'format'} = "vcs";
36 } elsif($arg eq "-g") {
37     shift;
38     $opts{'format'} = "grades";
39 }
40
41 Getopt::Long::Configure ("bundling", "auto_help");
42 die "Invalid arguments\n" unless
43 GetOptions(\%opts, 'schedule|S=s', 'grades|G=s', 'faculty=s', 'name|n=s', 'email|e=s', 'format|f=s', 'config|F=s', 'out|o=s');
44
45 if (-r $opts{'config'}) {
46     open CONFIG, $opts{'config'} or die $!;
47     while(<CONFIG>) {
48         s/\#.*//;
49         next unless m/^([^=]*)=(.*)/;
50         my ($l, $r) = ($1, $2);
51         if ($l =~ /^(schedule|grades|name|email|faculty)$/) {
52             $opts{$l}=$r unless(defined($opts{$l}));
53         } else {
54             warn "Unknown config file option $l.\n";
55         }
56     }
57     close CONFIG;
58 }
59
60 $opts{'schedule'} ||= "~/schedule.xml";
61 $opts{'grades'} ||= "~/grades.xml";
62 $opts{'faculty'} ||= "";
63
64 $opts{'schedule'} =~ s/(^|,)~\//$1$ENV{HOME}\//;
65 $opts{'grades'} =~ s/(^|,)~\//$1$ENV{HOME}\//;
66 $opts{'faculty'} =~ s/(^|,)~\//$1$ENV{HOME}\//;
67
68 if(!defined($opts{'out'}) && defined($ARGV[0])) {
69     $opts{'out'} = shift;
70 }
71
72 if(!defined($opts{'format'}) && defined($opts{'out'})) {
73     $opts{'format'} = $opts{'out'};
74     $opts{'format'} =~ s/.*\.//;
75     $opts{'format'} =~ s/^(.*\/|)\.?schedule$/mhc/;
76     undef $opts{'out'} if($opts{'out'} =~ /^(html|mhc|csv|vcs|ics|xml|grades)$/);
77 }
78
79 $opts{'format'} ||= "";
80 undef $opts{'out'} if(($opts{'out'}||"") eq "-");
81
82 sub generate_id {
83     my ($section, $number) = split("-", shift);
84     my $id = 0;
85     foreach my $c (split //, $section) {$id=26*$id+(ord($c)-1)%32;}
86     $id=10000*$id+$number;
87     return $id;
88 }
89
90 sub first_class {
91     my %days = (M => 1, T => 2, W => 3, R => 4, F => 5, S => 6, U => 7);
92     my %class = @_;
93     $class{'duration'} =~ /(\d\d\d\d)(\d\d)(\d\d)-(\d\d\d\d)(\d\d)(\d\d)/;
94     my $days = Delta_Days($1,$2,$3,$4,$5,$6);
95     my $firstday = Date::Calc->new($1,$2,$3);
96     my $lastday = Date::Calc->new($4,$5,$6);
97     my $today;
98     my @days=();
99     foreach my $d (split("",$class{'days'})) {
100         push @days, $days{$d};
101     }
102     my @off = ();
103     @off = @{$class{'off'}} if ($class{'off'});
104     for($today = $firstday; $today < $lastday; $today++) {
105         next unless(grep($_ == Day_of_Week($today->date), @days));
106         next if(grep($_ == "$today", @off));
107         return $today;
108     }
109     return undef;
110 }
111
112 sub next_class {
113     my %days = (M => 1, T => 2, W => 3, R => 4, F => 5, S => 6, U => 7);
114     my %class = @_;
115     $class{'duration'} =~ /(\d\d\d\d)(\d\d)(\d\d)-(\d\d\d\d)(\d\d)(\d\d)/;
116     my $days = Delta_Days($1,$2,$3,$4,$5,$6);
117     my $firstday = Date::Calc->new($1,$2,$3);
118     my $lastday = Date::Calc->new($4,$5,$6);
119     my $today = Date::Calc->new(Date::Calc->localtime(time+3600*6)->date);
120     my @days=();
121     foreach my $d(split("",$class{'days'})) {
122         push @days, $days{$d};
123     }
124     my @off = ();
125     @off = @{$class{'off'}} if ($class{'off'});
126     for($today = ($today > $firstday ? $today : $firstday); $today < $lastday; $today++) {
127         next unless(grep($_ == Day_of_Week($today->date), @days));
128         next if(grep($_ == "$today", @off));
129         return $today;
130     }
131     $today = Date::Calc->new(Date::Calc->gmtime->date);
132     for($today = ($today < $lastday ? $today : $lastday); $today > $firstday; $today--) {
133         next unless(grep($_ == Day_of_Week($today->date), @days));
134         next if(grep($_ == "$today", @off));
135         return $today;
136     }
137     return undef;
138 }
139
140 sub vcal_datetime {
141     my $date=shift;
142     my $time=shift;
143     $date =~ /(\d\d\d\d)(\d\d)(\d\d)/;
144     my ($y,$m,$d)=($1,$2,$3);
145     $time =~ /(\d\d):?(\d\d)/;
146     my $day=Date::Calc->gmtime(Mktime($y,$m,$d,$1,$2,0));
147     return sprintf ("%02d%02d%02dT%02d%02d%02dZ", $day->year(), $day->month(), $day->day(), $day->time());
148 }
149
150 sub capitalize {
151     local $_ = shift || "";
152     s/ +$//;
153     s/\b([A-Z])([A-Z]*)\b/$1\L$2/g;
154     s/\b(I)(i*)\b/$1\U$2/g;
155     s/\bUs\b/US/g;
156     s/ (And|For|Of|Or|The|To|With) / \l$1 /g;
157     s/\b(Mc)([a-z])/$1\u$2/g;
158     s/\b(Tcp\/Ip|Pc|Tba)\b/\U$&/g;
159     s/\bThru\b/Through/g;
160     s/\bAcct\b/Accounting/g;
161     s/\bAmer\b/American/g;
162     s/\bChem\b/Chemistry/g;
163     s/\bComp\b/Composition/g;
164     s/\bFed\b/Federal/g;
165     s/\bGen\b/General/g;
166     s/\bIntro\b/Introduction/g;
167     s/\bPrgm\b/Programming/g;
168     s/\bOp Sys\b/Operating System/g;
169     #s/\bGovt\b/Government/g;
170     s/\bLit\b/Literature/g;
171     s/\bPrin\b/Principles/g;
172     s/\bBus\b/Business/g;
173     s/\bSyst\b/Sys/g;
174     return $_;
175 }
176
177 sub read_fileurl {
178     my $content;
179     my $url=shift;
180     if($url =~ /:\/\//) {
181         my $ua = LWP::UserAgent->new;
182         $ua->timeout(10);
183         $ua->env_proxy;
184 #       $ua->cookie_jar( {} );
185         my $response = $ua->get("$url") or die "$!";
186         if($response->is_success) {
187             $content = $response->content;
188         } else {
189             die "$!" unless $_[0];
190         }
191     } else {
192         if(open(F,$url)) {
193             $content = join ("", <F>);
194             close F;
195         } else {
196             die "$!" unless $_[0];
197         }
198     }
199     return $content||"";
200     #my $ref = XMLin($content, ForceArray => [ 'class', 'cumulative', 'off' ], KeyAttr => "");
201     #return @{$ref->{'class'}};
202 }
203
204 sub get_schedule {
205     my $content = read_fileurl($opts{'schedule'});
206     my $ref = XMLin($content, ForceArray => [ 'class', 'off' ], KeyAttr => "");
207     die "Could not load schedule.\n" unless $ref->{'class'};
208     return @{$ref->{'class'}};
209 }
210
211 sub get_grades {
212     my $content = read_fileurl($opts{'grades'});
213     my $ref = XMLin($content, ForceArray => [ 'class', 'cumulative' ], KeyAttr => "");
214     return $ref;
215 }
216
217 sub load_faculty {
218     my ($name, $email, $url, $content);
219     if(($opts{'faculty'}) && ! %faculty) {
220         $faculty{'done'} = "true";
221         $content = read_fileurl($opts{'faculty'},1);
222         foreach my $f (split("\n", $content)) {
223             ($name, $email, $url) = $f =~ m/"([^"]*)",([^,]*),([^,]*)/; # "
224             next unless ($name);
225             $name =~ s/ [A-Z]\.//g;
226             $name = lc $name;
227             $name =~ s/\W//g;
228             $faculty{$name} = $email if($email);
229             $facurl{$name} = $url if ($url);
230         }
231     }
232 }
233
234 sub get_faculty_email {
235     load_faculty();
236     my ($name);
237     $name = shift;
238     $name =~ s/ [A-Z]r?\.//g;
239     $name = lc $name;
240     $name =~ s/\W//g;
241     return $faculty{$name};
242 }
243
244 sub get_faculty_url {
245     load_faculty();
246     my ($name);
247     $name = shift;
248     $name =~ s/ [A-Z]r?\.//g;
249     $name = lc $name;
250     $name =~ s/\W//g;
251     return $facurl{$name};
252 }
253
254 sub get_mhc_header {
255 return (
256 "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",
257 "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",
258 "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",
259 "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",
260 "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",
261 "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",
262 "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",
263 "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",
264 "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",
265 "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",
266 );
267 }
268
269 sub do_mhc_schedule {
270     $| = 1;
271     my %days = (M => "Mon", T => "Tue", W => "Wed", R => "Thu", F => "Fri", S => "Sat", U => "SU");
272     my @mon = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
273     my ($file, $current, @mhc, @schedule);
274     $file = $opts{'out'};
275     @schedule = get_schedule(@_);
276     @mhc = get_mhc_header;
277     if(defined($file) && (-d $file)) {
278         my @mhc2;
279         local $_;
280         foreach (@mhc) {
281             s/X-SC-Subject: ([^\n]*)/X-SC-Subject: $1\nSubject: $1/;
282             s/X-SC-Category: ([^\n]*)/X-SC-Category: $1\nFrom: $1/;
283             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;
284             push @mhc2, $_;
285         }
286         @mhc = @mhc2;
287     }
288     foreach my $row (@schedule) {
289         map {s/\n/-/g if defined; $_} %$row;
290         my $id=generate_id($row->{'id'});
291         my $next = next_class(%$row);
292         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
293         $row->{'days'} =~ s/^ //;
294         #$row->{'duration'} =~ s/(\d\d)-(\d\d)-(\d\d)/20$3$1$2/g;
295         my @day = ();
296         @day = map { "!$_" } (@{$row->{'off'}}) if ($row->{'off'});
297         $current = "";
298         #print "# $id\n";
299         $current .= "X-SC-Subject: " . $row->{'title'} . "\n";
300         $current .= "X-SC-Location: " . $row->{'location'} . "\n";
301         $current .= "X-SC-Category: School\n";
302         $current .= "X-SC-Cond: " . $row->{'days'} . "\n";
303         $current .= "X-SC-Time: ".$row->{'begin'}."-".$row->{'end'}."\n";
304         $current .= "X-SC-Duration: " . $row->{'duration'} . "\n";
305         $current .= "X-SC-Day: @day\n" if(exists $day[0]);
306         $current .= "X-SC-Alarm: 15 minutes\n";
307         $current .= "X-SC-Record-Id: <".$row->{'id'}."\@from.sctweb>\n";
308         if(defined($file) && (-d $file)) {
309             my $email = get_faculty_email $row->{'instructor'};
310             $row->{'instructor'} = '"' . $row->{'instructor'} . '" <'. ($email || ($1 || "unknown") . "\@from.sctweb") . ">";
311             $row->{'duration'} =~ /^(\d\d\d\d)(\d\d)(\d\d)-\d{8}$/;
312             $row->{'begin'} =~ /^(\d\d):(\d\d)$/;
313             my @date = Gmtime(Mktime($next->date,$1,$2,0));
314             $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];
315             $current .= "Subject: " . $row->{'title'} . "\n";
316             $current .= "From: " . $row->{'instructor'} . "\n";
317         }
318         #print "\n$current";
319         push @mhc, $current;
320     }
321     if(defined($file) && (-d $file)) {
322         my @lines;
323         foreach my $name (<$file/[1-9]*>) {
324             next unless $name =~ /^$file\/[1-9][0-9]*$/;
325             open (FH, $name) || die $!;
326             @lines = <FH>;
327             close FH;
328             foreach (@lines) {
329                 unlink $name if /^X-SC-Record-Id: <.*\@from.sctweb>/;
330             }
331         }
332         my $i=0;
333         foreach my $h (@mhc) {
334             while(-f ++$i) {}
335             open (FH, ">$file/$i") || die $!;
336             print FH $h;
337             close FH;
338         }
339     } else {
340         open(STDOUT, ">" . $file) || die $! if(defined($file));
341         print "# MHC school schedule\n# Autogenerated by sctweb ".localtime()."\n\n";
342         print join("\n", @mhc);
343     }
344 }
345
346 sub do_csv_schedule {
347     $| = 1;
348     my %days = (M => "Mon", T => "Tue", W => "Wed", R => "Thu", F => "Fri", S => "Sat", U => "SU");
349     my @mon = qw(Jan. Feb. Mar. Apr. May June July Aug. Sept. Oct. Nov. Dec.);
350     my ($current, @mhc, @schedule);
351     @schedule = get_schedule(@_);
352     open(STDOUT, ">" . $opts{'out'}) || die $! if(defined($opts{'out'}));
353     foreach my $row (@schedule) {
354         map {s/\n/-/g if defined; $_} %$row;
355         my $id=generate_id($row->{'id'});
356         my $next = next_class(%$row);
357         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
358         $row->{'days'} =~ s/^ //;
359         $current = "";
360         #print "# $id\n";
361         $current .= $row->{'id'} . ",";
362         $current .= $row->{'title'} . ",";
363         my $instructor = $row->{'instructor'};
364         $instructor =~ s/ [A-Z. ]* / /;
365         $current .= '"' . $instructor . '",';
366         $next =~ /^(\d\d\d\d)(\d\d)(\d\d)$/;
367         $current .= $1 . "-". $2 ."-" . $3 . "\n";
368         print $current;
369     }
370 }
371
372 sub do_vcalendar_schedule {
373     $| = 1;
374     my %days = (M => "MO", T => "TU", W => "WE", R => "TH", F => "FR", S => "SA", U => "SU");
375     my $file = $opts{'out'};
376     my @schedule = get_schedule(@_);
377     open(STDOUT, ">" . $file) || die $! if(defined($file) && (! -d $file));
378     open(STDOUT, ">/dev/null") || die $! if(defined($file) && (-d $file));
379     print "BEGIN:VCALENDAR\r\nVERSION:1.0\r\n";
380     foreach my $row (@schedule) {
381         map { s/\n/-/g; $_} %$row;
382         my ($starttime, $stoptime)=($row->{'begin'}, $row->{'end'});
383         my ($startdate, $stopdate)=split(/-/, $row->{'duration'});
384         $starttime =~ s/://;
385         $stoptime =~ s/://;
386         my $first = first_class(%$row);
387         my @day = ();
388         @day = @{$row->{'off'}} if ($row->{'off'});
389         my $day = "";
390         if(exists($day[0])) {
391             $day = join(";", @day);
392             $day =~ s/\b(\d{8})\b/$1T${starttime}00/g;
393         }
394         if(defined($file) && (-d $file)) {
395             open FH, ">$file/" . $row->{'id'} . ".vcs" or die "$!";
396             select FH;
397             print "BEGIN:VCALENDAR\r\nVERSION:1.0\r\n";
398         }
399         print "BEGIN:VEVENT\r\n";
400         print "SUMMARY:", $row->{'title'}, "\r\n";
401         print "DESCRIPTION:", $row->{'id'}, "\r\n";
402         print "LOCATION:", $row->{'location'}, "\r\n";
403         print "CATEGORIES:Education\r\n";
404         print "DTSTART:", vcal_datetime($first,$starttime), "\r\n";
405         print "DTEND:", vcal_datetime($first,$stoptime), "\r\n";
406         #print "DTSTART:", $first."T".$starttime, "00\r\n";
407         #print "DTEND:", $first."T".$stoptime, "00\r\n";
408         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
409         $row->{'days'} =~ s/^ //;
410         print "RRULE:W1 ", $row->{'days'} . " $stopdate", "T000000\r\n";
411         print("EXDATE:$day\r\n") if($day);
412         print "ATTENDEE;ROLE=OWNER;STATUS=CONFIRMED:", $opts{'name'}, ($opts{'email'}?" <".$opts{'email'}.">":""), "\r\n" if(defined($opts{'name'}));
413         print "ATTENDEE;ROLE=ORGANIZER;STATUS=CONFIRMED:", $row->{'instructor'}, " <" . (get_faculty_email($row->{'instructor'}) || "fake\@ddress"), ">\r\n";
414         print "END:VEVENT\r\n";
415         if(defined($file) && (-d $file)) {
416             print "END:VCALENDAR\r\n";
417             close FH;
418             select STDOUT;
419         }
420     }
421     print "END:VCALENDAR\r\n";
422 }
423
424 sub do_icalendar_schedule {
425     $| = 1;
426     my $r="\r";
427     # Ugh, I can't find a better solution than hardwiring it to CST
428     my $tzn = "America/Chicago";
429     my $timezone = <<EOF
430 BEGIN:VTIMEZONE$r
431 TZID:$tzn$r
432 BEGIN:STANDARD$r
433 DTSTART:20041031T020000$r
434 RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=-1SU;BYMONTH=10$r
435 TZOFFSETFROM:-0500$r
436 TZOFFSETTO:-0600$r
437 TZNAME:Standard Time$r
438 END:STANDARD$r
439 BEGIN:DAYLIGHT$r
440 DTSTART:20050403T020000$r
441 RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=1SU;BYMONTH=4$r
442 TZOFFSETFROM:-0600$r
443 TZOFFSETTO:-0500$r
444 TZNAME:Daylight Saving Time$r
445 END:DAYLIGHT$r
446 END:VTIMEZONE$r
447 EOF
448     ;
449     my $now = Date::Calc->now();
450     $now = sprintf ("%02d%02d%02dT%02d%02d%02dZ", $now->datetime());
451     my %days = (M => "MO", T => "TU", W => "WE", R => "TH", F => "FR", S => "SA", U => "SU");
452     my $file = $opts{'out'};
453     my @schedule = get_schedule(@_);
454     open(STDOUT, ">" . $file) || die $! if(defined($file) && (! -d $file));
455     open(STDOUT, ">/dev/null") || die $! if(defined($file) && (-d $file));
456     print "BEGIN:VCALENDAR$r\nPRODID:-//Tim Pope//NONSGML Schedproc//EN$r\nVERSION:2.0$r\nMETHOD:PUBLISH$r\n$timezone";
457     foreach my $row (@schedule) {
458         map { s/\n/-/g; $_} %$row;
459         my ($starttime, $stoptime)=($row->{'begin'}, $row->{'end'});
460         my ($startdate, $stopdate)=split(/-/, $row->{'duration'});
461         $starttime =~ s/://;
462         $stoptime =~ s/://;
463         my $first = first_class(%$row);
464         my @day = ();
465         @day = @{$row->{'off'}} if ($row->{'off'});
466         my $day = "";
467         if(exists($day[0])) {
468             $day = join(",", @day);
469             #$day =~ s/\b(\d{8})\b/$1T${starttime}00/g;
470         }
471         if(defined($file) && (-d $file)) {
472             open FH, ">$file/" . $row->{'id'} . ".vcs" or die "$!";
473             select FH;
474             print "BEGIN:VCALENDAR$r\nPRODID:-//Tim Pope//NONSGML Schedproc//EN$r\nVERSION:2.0$r\nMETHOD:PUBLISH$r\n$timezone";
475         }
476         print "BEGIN:VEVENT$r\n";
477         print "ORGANIZER:mailto:" . $opts{'email'} . "$r\n" if $opts{'email'};
478         print "UID:" . $row->{'id'} . "\@from.sctweb$r\n";
479         print "DTSTAMP:$now$r\n";
480         print "SUMMARY:", $row->{'title'}, "$r\n";
481         print "DESCRIPTION:", $row->{'id'}, "$r\n";
482         print "LOCATION:", $row->{'location'}, "$r\n";
483         print "CATEGORIES:Education$r\n";
484         print "TRANSP:OPAQUE$r\n";
485         print "DTSTART;TZID=\"$tzn\":", $first."T".$starttime, "00$r\n";
486         print "DTEND;TZID=\"$tzn\":", $first."T".$stoptime, "00$r\n";
487         $row->{'days'} =~ s/([MTWRFS])/,$days{$1}/g;
488         $row->{'days'} =~ s/^,//;
489         #$stopdate++;
490         print "RRULE:FREQ=WEEKLY;UNTIL=${stopdate}T000000Z;BYDAY=", $row->{'days'}, "$r\n";
491         #print("EXDATE;TZID=\"$tzn\":$day$r\n") if($day);
492         print("EXDATE;VALUE=DATE:$day$r\n") if($day);
493         print "ATTENDEE;CN=".$row->{'instructor'}.";RSVP=FALSE;PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:" . (get_faculty_email($row->{'instructor'}) || "fake\@ddress"), "$r\n";
494         print "ATTENDEE;CN=".$opts{'name'}.";RSVP=FALSE;PARTSTAT=ACCEPTED;ROLE=REQ-PARTICIPANT:mailto:" . ($opts{'email'} || "fake\@ddress"), "$r\n" if $opts{'name'};
495         print "END:VEVENT$r\n";
496         if(defined($file) && (-d $file)) {
497             print "END:VCALENDAR$r\n";
498             close FH;
499             select STDOUT;
500         }
501     }
502     print "END:VCALENDAR$r\n";
503 }
504
505 sub do_xml_schedule {
506     my $file = $opts{'out'};
507     my $schedule = { class => [ get_schedule(@_) ] };
508     my $xml = XMLout($schedule, NoAttr => 1, RootName => 'schedule');
509     if($file) {
510         open FH, ">$file" || die $!;
511         print FH $xml;
512         close FH;
513     } else {
514         print $xml;
515     }
516 }
517
518 sub do_html_schedule {
519     my @showheaders = ("Section ID/Title", "Instructor", "Days", "Time", "Duration", "Location");
520     my $shade = "dark";
521     my @schedule = get_schedule(@_);
522     if($opts{'out'}) {
523         open (FH, ">".$opts{'out'}) || die $!;
524         select FH;
525     }
526     print '<table id="schedule" cellpadding="3" cellspacing="0">'."\n<tr><th>";
527     print join("</th><th>",@showheaders);
528     print "</th></tr>\n";
529         foreach my $row (@schedule) {
530             map { s/\n/<br \/>/g; $_} %$row;
531             $row->{'duration'} =~ s/-/<br \/>/g;
532             $row->{'duration'} =~ s/\d\d(\d\d)(\d\d)(\d\d)/$2-$3-$1/g;
533             print '<tr class="'.$shade.'">';
534             $shade = ($shade eq "dark"?"light":"dark");
535             print '<td class="idtitle">';
536             print '<span class="sectionid">' .$row->{'id'}. '</span><br />';
537             print '<span class="coursetitle">' .$row->{'title'}. '</span></td>';
538             my $instructor = $row->{'instructor'};
539             #$instructor =~ s/ [A-Z. ]* / /;
540             my $url = get_faculty_url($row->{'instructor'});
541             if($url) {
542                 print '<td class="instructor"><a href="' . $url . '">'
543                 . $row->{'instructor'} . "</a></td>";
544             } else {
545                 print '<td class="instructor">' . $instructor . "</td>";
546             }
547             print "<td>" . $row->{'days'} . "</td>";
548             my ($a,$b) = ($row->{'begin'}, $row->{'end'});
549             $b .= "AM";
550             $a=~s/(1[3-9]|2\d|00):(\d\d)/sprintf "%d:%02d",abs $1-12,$2/e;
551             $b=~s/(1[3-9]|2\d|00):(\d\d)AM/sprintf "%d:%02dPM",abs $1-12,$2/e;
552             print "<td>$a-<wbr />$b</td>";
553             print "<td>" . $row->{'duration'} . "</td>";
554             print "<td>" . (ref($row->{'location'})?"":$row->{'location'}) . "</td>";
555             print "</tr>\n";
556         }
557     print "</table>\n";
558     select STDOUT;
559 }
560
561 sub do_html_grades {
562     my $grades;
563     my @showheaders = ("Section ID", "Course Title", "Grade", "Earned<br />Hours", "Quality<br />Hours", "Quality<br />Points");
564     $grades = get_grades(@_);
565     my ($row);
566     my $shade = "dark";
567     if($opts{'out'}) {
568         open (FH, ">".$opts{'out'}) || die $!;
569         select FH;
570     }
571     print '<table id="grades" cellpadding="3" cellspacing="0">'."\n<tr>";
572     print '<th align="left" class="sectionid">', $showheaders[0];
573     print '</th><th align="left" class="coursetitle">', $showheaders[1];
574     print '</th><th align="center" class="grade">';
575     print join('</th><th align="center" class="right-number">',@showheaders[2 .. 5]);
576     print "</th></tr>\n";
577     foreach my $ts ($grades->{'class'}) {
578         foreach my $row (@$ts) {
579             print '<tr class="'.$shade.'">';
580             $shade = ($shade eq "dark"?"light":"dark");
581             print '<td align="left" class="sectionid">', $row->{'id'}, '</td>';
582             print '<td align="left" class="coursetitle">', $row->{'title'}, '</td>';
583             print '<td align="center" class="grade">';
584             #print join('</td><td>', @$row[0 .. 1]);
585             print join('</td><td align="right" class="right-number">', ($row->{'grade'},$row->{'earned'},$row->{'hours'},$row->{'points'}));
586             print "</td></tr>\n";
587         }
588     }
589     my $lastrow = $grades->{'cumulative'}->[scalar @{$grades->{'cumulative'}}-1];
590     print '<tr class="cumulative '.$shade.'"><td id="cumulative" colspan="2">Cumulative: through ', capitalize($lastrow->{'term'});
591     print '</td><td align="center" id="gpa" class="grade">';
592     print $lastrow->{'gpa'};
593     print '</td><td align="right" class="right-number">';
594     print join('</td><td align="right" class="right-number">', ($lastrow->{'earned'}, $lastrow->{'hours'}, $lastrow->{'points'}));
595     print "</td></tr>\n";
596     print "</table>\n";
597     select STDOUT;
598 }
599
600
601 if ($opts{'format'} eq "xml") {
602     do_xml_schedule(@ARGV);
603 } elsif ($opts{'format'} eq "html") {
604     do_html_schedule(@ARGV);
605 } elsif ($opts{'format'} eq "mhc") {
606     do_mhc_schedule(@ARGV);
607 } elsif ($opts{'format'} eq "csv") {
608     do_csv_schedule(@ARGV);
609 } elsif ($opts{'format'} eq "vcs") {
610     do_vcalendar_schedule(@ARGV);
611 } elsif ($opts{'format'} eq "ics") {
612     do_icalendar_schedule(@ARGV);
613 } elsif ($opts{'format'} eq "grades") {
614     do_html_grades(@ARGV);
615 } else {
616     die "Unknown format.  Try specifying --format.\n"
617 }