Refactoring: SL::Template: Parameterübergabe als Hash, nicht positionsabhängig (Teil 2)
[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 Carp;
8 use Cwd;
9 use English qw(-no_match_vars);
10 use File::Basename;
11 use File::Temp;
12 use HTML::Entities ();
13 use List::MoreUtils qw(any);
14 use Unicode::Normalize qw();
15
16 use SL::DB::Default;
17
18 my %text_markup_replace = (
19   b => 'textbf',
20   i => 'textit',
21   u => 'underline',
22 );
23
24 sub _format_text {
25   my ($self, $content, %params) = @_;
26
27   $content = $::locale->quote_special_chars('Template/LaTeX', $content);
28
29   # Allow some HTML markup to be converted into the output format's
30   # corresponding markup code, e.g. bold or italic.
31   foreach my $key (keys(%text_markup_replace)) {
32     my $new   =  $text_markup_replace{$key};
33     $content =~ s/\$\<\$${key}\$\>\$(.*?)\$<\$\/${key}\$>\$/\\${new}\{$1\}/gi;
34   }
35
36   $content =~ s/[\x00-\x1f]//g;
37
38   return $content;
39 }
40
41 my %html_replace = (
42   '</p>'      => "\n\n",
43   '<ul>'      => "\\begin{itemize} ",
44   '</ul>'     => "\\end{itemize} ",
45   '<ol>'      => "\\begin{enumerate} ",
46   '</ol>'     => "\\end{enumerate} ",
47   '<li>'      => "\\item ",
48   '</li>'     => " ",
49   '<b>'       => "\\textbf{",
50   '</b>'      => "}",
51   '<strong>'  => "\\textbf{",
52   '</strong>' => "}",
53   '<i>'       => "\\textit{",
54   '</i>'      => "}",
55   '<em>'      => "\\textit{",
56   '</em>'     => "}",
57   '<u>'       => "\\underline{",
58   '</u>'      => "}",
59   '<s>'       => "\\sout{",
60   '</s>'      => "}",
61   '<sub>'     => "\\textsubscript{",
62   '</sub>'    => "}",
63   '<sup>'     => "\\textsuperscript{",
64   '</sup>'    => "}",
65   '<br/>'     => "\\newline ",
66   '<br>'      => "\\newline ",
67 );
68
69 sub _format_html {
70   my ($self, $content, %params) = @_;
71
72   $content =~ s{ \r+ }{}gx;
73   $content =~ s{ \n+ }{ }gx;
74   $content =~ s{ (?:\&nbsp;|\s)+ }{ }gx;
75
76   my @parts = map {
77     if (substr($_, 0, 1) eq '<') {
78       s{ +}{}g;
79       $html_replace{$_} || '';
80
81     } else {
82       $::locale->quote_special_chars('Template/LaTeX', HTML::Entities::decode_entities($_));
83     }
84   } split(m{(<.*?>)}x, $content);
85
86   return join('', @parts);
87 }
88
89 my %formatters = (
90   html => \&_format_html,
91   text => \&_format_text,
92 );
93
94 sub new {
95   my $type = shift;
96
97   my $self = $type->SUPER::new(@_);
98
99   return $self;
100 }
101
102 sub format_string {
103   my ($self, $content, $variable) = @_;
104
105   my $formatter =
106        $formatters{ $self->{variable_content_types}->{$variable} }
107     // $formatters{ $self->{default_content_type} }
108     // $formatters{ text };
109
110   return $formatter->($self, $content, variable => $variable);
111 }
112
113 sub parse_foreach {
114   my ($self, $var, $text, $start_tag, $end_tag, @indices) = @_;
115
116   my ($form, $new_contents) = ($self->{"form"}, "");
117
118   my $ary = $self->_get_loop_variable($var, 1, @indices);
119
120   my $sum                          = 0;
121   my $current_page                 = 1;
122   my ($current_line, $corrent_row) = (0, 1);
123   my $description_array            = $self->_get_loop_variable("description",     1);
124   my $longdescription_array        = $self->_get_loop_variable("longdescription", 1);
125   my $linetotal_array              = $self->_get_loop_variable("linetotal",       1);
126
127   $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal} = [];
128
129   # forech block hasn't given us an array. ignore
130   return $new_contents unless ref $ary eq 'ARRAY';
131
132   for (my $i = 0; $i < scalar(@{$ary}); $i++) {
133     # do magic markers
134     $form->{"__first__"}   = $i == 0;
135     $form->{"__last__"}    = ($i + 1) == scalar(@{$ary});
136     $form->{"__odd__"}     = (($i + 1) % 2) == 1;
137     $form->{"__counter__"} = $i + 1;
138
139   #everything from here to the next marker should be removed after the release of 2.7.0
140     if (   ref $description_array       eq 'ARRAY'
141         && scalar @{$description_array} == scalar @{$ary}
142         && $self->{"chars_per_line"}    != 0)
143     {
144       my $lines = int(length($description_array->[$i]) / $self->{"chars_per_line"});
145       my $lpp;
146
147       $description_array->[$i] =~ s/(\\newline\s?)*$//;
148       $lines++ while ($description_array->[$i] =~ m/\\newline/g);
149       $lines++;
150
151       if ($current_page == 1) {
152         $lpp = $self->{"lines_on_first_page"};
153       } else {
154         $lpp = $self->{"lines_on_second_page"};
155       }
156
157       # Yes we need a manual page break -- or the user has forced one
158       if (   (($current_line + $lines) > $lpp)
159           || ($description_array->[$i]     =~ /<pagebreak>/)
160           || (   ref $longdescription_array eq 'ARRAY'
161               && $longdescription_array->[$i] =~ /<pagebreak>/)) {
162         my $pb = $self->{"pagebreak_block"};
163
164         # replace the special variables <%sumcarriedforward%>
165         # and <%lastpage%>
166
167         my $psum = $form->format_amount($self->{"myconfig"}, $sum, 2);
168         $pb =~ s/$self->{tag_start_qm}sumcarriedforward$self->{tag_end_qm}/$psum/g;
169         $pb =~ s/$self->{tag_start_qm}lastpage$self->{tag_end_qm}/$current_page/g;
170
171         my $new_text = $self->parse_block($pb, (@indices, $i));
172         return undef unless (defined($new_text));
173         $new_contents .= $new_text;
174
175         $current_page++;
176         $current_line = 0;
177       }
178       $current_line += $lines;
179     }
180   #stop removing code here.
181
182     if (   ref $linetotal_array eq 'ARRAY'
183         && $i < scalar(@{$linetotal_array})) {
184       $sum += $form->parse_amount($self->{"myconfig"}, $linetotal_array->[$i]);
185     }
186
187     $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal}->[$i] = $form->format_amount($self->{"myconfig"}, $sum, 2);
188
189     my $new_text = $self->parse_block($text, (@indices, $i));
190     return undef unless (defined($new_text));
191     $new_contents .= $start_tag . $new_text . $end_tag;
192   }
193   map({ delete($form->{"__${_}__"}); } qw(first last odd counter));
194
195   return $new_contents;
196 }
197
198 sub find_end {
199   my ($self, $text, $pos, $var, $not) = @_;
200
201   my $tag_start_len = length $self->{tag_start};
202
203   my $depth = 1;
204   $pos = 0 unless ($pos);
205
206   while ($pos < length($text)) {
207     $pos++;
208
209     next if (substr($text, $pos - 1, length($self->{tag_start})) ne $self->{tag_start});
210
211     my $keyword_pos = $pos - 1 + $tag_start_len;
212
213     if ((substr($text, $keyword_pos, 2) eq 'if') || (substr($text, $keyword_pos, 7) eq 'foreach')) {
214       $depth++;
215
216     } elsif ((substr($text, $keyword_pos, 4) eq 'else') && (1 == $depth)) {
217       if (!$var) {
218         $self->{"error"} =
219             "$self->{tag_start}else$self->{tag_end} outside of "
220           . "$self->{tag_start}if$self->{tag_end} / "
221           . "$self->{tag_start}ifnot$self->{tag_end}.";
222         return undef;
223       }
224
225       my $block = substr($text, 0, $pos - 1);
226       substr($text, 0, $pos - 1) = "";
227       $text =~ s!^$self->{tag_start_qm}.+?$self->{tag_end_qm}!!;
228       $text =  $self->{tag_start} . 'if' . ($not ?  " " : "not ") . $var . $self->{tag_end} . $text;
229
230       return ($block, $text);
231
232     } elsif (substr($text, $keyword_pos, 3) eq 'end') {
233       $depth--;
234       if ($depth == 0) {
235         my $block = substr($text, 0, $pos - 1);
236         substr($text, 0, $pos - 1) = "";
237         $text =~ s!^$self->{tag_start_qm}.+?$self->{tag_end_qm}!!;
238
239         return ($block, $text);
240       }
241     }
242   }
243
244   return undef;
245 }
246
247 sub parse_block {
248   $main::lxdebug->enter_sub();
249
250   my ($self, $contents, @indices) = @_;
251
252   my $new_contents = "";
253
254   while ($contents ne "") {
255     my $pos_if      = index($contents, $self->{tag_start} . 'if');
256     my $pos_foreach = index($contents, $self->{tag_start} . 'foreach');
257
258     if ((-1 == $pos_if) && (-1 == $pos_foreach)) {
259       $new_contents .= $self->substitute_vars($contents, @indices);
260       last;
261     }
262
263     if ((-1 == $pos_if) || ((-1 != $pos_foreach) && ($pos_if > $pos_foreach))) {
264       $new_contents .= $self->substitute_vars(substr($contents, 0, $pos_foreach), @indices);
265       substr($contents, 0, $pos_foreach) = "";
266
267       if ($contents !~ m|^$self->{tag_start_qm}foreach (.+?)$self->{tag_end_qm}|) {
268         $self->{"error"} = "Malformed $self->{tag_start}foreach$self->{tag_end}.";
269         $main::lxdebug->leave_sub();
270         return undef;
271       }
272
273       my $var = $1;
274
275       substr($contents, 0, length($&)) = "";
276
277       my $block;
278       ($block, $contents) = $self->find_end($contents);
279       if (!$block) {
280         $self->{"error"} = "Unclosed $self->{tag_start}foreach$self->{tag_end}." unless ($self->{"error"});
281         $main::lxdebug->leave_sub();
282         return undef;
283       }
284
285       my $new_text = $self->parse_foreach($var, $block, "", "", @indices);
286       if (!defined($new_text)) {
287         $main::lxdebug->leave_sub();
288         return undef;
289       }
290       $new_contents .= $new_text;
291
292     } else {
293       if (!$self->_parse_block_if(\$contents, \$new_contents, $pos_if, @indices)) {
294         $main::lxdebug->leave_sub();
295         return undef;
296       }
297     }
298   }
299
300   $main::lxdebug->leave_sub();
301
302   return $new_contents;
303 }
304
305 sub parse_first_line {
306   my $self = shift;
307   my $line = shift || "";
308
309   if ($line =~ m/([^\s]+)set-tag-style([^\s]+)/) {
310     if ($1 eq $2) {
311       $self->{error} = "The tag start and end markers must not be equal.";
312       return 0;
313     }
314
315     $self->set_tag_style($1, $2);
316   }
317
318   return 1;
319 }
320
321 sub _parse_config_option {
322   my $self = shift;
323   my $line = shift;
324
325   $line =~ s/^\s*//;
326   $line =~ s/\s*$//;
327
328   my ($key, $value) = split m/\s*=\s*/, $line, 2;
329
330   if ($key eq 'tag-style') {
331     $self->set_tag_style(split(m/\s+/, $value, 2));
332   }
333   if ($key eq 'use-template-toolkit') {
334     $self->set_use_template_toolkit($value);
335   }
336 }
337
338 sub _parse_config_lines {
339   my $self  = shift;
340   my $lines = shift;
341
342   my ($comment_start, $comment_end) = ("", "");
343
344   if (ref $self eq 'SL::Template::LaTeX') {
345     $comment_start = '\s*%';
346   } elsif (ref $self eq 'SL::Template::HTML') {
347     $comment_start = '\s*<!--';
348     $comment_end   = '(?:--)?>\s*';
349   } else {
350     $comment_start = '\s*\#';
351   }
352
353   my $num_lines = scalar @{ $lines };
354   my $i         = 0;
355
356   while ($i < $num_lines) {
357     my $line = $lines->[$i];
358
359     if ($line !~ m/^${comment_start}\s*config\s*:(.*?)${comment_end}$/i) {
360       $i++;
361       next;
362     }
363
364     $self->_parse_config_option($1);
365     splice @{ $lines }, $i, 1;
366     $num_lines--;
367   }
368 }
369
370 sub _force_mandatory_packages {
371   my $self  = shift;
372   my $lines = shift;
373
374   my (%used_packages, $document_start_line, $last_usepackage_line);
375
376   foreach my $i (0 .. scalar @{ $lines } - 1) {
377     if ($lines->[$i] =~ m/\\usepackage[^\{]*{(.*?)}/) {
378       $used_packages{$1} = 1;
379       $last_usepackage_line = $i;
380
381     } elsif ($lines->[$i] =~ m/\\begin\{document\}/) {
382       $document_start_line = $i;
383       last;
384
385     }
386   }
387
388   my $insertion_point = defined($document_start_line)  ? $document_start_line
389                       : defined($last_usepackage_line) ? $last_usepackage_line
390                       :                                  scalar @{ $lines } - 1;
391
392   foreach my $package (qw(textcomp ulem)) {
393     next if $used_packages{$package};
394     splice @{ $lines }, $insertion_point, 0, "\\usepackage{${package}}\n";
395     $insertion_point++;
396   }
397 }
398
399 sub parse {
400   my $self = $_[0];
401   local *OUT = $_[1];
402   my $form = $self->{"form"};
403
404   if (!open(IN, "$form->{templates}/$form->{IN}")) {
405     $self->{"error"} = "$form->{templates}/$form->{IN}: $!";
406     return 0;
407   }
408   binmode IN, ":utf8";
409   my @lines = <IN>;
410   close(IN);
411
412   $self->_parse_config_lines(\@lines);
413   $self->_force_mandatory_packages(\@lines) if (ref $self eq 'SL::Template::LaTeX');
414
415   my $contents = join("", @lines);
416
417   # detect pagebreak block and its parameters
418   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) {
419     $self->{"chars_per_line"} = $1;
420     $self->{"lines_on_first_page"} = $2;
421     $self->{"lines_on_second_page"} = $3;
422     $self->{"pagebreak_block"} = $4;
423
424     substr($contents, length($`), length($&)) = "";
425   }
426
427   $self->{"forced_pagebreaks"} = [];
428
429   my $new_contents;
430   if ($self->{use_template_toolkit}) {
431     if ($self->{custom_tag_style}) {
432       $contents = "[% TAGS $self->{tag_start} $self->{tag_end} %]\n" . $contents;
433     }
434
435     $::form->init_template->process(\$contents, $form, \$new_contents) || die $::form->template->error;
436   } else {
437     $new_contents = $self->parse_block($contents);
438   }
439   if (!defined($new_contents)) {
440     $main::lxdebug->leave_sub();
441     return 0;
442   }
443
444   binmode OUT, ":utf8";
445   print OUT Unicode::Normalize::normalize('C', $new_contents);
446
447   if ($form->{"format"} =~ /postscript/i) {
448     return $self->convert_to_postscript();
449   } elsif ($form->{"format"} =~ /pdf/i) {
450     return $self->convert_to_pdf();
451   } else {
452     return 1;
453   }
454 }
455
456 sub convert_to_postscript {
457   my ($self) = @_;
458   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
459
460   # Convert the tex file to postscript
461   local $ENV{TEXINPUTS} = ".:" . $form->{cwd} . "/" . $form->{templates} . ":" . $ENV{TEXINPUTS};
462
463   if (!chdir("$userspath")) {
464     $self->{"error"} = "chdir : $!";
465     $self->cleanup();
466     return 0;
467   }
468
469   $form->{tmpfile} =~ s/\Q$userspath\E\///g;
470
471   my $latex = $self->_get_latex_path();
472   my $old_home = $ENV{HOME};
473   my $old_openin_any = $ENV{openin_any};
474   $ENV{HOME}   = $userspath =~ m|^/| ? $userspath : getcwd();
475   $ENV{openin_any} = "p";
476
477   for (my $run = 1; $run <= 2; $run++) {
478     system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
479            "> $form->{tmpfile}.err");
480     if ($?) {
481       $ENV{HOME} = $old_home;
482       $ENV{openin_any} = $old_openin_any;
483       $self->{"error"} = $form->cleanup($latex);
484       return 0;
485     }
486   }
487
488   $form->{tmpfile} =~ s/tex$/dvi/;
489
490   system("dvips $form->{tmpfile} -o -q > /dev/null");
491   $ENV{HOME} = $old_home;
492   $ENV{openin_any} = $old_openin_any;
493
494   if ($?) {
495     $self->{"error"} = "dvips : $!";
496     $self->cleanup('dvips');
497     return 0;
498   }
499   $form->{tmpfile} =~ s/dvi$/ps/;
500
501   $self->cleanup();
502
503   return 1;
504 }
505
506 sub convert_to_pdf {
507   my ($self) = @_;
508   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
509
510   # Convert the tex file to PDF
511   local $ENV{TEXINPUTS} = ".:" . $form->{cwd} . "/" . $form->{templates} . ":" . $ENV{TEXINPUTS};
512
513   if (!chdir("$userspath")) {
514     $self->{"error"} = "chdir : $!";
515     $self->cleanup();
516     return 0;
517   }
518
519   $form->{tmpfile} =~ s/\Q$userspath\E\///g;
520
521   my $latex = $self->_get_latex_path();
522   my $old_home = $ENV{HOME};
523   my $old_openin_any = $ENV{openin_any};
524   $ENV{HOME}   = $userspath =~ m|^/| ? $userspath : getcwd();
525   $ENV{openin_any} = "p";
526
527   for (my $run = 1; $run <= 2; $run++) {
528     system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
529            "> $form->{tmpfile}.err");
530     if ($?) {
531       $ENV{HOME}     = $old_home;
532       $ENV{openin_any} = $old_openin_any;
533       $self->{error} = $form->cleanup($latex);
534       return 0;
535     }
536   }
537
538   $ENV{HOME} = $old_home;
539   $ENV{openin_any} = $old_openin_any;
540   $form->{tmpfile} =~ s/tex$/pdf/;
541
542   $self->cleanup();
543
544   return 1;
545 }
546
547 sub _get_latex_path {
548   return $::lx_office_conf{applications}->{latex} || 'pdflatex';
549 }
550
551 sub get_mime_type() {
552   my ($self) = @_;
553
554   if ($self->{"form"}->{"format"} =~ /postscript/i) {
555     return "application/postscript";
556   } else {
557     return "application/pdf";
558   }
559 }
560
561 sub uses_temp_file {
562   return 1;
563 }
564
565 sub parse_and_create_pdf {
566   my ($class, $template_file_name, %params) = @_;
567
568   my $keep_temp                = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
569   my ($tex_fh, $tex_file_name) = File::Temp::tempfile(
570     'kivitendo-printXXXXXX',
571     SUFFIX => '.tex',
572     DIR    => $::lx_office_conf{paths}->{userspath},
573     UNLINK => $keep_temp ? 0 : 1,,
574   );
575
576   my $old_wd               = getcwd();
577
578   my $local_form           = Form->new('');
579   $local_form->{cwd}       = $old_wd;
580   $local_form->{IN}        = $template_file_name;
581   $local_form->{tmpdir}    = $::lx_office_conf{paths}->{userspath};
582   $local_form->{tmpfile}   = $tex_file_name;
583   $local_form->{templates} = SL::DB::Default->get->templates;
584
585   foreach (keys %params) {
586     croak "The parameter '$_' must not be used." if exists $local_form->{$_};
587     $local_form->{$_} = $params{$_};
588   }
589
590   my $error;
591   eval {
592     my $template = SL::Template::LaTeX->new(file_name => $template_file_name, form => $local_form);
593     my $result   = $template->parse($tex_fh) && $template->convert_to_pdf;
594
595     die $template->{error} unless $result;
596
597     1;
598   } or do { $error = $EVAL_ERROR; };
599
600   chdir $old_wd;
601   close $tex_fh;
602
603   if ($keep_temp) {
604     chmod(((stat $tex_file_name)[2] & 07777) | 0660, $tex_file_name);
605   } else {
606     my $tmpfile =  $tex_file_name;
607     $tmpfile    =~ s/\.\w+$//;
608     unlink(grep { !m/\.pdf$/ } <$tmpfile.*>);
609   }
610
611   return (error     => $error) if $error;
612   return (file_name => do { $tex_file_name =~ s/tex$/pdf/; $tex_file_name });
613 }
614
615 1;