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