File:  [LON-CAPA] / loncom / interface / printout.pl
Revision 1.177: download - view: text, annotated - select for diffs
Sat Nov 9 16:08:15 2024 UTC (3 months, 1 week ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, version_2_11_X, version_2_11_6_msu, version_2_11_6, HEAD
- Bug 6880
- Reduce amount of vertical space at top of each page for RHEL/Oracle/CentOS
  7 or later.
- Twelve combinations of orientation (portrait or landscape), columns (1 or 2),
  paper (letter, legal or a4) now supported.
- Use pstops instead of psnup for 2-column landscape for newer psnup version 2
  which does not support scale arg (RHEL/Oracle/Alma/Rocky/CentOS-Stream 9).

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

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