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