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