SL/Template.pm in eine Datei pro Package aufgeteilt.
[kivitendo-erp.git] / SL / Template / LaTeX.pm
1 package SL::Template::LaTeX;
2
3 use vars qw(@ISA);
4
5 use SL::Template;
6 @ISA = qw(SL::Template::Simple);
7
8 use strict;
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 == 1;
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, 3) eq 'for')) {
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);
297
298   foreach my $i (0 .. scalar @{ $lines } - 1) {
299     if ($lines->[$i] =~ m/\\usepackage[^\{]*{(.*?)}/) {
300       $used_packages{$1} = 1;
301
302     } elsif ($lines->[$i] =~ m/\\begin{document}/) {
303       $document_start_line = $i;
304       last;
305
306     }
307   }
308
309   $document_start_line = scalar @{ $lines } - 1 if (!defined $document_start_line);
310
311   if (!$used_packages{textcomp}) {
312     splice @{ $lines }, $document_start_line, 0, "\\usepackage{textcomp}\n";
313     $document_start_line++;
314   }
315 }
316
317 sub parse {
318   my $self = $_[0];
319   local *OUT = $_[1];
320   my $form = $self->{"form"};
321
322   if (!open(IN, "$form->{templates}/$form->{IN}")) {
323     $self->{"error"} = "$!";
324     return 0;
325   }
326   my @lines = <IN>;
327   close(IN);
328
329   $self->_parse_config_lines(\@lines);
330   $self->_force_mandatory_packages(\@lines) if (ref $self eq 'SL::Template::LaTeX');
331
332   my $contents = join("", @lines);
333
334   # detect pagebreak block and its parameters
335   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) {
336     $self->{"chars_per_line"} = $1;
337     $self->{"lines_on_first_page"} = $2;
338     $self->{"lines_on_second_page"} = $3;
339     $self->{"pagebreak_block"} = $4;
340
341     substr($contents, length($`), length($&)) = "";
342   }
343
344   $self->{"forced_pagebreaks"} = [];
345
346   my $new_contents = $self->parse_block($contents);
347   if (!defined($new_contents)) {
348     $main::lxdebug->leave_sub();
349     return 0;
350   }
351
352   print(OUT $new_contents);
353
354   if ($form->{"format"} =~ /postscript/i) {
355     return $self->convert_to_postscript();
356   } elsif ($form->{"format"} =~ /pdf/i) {
357     return $self->convert_to_pdf();
358   } else {
359     return 1;
360   }
361 }
362
363 sub convert_to_postscript {
364   my ($self) = @_;
365   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
366
367   # Convert the tex file to postscript
368
369   if (!chdir("$userspath")) {
370     $self->{"error"} = "chdir : $!";
371     $self->cleanup();
372     return 0;
373   }
374
375   $form->{tmpfile} =~ s/\Q$userspath\E\///g;
376
377   my $latex = $self->_get_latex_path();
378
379   for (my $run = 1; $run <= 2; $run++) {
380     system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
381            "> $form->{tmpfile}.err");
382     if ($?) {
383       $self->{"error"} = $form->cleanup();
384       $self->cleanup();
385       return 0;
386     }
387   }
388
389   $form->{tmpfile} =~ s/tex$/dvi/;
390
391   system("dvips $form->{tmpfile} -o -q > /dev/null");
392   if ($?) {
393     $self->{"error"} = "dvips : $!";
394     $self->cleanup();
395     return 0;
396   }
397   $form->{tmpfile} =~ s/dvi$/ps/;
398
399   $self->cleanup();
400
401   return 1;
402 }
403
404 sub convert_to_pdf {
405   my ($self) = @_;
406   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
407
408   # Convert the tex file to PDF
409
410   if (!chdir("$userspath")) {
411     $self->{"error"} = "chdir : $!";
412     $self->cleanup();
413     return 0;
414   }
415
416   $form->{tmpfile} =~ s/\Q$userspath\E\///g;
417
418   my $latex = $self->_get_latex_path();
419
420   for (my $run = 1; $run <= 2; $run++) {
421     system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
422            "> $form->{tmpfile}.err");
423     if ($?) {
424       $self->{"error"} = $form->cleanup();
425       $self->cleanup();
426       return 0;
427     }
428   }
429
430   $form->{tmpfile} =~ s/tex$/pdf/;
431
432   $self->cleanup();
433 }
434
435 sub _get_latex_path {
436   return $main::latex_bin || 'pdflatex';
437 }
438
439 sub get_mime_type() {
440   my ($self) = @_;
441
442   if ($self->{"form"}->{"format"} =~ /postscript/i) {
443     return "application/postscript";
444   } else {
445     return "application/pdf";
446   }
447 }
448
449 sub uses_temp_file {
450   return 1;
451 }
452
453 1;