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