Bug fix
[tpope-extra.git] / perl / sct6
1 #!/usr/bin/perl -w
2 # $Id$
3 # -*- perl -*- vim: ft=perl sw=4 sts=4
4
5 # Brief usage instructions:
6 # Create a ~/.sct6rc that has SID=yourssn and PIN=yourpin
7 # You'll need to change the url below if you go anywhere but TAMUK.
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 HTML::TableExtract;
14 use LWP::UserAgent;
15 use IO::File;
16 use XML::Writer;
17 use vars qw($ua %opts %faculty);
18
19 my ($response);
20
21 $opts{'holidays'} = { # %{$Profiles->{'US-TX'}},
22     "Martin Luther King Day"    => "3/Mon/Jan",
23     "Good Friday"               => "-2",
24     "Spring Break Monday"       => \&Spring_Break,
25     "Spring Break Tuesday"      => \&Spring_Break,
26     "Spring Break Wednesday"    => \&Spring_Break,
27     "Spring Break Thursday"     => \&Spring_Break,
28     "Spring Break Friday"       => \&Spring_Break,
29     "Spring Break Saturday"     => \&Spring_Break,
30     "Study Day"                 => "4/Thu/Apr", # ?
31     "Memorial Day"              => "5/Mon/May",
32     "Independence Day"          => \&US_Independence,
33     "Labor Day"                 => \&US_Labor,
34     #"Columbus Day"              => "2/Mon/Oct",
35     "Thanksgiving Day"          => "4/Thu/Nov",
36     "Thanksgiving Friday"       => \&Thanksgiving_Friday,
37 };
38
39 sub Spring_Break {
40     my($year,$label) = @_;
41     $label =~ s/^Spring Break //;
42     return( Add_Delta_Days(
43             Nth_Weekday_of_Month_Year($year,1,1,1),
44             7*(11-1) # This is for the 11th Monday of the year
45             +Decode_Day_of_Week($label)-1) );
46 }
47
48 sub Thanksgiving_Friday {
49     my($year,$label) = @_;
50     return( Add_Delta_Days(Nth_Weekday_of_Month_Year($year,11,4,4), 1) );
51 }
52 sub US_Independence # Fourth of July
53 {
54     my($year,$label) = @_;
55     return( &Date::Calendar::Profiles::Nearest_Workday($year,7,4) );
56 }
57 sub US_Labor # First Monday after the first Sunday in September
58 {
59     my($year,$label) = @_;
60     return( Add_Delta_Days(
61         Nth_Weekday_of_Month_Year($year,9,7,1), +1) );
62 }
63
64 my $config = $ENV{HOME} . "/.sct6rc";
65 if (($ARGV[0] || "") eq '-F') {
66     shift;
67     $config = shift;
68 }
69
70 my $arg = "";
71 $arg = shift if (defined($ARGV[0]) && $ARGV[0] =~ /^-\w$/);
72
73 if (-r $config) {
74     open CONFIG, $config;
75     while(<CONFIG>) {
76         s/\#.*//;
77         next unless m/^([^=]*)=(.*)/;
78         $opts{$1}=$2;
79     }
80     close CONFIG;
81 }
82 my $domain = $opts{'domain'} || "as1.tamuk.edu:9003";
83 my $url = "https://$domain/pls/PROD/";
84 $url = $opts{'url'} if(defined($opts{'url'}));
85
86 $ua = LWP::UserAgent->new;
87 $ua->timeout(10);
88 $ua->env_proxy;
89 $ua->cookie_jar( {} );
90 $ua->get("${url}twbkwbis.P_WWWLogin") or die "$!";
91 $response = $ua->post("${url}twbkwbis.P_ValLogin", { sid => $opts{SID}, PIN => $opts{PIN} }) or die "$!";
92
93 $response = $ua->get("${url}bwskflib.P_SelDefTerm"); # Valid terms
94 die $response->status_line unless $response->is_success;
95 my @terms = grep {s/^<option value="([^"]*)">.*/$1/i} (split( /\r?\n/, $response->content)); # "
96 die "Site down. Try again later.\n" unless (@terms);
97
98 sub generate_id {
99     my ($section, $number) = split("-", shift);
100     my $id = 0;
101     foreach (split //, $section) {$id=26*$id+(ord($_)-1)%32;}
102     $id=10000*$id+$number;
103     return $id;
104 }
105
106 sub next_class {
107     my %class = @_;
108     $class{'duration'} =~ /(\d\d\d\d)(\d\d)(\d\d)-(\d\d\d\d)(\d\d)(\d\d)/;
109     my $days = Delta_Days($1,$2,$3,$4,$5,$6);
110     my $firstday = Date::Calc->new($1,$2,$3);
111     my $lastday = Date::Calc->new($4,$5,$6);
112     my $today = Date::Calc->new(Date::Calc->localtime(time+3600*6)->date);
113     my @days=();
114     foreach(split(" ",$class{'days'})) {
115         push @days, Decode_Day_of_Week($_);
116     }
117     my @off = (off_for_holidays(%class),off_for_exams(%class));
118     for($today = ($today > $firstday ? $today : $firstday); $today < $lastday; $today++) {
119         next unless(grep($_ == Day_of_Week($today->date), @days));
120         next if(grep($_ == $today, @off));
121         return $today;
122     }
123     $today = Date::Calc->new(Date::Calc->gmtime->date);
124     for($today = ($today < $lastday ? $today : $lastday); $today > $firstday; $today--) {
125         next unless(grep($_ == Day_of_Week($today->date), @days));
126         next if(grep($_ == $today, @off));
127         return $today;
128     }
129     return undef;
130 }
131
132 sub off_for_holidays {
133     my %class = @_;
134     $class{'duration'} =~ /(\d\d\d\d)(\d\d)(\d\d)-(\d\d\d\d)(\d\d)(\d\d)/;
135     my $days = Delta_Days($1,$2,$3,$4,$5,$6);
136     my $firstday = Date::Calc->new($1,$2,$3);
137     my $lastday = Date::Calc->new($4,$5,$6);
138     my $year = Date::Calendar::Year->new($1, $opts{'holidays'});
139     my @holidays=();
140     my @days=();
141     foreach(split(" ",$class{days})) {
142         $days[Decode_Day_of_Week($_)] = 1;
143     }
144     foreach ($year->search("")) {
145         my $good=1;
146         #foreach my $x ($year->labels($_)) {
147         #    $good=0 if ($x =~ /Veteran/ or $x =~ /President/);
148         #}
149         next unless ($year->is_full($_) && $_>=$firstday && $_<=$lastday);
150         push @holidays, $_
151             if (defined($days[Day_of_Week($_->date)]) && $good > 0);
152     }
153     return wantarray ? @holidays : "@holidays";
154 }
155
156 sub off_for_exams {
157     my %class = @_;
158     my $time = $class{'begin'} . "-" . $class{'end'};
159     $class{'duration'} =~ /\d{8}-(\d\d\d\d)(\d\d)(\d\d)/;
160     my $lastday = Date::Calc->new($1,$2,$3);
161     return wantarray ? () : undef unless (Day_of_Week($lastday->date) == 7);
162     my $beginning="(08:00-09:15|11:00-12:15|14:00-15:15|17:00-18:15|17:30-18:45|20:00-21:15|20:30-21:45)";
163     my $ending   ="(06:30-07:45|09:30-10:45|12:30-13:45|15:30-16:45|18:30-19:45|19:00-20:15)";
164     my $days = join(" ",map {Decode_Day_of_Week($_)} split(/ /, $class{'days'}));
165     if($days eq "1 3") {
166         if($time =~ /$beginning/) {
167             return $lastday-4;
168         } elsif($time =~ /$ending/) {
169             return $lastday-6;
170         }
171     } elsif($days eq "2 4") {
172         if($time =~ /$beginning/) {
173             return $lastday-3;
174         } elsif($time =~ /$ending/) {
175             return $lastday-5;
176         }
177     } elsif($days eq "5") {
178         return $lastday-2;
179     }
180     return wantarray ? () : "";
181 }
182
183 sub capitalize {
184     local $_ = shift || "";
185     s/ +$//;
186     s/\b([A-Z])([A-Z]*)\b/$1\L$2/g;
187     s/\b(I)(i*)\b/$1\U$2/g;
188     s/\bUs\b/US/g;
189     s/ (And|For|Of|Or|The|To|With) / \l$1 /g;
190     s/\b(Mc)([a-z])/$1\u$2/g;
191     s/\b(Tcp\/Ip|Pc|Tba)\b/\U$&/g;
192     s/\bThru\b/Through/g;
193     s/\bAcct\b/Accounting/g;
194     s/\bAmer\b/American/g;
195     s/\bChem\b/Chemistry/g;
196     s/\bComp\b/Composition/g;
197     s/\bFed\b/Federal/g;
198     s/\bGen\b/General/g;
199     s/\bIntro\b/Introduction/g;
200     s/\bPrgm\b/Programming/g;
201     s/\bOp Sys\b/Operating System/g;
202     #s/\bGovt\b/Government/g;
203     s/\bLit\b/Literature/g;
204     s/\bPrin\b/Principles/g;
205     s/\bBus\b/Business/g;
206     s/\bSyst\b/Sys/g;
207     return $_;
208 }
209
210 sub get_schedule_terms {
211     my (@sterms, @a);
212     @a=('10','20','30','40');   # Fall, Spring, Summer I, Summer II
213                                 # Last 3 are currently guesses
214     my @localtime=localtime();
215     if ($localtime[4]<3) { # Through Mar 31
216         @sterms=((1900+$localtime[5]).$a[1]);
217     } elsif ($localtime[4]<5) { # Through May 31
218         @sterms=((1900+$localtime[5]).$a[1],(1900+$localtime[5]).$a[2]);
219     } elsif ($localtime[4]<7) { # through July 31
220         @sterms=((1900+$localtime[5]).$a[2],(1900+$localtime[5]).$a[3]);
221     } elsif ($localtime[4]<8) { # through Aug 31
222         @sterms=((1900+$localtime[5]).$a[3],(1901+$localtime[5]).$a[0]);
223     } elsif ($localtime[4]<10) { # through Oct 31
224         @sterms=((1901+$localtime[5]).$a[0]);
225     } else {
226         @sterms=((1901+$localtime[5]).$a[0],(1901+$localtime[5]).$a[1]);
227     }
228     return @sterms;
229 }
230
231 sub get_schedule {
232     my @readheaders = ("Type", "Time", "Days", "Where", "Date Range", "Schedule Type", "Instructors");
233     my @class;
234     my $te = new HTML::TableExtract( headers => [ @readheaders ] );
235     my (@schedule, @terms, $classid, $title, $begin, $end, $times, $days, $session);
236     @terms = get_schedule_terms();
237     foreach (@_ ? @_ : @terms) {
238         $response = $ua->get("${url}bwskfshd.P_CrseSchdDetl?term_in=$_" );
239         die $response->status_line unless $response->is_success;
240         $te->parse($response->content);
241         foreach my $l (split (/\n/, $response->content)) {
242             next unless $l =~ s/.*<CAPTION class=[^>]*>(.* - .... \d\d\d\d \d\d\d)<\/caption>.*/$1/i;
243             push @class, $l;
244         }
245     }
246     foreach my $ts ($te->table_states) {
247         foreach my $row ($ts->rows) {
248             #map { s/\xa0//g; $_} @$row;
249             #$row->[0] =~ s/.*launchWebCT\("([^"]*)"\).*/$1/s;
250             #$row->[0] =~ s/(.*) ?<[Bb][Rr][^>]*>(.*)/capitalize($2)/eg;
251             $classid = (shift @class);
252             $title = $classid;
253             $classid =~ s/.* - //;
254             $classid =~ s/ /-/g;
255             $title =~ s/ - .*//;
256             $row->[6] =~ s/\b([A-Z]r?)$/$1./;
257             $row->[6] = capitalize($row->[6]);
258             $row->[6] =~ s/ *\([A-Z]\)//;
259             $row->[1] =~ s/ ?([ap])m/\u$1M/g;
260             $row->[1] =~ s/ - /-/;
261             ($begin, $end) = split(/ ?- ?/, $row->[1]);
262             $begin =~ s/^(\d):/0$1:/;
263             $end =~ s/^(\d):/0$1:/;
264             if (($begin=~/PM$/ && $begin!~/^12/)||($begin=~/^12:..AM/)) {
265                 $begin =~ s/^(\d?\d)/($1+12)%24/e;
266             }
267             if (($end=~/PM$/ && $end!~/^12/)||($end=~/^12:..AM/)) {
268                 $end =~ s/^(\d?\d)/($1+12)%24/e;
269             }
270             $begin =~ s/ ?[AP]M//;
271             $end =~ s/ ?[AP]M//;
272             $row->[4] =~ s/([A-Za-z]{3,9})/(Decode_Month($1)<10?"0":"").Decode_Month($1)/eg;
273             $row->[4] =~ s/(\d\d?) (\d\d), (\d\d\d\d)/$3$1$2/g;
274             $row->[4] =~ s/ - /-/;
275             $row->[3] =~ s/(ON|MAIN) CAMPUS\n|Palo Alto Building \d* //ig;
276             $row->[3] =~ s/\n/ /g;
277             push @schedule, {
278                 id => $classid,
279                 title => capitalize($title),
280                 instructor => $row->[6],
281                 days => $row->[2],
282                 #'time' => $row->[1],
283                 begin => $begin,
284                 end => $end || undef,
285                 duration => $row->[4],
286                 location => $row->[3],
287             };
288         }
289     }
290     return @schedule;
291 }
292
293 sub get_faculty_email {
294     my ($name, $school, $email);
295     if((-f $ENV{'HOME'} . "/public_html/faculty.csv") && ! %faculty) {
296         open INS, $ENV{'HOME'} . "/public_html/faculty.csv";
297         while($_ = <INS>) {
298             chomp;
299             m/"([^"]*)",([^,]*),([^,]*)/; # "
300             ($name, $email, $school) = ($1, $2, $3);
301             $name =~ s/^([^,]*), ([^,]*)(.*)$/$2 $1$3/;
302             $name =~ s/ [A-Z]\.//g;
303             $name = lc $name;
304             $name =~ s/\W//g;
305             $faculty{$name} = $email;
306         }
307     }
308     $name = shift;
309     $name =~ s/ [A-Z]r?\.//g;
310     $name = lc $name;
311     $name =~ s/\W//g;
312     return $faculty{$name};
313 }
314
315 sub get_mhc_header {
316 return (
317 "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",
318 "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",
319 "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",
320 "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",
321 "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",
322 "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",
323 "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",
324 "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",
325 "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",
326 "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",
327 );
328 }
329
330 sub do_mhc_schedule {
331     $| = 1;
332     my %days = (M => "Mon", T => "Tue", W => "Wed", R => "Thu", F => "Fri", S => "Sat", U => "SU");
333     my @mon = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
334     my ($file, $current, @mhc, @schedule);
335     $file = shift unless (!defined $_[0] or $_[0] =~ /^\d/);
336     @schedule = get_schedule(@_);
337     @mhc = get_mhc_header;
338     if(defined($file) && (-d $file)) {
339         my @mhc2;
340         foreach (@mhc) {
341             $_ =~ s/X-SC-Subject: ([^\n]*)/X-SC-Subject: $1\nSubject: $1/;
342             $_ =~ s/X-SC-Category: ([^\n]*)/X-SC-Category: $1\nFrom: $1/;
343             $_ =~ 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;
344             push @mhc2, $_;
345         }
346         @mhc = @mhc2;
347     }
348     foreach my $row (@schedule) {
349         map {s/\n/-/g if defined; $_} %$row;
350         my $id=generate_id($row->{'id'});
351         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
352         $row->{'days'} =~ s/^ //;
353         #$row->{'duration'} =~ s/(\d\d)-(\d\d)-(\d\d)/20$3$1$2/g;
354         my @day = map { "!" . $_ } (off_for_holidays(%$row),off_for_exams(%$row));
355         $current = "";
356         #print "# $id\n";
357         $current .= "X-SC-Subject: " . $row->{'title'} . "\n";
358         $current .= "X-SC-Location: " . $row->{'location'} . "\n";
359         $current .= "X-SC-Category: School\n";
360         $current .= "X-SC-Cond: " . $row->{'days'} . "\n";
361         $current .= "X-SC-Time: ".$row->{'begin'}."-".$row->{'end'}."\n";
362         $current .= "X-SC-Duration: " . $row->{'duration'} . "\n";
363         $current .= "X-SC-Day: @day\n" if(exists $day[0]);
364         $current .= "X-SC-Alarm: 15 minutes\n";
365         $current .= "X-SC-Record-Id: <".$row->{'id'}."\@from.sctweb>\n";
366         if(defined($file) && (-d $file)) {
367             $row->{'instructor'} =~ s/^([^,]*), ([^,]*)(.*)/$2 $1$3/;
368             my $email = get_faculty_email $row->{'instructor'};
369             $row->{'instructor'} = '"' . $row->{'instructor'} . '" <'. ($email || ($1 || "unknown") . "\@from.sctweb") . ">";
370             $row->{'duration'} =~ /^(\d\d\d\d)(\d\d)(\d\d)-\d{8}$/;
371             $row->{'begin'} =~ /^(\d\d):(\d\d)$/;
372             my $next = next_class(%$row);
373             my @date = Gmtime(Mktime($next->date,$1,$2,0));
374             $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];
375             $current .= "Subject: " . $row->{'title'} . "\n";
376             $current .= "From: " . $row->{'instructor'} . "\n";
377         }
378         #print "\n$current";
379         push @mhc, $current;
380     }
381     if(defined($file) && (-d $file)) {
382         my @lines;
383         foreach my $name (<$file/[1-9]*>) {
384             next unless $name =~ /^$file\/[1-9][0-9]*$/;
385             open FH, $name;
386             @lines = <FH>;
387             close FH;
388             foreach (@lines) {
389                 unlink $name if /^X-SC-Record-Id: <.*\@from.sctweb>/;
390             }
391         }
392         my $i=0;
393         foreach (@mhc) {
394             while(-f ++$i) {}
395             open FH, ">$file/$i" or die $!;
396             print FH $_;
397             close FH;
398         }
399     } else {
400         open(STDOUT, ">" . $file) if(defined($file));
401         print "# MHC school schedule\n# Autogenerated by sctweb ".localtime()."\n\n";
402         print join("\n", @mhc);
403     }
404 }
405
406 sub do_csv_schedule {
407     $| = 1;
408     my %days = (M => "Mon", T => "Tue", W => "Wed", R => "Thu", F => "Fri", S => "Sat", U => "SU");
409     my @mon = qw(Jan. Feb. Mar. Apr. May June July Aug. Sept. Oct. Nov. Dec.);
410     my (@terms, $file, $current, @mhc, @schedule);
411     $file = shift unless (!defined $_[0] or $_[0] =~ /^\d/);
412     @schedule = get_schedule(@_);
413     open(STDOUT, ">" . $file) if(defined($file));
414     foreach my $row (@schedule) {
415         map {s/\n/-/g if defined; $_} %$row;
416         my $id=generate_id($row->{'id'});
417         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
418         $row->{'days'} =~ s/^ //;
419         $row->{'instructor'} =~ s/^([^,]*), ([^,]*)/$2 $1/;
420         my $next = next_class(%$row);
421         $current = "";
422         #print "# $id\n";
423         $current .= $row->{'id'} . ",";
424         $current .= $row->{'title'} . ",";
425         $current .= '"' . $row->{'instructor'} . '",';
426         $next =~ /^(\d\d\d\d)(\d\d)(\d\d)$/;
427         $current .= $1 . "-". $2 ."-" . $3 . "\n";
428         print $current;
429     }
430 }
431
432 sub do_vcalendar_schedule {
433     $| = 1;
434     my %days = (M => "MO", T => "TU", W => "WE", R => "TH", F => "FR", S => "SA", U => "SU");
435     my $file = shift if (defined $_[0] and $_[0] !~ /^\d/);
436     my @schedule = get_schedule(@_);
437     open(STDOUT, ">>" . $file) if(defined($file) && (! -d $file));
438     open(STDOUT, ">/dev/null") if(defined($file) && (-d $file));
439     print "BEGIN:VCALENDAR\r\nVERSION:1.0\r\n";
440     foreach my $row (@schedule) {
441         map { s/\n/-/g; $_} %$row;
442         $row->{'instructor'} =~ s/^([^,]*), ([^,]*)/$2 $1/;
443         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
444         $row->{'days'} =~ s/^ //;
445         #$row->{'duration'} =~ s/(\d\d)-(\d\d)-(\d\d)/20$3$1$2/g;
446         my @day = (off_for_holidays(%$row),off_for_exams(%$row));
447         my $day = "";
448         if(exists($day[0])) {
449             $day = join(";", @day);
450             $day =~ s/\b(\d{8})\b/$1T000000/g;
451         }
452         my ($starttime, $stoptime)=($row->{'begin'}, $row->{'end'});
453         my ($startdate, $stopdate)=split(/-/, $row->{'duration'});
454         $starttime =~ s/://;
455         $stoptime =~ s/://;
456         if(defined($file) && (-d $file)) {
457             open FH, ">$file/" . $row->{'id'} . ".vcs" or die "$!";
458             select FH;
459             print "BEGIN:VCALENDAR\r\nVERSION:1.0\r\n";
460         }
461         print "BEGIN:VEVENT\r\n";
462         print "SUMMARY:", $row->{'title'}, "\r\n";
463         print "DESCRIPTION:", $row->{'id'}, "\r\n";
464         print "LOCATION:", $row->{'location'}, "\r\n";
465         print "CATEGORIES:Education\r\n";
466         print "DTSTART:", $startdate."T".$starttime, "00\r\n";
467         print "DTEND:", $startdate."T".$stoptime, "00\r\n";
468         print "RRULE:W1 ", $row->{'days'} . " $stopdate", "T000000\r\n";
469         print("EXDATE:$day\r\n") if($day);
470         print "ATTENDEE;ROLE=OWNER;STATUS=CONFIRMED:", $opts{'name'}, "\r\n" if(defined($opts{'name'}));
471         print "ATTENDEE;ROLE=ORGANIZER;STATUS=CONFIRMED:", $row->{'instructor'}, " <" . (get_faculty_email($row->{'instructor'}) || "fake\@ddress"), ">\r\n";
472         print "END:VEVENT\r\n";
473         if(defined($file) && (-d $file)) {
474             print "END:VCALENDAR\r\n";
475             close FH;
476             select STDOUT;
477         }
478     }
479     print "END:VCALENDAR\r\n";
480 }
481
482 sub do_xml_schedule {
483     my $file = shift if (defined $_[0] and $_[0] !~ /^\d/);
484     my ($output, $writer);
485     if($file) {
486         $output = new IO::File(">$file");
487         $writer = new XML::Writer(OUTPUT => $output, DATA_MODE => 1);
488     } else {
489         $writer = new XML::Writer(DATA_MODE => 1);
490     }
491     my @schedule = get_schedule(@_);
492     $writer->startTag("schedule");
493     foreach my $class (@schedule) {
494         $writer->startTag("class");
495         foreach my $key (sort keys %$class) {
496             $writer->dataElement($key, $class->{$key});
497         }
498         $writer->endTag("class");
499     }
500     $writer->endTag("schedule");
501     $writer->end();
502     close $output if $file;
503 }
504
505 sub do_html_schedule {
506     my @showheaders = ("Section ID/Title", "Instructor", "Days", "Time", "Duration", "Location");
507     my $shade = "dark";
508     my @schedule = get_schedule(@_);
509     print '<table id="schedule" cellpadding="3" cellspacing="0">'."\n<tr><th>";
510     print join("</th><th>",@showheaders);
511     print "</th></tr>\n";
512         foreach my $row (@schedule) {
513             map { s/\n/<br \/>/g; $_} %$row;
514             $row->{'duration'} =~ s/-/\n/g;
515             $row->{'duration'} =~ s/\d\d(\d\d)(\d\d)(\d\d)/$2-$3-$1/g;
516             print '<tr class="'.$shade.'">';
517             $shade = ($shade eq "dark"?"light":"dark");
518             print '<td class="idtitle">';
519             print '<span class="sectionid">' .$row->{'id'}. '</span><br />';
520             print '<span class="coursetitle">' .$row->{'title'}. '</span></td>';
521             my $instructor = $row->{'instructor'};
522             $instructor =~ s/^([^,]*), ([^,]*)(.*)/$2 $1$3/;
523             my $email = get_faculty_email($instructor);
524             #if($email) {
525                 #print '<td><a href="mailto:' . $email . '">'
526                 #. $row->{'instructor'} . "</a></td>";
527             # } else {
528                 print "<td>" . $row->{'instructor'} . "</td>";
529             #}
530             print "<td>" . $row->{'days'} . "</td>";
531             print "<td>" . $row->{'begin'}."-<wbr />".$row->{'end'} . "</td>";
532             print "<td>" . $row->{'duration'} . "</td>";
533             print "<td>" . $row->{'location'} . "</td>";
534             print "</tr>\n";
535         }
536     print "</table>\n";
537 }
538
539 sub do_html_grades {
540     my @readheaders = ("Section ID", "Course Title", "Grade", "Earned  Hours", "Quality  Hours", "Quality  Points", "GPA");
541     @readheaders = ("Section", "Course Title", "FinalGrade", "Earned Hours", "Quality Hours", "Quality Points", "GPA") if($opts{'school'} eq 'tamuk');
542     my @showheaders = ("Section ID", "Course Title", "Grade", "Earned<br />Hours", "Quality<br />Hours", "Quality<br />Points");
543     my ($row, $lastrow);
544     my $shade = "dark";
545     my $te = new HTML::TableExtract( headers => [ @readheaders ] );
546     my $response = $ua->get("$url&tserve_tip_write=||WID|SID|PIN|Term&tserve_trans_config=rgrdterm.cfg"); # Valid grading terms
547     die $response->status_line unless $response->is_success;
548     #my @terms = reverse grep {s/^<option value="([^"]*)">.*/$1/} (split( /\r\n/, $response->content));
549     my @terms = ();
550     my $year = Date::Calc->localtime->year;
551     for(my $y=$year-4;$y<=$year;$y++) { push @terms, ($y.2,$y."F",$y.3,$y.4,$y.1,$y."S"); }
552     foreach(@_ ? @_ : @terms) {
553         $response = $ua->get("$url&tserve_tip_write=||WID|SID|PIN|Term&tserve_trans_config=rgrades.cfg&Term=".($_) );
554         die $response->status_line unless $response->is_success;
555         $te->parse($response->content);
556     }
557     print '<table id="grades" cellpadding="3" cellspacing="0">'."\n<tr>";
558     print '<th align="left" class="sectionid">', $showheaders[0];
559     print '</th><th align="left" class="coursetitle">', $showheaders[1];
560     print '</th><th align="center" class="grade">';
561     print join('</th><th align="center" class="right-number">',@showheaders[2 .. 5]);
562     print "</th></tr>\n";
563     foreach my $ts ($te->table_states) {
564         foreach my $row ($ts->rows) {
565             map { s/^\s+//; s/\xa0|\r//g; s/\n/<br \/>/g; $_} @$row;
566             $row->[1] = capitalize($row->[1]);
567             $row->[1] =~ s/&/&amp;/g;
568             $row->[0] =~ s/Cumulative through/Cumulative: through/;
569             $row->[0] =~ s/Cumulative:(.*) (\d{4}) (.*)/Cumulative:$1 $3 $2/;
570             $lastrow=$row;
571             next if $row->[0] =~ /:|Current Term/;
572             print '<tr class="'.$shade.'">';
573             $shade = ($shade eq "dark"?"light":"dark");
574             print '<td align="left" class="sectionid">', $$row[0], '</td>';
575             print '<td align="left" class="coursetitle">', $$row[1], '</td>';
576             print '<td align="center" class="grade">';
577             #print join('</td><td>', @$row[0 .. 1]);
578             print join('</td><td align="right" class="right-number">', @$row[2 .. 5]);
579             print "</td></tr>\n";
580         }
581     }
582     print '<tr class="cumulative '.$shade.'"><td id="cumulative" colspan="2">', capitalize($lastrow->[0]);
583     #shift @$lastrow; shift @$lastrow;
584     print '</td><td align="center" id="gpa" class="grade">';
585     print $$lastrow[6];
586     print '</td><td align="right" class="right-number">';
587     print join('</td><td align="right" class="right-number">', @$lastrow[3 .. 5]);
588     print "</td></tr>\n";
589     print "</table>\n";
590 }
591
592 sub do_transcripts {
593     $response = $ua->get("$url&tserve_tip_write=||WID|SID|PIN&tserve_trans_config=rtranscr.cfg&CareerReqNum=1");
594     foreach (split /\n/, $response->content) {
595         next unless s/^\&nbsp;|<pre>// || s/\&nbsp;/ /;
596         s/<\/?([Hh]\d|[Bb])>//g;
597         next if /<\/td>/;
598         print "$_\n";
599     }
600 }
601
602 if ($arg eq "-s" || $arg eq "-h") {
603     do_html_schedule(@ARGV);
604 } elsif ($arg eq "-m") {
605     do_mhc_schedule(@ARGV);
606 } elsif ($arg eq "-c") {
607     do_csv_schedule(@ARGV);
608 } elsif ($arg eq "-v") {
609     do_vcalendar_schedule(@ARGV);
610 } elsif ($arg eq "-g") {
611     die "Grade support currently broken.\n";
612     do_html_grades(@ARGV);
613 } elsif ($arg eq "-t") {
614     die "Transcript support currently broken.\n";
615     do_transcripts;
616 } elsif ($arg eq "-x" || 1) {
617     do_xml_schedule(@ARGV);
618 }
619
620 $ua->get("${url}twbkwbis.P_Logout"); # Logout