File:  [LON-CAPA] / loncom / interface / printout.pl
Revision 1.111: download - view: text, annotated - select for diffs
Mon Oct 30 11:40:49 2006 UTC (17 years, 6 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Part of bz 4265 - if the image conversion queue file has ps or eps images
in it, just convert any spaces in their names to _'s and copy to the
spool directory for the latex inclusion..

    1: #!/usr/bin/perl
    2: # CGI-script to run LaTeX, dvips, ps2ps, ps2pdf etc.
    3: #
    4: #
    5: # Copyright Michigan State University Board of Trustees
    6: #
    7: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    8: #
    9: # LON-CAPA is free software; you can redistribute it and/or modify
   10: # it under the terms of the GNU General Public License as published by
   11: # the Free Software Foundation; either version 2 of the License, or
   12: # (at your option) any later version.
   13: #
   14: # LON-CAPA is distributed in the hope that it will be useful,
   15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   17: # GNU General Public License for more details.
   18: #
   19: # You should have received a copy of the GNU General Public License
   20: # along with LON-CAPA; if not, write to the Free Software
   21: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   22: #
   23: # /home/httpd/html/adm/gpl.txt
   24: #
   25: # http://www.lon-capa.org/
   26: #
   27: 
   28: use lib '/home/httpd/lib/perl';
   29: use LONCAPA::loncgi;
   30: use File::Path;
   31: use File::Basename;
   32: use File::Copy;
   33: use IO::File;
   34: use Image::Magick;
   35: use Apache::lonhtmlcommon();
   36: use Apache::lonnet;
   37: use Apache::loncommon();
   38: use Apache::lonlocal;
   39: use Apache::lonmsg();
   40: use LONCAPA::Enrollment;
   41: 
   42: use strict;
   43: 
   44: 
   45: #   Determine if a user is operating as a student for this course/domain.
   46: #Parameters:
   47: #    none
   48: #Implicit:
   49: #    $env{request.role} contains the role under which this user operated this
   50: #                       this request.
   51: sub is_student {
   52:     return ($env{'request.role'}=~/^st\./);
   53: }
   54: 
   55: #
   56: #   Debugging:  Dump the environment for debugging.
   57: #
   58: sub dumpenv  {
   59:     print "<br />-------------------<br />";
   60:     foreach my $key (sort (keys %env)) {
   61: 	print "<br />$key -> $env{$key}";
   62:     }
   63:     print "<br />-------------------<br />";
   64: }
   65: 
   66: #
   67: #   This sub sends a message to the appropriate person if there was an error
   68: #   rendering the latex  At present, there's only one case to consider:
   69: #   a student printing inside a course results in messages to the course coordinator.
   70: #Parmaeters:
   71: #    identifier -  The unique identifier of this cgi request.
   72: #    badresource-  Filepath to most likely failing 
   73: #    logfile    -  The contents of the log file (included in the message).
   74: #    texfile    -  reference to an array containing the LaTeX input file
   75: #                  (included in the message).
   76: #Implicit inputs:
   77: #   From the environment:
   78: #       cgi.$identifier.user     - User doing the printing.
   79: #       cgi.$identifier.domain   - Domain the user is logged in on with printing.
   80: #       cgi.$identifier.courseid - Id of the course (if this is a course).
   81: #       cgi.$identifier.coursedom- Domain in which course was constituted.
   82: #       cgi.$identifier.resources - List of resource URL's for which the print
   83: #                                  was attempted.
   84: # 
   85: sub send_error_mail {
   86:     my ($identifier, $badresource, $logfile, $texfile) = @_;
   87:     my $user     = $env{"cgi.$identifier.user"};
   88:     my $domain   = $env{"cgi.$identifier.domain"};
   89:     my $courseid = $env{"cgi.$identifier.courseid"};
   90:     my $coursedom= $env{"cgi.$identifier.coursedom"};
   91:     my $resources= $env{"cgi.$identifier.resources"};
   92: 
   93:     #  resource file->URL
   94:     #
   95:     my $badurl = &Apache::lonnet::declutter($badresource);
   96: 
   97:     # &dumpenv();
   98: 
   99: 
  100: 
  101:     #  Only continue if there is a user, domain, courseid, course domain
  102:     #  and resources:
  103: 
  104:     if(defined($user)       && defined($domain) && defined($courseid) &&
  105:        defined($coursedom)  && defined($resources) ){
  106: 	   
  107: 	#  Only mail if the conditions are ripe for it:
  108: 	#  The user is a student in the course:
  109: 	#
  110: 	
  111: 	if (&is_student()) {
  112: 	    # build the subject and message body:
  113: 	    # print "sending message to course coordinators.<br />";
  114: 
  115: 	    # Todo: Convert badurl into a url from file path:
  116: 
  117: 	    my $subject  = "Error [$badurl] Print failed for $user".'@'.$domain;
  118: 	    my $message .= "Print failed to render LaTeX for $user".'@'."$domain\n";
  119: 	    $message    .= "  User was attempting to print: \n";
  120: 	    foreach my $resource (split(/:/,$resources)) {
  121: 		$message    .= "       $resource\n";
  122: 	    }
  123: 	    $message    .= "--------------------LaTeX logfile:------------ \n";
  124: 	    $message    .= $logfile;
  125: 	    $message    .= "-----------------LaTeX source file: ------------\n";
  126: 	    
  127: 	    foreach my $line (@$texfile) {
  128: 		$message .= "$line\n";
  129: 	    }
  130: 	    my (undef, %receivers) = &Apache::lonfeedback::decide_receiver(undef, 0,
  131: 									  1,1,1);
  132: 	    # print "<br /> sending...section:  $env{'request.course.sec'}";
  133: 	    foreach my $dest (keys %receivers) {
  134: 		# print "<br /> dest is $dest";
  135: 		my @destinfo = split(/:/,$dest);
  136: 		my $user = $destinfo[0];
  137: 		my $dom  = $destinfo[1];
  138: 
  139: 		&Apache::lonmsg::user_normal_msg($user, $dom,
  140: 						 $subject, $message);
  141: 		
  142: 		# No point in looking at the return status as there's no good
  143: 		# error action I can think of right now (log maybe?).
  144: 	    }
  145: 	}
  146:     }
  147: }
  148: 
  149: $|=1;
  150: if (! &LONCAPA::loncgi::check_cookie_and_load_env()) {
  151:     print <<END;
  152: Content-type: text/html
  153: 
  154: <html>
  155: <head><title>Bad Cookie</title></head>
  156: <body>
  157: Your cookie information is incorrect.
  158: </body>
  159: </html>
  160: END
  161:     return;
  162: }
  163:  &Apache::lonlocal::get_language_handle();
  164:  &Apache::loncommon::content_type(undef,'text/html');
  165: 
  166:   print(&Apache::loncommon::start_page('Creating PDF'));
  167: 
  168:   my $identifier = $ENV{'QUERY_STRING'};
  169:   my $texfile = $env{'cgi.'.$identifier.'.file'};
  170:   my $laystyle = $env{'cgi.'.$identifier.'.layout'};
  171:   my $numberofcolumns = $env{'cgi.'.$identifier.'.numcol'};
  172:   my $paper = $env{'cgi.'.$identifier.'.paper'};
  173:   my $selectionmade = $env{'cgi.'.$identifier.'.selection'};
  174:   my $tableofcontents = $env{'cgi.'.$identifier.'.tableofcontents'};
  175:   my $tableofindex = $env{'cgi.'.$identifier.'.tableofindex'};
  176:   my $advanced_role = $env{'cgi.'.$identifier.'.role'};
  177:   my $number_of_files = $env{'cgi.'.$identifier.'.numberoffiles'}+1;
  178:   my $student_names = $env{'cgi.'.$identifier.'.studentnames'};
  179:   my $backref = &Apache::lonnet::unescape($env{'cgi.'.$identifier.'.backref'});
  180: 
  181:   
  182:   my @names_pack=();
  183:   if ($student_names=~/_END_/) {  
  184:       @names_pack=split(/_ENDPERSON_/,$student_names);
  185:   }
  186: 
  187: print "<a href=\"$backref\"><b>Return</b></a> to last resource.<br /><br />";
  188: 
  189:   my $figfile = $texfile;
  190:   $figfile =~ s/^([^\.]+printout)[^t]+\.tex/$1\.dat/;
  191:   my $duefile = $texfile;
  192:   $duefile =~ s/^([^\.]+printout)[^t]+\.tex/$1\.due/;
  193:   #do we have figures?
  194:   # print "Figure file: $figfile\n";
  195:   if (-e $figfile) {
  196:       # print "$figfile exists\n";
  197:       my %done_conversion;
  198:       my $temporary_file=IO::File->new($figfile) || die "Couldn't open fig file $figfile for reading: $!\n";
  199:       my @content_of_file = <$temporary_file>;
  200:       close $temporary_file;  
  201:       my $noteps;
  202:       my %prog_state;
  203:       if ($advanced_role) { %prog_state=&Apache::lonhtmlcommon::Create_PrgWin('','Coverting Images to EPS','Picture Conversion Status',$#content_of_file,'inline','80');  }
  204:       print('<br />');
  205:       foreach my $not_eps (@content_of_file) {
  206: 	  chomp($not_eps);
  207: 	  if ($not_eps ne '') {
  208: 	      # print "Converting $not_eps"; # Debugging.
  209:               my $status_statement='EPS picture for '.$not_eps;
  210: 	      # print "$status_statement\n";
  211: 	      $not_eps=~s|\/\.\/|\/|g;
  212: 	      my $eps_f = $not_eps;
  213: 	      # $eps_f =~ s/\.[^.]*$/\.eps/i;
  214: 	      if ($eps_f=~/\/home\/([^\/]+)\/public_html\//) {
  215:                   $eps_f=~s/\/home\/([^\/]+)\/public_html/$1/;
  216: 		  $eps_f = '/home/httpd/prtspool/'.$eps_f;
  217: 	      } elsif ($eps_f=~/$Apache::lonnet::perlvar{'lonDocRoot'}\/res\//) {
  218: 		  $eps_f=~m/$Apache::lonnet::perlvar{'lonDocRoot'}\/res\/(.+)/;
  219: 		  $eps_f = '/home/httpd/prtspool/'.$1;
  220: 	      } elsif ($eps_f=~/$Apache::lonnet::perlvar{'lonUsersDir'}\//) {
  221: 		  $eps_f=~/$Apache::lonnet::perlvar{'lonUsersDir'}\/([^\/]+)\/\w\/\w\/\w\/(.+)/;
  222: 		  $eps_f = '/home/httpd/prtspool/'.$1.'/'.$2;
  223: 	      }
  224: 	      $eps_f  =~ s/ /\_/g; # Spaces are problematic for system commands and LaTeX.
  225: 	      # 
  226: 	      # If the file is already an .eps or .ps file,
  227: 	      # We really just need to copy it from where it was to prtspool
  228: 	      # but with the spaces substituted to _'s.
  229: 	      #
  230: 	      my ($path, $nsname, $sext) = fileparse($eps_f, qr/\.(ps|eps)/i);
  231: 	      if ($sext =~/ps$/i) {
  232: 		  File::Path::mkpath($path,0,0777);
  233: 		  $not_eps =~ s/^\s+//;
  234: 		  $not_eps =~ s/\s+$//;
  235: 		  $not_eps =~ s/ /\__/g;
  236: 		  File::Copy("$not_eps", "$eps_f"); 
  237: 	      } else {
  238: 	      
  239: 		  $eps_f .= '.eps';	# Just append the eps ext.
  240: 		  my $path=$eps_f;
  241: 		  $path =~ s/\/([^\/]+)\.eps$//;
  242: 		  # print "Final file path: $path "; # Debugging
  243: 		  File::Path::mkpath($path,0,0777);
  244: 		  $not_eps =~ s/^\s+//;
  245: 		  $not_eps =~ s/\s+$//;
  246: 		  $not_eps =~ s/ /\\ /g;
  247: 		  if ( exists($done_conversion{$not_eps})) { next; }
  248: 		  if ($advanced_role) {
  249: 		      my $prettyname=$not_eps;
  250: 		      $prettyname=~s|/home/([^/]+)/public_html|/priv/$1|;
  251: 		      $prettyname=~s|$Apache::lonnet::perlvar{'lonDocRoot'}/|/|;
  252: 		      &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,
  253: 							    'Converting to EPS '.$prettyname);
  254: 		  }
  255: 		  $done_conversion{$not_eps}=1;
  256: 		  # print "Converting $not_eps -> $eps_f"; # Debugging
  257: 		  system("convert $not_eps $eps_f");
  258: 		  # check is eps exist in prtspool
  259: 		  if (not -e $eps_f) {
  260: 		      # converting an animated gif creates either:
  261: 		      # anim.gif.eps.0
  262: 		      # or
  263: 		      # anim.gif-0.eps
  264: 		      for (my $i=0;$i<10000;$i++) {
  265: 			  if (-e $eps_f.'.'.$i) {
  266: 			      rename($eps_f.'.'.$i, $eps_f);
  267: 			      last;
  268: 			  }
  269: 			  my $anim_eps = $eps_f;
  270: 			  $anim_eps =~ s/(\.[^.]*)\.eps$/$1-$i\.eps/i;
  271: 			  if (-e $anim_eps) {
  272: 			      rename($anim_eps, $eps_f);
  273: 			      last;
  274: 			  }
  275: 		      }
  276: 		  }
  277: 		  
  278: 		  # imagemagick 6.2.0-6.2.7 fails to properly handle
  279: 		  # convert anim.gif anim.gif.eps
  280: 		  # it creates anim.eps instead. 
  281: 		  if (not -e $eps_f) {
  282: 		      my $eps_f2 = $eps_f;
  283: 		      $eps_f2 =~ s/\.[^.]*\.eps$/\.eps/i;
  284: 		      if(-e $eps_f2) {
  285: 			  rename($eps_f2,$eps_f);
  286: 		      }
  287: 		  }
  288: 	      }
  289: 
  290: 	  }
  291:       }
  292:       if ($advanced_role) { 
  293: 	  &Apache::lonhtmlcommon::Close_PrgWin('',\%prog_state); 
  294:       }
  295:       unlink($figfile);
  296:   }
  297:   #print "$texfile\n"; #name of the tex file for debugging only   
  298:   my @texfile=($texfile);
  299:   if ($number_of_files>1) {
  300:       @texfile=();
  301:       for (my $i=1;$i<=$number_of_files;$i++) {
  302: 	  my $new_texfile=$texfile;
  303: 	  $new_texfile=~s/\.tex//;
  304: 	  $new_texfile = sprintf("%s_%03d.tex", $new_texfile,$i);
  305: 	  push @texfile,$new_texfile;
  306:       } 
  307:   }
  308: 
  309: my $ind=-1;
  310: my %prog_state;
  311: if ($advanced_role) { %prog_state=&Apache::lonhtmlcommon::Create_PrgWin('','Print Status','Class Print Status',$number_of_files,'inline','80'); }
  312: print "<br />";
  313: my $num_files = @texfile;
  314: foreach $texfile (@texfile) {
  315:   my $status_statement='';
  316:   my $link_text='download PDF';
  317:   $ind++;
  318:   my @stud_info=split(/_END_/,$names_pack[$ind]);
  319:   my @tempo_array=split(/:/,$stud_info[0]);
  320:   my $name;
  321:   my $name_range='';
  322:   if ($tempo_array[3]) {
  323:       $name=$tempo_array[3];
  324:       ($name_range) = split(/,/,$name, 2);
  325:   } else {
  326:       $name=$tempo_array[0].'@'.$tempo_array[1];
  327:       $name_range = $tempo_array[0];
  328:   }
  329:   if (($name ne "") && ($name ne '@') ) { # Could be printing codes...
  330:       $link_text='<b>'.$name.'</b>';
  331:       $status_statement.=$name;
  332:   }
  333:   if ($#stud_info>0) {
  334:       @tempo_array=split(/:/,$stud_info[-1]);
  335:       if ($tempo_array[3]) {
  336: 	  $name=$tempo_array[3];
  337: 	  my ($lastname) = split(/,/, $name,2);
  338: 	  $name_range .= "-".$lastname;
  339:       } else {
  340: 	  $name=$tempo_array[0].'@'.$tempo_array[1];
  341: 	  $name_range .= '-'.$tempo_array[0];
  342:       }
  343:       if (($name ne "") && ($name ne '@')) {
  344: 	  $link_text.=' - <b>'.$name.'</b>';
  345: 	  $status_statement.=' -  '.$name;
  346:   
  347:       }
  348:   }
  349:   if(($num_files > 1) && ($link_text eq 'download PDF')) { # Printing codes
  350:       $link_text = '<b>'.basename($texfile,'.tex').'.pdf</b>';
  351:       $status_statement .= basename($texfile);
  352:   }
  353:   $name_range =~ s/'//g;	# O'Neil -> ONeil e.g.
  354:   print "<br/>";
  355:   if ($advanced_role) { &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,'Creating PDF for '.$status_statement); }
  356:   #  This little piece of dirt puts username ranges into the original tex
  357:   #  Tex filename from which they'll propagate into the other filenames as well.
  358:   #
  359:   if (-e $texfile) {
  360:       if (($name_range ne '') && ($num_files > 1)) {
  361: 	  my $newtexfile = $texfile;
  362: 	  $newtexfile    =~ s/\.tex/$name_range\.tex/;
  363: 	  rename($texfile, $newtexfile);
  364: 	  $texfile       = $newtexfile;
  365:       }
  366:       $texfile =~ m/^(.*)\/([^\/]+)$/; 
  367:       my $name_file = $2;
  368:       my $path_file = $1.'/';
  369:       chdir $path_file;
  370:       my $dvi_file= $name_file; $dvi_file =~ s/\.tex/$name_range\.dvi/;
  371:       &busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
  372: 			 "for $status_statement now LaTeXing file",
  373: 			 \%prog_state,$dvi_file);
  374:       if ($tableofcontents eq 'yes') {
  375:       &busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
  376: 			 "for $status_statement First LaTeX of file for table of contents",
  377: 			 \%prog_state,$dvi_file);
  378:       &busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
  379: 			 "for $status_statement Second LaTeX of file for table of contents",
  380: 			 \%prog_state,$dvi_file);
  381:       } #to create table of contents
  382:       my $idxname=$name_file;
  383:       $idxname=~s/\.tex$/\.idx/;
  384:       if ($tableofindex eq 'yes') {
  385: 	  &busy_wait_command("makeindex $idxname",
  386: 			     "making index file",
  387: 			     \%prog_state,$idxname);
  388: 	  &busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
  389: 			     "for $status_statement now LaTeXing file for index section",
  390: 			     \%prog_state,$dvi_file);
  391:       } #to create index
  392:       #Do we have a latex error in the log file?
  393:       my $logfilename = $texfile; $logfilename =~ s/\.tex$/\.log/;
  394:       my $temporary_file=IO::File->new($logfilename) || die "Couldn't open log file $logfilename for reading: $!\n";
  395:       my @content_of_file = <$temporary_file>;
  396:       close $temporary_file; 
  397:       my $body_log_file = join(' ',@content_of_file);
  398:       $logfilename =~ s/\.log$/\.html/;
  399:       $temporary_file = IO::File->new('>'.$logfilename); 
  400:       print $temporary_file '<html><head><title>LOGFILE</title></head><body><pre>'.$body_log_file.'</pre></body></html>'."\n";
  401:       if ($body_log_file=~m/!\s+Emergency stop/) {
  402: 	  my $whereitbegins = rindex $body_log_file,'STAMPOFPASSEDRESOURCESTART';
  403: 	  my $whereitends = rindex $body_log_file,'STAMPOFPASSEDRESOURCEEND';
  404: 	  my $badresource;
  405: 	  my $badtext;
  406: 	  if ($whereitbegins!=-1 and $whereitends!=-1) {
  407: 	      $badtext = substr($body_log_file,$whereitbegins+26, $whereitends-$whereitbegins-26);
  408: 	      $whereitbegins  = rindex $badtext,'located in';
  409: 	      if ($whereitbegins != -1) {
  410: 		  
  411: 		  $badresource = substr($badtext, $whereitbegins+27, 
  412: 					length($badtext) - $whereitbegins - 48);
  413: 		  # print "<br />failing resourcename: $badresource<br />";
  414: 	      }
  415: 	  }
  416: 	  
  417:           if ($advanced_role) {  
  418: 	      #LaTeX failed to parse tex file 
  419: 	      print "<h2>LaTeX could not successfully parse your tex file.</h2>";
  420: 	      print "It probably has errors in it.<br />";
  421: 	      print "With very high probability this error occured in ".$badtext."<br /><br />";
  422: 	      print "Here are the error messages in the LaTeX log file<br /><pre>";
  423: 
  424: 	      my $sygnal = 0;
  425: 	      for (my $i=0;$i<=$#content_of_file;$i++) {
  426: 		  if ($content_of_file[$i]=~m/^Runaway argument?/ or $content_of_file[$i]=~m/^!/) {
  427: 		      $sygnal = 1;
  428: 		  } 
  429: 		  if ($content_of_file[$i]=~m/Here is how much of/) {
  430: 		      $sygnal = 0;
  431: 		  } 
  432: 		  if ($sygnal) {
  433: 		      print "$content_of_file[$i]";
  434: 		  }  
  435: 	      }
  436: 	      print "</pre>\n";
  437: 	      # print "<br /> Advanced role <br />";
  438:               print "<b><big>The link to ";
  439:               $logfilename=~s/\/home\/httpd//;
  440: 	      print "<a href=\"$logfilename\">Your log file </a></big></b>";
  441: 	      print "\n";
  442:               #link tooriginal LaTeX file (included according Michael Hamlin desire)
  443: 	      my $tex_temporary_file=IO::File->new($texfile) || die "Couldn't open tex file $texfile for reading: $!\n";
  444: 	      my @tex_content_of_file = <$tex_temporary_file>;
  445: 	      close $tex_temporary_file; 
  446: 	      my $body_tex_file = join(' ',@tex_content_of_file);
  447: 	      $texfile =~ s/\.tex$/aaaaa\.html/;
  448: 	      $tex_temporary_file = IO::File->new('>'.$texfile); 
  449: 	      print $tex_temporary_file '<html><head><title>LOGFILE</title></head><body><pre>'.$body_tex_file.'</pre></body></html>'."\n";
  450: 	      print "<br /><br />";
  451: 	      print "<b><big>The link to ";
  452: 	      $texfile=~s/\/home\/httpd//;
  453: 	      print "<a href=\"$texfile\">Your original LaTeX file </a></big></b>";
  454: 	      print "\n";
  455: 	      my $help_text = &Apache::loncommon::help_open_topic("Print_Resource", "Help on printing");
  456: 	      print ("$help_text");
  457: 
  458: 	  } else {		# Student role...
  459: 	      #  at this point:
  460: 	      #    $body_log_file - contains the log file.
  461:               #    $name_file     - is the name of the LaTeX file.
  462:               #    $identifier    - is the unique LaTeX identifier.l
  463: 
  464: 	      print "<br />There are errors in $badtext";
  465: 	      print "<br />These errors prevent this resource from printing correctly";
  466: 	      my $tex_handle = IO::File->new($name_file);
  467: 	      my @tex_contents = <$tex_handle>;
  468: 	      &send_error_mail($identifier, $badresource, $body_log_file, \@tex_contents);
  469: 	      print "<br />A message has been sent to the instructor describing this failure<br />";
  470: 	      my $help_text = &Apache::loncommon::help_open_topic("Print_Resource", "Help on printing");
  471: 	      print  ("$help_text");
  472: 
  473: 	  }
  474: 
  475:       } elsif ($body_log_file=~m/<inserted text>/) {
  476: 	  my $whereitbegins = index $body_log_file,'<inserted text>';
  477: 	  print "You are running LaTeX in <b>batch mode</b>.";
  478: 	  while ($whereitbegins != -1) {
  479: 	      my $tempobegin=$whereitbegins;
  480: 	      $whereitbegins = rindex $body_log_file,'STAMPOFPASSEDRESOURCESTART',$whereitbegins;
  481: 	      my $whereitends = index $body_log_file,'STAMPOFPASSEDRESOURCEEND',$whereitbegins;
  482: 	      print "<br />It has found an error in".substr($body_log_file,$whereitbegins+26,$whereitends-$whereitbegins-26)." <br /> and corrected it.\n";
  483: 	      print "Usually this correction is valid but you probably need to check the indicated resource one more time and implement neccessary corrections by yourself.\n";
  484: 	      $whereitbegins = index $body_log_file,'<inserted text>',$tempobegin+10;
  485: 	  }
  486: 	  $name_file =~ s/\.tex/\.dvi/;
  487: 	  my $new_name_file = $name_file;
  488: 	  $new_name_file =~ s/\.dvi/\.ps/;
  489: 	  my $papera=$paper;
  490: 	  if ($papera eq 'letter') {$papera='';}
  491: 	  if ($papera ne '') {$papera='-t'.$papera;}
  492: 	  my $comma = "dvips $papera -Ppdf -G0 -o $new_name_file";
  493: 	  &busy_wait_command("$comma $name_file 1>/dev/null 2>/dev/null",
  494: 			     "for $status_statement now Converting to PS",
  495: 			     \%prog_state,$new_name_file);
  496: 	  if (-e $new_name_file) {
  497: 	      my $latex_file = $name_file;
  498: 	      $latex_file    =~ s/\.dvi/\.tex/;
  499: 	      &repaginate($new_name_file, $latex_file, $numberofcolumns);
  500: 	      #
  501: 	      #  Now have to re-latex, re dvips again to 
  502: 	      #  get the repaginated postscript.
  503: 	      #
  504: 	      &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  505: 				 "for $status_statement first latex to repaginate",
  506: 				 \%prog_state, $name_file);
  507: 	      if ($tableofcontents eq 'yes') {
  508: 		  &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  509: 				     "for $status_statement second latex to repaginate",
  510: 				     \%prog_state, $name_file);
  511: 		  &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  512: 				     "for $status_statement third latex to repaginate",
  513: 				     \%prog_state, $name_file);
  514: 	      }
  515: 	      if ($tableofindex eq 'yes') {
  516: 		  my $idxname = $latex_file;
  517: 		  $idxname =~ s/\.tex$/\.idx/;
  518: 		  &busy_wait_command("makindex $idxname",
  519: 				     "Re-creating index file",
  520: 				     \%prog_state, $idxname);
  521: 		  &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  522: 				     "for $status_statement now Recreting index (latex)",
  523: 				     \%prog_state, $dvi_file);
  524: 
  525: 	      }
  526: 	      &busy_wait_command("$comma $name_file 1>dev/null 2>/dev/null",
  527: 				 "for $status_statement dvips to repaginate",
  528: 				 \%prog_state, $new_name_file);
  529: 	      print "\n<h1>PDF output file (see link below)</h1>\n";
  530: 	      $new_name_file =~ m/^(.*)\./;
  531: 	      my $ps_file = my $tempo_file = $1.'temporar.ps';
  532: 	      my $pdf_file = $1.'.pdf';
  533: 	      if ($laystyle eq 'album' and $numberofcolumns eq '2') {
  534: 		  my $papera=$paper;
  535:                   if ($papera eq 'letter') {$papera='';}
  536: 		  if ($papera ne '') {$papera='-p'.$papera;}
  537: 		  $comma = "psnup $papera -2 -s1.0 $new_name_file";
  538: 		  &busy_wait_command("$comma $tempo_file 1>/dev/null 2>/dev/null",
  539: 				     "for $status_statement now Modifying PS layout",
  540: 				     \%prog_state,$tempo_file); 
  541: 	      } elsif ($laystyle eq 'book' and $numberofcolumns eq '2') {
  542: 		  my $papera=$paper;
  543:                   if ($papera eq 'letter') {$papera='';}
  544: 		  if ($papera ne '') {$papera='-p'.$papera;}
  545: 		  $comma = 'pstops '.$papera.' "2:0+1(0.48w,0)"';
  546: 		  &busy_wait_command("$comma $new_name_file $tempo_file 1>/dev/null 2>/dev/null",
  547: 				     "for $status_statement now Modifying PS layout",
  548: 				     \%prog_state,$tempo_file); 
  549: 
  550: 	      } else {
  551: 		  $ps_file=$new_name_file;
  552: 	      }	    
  553: 	      &busy_wait_command("ps2pdf $ps_file $pdf_file 1>/dev/null 2>/dev/null",
  554: 				 "for $status_statement now Converting PS to PDF",
  555: 				 \%prog_state, $pdf_file);
  556: 
  557: 	      my $texlog = $texfile;
  558: 	      my $texaux = $texfile;
  559: 	      my $texdvi = $texfile;
  560: 	      my $texps = $texfile;
  561: 	      $texlog =~ s/\.tex/\.log/;
  562: 	      $texaux =~ s/\.tex/\.aux/;
  563: 	      $texdvi =~ s/\.tex/\.dvi/;
  564: 	      $texps =~ s/\.tex/\.ps/;
  565: 	      my @garb = ($texaux,$texdvi,$texps);
  566: #	  unlink @garb;
  567: 	      unlink $duefile;
  568: 	      print "<a href=\"/prtspool/$pdf_file\">Your PDF document</a>";
  569: 	  }
  570: 	  if ($advanced_role) {  
  571: 	      print "<br /><br />";
  572: 	      print "<b><big>The link to ";
  573: 	      $logfilename=~s/\/home\/httpd//;
  574: 	      print "<a href=\"$logfilename\">Your log file </a></big></b>";
  575: 	      print "\n";
  576: 	      #link tooriginal LaTeX file (included according Michael Hamlin desire)
  577: 	      my $tex_temporary_file=IO::File->new($texfile) || die "Couldn't open tex file $texfile for reading: $!\n";
  578: 	      my @tex_content_of_file = <$tex_temporary_file>;
  579: 	      close $tex_temporary_file; 
  580: 	      my $body_tex_file = join(' ',@tex_content_of_file);
  581: 	      $texfile =~ s/\.tex$/aaaaa\.html/;
  582: 	      $tex_temporary_file = IO::File->new('>'.$texfile); 
  583: 	      print $tex_temporary_file '<html><head><title>LOGFILE</title></head><body><pre>'.$body_tex_file.'</pre></body></html>'."\n";
  584: 	      print "<br /><br />";
  585: 	      print "<b><big>The link to ";
  586: 	      $texfile=~s/\/home\/httpd//;
  587: 	      print "<a href=\"$texfile\">Your original LaTeX file </a></big></b>";
  588: 	      print "\n";
  589: 	  }
  590:       } else {
  591: 	  #LaTeX successfully parsed tex file 
  592: 	  $name_file =~ s/\.tex/\.dvi/;
  593: 	  my $new_name_file = $name_file;
  594: 	  $new_name_file =~ s/\.dvi/\.ps/;
  595: 	  my $papera=$paper;
  596: 	  if ($papera eq 'letter') {$papera='';}
  597: 	  if ($papera ne '') {$papera='-t'.$papera;}
  598: 	  my $comma = "dvips $papera -Ppdf -G0 -o $new_name_file";
  599: 	  &busy_wait_command("$comma $name_file 1>/dev/null 2>/dev/null",
  600: 			     "for $status_statement now Converting to PS",
  601: 			     \%prog_state,$new_name_file);
  602: 	  if (-e $new_name_file) {
  603: 	      my $latex_file = $name_file;
  604: 	      $latex_file =~ s/\.dvi/\.tex/;
  605: 	      &repaginate($new_name_file, $latex_file,  $numberofcolumns);
  606: 	      &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  607: 				 "for $status_statement first latex to repaginate",
  608: 				 \%prog_state, $name_file);
  609: 	      if ($tableofcontents eq 'yes') {
  610: 		  &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  611: 				     "for $status_statement second latex to repaginate",
  612: 				     \%prog_state, $name_file);
  613: 		  &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  614: 				     "for $status_statement third latex to repaginate",
  615: 				     \%prog_state, $name_file);
  616: 	      }
  617: 	      if ($tableofindex eq 'yes') {
  618: 		  my $idxname = $latex_file;
  619: 		  $idxname    =~ s/\.tex$/\.idx/;
  620: 		  &busy_wait_command("makeindex $idxname",
  621: 				     "Re-creating index file",
  622: 				     \%prog_state, $idxname);
  623: 		  &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  624: 				     "for $status_statement now Recreting index (latex)",
  625: 				     \%prog_state, $dvi_file);
  626: 	      }
  627: 	      &busy_wait_command("$comma $name_file 1>/dev/null 2>/dev/null",
  628: 				 "for $status_statement dvips to repaginate",
  629: 				 \%prog_state, $new_name_file);
  630: 	      print "<br />";
  631: 	      $new_name_file =~ m/^(.*)\./;
  632: 	      my $ps_file = my $tempo_file = $1.'temporar.ps';
  633: 	      my $pdf_file = $1.'.pdf';
  634: 	      $papera=~s/t/p/;
  635: 	      if ($laystyle eq 'album' and $numberofcolumns eq '2') {
  636: 		  $comma = "psnup $papera -2 -s1.0 $new_name_file";
  637: 		  &busy_wait_command("$comma $tempo_file 1>/dev/null 2>/dev/null",
  638: 				     "for $status_statement now Modifying PS layout",
  639: 				     \%prog_state,$tempo_file);
  640: 	      } elsif ($laystyle eq 'book' and $numberofcolumns eq '2') {
  641: 		  $comma = 'pstops '.$papera.' "2:0+1(0.48w,0)"';
  642: 		  &busy_wait_command("$comma $new_name_file $tempo_file 1>/dev/null 2>/dev/null",
  643: 				     "for $status_statement now Modifying PS layout",
  644: 				     \%prog_state,$tempo_file); 
  645: 	      } else {
  646: 		  $ps_file=$new_name_file;
  647: 	      }
  648: 	      my $addtoPSfile={'legal'=>'<< /PageSize [612 1008] >> setpagedevice',
  649:                                'tabloid'=>'<< /PageSize [792 1224] >> setpagedevice',
  650:                                'executive'=>,'<< /PageSize [540 720] >> setpagedevice',
  651:                                'a2'=>'<< /PageSize [1195.02 1690.09] >> setpagedevice',
  652:                                'a3'=>'<< /PageSize [842 1195.02] >> setpagedevice',
  653:                                'a4'=>'<< /PageSize [595.2 842] >> setpagedevice',
  654:                                'a5'=>'<< /PageSize [421.1 595.2] >> setpagedevice',
  655:                                'a6'=>'<< /PageSize [298.75 421.1] >> setpagedevice',
  656: 			   };
  657: 	      if ($paper ne 'letter') {
  658: 		  open(FFH,'<',$ps_file) || die "Couldn't open ps file $ps_file for reading: $!\n";
  659: 		  my $new_ps_file='new'.$ps_file;
  660: 		  open(FFHS,'>',$new_ps_file) || die "Couldn't open new ps file $new_ps_file for reading: $!\n";
  661: 		  print FFHS $addtoPSfile->{$paper}."\n";
  662: 		  while (<FFH>) {
  663: 		      print FFHS $_;
  664: 		  }
  665: 		  close(FFH);
  666: 		  close(FFHS);
  667: 		  $ps_file=$new_ps_file;	  
  668: 	      }
  669: 	      &busy_wait_command("ps2pdf $ps_file $pdf_file 1>/dev/null 2>/dev/null",
  670: 				 "for $status_statement now Converting PS to PDF",
  671: 				 \%prog_state,$pdf_file);
  672: 	    
  673: 	      my $texlog = $texfile;
  674: 	      my $texaux = $texfile;
  675: 	      my $texdvi = $texfile;
  676: 	      my $texps = $texfile;
  677: 	      $texlog =~ s/\.tex/\.log/;
  678: 	      $texaux =~ s/\.tex/\.aux/;
  679: 	      $texdvi =~ s/\.tex/\.dvi/;
  680: 	      $texps =~ s/\.tex/\.ps/;
  681: 	      my @garb = ($texlog,$texaux,$texdvi,$texps);
  682: #	  unlink @garb;
  683: 	      unlink $duefile;
  684: 	      print "<a href=\"/prtspool/$pdf_file\">$link_text - click here to download pdf</a>";
  685: 	      print "\n";
  686: 	  }
  687:       }  
  688:   } else {
  689:       print "LaTeX file $texfile was not created successfully";
  690:   }
  691: }
  692: print "<br />";
  693: if ($number_of_files>1) {
  694:     my $zipfile=$texfile[0];
  695:     $zipfile=~s/\.tex/\.zip/;
  696:     my $statement="zip $zipfile";
  697:     foreach my $file (@texfile) {
  698: 	$file=~s/\.tex/.\pdf/;
  699: 	$statement.=' '.$file; 
  700:     }
  701:     print("<pre>Zip Output:\n");
  702:     system($statement);
  703:     print("</pre>");
  704:     $zipfile=~s/\/home\/httpd//;
  705:     print "<br /> A <a href=\"$zipfile\">ZIP file</a> of all the PDFs.";
  706: }
  707: if ($advanced_role) { &Apache::lonhtmlcommon::Close_PrgWin('',\%prog_state); }
  708: print(&Apache::loncommon::end_page());
  709: my $done;
  710: 
  711: sub REAPER {
  712:     $done=1;
  713: }
  714: 
  715: sub busy_wait_command {
  716:     my ($command,$message,$progress_win,$output_file)=@_;
  717:     
  718:     $SIG{CHLD} = \&REAPER;
  719:     $done=0;
  720:     my $pid=open(CMD,"$command |");
  721:     if ($advanced_role) {
  722: 	&Apache::lonhtmlcommon::Update_PrgWin('',$progress_win,$message);
  723:     }
  724:     while(!$done) {
  725: 	sleep 1;
  726: 	my $extra_msg;
  727: 	if ($output_file) {
  728: 	    my $size=(stat($output_file))[7];
  729: 	    $extra_msg=", $size bytes generated";
  730: 	}
  731: 	if ($advanced_role) {
  732: 	    &Apache::lonhtmlcommon::Update_PrgWin('',$progress_win,
  733: 						  $message.$extra_msg);
  734: 	}
  735:     }
  736:     $SIG{CHLD}='IGNORE';
  737:     close(CMD);
  738: }
  739: 
  740: #  Repagninate
  741: #  What we need to do:
  742: #   - Count the number of pages in each student.
  743: #   - Rewrite the latex file replacing the \specials that
  744: #     mark the end of student with an appropriate number of newlines.
  745: #   parameters:
  746: #     psfile     - Postscript filename
  747: #     latexfile  - LaTeX filename
  748: #     columns    - number of columns.
  749: sub repaginate {
  750: 
  751:     # We will try to do this in 2 passes through the postscript since
  752:     # the postscript is potentially large, to do 2 passes, the first pass
  753:     # must be able to calculate the total number of document pages so that
  754:     # at the beginning of the second pass we already know how to replace
  755:     #  %%Pages:
  756: 
  757:     #  Figure out
  758:     #    1. Number of pages in the document
  759:     #    2. Maximum number of pages in a student
  760:     #    3. Number of pages in each student.
  761: 
  762:     my ($postscript_filename, $latex_filename, $num_columns) = @_;
  763:     open(PSFILE, "<$postscript_filename");
  764:     my $line;
  765:     my $total_pages;		# Total pages in document.
  766:     my $seen_pages        = 0;	# There are several %%Pages only the first is useful
  767:     my @pages_in_student;	# For each student his/her initial page count.
  768:     my $max_pages = 0;		# Pages in 'longest' student.
  769:     my $page_number = 0;
  770:     &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state, 
  771: 					  &mt("Counting pages for student: [_1]",1));
  772: 
  773:     while ($line = <PSFILE>) {
  774: 	
  775: 	# Check for total pages (%%Pages:)
  776: 
  777: 	if (($line =~ /^%%Pages:/) && (!$seen_pages)) {
  778: 	    my @pageinfo = split(/ /,$line);
  779: 	    $total_pages = $pageinfo[1];
  780: 	    $seen_pages  = 1;
  781: 	}
  782: 	#  Check for %%Page: n m  $page_number will be the
  783: 	#  biggest of these until we see an endofstudent.
  784: 	#  Note that minipages generate spurious %Page: 1 1's so
  785: 	#  we only are looking for the largest n (n is page number at the
  786: 	#  bottom of the page, m the page number within the document.
  787: 	#
  788: 
  789: 	if ($line =~ /^%%Page:/) {
  790: 	    my @pageinfo = split(/ /, $line);
  791: 	    if ($page_number < $pageinfo[1]) {
  792: 		$page_number = $pageinfo[1];
  793: 	    } elsif ($pageinfo[2] ne 1) {
  794: 		#  current page count reset, and it's not because of a 
  795: 		#    minipage 
  796: 		# - save the page_number, reset and, if necessary
  797: 		#    update max_pages.
  798: 		push(@pages_in_student, $page_number);
  799: 		&Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state, 
  800: 						      &mt("Counting pages for student: [_1]", scalar(@pages_in_student)));
  801: 		if ($page_number > $max_pages) {
  802: 		    $max_pages = $page_number;
  803: 		}
  804: 		$page_number = $pageinfo[1];
  805: 	    }
  806: 	}
  807: 
  808: 	
  809:     }
  810:     # file ended so one more student
  811:     push(@pages_in_student, $page_number);
  812:     &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state, 
  813: 					  &mt("Counting pages for student: [_1]",scalar(@pages_in_student)));
  814:     if ($page_number > $max_pages) {
  815: 	$max_pages = $page_number;
  816:     }
  817:     $page_number = 0;
  818:     
  819:     close(PSFILE);
  820: 
  821:     #  If 2 columns, max_pages must go to an even number of columns:
  822: 
  823:    
  824:     if ($num_columns == 2) {
  825: 	if ($max_pages % 2) {
  826: 	    $max_pages++;
  827: 	}
  828:     }
  829:     
  830:     #  Now rewrite the LaTex file, substituting our \special
  831:     #  with an appropriate number of \newpage directives.
  832: 
  833:     my $outfilename = $latex_filename."temp";
  834: 
  835:     open(LATEXIN, "<$latex_filename");
  836:     open(LATEXOUT, ">$outfilename");
  837: 
  838: 
  839:     my $student_number    = 0;	# Index of student we're working on.
  840:     &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state, 
  841: 					  "Repaginating student ".$student_number+1);
  842: 
  843:     while (my $line = <LATEXIN>) {
  844: 	if ($line eq "\\special{ps:ENDOFSTUDENTSTAMP}\n") {
  845: 	    # only end of student stamp if next line is ENDOFSTUDENTSTAMP:
  846: 
  847: 
  848: 	    # End of student replace with 0 or more newpages.
  849: 	    
  850: 	    my $addlines = $max_pages - $pages_in_student[$student_number];
  851: 	    while($addlines)  {
  852: 		print LATEXOUT '\clearpage \strut \clearpage';
  853: 
  854: 		$addlines--;
  855: 	    }
  856: 	    
  857: 	    $student_number++;
  858: 	    &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state, 
  859: 						  "Repaginating student ".$student_number+1);
  860: 	    
  861: 	} else {
  862: 	    print LATEXOUT $line;
  863: 	}
  864:     }
  865: 
  866:     close(LATEXIN);
  867:     close(LATEXOUT);
  868:     rename($outfilename, $latex_filename);
  869: 
  870: }
  871: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>