Annotation of loncom/interface/printout.pl, revision 1.172

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

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