File:  [LON-CAPA] / loncom / interface / printout.pl
Revision 1.164: download - view: text, annotated - select for diffs
Sun Jan 29 23:53:55 2017 UTC (7 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_11_2_uiuc, version_2_11_2_educog, version_2_11_2, HEAD
- Escape value of URLback before storing in %env.
- &unescape() was moved from lonnet.pm to LONCAPA.pm in 2006.

    1: #!/usr/bin/perl
    2: # CGI-script to run LaTeX, dvips, ps2ps, ps2pdf etc.
    3: #
    4: # $Id: printout.pl,v 1.164 2017/01/29 23:53:55 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: use lib '/home/httpd/lib/perl';
   30: use LONCAPA::loncgi;
   31: use File::Path;
   32: use File::Basename;
   33: use File::Copy;
   34: use IO::File;
   35: use Image::Magick;
   36: use Apache::lonhtmlcommon();
   37: use Apache::lonnet;
   38: use Apache::loncommon();
   39: use Apache::lonlocal;
   40: use Apache::lonmsg();
   41: use LONCAPA::Enrollment;
   42: use LONCAPA::Configuration;
   43: use LONCAPA;
   44: 
   45: use strict;
   46: 
   47: my $busy_wait_timeout = 30; 
   48: my $pdfs_converted    = 0;	# non zero if PDF includes (need to fixps).
   49: 
   50: my $debugging = 0;
   51: 
   52: sub debug {
   53:     if ($debugging) {
   54: 	my ($text) = @_;
   55: 	print "$text <br />\n";
   56:     }
   57: }
   58: 
   59: #   Determine if a user is operating as a student for this course/domain.
   60: #Parameters:
   61: #    none
   62: #Implicit:
   63: #    $env{request.role} contains the role under which this user operated this
   64: #                       this request.
   65: sub is_student {
   66:     return ($env{'request.role'}=~/^st\./);
   67: }
   68: 
   69: #
   70: #   Debugging:  Dump the environment for debugging.
   71: #
   72: sub dumpenv  {
   73:     print "<br />-------------------<br />";
   74:     foreach my $key (sort (keys %env)) {
   75: 	print "<br />$key -> $env{$key}";
   76:     }
   77:     print "<br />-------------------<br />";
   78: }
   79: 
   80: #
   81: #   This sub sends a message to the appropriate person if there was an error
   82: #   rendering the latex  At present, there's only one case to consider:
   83: #   a student printing inside a course results in messages to the course coordinator.
   84: #Parmaeters:
   85: #    identifier -  The unique identifier of this cgi request.
   86: #    badresource-  Filepath to most likely failing 
   87: #    logfile    -  The contents of the log file (included in the message).
   88: #    texfile    -  reference to an array containing the LaTeX input file
   89: #                  (included in the message).
   90: #Implicit inputs:
   91: #   From the environment:
   92: #       cgi.$identifier.user     - User doing the printing.
   93: #       cgi.$identifier.domain   - Domain the user is logged in on with printing.
   94: #       cgi.$identifier.courseid - Id of the course (if this is a course).
   95: #       cgi.$identifier.coursedom- Domain in which course was constituted.
   96: #       cgi.$identifier.resources - List of resource URL's for which the print
   97: #                                  was attempted.
   98: # 
   99: sub send_error_mail {
  100:     my ($identifier, $badresource, $logfile, $texfile) = @_;
  101:     my $user     = $env{"cgi.$identifier.user"};
  102:     my $domain   = $env{"cgi.$identifier.domain"};
  103:     my $courseid = $env{"cgi.$identifier.courseid"};
  104:     my $coursedom= $env{"cgi.$identifier.coursedom"};
  105:     my $resources= $env{"cgi.$identifier.resources"};
  106: 
  107:     #  resource file->URL
  108:     #
  109:     my $badurl = &Apache::lonnet::declutter($badresource);
  110: 
  111:     # &dumpenv();
  112: 
  113: 
  114: 
  115:     #  Only continue if there is a user, domain, courseid, course domain
  116:     #  and resources:
  117: 
  118:     if(defined($user)       && defined($domain) && defined($courseid) &&
  119:        defined($coursedom)  && defined($resources) ){
  120: 	   
  121: 	#  Only mail if the conditions are ripe for it:
  122: 	#  The user is a student in the course:
  123: 	#
  124: 	
  125: 	if (&is_student()) {
  126: 	    # build the subject and message body:
  127: 	    &debug("sending message to course coordinators.");
  128: 
  129: 	    # Todo: Convert badurl into a url from file path:
  130: 
  131: 	    my $subject  = "Error [$badurl] Print failed for $user".':'.$domain;
  132: 	    my $message .= "Print failed to render LaTeX for $user".':'."$domain\n";
  133: 	    $message    .= "  User was attempting to print: \n";
  134: 	    foreach my $resource (split(/:/,$resources)) {
  135: 		$message    .= "       $resource\n";
  136: 	    }
  137: 	    $message    .= "--------------------LaTeX logfile:------------ \n";
  138: 	    $message    .= $logfile;
  139: 	    $message    .= "-----------------LaTeX source file: ------------\n";
  140: 	    
  141: 	    foreach my $line (@$texfile) {
  142: 		$message .= "$line\n";
  143: 	    }
  144: 	    my (undef, %receivers) = &Apache::lonmsg::decide_receiver(undef, 0,
  145: 								      1,1,1);
  146: 	    &debug("sending...section:  $env{'request.course.sec'}");
  147: 	    foreach my $dest (keys %receivers) {
  148: 		&debug("dest is $dest");
  149: 		my @destinfo = split(/:/,$dest);
  150: 		my $user = $destinfo[0];
  151: 		my $dom  = $destinfo[1];
  152: 
  153: 		&Apache::lonmsg::user_normal_msg($user, $dom,
  154: 						 $subject, $message);
  155: 		
  156: 		# No point in looking at the return status as there's no good
  157: 		# error action I can think of right now (log maybe?).
  158: 	    }
  159: 	}
  160:     }
  161: }
  162: 
  163: $|=1;
  164: if (! &LONCAPA::loncgi::check_cookie_and_load_env()) {
  165:     print <<END;
  166: Content-type: text/html
  167: 
  168: <html>
  169: <head><title>Bad Cookie</title></head>
  170: <body>
  171: Your cookie information is incorrect.
  172: </body>
  173: </html>
  174: END
  175:     exit;
  176: }
  177: 
  178: my %perlvar=%{&LONCAPA::Configuration::read_conf('loncapa.conf')};
  179: &Apache::lonlocal::get_language_handle();
  180: &Apache::loncommon::content_type(undef,'text/html');
  181: $env{'request.noversionuri'} = '/cgi-bin/printout.pl';
  182: # Breadcrumbs
  183: #FIXME: Choose better/different breadcrumbs?!? Links?
  184: my $brcrum = [{'href' => '',
  185:                'text' => 'Helper'}, #FIXME: Different origin possible than print out helper?
  186:               {'href' => '',
  187:                'text' => 'Preparing Printout'},
  188:               {'href' => '',
  189:                'text' => 'Creating PDF'}];
  190: print(&Apache::loncommon::start_page('Creating PDF',
  191:                                      undef,
  192:                                      {'bread_crumbs' => $brcrum,}));
  193: 
  194: my $identifier = $ENV{'QUERY_STRING'};
  195: my $texfile = $env{'cgi.'.$identifier.'.file'};
  196: my $laystyle = $env{'cgi.'.$identifier.'.layout'};
  197: my $numberofcolumns = $env{'cgi.'.$identifier.'.numcol'};
  198: my $paper = $env{'cgi.'.$identifier.'.paper'};
  199: my $selectionmade = $env{'cgi.'.$identifier.'.selection'};
  200: my $tableofcontents = $env{'cgi.'.$identifier.'.tableofcontents'};
  201: my $tableofindex = $env{'cgi.'.$identifier.'.tableofindex'};
  202: my $advanced_role = $env{'cgi.'.$identifier.'.role'};
  203: my $number_of_files = $env{'cgi.'.$identifier.'.numberoffiles'}+1;
  204: my $student_names = $env{'cgi.'.$identifier.'.studentnames'};
  205: my $backref = &unescape($env{'cgi.'.$identifier.'.backref'});
  206: 
  207: 
  208: my @names_pack=();
  209: if ($student_names=~/_END_/) {  
  210:     @names_pack=split(/_ENDPERSON_/,$student_names);
  211: }
  212: if ($backref) {
  213:     print('<p>'.&mt("[_1]Return[_2] to resource.",
  214: 		    "<a href=\"$backref\"><b>","</b></a>").'</p>');
  215:     print('<p><a href="javascript:gopost(\'/adm/printout\',\''.$backref.'\');">'.
  216:         &mt("Change Printing Options").'</a></p>'."\n");
  217: }
  218: my $figfile = $texfile;
  219: $figfile =~ s/^(.*_printout)_\d+_\d+_\d+\.tex/$1\.dat/;
  220: my $duefile = $texfile;
  221: $duefile =~ s/^(.*_printout)_\d+_\d+_\d+\.tex/$1\.due/;
  222: 
  223: 
  224: #-------------------------------------------------------------------------------------
  225: #
  226: #   Each print may have associated with it a file that contains a set of figures
  227: #   that need to be converted to .eps from whatever form they were in when included
  228: #   in the resource.  The name of the figure file is in $figfile.  If it exists,
  229: #   it contains the names of the files that need to be converted, one per line.
  230: #
  231: 
  232: &debug("Figure file is $figfile");
  233: 
  234: if (-e $figfile) {
  235:     &debug( "Figure file exists");
  236:     &debug("$figfile exists");
  237:     my %done_conversion;
  238:     my $temporary_file=IO::File->new($figfile) || die "Couldn't open fig file $figfile for reading: $!\n";
  239:     my @content_of_file = <$temporary_file>;
  240:     close $temporary_file;  
  241:     my $noteps;
  242:     my %prog_state;
  243:     if ($advanced_role) { %prog_state=&Apache::lonhtmlcommon::Create_PrgWin('',$#content_of_file);  }
  244:     print('<br />');
  245:     foreach my $not_eps (@content_of_file) {
  246: 	chomp($not_eps);
  247: 	&debug( "Being asked to convert $not_eps");
  248: 	if ($not_eps ne '') {
  249: 	    $not_eps=~s|\/\.\/|\/|g;
  250: 	    if (!$done_conversion{$not_eps}) { #  Only convert multiple includes once.
  251: 		&convert_figure($not_eps);
  252: 		$done_conversion{$not_eps} = 1;
  253: 	    }
  254: 	}
  255:     }
  256:     if ($advanced_role) { 
  257: 	&Apache::lonhtmlcommon::Close_PrgWin('',\%prog_state); 
  258:     }
  259:     unlink($figfile);
  260: }
  261: #     End of figure conversion section:
  262: #
  263: #--------------------------------------------------------------------------------------------
  264: #
  265: #  Figure out which Tex files we need to process.  If this is a large class e.g.
  266: #  the instructor may have asked that the printout be by section, one section per file
  267: #  in that case, the output tex fiels will be the base filename with 3 digit serial numbers
  268: #  just prior to the .tex file type.
  269: #  By the time this loop exits, @texfile is an array of the files to process.
  270: #
  271: 
  272: my @texfile=($texfile);
  273: if ($number_of_files>1) {
  274:     @texfile=();
  275:     for (my $i=1;$i<=$number_of_files;$i++) {
  276: 	my $new_texfile=$texfile;
  277: 	$new_texfile=~s/\.tex//;
  278: 	$new_texfile = sprintf("%s_%03d.tex", $new_texfile,$i);
  279: 	push @texfile,$new_texfile;
  280:     } 
  281: }
  282: 
  283: #--------------------------------------------------------------------------------------------
  284: 
  285: my $ind=-1;
  286: 
  287: my %prog_state;
  288: if ($advanced_role) { 
  289:     %prog_state=&Apache::lonhtmlcommon::Create_PrgWin('',$number_of_files); 
  290: }
  291: print "<br />";
  292: my $num_files = @texfile;	# How does this differ from $number_of_files , can that be 0?
  293: 
  294: 
  295: 
  296: 
  297: foreach $texfile (@texfile) {
  298:   my $status_statement='';
  299:   my $link_text='download PDF';
  300:   $ind++;
  301: 
  302:   #---------------------------------------------------------------------------------------
  303:   #  This chunk of code 
  304:   #  determines the status message for the printout, and the download link text.
  305:   #  If the print is for one or more students, both will contain the range of students
  306:   #  covered by this file.
  307:   #  
  308: 
  309:   my @stud_info=split(/_END_/,$names_pack[$ind]);
  310:   my @tempo_array=split(/:/,$stud_info[0]);       # username:domain:section:full name:...
  311:   my $name;
  312:   my $name_range='';
  313: 
  314:   # $name       -> Either user's full name or username:domain
  315:   # $name_range -> Either user's last name or username.
  316: 
  317:   if ($tempo_array[3]) {
  318:       $name=$tempo_array[3];
  319:       $name =~ s{^\s+|\s+$}{}g;
  320:       if ($name =~ /,/) { 
  321:           ($name_range) = split(/,/,$name, 2);
  322:       } elsif ($name =~ /\s/) {
  323:           $name_range = $name;
  324:           $name_range =~ s/\s+/_/;
  325:       } else {
  326:           $name_range = $name;  
  327:       }
  328:       $name_range =~ s/[^\w\:\-]+//g;
  329:   } else {
  330:       $name=$tempo_array[0].':'.$tempo_array[1];
  331:       $name_range = $tempo_array[0];
  332:   }
  333: 
  334:   # If there truly is a name add it to the status text so we know which
  335:   # user is getting printed.
  336:   #
  337: 
  338:   if (($name ne "") && ($name ne ':') ) { # Could be printing codes...
  339:       $link_text='<b>'.$name.'</b>';
  340:       $status_statement.=$name;
  341:   }
  342: 
  343:   # Group of students being printed...
  344:   # $name_range -> first student's name - last student's name
  345:   #
  346: 
  347:   if ($#stud_info>0) {
  348:       @tempo_array=split(/:/,$stud_info[-1]);
  349:       if ($tempo_array[3]) {
  350: 	  $name=$tempo_array[3];
  351:           $name =~ s{^\s+|\s+$}{}g;
  352:           my $lastname;
  353:           if ($name =~ /,/) {
  354: 	      ($lastname) = split(/,/, $name,2);
  355:           } elsif ($name =~ /\s/) {
  356:               $lastname = $name;
  357:               $lastname =~ s/\s+/_/;
  358:           } else {
  359:               $lastname = $name;
  360:           }
  361: 	  $name_range .= "-".$lastname;
  362:           $name_range =~ s/[^\w\:\-]+//g;
  363:       } else {
  364: 	  $name=$tempo_array[0].':'.$tempo_array[1];
  365: 	  $name_range .= '-'.$tempo_array[0];
  366:       }
  367:       if (($name ne "") && ($name ne ':')) {
  368: 	  $link_text.=' - <b>'.$name.'</b>';
  369: 	  $status_statement.=' -  '.$name;
  370:   
  371:       }
  372:   }
  373: 
  374:   # $name_range is the range of names in this file.
  375:   # $name is the first of the names in this file.
  376:   #
  377:   #-----------------------------------------------------------------------
  378: 
  379:   #  If the number of files is > 1, but we don't have multiple
  380:   #  student names, we must be printing an exam from codes.
  381:   #  The download link becomes the filename (basename.tex
  382:   #  The status info has the basename appended to it.
  383:   #
  384:   if(($num_files > 1) && ($link_text eq 'download PDF')) {
  385:       $link_text = '<b>'.basename($texfile,'.tex').'.pdf</b>';
  386:       $status_statement .= basename($texfile);
  387:   }
  388: 
  389: 
  390:   #------------------------------------------------------------------------
  391: 
  392:   $name_range =~ s/'//g;	# O'Neil -> ONeil e.g.
  393: 
  394: 
  395:   print "<br/>";
  396:   if ($advanced_role) { 
  397:       &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,&mt('Creating PDF for: [_1]',$status_statement)); 
  398:   }
  399: 
  400:   if (-e $texfile) {		# Ensure the tex file exists:
  401: 
  402:       #---------------------------------------------------------------------
  403:       #
  404:       #  Put username ranges into the original tex
  405:       #  Tex filename from which they'll propagate into the other filenames as well.
  406:       #
  407: 
  408:       if (($name_range ne '') && ($num_files > 1)) {
  409: 	  my $newtexfile = $texfile;
  410: 	  $newtexfile    =~ s/\.tex/$name_range\.tex/;
  411: 	  rename($texfile, $newtexfile);
  412: 	  $texfile       = $newtexfile;
  413:       }
  414: 
  415:       #---------------------------------------------------------------------
  416: 
  417:       $texfile =~ m/^(.*)\/([^\/]+)$/; 
  418:       my $name_file = $2;
  419:       my $path_file = $1.'/';
  420:       chdir $path_file;
  421:       my $dvi_file= $name_file; $dvi_file =~ s/\.tex$/\.dvi/;
  422:       &make_dvi_file($name_file,
  423: 		     $dvi_file,
  424: 		     $tableofcontents,
  425: 		     $tableofindex,
  426: 		     $status_statement,
  427: 		     \%prog_state,
  428: 		     $busy_wait_timeout);
  429: 
  430: 
  431:       #Do we have a latex error in the log file?
  432: 
  433: 
  434:       my $logfilename = $texfile; $logfilename =~ s/\.tex$/\.log/;
  435: 
  436: 
  437:       if (&analyze_logfile($logfilename, $texfile, $advanced_role)) {
  438: 	  
  439: 
  440: 	  #LaTeX successfully parsed tex file 
  441: 	  $name_file =~ s/\.tex/\.dvi/;
  442: 	  my $new_name_file = $name_file;
  443: 	  $new_name_file =~ s/\.dvi/\.ps/;
  444: # Explicitly include a switch for papertype, otherwise dvips will default
  445: # to whatever is listed first in config.ps (which in most cases is a4).
  446: # Historically (since 2004) LON-CAPA printing expected to use the default,
  447: # i.e., a papertype of a4, when the user selected letter [8 1/2 x 11 in] 
  448: # in the Layout options, so I follow that convention if $papera is letter.  
  449: 	  my $papera=$paper;
  450: 	  if ($papera eq 'letter') {$papera='a4';}
  451: 	  if ($papera ne '') {$papera='-t'.$papera;}
  452: 	  my $extra_ps_header = $perlvar{'lonLib'} .'/includepsheader.ps';
  453: 	  my $comma = "dvips $papera -h $extra_ps_header -Ppdf -G0 -o  $new_name_file";
  454: 	  &busy_wait_command("$comma $name_file 1>/dev/null 2>/dev/null",
  455: 			     "for $status_statement now Converting to PS",
  456: 			     \%prog_state,$new_name_file);
  457: 	  #
  458: 	  #  One last little hinky kinky thing.
  459: 	  #  It's just possible that some fonts could not be maded
  460: 	  #  at the resolution of the pdf print driver.
  461: 	  #  In that case a file called missfont.log will have been
  462: 	  #  created that will contain the commands that were attempted
  463: 	  # to create the missing fonts.  If we basically
  464: 	  # take all the 8000 strings in that file, and
  465: 	  # replace them with 600 (the ljfour resolution)
  466: 	  # run the commands in that file and redvips,
  467: 	  # we'll be able to print the missing glyphs at 600dpi.
  468: 	  #
  469: 	  # Supposedly it is possible to tune TeX/Metafont to do this
  470: 	  # right but I failed to get that to work when following the
  471: 	  # docs at the tug site, hence this rather kludgey fix.
  472: 	  #
  473: 
  474: 	  my $print_directory = dirname($name_file);
  475: 	  my $missfonts_file  = $print_directory."/missfont.log";
  476: 	  #print("<br /> Missing fonts file is: $missfonts_file");
  477: 	  if (-e $missfonts_file) {
  478: 	      #print("<br />Missing fonts file exists\n");
  479: 	      &create_missing_fonts($missfonts_file,\%prog_state);
  480: 	      &busy_wait_command("$comma $name_file 1>/dev/null 2>/dev/null",
  481: 				 "for $status_statement dvips generated missing fonts",
  482: 				 \%prog_state, $new_name_file);
  483: 	  }
  484: 	  if (-e $new_name_file) {
  485: 	      my $latex_file = $name_file;
  486: 	      $latex_file =~ s/\.dvi/\.tex/;
  487: 	      &repaginate($new_name_file, $latex_file,  $numberofcolumns);
  488: 
  489: 	      &make_dvi_file($latex_file,
  490: 			     $name_file,
  491: 			     $tableofcontents,
  492: 			     $tableofindex,
  493: 			     $status_statement,
  494: 			     \%prog_state,
  495: 			     $busy_wait_timeout);
  496: 
  497: 
  498: 	      &busy_wait_command("$comma $name_file 1>/dev/null 2>/dev/null",
  499: 				 "for $status_statement dvips to repaginate",
  500: 				 \%prog_state, $new_name_file);
  501: 
  502: 	      print "<br />";
  503: 	      $new_name_file =~ m/^(.*)\./;
  504: 	      my $ps_file = my $tempo_file = $1.'temporar.ps';
  505: 	      my $pdf_file = $1.'.pdf';
  506: 	      $papera=~s/t/p/;
  507: #----
  508: # The code below uses fixps to make pdf include in sequences work.
  509: #
  510: #              $comma = "fixps --force $new_name_file";
  511: #              &debug("FIXPS command: $comma");
  512: #              &busy_wait_command("$comma 1>$tempo_file  2>/dev/null",
  513: #                                 "for $status_statement now validating PS",
  514: #                                 \%prog_state,$tempo_file);
  515: 
  516: #--- 
  517: #  The code below uses gs to make pdf includes in sequences work
  518: 
  519: 	      # Use gs to fix the postscript -> level 1.5 
  520: 	      # .. if pdfs were included
  521: 
  522: 	      if ($pdfs_converted > 0) {
  523: 		  $comma = "gs -sDEVICE=pswrite -dLanguageLevel=1.5 ";
  524: 		  &busy_wait_command("$comma -o $tempo_file $new_name_file 2>/dev/null 1>/dev/null",
  525: 				     "for $status_statement now validating PS",
  526: 				     \%prog_state, $tempo_file);
  527: 		  
  528: #---
  529: 		  &busy_wait_command("mv $tempo_file $new_name_file",
  530: 				     'File move', \%prog_state, $new_name_file);
  531: 	      }
  532: 	      if ($laystyle eq 'album' and $numberofcolumns eq '2') {
  533: 		  $comma = "psnup $papera -2 -s1.0 $new_name_file";
  534: 		  &debug("PSNUP command: $comma");
  535: 		  &busy_wait_command("$comma $tempo_file 1>/dev/null 2>/dev/null",
  536: 				     "for $status_statement now Modifying PS layout",
  537: 				     \%prog_state,$tempo_file);
  538: 	      } elsif ($laystyle eq 'book' and $numberofcolumns eq '2') {
  539: 		  $comma = 'pstops '.$papera.' "2:0+1(0.48w,0)" '.$new_name_file;
  540: 		  &debug("PSTOPS command: $comma ");
  541: 		  &busy_wait_command("$comma $tempo_file 1>/dev/null 2>/dev/null",
  542: 				     "for $status_statement now Modifying PS layout",
  543: 				     \%prog_state,$tempo_file); 
  544: 	      } else {
  545: 		  $ps_file=$new_name_file;
  546: 	      }
  547: 	      my $addtoPSfile={'legal'=>'<< /PageSize [612 1008] >> setpagedevice',
  548:                                'tabloid'=>'<< /PageSize [792 1224] >> setpagedevice',
  549:                                'executive'=>,'<< /PageSize [540 720] >> setpagedevice',
  550:                                'a2'=>'<< /PageSize [1195.02 1690.09] >> setpagedevice',
  551:                                'a3'=>'<< /PageSize [842 1195.02] >> setpagedevice',
  552:                                'a4'=>'<< /PageSize [595.2 842] >> setpagedevice',
  553:                                'a5'=>'<< /PageSize [421.1 595.2] >> setpagedevice',
  554:                                'a6'=>'<< /PageSize [298.75 421.1] >> setpagedevice',
  555: 			   };
  556: 	      if ($paper ne 'letter') {
  557: 		  open(FFH,'<',$ps_file) || die "Couldn't open ps file $ps_file for reading: $!\n";
  558: 		  my $new_ps_file='new'.$ps_file;
  559: 		  open(FFHS,'>',$new_ps_file) || die "Couldn't open new ps file $new_ps_file for reading: $!\n";
  560: 		  print FFHS $addtoPSfile->{$paper}."\n";
  561: 		  while (<FFH>) {
  562: 		      print FFHS $_;
  563: 		  }
  564: 		  close(FFH);
  565: 		  close(FFHS);
  566: 		  $ps_file=$new_ps_file;	  
  567: 	      }
  568: 	      &busy_wait_command("ps2pdf13 $ps_file $pdf_file 1>/dev/null 2>/dev/null",
  569: 				 "for $status_statement now Converting PS to PDF",
  570: 				 \%prog_state,$pdf_file);
  571: 	    
  572: 	      my $texlog = $texfile;
  573: 	      my $texaux = $texfile;
  574: 	      my $texdvi = $texfile;
  575: 	      my $texps = $texfile;
  576: 	      $texlog =~ s/\.tex/\.log/;
  577: 	      $texaux =~ s/\.tex/\.aux/;
  578: 	      $texdvi =~ s/\.tex/\.dvi/;
  579: 	      $texps =~ s/\.tex/\.ps/;
  580: 	      my @garb = ($texlog,$texaux,$texdvi,$texps);
  581: #	  unlink @garb;
  582: 	      unlink($duefile);
  583: 	      print
  584:                   '<p>'
  585:                  .&mt('[_1] - [_2]Your PDF file[_3] is ready for download.',
  586:                       $link_text,'<a href="/prtspool/'.$pdf_file.'">','</a>')
  587:                  .'</p>'."\n";
  588: 	  }
  589: 	  unlink($missfonts_file);
  590: 
  591:       }  
  592:   } else {
  593:       print
  594:           '<p class="LC_error">'
  595:          .&mt('The LaTeX file [_1] was not created successfully.',
  596:               '<span class="LC_filename">'.$texfile.'</span>')
  597:          .'</p>';
  598:   }
  599: }
  600: print "<br />";
  601: if ($number_of_files>1) {
  602:     my $zipfile=$texfile[0];
  603:     $zipfile=~s/\.tex/\.zip/;
  604:     my $statement="zip $zipfile";
  605:     foreach my $file (@texfile) {
  606: 	$file=~s/\.tex/.\pdf/;
  607: 	$statement.=' '.$file; 
  608:     }
  609:     print('<p>'.&mt('Zip Output:')."\n<pre>\n");
  610:     system($statement);
  611:     print("</pre></p>\n");
  612:     $zipfile=~s{^\Q$perlvar{'lonPrtDir'}\E}{/prtspool};
  613:     print
  614:         '<p>'
  615:        .&mt('A [_1]ZIP file[_2] of all the PDF files is ready for download.',
  616:             '<a href="'.$zipfile.'">','</a>')
  617:        .'</p>';
  618: }
  619: if ($advanced_role) { &Apache::lonhtmlcommon::Close_PrgWin('',\%prog_state); }
  620: print(&Apache::loncommon::end_page());
  621: my $done;
  622: 
  623: sub REAPER {
  624:     $done=1;
  625: }
  626: #
  627: #  Execute a command updating the status window as the command's
  628: #  output file builds up (at intervals of a second).
  629: #
  630: #   If the timeout argument defined, then if that many seconds
  631: #   elapses without an increase in the size of the output file,
  632: #   the command will be killed (this deals with the case when
  633: #   latex crawls into an infinite loop).
  634: #
  635: sub busy_wait_command {
  636:     my ($command,$message,$progress_win,$output_file, $timeout)=@_;
  637:     
  638:     $SIG{CHLD} = \&REAPER;
  639:     $done=0;
  640:     my $pid=open(CMD,"$command |");
  641:     if ($advanced_role) {
  642: 	&Apache::lonhtmlcommon::Update_PrgWin('',$progress_win,$message);
  643:     }
  644:     my $last_size      = 0;
  645:     my $unchanged_time = 0;
  646:     while(!$done) {
  647: 	sleep 1;
  648: 	my $extra_msg;
  649: 	if ($output_file) {
  650: 	    my $size=(stat($output_file))[7];
  651: 	    $extra_msg=", $size bytes generated";
  652: 	    if ($size == $last_size) {
  653: 		$unchanged_time++;
  654: 		if ($timeout && ($unchanged_time > $timeout)) {
  655: 		    print '<p class="LC_error">'.&mt('Operation timed out!')."</p>\n";
  656: 		    print "<p>Executing $command, the output file $output_file did not grow\n";
  657: 		    print "after $timeout seconds.  This <em>may</em> indicate $command\n";
  658: 		    print "is in an infinite loop.\n";
  659: 		    print "See if printing fewer copies helps.  Please contact LON-CAPA\n";
  660: 		    print "support about this in any event.";
  661: 		    print "</p>";
  662: 		    kill(9, $pid); # Reaper will do the rest...I hope there's errors in the log.
  663: 		}
  664: 	    } else {
  665: 		$last_size      = $size;
  666: 		$unchanged_time = 0;
  667: 	    }
  668: 	}
  669: 	if ($advanced_role) {
  670: 	    &Apache::lonhtmlcommon::Update_PrgWin('',$progress_win,$message.$extra_msg);
  671: 	}
  672:     }
  673:     $SIG{CHLD}='IGNORE';
  674:     close(CMD);
  675: }
  676: 
  677: # Make the dvi file (or rather try to), from the latex file and the
  678: # various bits and pieces that control how the latex file is processed:
  679: # LaTeX is run as many times a needed to make this all happen... this may
  680: # result in several runs of LaTeX that just are errors if the LaTeX is
  681: # bad, but the printing subsystem is _supposed_ to not do that.
  682: #
  683: # Parameters:
  684: #   name_file        - Name of the LaTeX file to process.
  685: #   dvi_file         - Name of resulting dvi file.
  686: #   tableofcontents  - "yes" if we are supposed to make a table of contents.
  687: #   tableofindex     - "yes" if we are suposed to make an index.
  688: #   status_statement - Part of the status statement for ths status window.
  689: #   prog_state       - Reference to the program state hash.
  690: #   busy_wait_timeout- Seconds without any progress that imply a problem.
  691: #
  692: #
  693: sub make_dvi_file {
  694:     my ($name_file,
  695: 	$dvi_file,
  696: 	$tableofcontents,
  697: 	$tableofindex,
  698: 	$status_statement,
  699: 	$prog_state,
  700: 	$busy_wait_timeout) = @_;
  701:     
  702:     
  703:     &busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
  704: 		       "for $status_statement now LaTeXing file",
  705: 		       $prog_state,$dvi_file, $busy_wait_timeout);
  706: 
  707:     # If the tableof contents was requested, we need to run 
  708:     # LaTex a couple more times to get all the references sorted out.
  709: 
  710:     if ($tableofcontents eq 'yes') {
  711: 	&busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
  712: 			   "for $status_statement First LaTeX of file for table of contents",
  713: 			   $prog_state,$dvi_file, $busy_wait_timeout);
  714: 	&busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
  715: 			   "for $status_statement Second LaTeX of file for table of contents",
  716: 			   $prog_state,$dvi_file,$busy_wait_timeout);
  717:     } 
  718: 
  719:     # And makeindex and another run of LaTeX to incorporate it if the index
  720:     # is enabled.
  721: 
  722: 
  723:     if ($tableofindex eq 'yes') {
  724: 	my $idxname=$name_file;
  725: 	$idxname=~s/\.tex$/\.idx/;
  726: 	&busy_wait_command("makeindex $idxname",
  727: 			   "making index file",
  728: 			   $prog_state,$idxname);
  729: 	&busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
  730: 			   "for $status_statement now LaTeXing file for index section",
  731: 			   $prog_state,$dvi_file, $busy_wait_timeout);
  732:     } 
  733:     
  734: }    
  735: 
  736: 
  737: #  Repagninate
  738: #  What we need to do:
  739: #   - Count the number of pages in each student.
  740: #   - Rewrite the latex file replacing the \specials that
  741: #     mark the end of student with an appropriate number of newlines.
  742: #   parameters:
  743: #     psfile     - Postscript filename
  744: #     latexfile  - LaTeX filename
  745: #     columns    - number of columns.
  746: sub repaginate {
  747: 
  748:     # We will try to do this in 2 passes through the postscript since
  749:     # the postscript is potentially large, to do 2 passes, the first pass
  750:     # must be able to calculate the total number of document pages so that
  751:     # at the beginning of the second pass we already know how to replace
  752:     #  %%Pages:
  753: 
  754:     #  Figure out
  755:     #    1. Number of pages in the document
  756:     #    2. Maximum number of pages in a student
  757:     #    3. Number of pages in each student.
  758: 
  759:     my ($postscript_filename, $latex_filename, $num_columns) = @_;
  760:     open(PSFILE, "<$postscript_filename");
  761:     my $line;
  762:     my $total_pages;		# Total pages in document.
  763:     my $seen_pages        = 0;	# There are several %%Pages only the first is useful
  764:     my @pages_in_student;	# For each student his/her initial page count.
  765:     my $max_pages = 0;		# Pages in 'longest' student.
  766:     my $page_number = 0;
  767:     &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,&mt("Counting pages for student: [_1]",1));
  768: 
  769:     while ($line = <PSFILE>) {
  770: 	
  771: 	# Check for total pages (%%Pages:)
  772: 
  773: 	if (($line =~ /^%%Pages:/) && (!$seen_pages)) {
  774: 	    my @pageinfo = split(/ /,$line);
  775: 	    $total_pages = $pageinfo[1];
  776: 	    $seen_pages  = 1;
  777: 	}
  778: 	#  Check for %%Page: n m  $page_number will be the
  779: 	#  biggest of these until we see an endofstudent.
  780: 	#  Note that minipages generate spurious %Page: 1 1's so
  781: 	#  we only are looking for the largest n (n is page number at the
  782: 	#  bottom of the page, m the page number within the document.
  783: 	#
  784: 
  785: 	if ($line =~ /^%%Page:\s+\d+\s+\d+/) {
  786: 	    my @pageinfo = split(/\s+/, $line);
  787: 	    if ($page_number < $pageinfo[1]) {
  788: 		$page_number = $pageinfo[1];
  789: 	    } elsif ($pageinfo[2] ne 1) {
  790: 		#  current page count reset, and it's not because of a 
  791: 		#    minipage 
  792: 		# - save the page_number, reset and, if necessary
  793: 		#    update max_pages.
  794: 		push(@pages_in_student, $page_number);
  795: 		&Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,&mt("Counting pages for student: [_1]", scalar(@pages_in_student)));
  796: 		if ($page_number > $max_pages) {
  797: 		    $max_pages = $page_number;
  798: 		}
  799: 		$page_number = $pageinfo[1];
  800: 	    }
  801: 	}
  802: 
  803: 	
  804:     }
  805:     # file ended so one more student
  806:     push(@pages_in_student, $page_number);
  807:     &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,&mt("Counting pages for student: [_1]",scalar(@pages_in_student)));
  808:     if ($page_number > $max_pages) {
  809: 	$max_pages = $page_number;
  810:     }
  811:     $page_number = 0;
  812:     
  813:     close(PSFILE);
  814: 
  815:     #  If 2 columns, max_pages must go to an even number of columns:
  816: 
  817:    
  818:     if ($num_columns == 2) {
  819: 	if ($max_pages % 2) {
  820: 	    $max_pages++;
  821: 	}
  822:     }
  823:     
  824:     #  Now rewrite the LaTex file, substituting our \special
  825:     #  with an appropriate number of \newpage directives.
  826: 
  827:     my $outfilename = $latex_filename."temp";
  828: 
  829:     open(LATEXIN, "<$latex_filename");
  830:     open(LATEXOUT, ">$outfilename");
  831: 
  832: 
  833:     my $student_number    = 0;	# Index of student we're working on.
  834:     &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,&mt("Repaginating student: [_1]",$student_number+1));
  835: 
  836:     while (my $line = <LATEXIN>) {
  837: 	if ($line eq "\\special{ps:ENDOFSTUDENTSTAMP}\n") {
  838: 	    # only end of student stamp if next line is ENDOFSTUDENTSTAMP:
  839: 
  840: 
  841: 	    # End of student replace with 0 or more newpages.
  842: 	    
  843: 	    my $addlines = $max_pages - $pages_in_student[$student_number];
  844: 	    while($addlines)  {
  845: 		print LATEXOUT '\clearpage \strut \clearpage';
  846: 
  847: 		$addlines--;
  848: 	    }
  849: 	    
  850: 	    $student_number++;
  851: 	    &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,&mt("Repaginating student: [_1]",$student_number+1));
  852: 	    
  853: 	} else {
  854: 	    print LATEXOUT $line;
  855: 	}
  856:     }
  857: 
  858:     close(LATEXIN);
  859:     close(LATEXOUT);
  860:     rename($outfilename, $latex_filename);
  861: 
  862: }
  863: 
  864: #
  865: #   Create missing fonts given a latex missfonts.log file.
  866: #   This file will have lines like:
  867: #
  868: #   mktexpk --mfmode ljfour --bdpi 8000 --mag 1+0/8000 --dpi 8000 tcrm0500
  869: #
  870: #  We want to execute those lines with the 8000's changed to 600's
  871: #  in order to match the resolution of the ljfour printer.
  872: #  Of course if some wiseguy has changed the default printer from ljfour
  873: #  in the dvips's config.ps file that will break so we'll also
  874: #  ensure that --mfmode is ljfour.
  875: #
  876: sub create_missing_fonts {
  877:     my ($fontfile, $state) = @_;
  878: 
  879:     # Open and read in the font file..we'll read it into the array
  880:     #  font_commands.
  881:     #
  882:     open(my $font_handle, $fontfile);
  883:     my @font_commands = <$font_handle>;
  884: 
  885:     # make the list contain each command only once
  886:     my %uniq;
  887:     @font_commands = map { $uniq{$_}++ == 0 ? $_ : () } @font_commands;
  888: 
  889:     #  Now process each command replacing the appropriate 8000's with
  890:     #  600's ensuring that font names with 8000's in them are not corrupted.
  891:     #  and if the --mfmode is not ljfour we turn it into ljfour.
  892:     #   Then we execute the command.
  893:     #
  894:     
  895:     foreach my $command (@font_commands) {
  896: 	#print("<br />Raw command: $command");
  897: 	$command =~ s/ 8000/ 600/g;    # dpi directives.
  898: 	$command =~ s/\/8000/\/600/g;  # mag directives.
  899: 	#print("<br />After dpi replacements: $command");
  900: 
  901: 	my @cmdarray = split(/ /,$command);
  902: 	for (my $i =0; $i < scalar(@cmdarray); $i++) {
  903: 	    if ($cmdarray[$i] eq '--mfmode') {
  904: 		$cmdarray[$i+1] = "ljfour";
  905: 	    }
  906: 	}
  907: 	#print("<br /> before reassembly : (@cmdarray)");
  908: 	$command = join(" ", (@cmdarray));
  909: 
  910: 	#print("<br />Creating fonts via command: $command");
  911: 	&busy_wait_command("$command 1>/dev/null 2>/dev/null",
  912: 			   "Creating missing font",
  913: 			   $state);
  914: 			   
  915:     }
  916: 
  917: }
  918: #
  919: #  Convert a figure file to encapsulated postscript:
  920: #  At present, this is using a lot of file scoped globals to pass data around. 
  921: # Parameters:
  922: #    not_eps  - The name of the file to convert which, presumably, is not
  923: #               already an eps file.
  924: #
  925: sub convert_figure {
  926:     my ($not_eps) = @_;
  927:     &debug("in convert_figure");
  928: 
  929:     my $status_statement='EPS picture for '.$not_eps;
  930:     my $eps_f = $not_eps;
  931: 
  932:     if ($eps_f=~/\/home\/httpd\/html\/priv\/[^\/]+\/([^\/]+)\//) {
  933: 	$eps_f=~s/\/home\/httpd\/html\/priv\/[^\/]+\/([^\/]+)/$1/;
  934:     } elsif ($eps_f=~/$perlvar{'lonDocRoot'}\/res\//) {
  935: 	$eps_f=~ s/$perlvar{'lonDocRoot'}\/res\/(.+)/$1/;
  936:     } elsif ($eps_f=~/$perlvar{'lonUsersDir'}\//) {
  937: 	$eps_f=~ s/$perlvar{'lonUsersDir'}\/([^\/]+)\/\w\/\w\/\w\/(.+)/$1\/$2/;
  938:     }
  939: 
  940:     $eps_f = $perlvar{'lonPrtDir'}.'/'.$eps_f;
  941: 
  942:     # Spaces are problematic for system commands and LaTeX, replace with _
  943: 
  944:     $eps_f  =~ s/ /\_/g;
  945: 
  946:     # 
  947:     # If the file is already an .eps or .ps file (eps_f still has the original
  948:     # file type),
  949:     # We really just need to copy it from where it was to prtspool
  950:     # but with the spaces substituted to _'s.
  951:     #
  952:     my ($nsname,$path, $sext) = &fileparse($eps_f, qr/\.(ps|eps)/i);
  953:     if ($sext =~/ps$/i) {
  954: 	&File::Path::mkpath($path,0,0777);
  955: 	copy("$not_eps", "$eps_f"); 
  956:     } else {
  957: 	
  958: 	$eps_f .= '.eps';	# Just append the eps ext.
  959: 	my $path= &dirname($eps_f);
  960: 	&File::Path::mkpath($path,0,0777);
  961: 	$not_eps =~ s/^\s+//;
  962: 	$not_eps =~ s/\s+$//;
  963: 	$not_eps =~ s/ /\\ /g;
  964:     my $prettyname=$not_eps;
  965: 	if ($advanced_role) {
  966: 	    $prettyname=~s|$perlvar{'lonDocRoot'}/|/|;
  967: 	    &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,&mt('Converting to EPS: [_1]',$prettyname));
  968: 	}
  969: 	#
  970: 	#  If the file is a PDF, need to use pdftops to convert it to a ps file.
  971: 	#  otherwise use imagemagik:
  972: 	#
  973: 	if($not_eps =~/\.(pdf|PDF)$/) {
  974: 
  975: 	    #
  976: 	    # For whatever reason, pure postscript conversions have to be
  977: 	    # in the same dir as the base file:
  978: 	    #
  979: 	    $eps_f = &basename($eps_f);
  980: 	    $eps_f = $perlvar{'lonPrtDir'}.'/'.$eps_f;
  981: 
  982: 	    &debug("Converting pdf $not_eps to postscript: $eps_f");
  983: 	    system("pdftops $not_eps $eps_f");
  984: 	    $pdfs_converted++;	# Need to fix ps in last pass.
  985: 	} else {
  986: 	    system("convert $not_eps $eps_f");
  987:         if($? and $advanced_role){
  988:             print '<p class="LC_warning">'
  989:                  .&mt('An error occurred during the conversion of [_1].',
  990:                           '<span class="LC_filename">'.$prettyname.'</span>')
  991:                  .'<br />'
  992:                  .&mt('If possible try to save this image using different settings and republish it.')
  993:                  .'</p>';
  994:         }
  995: 	}
  996: 
  997: 	if (not -e $eps_f) {
  998: 	    # converting an animated gif creates either:
  999: 	    # anim.gif.eps.0
 1000: 	    # or
 1001: 	    # anim.gif-0.eps
 1002: 	    for (my $i=0;$i<10000;$i++) {
 1003: 		if (-e $eps_f.'.'.$i) {
 1004: 		    rename($eps_f.'.'.$i, $eps_f);
 1005: 		    last;
 1006: 		}
 1007: 		my $anim_eps = $eps_f;
 1008: 		$anim_eps =~ s/(\.[^.]*)\.eps$/$1-$i\.eps/i;
 1009: 		if (-e $anim_eps) {
 1010: 		    rename($anim_eps, $eps_f);
 1011: 		    last;
 1012: 		}
 1013: 	    }
 1014: 	}
 1015: 	
 1016: 	# imagemagick 6.2.0-6.2.7 fails to properly handle
 1017: 	# convert anim.gif anim.gif.eps
 1018: 	# it creates anim.eps instead. 
 1019: 	if (not -e $eps_f) {
 1020: 	    my $eps_f2 = $eps_f;
 1021: 	    $eps_f2 =~ s/\.[^.]*\.eps$/\.eps/i;
 1022: 	    if(-e $eps_f2) {
 1023: 		rename($eps_f2,$eps_f);
 1024: 	    }
 1025: 	}
 1026:     }
 1027:     
 1028: }
 1029: #
 1030: #   Analyze a LaTeX logfile producing appropriate  output on error and 
 1031: #   returning a boolean to let the caller know if, in our opinion, it's
 1032: #   worth continuing on to produce the PDF file.
 1033: #
 1034: # Parameters:
 1035: #   logfilename   - Name of the logfile.
 1036: #   texfile       - Name of the LaTeX file that was being processed.
 1037: #   advanced_role - True if the user is privileged with respect to the printout
 1038: #                   (e.g. is the course coordinator or some such thing).
 1039: # Returns:
 1040: #    1            - Caller is advised to continue to create the PDF.
 1041: #    0            - Caller need not bother creating the PDF.
 1042: # Side Effects:
 1043: #   Messages are printed to describe any errors that have been encountered.
 1044: # NOTE:
 1045: #    The current policy is to assume that if LaTeX decided to insert some text
 1046: #    it has salvaged the resource and the resource can be printed.. in that case
 1047: #    a message is emitted from this sub.
 1048: #
 1049: sub analyze_logfile {
 1050:     my ($logfilename, $texfile, $advanced_role) = @_;
 1051: 
 1052:     my $temporary_file=IO::File->new($logfilename) || die "Couldn't open log file $logfilename for reading: $!\n";
 1053:     my @content_of_file = <$temporary_file>;
 1054:     close $temporary_file; 
 1055:     my $body_log_file = join(' ',@content_of_file);
 1056:     $logfilename =~ s/\.log$/\.html/;
 1057:     $temporary_file = IO::File->new('>'.$logfilename); 
 1058:     print $temporary_file '<html><head><title>LOGFILE</title></head><body><pre>'.$body_log_file.'</pre></body></html>'."\n";
 1059:     if ($body_log_file=~m/!\s+Emergency stop/) {
 1060: 	my $whereitbegins = rindex $body_log_file,'STAMPOFPASSEDRESOURCESTART';
 1061: 	my $whereitends = rindex $body_log_file,'STAMPOFPASSEDRESOURCEEND';
 1062: 	my $badresource;
 1063: 	my $badtext;
 1064: 	if ($whereitbegins!=-1 and $whereitends!=-1) {
 1065: 	    $badtext = substr($body_log_file,$whereitbegins+26, $whereitends-$whereitbegins-26);
 1066: 	    $whereitbegins  = rindex $badtext,'located in';
 1067: 	    if ($whereitbegins != -1) {
 1068: 		
 1069: 		$badresource = substr($badtext, $whereitbegins+27, 
 1070: 				      length($badtext) - $whereitbegins - 48);
 1071: 		# print "<br />failing resourcename: $badresource<br />";
 1072: 	    }
 1073:         }
 1074: 
 1075: 	# Guys with privileged roles get a more detailed error output:
 1076: 
 1077: 	if ($advanced_role) {  
 1078: 	    #LaTeX failed to parse tex file 
 1079: 	    print "<h2>".&mt('LaTeX could not successfully parse your TeX file.')."</h2>";
 1080: 	    print &mt('It probably has errors in it.')."<br />";
 1081: 	    if ($badtext) {
 1082:                 print &mt('With very high probability this error occurred in [_1].',$badtext)
 1083:                      ."<br /><br />";
 1084:             }
 1085: 	    print &mt('Here are the error messages in the LaTeX log file:')
 1086:                  ."<br /><pre>";
 1087: 	    
 1088: 	    my $sygnal = 0;
 1089: 	    for (my $i=0;$i<=$#content_of_file;$i++) {
 1090: 		if ($content_of_file[$i]=~m/^Runaway argument?/ or $content_of_file[$i]=~m/^!/) {
 1091: 		    $sygnal = 1;
 1092: 		} 
 1093: 		if ($content_of_file[$i]=~m/Here is how much of/) {
 1094: 		    $sygnal = 0;
 1095: 		} 
 1096: 		if ($sygnal) {
 1097: 		    print "$content_of_file[$i]";
 1098: 		}  
 1099: 	    }
 1100: 	    print "</pre>\n";
 1101: 	    # print "<br /> Advanced role <br />";
 1102: 	    $logfilename=~s{^\Q$perlvar{'lonPrtDir'}\E}{/prtspool};
 1103: 	    print "<b><big>"
 1104:                  .&mt('The link to [_1]Your log file[_2]','<a href="'.$logfilename.'">','</a>')
 1105: 	         ."</big></b>\n";
 1106: 	    #link to original LaTeX file
 1107: 	    my $tex_temporary_file=IO::File->new($texfile) || die "Couldn't open tex file $texfile for reading: $!\n";
 1108: 	    my @tex_content_of_file = <$tex_temporary_file>;
 1109: 	    close $tex_temporary_file; 
 1110: 	    my $body_tex_file = join(' ',@tex_content_of_file);
 1111: 	    $texfile =~ s/\.tex$/aaaaa\.html/;
 1112: 	    $tex_temporary_file = IO::File->new('>'.$texfile); 
 1113: 	    print $tex_temporary_file '<html><head><title>LOGFILE</title></head><body><pre>'.$body_tex_file.'</pre></body></html>'."\n";
 1114: 	    print "<br /><br />";
 1115: 	    $texfile=~s{^\Q$perlvar{'lonPrtDir'}\E}{/prtspool};
 1116: 	    print "<b><big>"
 1117:                  .&mt('The link to [_1]Your original LaTeX file[_2]','<a href="'.$texfile.'">','</a>')
 1118: 	         ."</big></b><br /><br />\n";
 1119: 	    my $help_text = &Apache::loncommon::help_open_topic("Print_Resource", &mt('Help on printing'));
 1120: 	    print ("$help_text");
 1121: 
 1122: 	    # Students on the other hand get a minimal error message, since they won't
 1123: 	    # be able to correct the error message. A message is sent to the 
 1124: 	    # instructor:
 1125: 
 1126: 	} else {		# Student role...
 1127: 	    #  at this point:
 1128: 	    #    $body_log_file - contains the log file.
 1129: 	    #    $name_file     - is the name of the LaTeX file.
 1130: 	    #    $identifier    - is the unique LaTeX identifier.l
 1131: 	    
 1132:             print '<p class="LC_error">';
 1133: 	    if ($badtext) {
 1134:                 print &mt('There are errors in [_1].',$badtext);
 1135:             } else {
 1136:                 print &mt('There are errors.');
 1137:             }
 1138:             print '</p>'
 1139:                  .&mt('These errors prevent this resource from printing correctly.');
 1140: 
 1141: 	    my $tex_handle = IO::File->new($texfile);
 1142: 	    my @tex_contents = <$tex_handle>;
 1143: 	    &send_error_mail($identifier, $badresource, $body_log_file, \@tex_contents);
 1144: 	    print "<p>"
 1145:                  .&mt('A message has been sent to the instructor describing this failure.')
 1146:                  ."</p>";
 1147: 	    my $help_text = &Apache::loncommon::help_open_topic("Print_Resource", &mt('Help on printing'));
 1148: 	    print  ("$help_text");
 1149: 	    
 1150: 	  }
 1151: 
 1152: 	# Either way, an emergency stop does not allow us to continue so:
 1153: 
 1154: 	return 0;
 1155: 	
 1156: 	# The branch of code below is taken if it appears that 
 1157: 	# there was no emergency stop but LaTeX had to correct the
 1158: 	# input file to run.
 1159: 	# In that case we need to provide error feedback, as the correction >may< not be
 1160: 	# sufficient, we can let the game continue as there's a dvi file to process.
 1161: 
 1162:     } elsif ($body_log_file=~m/<inserted text>/) {
 1163: 	my $whereitbegins = index $body_log_file,'<inserted text>';
 1164: 	print &mt('You are running LaTeX in [_1]batch mode[_2].','<b>','</b>');
 1165: 	while ($whereitbegins != -1) {
 1166: 	    my $tempobegin=$whereitbegins;
 1167: 	    $whereitbegins = rindex $body_log_file,'STAMPOFPASSEDRESOURCESTART',$whereitbegins;
 1168: 	    my $whereitends = index $body_log_file,'STAMPOFPASSEDRESOURCEEND',$whereitbegins;
 1169: 	    print "<br />"
 1170:                  .&mt('It has found an error in [_1][_2]and corrected it.',substr($body_log_file,$whereitbegins+26,$whereitends-$whereitbegins-26),"<br />")."\n";
 1171: 	    print &mt('Usually this correction is valid but you probably need to check the indicated resource one more time and implement necessary corrections by yourself.')."\n";
 1172: 	    $whereitbegins = index $body_log_file,'<inserted text>',$tempobegin+10;
 1173: 	}
 1174: 
 1175: 	if ($advanced_role) {  
 1176: 	    print "<br /><br />";
 1177: 	    $logfilename=~s{^\Q$perlvar{'lonPrtDir'}\E}{/prtspool};
 1178: 	    print "<b><big>"
 1179:                  .&mt('The link to [_1]Your log file[_2]'
 1180:                      ,'<a href="'.$logfilename.'">','</a>')
 1181: 	         ."</big></b>\n";
 1182: 	    #link to original LaTeX file
 1183: 	    my $tex_temporary_file=IO::File->new($texfile) || die "Couldn't open tex file $texfile for reading: $!\n";
 1184: 	    my @tex_content_of_file = <$tex_temporary_file>;
 1185: 	    close $tex_temporary_file; 
 1186: 	    my $body_tex_file = join(' ',@tex_content_of_file);
 1187: 	    $texfile =~ s/\.tex$/aaaaa\.html/;
 1188: 	    $tex_temporary_file = IO::File->new('>'.$texfile); 
 1189: 	    print $tex_temporary_file '<html><head><title>LOGFILE</title></head><body><pre>'.$body_tex_file.'</pre></body></html>'."\n";
 1190: 	    print "<br /><br />";
 1191: 	    $texfile=~s{^\Q$perlvar{'lonPrtDir'}\E}{/prtspool};
 1192: 	    print "<b><big>"
 1193:                   .&mt('The link to [_1]Your original LaTeX file[_2]','<a href="'.$texfile.'">','</a>');
 1194: 	    print "</big></b>\n";
 1195: 	}
 1196: 	return 1;
 1197:     }
 1198:     return 1;			# NO log file issues at all.
 1199: }

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