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