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