de2e0e0b33a1e80be7d639b5b828e0b76365390a
[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 (split //, $section) {$id=26*$id+(ord($_)-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(split("",$class{'days'})) {
100         push @days, $days{$_};
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(split("",$class{'days'})) {
122         push @days, $days{$_};
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 ical_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 $_ (split("\n", $content)) {
223             m/"([^"]*)",([^,]*),([^,]*)/; # "
224             ($name, $email, $url) = ($1, $2, $3);
225             next unless ($name);
226             $name =~ s/ [A-Z]\.//g;
227             $name = lc $name;
228             $name =~ s/\W//g;
229             $faculty{$name} = $email if($email);
230             $facurl{$name} = $url if ($url);
231         }
232     }
233 }
234
235 sub get_faculty_email {
236     load_faculty();
237     my ($name);
238     $name = shift;
239     $name =~ s/ [A-Z]r?\.//g;
240     $name = lc $name;
241     $name =~ s/\W//g;
242     return $faculty{$name};
243 }
244
245 sub get_faculty_url {
246     load_faculty();
247     my ($name);
248     $name = shift;
249     $name =~ s/ [A-Z]r?\.//g;
250     $name = lc $name;
251     $name =~ s/\W//g;
252     return $facurl{$name};
253 }
254
255 sub get_mhc_header {
256 return (
257 "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",
258 "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",
259 "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",
260 "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",
261 "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",
262 "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",
263 "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",
264 "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",
265 "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",
266 "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",
267 );
268 }
269
270 sub do_mhc_schedule {
271     $| = 1;
272     my %days = (M => "Mon", T => "Tue", W => "Wed", R => "Thu", F => "Fri", S => "Sat", U => "SU");
273     my @mon = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
274     my ($file, $current, @mhc, @schedule);
275     $file = $opts{'out'};
276     @schedule = get_schedule(@_);
277     @mhc = get_mhc_header;
278     if(defined($file) && (-d $file)) {
279         my @mhc2;
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 (@mhc) {
334             while(-f ++$i) {}
335             open (FH, ">$file/$i") || die $!;
336             print FH $_;
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 @day = ();
383         @day = @{$row->{'off'}} if ($row->{'off'});
384         my $day = "";
385         if(exists($day[0])) {
386             $day = join(";", @day);
387             $day =~ s/\b(\d{8})\b/$1T000000/g;
388         }
389         my ($starttime, $stoptime)=($row->{'begin'}, $row->{'end'});
390         my ($startdate, $stopdate)=split(/-/, $row->{'duration'});
391         $starttime =~ s/://;
392         $stoptime =~ s/://;
393         my $first = first_class(%$row);
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:", ical_datetime(first_class(%$row),$starttime), "\r\n";
405         print "DTSTART:", $first."T".$starttime, "00\r\n";
406         print "DTEND:", $first."T".$stoptime, "00\r\n";
407         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
408         $row->{'days'} =~ s/^ //;
409         print "RRULE:W1 ", $row->{'days'} . " $stopdate", "T000000\r\n";
410         print("EXDATE:$day\r\n") if($day);
411         print "ATTENDEE;ROLE=OWNER;STATUS=CONFIRMED:", $opts{'name'}, ($opts{'email'}?" <".$opts{'email'}.">":""), "\r\n" if(defined($opts{'name'}));
412         print "ATTENDEE;ROLE=ORGANIZER;STATUS=CONFIRMED:", $row->{'instructor'}, " <" . (get_faculty_email($row->{'instructor'}) || "fake\@ddress"), ">\r\n";
413         print "END:VEVENT\r\n";
414         if(defined($file) && (-d $file)) {
415             print "END:VCALENDAR\r\n";
416             close FH;
417             select STDOUT;
418         }
419     }
420     print "END:VCALENDAR\r\n";
421 }
422
423 sub do_icalendar_schedule {
424     $| = 1;
425     my $r="\r";
426     # Ugh, I can't find a better solution than hardwiring it to CST
427     my $tzn = "America/Chicago";
428     my $timezone = <<EOF
429 BEGIN:VTIMEZONE$r
430 TZID:$tzn$r
431 BEGIN:STANDARD$r
432 DTSTART:20041031T020000$r
433 RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=-1SU;BYMONTH=10$r
434 TZOFFSETFROM:-0500$r
435 TZOFFSETTO:-0600$r
436 TZNAME:Standard Time$r
437 END:STANDARD$r
438 BEGIN:DAYLIGHT$r
439 DTSTART:20050403T020000$r
440 RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=1SU;BYMONTH=4$r
441 TZOFFSETFROM:-0600$r
442 TZOFFSETTO:-0500$r
443 TZNAME:Daylight Savings Time$r
444 END:DAYLIGHT$r
445 END:VTIMEZONE$r
446 EOF
447     ;
448     my %days = (M => "MO", T => "TU", W => "WE", R => "TH", F => "FR", S => "SA", U => "SU");
449     my $file = $opts{'out'};
450     my @schedule = get_schedule(@_);
451     open(STDOUT, ">" . $file) || die $! if(defined($file) && (! -d $file));
452     open(STDOUT, ">/dev/null") || die $! if(defined($file) && (-d $file));
453     print "BEGIN:VCALENDAR$r\nVERSION:2.0$r\n$timezone";
454     foreach my $row (@schedule) {
455         map { s/\n/-/g; $_} %$row;
456         my @day = ();
457         @day = @{$row->{'off'}} if ($row->{'off'});
458         my ($starttime, $stoptime)=($row->{'begin'}, $row->{'end'});
459         my ($startdate, $stopdate)=split(/-/, $row->{'duration'});
460         $starttime =~ s/://;
461         $stoptime =~ s/://;
462         my $first = first_class(%$row);
463         if(defined($file) && (-d $file)) {
464             open FH, ">$file/" . $row->{'id'} . ".vcs" or die "$!";
465             select FH;
466             print "BEGIN:VCALENDAR$r\nVERSION:2.0$r\n$timezone";
467         }
468         print "BEGIN:VEVENT$r\n";
469         print "SUMMARY:", $row->{'title'}, "$r\n";
470         print "DESCRIPTION:", $row->{'id'}, "$r\n";
471         print "LOCATION:", $row->{'location'}, "$r\n";
472         print "CATEGORIES:Education$r\n";
473         #print "DTSTART;$tzn$first,$starttime), "$r\n";
474         #print "DTEND;$tzn$first,$stoptime), "$r\n";
475         print "DTSTART;\"$tzn\":", $first."T".$starttime, "00$r\n";
476         print "DTEND;\"$tzn\":", $first."T".$stoptime, "00$r\n";
477         $row->{'days'} =~ s/([MTWRFS])/,$days{$1}/g;
478         $row->{'days'} =~ s/^,//;
479         print "RRULE:FREQ=WEEKLY;UNTIL=$stopdate;BYDAY=", $row->{'days'}, "$r\n";
480         foreach my $day (@day) {
481             print("\"EXDATE\";$tzn$day$r\n");
482         }
483         print "ATTENDEE;CN=".$row->{'instructor'}.";RSVP=FALSE;PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:" . (get_faculty_email($row->{'instructor'}) || "fake\@ddress"), "$r\n";
484         print "ATTENDEE;CN=".$opts{'name'}.";RSVP=FALSE;PARTSTAT=ACCEPTED;ROLE=REQ-PARTICIPANT:mailto:" . ($opts{'email'} || "fake\@ddress"), "$r\n" if $opts{'name'};
485         print "END:VEVENT$r\n";
486         if(defined($file) && (-d $file)) {
487             print "END:VCALENDAR$r\n";
488             close FH;
489             select STDOUT;
490         }
491     }
492     print "END:VCALENDAR$r\n";
493 }
494
495 sub do_xml_schedule {
496     my $file = $opts{'out'};
497     my $schedule = { class => [ get_schedule(@_) ] };
498     my $xml = XMLout($schedule, NoAttr => 1, RootName => 'schedule');
499     if($file) {
500         open FH, ">$file" || die $!;
501         print FH $xml;
502         close FH;
503     } else {
504         print $xml;
505     }
506 }
507
508 sub do_html_schedule {
509     my @showheaders = ("Section ID/Title", "Instructor", "Days", "Time", "Duration", "Location");
510     my $shade = "dark";
511     my @schedule = get_schedule(@_);
512     if($opts{'out'}) {
513         open (FH, ">".$opts{'out'}) || die $!;
514         select FH;
515     }
516     print '<table id="schedule" cellpadding="3" cellspacing="0">'."\n<tr><th>";
517     print join("</th><th>",@showheaders);
518     print "</th></tr>\n";
519         foreach my $row (@schedule) {
520             map { s/\n/<br \/>/g; $_} %$row;
521             $row->{'duration'} =~ s/-/<br \/>/g;
522             $row->{'duration'} =~ s/\d\d(\d\d)(\d\d)(\d\d)/$2-$3-$1/g;
523             print '<tr class="'.$shade.'">';
524             $shade = ($shade eq "dark"?"light":"dark");
525             print '<td class="idtitle">';
526             print '<span class="sectionid">' .$row->{'id'}. '</span><br />';
527             print '<span class="coursetitle">' .$row->{'title'}. '</span></td>';
528             my $instructor = $row->{'instructor'};
529             #$instructor =~ s/ [A-Z. ]* / /;
530             my $url = get_faculty_url($row->{'instructor'});
531             if($url) {
532                 print '<td class="instructor"><a href="' . $url . '">'
533                 . $row->{'instructor'} . "</a></td>";
534             } else {
535                 print '<td class="instructor">' . $instructor . "</td>";
536             }
537             print "<td>" . $row->{'days'} . "</td>";
538             my ($a,$b) = ($row->{'begin'}, $row->{'end'});
539             $b .= "AM";
540             $a=~s/(1[3-9]|2\d|00):(\d\d)/sprintf "%d:%02d",abs $1-12,$2/e;
541             $b=~s/(1[3-9]|2\d|00):(\d\d)AM/sprintf "%d:%02dPM",abs $1-12,$2/e;
542             print "<td>$a-<wbr />$b</td>";
543             print "<td>" . $row->{'duration'} . "</td>";
544             print "<td>" . $row->{'location'} . "</td>";
545             print "</tr>\n";
546         }
547     print "</table>\n";
548     select STDOUT;
549 }
550
551 sub do_html_grades {
552     my $grades;
553     my @showheaders = ("Section ID", "Course Title", "Grade", "Earned<br />Hours", "Quality<br />Hours", "Quality<br />Points");
554     $grades = get_grades(@_);
555     my ($row);
556     my $shade = "dark";
557     if($opts{'out'}) {
558         open (FH, ">".$opts{'out'}) || die $!;
559         select FH;
560     }
561     print '<table id="grades" cellpadding="3" cellspacing="0">'."\n<tr>";
562     print '<th align="left" class="sectionid">', $showheaders[0];
563     print '</th><th align="left" class="coursetitle">', $showheaders[1];
564     print '</th><th align="center" class="grade">';
565     print join('</th><th align="center" class="right-number">',@showheaders[2 .. 5]);
566     print "</th></tr>\n";
567     foreach my $ts ($grades->{'class'}) {
568         foreach my $row (@$ts) {
569             print '<tr class="'.$shade.'">';
570             $shade = ($shade eq "dark"?"light":"dark");
571             print '<td align="left" class="sectionid">', $row->{'id'}, '</td>';
572             print '<td align="left" class="coursetitle">', $row->{'title'}, '</td>';
573             print '<td align="center" class="grade">';
574             #print join('</td><td>', @$row[0 .. 1]);
575             print join('</td><td align="right" class="right-number">', ($row->{'grade'},$row->{'earned'},$row->{'hours'},$row->{'points'}));
576             print "</td></tr>\n";
577         }
578     }
579     my $lastrow = $grades->{'cumulative'}->[scalar @{$grades->{'cumulative'}}-1];
580     print '<tr class="cumulative '.$shade.'"><td id="cumulative" colspan="2">Cumulative: through ', capitalize($lastrow->{'term'});
581     print '</td><td align="center" id="gpa" class="grade">';
582     print $lastrow->{'gpa'};
583     print '</td><td align="right" class="right-number">';
584     print join('</td><td align="right" class="right-number">', ($lastrow->{'earned'}, $lastrow->{'hours'}, $lastrow->{'points'}));
585     print "</td></tr>\n";
586     print "</table>\n";
587     select STDOUT;
588 }
589
590
591 if ($opts{'format'} eq "xml") {
592     do_xml_schedule(@ARGV);
593 } elsif ($opts{'format'} eq "html") {
594     do_html_schedule(@ARGV);
595 } elsif ($opts{'format'} eq "mhc") {
596     do_mhc_schedule(@ARGV);
597 } elsif ($opts{'format'} eq "csv") {
598     do_csv_schedule(@ARGV);
599 } elsif ($opts{'format'} eq "vcs") {
600     do_vcalendar_schedule(@ARGV);
601 } elsif ($opts{'format'} eq "ics") {
602     do_icalendar_schedule(@ARGV);
603 } elsif ($opts{'format'} eq "grades") {
604     do_html_grades(@ARGV);
605 } else {
606     die "Unknown format.  Try specifying --format.\n"
607 }