d4b336b884f67c820ed7cad4910a4e6a98d381c3
[kivitendo-erp.git] / SL / Template / LaTeX.pm
1 package SL::Template::LaTeX;
2
3 use parent qw(SL::Template::Simple);
4
5 use strict;
6
7 use Carp;
8 use Cwd;
9 use English qw(-no_match_vars);
10 use File::Basename;
11 use File::Temp;
12 use HTML::Entities ();
13 use List::MoreUtils qw(any);
14 use Scalar::Util qw(blessed);
15 use Unicode::Normalize qw();
16
17 use SL::DB::Default;
18 use SL::System::Process;
19
20 my %text_markup_replace = (
21   b => 'textbf',
22   i => 'textit',
23   u => 'underline',
24 );
25
26 sub _format_text {
27   my ($self, $content, %params) = @_;
28
29   $content = $::locale->quote_special_chars('Template/LaTeX', $content);
30
31   # Allow some HTML markup to be converted into the output format's
32   # corresponding markup code, e.g. bold or italic.
33   foreach my $key (keys(%text_markup_replace)) {
34     my $new   =  $text_markup_replace{$key};
35     $content =~ s/\$\<\$${key}\$\>\$(.*?)\$<\$\/${key}\$>\$/\\${new}\{$1\}/gi;
36   }
37
38   $content =~ s/[\x00-\x1f]//g;
39
40   return $content;
41 }
42
43 my %html_replace = (
44   '</p>'      => "\n\n",
45   '<ul>'      => "\\begin{itemize} ",
46   '</ul>'     => "\\end{itemize} ",
47   '<ol>'      => "\\begin{enumerate} ",
48   '</ol>'     => "\\end{enumerate} ",
49   '<li>'      => "\\item ",
50   '</li>'     => " ",
51   '<b>'       => "\\textbf{",
52   '</b>'      => "}",
53   '<strong>'  => "\\textbf{",
54   '</strong>' => "}",
55   '<i>'       => "\\textit{",
56   '</i>'      => "}",
57   '<em>'      => "\\textit{",
58   '</em>'     => "}",
59   '<u>'       => "\\underline{",
60   '</u>'      => "}",
61   '<s>'       => "\\sout{",
62   '</s>'      => "}",
63   '<sub>'     => "\\textsubscript{",
64   '</sub>'    => "}",
65   '<sup>'     => "\\textsuperscript{",
66   '</sup>'    => "}",
67   '<br/>'     => "\\newline ",
68   '<br>'      => "\\newline ",
69 );
70
71 sub _lb_to_space {
72   my ($to_replace) = @_;
73
74   my $vspace = '\vspace*{0.5cm}';
75   return $vspace x (length($to_replace) / length($html_replace{'<br>'}));
76 }
77
78 sub _format_html {
79   my ($self, $content, %params) = @_;
80
81   $content =~ s{ \r+ }{}gx;
82   $content =~ s{ \n+ }{ }gx;
83   $content =~ s{ (?:\&nbsp;|\s)+ }{ }gx;
84   $content =~ s{ (?:\&nbsp;|\s)+$ }{}gx;
85   $content =~ s{ (?: <br/?> )+$ }{}gx;
86
87   my @parts = grep { $_ } map {
88     if (substr($_, 0, 1) eq '<') {
89       s{ +}{}g;
90       $html_replace{$_} || '';
91
92     } else {
93       $::locale->quote_special_chars('Template/LaTeX', HTML::Entities::decode_entities($_));
94     }
95   } split(m{(<.*?>)}x, $content);
96
97   $content =  join '', @parts;
98   $content =~ s{ (?: [\n\s] | \\newline )+ $ }{}gx;                                         # remove line breaks at the end of the text
99   $content =~ s{ ^ \s+ }{}gx;                                                               # remove white space at the start of the text
100   $content =~ s{ ^ ( \\newline \  )+ }{ _lb_to_space($1) }gxe;                              # convert line breaks at the start of the text to vertical space
101   $content =~ s{ ( \n\n+ ) ( \\newline \  )+ }{ $1 . _lb_to_space($2) }gxe;                 # convert line breaks at the start of a paragraph to vertical space
102   $content =~ s{ ( \\end\{ [^\}]+ \} \h* ) ( \\newline \  )+ }{ $1 . _lb_to_space($2) }gxe; # convert line breaks after LaTeX environments like lists to vertical space
103   $content =~ s{ ^ \h+ \\newline }{\\newline}gmx;
104   $content =~ s{ \n\n \h* \\newline \h* }{\n\n}gmx;
105
106   return $content;
107 }
108
109 my %formatters = (
110   html => \&_format_html,
111   text => \&_format_text,
112 );
113
114 sub new {
115   my $type = shift;
116
117   my $self = $type->SUPER::new(@_);
118
119   return $self;
120 }
121
122 sub format_string {
123   my ($self, $content, $variable) = @_;
124
125   my $formatter =
126        $formatters{ $self->{variable_content_types}->{$variable} }
127     // $formatters{ $self->{default_content_type} }
128     // $formatters{ text };
129
130   $content  =~ s{[^\p{Print}\n]|\p{Cf}}{}g;
131   $variable =~ s{[^\p{Print}\n]|\p{Cf}}{}g;
132
133   return $formatter->($self, $content, variable => $variable);
134 }
135
136 sub parse_foreach {
137   my ($self, $var, $text, $start_tag, $end_tag, @indices) = @_;
138
139   my ($form, $new_contents) = ($self->{"form"}, "");
140
141   my $ary = $self->_get_loop_variable($var, 1, @indices);
142
143   my $sum                          = 0;
144   my $current_page                 = 1;
145   my ($current_line, $corrent_row) = (0, 1);
146   my $description_array            = $self->_get_loop_variable("description",     1);
147   my $longdescription_array        = $self->_get_loop_variable("longdescription", 1);
148   my $linetotal_array              = $self->_get_loop_variable("linetotal",       1);
149
150   $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal} = [];
151
152   # forech block hasn't given us an array. ignore
153   return $new_contents unless ref $ary eq 'ARRAY';
154
155   for (my $i = 0; $i < scalar(@{$ary}); $i++) {
156     # do magic markers
157     $form->{"__first__"}   = $i == 0;
158     $form->{"__last__"}    = ($i + 1) == scalar(@{$ary});
159     $form->{"__odd__"}     = (($i + 1) % 2) == 1;
160     $form->{"__counter__"} = $i + 1;
161
162   #everything from here to the next marker should be removed after the release of 2.7.0
163     if (   ref $description_array       eq 'ARRAY'
164         && scalar @{$description_array} == scalar @{$ary}
165         && $self->{"chars_per_line"}    != 0)
166     {
167       my $lines = int(length($description_array->[$i]) / $self->{"chars_per_line"});
168       my $lpp;
169
170       $description_array->[$i] =~ s/(\\newline\s?)*$//;
171       $lines++ while ($description_array->[$i] =~ m/\\newline/g);
172       $lines++;
173
174       if ($current_page == 1) {
175         $lpp = $self->{"lines_on_first_page"};
176       } else {
177         $lpp = $self->{"lines_on_second_page"};
178       }
179
180       # Yes we need a manual page break -- or the user has forced one
181       if (   (($current_line + $lines) > $lpp)
182           || ($description_array->[$i]     =~ /<pagebreak>/)
183           || (   ref $longdescription_array eq 'ARRAY'
184               && $longdescription_array->[$i] =~ /<pagebreak>/)) {
185         my $pb = $self->{"pagebreak_block"};
186
187         # replace the special variables <%sumcarriedforward%>
188         # and <%lastpage%>
189
190         my $psum = $form->format_amount($self->{"myconfig"}, $sum, 2);
191         $pb =~ s/$self->{tag_start_qm}sumcarriedforward$self->{tag_end_qm}/$psum/g;
192         $pb =~ s/$self->{tag_start_qm}lastpage$self->{tag_end_qm}/$current_page/g;
193
194         my $new_text = $self->parse_block($pb, (@indices, $i));
195         return undef unless (defined($new_text));
196         $new_contents .= $new_text;
197
198         $current_page++;
199         $current_line = 0;
200       }
201       $current_line += $lines;
202     }
203   #stop removing code here.
204
205     if (   ref $linetotal_array eq 'ARRAY'
206         && $i < scalar(@{$linetotal_array})) {
207       $sum += $form->parse_amount($self->{"myconfig"}, $linetotal_array->[$i]);
208     }
209
210     $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal}->[$i] = $form->format_amount($self->{"myconfig"}, $sum, 2);
211
212     my $new_text = $self->parse_block($text, (@indices, $i));
213     return undef unless (defined($new_text));
214     $new_contents .= $start_tag . $new_text . $end_tag;
215   }
216   map({ delete($form->{"__${_}__"}); } qw(first last odd counter));
217
218   return $new_contents;
219 }
220
221 sub find_end {
222   my ($self, $text, $pos, $var, $not) = @_;
223
224   my $tag_start_len = length $self->{tag_start};
225
226   my $depth = 1;
227   $pos = 0 unless ($pos);
228
229   while ($pos < length($text)) {
230     $pos++;
231
232     next if (substr($text, $pos - 1, length($self->{tag_start})) ne $self->{tag_start});
233
234     my $keyword_pos = $pos - 1 + $tag_start_len;
235
236     if ((substr($text, $keyword_pos, 2) eq 'if') || (substr($text, $keyword_pos, 7) eq 'foreach')) {
237       $depth++;
238
239     } elsif ((substr($text, $keyword_pos, 4) eq 'else') && (1 == $depth)) {
240       if (!$var) {
241         $self->{"error"} =
242             "$self->{tag_start}else$self->{tag_end} outside of "
243           . "$self->{tag_start}if$self->{tag_end} / "
244           . "$self->{tag_start}ifnot$self->{tag_end}.";
245         return undef;
246       }
247
248       my $block = substr($text, 0, $pos - 1);
249       substr($text, 0, $pos - 1) = "";
250       $text =~ s!^$self->{tag_start_qm}.+?$self->{tag_end_qm}!!;
251       $text =  $self->{tag_start} . 'if' . ($not ?  " " : "not ") . $var . $self->{tag_end} . $text;
252
253       return ($block, $text);
254
255     } elsif (substr($text, $keyword_pos, 3) eq 'end') {
256       $depth--;
257       if ($depth == 0) {
258         my $block = substr($text, 0, $pos - 1);
259         substr($text, 0, $pos - 1) = "";
260         $text =~ s!^$self->{tag_start_qm}.+?$self->{tag_end_qm}!!;
261
262         return ($block, $text);
263       }
264     }
265   }
266
267   return undef;
268 }
269
270 sub parse_block {
271   $main::lxdebug->enter_sub();
272
273   my ($self, $contents, @indices) = @_;
274
275   my $new_contents = "";
276
277   while ($contents ne "") {
278     my $pos_if      = index($contents, $self->{tag_start} . 'if');
279     my $pos_foreach = index($contents, $self->{tag_start} . 'foreach');
280
281     if ((-1 == $pos_if) && (-1 == $pos_foreach)) {
282       $new_contents .= $self->substitute_vars($contents, @indices);
283       last;
284     }
285
286     if ((-1 == $pos_if) || ((-1 != $pos_foreach) && ($pos_if > $pos_foreach))) {
287       $new_contents .= $self->substitute_vars(substr($contents, 0, $pos_foreach), @indices);
288       substr($contents, 0, $pos_foreach) = "";
289
290       if ($contents !~ m|^($self->{tag_start_qm}foreach (.+?)$self->{tag_end_qm})|) {
291         $self->{"error"} = "Malformed $self->{tag_start}foreach$self->{tag_end}.";
292         $main::lxdebug->leave_sub();
293         return undef;
294       }
295
296       my $var = $2;
297
298       substr($contents, 0, length($1)) = "";
299
300       my $block;
301       ($block, $contents) = $self->find_end($contents);
302       if (!$block) {
303         $self->{"error"} = "Unclosed $self->{tag_start}foreach$self->{tag_end}." unless ($self->{"error"});
304         $main::lxdebug->leave_sub();
305         return undef;
306       }
307
308       my $new_text = $self->parse_foreach($var, $block, "", "", @indices);
309       if (!defined($new_text)) {
310         $main::lxdebug->leave_sub();
311         return undef;
312       }
313       $new_contents .= $new_text;
314
315     } else {
316       if (!$self->_parse_block_if(\$contents, \$new_contents, $pos_if, @indices)) {
317         $main::lxdebug->leave_sub();
318         return undef;
319       }
320     }
321   }
322
323   $main::lxdebug->leave_sub();
324
325   return $new_contents;
326 }
327
328 sub parse_first_line {
329   my $self = shift;
330   my $line = shift || "";
331
332   if ($line =~ m/([^\s]+)set-tag-style([^\s]+)/) {
333     if ($1 eq $2) {
334       $self->{error} = "The tag start and end markers must not be equal.";
335       return 0;
336     }
337
338     $self->set_tag_style($1, $2);
339   }
340
341   return 1;
342 }
343
344 sub _parse_config_option {
345   my $self = shift;
346   my $line = shift;
347
348   $line =~ s/^\s*//;
349   $line =~ s/\s*$//;
350
351   my ($key, $value) = split m/\s*=\s*/, $line, 2;
352
353   if ($key eq 'tag-style') {
354     $self->set_tag_style(split(m/\s+/, $value, 2));
355   }
356   if ($key eq 'use-template-toolkit') {
357     $self->set_use_template_toolkit($value);
358   }
359 }
360
361 sub _parse_config_lines {
362   my $self  = shift;
363   my $lines = shift;
364
365   my ($comment_start, $comment_end) = ("", "");
366
367   if (ref $self eq 'SL::Template::LaTeX') {
368     $comment_start = '\s*%';
369   } elsif (ref $self eq 'SL::Template::HTML') {
370     $comment_start = '\s*<!--';
371     $comment_end   = '(?:--)?>\s*';
372   } else {
373     $comment_start = '\s*\#';
374   }
375
376   my $num_lines = scalar @{ $lines };
377   my $i         = 0;
378
379   while ($i < $num_lines) {
380     my $line = $lines->[$i];
381
382     if ($line !~ m/^${comment_start}\s*config\s*:(.*?)${comment_end}$/i) {
383       $i++;
384       next;
385     }
386
387     $self->_parse_config_option($1);
388     splice @{ $lines }, $i, 1;
389     $num_lines--;
390   }
391 }
392
393 sub _embed_file_directive {
394   my ($self, $file) = @_;
395
396   # { source      => $xmlfile,
397   #   name        => 'ZUGFeRD-invoice.xml',
398   #   description => $::locale->text('ZUGFeRD invoice'), }
399
400   my $file_name  =  blessed($file->{source}) && $file->{source}->can('filename') ? $file->{source}->filename : "" . $file->{source}->filename;
401   my $embed_name =  $file->{name} // $file_name;
402   $embed_name    =~ s{.*/}{};
403   my @options;
404
405   my $add_opt = sub {
406     my ($name, $value) = @_;
407     return if ($value // '') eq '';
408     push @options, sprintf('%s={%s}', $name, $value); # TODO: escaping
409   };
410
411  $add_opt->('ucfilespec',     $embed_name);
412  $add_opt->('desc',           $file->{description});
413  $add_opt->('afrelationship', $file->{relationship});
414  $add_opt->('mimetype',       $file->{mime_type});
415
416   return sprintf('\embedfile[%s]{%s}', join(',', @options), $file_name);
417 }
418
419 sub _force_mandatory_packages {
420   my ($self, @lines) = @_;
421   my @new_lines;
422
423   my (%used_packages, $at_beginning_of_document);
424   my @required_packages = qw(textcomp ulem);
425   push @required_packages, 'embedfile' if $self->{pdf_a};
426
427   foreach my $line (@lines) {
428     if ($line =~ m/\\usepackage[^\{]*{(.*?)}/) {
429       $used_packages{$1} = 1;
430
431     } elsif (($line =~ m/\\documentclass/) && $self->{pdf_a}) {
432       my $version = $self->{pdf_a}->{version}   // '3a';
433       my $meta    = $self->{pdf_a}->{meta_data} // {};
434
435       push @new_lines, (
436         "\\RequirePackage{filecontents}\n",
437         "\\begin{filecontents*}{\\jobname.xmpdata}\n",
438         ($meta->{title}    ? sprintf("\\Title{%s}\n",    $meta->{title})    : ""),
439         ($meta->{author}   ? sprintf("\\Author{%s}\n",   $meta->{author})   : ""),
440         ($meta->{language} ? sprintf("\\Language{%s}\n", $meta->{language}) : ""),
441         "\\end{filecontents*}\n",
442         $line,
443         "\\usepackage[a-${version},mathxmp]{pdfx}[2018/12/22]\n",
444         "\\usepackage[genericmode]{tagpdf}\n",
445         "\\tagpdfsetup{activate-all}\n",
446         "\\hypersetup{pdfstartview=}\n",
447       );
448
449       next;
450
451     } elsif ($line =~ m/\\begin\{document\}/) {
452       $at_beginning_of_document = 1;
453       push @new_lines, map { "\\usepackage{$_}\n" } grep { !$used_packages{$_} } @required_packages;
454     }
455
456     push @new_lines, $line;
457
458     if ($at_beginning_of_document) {
459       $at_beginning_of_document = 0;
460
461       push @new_lines, map { $self->_embed_file_directive($_) } @{ $self->{pdf_attachments} // [] };
462     }
463   }
464
465   return @new_lines;
466 }
467
468 sub parse {
469   my $self = $_[0];
470   local *OUT = $_[1];
471   my $form = $self->{"form"};
472
473   if (!open(IN, "$form->{templates}/$form->{IN}")) {
474     $self->{"error"} = "$form->{templates}/$form->{IN}: $!";
475     return 0;
476   }
477   binmode IN, ":utf8";
478   my @lines = <IN>;
479   close(IN);
480
481   $self->_parse_config_lines(\@lines);
482   @lines = $self->_force_mandatory_packages(@lines) if (ref $self eq 'SL::Template::LaTeX');
483
484   my $contents = join("", @lines);
485
486   # detect pagebreak block and its parameters
487   if ($contents =~ /^(.*)($self->{tag_start_qm}pagebreak\s+(\d+)\s+(\d+)\s+(\d+)\s*$self->{tag_end_qm}(.*?)$self->{tag_start_qm}end(\s*pagebreak)?$self->{tag_end_qm})/s) {
488     $self->{"chars_per_line"} = $3;
489     $self->{"lines_on_first_page"} = $4;
490     $self->{"lines_on_second_page"} = $5;
491     $self->{"pagebreak_block"} = $6;
492
493     substr($contents, length($1), length($2)) = "";
494   }
495
496   $self->{"forced_pagebreaks"} = [];
497
498   my $new_contents;
499   if ($self->{use_template_toolkit}) {
500     if ($self->{custom_tag_style}) {
501       $contents = "[% TAGS $self->{tag_start} $self->{tag_end} %]\n" . $contents;
502     }
503
504     my $globals = global_vars();
505
506     $::form->template->process(\$contents, { %$form, %$globals }, \$new_contents) || die $::form->template->error;
507   } else {
508     $new_contents = $self->parse_block($contents);
509   }
510   if (!defined($new_contents)) {
511     $main::lxdebug->leave_sub();
512     return 0;
513   }
514
515   binmode OUT, ":utf8";
516   print OUT Unicode::Normalize::normalize('C', $new_contents);
517
518   if ($form->{"format"} =~ /postscript/i) {
519     return $self->convert_to_postscript();
520   } elsif ($form->{"format"} =~ /pdf/i) {
521     return $self->convert_to_pdf();
522   } else {
523     return 1;
524   }
525 }
526
527 sub _texinputs_path {
528   my ($self, $templates_path) = @_;
529
530   my $exe_dir     = SL::System::Process::exe_dir();
531   $templates_path = $exe_dir . '/' . $templates_path unless $templates_path =~ m{^/};
532
533   return join(':', grep({ $_ } ('.', $exe_dir . '/texmf', $templates_path, $ENV{TEXINPUTS})), '');
534 }
535
536 sub convert_to_postscript {
537   my ($self) = @_;
538   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
539
540   # Convert the tex file to postscript
541   local $ENV{TEXINPUTS} = $self->_texinputs_path($form->{templates});
542
543   if (!chdir("$userspath")) {
544     $self->{"error"} = "chdir : $!";
545     $self->cleanup();
546     return 0;
547   }
548
549   $form->{tmpfile} =~ s/\Q$userspath\E\///g;
550
551   my $latex = $self->_get_latex_path();
552   my $old_home = $ENV{HOME};
553   my $old_openin_any = $ENV{openin_any};
554   $ENV{HOME}   = $userspath =~ m|^/| ? $userspath : getcwd();
555   $ENV{openin_any} = "r";
556
557   for (my $run = 1; $run <= 2; $run++) {
558     if (system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
559                "> $form->{tmpfile}.err") == -1) {
560       die "system call to $latex failed: $!";
561     }
562     if ($?) {
563       $ENV{HOME} = $old_home;
564       $ENV{openin_any} = $old_openin_any;
565       $self->{"error"} = $form->cleanup($latex);
566       return 0;
567     }
568   }
569
570   $form->{tmpfile} =~ s/tex$/dvi/;
571
572   if (system("dvips $form->{tmpfile} -o -q > /dev/null") == -1) {
573     die "system call to dvips failed: $!";
574   }
575   $ENV{HOME} = $old_home;
576   $ENV{openin_any} = $old_openin_any;
577
578   if ($?) {
579     $self->{"error"} = "dvips : $?";
580     $self->cleanup('dvips');
581     return 0;
582   }
583   $form->{tmpfile} =~ s/dvi$/ps/;
584
585   $self->cleanup();
586
587   return 1;
588 }
589
590 sub convert_to_pdf {
591   my ($self) = @_;
592   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
593
594   # Convert the tex file to PDF
595   local $ENV{TEXINPUTS} = $self->_texinputs_path($form->{templates});
596
597   if (!chdir("$userspath")) {
598     $self->{"error"} = "chdir : $!";
599     $self->cleanup();
600     return 0;
601   }
602
603   $form->{tmpfile} =~ s/\Q$userspath\E\///g;
604
605   my $latex = $self->_get_latex_path();
606   my $old_home = $ENV{HOME};
607   my $old_openin_any = $ENV{openin_any};
608   $ENV{HOME}   = $userspath =~ m|^/| ? $userspath : getcwd();
609   $ENV{openin_any} = "r";
610
611   for (my $run = 1; $run <= 2; $run++) {
612     if (system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
613                "> $form->{tmpfile}.err") == -1) {
614       die "system call to $latex failed: $!";
615     }
616
617     if ($?) {
618       $ENV{HOME}     = $old_home;
619       $ENV{openin_any} = $old_openin_any;
620       $self->{error} = $form->cleanup($latex);
621       return 0;
622     }
623   }
624
625   $ENV{HOME} = $old_home;
626   $ENV{openin_any} = $old_openin_any;
627   $form->{tmpfile} =~ s/tex$/pdf/;
628
629   $self->cleanup();
630
631   return 1;
632 }
633
634 sub _get_latex_path {
635   return $::lx_office_conf{applications}->{latex} || 'pdflatex';
636 }
637
638 sub get_mime_type() {
639   my ($self) = @_;
640
641   if ($self->{"form"}->{"format"} =~ /postscript/i) {
642     return "application/postscript";
643   } else {
644     return "application/pdf";
645   }
646 }
647
648 sub uses_temp_file {
649   return 1;
650 }
651
652 sub parse_and_create_pdf {
653   my ($class, $template_file_name, %params) = @_;
654
655   my $keep_temp                = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
656   my ($tex_fh, $tex_file_name) = File::Temp::tempfile(
657     'kivitendo-printXXXXXX',
658     SUFFIX => '.tex',
659     DIR    => $::lx_office_conf{paths}->{userspath},
660     UNLINK => $keep_temp ? 0 : 1,,
661   );
662
663   my $old_wd               = getcwd();
664
665   my $local_form           = Form->new('');
666   $local_form->{cwd}       = $old_wd;
667   $local_form->{IN}        = $template_file_name;
668   $local_form->{tmpdir}    = $::lx_office_conf{paths}->{userspath};
669   $local_form->{tmpfile}   = $tex_file_name;
670   $local_form->{templates} = SL::DB::Default->get->templates;
671
672   foreach (keys %params) {
673     croak "The parameter '$_' must not be used." if exists $local_form->{$_};
674     $local_form->{$_} = $params{$_};
675   }
676
677   my $error;
678   eval {
679     my $template = SL::Template::LaTeX->new(file_name => $template_file_name, form => $local_form);
680     my $result   = $template->parse($tex_fh) && $template->convert_to_pdf;
681
682     die $template->{error} unless $result;
683
684     1;
685   } or do { $error = $EVAL_ERROR; };
686
687   chdir $old_wd;
688   close $tex_fh;
689
690   if ($keep_temp) {
691     chmod(((stat $tex_file_name)[2] & 07777) | 0660, $tex_file_name);
692   } else {
693     my $tmpfile =  $tex_file_name;
694     $tmpfile    =~ s/\.\w+$//;
695     unlink(grep { !m/\.pdf$/ } <$tmpfile.*>);
696   }
697
698   return (error     => $error) if $error;
699   return (file_name => do { $tex_file_name =~ s/tex$/pdf/; $tex_file_name });
700 }
701
702 sub global_vars {
703   {
704     AUTH            => $::auth,
705     INSTANCE_CONF   => $::instance_conf,
706     LOCALE          => $::locale,
707     LXCONFIG        => $::lx_office_conf,
708     LXDEBUG         => $::lxdebug,
709     MYCONFIG        => \%::myconfig,
710   };
711 }
712
713 1;