Vor dem Ausführen von (pdf)latex das HOME auf das users-Verzeichnis setzen
[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);
296
297   foreach my $i (0 .. scalar @{ $lines } - 1) {
298     if ($lines->[$i] =~ m/\\usepackage[^\{]*{(.*?)}/) {
299       $used_packages{$1} = 1;
300
301     } elsif ($lines->[$i] =~ m/\\begin{document}/) {
302       $document_start_line = $i;
303       last;
304
305     }
306   }
307
308   $document_start_line = scalar @{ $lines } - 1 if (!defined $document_start_line);
309
310   if (!$used_packages{textcomp}) {
311     splice @{ $lines }, $document_start_line, 0, "\\usepackage{textcomp}\n";
312     $document_start_line++;
313   }
314 }
315
316 sub parse {
317   my $self = $_[0];
318   local *OUT = $_[1];
319   my $form = $self->{"form"};
320
321   if (!open(IN, "$form->{templates}/$form->{IN}")) {
322     $self->{"error"} = "$!";
323     return 0;
324   }
325   binmode IN, ":utf8" if $::locale->is_utf8;
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   binmode OUT, ":utf8" if $::locale->is_utf8;
353   print(OUT $new_contents);
354
355   if ($form->{"format"} =~ /postscript/i) {
356     return $self->convert_to_postscript();
357   } elsif ($form->{"format"} =~ /pdf/i) {
358     return $self->convert_to_pdf();
359   } else {
360     return 1;
361   }
362 }
363
364 sub convert_to_postscript {
365   my ($self) = @_;
366   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
367
368   # Convert the tex file to postscript
369
370   if (!chdir("$userspath")) {
371     $self->{"error"} = "chdir : $!";
372     $self->cleanup();
373     return 0;
374   }
375
376   $form->{tmpfile} =~ s/\Q$userspath\E\///g;
377
378   my $latex = $self->_get_latex_path();
379   my $old_home = $ENV{HOME};
380   $ENV{HOME}   = $userspath =~ m|^/| ? $userspath : getcwd() . "/" . $userspath;
381
382   for (my $run = 1; $run <= 2; $run++) {
383     system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
384            "> $form->{tmpfile}.err");
385     if ($?) {
386       $ENV{HOME} = $old_home;
387       $self->{"error"} = $form->cleanup();
388       $self->cleanup();
389       return 0;
390     }
391   }
392
393   $form->{tmpfile} =~ s/tex$/dvi/;
394
395   system("dvips $form->{tmpfile} -o -q > /dev/null");
396   $ENV{HOME} = $old_home;
397
398   if ($?) {
399     $self->{"error"} = "dvips : $!";
400     $self->cleanup();
401     return 0;
402   }
403   $form->{tmpfile} =~ s/dvi$/ps/;
404
405   $self->cleanup();
406
407   return 1;
408 }
409
410 sub convert_to_pdf {
411   my ($self) = @_;
412   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
413
414   # Convert the tex file to PDF
415
416   if (!chdir("$userspath")) {
417     $self->{"error"} = "chdir : $!";
418     $self->cleanup();
419     return 0;
420   }
421
422   $form->{tmpfile} =~ s/\Q$userspath\E\///g;
423
424   my $latex = $self->_get_latex_path();
425   my $old_home = $ENV{HOME};
426   $ENV{HOME}   = $userspath =~ m|^/| ? $userspath : getcwd() . "/" . $userspath;
427
428   for (my $run = 1; $run <= 2; $run++) {
429     system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
430            "> $form->{tmpfile}.err");
431     if ($?) {
432       $ENV{HOME} = $old_home;
433       $self->{"error"} = $form->cleanup();
434       $self->cleanup();
435       return 0;
436     }
437   }
438
439   $ENV{HOME} = $old_home;
440   $form->{tmpfile} =~ s/tex$/pdf/;
441
442   $self->cleanup();
443 }
444
445 sub _get_latex_path {
446   return $main::latex_bin || 'pdflatex';
447 }
448
449 sub get_mime_type() {
450   my ($self) = @_;
451
452   if ($self->{"form"}->{"format"} =~ /postscript/i) {
453     return "application/postscript";
454   } else {
455     return "application/pdf";
456   }
457 }
458
459 sub uses_temp_file {
460   return 1;
461 }
462
463 1;