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