Freakin' bugs
[tpope-extra.git] / perl / sct6
1 #!/usr/bin/perl -w
2 # $Id$
3 # -*- perl -*- vim: ft=perl sw=4 sts=4
4
5 # Brief usage instructions:
6 # Create a ~/.sct6rc that has SID=yourssn and PIN=yourpin
7 # You'll need to change the url below if you go anywhere but TAMUK.
8
9 use strict;
10 use Date::Calc::Object qw(Day_of_Week Decode_Day_of_Week Decode_Month Week_of_Year Monday_of_Week Day_of_Week_Abbreviation Delta_Days Add_Delta_Days Nth_Weekday_of_Month_Year Gmtime Mktime);
11 use Date::Calendar::Profiles qw($Profiles);
12 use Date::Calendar::Year;
13 use HTML::TableExtract;
14 use LWP::UserAgent;
15 use XML::Simple;
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 = @{$class{'off'}};
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     my %days = (M => "Mon", T => "Tue", W => "Wed", R => "Thu", F => "Fri", S => "Sat", U => "SU");
134     my $d = $class{'days'};
135     $d =~ s/([MTWRFS])/ $days{$1}/g;
136     $d =~ s/^ //;
137     $class{'duration'} =~ /(\d\d\d\d)(\d\d)(\d\d)-(\d\d\d\d)(\d\d)(\d\d)/;
138     my $days = Delta_Days($1,$2,$3,$4,$5,$6);
139     my $firstday = Date::Calc->new($1,$2,$3);
140     my $lastday = Date::Calc->new($4,$5,$6);
141     my $year = Date::Calendar::Year->new($1, $opts{'holidays'});
142     my @holidays=();
143     my @days=();
144     foreach(split(" ",$d)) {
145         $days[Decode_Day_of_Week($_)] = 1;
146     }
147     foreach ($year->search("")) {
148         my $good=1;
149         #foreach my $x ($year->labels($_)) {
150         #    $good=0 if ($x =~ /Veteran/ or $x =~ /President/);
151         #}
152         next unless ($year->is_full($_) && $_>=$firstday && $_<=$lastday);
153         push @holidays, $_
154             if (defined($days[Day_of_Week($_->date)]) && $good > 0);
155     }
156     return wantarray ? @holidays : "@holidays";
157 }
158
159 sub off_for_exams {
160     my %class = @_;
161     my $time = $class{'begin'} . "-" . $class{'end'};
162     $class{'duration'} =~ /\d{8}-(\d\d\d\d)(\d\d)(\d\d)/;
163     my $lastday = Date::Calc->new($1,$2,$3);
164     return wantarray ? () : undef unless (Day_of_Week($lastday->date) == 7);
165     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)";
166     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)";
167     my $days = join(" ",map {Decode_Day_of_Week($_)} split(/ /, $class{'days'}));
168     if($days eq "1 3") {
169         if($time =~ /$beginning/) {
170             return $lastday-4;
171         } elsif($time =~ /$ending/) {
172             return $lastday-6;
173         }
174     } elsif($days eq "2 4") {
175         if($time =~ /$beginning/) {
176             return $lastday-3;
177         } elsif($time =~ /$ending/) {
178             return $lastday-5;
179         }
180     } elsif($days eq "5") {
181         return $lastday-2;
182     }
183     return wantarray ? () : "";
184 }
185
186 sub capitalize {
187     local $_ = shift || "";
188     s/ +$//;
189     s/\b([A-Z])([A-Z]*)\b/$1\L$2/g;
190     s/\b(I)(i*)\b/$1\U$2/g;
191     s/\bUs\b/US/g;
192     s/ (And|For|Of|Or|The|To|With) / \l$1 /g;
193     s/\b(Mc)([a-z])/$1\u$2/g;
194     s/\b(Tcp\/Ip|Pc|Tba)\b/\U$&/g;
195     s/\bThru\b/Through/g;
196     s/\bAcct\b/Accounting/g;
197     s/\bAmer\b/American/g;
198     s/\bChem\b/Chemistry/g;
199     s/\bComp\b/Composition/g;
200     s/\bFed\b/Federal/g;
201     s/\bGen\b/General/g;
202     s/\bIntro\b/Introduction/g;
203     s/\bPrgm\b/Programming/g;
204     s/\bOp Sys\b/Operating System/g;
205     #s/\bGovt\b/Government/g;
206     s/\bLit\b/Literature/g;
207     s/\bPrin\b/Principles/g;
208     s/\bBus\b/Business/g;
209     s/\bSyst\b/Sys/g;
210     return $_;
211 }
212
213 sub get_schedule_terms {
214     my (@sterms, @a);
215     @a=('10','20','30','40');   # Fall, Spring, Summer I, Summer II
216                                 # Last 3 are currently guesses
217     my @localtime=localtime();
218     if ($localtime[4]<3) { # Through Mar 31
219         @sterms=((1900+$localtime[5]).$a[1]);
220     } elsif ($localtime[4]<5) { # Through May 31
221         @sterms=((1900+$localtime[5]).$a[1],(1900+$localtime[5]).$a[2]);
222     } elsif ($localtime[4]<7) { # through July 31
223         @sterms=((1900+$localtime[5]).$a[2],(1900+$localtime[5]).$a[3]);
224     } elsif ($localtime[4]<8) { # through Aug 31
225         @sterms=((1900+$localtime[5]).$a[3],(1901+$localtime[5]).$a[0]);
226     } elsif ($localtime[4]<10) { # through Oct 31
227         @sterms=((1901+$localtime[5]).$a[0]);
228     } else {
229         @sterms=((1901+$localtime[5]).$a[0],(1901+$localtime[5]).$a[1]);
230     }
231     return @sterms;
232 }
233
234 sub get_schedule {
235     my @readheaders = ("Type", "Time", "Days", "Where", "Date Range", "Schedule Type", "Instructors");
236     my @class;
237     my $te = new HTML::TableExtract( headers => [ @readheaders ] );
238     my (@schedule, @terms, $classid, $title, $begin, $end, $times, $days, $session);
239     @terms = get_schedule_terms();
240     foreach (@_ ? @_ : @terms) {
241         $response = $ua->get("${url}bwskfshd.P_CrseSchdDetl?term_in=$_" );
242         die $response->status_line unless $response->is_success;
243         $te->parse($response->content);
244         foreach my $l (split (/\n/, $response->content)) {
245             next unless $l =~ s/.*<CAPTION class=[^>]*>(.* - .... \d\d\d\d \d\d\d)<\/caption>.*/$1/i;
246             push @class, $l;
247         }
248     }
249     foreach my $ts ($te->table_states) {
250         foreach my $row ($ts->rows) {
251             #map { s/\xa0//g; $_} @$row;
252             #$row->[0] =~ s/.*launchWebCT\("([^"]*)"\).*/$1/s;
253             #$row->[0] =~ s/(.*) ?<[Bb][Rr][^>]*>(.*)/capitalize($2)/eg;
254             $classid = (shift @class);
255             $title = $classid;
256             $classid =~ s/.* - //;
257             $classid =~ s/ /-/g;
258             $title =~ s/ - .*//;
259             $row->[6] =~ s/\b([A-Z]r?)$/$1./;
260             $row->[6] = capitalize($row->[6]);
261             $row->[6] =~ s/ *\([A-Z]\)//;
262             $row->[1] =~ s/ ?([ap])m/\u$1M/g;
263             $row->[1] =~ s/ - /-/;
264             ($begin, $end) = split(/ ?- ?/, $row->[1]);
265             $begin =~ s/^(\d):/0$1:/;
266             $end =~ s/^(\d):/0$1:/;
267             if (($begin=~/PM$/ && $begin!~/^12/)||($begin=~/^12:..AM/)) {
268                 $begin =~ s/^(\d?\d)/($1+12)%24/e;
269             }
270             if (($end=~/PM$/ && $end!~/^12/)||($end=~/^12:..AM/)) {
271                 $end =~ s/^(\d?\d)/($1+12)%24/e;
272             }
273             $begin =~ s/ ?[AP]M//;
274             $end =~ s/ ?[AP]M//;
275             $row->[4] =~ s/([A-Za-z]{3,9})/(Decode_Month($1)<10?"0":"").Decode_Month($1)/eg;
276             $row->[4] =~ s/(\d\d?) (\d\d), (\d\d\d\d)/$3$1$2/g;
277             $row->[4] =~ s/ - /-/;
278             $row->[3] =~ s/(ON|MAIN) CAMPUS\n|Palo Alto Building \d* //ig;
279             $row->[3] =~ s/\n/ /g;
280             my %class = (
281                 id => $classid,
282                 title => capitalize($title),
283                 instructor => $row->[6],
284                 days => $row->[2],
285                 #'time' => $row->[1],
286                 begin => $begin,
287                 end => $end || undef,
288                 duration => $row->[4],
289                 location => $row->[3],
290             );
291             my @off = ( map { "$_"; } (off_for_holidays(%class), off_for_exams(%class)));
292             $class{'off'} = [ @off ] if (@off);
293             push @schedule, \%class;
294         }
295     }
296     return @schedule;
297 }
298
299 sub get_faculty_email {
300     my ($name, $school, $email);
301     if((-f $ENV{'HOME'} . "/public_html/faculty.csv") && ! %faculty) {
302         open INS, $ENV{'HOME'} . "/public_html/faculty.csv";
303         while($_ = <INS>) {
304             chomp;
305             m/"([^"]*)",([^,]*),([^,]*)/; # "
306             ($name, $email, $school) = ($1, $2, $3);
307             #$name =~ s/^([^,]*), ([^,]*)(.*)$/$2 $1$3/;
308             $name =~ s/ [A-Z]\.//g;
309             $name = lc $name;
310             $name =~ s/\W//g;
311             $faculty{$name} = $email;
312         }
313     }
314     $name = shift;
315     $name =~ s/ [A-Z]r?\.//g;
316     $name = lc $name;
317     $name =~ s/\W//g;
318     return $faculty{$name};
319 }
320
321 sub get_mhc_header {
322 return (
323 "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",
324 "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",
325 "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",
326 "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",
327 "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",
328 "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",
329 "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",
330 "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",
331 "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",
332 "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",
333 );
334 }
335
336 sub do_xml_schedule {
337     my $file = shift if (defined $_[0] and $_[0] !~ /^\d/);
338     my $schedule = { class => [ get_schedule(@_) ] };
339     my $xml = XMLout($schedule, NoAttr => 1, RootName => 'schedule');
340     if($file) {
341         open FH, ">$file";
342         print FH $xml;
343         close FH;
344     } else {
345         print $xml;
346     }
347 }
348
349 sub do_html_schedule {
350     my @showheaders = ("Section ID/Title", "Instructor", "Days", "Time", "Duration", "Location");
351     my $shade = "dark";
352     my @schedule = get_schedule(@_);
353     print '<table id="schedule" cellpadding="3" cellspacing="0">'."\n<tr><th>";
354     print join("</th><th>",@showheaders);
355     print "</th></tr>\n";
356         foreach my $row (@schedule) {
357             map { s/\n/<br \/>/g; $_} %$row;
358             $row->{'duration'} =~ s/-/<br \/>/g;
359             $row->{'duration'} =~ s/\d\d(\d\d)(\d\d)(\d\d)/$2-$3-$1/g;
360             print '<tr class="'.$shade.'">';
361             $shade = ($shade eq "dark"?"light":"dark");
362             print '<td class="idtitle">';
363             print '<span class="sectionid">' .$row->{'id'}. '</span><br />';
364             print '<span class="coursetitle">' .$row->{'title'}. '</span></td>';
365             my $instructor = $row->{'instructor'};
366             #$instructor =~ s/^([^,]*), ([^,]*)(.*)/$2 $1$3/;
367             my $email = get_faculty_email($instructor);
368             #if($email) {
369                 #print '<td><a href="mailto:' . $email . '">'
370                 #. $row->{'instructor'} . "</a></td>";
371             # } else {
372                 print "<td>" . $row->{'instructor'} . "</td>";
373             #}
374             print "<td>" . $row->{'days'} . "</td>";
375             print "<td>" . $row->{'begin'}."-<wbr />".$row->{'end'} . "</td>";
376             print "<td>" . $row->{'duration'} . "</td>";
377             print "<td>" . $row->{'location'} . "</td>";
378             print "</tr>\n";
379         }
380     print "</table>\n";
381 }
382
383 sub do_html_grades {
384     my @readheaders = ("Section ID", "Course Title", "Grade", "Earned  Hours", "Quality  Hours", "Quality  Points", "GPA");
385     @readheaders = ("Section", "Course Title", "FinalGrade", "Earned Hours", "Quality Hours", "Quality Points", "GPA") if($opts{'school'} eq 'tamuk');
386     my @showheaders = ("Section ID", "Course Title", "Grade", "Earned<br />Hours", "Quality<br />Hours", "Quality<br />Points");
387     my ($row, $lastrow);
388     my $shade = "dark";
389     my $te = new HTML::TableExtract( headers => [ @readheaders ] );
390     my $response = $ua->get("$url&tserve_tip_write=||WID|SID|PIN|Term&tserve_trans_config=rgrdterm.cfg"); # Valid grading terms
391     die $response->status_line unless $response->is_success;
392     #my @terms = reverse grep {s/^<option value="([^"]*)">.*/$1/} (split( /\r\n/, $response->content));
393     my @terms = ();
394     my $year = Date::Calc->localtime->year;
395     for(my $y=$year-4;$y<=$year;$y++) { push @terms, ($y.2,$y."F",$y.3,$y.4,$y.1,$y."S"); }
396     foreach(@_ ? @_ : @terms) {
397         $response = $ua->get("$url&tserve_tip_write=||WID|SID|PIN|Term&tserve_trans_config=rgrades.cfg&Term=".($_) );
398         die $response->status_line unless $response->is_success;
399         $te->parse($response->content);
400     }
401     print '<table id="grades" cellpadding="3" cellspacing="0">'."\n<tr>";
402     print '<th align="left" class="sectionid">', $showheaders[0];
403     print '</th><th align="left" class="coursetitle">', $showheaders[1];
404     print '</th><th align="center" class="grade">';
405     print join('</th><th align="center" class="right-number">',@showheaders[2 .. 5]);
406     print "</th></tr>\n";
407     foreach my $ts ($te->table_states) {
408         foreach my $row ($ts->rows) {
409             map { s/^\s+//; s/\xa0|\r//g; s/\n/<br \/>/g; $_} @$row;
410             $row->[1] = capitalize($row->[1]);
411             $row->[1] =~ s/&/&amp;/g;
412             $row->[0] =~ s/Cumulative through/Cumulative: through/;
413             $row->[0] =~ s/Cumulative:(.*) (\d{4}) (.*)/Cumulative:$1 $3 $2/;
414             $lastrow=$row;
415             next if $row->[0] =~ /:|Current Term/;
416             print '<tr class="'.$shade.'">';
417             $shade = ($shade eq "dark"?"light":"dark");
418             print '<td align="left" class="sectionid">', $$row[0], '</td>';
419             print '<td align="left" class="coursetitle">', $$row[1], '</td>';
420             print '<td align="center" class="grade">';
421             #print join('</td><td>', @$row[0 .. 1]);
422             print join('</td><td align="right" class="right-number">', @$row[2 .. 5]);
423             print "</td></tr>\n";
424         }
425     }
426     print '<tr class="cumulative '.$shade.'"><td id="cumulative" colspan="2">', capitalize($lastrow->[0]);
427     #shift @$lastrow; shift @$lastrow;
428     print '</td><td align="center" id="gpa" class="grade">';
429     print $$lastrow[6];
430     print '</td><td align="right" class="right-number">';
431     print join('</td><td align="right" class="right-number">', @$lastrow[3 .. 5]);
432     print "</td></tr>\n";
433     print "</table>\n";
434 }
435
436 sub do_transcripts {
437     $response = $ua->get("$url&tserve_tip_write=||WID|SID|PIN&tserve_trans_config=rtranscr.cfg&CareerReqNum=1");
438     foreach (split /\n/, $response->content) {
439         next unless s/^\&nbsp;|<pre>// || s/\&nbsp;/ /;
440         s/<\/?([Hh]\d|[Bb])>//g;
441         next if /<\/td>/;
442         print "$_\n";
443     }
444 }
445
446 if ($arg eq "-s" || $arg eq "-h") {
447     do_html_schedule(@ARGV);
448 } elsif ($arg eq "-m") {
449     do_mhc_schedule(@ARGV);
450 } elsif ($arg eq "-c") {
451     do_csv_schedule(@ARGV);
452 } elsif ($arg eq "-v") {
453     do_vcalendar_schedule(@ARGV);
454 } elsif ($arg eq "-g") {
455     die "Grade support currently broken.\n";
456     do_html_grades(@ARGV);
457 } elsif ($arg eq "-t") {
458     die "Transcript support currently broken.\n";
459     do_transcripts;
460 } elsif ($arg eq "-x" || 1) {
461     do_xml_schedule(@ARGV);
462 }
463
464 $ua->get("${url}twbkwbis.P_Logout"); # Logout