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