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