File:  [LON-CAPA] / loncom / interface / printout.pl
Revision 1.110: download - view: text, annotated - select for diffs
Thu Sep 14 17:04:42 2006 UTC (17 years, 7 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#5017, extra page at end of printing when priting multiple users

    1: #!/usr/bin/perl
    2: # CGI-script to run LaTeX, dvips, ps2ps, ps2pdf etc.
    3: #
    4: #
    5: # Copyright Michigan State University Board of Trustees
    6: #
    7: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    8: #
    9: # LON-CAPA is free software; you can redistribute it and/or modify
   10: # it under the terms of the GNU General Public License as published by
   11: # the Free Software Foundation; either version 2 of the License, or
   12: # (at your option) any later version.
   13: #
   14: # LON-CAPA is distributed in the hope that it will be useful,
   15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   17: # GNU General Public License for more details.
   18: #
   19: # You should have received a copy of the GNU General Public License
   20: # along with LON-CAPA; if not, write to the Free Software
   21: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   22: #
   23: # /home/httpd/html/adm/gpl.txt
   24: #
   25: # http://www.lon-capa.org/
   26: #
   27: 
   28: use lib '/home/httpd/lib/perl';
   29: use LONCAPA::loncgi;
   30: use File::Path;
   31: use File::Basename;
   32: use IO::File;
   33: use Image::Magick;
   34: use Apache::lonhtmlcommon();
   35: use Apache::lonnet;
   36: use Apache::loncommon();
   37: use Apache::lonlocal;
   38: use Apache::lonmsg();
   39: use LONCAPA::Enrollment;
   40: 
   41: use strict;
   42: 
   43: 
   44: #   Determine if a user is operating as a student for this course/domain.
   45: #Parameters:
   46: #    none
   47: #Implicit:
   48: #    $env{request.role} contains the role under which this user operated this
   49: #                       this request.
   50: sub is_student {
   51:     return ($env{'request.role'}=~/^st\./);
   52: }
   53: 
   54: #
   55: #   Debugging:  Dump the environment for debugging.
   56: #
   57: sub dumpenv  {
   58:     print "<br />-------------------<br />";
   59:     foreach my $key (sort (keys %env)) {
   60: 	print "<br />$key -> $env{$key}";
   61:     }
   62:     print "<br />-------------------<br />";
   63: }
   64: 
   65: #
   66: #   This sub sends a message to the appropriate person if there was an error
   67: #   rendering the latex  At present, there's only one case to consider:
   68: #   a student printing inside a course results in messages to the course coordinator.
   69: #Parmaeters:
   70: #    identifier -  The unique identifier of this cgi request.
   71: #    badresource-  Filepath to most likely failing 
   72: #    logfile    -  The contents of the log file (included in the message).
   73: #    texfile    -  reference to an array containing the LaTeX input file
   74: #                  (included in the message).
   75: #Implicit inputs:
   76: #   From the environment:
   77: #       cgi.$identifier.user     - User doing the printing.
   78: #       cgi.$identifier.domain   - Domain the user is logged in on with printing.
   79: #       cgi.$identifier.courseid - Id of the course (if this is a course).
   80: #       cgi.$identifier.coursedom- Domain in which course was constituted.
   81: #       cgi.$identifier.resources - List of resource URL's for which the print
   82: #                                  was attempted.
   83: # 
   84: sub send_error_mail {
   85:     my ($identifier, $badresource, $logfile, $texfile) = @_;
   86:     my $user     = $env{"cgi.$identifier.user"};
   87:     my $domain   = $env{"cgi.$identifier.domain"};
   88:     my $courseid = $env{"cgi.$identifier.courseid"};
   89:     my $coursedom= $env{"cgi.$identifier.coursedom"};
   90:     my $resources= $env{"cgi.$identifier.resources"};
   91: 
   92:     #  resource file->URL
   93:     #
   94:     my $badurl = &Apache::lonnet::declutter($badresource);
   95: 
   96:     # &dumpenv();
   97: 
   98: 
   99: 
  100:     #  Only continue if there is a user, domain, courseid, course domain
  101:     #  and resources:
  102: 
  103:     if(defined($user)       && defined($domain) && defined($courseid) &&
  104:        defined($coursedom)  && defined($resources) ){
  105: 	   
  106: 	#  Only mail if the conditions are ripe for it:
  107: 	#  The user is a student in the course:
  108: 	#
  109: 	
  110: 	if (&is_student()) {
  111: 	    # build the subject and message body:
  112: 	    # print "sending message to course coordinators.<br />";
  113: 
  114: 	    # Todo: Convert badurl into a url from file path:
  115: 
  116: 	    my $subject  = "Error [$badurl] Print failed for $user".'@'.$domain;
  117: 	    my $message .= "Print failed to render LaTeX for $user".'@'."$domain\n";
  118: 	    $message    .= "  User was attempting to print: \n";
  119: 	    foreach my $resource (split(/:/,$resources)) {
  120: 		$message    .= "       $resource\n";
  121: 	    }
  122: 	    $message    .= "--------------------LaTeX logfile:------------ \n";
  123: 	    $message    .= $logfile;
  124: 	    $message    .= "-----------------LaTeX source file: ------------\n";
  125: 	    
  126: 	    foreach my $line (@$texfile) {
  127: 		$message .= "$line\n";
  128: 	    }
  129: 	    my (undef, %receivers) = &Apache::lonfeedback::decide_receiver(undef, 0,
  130: 									  1,1,1);
  131: 	    # print "<br /> sending...section:  $env{'request.course.sec'}";
  132: 	    foreach my $dest (keys %receivers) {
  133: 		# print "<br /> dest is $dest";
  134: 		my @destinfo = split(/:/,$dest);
  135: 		my $user = $destinfo[0];
  136: 		my $dom  = $destinfo[1];
  137: 
  138: 		&Apache::lonmsg::user_normal_msg($user, $dom,
  139: 						 $subject, $message);
  140: 		
  141: 		# No point in looking at the return status as there's no good
  142: 		# error action I can think of right now (log maybe?).
  143: 	    }
  144: 	}
  145:     }
  146: }
  147: 
  148: $|=1;
  149: if (! &LONCAPA::loncgi::check_cookie_and_load_env()) {
  150:     print <<END;
  151: Content-type: text/html
  152: 
  153: <html>
  154: <head><title>Bad Cookie</title></head>
  155: <body>
  156: Your cookie information is incorrect.
  157: </body>
  158: </html>
  159: END
  160:     return;
  161: }
  162:  &Apache::lonlocal::get_language_handle();
  163:  &Apache::loncommon::content_type(undef,'text/html');
  164: 
  165:   print(&Apache::loncommon::start_page('Creating PDF'));
  166: 
  167:   my $identifier = $ENV{'QUERY_STRING'};
  168:   my $texfile = $env{'cgi.'.$identifier.'.file'};
  169:   my $laystyle = $env{'cgi.'.$identifier.'.layout'};
  170:   my $numberofcolumns = $env{'cgi.'.$identifier.'.numcol'};
  171:   my $paper = $env{'cgi.'.$identifier.'.paper'};
  172:   my $selectionmade = $env{'cgi.'.$identifier.'.selection'};
  173:   my $tableofcontents = $env{'cgi.'.$identifier.'.tableofcontents'};
  174:   my $tableofindex = $env{'cgi.'.$identifier.'.tableofindex'};
  175:   my $advanced_role = $env{'cgi.'.$identifier.'.role'};
  176:   my $number_of_files = $env{'cgi.'.$identifier.'.numberoffiles'}+1;
  177:   my $student_names = $env{'cgi.'.$identifier.'.studentnames'};
  178:   my $backref = &Apache::lonnet::unescape($env{'cgi.'.$identifier.'.backref'});
  179: 
  180:   
  181:   my @names_pack=();
  182:   if ($student_names=~/_END_/) {  
  183:       @names_pack=split(/_ENDPERSON_/,$student_names);
  184:   }
  185: 
  186: print "<a href=\"$backref\"><b>Return</b></a> to last resource.<br /><br />";
  187: 
  188:   my $figfile = $texfile;
  189:   $figfile =~ s/^([^\.]+printout)[^t]+\.tex/$1\.dat/;
  190:   my $duefile = $texfile;
  191:   $duefile =~ s/^([^\.]+printout)[^t]+\.tex/$1\.due/;
  192:   #do we have figures?
  193:   # print "Figure file: $figfile\n";
  194:   if (-e $figfile) {
  195:       # print "$figfile exists\n";
  196:       my %done_conversion;
  197:       my $temporary_file=IO::File->new($figfile) || die "Couldn't open fig file $figfile for reading: $!\n";
  198:       my @content_of_file = <$temporary_file>;
  199:       close $temporary_file;  
  200:       my $noteps;
  201:       my %prog_state;
  202:       if ($advanced_role) { %prog_state=&Apache::lonhtmlcommon::Create_PrgWin('','Coverting Images to EPS','Picture Conversion Status',$#content_of_file,'inline','80');  }
  203:       print('<br />');
  204:       foreach my $not_eps (@content_of_file) {
  205: 	  chomp($not_eps);
  206: 	  if ($not_eps ne '') {
  207: 	      # print "Converting $not_eps"; # Debugging.
  208:               my $status_statement='EPS picture for '.$not_eps;
  209: 	      # print "$status_statement\n";
  210: 	      $not_eps=~s|\/\.\/|\/|g;
  211: 	      my $eps_f = $not_eps;
  212: 	      # $eps_f =~ s/\.[^.]*$/\.eps/i;
  213: 	      $eps_f .= '.eps';	# Just append the eps ext.
  214: 	      if ($eps_f=~/\/home\/([^\/]+)\/public_html\//) {
  215:                   $eps_f=~s/\/home\/([^\/]+)\/public_html/$1/;
  216: 		  $eps_f = '/home/httpd/prtspool/'.$eps_f;
  217: 	      } elsif ($eps_f=~/$Apache::lonnet::perlvar{'lonDocRoot'}\/res\//) {
  218: 		  $eps_f=~m/$Apache::lonnet::perlvar{'lonDocRoot'}\/res\/(.+)/;
  219: 		  $eps_f = '/home/httpd/prtspool/'.$1;
  220: 	      } elsif ($eps_f=~/$Apache::lonnet::perlvar{'lonUsersDir'}\//) {
  221: 		  $eps_f=~/$Apache::lonnet::perlvar{'lonUsersDir'}\/([^\/]+)\/\w\/\w\/\w\/(.+)/;
  222: 		  $eps_f = '/home/httpd/prtspool/'.$1.'/'.$2;
  223: 	      }
  224: 	      $eps_f  =~ s/ /\_/g; # Spaces are problematic for system commands and LaTeX.
  225: 	      my $path=$eps_f;
  226: 	      $path =~ s/\/([^\/]+)\.eps$//;
  227: 	      # print "Final file path: $path "; # Debugging
  228: 	      File::Path::mkpath($path,0,0777);
  229: 	      $not_eps =~ s/^\s+//;
  230: 	      $not_eps =~ s/\s+$//;
  231: 	      $not_eps =~ s/ /\\ /g;
  232: 	      if ( exists($done_conversion{$not_eps})) { next; }
  233: 	      if ($advanced_role) {
  234: 		  my $prettyname=$not_eps;
  235: 		  $prettyname=~s|/home/([^/]+)/public_html|/priv/$1|;
  236: 		  $prettyname=~s|$Apache::lonnet::perlvar{'lonDocRoot'}/|/|;
  237: 		  &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,
  238: 							'Converting to EPS '.$prettyname);
  239: 	      }
  240: 	      $done_conversion{$not_eps}=1;
  241: 	      # print "Converting $not_eps -> $eps_f"; # Debugging
  242: 	      system("convert $not_eps $eps_f");
  243:               # check is eps exist in prtspool
  244:               if (not -e $eps_f) {
  245: 		  # converting an animated gif creates either:
  246:                   # anim.gif.eps.0
  247:                   # or
  248:                   # anim.gif-0.eps
  249: 		  for (my $i=0;$i<10000;$i++) {
  250: 		      if (-e $eps_f.'.'.$i) {
  251: 			  rename($eps_f.'.'.$i, $eps_f);
  252: 			  last;
  253: 		      }
  254: 		      my $anim_eps = $eps_f;
  255: 		      $anim_eps =~ s/(\.[^.]*)\.eps$/$1-$i\.eps/i;
  256: 		      if (-e $anim_eps) {
  257: 			  rename($anim_eps, $eps_f);
  258: 			  last;
  259: 		      }
  260: 		  }
  261: 	      }
  262: 	      # imagemagick 6.2.0-6.2.7 fails to properly handle
  263:               # convert anim.gif anim.gif.eps
  264:               # it creates anim.eps instead. 
  265:               if (not -e $eps_f) {
  266: 		  my $eps_f2 = $eps_f;
  267: 		  $eps_f2 =~ s/\.[^.]*\.eps$/\.eps/i;
  268: 		  if(-e $eps_f2) {
  269: 		      rename($eps_f2,$eps_f);
  270: 		  }
  271: 	      }
  272: 
  273: 	  }
  274:       }
  275:       if ($advanced_role) { 
  276: 	  &Apache::lonhtmlcommon::Close_PrgWin('',\%prog_state); 
  277:       }
  278:       unlink($figfile);
  279:   }
  280:   #print "$texfile\n"; #name of the tex file for debugging only   
  281:   my @texfile=($texfile);
  282:   if ($number_of_files>1) {
  283:       @texfile=();
  284:       for (my $i=1;$i<=$number_of_files;$i++) {
  285: 	  my $new_texfile=$texfile;
  286: 	  $new_texfile=~s/\.tex//;
  287: 	  $new_texfile = sprintf("%s_%03d.tex", $new_texfile,$i);
  288: 	  push @texfile,$new_texfile;
  289:       } 
  290:   }
  291: 
  292: my $ind=-1;
  293: my %prog_state;
  294: if ($advanced_role) { %prog_state=&Apache::lonhtmlcommon::Create_PrgWin('','Print Status','Class Print Status',$number_of_files,'inline','80'); }
  295: print "<br />";
  296: my $num_files = @texfile;
  297: foreach $texfile (@texfile) {
  298:   my $status_statement='';
  299:   my $link_text='download PDF';
  300:   $ind++;
  301:   my @stud_info=split(/_END_/,$names_pack[$ind]);
  302:   my @tempo_array=split(/:/,$stud_info[0]);
  303:   my $name;
  304:   my $name_range='';
  305:   if ($tempo_array[3]) {
  306:       $name=$tempo_array[3];
  307:       ($name_range) = split(/,/,$name, 2);
  308:   } else {
  309:       $name=$tempo_array[0].'@'.$tempo_array[1];
  310:       $name_range = $tempo_array[0];
  311:   }
  312:   if (($name ne "") && ($name ne '@') ) { # Could be printing codes...
  313:       $link_text='<b>'.$name.'</b>';
  314:       $status_statement.=$name;
  315:   }
  316:   if ($#stud_info>0) {
  317:       @tempo_array=split(/:/,$stud_info[-1]);
  318:       if ($tempo_array[3]) {
  319: 	  $name=$tempo_array[3];
  320: 	  my ($lastname) = split(/,/, $name,2);
  321: 	  $name_range .= "-".$lastname;
  322:       } else {
  323: 	  $name=$tempo_array[0].'@'.$tempo_array[1];
  324: 	  $name_range .= '-'.$tempo_array[0];
  325:       }
  326:       if (($name ne "") && ($name ne '@')) {
  327: 	  $link_text.=' - <b>'.$name.'</b>';
  328: 	  $status_statement.=' -  '.$name;
  329:   
  330:       }
  331:   }
  332:   if(($num_files > 1) && ($link_text eq 'download PDF')) { # Printing codes
  333:       $link_text = '<b>'.basename($texfile,'.tex').'.pdf</b>';
  334:       $status_statement .= basename($texfile);
  335:   }
  336:   $name_range =~ s/'//g;	# O'Neil -> ONeil e.g.
  337:   print "<br/>";
  338:   if ($advanced_role) { &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,'Creating PDF for '.$status_statement); }
  339:   #  This little piece of dirt puts username ranges into the original tex
  340:   #  Tex filename from which they'll propagate into the other filenames as well.
  341:   #
  342:   if (-e $texfile) {
  343:       if (($name_range ne '') && ($num_files > 1)) {
  344: 	  my $newtexfile = $texfile;
  345: 	  $newtexfile    =~ s/\.tex/$name_range\.tex/;
  346: 	  rename($texfile, $newtexfile);
  347: 	  $texfile       = $newtexfile;
  348:       }
  349:       $texfile =~ m/^(.*)\/([^\/]+)$/; 
  350:       my $name_file = $2;
  351:       my $path_file = $1.'/';
  352:       chdir $path_file;
  353:       my $dvi_file= $name_file; $dvi_file =~ s/\.tex/$name_range\.dvi/;
  354:       &busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
  355: 			 "for $status_statement now LaTeXing file",
  356: 			 \%prog_state,$dvi_file);
  357:       if ($tableofcontents eq 'yes') {
  358:       &busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
  359: 			 "for $status_statement First LaTeX of file for table of contents",
  360: 			 \%prog_state,$dvi_file);
  361:       &busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
  362: 			 "for $status_statement Second LaTeX of file for table of contents",
  363: 			 \%prog_state,$dvi_file);
  364:       } #to create table of contents
  365:       my $idxname=$name_file;
  366:       $idxname=~s/\.tex$/\.idx/;
  367:       if ($tableofindex eq 'yes') {
  368: 	  &busy_wait_command("makeindex $idxname",
  369: 			     "making index file",
  370: 			     \%prog_state,$idxname);
  371: 	  &busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
  372: 			     "for $status_statement now LaTeXing file for index section",
  373: 			     \%prog_state,$dvi_file);
  374:       } #to create index
  375:       #Do we have a latex error in the log file?
  376:       my $logfilename = $texfile; $logfilename =~ s/\.tex$/\.log/;
  377:       my $temporary_file=IO::File->new($logfilename) || die "Couldn't open log file $logfilename for reading: $!\n";
  378:       my @content_of_file = <$temporary_file>;
  379:       close $temporary_file; 
  380:       my $body_log_file = join(' ',@content_of_file);
  381:       $logfilename =~ s/\.log$/\.html/;
  382:       $temporary_file = IO::File->new('>'.$logfilename); 
  383:       print $temporary_file '<html><head><title>LOGFILE</title></head><body><pre>'.$body_log_file.'</pre></body></html>'."\n";
  384:       if ($body_log_file=~m/!\s+Emergency stop/) {
  385: 	  my $whereitbegins = rindex $body_log_file,'STAMPOFPASSEDRESOURCESTART';
  386: 	  my $whereitends = rindex $body_log_file,'STAMPOFPASSEDRESOURCEEND';
  387: 	  my $badresource;
  388: 	  my $badtext;
  389: 	  if ($whereitbegins!=-1 and $whereitends!=-1) {
  390: 	      $badtext = substr($body_log_file,$whereitbegins+26, $whereitends-$whereitbegins-26);
  391: 	      $whereitbegins  = rindex $badtext,'located in';
  392: 	      if ($whereitbegins != -1) {
  393: 		  
  394: 		  $badresource = substr($badtext, $whereitbegins+27, 
  395: 					length($badtext) - $whereitbegins - 48);
  396: 		  # print "<br />failing resourcename: $badresource<br />";
  397: 	      }
  398: 	  }
  399: 	  
  400:           if ($advanced_role) {  
  401: 	      #LaTeX failed to parse tex file 
  402: 	      print "<h2>LaTeX could not successfully parse your tex file.</h2>";
  403: 	      print "It probably has errors in it.<br />";
  404: 	      print "With very high probability this error occured in ".$badtext."<br /><br />";
  405: 	      print "Here are the error messages in the LaTeX log file<br /><pre>";
  406: 
  407: 	      my $sygnal = 0;
  408: 	      for (my $i=0;$i<=$#content_of_file;$i++) {
  409: 		  if ($content_of_file[$i]=~m/^Runaway argument?/ or $content_of_file[$i]=~m/^!/) {
  410: 		      $sygnal = 1;
  411: 		  } 
  412: 		  if ($content_of_file[$i]=~m/Here is how much of/) {
  413: 		      $sygnal = 0;
  414: 		  } 
  415: 		  if ($sygnal) {
  416: 		      print "$content_of_file[$i]";
  417: 		  }  
  418: 	      }
  419: 	      print "</pre>\n";
  420: 	      # print "<br /> Advanced role <br />";
  421:               print "<b><big>The link to ";
  422:               $logfilename=~s/\/home\/httpd//;
  423: 	      print "<a href=\"$logfilename\">Your log file </a></big></b>";
  424: 	      print "\n";
  425:               #link tooriginal LaTeX file (included according Michael Hamlin desire)
  426: 	      my $tex_temporary_file=IO::File->new($texfile) || die "Couldn't open tex file $texfile for reading: $!\n";
  427: 	      my @tex_content_of_file = <$tex_temporary_file>;
  428: 	      close $tex_temporary_file; 
  429: 	      my $body_tex_file = join(' ',@tex_content_of_file);
  430: 	      $texfile =~ s/\.tex$/aaaaa\.html/;
  431: 	      $tex_temporary_file = IO::File->new('>'.$texfile); 
  432: 	      print $tex_temporary_file '<html><head><title>LOGFILE</title></head><body><pre>'.$body_tex_file.'</pre></body></html>'."\n";
  433: 	      print "<br /><br />";
  434: 	      print "<b><big>The link to ";
  435: 	      $texfile=~s/\/home\/httpd//;
  436: 	      print "<a href=\"$texfile\">Your original LaTeX file </a></big></b>";
  437: 	      print "\n";
  438: 	      my $help_text = &Apache::loncommon::help_open_topic("Print_Resource", "Help on printing");
  439: 	      print ("$help_text");
  440: 
  441: 	  } else {		# Student role...
  442: 	      #  at this point:
  443: 	      #    $body_log_file - contains the log file.
  444:               #    $name_file     - is the name of the LaTeX file.
  445:               #    $identifier    - is the unique LaTeX identifier.l
  446: 
  447: 	      print "<br />There are errors in $badtext";
  448: 	      print "<br />These errors prevent this resource from printing correctly";
  449: 	      my $tex_handle = IO::File->new($name_file);
  450: 	      my @tex_contents = <$tex_handle>;
  451: 	      &send_error_mail($identifier, $badresource, $body_log_file, \@tex_contents);
  452: 	      print "<br />A message has been sent to the instructor describing this failure<br />";
  453: 	      my $help_text = &Apache::loncommon::help_open_topic("Print_Resource", "Help on printing");
  454: 	      print  ("$help_text");
  455: 
  456: 	  }
  457: 
  458:       } elsif ($body_log_file=~m/<inserted text>/) {
  459: 	  my $whereitbegins = index $body_log_file,'<inserted text>';
  460: 	  print "You are running LaTeX in <b>batch mode</b>.";
  461: 	  while ($whereitbegins != -1) {
  462: 	      my $tempobegin=$whereitbegins;
  463: 	      $whereitbegins = rindex $body_log_file,'STAMPOFPASSEDRESOURCESTART',$whereitbegins;
  464: 	      my $whereitends = index $body_log_file,'STAMPOFPASSEDRESOURCEEND',$whereitbegins;
  465: 	      print "<br />It has found an error in".substr($body_log_file,$whereitbegins+26,$whereitends-$whereitbegins-26)." <br /> and corrected it.\n";
  466: 	      print "Usually this correction is valid but you probably need to check the indicated resource one more time and implement neccessary corrections by yourself.\n";
  467: 	      $whereitbegins = index $body_log_file,'<inserted text>',$tempobegin+10;
  468: 	  }
  469: 	  $name_file =~ s/\.tex/\.dvi/;
  470: 	  my $new_name_file = $name_file;
  471: 	  $new_name_file =~ s/\.dvi/\.ps/;
  472: 	  my $papera=$paper;
  473: 	  if ($papera eq 'letter') {$papera='';}
  474: 	  if ($papera ne '') {$papera='-t'.$papera;}
  475: 	  my $comma = "dvips $papera -Ppdf -G0 -o $new_name_file";
  476: 	  &busy_wait_command("$comma $name_file 1>/dev/null 2>/dev/null",
  477: 			     "for $status_statement now Converting to PS",
  478: 			     \%prog_state,$new_name_file);
  479: 	  if (-e $new_name_file) {
  480: 	      my $latex_file = $name_file;
  481: 	      $latex_file    =~ s/\.dvi/\.tex/;
  482: 	      &repaginate($new_name_file, $latex_file, $numberofcolumns);
  483: 	      #
  484: 	      #  Now have to re-latex, re dvips again to 
  485: 	      #  get the repaginated postscript.
  486: 	      #
  487: 	      &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  488: 				 "for $status_statement first latex to repaginate",
  489: 				 \%prog_state, $name_file);
  490: 	      if ($tableofcontents eq 'yes') {
  491: 		  &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  492: 				     "for $status_statement second latex to repaginate",
  493: 				     \%prog_state, $name_file);
  494: 		  &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  495: 				     "for $status_statement third latex to repaginate",
  496: 				     \%prog_state, $name_file);
  497: 	      }
  498: 	      if ($tableofindex eq 'yes') {
  499: 		  my $idxname = $latex_file;
  500: 		  $idxname =~ s/\.tex$/\.idx/;
  501: 		  &busy_wait_command("makindex $idxname",
  502: 				     "Re-creating index file",
  503: 				     \%prog_state, $idxname);
  504: 		  &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  505: 				     "for $status_statement now Recreting index (latex)",
  506: 				     \%prog_state, $dvi_file);
  507: 
  508: 	      }
  509: 	      &busy_wait_command("$comma $name_file 1>dev/null 2>/dev/null",
  510: 				 "for $status_statement dvips to repaginate",
  511: 				 \%prog_state, $new_name_file);
  512: 	      print "\n<h1>PDF output file (see link below)</h1>\n";
  513: 	      $new_name_file =~ m/^(.*)\./;
  514: 	      my $ps_file = my $tempo_file = $1.'temporar.ps';
  515: 	      my $pdf_file = $1.'.pdf';
  516: 	      if ($laystyle eq 'album' and $numberofcolumns eq '2') {
  517: 		  my $papera=$paper;
  518:                   if ($papera eq 'letter') {$papera='';}
  519: 		  if ($papera ne '') {$papera='-p'.$papera;}
  520: 		  $comma = "psnup $papera -2 -s1.0 $new_name_file";
  521: 		  &busy_wait_command("$comma $tempo_file 1>/dev/null 2>/dev/null",
  522: 				     "for $status_statement now Modifying PS layout",
  523: 				     \%prog_state,$tempo_file); 
  524: 	      } elsif ($laystyle eq 'book' and $numberofcolumns eq '2') {
  525: 		  my $papera=$paper;
  526:                   if ($papera eq 'letter') {$papera='';}
  527: 		  if ($papera ne '') {$papera='-p'.$papera;}
  528: 		  $comma = 'pstops '.$papera.' "2:0+1(0.48w,0)"';
  529: 		  &busy_wait_command("$comma $new_name_file $tempo_file 1>/dev/null 2>/dev/null",
  530: 				     "for $status_statement now Modifying PS layout",
  531: 				     \%prog_state,$tempo_file); 
  532: 
  533: 	      } else {
  534: 		  $ps_file=$new_name_file;
  535: 	      }	    
  536: 	      &busy_wait_command("ps2pdf $ps_file $pdf_file 1>/dev/null 2>/dev/null",
  537: 				 "for $status_statement now Converting PS to PDF",
  538: 				 \%prog_state, $pdf_file);
  539: 
  540: 	      my $texlog = $texfile;
  541: 	      my $texaux = $texfile;
  542: 	      my $texdvi = $texfile;
  543: 	      my $texps = $texfile;
  544: 	      $texlog =~ s/\.tex/\.log/;
  545: 	      $texaux =~ s/\.tex/\.aux/;
  546: 	      $texdvi =~ s/\.tex/\.dvi/;
  547: 	      $texps =~ s/\.tex/\.ps/;
  548: 	      my @garb = ($texaux,$texdvi,$texps);
  549: #	  unlink @garb;
  550: 	      unlink $duefile;
  551: 	      print "<a href=\"/prtspool/$pdf_file\">Your PDF document</a>";
  552: 	  }
  553: 	  if ($advanced_role) {  
  554: 	      print "<br /><br />";
  555: 	      print "<b><big>The link to ";
  556: 	      $logfilename=~s/\/home\/httpd//;
  557: 	      print "<a href=\"$logfilename\">Your log file </a></big></b>";
  558: 	      print "\n";
  559: 	      #link tooriginal LaTeX file (included according Michael Hamlin desire)
  560: 	      my $tex_temporary_file=IO::File->new($texfile) || die "Couldn't open tex file $texfile for reading: $!\n";
  561: 	      my @tex_content_of_file = <$tex_temporary_file>;
  562: 	      close $tex_temporary_file; 
  563: 	      my $body_tex_file = join(' ',@tex_content_of_file);
  564: 	      $texfile =~ s/\.tex$/aaaaa\.html/;
  565: 	      $tex_temporary_file = IO::File->new('>'.$texfile); 
  566: 	      print $tex_temporary_file '<html><head><title>LOGFILE</title></head><body><pre>'.$body_tex_file.'</pre></body></html>'."\n";
  567: 	      print "<br /><br />";
  568: 	      print "<b><big>The link to ";
  569: 	      $texfile=~s/\/home\/httpd//;
  570: 	      print "<a href=\"$texfile\">Your original LaTeX file </a></big></b>";
  571: 	      print "\n";
  572: 	  }
  573:       } else {
  574: 	  #LaTeX successfully parsed tex file 
  575: 	  $name_file =~ s/\.tex/\.dvi/;
  576: 	  my $new_name_file = $name_file;
  577: 	  $new_name_file =~ s/\.dvi/\.ps/;
  578: 	  my $papera=$paper;
  579: 	  if ($papera eq 'letter') {$papera='';}
  580: 	  if ($papera ne '') {$papera='-t'.$papera;}
  581: 	  my $comma = "dvips $papera -Ppdf -G0 -o $new_name_file";
  582: 	  &busy_wait_command("$comma $name_file 1>/dev/null 2>/dev/null",
  583: 			     "for $status_statement now Converting to PS",
  584: 			     \%prog_state,$new_name_file);
  585: 	  if (-e $new_name_file) {
  586: 	      my $latex_file = $name_file;
  587: 	      $latex_file =~ s/\.dvi/\.tex/;
  588: 	      &repaginate($new_name_file, $latex_file,  $numberofcolumns);
  589: 	      &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  590: 				 "for $status_statement first latex to repaginate",
  591: 				 \%prog_state, $name_file);
  592: 	      if ($tableofcontents eq 'yes') {
  593: 		  &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  594: 				     "for $status_statement second latex to repaginate",
  595: 				     \%prog_state, $name_file);
  596: 		  &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  597: 				     "for $status_statement third latex to repaginate",
  598: 				     \%prog_state, $name_file);
  599: 	      }
  600: 	      if ($tableofindex eq 'yes') {
  601: 		  my $idxname = $latex_file;
  602: 		  $idxname    =~ s/\.tex$/\.idx/;
  603: 		  &busy_wait_command("makeindex $idxname",
  604: 				     "Re-creating index file",
  605: 				     \%prog_state, $idxname);
  606: 		  &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
  607: 				     "for $status_statement now Recreting index (latex)",
  608: 				     \%prog_state, $dvi_file);
  609: 	      }
  610: 	      &busy_wait_command("$comma $name_file 1>/dev/null 2>/dev/null",
  611: 				 "for $status_statement dvips to repaginate",
  612: 				 \%prog_state, $new_name_file);
  613: 	      print "<br />";
  614: 	      $new_name_file =~ m/^(.*)\./;
  615: 	      my $ps_file = my $tempo_file = $1.'temporar.ps';
  616: 	      my $pdf_file = $1.'.pdf';
  617: 	      $papera=~s/t/p/;
  618: 	      if ($laystyle eq 'album' and $numberofcolumns eq '2') {
  619: 		  $comma = "psnup $papera -2 -s1.0 $new_name_file";
  620: 		  &busy_wait_command("$comma $tempo_file 1>/dev/null 2>/dev/null",
  621: 				     "for $status_statement now Modifying PS layout",
  622: 				     \%prog_state,$tempo_file);
  623: 	      } elsif ($laystyle eq 'book' and $numberofcolumns eq '2') {
  624: 		  $comma = 'pstops '.$papera.' "2:0+1(0.48w,0)"';
  625: 		  &busy_wait_command("$comma $new_name_file $tempo_file 1>/dev/null 2>/dev/null",
  626: 				     "for $status_statement now Modifying PS layout",
  627: 				     \%prog_state,$tempo_file); 
  628: 	      } else {
  629: 		  $ps_file=$new_name_file;
  630: 	      }
  631: 	      my $addtoPSfile={'legal'=>'<< /PageSize [612 1008] >> setpagedevice',
  632:                                'tabloid'=>'<< /PageSize [792 1224] >> setpagedevice',
  633:                                'executive'=>,'<< /PageSize [540 720] >> setpagedevice',
  634:                                'a2'=>'<< /PageSize [1195.02 1690.09] >> setpagedevice',
  635:                                'a3'=>'<< /PageSize [842 1195.02] >> setpagedevice',
  636:                                'a4'=>'<< /PageSize [595.2 842] >> setpagedevice',
  637:                                'a5'=>'<< /PageSize [421.1 595.2] >> setpagedevice',
  638:                                'a6'=>'<< /PageSize [298.75 421.1] >> setpagedevice',
  639: 			   };
  640: 	      if ($paper ne 'letter') {
  641: 		  open(FFH,'<',$ps_file) || die "Couldn't open ps file $ps_file for reading: $!\n";
  642: 		  my $new_ps_file='new'.$ps_file;
  643: 		  open(FFHS,'>',$new_ps_file) || die "Couldn't open new ps file $new_ps_file for reading: $!\n";
  644: 		  print FFHS $addtoPSfile->{$paper}."\n";
  645: 		  while (<FFH>) {
  646: 		      print FFHS $_;
  647: 		  }
  648: 		  close(FFH);
  649: 		  close(FFHS);
  650: 		  $ps_file=$new_ps_file;	  
  651: 	      }
  652: 	      &busy_wait_command("ps2pdf $ps_file $pdf_file 1>/dev/null 2>/dev/null",
  653: 				 "for $status_statement now Converting PS to PDF",
  654: 				 \%prog_state,$pdf_file);
  655: 	    
  656: 	      my $texlog = $texfile;
  657: 	      my $texaux = $texfile;
  658: 	      my $texdvi = $texfile;
  659: 	      my $texps = $texfile;
  660: 	      $texlog =~ s/\.tex/\.log/;
  661: 	      $texaux =~ s/\.tex/\.aux/;
  662: 	      $texdvi =~ s/\.tex/\.dvi/;
  663: 	      $texps =~ s/\.tex/\.ps/;
  664: 	      my @garb = ($texlog,$texaux,$texdvi,$texps);
  665: #	  unlink @garb;
  666: 	      unlink $duefile;
  667: 	      print "<a href=\"/prtspool/$pdf_file\">$link_text - click here to download pdf</a>";
  668: 	      print "\n";
  669: 	  }
  670:       }  
  671:   } else {
  672:       print "LaTeX file $texfile was not created successfully";
  673:   }
  674: }
  675: print "<br />";
  676: if ($number_of_files>1) {
  677:     my $zipfile=$texfile[0];
  678:     $zipfile=~s/\.tex/\.zip/;
  679:     my $statement="zip $zipfile";
  680:     foreach my $file (@texfile) {
  681: 	$file=~s/\.tex/.\pdf/;
  682: 	$statement.=' '.$file; 
  683:     }
  684:     print("<pre>Zip Output:\n");
  685:     system($statement);
  686:     print("</pre>");
  687:     $zipfile=~s/\/home\/httpd//;
  688:     print "<br /> A <a href=\"$zipfile\">ZIP file</a> of all the PDFs.";
  689: }
  690: if ($advanced_role) { &Apache::lonhtmlcommon::Close_PrgWin('',\%prog_state); }
  691: print(&Apache::loncommon::end_page());
  692: my $done;
  693: 
  694: sub REAPER {
  695:     $done=1;
  696: }
  697: 
  698: sub busy_wait_command {
  699:     my ($command,$message,$progress_win,$output_file)=@_;
  700:     
  701:     $SIG{CHLD} = \&REAPER;
  702:     $done=0;
  703:     my $pid=open(CMD,"$command |");
  704:     if ($advanced_role) {
  705: 	&Apache::lonhtmlcommon::Update_PrgWin('',$progress_win,$message);
  706:     }
  707:     while(!$done) {
  708: 	sleep 1;
  709: 	my $extra_msg;
  710: 	if ($output_file) {
  711: 	    my $size=(stat($output_file))[7];
  712: 	    $extra_msg=", $size bytes generated";
  713: 	}
  714: 	if ($advanced_role) {
  715: 	    &Apache::lonhtmlcommon::Update_PrgWin('',$progress_win,
  716: 						  $message.$extra_msg);
  717: 	}
  718:     }
  719:     $SIG{CHLD}='IGNORE';
  720:     close(CMD);
  721: }
  722: 
  723: #  Repagninate
  724: #  What we need to do:
  725: #   - Count the number of pages in each student.
  726: #   - Rewrite the latex file replacing the \specials that
  727: #     mark the end of student with an appropriate number of newlines.
  728: #   parameters:
  729: #     psfile     - Postscript filename
  730: #     latexfile  - LaTeX filename
  731: #     columns    - number of columns.
  732: sub repaginate {
  733: 
  734:     # We will try to do this in 2 passes through the postscript since
  735:     # the postscript is potentially large, to do 2 passes, the first pass
  736:     # must be able to calculate the total number of document pages so that
  737:     # at the beginning of the second pass we already know how to replace
  738:     #  %%Pages:
  739: 
  740:     #  Figure out
  741:     #    1. Number of pages in the document
  742:     #    2. Maximum number of pages in a student
  743:     #    3. Number of pages in each student.
  744: 
  745:     my ($postscript_filename, $latex_filename, $num_columns) = @_;
  746:     open(PSFILE, "<$postscript_filename");
  747:     my $line;
  748:     my $total_pages;		# Total pages in document.
  749:     my $seen_pages        = 0;	# There are several %%Pages only the first is useful
  750:     my @pages_in_student;	# For each student his/her initial page count.
  751:     my $max_pages = 0;		# Pages in 'longest' student.
  752:     my $page_number = 0;
  753:     &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state, 
  754: 					  &mt("Counting pages for student: [_1]",1));
  755: 
  756:     while ($line = <PSFILE>) {
  757: 	
  758: 	# Check for total pages (%%Pages:)
  759: 
  760: 	if (($line =~ /^%%Pages:/) && (!$seen_pages)) {
  761: 	    my @pageinfo = split(/ /,$line);
  762: 	    $total_pages = $pageinfo[1];
  763: 	    $seen_pages  = 1;
  764: 	}
  765: 	#  Check for %%Page: n m  $page_number will be the
  766: 	#  biggest of these until we see an endofstudent.
  767: 	#  Note that minipages generate spurious %Page: 1 1's so
  768: 	#  we only are looking for the largest n (n is page number at the
  769: 	#  bottom of the page, m the page number within the document.
  770: 	#
  771: 
  772: 	if ($line =~ /^%%Page:/) {
  773: 	    my @pageinfo = split(/ /, $line);
  774: 	    if ($page_number < $pageinfo[1]) {
  775: 		$page_number = $pageinfo[1];
  776: 	    } elsif ($pageinfo[2] ne 1) {
  777: 		#  current page count reset, and it's not because of a 
  778: 		#    minipage 
  779: 		# - save the page_number, reset and, if necessary
  780: 		#    update max_pages.
  781: 		push(@pages_in_student, $page_number);
  782: 		&Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state, 
  783: 						      &mt("Counting pages for student: [_1]", scalar(@pages_in_student)));
  784: 		if ($page_number > $max_pages) {
  785: 		    $max_pages = $page_number;
  786: 		}
  787: 		$page_number = $pageinfo[1];
  788: 	    }
  789: 	}
  790: 
  791: 	
  792:     }
  793:     # file ended so one more student
  794:     push(@pages_in_student, $page_number);
  795:     &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state, 
  796: 					  &mt("Counting pages for student: [_1]",scalar(@pages_in_student)));
  797:     if ($page_number > $max_pages) {
  798: 	$max_pages = $page_number;
  799:     }
  800:     $page_number = 0;
  801:     
  802:     close(PSFILE);
  803: 
  804:     #  If 2 columns, max_pages must go to an even number of columns:
  805: 
  806:    
  807:     if ($num_columns == 2) {
  808: 	if ($max_pages % 2) {
  809: 	    $max_pages++;
  810: 	}
  811:     }
  812:     
  813:     #  Now rewrite the LaTex file, substituting our \special
  814:     #  with an appropriate number of \newpage directives.
  815: 
  816:     my $outfilename = $latex_filename."temp";
  817: 
  818:     open(LATEXIN, "<$latex_filename");
  819:     open(LATEXOUT, ">$outfilename");
  820: 
  821: 
  822:     my $student_number    = 0;	# Index of student we're working on.
  823:     &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state, 
  824: 					  "Repaginating student ".$student_number+1);
  825: 
  826:     while (my $line = <LATEXIN>) {
  827: 	if ($line eq "\\special{ps:ENDOFSTUDENTSTAMP}\n") {
  828: 	    # only end of student stamp if next line is ENDOFSTUDENTSTAMP:
  829: 
  830: 
  831: 	    # End of student replace with 0 or more newpages.
  832: 	    
  833: 	    my $addlines = $max_pages - $pages_in_student[$student_number];
  834: 	    while($addlines)  {
  835: 		print LATEXOUT '\clearpage \strut \clearpage';
  836: 
  837: 		$addlines--;
  838: 	    }
  839: 	    
  840: 	    $student_number++;
  841: 	    &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state, 
  842: 						  "Repaginating student ".$student_number+1);
  843: 	    
  844: 	} else {
  845: 	    print LATEXOUT $line;
  846: 	}
  847:     }
  848: 
  849:     close(LATEXIN);
  850:     close(LATEXOUT);
  851:     rename($outfilename, $latex_filename);
  852: 
  853: }
  854: 

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