Factur-X/ZUGFeRD: in »Factur-X/ZUGFeRD« umbenannt
[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        => 'factur-x.xml',
398   #   description => $::locale->text('Factur-X/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
404   my $embed_name_ascii = $::locale->quote_special_chars('filenames', $embed_name);
405   $embed_name_ascii    =~ s{[^a-z0-9!@#$%^&*(){}[\],.+'"=_-]+}{}gi;
406
407   my @options;
408
409   my $add_opt = sub {
410     my ($name, $value) = @_;
411     return if ($value // '') eq '';
412     push @options, sprintf('%s={%s}', $name, $value); # TODO: escaping
413   };
414
415   $add_opt->('filespec',       $embed_name_ascii);
416   $add_opt->('ucfilespec',     $embed_name);
417   $add_opt->('desc',           $file->{description});
418   $add_opt->('afrelationship', $file->{relationship});
419   $add_opt->('mimetype',       $file->{mime_type});
420
421   return sprintf('\embedfile[%s]{%s}', join(',', @options), $file_name);
422 }
423
424 sub _force_mandatory_packages {
425   my ($self, @lines) = @_;
426   my @new_lines;
427
428   my %used_packages;
429   my @required_packages = qw(textcomp ulem);
430   push @required_packages, 'embedfile' if $self->{pdf_a};
431
432   foreach my $line (@lines) {
433     if ($line =~ m/\\usepackage[^\{]*{(.*?)}/) {
434       $used_packages{$1} = 1;
435
436     } elsif ($line =~ m/\\begin\{document\}/) {
437       if ($self->{pdf_a} && $self->{pdf_a}->{xmp}) {
438         my $version       = $self->{pdf_a}->{version}   // '3a';
439         my $xmp_file_name = $self->{userspath} . "/pdfa.xmp";
440         my $out           = IO::File->new($xmp_file_name, ">:encoding(utf-8)") || croak "Error creating ${xmp_file_name}: $!";
441         $out->print(Encode::encode('utf-8', $self->{pdf_a}->{xmp}));
442         $out->close;
443
444         push @new_lines, (
445           "\\usepackage[a-${version},mathxmp]{pdfx}[2018/12/22]\n",
446           "\\usepackage[genericmode]{tagpdf}\n",
447           "\\tagpdfsetup{activate-all}\n",
448           "\\hypersetup{pdfstartview=}\n",
449         );
450       }
451
452       push @new_lines, map { "\\usepackage{$_}\n" } grep { !$used_packages{$_} } @required_packages;
453       push @new_lines, $line;
454       push @new_lines, map { $self->_embed_file_directive($_) } @{ $self->{pdf_attachments} // [] };
455
456       next;
457     }
458
459     push @new_lines, $line;
460   }
461
462   return @new_lines;
463 }
464
465 sub parse {
466   my $self = $_[0];
467   local *OUT = $_[1];
468   my $form = $self->{"form"};
469
470   if (!open(IN, "$form->{templates}/$form->{IN}")) {
471     $self->{"error"} = "$form->{templates}/$form->{IN}: $!";
472     return 0;
473   }
474   binmode IN, ":utf8";
475   my @lines = <IN>;
476   close(IN);
477
478   $self->_parse_config_lines(\@lines);
479   @lines = $self->_force_mandatory_packages(@lines) if (ref $self eq 'SL::Template::LaTeX');
480
481   my $contents = join("", @lines);
482
483   # detect pagebreak block and its parameters
484   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) {
485     $self->{"chars_per_line"} = $3;
486     $self->{"lines_on_first_page"} = $4;
487     $self->{"lines_on_second_page"} = $5;
488     $self->{"pagebreak_block"} = $6;
489
490     substr($contents, length($1), length($2)) = "";
491   }
492
493   $self->{"forced_pagebreaks"} = [];
494
495   my $new_contents;
496   if ($self->{use_template_toolkit}) {
497     if ($self->{custom_tag_style}) {
498       $contents = "[% TAGS $self->{tag_start} $self->{tag_end} %]\n" . $contents;
499     }
500
501     my $globals = global_vars();
502
503     $::form->template->process(\$contents, { %$form, %$globals }, \$new_contents) || die $::form->template->error;
504   } else {
505     $new_contents = $self->parse_block($contents);
506   }
507   if (!defined($new_contents)) {
508     $main::lxdebug->leave_sub();
509     return 0;
510   }
511
512   binmode OUT, ":utf8";
513   print OUT Unicode::Normalize::normalize('C', $new_contents);
514
515   if ($form->{"format"} =~ /postscript/i) {
516     return $self->convert_to_postscript();
517   } elsif ($form->{"format"} =~ /pdf/i) {
518     return $self->convert_to_pdf();
519   } else {
520     return 1;
521   }
522 }
523
524 sub _texinputs_path {
525   my ($self, $templates_path) = @_;
526
527   my $exe_dir     = SL::System::Process::exe_dir();
528   $templates_path = $exe_dir . '/' . $templates_path unless $templates_path =~ m{^/};
529
530   return join(':', grep({ $_ } ('.', $exe_dir . '/texmf', $exe_dir . '/users', $templates_path, $ENV{TEXINPUTS})), '');
531 }
532
533 sub convert_to_postscript {
534   my ($self) = @_;
535   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
536
537   # Convert the tex file to postscript
538   local $ENV{TEXINPUTS} = $self->_texinputs_path($form->{templates});
539
540   if (!chdir("$userspath")) {
541     $self->{"error"} = "chdir : $!";
542     $self->cleanup();
543     return 0;
544   }
545
546   $form->{tmpfile} =~ s/\Q$userspath\E\///g;
547
548   my $latex = $self->_get_latex_path();
549   my $old_home = $ENV{HOME};
550   my $old_openin_any = $ENV{openin_any};
551   $ENV{HOME}   = $userspath =~ m|^/| ? $userspath : getcwd();
552   $ENV{openin_any} = "r";
553
554   for (my $run = 1; $run <= 2; $run++) {
555     if (system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
556                "> $form->{tmpfile}.err") == -1) {
557       die "system call to $latex failed: $!";
558     }
559     if ($?) {
560       $ENV{HOME} = $old_home;
561       $ENV{openin_any} = $old_openin_any;
562       $self->{"error"} = $form->cleanup($latex);
563       return 0;
564     }
565   }
566
567   $form->{tmpfile} =~ s/tex$/dvi/;
568
569   if (system("dvips $form->{tmpfile} -o -q > /dev/null") == -1) {
570     die "system call to dvips failed: $!";
571   }
572   $ENV{HOME} = $old_home;
573   $ENV{openin_any} = $old_openin_any;
574
575   if ($?) {
576     $self->{"error"} = "dvips : $?";
577     $self->cleanup('dvips');
578     return 0;
579   }
580   $form->{tmpfile} =~ s/dvi$/ps/;
581
582   $self->cleanup();
583
584   return 1;
585 }
586
587 sub convert_to_pdf {
588   my ($self) = @_;
589   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
590
591   # Convert the tex file to PDF
592   local $ENV{TEXINPUTS} = $self->_texinputs_path($form->{templates});
593
594   if (!chdir("$userspath")) {
595     $self->{"error"} = "chdir : $!";
596     $self->cleanup();
597     return 0;
598   }
599
600   $form->{tmpfile} =~ s/\Q$userspath\E\///g;
601
602   my $latex = $self->_get_latex_path();
603   my $old_home = $ENV{HOME};
604   my $old_openin_any = $ENV{openin_any};
605   $ENV{HOME}   = $userspath =~ m|^/| ? $userspath : getcwd();
606   $ENV{openin_any} = "r";
607
608   for (my $run = 1; $run <= 2; $run++) {
609     if (system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
610                "> $form->{tmpfile}.err") == -1) {
611       die "system call to $latex failed: $!";
612     }
613
614     if ($?) {
615       $ENV{HOME}     = $old_home;
616       $ENV{openin_any} = $old_openin_any;
617       $self->{error} = $form->cleanup($latex);
618       return 0;
619     }
620   }
621
622   $ENV{HOME} = $old_home;
623   $ENV{openin_any} = $old_openin_any;
624   $form->{tmpfile} =~ s/tex$/pdf/;
625
626   $self->cleanup();
627
628   return 1;
629 }
630
631 sub _get_latex_path {
632   return $::lx_office_conf{applications}->{latex} || 'pdflatex';
633 }
634
635 sub get_mime_type() {
636   my ($self) = @_;
637
638   if ($self->{"form"}->{"format"} =~ /postscript/i) {
639     return "application/postscript";
640   } else {
641     return "application/pdf";
642   }
643 }
644
645 sub uses_temp_file {
646   return 1;
647 }
648
649 sub parse_and_create_pdf {
650   my ($class, $template_file_name, %params) = @_;
651
652   my $userspath                = delete($params{userspath}) || $::lx_office_conf{paths}->{userspath};
653   my $keep_temp                = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
654   my ($tex_fh, $tex_file_name) = File::Temp::tempfile(
655     'kivitendo-printXXXXXX',
656     SUFFIX => '.tex',
657     DIR    => $userspath,
658     UNLINK => $keep_temp ? 0 : 1,,
659   );
660
661   my $old_wd               = getcwd();
662
663   my $local_form           = Form->new('');
664   $local_form->{cwd}       = $old_wd;
665   $local_form->{IN}        = $template_file_name;
666   $local_form->{tmpdir}    = $userspath;
667   $local_form->{tmpfile}   = $tex_file_name;
668   $local_form->{templates} = SL::DB::Default->get->templates;
669
670   foreach (keys %params) {
671     croak "The parameter '$_' must not be used." if exists $local_form->{$_};
672     $local_form->{$_} = $params{$_};
673   }
674
675   my $error;
676   eval {
677     my $template = SL::Template::LaTeX->new(file_name => $template_file_name, form => $local_form, userspath => $userspath);
678     my $result   = $template->parse($tex_fh) && $template->convert_to_pdf;
679
680     die $template->{error} unless $result;
681
682     1;
683   } or do { $error = $EVAL_ERROR; };
684
685   chdir $old_wd;
686   close $tex_fh;
687
688   if ($keep_temp) {
689     chmod(((stat $tex_file_name)[2] & 07777) | 0660, $tex_file_name);
690   } else {
691     my $tmpfile =  $tex_file_name;
692     $tmpfile    =~ s/\.\w+$//;
693     unlink(grep { !m/\.pdf$/ } <$tmpfile.*>);
694   }
695
696   return (error     => $error) if $error;
697   return (file_name => do { $tex_file_name =~ s/tex$/pdf/; $tex_file_name });
698 }
699
700 sub global_vars {
701   {
702     AUTH            => $::auth,
703     INSTANCE_CONF   => $::instance_conf,
704     LOCALE          => $::locale,
705     LXCONFIG        => $::lx_office_conf,
706     LXDEBUG         => $::lxdebug,
707     MYCONFIG        => \%::myconfig,
708   };
709 }
710
711 1;