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