DRY: "use parent"
[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 == 1;
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 'for')) {
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   my @lines = <IN>;
324   close(IN);
325
326   $self->_parse_config_lines(\@lines);
327   $self->_force_mandatory_packages(\@lines) if (ref $self eq 'SL::Template::LaTeX');
328
329   my $contents = join("", @lines);
330
331   # detect pagebreak block and its parameters
332   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) {
333     $self->{"chars_per_line"} = $1;
334     $self->{"lines_on_first_page"} = $2;
335     $self->{"lines_on_second_page"} = $3;
336     $self->{"pagebreak_block"} = $4;
337
338     substr($contents, length($`), length($&)) = "";
339   }
340
341   $self->{"forced_pagebreaks"} = [];
342
343   my $new_contents = $self->parse_block($contents);
344   if (!defined($new_contents)) {
345     $main::lxdebug->leave_sub();
346     return 0;
347   }
348
349   print(OUT $new_contents);
350
351   if ($form->{"format"} =~ /postscript/i) {
352     return $self->convert_to_postscript();
353   } elsif ($form->{"format"} =~ /pdf/i) {
354     return $self->convert_to_pdf();
355   } else {
356     return 1;
357   }
358 }
359
360 sub convert_to_postscript {
361   my ($self) = @_;
362   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
363
364   # Convert the tex file to postscript
365
366   if (!chdir("$userspath")) {
367     $self->{"error"} = "chdir : $!";
368     $self->cleanup();
369     return 0;
370   }
371
372   $form->{tmpfile} =~ s/\Q$userspath\E\///g;
373
374   my $latex = $self->_get_latex_path();
375
376   for (my $run = 1; $run <= 2; $run++) {
377     system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
378            "> $form->{tmpfile}.err");
379     if ($?) {
380       $self->{"error"} = $form->cleanup();
381       $self->cleanup();
382       return 0;
383     }
384   }
385
386   $form->{tmpfile} =~ s/tex$/dvi/;
387
388   system("dvips $form->{tmpfile} -o -q > /dev/null");
389   if ($?) {
390     $self->{"error"} = "dvips : $!";
391     $self->cleanup();
392     return 0;
393   }
394   $form->{tmpfile} =~ s/dvi$/ps/;
395
396   $self->cleanup();
397
398   return 1;
399 }
400
401 sub convert_to_pdf {
402   my ($self) = @_;
403   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
404
405   # Convert the tex file to PDF
406
407   if (!chdir("$userspath")) {
408     $self->{"error"} = "chdir : $!";
409     $self->cleanup();
410     return 0;
411   }
412
413   $form->{tmpfile} =~ s/\Q$userspath\E\///g;
414
415   my $latex = $self->_get_latex_path();
416
417   for (my $run = 1; $run <= 2; $run++) {
418     system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
419            "> $form->{tmpfile}.err");
420     if ($?) {
421       $self->{"error"} = $form->cleanup();
422       $self->cleanup();
423       return 0;
424     }
425   }
426
427   $form->{tmpfile} =~ s/tex$/pdf/;
428
429   $self->cleanup();
430 }
431
432 sub _get_latex_path {
433   return $main::latex_bin || 'pdflatex';
434 }
435
436 sub get_mime_type() {
437   my ($self) = @_;
438
439   if ($self->{"form"}->{"format"} =~ /postscript/i) {
440     return "application/postscript";
441   } else {
442     return "application/pdf";
443   }
444 }
445
446 sub uses_temp_file {
447   return 1;
448 }
449
450 1;