--- rat/lonpage.pm	2000/10/31 19:31:42	1.15
+++ rat/lonpage.pm	2003/02/03 18:03:53	1.48
@@ -1,19 +1,53 @@
 # The LearningOnline Network with CAPA
 # Page Handler
 #
+# $Id: lonpage.pm,v 1.48 2003/02/03 18:03:53 harris41 Exp $
+#
+# Copyright Michigan State University Board of Trustees
+#
+# This file is part of the LearningOnline Network with CAPA (LON-CAPA).
+#
+# LON-CAPA is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# LON-CAPA is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with LON-CAPA; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# /home/httpd/html/adm/gpl.txt
+#
+# http://www.lon-capa.org/
+#
 # (TeX Content Handler
 #
+# YEAR=2000
 # 05/29/00,05/30 Gerd Kortemeyer)
 # 08/30,08/31,09/06,09/14,09/15,09/16,09/19,09/20,09/21,09/23,
-# 10/02,10/10,10/14,10/16,10/18,10/19,10/31 Gerd Kortemeyer
+# 10/02,10/10,10/14,10/16,10/18,10/19,10/31,11/6,11/14,11/16,
+# YEAR=2001
+# 08/13/01,08/30,10/1 Gerd Kortemeyer
+# YEAR=2002
+# 03/19 Gerd Kortemeyer
+#
+###
 
 package Apache::lonpage;
 
 use strict;
 use Apache::Constants qw(:common :http);
 use Apache::lonnet();
+use Apache::loncommon();
+use Apache::lonxml();
 use HTML::TokeParser;
 use GDBM_File;
+use Apache::lonsequence;
 
 # -------------------------------------------------------------- Module Globals
 my %hash;
@@ -76,7 +110,7 @@ sub tracetable {
        if (defined($hash{'to_'.$rid})) {
 	  my $mincond=1;
           my $next='';
-          map {
+          foreach (split(/\,/,$hash{'to_'.$rid})) {
               my $thiscond=
       &Apache::lonnet::directcondval($hash{'condid_'.$hash{'undercond_'.$_}});
               if ($thiscond>=$mincond) {
@@ -87,14 +121,14 @@ sub tracetable {
 		  }
                   if ($thiscond>$mincond) { $mincond=$thiscond; }
 	      }
-          } split(/\,/,$hash{'to_'.$rid});
-          map {
+          }
+          foreach (split(/\,/,$next)) {
               my ($linkid,$condval)=split(/\:/,$_);
               if ($condval>=$mincond) {
                 my $now=&tracetable($sofar,$hash{'goesto_'.$linkid},$beenhere);
                 if ($now>$further) { $further=$now; }
 	      }
-          } split(/\,/,$next);
+          }
 
        }
     }
@@ -112,18 +146,22 @@ sub handler {
        if ($ENV{'browser.mathml'}) {
            $r->content_type('text/xml');
        } else {
-           $r->content_type('text/html');
+           $r->content_type('text/html'); 
        }
        $r->send_http_header;
        return OK;
    }
-
-  my $requrl=$r->uri;
+  
+   &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
+                                          ['forceselect','launch']);
+  my $number_of_columns = 1;
+  my $requrl=$r->uri;  
+  my $target = $ENV{'form.grade_target'};
 # ----------------------------------------------------------------- Tie db file
