File:
[LON-CAPA] /
loncom /
interface /
printout.pl
Revision
1.131:
download - view:
text,
annotated -
select for diffs
Mon Mar 10 22:42:28 2008 UTC (16 years, 5 months ago) by
www
Branches:
MAIN
CVS tags:
HEAD
Bug #5643 - maybe. If what we want to detect are INFINITE loops, maybe we
can wait five minutes instead of 10 seconds. Given that a normal exam printing
run for me takes about 50 minutes, I think five minutes are okay.
1: #!/usr/bin/perl
2: # CGI-script to run LaTeX, dvips, ps2ps, ps2pdf etc.
3: #
4: # $Id: printout.pl,v 1.131 2008/03/10 22:42:28 www Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: use lib '/home/httpd/lib/perl';
30: use LONCAPA::loncgi;
31: use File::Path;
32: use File::Basename;
33: use File::Copy;
34: use IO::File;
35: use Image::Magick;
36: use Apache::lonhtmlcommon();
37: use Apache::lonnet;
38: use Apache::loncommon();
39: use Apache::lonlocal;
40: use Apache::lonmsg();
41: use LONCAPA::Enrollment;
42: use LONCAPA::Configuration;
43:
44: use strict;
45:
46: my $busy_wait_timeout = 300;
47:
48: # Determine if a user is operating as a student for this course/domain.
49: #Parameters:
50: # none
51: #Implicit:
52: # $env{request.role} contains the role under which this user operated this
53: # this request.
54: sub is_student {
55: return ($env{'request.role'}=~/^st\./);
56: }
57:
58: #
59: # Debugging: Dump the environment for debugging.
60: #
61: sub dumpenv {
62: print "<br />-------------------<br />";
63: foreach my $key (sort (keys %env)) {
64: print "<br />$key -> $env{$key}";
65: }
66: print "<br />-------------------<br />";
67: }
68:
69: #
70: # This sub sends a message to the appropriate person if there was an error
71: # rendering the latex At present, there's only one case to consider:
72: # a student printing inside a course results in messages to the course coordinator.
73: #Parmaeters:
74: # identifier - The unique identifier of this cgi request.
75: # badresource- Filepath to most likely failing
76: # logfile - The contents of the log file (included in the message).
77: # texfile - reference to an array containing the LaTeX input file
78: # (included in the message).
79: #Implicit inputs:
80: # From the environment:
81: # cgi.$identifier.user - User doing the printing.
82: # cgi.$identifier.domain - Domain the user is logged in on with printing.
83: # cgi.$identifier.courseid - Id of the course (if this is a course).
84: # cgi.$identifier.coursedom- Domain in which course was constituted.
85: # cgi.$identifier.resources - List of resource URL's for which the print
86: # was attempted.
87: #
88: sub send_error_mail {
89: my ($identifier, $badresource, $logfile, $texfile) = @_;
90: my $user = $env{"cgi.$identifier.user"};
91: my $domain = $env{"cgi.$identifier.domain"};
92: my $courseid = $env{"cgi.$identifier.courseid"};
93: my $coursedom= $env{"cgi.$identifier.coursedom"};
94: my $resources= $env{"cgi.$identifier.resources"};
95:
96: # resource file->URL
97: #
98: my $badurl = &Apache::lonnet::declutter($badresource);
99:
100: # &dumpenv();
101:
102:
103:
104: # Only continue if there is a user, domain, courseid, course domain
105: # and resources:
106:
107: if(defined($user) && defined($domain) && defined($courseid) &&
108: defined($coursedom) && defined($resources) ){
109:
110: # Only mail if the conditions are ripe for it:
111: # The user is a student in the course:
112: #
113:
114: if (&is_student()) {
115: # build the subject and message body:
116: # print "sending message to course coordinators.<br />";
117:
118: # Todo: Convert badurl into a url from file path:
119:
120: my $subject = "Error [$badurl] Print failed for $user".'@'.$domain;
121: my $message .= "Print failed to render LaTeX for $user".'@'."$domain\n";
122: $message .= " User was attempting to print: \n";
123: foreach my $resource (split(/:/,$resources)) {
124: $message .= " $resource\n";
125: }
126: $message .= "--------------------LaTeX logfile:------------ \n";
127: $message .= $logfile;
128: $message .= "-----------------LaTeX source file: ------------\n";
129:
130: foreach my $line (@$texfile) {
131: $message .= "$line\n";
132: }
133: my (undef, %receivers) = &Apache::lonmsg::decide_receiver(undef, 0,
134: 1,1,1);
135: # print "<br /> sending...section: $env{'request.course.sec'}";
136: foreach my $dest (keys %receivers) {
137: # print "<br /> dest is $dest";
138: my @destinfo = split(/:/,$dest);
139: my $user = $destinfo[0];
140: my $dom = $destinfo[1];
141:
142: &Apache::lonmsg::user_normal_msg($user, $dom,
143: $subject, $message);
144:
145: # No point in looking at the return status as there's no good
146: # error action I can think of right now (log maybe?).
147: }
148: }
149: }
150: }
151:
152: $|=1;
153: if (! &LONCAPA::loncgi::check_cookie_and_load_env()) {
154: print <<END;
155: Content-type: text/html
156:
157: <html>
158: <head><title>Bad Cookie</title></head>
159: <body>
160: Your cookie information is incorrect.
161: </body>
162: </html>
163: END
164: return;
165: }
166:
167: my %perlvar=%{&LONCAPA::Configuration::read_conf('loncapa.conf')};
168: &Apache::lonlocal::get_language_handle();
169: &Apache::loncommon::content_type(undef,'text/html');
170: $env{'request.noversionuri'} = '/cgi-bin/printout.pl';
171: print(&Apache::loncommon::start_page('Creating PDF'));
172:
173: my $identifier = $ENV{'QUERY_STRING'};
174: my $texfile = $env{'cgi.'.$identifier.'.file'};
175: my $laystyle = $env{'cgi.'.$identifier.'.layout'};
176: my $numberofcolumns = $env{'cgi.'.$identifier.'.numcol'};
177: my $paper = $env{'cgi.'.$identifier.'.paper'};
178: my $selectionmade = $env{'cgi.'.$identifier.'.selection'};
179: my $tableofcontents = $env{'cgi.'.$identifier.'.tableofcontents'};
180: my $tableofindex = $env{'cgi.'.$identifier.'.tableofindex'};
181: my $advanced_role = $env{'cgi.'.$identifier.'.role'};
182: my $number_of_files = $env{'cgi.'.$identifier.'.numberoffiles'}+1;
183: my $student_names = $env{'cgi.'.$identifier.'.studentnames'};
184: my $backref = &Apache::lonnet::unescape($env{'cgi.'.$identifier.'.backref'});
185:
186:
187: my @names_pack=();
188: if ($student_names=~/_END_/) {
189: @names_pack=split(/_ENDPERSON_/,$student_names);
190: }
191: if ($backref) {
192: print('<p>'.&mt("[_1]Return[_2] to editing resource.",
193: "<a href=\"$backref\"><b>","</b></a>").'</p>');
194: }
195: my $figfile = $texfile;
196: $figfile =~ s/^(.*_printout)_\d+_\d+_\d+\.tex/$1\.dat/;
197: my $duefile = $texfile;
198: $duefile =~ s/^(.*_printout)_\d+_\d+_\d+\.tex/$1\.due/;
199: #do we have figures?
200: # print "Figure file: $figfile\n";
201: if (-e $figfile) {
202: # print "$figfile exists\n";
203: my %done_conversion;
204: my $temporary_file=IO::File->new($figfile) || die "Couldn't open fig file $figfile for reading: $!\n";
205: my @content_of_file = <$temporary_file>;
206: close $temporary_file;
207: my $noteps;
208: my %prog_state;
209: if ($advanced_role) { %prog_state=&Apache::lonhtmlcommon::Create_PrgWin('','Coverting Images to EPS','Picture Conversion Status',$#content_of_file,'inline','80'); }
210: print('<br />');
211: foreach my $not_eps (@content_of_file) {
212: chomp($not_eps);
213: if ($not_eps ne '') {
214: # print "Converting $not_eps"; # Debugging.
215: my $status_statement='EPS picture for '.$not_eps;
216: # print "$status_statement\n";
217: $not_eps=~s|\/\.\/|\/|g;
218: my $eps_f = $not_eps;
219: # $eps_f =~ s/\.[^.]*$/\.eps/i;
220: if ($eps_f=~/\/home\/([^\/]+)\/public_html\//) {
221: $eps_f=~s/\/home\/([^\/]+)\/public_html/$1/;
222: $eps_f = $perlvar{'lonPrtDir'}.'/'.$eps_f;
223: } elsif ($eps_f=~/$perlvar{'lonDocRoot'}\/res\//) {
224: $eps_f=~m/$perlvar{'lonDocRoot'}\/res\/(.+)/;
225: $eps_f = $perlvar{'lonPrtDir'}.'/'.$1;
226: } elsif ($eps_f=~/$perlvar{'lonUsersDir'}\//) {
227: $eps_f=~/$perlvar{'lonUsersDir'}\/([^\/]+)\/\w\/\w\/\w\/(.+)/;
228: $eps_f = $perlvar{'lonPrtDir'}.'/'.$1.'/'.$2;
229: }
230: $eps_f =~ s/ /\_/g; # Spaces are problematic for system commands and LaTeX.
231: #
232: # If the file is already an .eps or .ps file,
233: # We really just need to copy it from where it was to prtspool
234: # but with the spaces substituted to _'s.
235: #
236: my ($nsname,$path, $sext) = &fileparse($eps_f, qr/\.(ps|eps)/i);
237: if ($sext =~/ps$/i) {
238: # print "$not_eps is a postscript file. copy to $path\n";
239: &File::Path::mkpath($path,0,0777);
240: #print("Made path: $path");
241: #$not_eps =~ s/^\s+//;
242: #$not_eps =~ s/\s+$//;
243: #$not_eps =~ s/ /\__/g;
244: #print("Copying $not_eps to $eps_f\n");
245: copy("$not_eps", "$eps_f");
246: # print "Copy complete\n";
247: } else {
248:
249: $eps_f .= '.eps'; # Just append the eps ext.
250: my $path=$eps_f;
251: $path =~ s/\/([^\/]+)\.eps$//;
252: # print "Final file path: $path "; # Debugging
253: &File::Path::mkpath($path,0,0777);
254: $not_eps =~ s/^\s+//;
255: $not_eps =~ s/\s+$//;
256: $not_eps =~ s/ /\\ /g;
257: if ( exists($done_conversion{$not_eps})) { next; }
258: if ($advanced_role) {
259: my $prettyname=$not_eps;
260: $prettyname=~s|/home/([^/]+)/public_html|/priv/$1|;
261: $prettyname=~s|$perlvar{'lonDocRoot'}/|/|;
262: &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,
263: 'Converting to EPS '.$prettyname);
264: }
265: $done_conversion{$not_eps}=1;
266: # print "Converting $not_eps -> $eps_f"; # Debugging
267: system("convert $not_eps $eps_f");
268: # check is eps exist in prtspool
269: if (not -e $eps_f) {
270: # converting an animated gif creates either:
271: # anim.gif.eps.0
272: # or
273: # anim.gif-0.eps
274: for (my $i=0;$i<10000;$i++) {
275: if (-e $eps_f.'.'.$i) {
276: rename($eps_f.'.'.$i, $eps_f);
277: last;
278: }
279: my $anim_eps = $eps_f;
280: $anim_eps =~ s/(\.[^.]*)\.eps$/$1-$i\.eps/i;
281: if (-e $anim_eps) {
282: rename($anim_eps, $eps_f);
283: last;
284: }
285: }
286: }
287:
288: # imagemagick 6.2.0-6.2.7 fails to properly handle
289: # convert anim.gif anim.gif.eps
290: # it creates anim.eps instead.
291: if (not -e $eps_f) {
292: my $eps_f2 = $eps_f;
293: $eps_f2 =~ s/\.[^.]*\.eps$/\.eps/i;
294: if(-e $eps_f2) {
295: rename($eps_f2,$eps_f);
296: }
297: }
298: }
299:
300: }
301: }
302: if ($advanced_role) {
303: &Apache::lonhtmlcommon::Close_PrgWin('',\%prog_state);
304: }
305: unlink($figfile);
306: }
307: #print "$texfile\n"; #name of the tex file for debugging only
308: my @texfile=($texfile);
309: if ($number_of_files>1) {
310: @texfile=();
311: for (my $i=1;$i<=$number_of_files;$i++) {
312: my $new_texfile=$texfile;
313: $new_texfile=~s/\.tex//;
314: $new_texfile = sprintf("%s_%03d.tex", $new_texfile,$i);
315: push @texfile,$new_texfile;
316: }
317: }
318:
319: my $ind=-1;
320: my %prog_state;
321: if ($advanced_role) { %prog_state=&Apache::lonhtmlcommon::Create_PrgWin('','Print Status','Class Print Status',$number_of_files,'inline','80'); }
322: print "<br />";
323: my $num_files = @texfile;
324: foreach $texfile (@texfile) {
325: my $status_statement='';
326: my $link_text='download PDF';
327: $ind++;
328: my @stud_info=split(/_END_/,$names_pack[$ind]);
329: my @tempo_array=split(/:/,$stud_info[0]);
330: my $name;
331: my $name_range='';
332: if ($tempo_array[3]) {
333: $name=$tempo_array[3];
334: ($name_range) = split(/,/,$name, 2);
335: } else {
336: $name=$tempo_array[0].'@'.$tempo_array[1];
337: $name_range = $tempo_array[0];
338: }
339: if (($name ne "") && ($name ne '@') ) { # Could be printing codes...
340: $link_text='<b>'.$name.'</b>';
341: $status_statement.=$name;
342: }
343: if ($#stud_info>0) {
344: @tempo_array=split(/:/,$stud_info[-1]);
345: if ($tempo_array[3]) {
346: $name=$tempo_array[3];
347: my ($lastname) = split(/,/, $name,2);
348: $name_range .= "-".$lastname;
349: } else {
350: $name=$tempo_array[0].'@'.$tempo_array[1];
351: $name_range .= '-'.$tempo_array[0];
352: }
353: if (($name ne "") && ($name ne '@')) {
354: $link_text.=' - <b>'.$name.'</b>';
355: $status_statement.=' - '.$name;
356:
357: }
358: }
359: if(($num_files > 1) && ($link_text eq 'download PDF')) { # Printing codes
360: $link_text = '<b>'.basename($texfile,'.tex').'.pdf</b>';
361: $status_statement .= basename($texfile);
362: }
363: $name_range =~ s/'//g; # O'Neil -> ONeil e.g.
364: print "<br/>";
365: if ($advanced_role) { &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,'Creating PDF for '.$status_statement); }
366: # This little piece of dirt puts username ranges into the original tex
367: # Tex filename from which they'll propagate into the other filenames as well.
368: #
369: if (-e $texfile) {
370: if (($name_range ne '') && ($num_files > 1)) {
371: my $newtexfile = $texfile;
372: $newtexfile =~ s/\.tex/$name_range\.tex/;
373: rename($texfile, $newtexfile);
374: $texfile = $newtexfile;
375: }
376: $texfile =~ m/^(.*)\/([^\/]+)$/;
377: my $name_file = $2;
378: my $path_file = $1.'/';
379: chdir $path_file;
380: my $dvi_file= $name_file; $dvi_file =~ s/\.tex/$name_range\.dvi/;
381: &busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
382: "for $status_statement now LaTeXing file",
383: \%prog_state,$dvi_file, $busy_wait_timeout);
384: if ($tableofcontents eq 'yes') {
385: &busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
386: "for $status_statement First LaTeX of file for table of contents",
387: \%prog_state,$dvi_file, $busy_wait_timeout);
388: &busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
389: "for $status_statement Second LaTeX of file for table of contents",
390: \%prog_state,$dvi_file,$busy_wait_timeout);
391: } #to create table of contents
392: my $idxname=$name_file;
393: $idxname=~s/\.tex$/\.idx/;
394: if ($tableofindex eq 'yes') {
395: &busy_wait_command("makeindex $idxname",
396: "making index file",
397: \%prog_state,$idxname);
398: &busy_wait_command("latex $name_file 1>/dev/null 2>/dev/null",
399: "for $status_statement now LaTeXing file for index section",
400: \%prog_state,$dvi_file, $busy_wait_timeout);
401: } #to create index
402: #Do we have a latex error in the log file?
403: my $logfilename = $texfile; $logfilename =~ s/\.tex$/\.log/;
404: my $temporary_file=IO::File->new($logfilename) || die "Couldn't open log file $logfilename for reading: $!\n";
405: my @content_of_file = <$temporary_file>;
406: close $temporary_file;
407: my $body_log_file = join(' ',@content_of_file);
408: $logfilename =~ s/\.log$/\.html/;
409: $temporary_file = IO::File->new('>'.$logfilename);
410: print $temporary_file '<html><head><title>LOGFILE</title></head><body><pre>'.$body_log_file.'</pre></body></html>'."\n";
411: if ($body_log_file=~m/!\s+Emergency stop/) {
412: my $whereitbegins = rindex $body_log_file,'STAMPOFPASSEDRESOURCESTART';
413: my $whereitends = rindex $body_log_file,'STAMPOFPASSEDRESOURCEEND';
414: my $badresource;
415: my $badtext;
416: if ($whereitbegins!=-1 and $whereitends!=-1) {
417: $badtext = substr($body_log_file,$whereitbegins+26, $whereitends-$whereitbegins-26);
418: $whereitbegins = rindex $badtext,'located in';
419: if ($whereitbegins != -1) {
420:
421: $badresource = substr($badtext, $whereitbegins+27,
422: length($badtext) - $whereitbegins - 48);
423: # print "<br />failing resourcename: $badresource<br />";
424: }
425: }
426:
427: if ($advanced_role) {
428: #LaTeX failed to parse tex file
429: print "<h2>LaTeX could not successfully parse your tex file.</h2>";
430: print "It probably has errors in it.<br />";
431: print "With very high probability this error occured in ".$badtext."<br /><br />";
432: print "Here are the error messages in the LaTeX log file<br /><pre>";
433:
434: my $sygnal = 0;
435: for (my $i=0;$i<=$#content_of_file;$i++) {
436: if ($content_of_file[$i]=~m/^Runaway argument?/ or $content_of_file[$i]=~m/^!/) {
437: $sygnal = 1;
438: }
439: if ($content_of_file[$i]=~m/Here is how much of/) {
440: $sygnal = 0;
441: }
442: if ($sygnal) {
443: print "$content_of_file[$i]";
444: }
445: }
446: print "</pre>\n";
447: # print "<br /> Advanced role <br />";
448: print "<b><big>The link to ";
449: $logfilename=~s{^\Q$perlvar{'lonPrtDir'}\E}{/prtspool};
450: print "<a href=\"$logfilename\">Your log file </a></big></b>";
451: print "\n";
452: #link tooriginal LaTeX file (included according Michael Hamlin desire)
453: my $tex_temporary_file=IO::File->new($texfile) || die "Couldn't open tex file $texfile for reading: $!\n";
454: my @tex_content_of_file = <$tex_temporary_file>;
455: close $tex_temporary_file;
456: my $body_tex_file = join(' ',@tex_content_of_file);
457: $texfile =~ s/\.tex$/aaaaa\.html/;
458: $tex_temporary_file = IO::File->new('>'.$texfile);
459: print $tex_temporary_file '<html><head><title>LOGFILE</title></head><body><pre>'.$body_tex_file.'</pre></body></html>'."\n";
460: print "<br /><br />";
461: print "<b><big>The link to ";
462: $texfile=~s{^\Q$perlvar{'lonPrtDir'}\E}{/prtspool};
463: print "<a href=\"$texfile\">Your original LaTeX file </a></big></b>";
464: print "\n";
465: my $help_text = &Apache::loncommon::help_open_topic("Print_Resource", "Help on printing");
466: print ("$help_text");
467:
468: } else { # Student role...
469: # at this point:
470: # $body_log_file - contains the log file.
471: # $name_file - is the name of the LaTeX file.
472: # $identifier - is the unique LaTeX identifier.l
473:
474: print "<br />There are errors in $badtext";
475: print "<br />These errors prevent this resource from printing correctly";
476: my $tex_handle = IO::File->new($name_file);
477: my @tex_contents = <$tex_handle>;
478: &send_error_mail($identifier, $badresource, $body_log_file, \@tex_contents);
479: print "<br />A message has been sent to the instructor describing this failure<br />";
480: my $help_text = &Apache::loncommon::help_open_topic("Print_Resource", "Help on printing");
481: print ("$help_text");
482:
483: }
484:
485: } elsif ($body_log_file=~m/<inserted text>/) {
486: my $whereitbegins = index $body_log_file,'<inserted text>';
487: print "You are running LaTeX in <b>batch mode</b>.";
488: while ($whereitbegins != -1) {
489: my $tempobegin=$whereitbegins;
490: $whereitbegins = rindex $body_log_file,'STAMPOFPASSEDRESOURCESTART',$whereitbegins;
491: my $whereitends = index $body_log_file,'STAMPOFPASSEDRESOURCEEND',$whereitbegins;
492: print "<br />It has found an error in".substr($body_log_file,$whereitbegins+26,$whereitends-$whereitbegins-26)." <br /> and corrected it.\n";
493: 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";
494: $whereitbegins = index $body_log_file,'<inserted text>',$tempobegin+10;
495: }
496: $name_file =~ s/\.tex/\.dvi/;
497: my $new_name_file = $name_file;
498: $new_name_file =~ s/\.dvi/\.ps/;
499: my $papera=$paper;
500: if ($papera eq 'letter') {$papera='';}
501: if ($papera ne '') {$papera='-t'.$papera;}
502: my $comma = "dvips $papera -Ppdf -G0 -o $new_name_file";
503: &busy_wait_command("$comma $name_file 1>/dev/null 2>/dev/null",
504: "for $status_statement now Converting to PS",
505: \%prog_state,$new_name_file);
506: if (-e $new_name_file) {
507: my $latex_file = $name_file;
508: $latex_file =~ s/\.dvi/\.tex/;
509: &repaginate($new_name_file, $latex_file, $numberofcolumns);
510: #
511: # Now have to re-latex, re dvips again to
512: # get the repaginated postscript.
513: #
514: &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
515: "for $status_statement first latex to repaginate",
516: \%prog_state, $name_file,$busy_wait_timeout);
517: if ($tableofcontents eq 'yes') {
518: &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
519: "for $status_statement second latex to repaginate",
520: \%prog_state, $name_file,$busy_wait_timeout);
521: &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
522: "for $status_statement third latex to repaginate",
523: \%prog_state, $name_file,$busy_wait_timeout);
524: }
525: if ($tableofindex eq 'yes') {
526: my $idxname = $latex_file;
527: $idxname =~ s/\.tex$/\.idx/;
528: &busy_wait_command("makeindex $idxname",
529: "Re-creating index file",
530: \%prog_state, $idxname);
531: &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
532: "for $status_statement now Recreting index (latex)",
533: \%prog_state, $dvi_file,$busy_wait_timeout);
534:
535: }
536: &busy_wait_command("$comma $name_file 1>/dev/null 2>/dev/null",
537: "for $status_statement dvips to repaginate",
538: \%prog_state, $new_name_file);
539: #
540: # One last little hinky kinky thing.
541: # It's just possible that some fonts could not be maded
542: # at the resolution of the pdf print driver.
543: # In that case a file called missfont.log will have been
544: # created that will contain the commands that were attempted
545: # to create the missing fonts. If we basically
546: # take all the 8000 strings in that file, and
547: # replace them with 600 (the ljfour resolution)
548: # run the commands in that file and redvips,
549: # we'll be able to print the missing glyphs at 600dpi.
550: #
551: # Supposedly it is possible to tune TeX/Metafont to do this
552: # right but I failed to get that to work when following the
553: # docs at the tug site, hence this rather kludgey fix.
554: #
555: # We make the (I think) reasonable assumption that
556: # missing glyphs won't change the pagination and I think
557: # this is true because TeX/dvips will leave a space
558: # instead of these glyphs based on the font metrics
559: # (fancy way to say there will be a blank the size of the missing
560: # glyphs).
561: #
562: my $print_directory = dirname($name_file);
563: my $missfonts_file = $print_directory."/missfont.log";
564: #print("<br /> Missing fonts file is: $missfonts_file");
565: if (-e $missfonts_file) {
566: #print("<br />Missing fonts file exists\n");
567: &create_missing_fonts($missfonts_file,\%prog_state);
568: &busy_wait_command("$comma $name_file 1>/dev/null 2>/dev/null",
569: "for $status_statement dvips generated missing fonts",
570: \%prog_state, $new_name_file);
571: }
572:
573: #
574: print "\n<h1>PDF output file (see link below)</h1>\n";
575: $new_name_file =~ m/^(.*)\./;
576: my $ps_file = my $tempo_file = $1.'temporar.ps';
577: my $pdf_file = $1.'.pdf';
578: if ($laystyle eq 'album' and $numberofcolumns eq '2') {
579: my $papera=$paper;
580: if ($papera eq 'letter') {$papera='';}
581: if ($papera ne '') {$papera='-p'.$papera;}
582: $comma = "psnup $papera -2 -s1.0 $new_name_file";
583: &busy_wait_command("$comma $tempo_file 1>/dev/null 2>/dev/null",
584: "for $status_statement now Modifying PS layout",
585: \%prog_state,$tempo_file);
586: } elsif ($laystyle eq 'book' and $numberofcolumns eq '2') {
587: my $papera=$paper;
588: if ($papera eq 'letter') {$papera='';}
589: if ($papera ne '') {$papera='-p'.$papera;}
590: $comma = 'pstops '.$papera.' "2:0+1(0.48w,0)"';
591: &busy_wait_command("$comma $new_name_file $tempo_file 1>/dev/null 2>/dev/null",
592: "for $status_statement now Modifying PS layout",
593: \%prog_state,$tempo_file);
594:
595: } else {
596: $ps_file=$new_name_file;
597: }
598: &busy_wait_command("ps2pdf $ps_file $pdf_file 1>/dev/null 2>/dev/null",
599: "for $status_statement now Converting PS to PDF",
600: \%prog_state, $pdf_file);
601:
602: my $texlog = $texfile;
603: my $texaux = $texfile;
604: my $texdvi = $texfile;
605: my $texps = $texfile;
606: $texlog =~ s/\.tex/\.log/;
607: $texaux =~ s/\.tex/\.aux/;
608: $texdvi =~ s/\.tex/\.dvi/;
609: $texps =~ s/\.tex/\.ps/;
610: my @garb = ($texaux,$texdvi,$texps);
611: # unlink @garb;
612: unlink($duefile);
613: print "<a href=\"/prtspool/$pdf_file\">Your PDF document</a>";
614: unlink($missfonts_file);
615:
616: }
617: if ($advanced_role) {
618: print "<br /><br />";
619: print "<b><big>The link to ";
620: $logfilename=~s{^\Q$perlvar{'lonPrtDir'}\E}{/prtspool};
621: print "<a href=\"$logfilename\">Your log file </a></big></b>";
622: print "\n";
623: #link tooriginal LaTeX file (included according Michael Hamlin desire)
624: my $tex_temporary_file=IO::File->new($texfile) || die "Couldn't open tex file $texfile for reading: $!\n";
625: my @tex_content_of_file = <$tex_temporary_file>;
626: close $tex_temporary_file;
627: my $body_tex_file = join(' ',@tex_content_of_file);
628: $texfile =~ s/\.tex$/aaaaa\.html/;
629: $tex_temporary_file = IO::File->new('>'.$texfile);
630: print $tex_temporary_file '<html><head><title>LOGFILE</title></head><body><pre>'.$body_tex_file.'</pre></body></html>'."\n";
631: print "<br /><br />";
632: print "<b><big>The link to ";
633: $texfile=~s{^\Q$perlvar{'lonPrtDir'}\E}{/prtspool};
634: print "<a href=\"$texfile\">Your original LaTeX file </a></big></b>";
635: print "\n";
636: }
637:
638: } else {
639: #LaTeX successfully parsed tex file
640: $name_file =~ s/\.tex/\.dvi/;
641: my $new_name_file = $name_file;
642: $new_name_file =~ s/\.dvi/\.ps/;
643: my $papera=$paper;
644: if ($papera eq 'letter') {$papera='';}
645: if ($papera ne '') {$papera='-t'.$papera;}
646: my $comma = "dvips $papera -Ppdf -G0 -o $new_name_file";
647: &busy_wait_command("$comma $name_file 1>/dev/null 2>/dev/null",
648: "for $status_statement now Converting to PS",
649: \%prog_state,$new_name_file);
650: #
651: # One last little hinky kinky thing.
652: # It's just possible that some fonts could not be maded
653: # at the resolution of the pdf print driver.
654: # In that case a file called missfont.log will have been
655: # created that will contain the commands that were attempted
656: # to create the missing fonts. If we basically
657: # take all the 8000 strings in that file, and
658: # replace them with 600 (the ljfour resolution)
659: # run the commands in that file and redvips,
660: # we'll be able to print the missing glyphs at 600dpi.
661: #
662: # Supposedly it is possible to tune TeX/Metafont to do this
663: # right but I failed to get that to work when following the
664: # docs at the tug site, hence this rather kludgey fix.
665: #
666: # We make the (I think) reasonable assumption that
667: # missing glyphs won't change the pagination and I think
668: # this is true because TeX/dvips will leave a space
669: # instead of these glyphs based on the font metrics
670: # (fancy way to say there will be a blank the size of the missing
671: # glyphs).
672: #
673: my $print_directory = dirname($name_file);
674: my $missfonts_file = $print_directory."/missfont.log";
675: #print("<br /> Missing fonts file is: $missfonts_file");
676: if (-e $missfonts_file) {
677: #print("<br />Missing fonts file exists\n");
678: &create_missing_fonts($missfonts_file,\%prog_state);
679: &busy_wait_command("$comma $name_file 1>/dev/null 2>/dev/null",
680: "for $status_statement dvips generated missing fonts",
681: \%prog_state, $new_name_file);
682: }
683: if (-e $new_name_file) {
684: my $latex_file = $name_file;
685: $latex_file =~ s/\.dvi/\.tex/;
686: &repaginate($new_name_file, $latex_file, $numberofcolumns);
687: &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
688: "for $status_statement first latex to repaginate",
689: \%prog_state, $name_file, $busy_wait_timeout);
690: if ($tableofcontents eq 'yes') {
691: &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
692: "for $status_statement second latex to repaginate",
693: \%prog_state, $name_file, $busy_wait_timeout);
694: &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
695: "for $status_statement third latex to repaginate",
696: \%prog_state, $name_file, $busy_wait_timeout);
697: }
698: if ($tableofindex eq 'yes') {
699: my $idxname = $latex_file;
700: $idxname =~ s/\.tex$/\.idx/;
701: &busy_wait_command("makeindex $idxname",
702: "Re-creating index file",
703: \%prog_state, $idxname);
704: &busy_wait_command("latex $latex_file 1>/dev/null 2>/dev/null",
705: "for $status_statement now Recreting index (latex)",
706: \%prog_state, $dvi_file, $busy_wait_timeout);
707: }
708: &busy_wait_command("$comma $name_file 1>/dev/null 2>/dev/null",
709: "for $status_statement dvips to repaginate",
710: \%prog_state, $new_name_file);
711:
712: print "<br />";
713: $new_name_file =~ m/^(.*)\./;
714: my $ps_file = my $tempo_file = $1.'temporar.ps';
715: my $pdf_file = $1.'.pdf';
716: $papera=~s/t/p/;
717: if ($laystyle eq 'album' and $numberofcolumns eq '2') {
718: $comma = "psnup $papera -2 -s1.0 $new_name_file";
719: &busy_wait_command("$comma $tempo_file 1>/dev/null 2>/dev/null",
720: "for $status_statement now Modifying PS layout",
721: \%prog_state,$tempo_file);
722: } elsif ($laystyle eq 'book' and $numberofcolumns eq '2') {
723: $comma = 'pstops '.$papera.' "2:0+1(0.48w,0)"';
724: &busy_wait_command("$comma $new_name_file $tempo_file 1>/dev/null 2>/dev/null",
725: "for $status_statement now Modifying PS layout",
726: \%prog_state,$tempo_file);
727: } else {
728: $ps_file=$new_name_file;
729: }
730: my $addtoPSfile={'legal'=>'<< /PageSize [612 1008] >> setpagedevice',
731: 'tabloid'=>'<< /PageSize [792 1224] >> setpagedevice',
732: 'executive'=>,'<< /PageSize [540 720] >> setpagedevice',
733: 'a2'=>'<< /PageSize [1195.02 1690.09] >> setpagedevice',
734: 'a3'=>'<< /PageSize [842 1195.02] >> setpagedevice',
735: 'a4'=>'<< /PageSize [595.2 842] >> setpagedevice',
736: 'a5'=>'<< /PageSize [421.1 595.2] >> setpagedevice',
737: 'a6'=>'<< /PageSize [298.75 421.1] >> setpagedevice',
738: };
739: if ($paper ne 'letter') {
740: open(FFH,'<',$ps_file) || die "Couldn't open ps file $ps_file for reading: $!\n";
741: my $new_ps_file='new'.$ps_file;
742: open(FFHS,'>',$new_ps_file) || die "Couldn't open new ps file $new_ps_file for reading: $!\n";
743: print FFHS $addtoPSfile->{$paper}."\n";
744: while (<FFH>) {
745: print FFHS $_;
746: }
747: close(FFH);
748: close(FFHS);
749: $ps_file=$new_ps_file;
750: }
751: &busy_wait_command("ps2pdf $ps_file $pdf_file 1>/dev/null 2>/dev/null",
752: "for $status_statement now Converting PS to PDF",
753: \%prog_state,$pdf_file);
754:
755: my $texlog = $texfile;
756: my $texaux = $texfile;
757: my $texdvi = $texfile;
758: my $texps = $texfile;
759: $texlog =~ s/\.tex/\.log/;
760: $texaux =~ s/\.tex/\.aux/;
761: $texdvi =~ s/\.tex/\.dvi/;
762: $texps =~ s/\.tex/\.ps/;
763: my @garb = ($texlog,$texaux,$texdvi,$texps);
764: # unlink @garb;
765: unlink($duefile);
766: print "<a href=\"/prtspool/$pdf_file\">$link_text - click here to download pdf</a>";
767: print "\n";
768: }
769: unlink($missfonts_file);
770:
771: }
772: } else {
773: print "LaTeX file $texfile was not created successfully";
774: }
775: }
776: print "<br />";
777: if ($number_of_files>1) {
778: my $zipfile=$texfile[0];
779: $zipfile=~s/\.tex/\.zip/;
780: my $statement="zip $zipfile";
781: foreach my $file (@texfile) {
782: $file=~s/\.tex/.\pdf/;
783: $statement.=' '.$file;
784: }
785: print("<pre>Zip Output:\n");
786: system($statement);
787: print("</pre>");
788: $zipfile=~s{^\Q$perlvar{'lonPrtDir'}\E}{/prtspool};
789: print "<br /> A <a href=\"$zipfile\">ZIP file</a> of all the PDFs.";
790: }
791: if ($advanced_role) { &Apache::lonhtmlcommon::Close_PrgWin('',\%prog_state); }
792: print(&Apache::loncommon::end_page());
793: my $done;
794:
795: sub REAPER {
796: $done=1;
797: }
798: #
799: # Execute a command updating the status window as the command's
800: # output file builds up (at intervals of a second).
801: #
802: # If the timeout argument defined, then if that many seconds
803: # elapses without an increase in the size of the output file,
804: # the command will be killed (this deals with the case when
805: # latex crawls into an infinite loop).
806: #
807: sub busy_wait_command {
808: my ($command,$message,$progress_win,$output_file, $timeout)=@_;
809:
810: $SIG{CHLD} = \&REAPER;
811: $done=0;
812: my $pid=open(CMD,"$command |");
813: if ($advanced_role) {
814: &Apache::lonhtmlcommon::Update_PrgWin('',$progress_win,$message);
815: }
816: my $last_size = 0;
817: my $unchanged_time = 0;
818: while(!$done) {
819: sleep 1;
820: my $extra_msg;
821: if ($output_file) {
822: my $size=(stat($output_file))[7];
823: $extra_msg=", $size bytes generated";
824: if ($size == $last_size) {
825: $unchanged_time++;
826: if ($timeout && ($unchanged_time > $timeout)) {
827: print "<h1>Operation timed out!!!</h1>\n";
828: print "<p>Executing $command, the output file $output_file did not grow\n";
829: print "after $timeout seconds. This <em>may</em> indicate $command\n";
830: print "is in an infinite loop.\n";
831: print "See if printing fewer copies helps. Please contact LON-CAPA\n";
832: print "support about this in any event.";
833: print "</p>";
834: kill(9, $pid); # Reaper will do the rest...I hope there's errors in the log.
835: }
836: } else {
837: $last_size = $size;
838: $unchanged_time = 0;
839: }
840: }
841: if ($advanced_role) {
842: &Apache::lonhtmlcommon::Update_PrgWin('',$progress_win,
843: $message.$extra_msg);
844: }
845: }
846: $SIG{CHLD}='IGNORE';
847: close(CMD);
848: }
849:
850: # Repagninate
851: # What we need to do:
852: # - Count the number of pages in each student.
853: # - Rewrite the latex file replacing the \specials that
854: # mark the end of student with an appropriate number of newlines.
855: # parameters:
856: # psfile - Postscript filename
857: # latexfile - LaTeX filename
858: # columns - number of columns.
859: sub repaginate {
860:
861: # We will try to do this in 2 passes through the postscript since
862: # the postscript is potentially large, to do 2 passes, the first pass
863: # must be able to calculate the total number of document pages so that
864: # at the beginning of the second pass we already know how to replace
865: # %%Pages:
866:
867: # Figure out
868: # 1. Number of pages in the document
869: # 2. Maximum number of pages in a student
870: # 3. Number of pages in each student.
871:
872: my ($postscript_filename, $latex_filename, $num_columns) = @_;
873: open(PSFILE, "<$postscript_filename");
874: my $line;
875: my $total_pages; # Total pages in document.
876: my $seen_pages = 0; # There are several %%Pages only the first is useful
877: my @pages_in_student; # For each student his/her initial page count.
878: my $max_pages = 0; # Pages in 'longest' student.
879: my $page_number = 0;
880: &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,
881: &mt("Counting pages for student: [_1]",1));
882:
883: while ($line = <PSFILE>) {
884:
885: # Check for total pages (%%Pages:)
886:
887: if (($line =~ /^%%Pages:/) && (!$seen_pages)) {
888: my @pageinfo = split(/ /,$line);
889: $total_pages = $pageinfo[1];
890: $seen_pages = 1;
891: }
892: # Check for %%Page: n m $page_number will be the
893: # biggest of these until we see an endofstudent.
894: # Note that minipages generate spurious %Page: 1 1's so
895: # we only are looking for the largest n (n is page number at the
896: # bottom of the page, m the page number within the document.
897: #
898:
899: if ($line =~ /^%%Page:\s+\d+\s+\d+/) {
900: my @pageinfo = split(/\s+/, $line);
901: if ($page_number < $pageinfo[1]) {
902: $page_number = $pageinfo[1];
903: } elsif ($pageinfo[2] ne 1) {
904: # current page count reset, and it's not because of a
905: # minipage
906: # - save the page_number, reset and, if necessary
907: # update max_pages.
908: push(@pages_in_student, $page_number);
909: &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,
910: &mt("Counting pages for student: [_1]", scalar(@pages_in_student)));
911: if ($page_number > $max_pages) {
912: $max_pages = $page_number;
913: }
914: $page_number = $pageinfo[1];
915: }
916: }
917:
918:
919: }
920: # file ended so one more student
921: push(@pages_in_student, $page_number);
922: &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,
923: &mt("Counting pages for student: [_1]",scalar(@pages_in_student)));
924: if ($page_number > $max_pages) {
925: $max_pages = $page_number;
926: }
927: $page_number = 0;
928:
929: close(PSFILE);
930:
931: # If 2 columns, max_pages must go to an even number of columns:
932:
933:
934: if ($num_columns == 2) {
935: if ($max_pages % 2) {
936: $max_pages++;
937: }
938: }
939:
940: # Now rewrite the LaTex file, substituting our \special
941: # with an appropriate number of \newpage directives.
942:
943: my $outfilename = $latex_filename."temp";
944:
945: open(LATEXIN, "<$latex_filename");
946: open(LATEXOUT, ">$outfilename");
947:
948:
949: my $student_number = 0; # Index of student we're working on.
950: &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,
951: "Repaginating student ".$student_number+1);
952:
953: while (my $line = <LATEXIN>) {
954: if ($line eq "\\special{ps:ENDOFSTUDENTSTAMP}\n") {
955: # only end of student stamp if next line is ENDOFSTUDENTSTAMP:
956:
957:
958: # End of student replace with 0 or more newpages.
959:
960: my $addlines = $max_pages - $pages_in_student[$student_number];
961: while($addlines) {
962: print LATEXOUT '\clearpage \strut \clearpage';
963:
964: $addlines--;
965: }
966:
967: $student_number++;
968: &Apache::lonhtmlcommon::Update_PrgWin('',\%prog_state,
969: "Repaginating student ".$student_number+1);
970:
971: } else {
972: print LATEXOUT $line;
973: }
974: }
975:
976: close(LATEXIN);
977: close(LATEXOUT);
978: rename($outfilename, $latex_filename);
979:
980: }
981:
982: #
983: # Create missing fonts given a latex missfonts.log file.
984: # This file will have lines like:
985: #
986: # mktexpk --mfmode ljfour --bdpi 8000 --mag 1+0/8000 --dpi 8000 tcrm0500
987: #
988: # We want to execute those lines with the 8000's changed to 600's
989: # in order to match the resolution of the ljfour printer.
990: # Of course if some wiseguy has changed the default printer from ljfour
991: # in the dvips's config.ps file that will break so we'll also
992: # ensure that --mfmode is ljfour.
993: #
994: sub create_missing_fonts {
995: my ($fontfile, $state) = @_;
996:
997: # Open and read in the font file..we'll read it into the array
998: # font_commands.
999: #
1000: open(my $font_handle, $fontfile);
1001: my @font_commands = <$font_handle>;
1002:
1003: # make the list contain each command only once
1004: my %uniq;
1005: @font_commands = map { $uniq{$_}++ == 0 ? $_ : () } @font_commands;
1006:
1007: # Now process each command replacing the appropriate 8000's with
1008: # 600's ensuring that font names with 8000's in them are not corrupted.
1009: # and if the --mfmode is not ljfour we turn it into ljfour.
1010: # Then we execute the command.
1011: #
1012:
1013: foreach my $command (@font_commands) {
1014: #print("<br />Raw command: $command");
1015: $command =~ s/ 8000/ 600/g; # dpi directives.
1016: $command =~ s/\/8000/\/600/g; # mag directives.
1017: #print("<br />After dpi replacements: $command");
1018:
1019: my @cmdarray = split(/ /,$command);
1020: for (my $i =0; $i < scalar(@cmdarray); $i++) {
1021: if ($cmdarray[$i] eq '--mfmode') {
1022: $cmdarray[$i+1] = "ljfour";
1023: }
1024: }
1025: #print("<br /> before reassembly : (@cmdarray)");
1026: $command = join(" ", (@cmdarray));
1027:
1028: #print("<br />Creating fonts via command: $command");
1029: &busy_wait_command("$command 1>/dev/null 2>/dev/null",
1030: "Creating missing font",
1031: $state);
1032:
1033: }
1034:
1035: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>