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