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