-  if ($ENV{'request.course.fn'}) {
+  if (($ENV{'request.course.fn'}) && (!$ENV{'form.forceselect'})) {
       my $fn=$ENV{'request.course.fn'};
       if (-e "$fn.db") {
-          if (tie(%hash,'GDBM_File',"$fn.db",&GDBM_READER,0640)) {
+          if (tie(%hash,'GDBM_File',"$fn.db",&GDBM_READER(),0640)) {
 # ------------------------------------------------------------------- Hash tied
               my $firstres=$hash{'map_start_'.$requrl};
               my $lastres=$hash{'map_finish_'.$requrl};
@@ -132,14 +170,7 @@ sub handler {
 
                   @rows=();
 
-                  &tracetable(0,$firstres,'&'.$lastres.'&');
-                  if ($hash{'src_'.$lastres}) {
-                     my $brepriv=
-                        &Apache::lonnet::allowed('bre',$hash{'src_'.$lastres});
-                     if (($brepriv eq '2') || ($brepriv eq 'F')) {
-                        $rows[$#rows+1]=''.$lastres;
-		     }
-		  }
+                  &tracetable(0,$firstres,'&');
 
 # ------------------------------------------------------------ Add to symb list
 
@@ -148,9 +179,9 @@ sub handler {
                   for ($i=0;$i<=$#rows;$i++) {
 		     if ($rows[$i]) {
                         my @colcont=split(/\&/,$rows[$i]);
-                        map {
+                        foreach (@colcont) {
                            $symbhash{$hash{'src_'.$_}}='';
-		        } @colcont;
+		        }
 		     }
 		  }
                   &Apache::lonnet::symblist($requrl,%symbhash);
@@ -180,8 +211,6 @@ sub handler {
                   my $xmlheader='';
                   my $xmlbody='';
 
-                  my %httpref=();
-
 # --------------------------------------------- Get SSI output, post parameters
 
                   for ($i=0;$i<=$#rows;$i++) {
@@ -189,33 +218,39 @@ sub handler {
 		      $contents++;
                       my @colcont=split(/\&/,$rows[$i]);
                       $lcm*=($#colcont+1)/euclid($lcm,($#colcont+1));
-                      map {
+                      foreach (@colcont) {
                           my $src=$hash{'src_'.$_};
                           $src=~/\.(\w+)$/;
                           $metalink{$_}=$src.'.meta';
-                          $cellemb{$_}=Apache::lonnet::fileembstyle($1);
+                          $cellemb{$_}=Apache::loncommon::fileembstyle($1);
                           if ($cellemb{$_} eq 'ssi') {
 # --------------------------------------------------------- This is an SSI cell
 			      my $prefix=$_.'_';
                               my %posthash=('request.prefix' => $prefix);
                               if (($ENV{'form.'.$prefix.'submit'}) 
                                || ($ENV{'form.all_submit'})) {
-                               map {
+                               foreach (keys %ENV) {
 				  if ($_=~/^form.$prefix/) {
 				      my $name=$_;
                                       $name=~s/^form.$prefix//;
                                       $posthash{$name}=$ENV{$_};
                                   }
-                               } keys %ENV;
+                               }
 			      }
                               my $output=Apache::lonnet::ssi($src,%posthash);
+                              if ($target eq 'tex') {
+				  $output =~ s/^([^&]+)\\begin{document}//;
+				  $output =~ s/\\end{document}//;
+				  $output = '\parbox{\minipagewidth}{ '.$output.' }';
+                                  #some additional cleanup necessary for LateX (due to limitations of table environment 
+				  $output =~ s/(\\vskip\s*\d+mm)\s*(\\\\)+/$1/g;
+			      }
                               my $parser=HTML::TokeParser->new(\$output);
                               my $token;
                               my $thisdir=$src;
                               my $bodydef=0;
                               my $thisxml=0;
                               my @rlinks=();
-                              my @alinks=();
                               if ($output=~/\?xml/) {
                                  $isxml=1;
                                  $thisxml=1;
@@ -233,23 +268,9 @@ sub handler {
 				  } elsif ($token->[1] eq 'img') {
                                          $rlinks[$#rlinks+1]=
 					     $token->[2]->{'src'};
-                                         $alinks[$#alinks+1]=
-					     $token->[2]->{'src'};
 				  } elsif ($token->[1] eq 'embed') {
                                          $rlinks[$#rlinks+1]=
 					     $token->[2]->{'src'};
-                                         $alinks[$#alinks+1]=
-					     $token->[2]->{'src'};
-				  } elsif ($token->[1] eq 'applet') {
-                                         $alinks[$#alinks+1]=
-					     $token->[2]->{'code'};
-                                         $alinks[$#alinks+1]=
-					     $token->[2]->{'archive'};
-				  } elsif ($token->[1] eq 'param') {
-				      if ($token->[2]->{'name'} eq 'cabbase') {
-                                         $alinks[$#alinks+1]=
-					     $token->[2]->{'value'};
-                                      }   
 				  } elsif ($token->[1] eq 'base') {
 				      $thisdir=$token->[2]->{'href'};
 				  } elsif ($token->[1] eq 'body') {
@@ -263,7 +284,11 @@ sub handler {
 					  $xmlbody=$token->[4];
                                       }
                                   } elsif ($token->[1] eq 'meta') {
+				    if ($token->[4] !~ m:/>$:) {
 				      $allmeta.="\n".$token->[4].'</meta>';
+				    } else {
+				      $allmeta.="\n".$token->[4];
+				    }
                                   } elsif (($token->[1] eq 'script') &&
                                            ($bodydef==0)) {
 				      $allscript.="\n\n"
@@ -279,26 +304,27 @@ sub handler {
 				  $nforms++;
                                   $output=~s/\<form[^\>]*\>//gsi;
                                   $output=~s/\<\/form[^\>]*\>//gsi;
+                                  $output=~
+				      s/\<((?:input|select|button|textarea)[^\>]+)name\s*\=\s*[\'\"]*([\w\.\:]+)[\'\"]*([^\>]*)\>/\<$1 name="$prefix$2" $3\>/gsi;
                               }
                               $thisdir=~s/\/[^\/]*$//;
-			      map {
+			      foreach (@rlinks) {
 				  unless (($_=~/^http:\/\//i) ||
-                                          ($_=~/^\//)) {
+					  ($_=~/^\//) ||
+					  ($_=~/^javascript:/i) ||
+					  ($_=~/^mailto:/i) ||
+					  ($_=~/^\#/)) {
 				      my $newlocation=
 				    &Apache::lonnet::hreflocation($thisdir,$_);
                      $output=~s/(\"|\'|\=\s*)$_(\"|\'|\s|\>)/$1$newlocation$2/;
 				  }
-			      } @rlinks;
-                              map {
-                                  $httpref{'httpref.'.
-			       &Apache::lonnet::hreflocation($thisdir,$_)}=
-				   $r->uri;
-                              } @alinks;
-                     $output=~s/\<\s*applet/\<applet codebase=\"$thisdir\" /gi;
+			      }
+# -------------------------------------------------- Deal with Applet codebases
+  $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 			      $ssibody{$_}=$output;
 # ---------------------------------------------------------------- End SSI cell
                           }
-                      } @colcont;
+                      }
                      } 
                   }
                   unless ($contents) {
@@ -308,40 +334,59 @@ sub handler {
                   } else {
 # ------------------------------------------------------------------ Build page
 
-# ------------------------------------------------------------- Mark references
-                      &Apache::lonnet::appenv(%httpref);
 # ---------------------------------------------------------------- Send headers
-                      if ($isxml) {
-			  $r->content_type('text/xml');
-                          $r->send_http_header;
-                          $r->print($xmlheader);
-		      } else {
-                          $r->content_type('text/html');
-                          $r->send_http_header;
-                          $r->print('<html>');
-		      }
+		      unless ($target eq 'tex') {
+			  if ($isxml) {
+			      $r->content_type('text/xml');
+			      $r->send_http_header;
+			      $r->print($xmlheader);
+			  } else {
+			      $r->content_type('text/html');
+			      $r->send_http_header;
+			      $r->print('<html>');
+			  }
 # ------------------------------------------------------------------------ Head
-                      $r->print("\n<head>\n".$allmeta);
-                      if ($allscript) {
-			  $r->print("\n<script>\n".$allscript."\n</script>\n");
-                      }
-                      $r->print("\n</head>\n");
+			  $r->print("\n<head>\n".$allmeta);
+			  $allscript=~
+			      s/\/\/ BEGIN LON\-CAPA Internal.+\/\/ END LON\-CAPA Internal\s//gs;
+			  if ($allscript) {
+			      $r->print("\n<script language='JavaScript'>\n".
+					$allscript."\n</script>\n");
+			  }
+			  $r->print(&Apache::lonxml::registerurl(1,undef));
+			  $r->print("\n</head>\n");
 # ------------------------------------------------------------------ Start body
-                      if ($isxml) {
-                          $r->print($xmlbody);
-                      } else {
-			  $r->print('<body bgcolor="#FFFFFF">');
-                      }
+			  if ($isxml) {
+			      $r->print($xmlbody);
+			  } else {
+			      $r->print('<body bgcolor="#FFFFFF" onLoad="'.&Apache::lonxml::loadevents.'" onUnload="'.&Apache::lonxml::unloadevents.'">');
+			  }
 # ------------------------------------------------------------------ Start form
-                      if ($nforms) {
-			  $r->print('<form method="post" action="'.
-				    $requrl.'">');
-                      }
+			  if ($nforms) {
+			      $r->print('<form method="post" action="'.
+					$requrl.'">');
+			  }
+		      } else {
+			  $r->print('\documentclass{article}
+                                 \newcommand{\keephidden}[1]{}           
+                                 \usepackage[dvips]{graphicx}
+                                 \usepackage{epsfig}
+                                 \usepackage{calc}
+                                 \usepackage{longtable}
+                                 \begin{document}');
+		      }
 # ----------------------------------------------------------------- Start table
-                      $r->print('<table cols="'.$lcm.'" border="0">');
+		      if ($target eq 'tex') {
+			  $r->print('\begin{longtable}INSERTTHEHEADOFLONGTABLE\endfirsthead\endhead ');
+			  if ($number_of_columns le $lcm) {$number_of_columns=$lcm;};
+		      } else {
+			  $r->print('<table cols="'.$lcm.'" border="0">');
+		      }
                       for ($i=0;$i<=$#rows;$i++) {
 			if ($rows[$i]) {
-                          $r->print("\n<tr>");
+			    unless ($target eq 'tex') {
+				$r->print("\n<tr>");
+			    }
                           my @colcont=split(/\&/,$rows[$i]);
                           my $avespan=$lcm/($#colcont+1);
                           for ($j=0;$j<=$#colcont;$j++) {
@@ -349,55 +394,117 @@ sub handler {
                               my $metainfo='<a href="'.
                                     $metalink{$rid}.'" target="LONcatInfo">'.
                           '<img src="/adm/lonMisc/cat_button.gif" border=0>'.
-			  '</img></a><br></br>';
-                              $r->print('<td colspan="'.$avespan.'"');
+			  '</img></a><a href="/adm/evaluate?postdata='.
+      &Apache::lonnet::escape(&Apache::lonnet::declutter($hash{'src_'.$rid}))
+      .'" target="LONcatInfo">'.
+                          '<img src="/adm/lonMisc/eval_button.gif" border=0>'.
+                          '</img></a>';
+                              if (
+ ($hash{'src_'.$rid}=~/\.(problem|exam|quiz|assess|survey|form)$/) &&
+ (&Apache::lonnet::allowed('mgr',$ENV{'request.course.id'}))) {
+				  my ($mapid,$resid)=split(/\./,$rid);
+                                 my $symb=
+                &Apache::lonnet::declutter($hash{'map_id_'.$mapid}).
+                '___'.$resid.'___'.
+		&Apache::lonnet::declutter($hash{'src_'.$rid});
+                                 $metainfo.=
+                  '<a href="/adm/grades?symb='.&Apache::lonnet::escape($symb).
+                  '&command=submission" target="LONcatInfo">'.
+                          '<img src="/adm/lonMisc/subm_button.gif" border=0>'.
+			  '</img></a>'.
+                  '<a href="/adm/grades?symb='.&Apache::lonnet::escape($symb).
+                  '&command=gradingmenu" target="LONcatInfo">'.
+                          '<img src="/adm/lonMisc/pgrd_button.gif" border=0>'.
+			  '</img></a>'.
+                  '<a href="/adm/parmset?symb='.&Apache::lonnet::escape($symb).
+                          '" target="LONcatInfo">'.
+                          '<img src="/adm/lonMisc/pprm_button.gif" border=0>'.
+			      '</img></a>';
+                              }
+                              $metainfo.='<br></br>';
+			    unless ($target eq 'tex') {
+				$r->print('<td colspan="'.$avespan.'"');
+			    }
                               if ($cellemb{$rid} eq 'ssi') {
-				  if ($ssibgcolor{$rid}) {
-                                     $r->print(' bgcolor="'.
-                                               $ssibgcolor{$rid}.'"');
-                                  }
-                                  $r->print('>'.$metainfo.'<font');
-                                  if ($ssitext{$rid}) {
-				     $r->print(' text="'.$ssitext{$rid}.'"');
-                                  }
-                                  if ($ssilink{$rid}) {
-				     $r->print(' link="'.$ssilink{$rid}.'"');
-                                  }
-                                  if ($ssitext{$rid}) {
-				     $r->print(' vlink="'.$ssivlink{$rid}.'"');
-                                  }
-                                  if ($ssialink{$rid}) {
-				     $r->print(' alink="'.$ssialink{$rid}.'"');
+				  unless ($target eq 'tex') {
+				      if ($ssibgcolor{$rid}) {
+					  $r->print(' bgcolor="'.
+						    $ssibgcolor{$rid}.'"');
+				      }
+				      $r->print('>'.$metainfo.'<font');
+		    
+				      if ($ssitext{$rid}) {
+					  $r->print(' text="'.$ssitext{$rid}.'"');
+				      }
+				      if ($ssilink{$rid}) {
+					  $r->print(' link="'.$ssilink{$rid}.'"');
+				      }
+				      if ($ssitext{$rid}) {
+					  $r->print(' vlink="'.$ssivlink{$rid}.'"');
+				      }
+				      if ($ssialink{$rid}) {
+					  $r->print(' alink="'.$ssialink{$rid}.'"');
+				      }             
+				      $r->print('>');
+				  }
+                                  $r->print($ssibody{$rid});	
+				  unless ($target eq 'tex') {
+				      $r->print('</font>');
                                   }
-                            
-                                  $r->print('>'.$ssibody{$rid}.'</font>');
-                              } elsif ($cellemb{$rid} eq 'img') {
+                                  if ($ENV{'course.'.
+                                      $ENV{'request.course.id'}.
+                                      '.pageseparators'} eq 'yes') {
+                                      unless($target eq 'tex') {
+                                          $r->print('<hr />');
+                                      } else {
+                                          $r->print('\hline');
+                                      }
+				  }
+			      } elsif ($cellemb{$rid} eq 'img') {
                                   $r->print('>'.$metainfo.'<img src="'.
                                     $hash{'src_'.$rid}.'"></img>');
 			      } elsif ($cellemb{$rid} eq 'emb') {
                                   $r->print('>'.$metainfo.'<embed src="'.
                                     $hash{'src_'.$rid}.'"></embed>');
                               }
-                              $r->print('</td>');
+			      unless ($target eq 'tex') {
+				  $r->print('</td>');
+			      } else {
+                                  for (my $incol=1;$incol<=$avespan;$incol++) {
+				      $r->print(' & ');
+				  }
+			      }
                           }
-                          $r->print('</tr>');
+			      unless ($target eq 'tex') {
+				  $r->print('</tr>');
+			      } else {
+				  $r->print('REMOVETHEHEADOFLONGTABLE\\\\');
+			      }
 		        }
                       }
-                      $r->print("\n</table>");
+		      unless ($target eq 'tex') {
+			  $r->print("\n</table>");
+		      } else {
+			  $r->print('\end{longtable}\strut');
+		      }
 # ---------------------------------------------------------------- Submit, etc.
                       if ($nforms) {
                           $r->print(
 	                  '<input name="all_submit" value="Submit All" type="'.
 			  (($nforms>1)?'submit':'hidden').'"></input></form>');
                       }
-                      $r->print('</body></html>');
+		      unless ($target eq 'tex') {
+			  $r->print('</body>'.&Apache::lonxml::xmlend());
+		      } else {
+			  $r->print('\end{document}'.$number_of_columns);
+		      }
 # -------------------------------------------------------------------- End page
                   }                  
 # ------------------------------------------------------------- End render page
               } else {
                   $r->content_type('text/html');
                   $r->send_http_header;
-		  $r->print('<html><body>Page undefined.</body></html>');
+                  &Apache::lonsequence::viewmap($r,$requrl);
               }
 # ------------------------------------------------------------------ Untie hash
               unless (untie(%hash)) {
@@ -410,15 +517,114 @@ sub handler {
           }
       } 
   }
-  $ENV{'user.error.msg'}="$requrl:bre:0:0:Course not initialized";
-  return HTTP_NOT_ACCEPTABLE; 
+  $r->content_type('text/html');
+  $r->send_http_header;
+  &Apache::lonsequence::viewmap($r,$requrl);
+  return OK; 
 }
 
 1;
 __END__
 
+=head1 NAME
+
+Apache::lonpage - Page Handler
+
+=head1 SYNOPSIS
+
+Invoked by /etc/httpd/conf/srm.conf:
+
+ <LocationMatch "^/res/.*\.page$>
+ SetHandler perl-script
+ PerlHandler Apache::lonpage
+ </LocationMatch>
+
+=head1 INTRODUCTION
+
+This module renders a .page resource.
+
+This is part of the LearningOnline Network with CAPA project
+described at http://www.lon-capa.org.
+
+=head1 HANDLER SUBROUTINE
+
+This routine is called by Apache and mod_perl.
+
+=over 4
+
+=item *
+
+set document type for header only
+
+=item *
+
+tie db file
+
+=item *
+
+render page
+
+=item *
+
+add to symb list
+
+=item *
+
+page parms
+
+=item *
+
+Get SSI output, post parameters
+
+=item *
+
+SSI cell rendering
+
+=item *
+
+Deal with Applet codebases
+
+=item *
+
+Build page
+
+=item *
+
+send headers
+
+=item *
+
+start body
+
+=item *
+
+start form
+
+=item *
+
+start table
+
+=item *
+
+submit element, etc, render page, untie hash
+
+=back
+
+=head1 OTHER SUBROUTINES
+
+=over 4
+
+=item *
+
+euclid() : Euclid's method for determining the greatest common denominator.
+
+=item *
+
+tracetable() : Build page table.
 
+=back
 
+=cut