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