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