File:  [LON-CAPA] / loncom / interface / printout.pl
Revision 1.161: download - view: text, annotated - select for diffs
Thu Jan 28 19:37:42 2016 UTC (8 years, 3 months ago) by damieng
Branches: MAIN
CVS tags: HEAD
in the last printing page, added a link back to the resource when not authoring, and a link to change options

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

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