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

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

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