Last name first business
[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             $row->[2] =~ s/^([^,]*), ([^,.]*|[^,]{4,})/$2 $1/;
265             ($begin, $end) = split("-", $row->[7]);
266             if($row->[7] =~ /^(\d\d):\d\d-(\d\d):\d\dPM$/) {
267                 if($1 < $2 && $2 != 12) {
268                     $begin =~ s/^(\d\d)/$1+12/e;
269                 }
270                 if($2 != 12) {
271                     $end =~ s/^(\d\d)/$1+12/e;
272                 }
273                 $end =~ s/PM$//;
274             } else { $end =~ s/AM$//; }
275             $row->[8] =~ s/(\d\d)-(\d\d)-(\d\d)/20$3$1$2/g;
276             $row->[9] =~ s/(ON|MAIN) CAMPUS\n//ig;
277             $row->[9] =~ s/\n/ /g;
278             push @schedule, {
279                 id => $classid,
280                 title => $row->[0],
281                 #session => $row->[1],
282                 instructor => $row->[2],
283                 credits => $row->[3],
284                 crn => $row->[4],
285                 #gradetype => $row->[5],
286                 days => $row->[6],
287                 #'time' => $row->[7],
288                 begin => $begin,
289                 end => $end || undef,
290                 duration => $row->[8],
291                 location => $row->[9],
292                 #message => $row->[10],
293             };
294         }
295     }
296     foreach my $ts ($tf->table_states) {
297         foreach my $row ($ts->rows) {
298             next if ($row->[0] =~ /Total Enrolled Hours/);
299             $row->[1] =~ s/\xa0/ /g;
300             map { s/\xa0//g; $_} @$row;
301             map { s/^\r?\n? *//g; $_} @$row;
302             $row->[0] =~ s/.*launchWebCT\("([^"]*)"[^)]*\).*>\s*//s;
303             $classid=$1;
304             $row->[0] =~ s/(.*)/capitalize($1)/eg;
305             $row->[1] =~ s/^([MTWRFS]*) *([0-9:-]*[AP]M)\s*//;
306             ($days, $times) = ($1, $2);
307             ($begin, $end) = split("-", $times);
308             if($times =~ /^(\d\d):\d\d-(\d\d):\d\dPM$/) {
309                 if($1 < $2 && $2 != 12) {
310                     $begin =~ s/^(\d\d)/$1+12/e;
311                 }
312                 if($2 != 12) {
313                     $end =~ s/^(\d\d)/$1+12/e;
314                 }
315                 $end =~ s/PM$//;
316             } else { $end =~ s/AM$//; }
317             $row->[2] =~ s/(.*\S)\s*//;
318             $session = $1;
319             $row->[2] =~ s/(\d\d)-(\d\d)-(\d\d)/20$3$1$2/g;
320             $row->[2] =~ s/ *to */-/g;
321             $row->[3] = capitalize($row->[3]);
322             $row->[3] =~ s/([A-Z]r?)$/$1./;
323             $row->[3] =~ s/^([^,]*), ([^,.]{3}[^,]*)/$2 $1/;
324             push @schedule, {
325                 id => $classid,
326                 title => $row->[0],
327                 #session => $session,
328                 instructor => $row->[3],
329                 credits => $row->[4],
330                 crn => $row->[5],
331                 #gradetype => $row->[6],
332                 days => $days,
333                 #'time' => $times,
334                 begin => $begin,
335                 end => $end || undef,
336                 duration => $row->[2],
337                 location => $row->[1],
338                 #message => $row->[7],
339             };
340         }
341     }
342     return @schedule;
343 }
344
345 sub get_faculty_email {
346     my ($name, $school, $email);
347     if((-f $ENV{'HOME'} . "/public_html/faculty.csv") && ! %faculty) {
348         open INS, $ENV{'HOME'} . "/public_html/faculty.csv";
349         while($_ = <INS>) {
350             chomp;
351             m/"([^"]*)",([^,]*),([^,]*)/; # "
352             ($name, $email, $school) = ($1, $2, $3);
353             #$name =~ s/^([^,]*), ([^,]*)(.*)$/$2 $1$3/;
354             $name =~ s/ [A-Z]\.//g;
355             $name = lc $name;
356             $name =~ s/\W//g;
357             $faculty{$name} = $email;
358         }
359     }
360     $name = shift;
361     $name =~ s/ [A-Z]r?\.//g;
362     $name = lc $name;
363     $name =~ s/\W//g;
364     return $faculty{$name};
365 }
366
367 sub get_mhc_header {
368 return (
369 "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",
370 "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",
371 "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",
372 "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",
373 "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",
374 "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",
375 "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",
376 "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",
377 "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",
378 "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",
379 );
380 }
381
382 sub do_mhc_schedule {
383     $| = 1;
384     my %days = (M => "Mon", T => "Tue", W => "Wed", R => "Thu", F => "Fri", S => "Sat", U => "SU");
385     my @mon = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
386     my ($file, $current, @mhc, @schedule);
387     $file = shift unless (!defined $_[0] or $_[0] =~ /^\d/);
388     @schedule = get_schedule(@_);
389     @mhc = get_mhc_header;
390     if(defined($file) && (-d $file)) {
391         my @mhc2;
392         foreach (@mhc) {
393             $_ =~ s/X-SC-Subject: ([^\n]*)/X-SC-Subject: $1\nSubject: $1/;
394             $_ =~ s/X-SC-Category: ([^\n]*)/X-SC-Category: $1\nFrom: $1/;
395             $_ =~ 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;
396             push @mhc2, $_;
397         }
398         @mhc = @mhc2;
399     }
400     foreach my $row (@schedule) {
401         map {s/\n/-/g if defined; $_} %$row;
402         my $id=generate_id($row->{'id'});
403         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
404         $row->{'days'} =~ s/^ //;
405         #$row->{'duration'} =~ s/(\d\d)-(\d\d)-(\d\d)/20$3$1$2/g;
406         my @day = map { "!" . $_ } (off_for_holidays(%$row),off_for_exams(%$row));
407         $current = "";
408         #print "# $id\n";
409         $current .= "X-SC-Subject: " . $row->{'title'} . "\n";
410         $current .= "X-SC-Location: " . $row->{'location'} . "\n";
411         $current .= "X-SC-Category: School\n";
412         $current .= "X-SC-Cond: " . $row->{'days'} . "\n";
413         $current .= "X-SC-Time: ".$row->{'begin'}."-".$row->{'end'}."\n";
414         $current .= "X-SC-Duration: " . $row->{'duration'} . "\n";
415         $current .= "X-SC-Day: @day\n" if(exists $day[0]);
416         $current .= "X-SC-Alarm: 15 minutes\n";
417         $current .= "X-SC-Record-Id: <".$row->{'id'}."\@from.sctweb>\n";
418         if(defined($file) && (-d $file)) {
419             #$row->{'instructor'} =~ s/^([^,]*), ([^,]*)(.*)/$2 $1$3/;
420             my $email = get_faculty_email $row->{'instructor'};
421             $row->{'instructor'} = '"' . $row->{'instructor'} . '" <'. ($email || ($1 || "unknown") . "\@from.sctweb") . ">";
422             $row->{'duration'} =~ /^(\d\d\d\d)(\d\d)(\d\d)-\d{8}$/;
423             $row->{'begin'} =~ /^(\d\d):(\d\d)$/;
424             my $next = next_class(%$row);
425             my @date = Gmtime(Mktime($next->date,$1,$2,0));
426             $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];
427             $current .= "Subject: " . $row->{'title'} . "\n";
428             $current .= "From: " . $row->{'instructor'} . "\n";
429         }
430         #print "\n$current";
431         push @mhc, $current;
432     }
433     if(defined($file) && (-d $file)) {
434         my @lines;
435         foreach my $name (<$file/[1-9]*>) {
436             next unless $name =~ /^$file\/[1-9][0-9]*$/;
437             open FH, $name;
438             @lines = <FH>;
439             close FH;
440             foreach (@lines) {
441                 unlink $name if /^X-SC-Record-Id: <.*\@from.sctweb>/;
442             }
443         }
444         my $i=0;
445         foreach (@mhc) {
446             while(-f ++$i) {}
447             open FH, ">$file/$i" or die $!;
448             print FH $_;
449             close FH;
450         }
451     } else {
452         open(STDOUT, ">" . $file) if(defined($file));
453         print "# MHC school schedule\n# Autogenerated by sctweb ".localtime()."\n\n";
454         print join("\n", @mhc);
455     }
456 }
457
458 sub do_csv_schedule {
459     $| = 1;
460     my %days = (M => "Mon", T => "Tue", W => "Wed", R => "Thu", F => "Fri", S => "Sat", U => "SU");
461     my @mon = qw(Jan. Feb. Mar. Apr. May June July Aug. Sept. Oct. Nov. Dec.);
462     my (@terms, $file, $current, @mhc, @schedule);
463     $file = shift unless (!defined $_[0] or $_[0] =~ /^\d/);
464     @schedule = get_schedule(@_);
465     open(STDOUT, ">" . $file) if(defined($file));
466     foreach my $row (@schedule) {
467         map {s/\n/-/g if defined; $_} %$row;
468         my $id=generate_id($row->{'id'});
469         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
470         $row->{'days'} =~ s/^ //;
471         #$row->{'instructor'} =~ s/^([^,]*), ([^,])/$2 $1/;
472         my $next = next_class(%$row);
473         $current = "";
474         #print "# $id\n";
475         $current .= $row->{'id'} . ",";
476         $current .= $row->{'title'} . ",";
477         $current .= '"' . $row->{'instructor'} . '",';
478         $next =~ /^(\d\d\d\d)(\d\d)(\d\d)$/;
479         $current .= $1 . "-". $2 ."-" . $3 . "\n";
480         print $current;
481     }
482 }
483
484 sub do_vcalendar_schedule {
485     $| = 1;
486     my %days = (M => "MO", T => "TU", W => "WE", R => "TH", F => "FR", S => "SA", U => "SU");
487     my $file = shift if (defined $_[0] and $_[0] !~ /^\d/);
488     my @schedule = get_schedule(@_);
489     open(STDOUT, ">>" . $file) if(defined($file) && (! -d $file));
490     open(STDOUT, ">/dev/null") if(defined($file) && (-d $file));
491     print "BEGIN:VCALENDAR\r\nVERSION:1.0\r\n";
492     foreach my $row (@schedule) {
493         map { s/\n/-/g; $_} %$row;
494         #$row->{'instructor'} =~ s/^([^,]*), ([^,]*)/$2 $1/;
495         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
496         $row->{'days'} =~ s/^ //;
497         #$row->{'duration'} =~ s/(\d\d)-(\d\d)-(\d\d)/20$3$1$2/g;
498         my @day = (off_for_holidays(%$row),off_for_exams(%$row));
499         my $day = "";
500         if(exists($day[0])) {
501             $day = join(";", @day);
502             $day =~ s/\b(\d{8})\b/$1T000000/g;
503         }
504         my ($starttime, $stoptime)=($row->{'begin'}, $row->{'end'});
505         my ($startdate, $stopdate)=split(/-/, $row->{'duration'});
506         $starttime =~ s/://;
507         $stoptime =~ s/://;
508         if(defined($file) && (-d $file)) {
509             open FH, ">$file/" . $row->{'id'} . ".vcs" or die "$!";
510             select FH;
511             print "BEGIN:VCALENDAR\r\nVERSION:1.0\r\n";
512         }
513         print "BEGIN:VEVENT\r\n";
514         print "SUMMARY:", $row->{'title'}, "\r\n";
515         print "DESCRIPTION:", $row->{'id'}, "\r\n";
516         print "LOCATION:", $row->{'location'}, "\r\n";
517         print "CATEGORIES:Education\r\n";
518         print "DTSTART:", $startdate."T".$starttime, "00\r\n";
519         print "DTEND:", $startdate."T".$stoptime, "00\r\n";
520         print "RRULE:W1 ", $row->{'days'} . " $stopdate", "T000000\r\n";
521         print("EXDATE:$day\r\n") if($day);
522         print "ATTENDEE;ROLE=OWNER;STATUS=CONFIRMED:", $opts{'name'}, "\r\n" if(defined($opts{'name'}));
523         print "ATTENDEE;ROLE=ORGANIZER;STATUS=CONFIRMED:", $row->{'instructor'}, " <" . (get_faculty_email($row->{'instructor'}) || "fake\@ddress"), ">\r\n";
524         print "END:VEVENT\r\n";
525         if(defined($file) && (-d $file)) {
526             print "END:VCALENDAR\r\n";
527             close FH;
528             select STDOUT;
529         }
530     }
531     print "END:VCALENDAR\r\n";
532 }
533
534 sub do_xml_schedule {
535     my $file = shift if (defined $_[0] and $_[0] !~ /^\d/);
536     my ($output, $writer);
537     if($file) {
538         $output = new IO::File(">$file");
539         $writer = new XML::Writer(OUTPUT => $output, DATA_MODE => 1);
540     } else {
541         $writer = new XML::Writer(DATA_MODE => 1);
542     }
543     my @schedule = get_schedule(@_);
544     $writer->startTag("schedule");
545     foreach my $class (@schedule) {
546         $writer->startTag("class");
547         foreach my $key (sort keys %$class) {
548             $writer->dataElement($key, $class->{$key});
549         }
550         $writer->endTag("class");
551     }
552     $writer->endTag("schedule");
553     $writer->end();
554     close $output if $file;
555 }
556
557 sub do_html_schedule {
558     my @showheaders = ("Section ID/Title", "Instructor", "Days", "Time", "Duration", "Location");
559     my $shade = "dark";
560     my @schedule = get_schedule(@_);
561     print '<table id="schedule" cellpadding="3" cellspacing="0">'."\n<tr><th>";
562     print join("</th><th>",@showheaders);
563     print "</th></tr>\n";
564         foreach my $row (@schedule) {
565             map { s/\n/<br \/>/g; $_} %$row;
566             #$row->{'time'} =~ s/-/-<wbr \/>/;
567             $row->{'duration'} =~ s/-/<br \/>/;
568             $row->{'duration'} =~ s/\d\d(\d\d)(\d\d)(\d\d)/$2-$3-$1/g;
569             print '<tr class="'.$shade.'">';
570             $shade = ($shade eq "dark"?"light":"dark");
571             print '<td class="idtitle">';
572             print '<span class="sectionid">' .$row->{'id'}. '</span><br />';
573             print '<span class="coursetitle">' .$row->{'title'}. '</span></td>';
574             my $instructor = $row->{'instructor'};
575             #$instructor =~ s/^([^,]*), ([^,]*)(.*)/$2 $1$3/;
576             my $email = get_faculty_email($instructor);
577             #if($email) {
578                 #print '<td><a href="mailto:' . $email . '">'
579                 #. $row->{'instructor'} . "</a></td>";
580             # } else {
581                 print "<td>" . $row->{'instructor'} . "</td>";
582             #}
583             print "<td>" . $row->{'days'} . "</td>";
584             print "<td>" . $row->{'begin'}."-<wbr />".$row->{'end'} . "</td>";
585             print "<td>" . $row->{'duration'} . "</td>";
586             print "<td>" . $row->{'location'} . "</td>";
587             print "</tr>\n";
588         }
589     print "</table>\n";
590 }
591
592 sub do_html_grades {
593     my @readheaders = ("Section ID", "Course Title", "Grade", "Earned  Hours", "Quality  Hours", "Quality  Points", "GPA");
594     @readheaders = ("Section", "Course Title", "FinalGrade", "Earned Hours", "Quality Hours", "Quality Points", "GPA") if($opts{'school'} eq 'tamuk');
595     my @showheaders = ("Section ID", "Course Title", "Grade", "Earned<br />Hours", "Quality<br />Hours", "Quality<br />Points");
596     my ($row, $lastrow);
597     my $shade = "dark";
598     my $te = new HTML::TableExtract( headers => [ @readheaders ] );
599     my $response = $ua->get("$url&tserve_tip_write=||WID|SID|PIN|Term&tserve_trans_config=rgrdterm.cfg"); # Valid grading terms
600     die $response->status_line unless $response->is_success;
601     #my @terms = reverse grep {s/^<option value="([^"]*)">.*/$1/} (split( /\r\n/, $response->content));
602     my @terms = ();
603     my $year = Date::Calc->localtime->year;
604     for(my $y=$year-4;$y<=$year;$y++) { push @terms, ($y.2,$y."F",$y.3,$y.4,$y.1,$y."S"); }
605     foreach(@_ ? @_ : @terms) {
606         $response = $ua->get("$url&tserve_tip_write=||WID|SID|PIN|Term&tserve_trans_config=rgrades.cfg&Term=".($_) );
607         die $response->status_line unless $response->is_success;
608         $te->parse($response->content);
609     }
610     print '<table id="grades" cellpadding="3" cellspacing="0">'."\n<tr>";
611     print '<th align="left" class="sectionid">', $showheaders[0];
612     print '</th><th align="left" class="coursetitle">', $showheaders[1];
613     print '</th><th align="center" class="grade">';
614     print join('</th><th align="center" class="right-number">',@showheaders[2 .. 5]);
615     print "</th></tr>\n";
616     foreach my $ts ($te->table_states) {
617         foreach my $row ($ts->rows) {
618             map { s/^\s+//; s/\xa0|\r//g; s/\n/<br \/>/g; $_} @$row;
619             $row->[1] = capitalize($row->[1]);
620             $row->[1] =~ s/&/&amp;/g;
621             $row->[0] =~ s/Cumulative through/Cumulative: through/;
622             $row->[0] =~ s/Cumulative:(.*) (\d{4}) (.*)/Cumulative:$1 $3 $2/;
623             $lastrow=$row;
624             next if $row->[0] =~ /:|Current Term/;
625             print '<tr class="'.$shade.'">';
626             $shade = ($shade eq "dark"?"light":"dark");
627             print '<td align="left" class="sectionid">', $$row[0], '</td>';
628             print '<td align="left" class="coursetitle">', $$row[1], '</td>';
629             print '<td align="center" class="grade">';
630             #print join('</td><td>', @$row[0 .. 1]);
631             print join('</td><td align="right" class="right-number">', @$row[2 .. 5]);
632             print "</td></tr>\n";
633         }
634     }
635     print '<tr class="cumulative '.$shade.'"><td id="cumulative" colspan="2">', capitalize($lastrow->[0]);
636     #shift @$lastrow; shift @$lastrow;
637     print '</td><td align="center" id="gpa" class="grade">';
638     print $$lastrow[6];
639     print '</td><td align="right" class="right-number">';
640     print join('</td><td align="right" class="right-number">', @$lastrow[3 .. 5]);
641     print "</td></tr>\n";
642     print "</table>\n";
643 }
644
645 sub do_faculty {
646     my @readheaders = ("Name", "College", "Email");
647     my $te = new HTML::TableExtract( headers => [ @readheaders ] );
648     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)) {
649         my $response = $ua->get("http://$domain/fs/".$_."dir.htm");
650         die $response->status_line unless $response->is_success;
651         $te->parse($response->content);
652     }
653     foreach my $ts ($te->table_states) {
654         foreach my $row ($ts->rows) {
655             map { s/[\r\n]//g; $_} @$row;
656             $row->[0] = capitalize($row->[0]);
657             $row->[0] =~ s/([A-Z]r?)$/$1./;
658             print '"'.$row->[0].'",',$row->[2].',', $row->[1], "\n";
659         }
660     }
661 }
662
663 sub do_transcripts {
664     $response = $ua->get("$url&tserve_tip_write=||WID|SID|PIN&tserve_trans_config=rtranscr.cfg&CareerReqNum=1");
665     foreach (split /\n/, $response->content) {
666         next unless s/^\&nbsp;|<pre>// || s/\&nbsp;/ /;
667         s/<\/?([Hh]\d|[Bb])>//g;
668         next if /<\/td>/;
669         print "$_\n";
670     }
671 }
672
673 if ($arg eq "-s" || $arg eq "-h") {
674     do_html_schedule(@ARGV);
675 } elsif ($arg eq "-m") {
676     do_mhc_schedule(@ARGV);
677 } elsif ($arg eq "-c") {
678     do_csv_schedule(@ARGV);
679 } elsif ($arg eq "-v") {
680     do_vcalendar_schedule(@ARGV);
681 } elsif ($arg eq "-g") {
682     do_html_grades(@ARGV);
683 } elsif ($arg eq "-t") {
684     do_transcripts;
685 } elsif ($arg eq "-f") {
686     do_faculty;
687 } elsif ($arg eq "-x" || 1) {
688     do_xml_schedule(@ARGV);
689 }
690
691 $ua->get("$url&tserve_trans_config=alogout.cfg"); # Logout