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

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

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