1 package SL::Template::LaTeX;
 
   3 use parent qw(SL::Template::Simple);
 
   9 use English qw(-no_match_vars);
 
  12 use HTML::Entities ();
 
  13 use List::MoreUtils qw(any);
 
  14 use Unicode::Normalize qw();
 
  18 my %text_markup_replace = (
 
  25   my ($self, $content, %params) = @_;
 
  27   $content = $::locale->quote_special_chars('Template/LaTeX', $content);
 
  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;
 
  36   $content =~ s/[\x00-\x1f]//g;
 
  43   '<ul>'      => "\\begin{itemize} ",
 
  44   '</ul>'     => "\\end{itemize} ",
 
  45   '<ol>'      => "\\begin{enumerate} ",
 
  46   '</ol>'     => "\\end{enumerate} ",
 
  51   '<strong>'  => "\\textbf{",
 
  55   '<em>'      => "\\textit{",
 
  57   '<u>'       => "\\underline{",
 
  61   '<sub>'     => "\\textsubscript{",
 
  63   '<sup>'     => "\\textsuperscript{",
 
  65   '<br/>'     => "\\newline ",
 
  66   '<br>'      => "\\newline ",
 
  70   my ($to_replace) = @_;
 
  72   my $vspace = '\vspace*{0.5cm}';
 
  73   return $vspace x (length($to_replace) / length($html_replace{'<br>'}));
 
  77   my ($self, $content, %params) = @_;
 
  79   $content =~ s{ \r+ }{}gx;
 
  80   $content =~ s{ \n+ }{ }gx;
 
  81   $content =~ s{ (?:\ |\s)+ }{ }gx;
 
  82   $content =~ s{ (?:\ |\s)+$ }{}gx;
 
  83   $content =~ s{ (?: <br/?> )+$ }{}gx;
 
  85   my @parts = grep { $_ } map {
 
  86     if (substr($_, 0, 1) eq '<') {
 
  88       $html_replace{$_} || '';
 
  91       $::locale->quote_special_chars('Template/LaTeX', HTML::Entities::decode_entities($_));
 
  93   } split(m{(<.*?>)}x, $content);
 
  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;
 
 108   html => \&_format_html,
 
 109   text => \&_format_text,
 
 115   my $self = $type->SUPER::new(@_);
 
 121   my ($self, $content, $variable) = @_;
 
 124        $formatters{ $self->{variable_content_types}->{$variable} }
 
 125     // $formatters{ $self->{default_content_type} }
 
 126     // $formatters{ text };
 
 128   $content  =~ s{[^\p{Print}\n]|\p{Cf}}{}g;
 
 129   $variable =~ s{[^\p{Print}\n]|\p{Cf}}{}g;
 
 131   return $formatter->($self, $content, variable => $variable);
 
 135   my ($self, $var, $text, $start_tag, $end_tag, @indices) = @_;
 
 137   my ($form, $new_contents) = ($self->{"form"}, "");
 
 139   my $ary = $self->_get_loop_variable($var, 1, @indices);
 
 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);
 
 148   $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal} = [];
 
 150   # forech block hasn't given us an array. ignore
 
 151   return $new_contents unless ref $ary eq 'ARRAY';
 
 153   for (my $i = 0; $i < scalar(@{$ary}); $i++) {
 
 155     $form->{"__first__"}   = $i == 0;
 
 156     $form->{"__last__"}    = ($i + 1) == scalar(@{$ary});
 
 157     $form->{"__odd__"}     = (($i + 1) % 2) == 1;
 
 158     $form->{"__counter__"} = $i + 1;
 
 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)
 
 165       my $lines = int(length($description_array->[$i]) / $self->{"chars_per_line"});
 
 168       $description_array->[$i] =~ s/(\\newline\s?)*$//;
 
 169       $lines++ while ($description_array->[$i] =~ m/\\newline/g);
 
 172       if ($current_page == 1) {
 
 173         $lpp = $self->{"lines_on_first_page"};
 
 175         $lpp = $self->{"lines_on_second_page"};
 
 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"};
 
 185         # replace the special variables <%sumcarriedforward%>
 
 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;
 
 192         my $new_text = $self->parse_block($pb, (@indices, $i));
 
 193         return undef unless (defined($new_text));
 
 194         $new_contents .= $new_text;
 
 199       $current_line += $lines;
 
 201   #stop removing code here.
 
 203     if (   ref $linetotal_array eq 'ARRAY'
 
 204         && $i < scalar(@{$linetotal_array})) {
 
 205       $sum += $form->parse_amount($self->{"myconfig"}, $linetotal_array->[$i]);
 
 208     $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal}->[$i] = $form->format_amount($self->{"myconfig"}, $sum, 2);
 
 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;
 
 214   map({ delete($form->{"__${_}__"}); } qw(first last odd counter));
 
 216   return $new_contents;
 
 220   my ($self, $text, $pos, $var, $not) = @_;
 
 222   my $tag_start_len = length $self->{tag_start};
 
 225   $pos = 0 unless ($pos);
 
 227   while ($pos < length($text)) {
 
 230     next if (substr($text, $pos - 1, length($self->{tag_start})) ne $self->{tag_start});
 
 232     my $keyword_pos = $pos - 1 + $tag_start_len;
 
 234     if ((substr($text, $keyword_pos, 2) eq 'if') || (substr($text, $keyword_pos, 7) eq 'foreach')) {
 
 237     } elsif ((substr($text, $keyword_pos, 4) eq 'else') && (1 == $depth)) {
 
 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}.";
 
 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;
 
 251       return ($block, $text);
 
 253     } elsif (substr($text, $keyword_pos, 3) eq 'end') {
 
 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}!!;
 
 260         return ($block, $text);
 
 269   $main::lxdebug->enter_sub();
 
 271   my ($self, $contents, @indices) = @_;
 
 273   my $new_contents = "";
 
 275   while ($contents ne "") {
 
 276     my $pos_if      = index($contents, $self->{tag_start} . 'if');
 
 277     my $pos_foreach = index($contents, $self->{tag_start} . 'foreach');
 
 279     if ((-1 == $pos_if) && (-1 == $pos_foreach)) {
 
 280       $new_contents .= $self->substitute_vars($contents, @indices);
 
 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) = "";
 
 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();
 
 296       substr($contents, 0, length($1)) = "";
 
 299       ($block, $contents) = $self->find_end($contents);
 
 301         $self->{"error"} = "Unclosed $self->{tag_start}foreach$self->{tag_end}." unless ($self->{"error"});
 
 302         $main::lxdebug->leave_sub();
 
 306       my $new_text = $self->parse_foreach($var, $block, "", "", @indices);
 
 307       if (!defined($new_text)) {
 
 308         $main::lxdebug->leave_sub();
 
 311       $new_contents .= $new_text;
 
 314       if (!$self->_parse_block_if(\$contents, \$new_contents, $pos_if, @indices)) {
 
 315         $main::lxdebug->leave_sub();
 
 321   $main::lxdebug->leave_sub();
 
 323   return $new_contents;
 
 326 sub parse_first_line {
 
 328   my $line = shift || "";
 
 330   if ($line =~ m/([^\s]+)set-tag-style([^\s]+)/) {
 
 332       $self->{error} = "The tag start and end markers must not be equal.";
 
 336     $self->set_tag_style($1, $2);
 
 342 sub _parse_config_option {
 
 349   my ($key, $value) = split m/\s*=\s*/, $line, 2;
 
 351   if ($key eq 'tag-style') {
 
 352     $self->set_tag_style(split(m/\s+/, $value, 2));
 
 354   if ($key eq 'use-template-toolkit') {
 
 355     $self->set_use_template_toolkit($value);
 
 359 sub _parse_config_lines {
 
 363   my ($comment_start, $comment_end) = ("", "");
 
 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*';
 
 371     $comment_start = '\s*\#';
 
 374   my $num_lines = scalar @{ $lines };
 
 377   while ($i < $num_lines) {
 
 378     my $line = $lines->[$i];
 
 380     if ($line !~ m/^${comment_start}\s*config\s*:(.*?)${comment_end}$/i) {
 
 385     $self->_parse_config_option($1);
 
 386     splice @{ $lines }, $i, 1;
 
 391 sub _force_mandatory_packages {
 
 395   my (%used_packages, $document_start_line, $last_usepackage_line);
 
 397   foreach my $i (0 .. scalar @{ $lines } - 1) {
 
 398     if ($lines->[$i] =~ m/\\usepackage[^\{]*{(.*?)}/) {
 
 399       $used_packages{$1} = 1;
 
 400       $last_usepackage_line = $i;
 
 402     } elsif ($lines->[$i] =~ m/\\begin\{document\}/) {
 
 403       $document_start_line = $i;
 
 409   my $insertion_point = defined($document_start_line)  ? $document_start_line
 
 410                       : defined($last_usepackage_line) ? $last_usepackage_line
 
 411                       :                                  scalar @{ $lines } - 1;
 
 413   foreach my $package (qw(textcomp ulem)) {
 
 414     next if $used_packages{$package};
 
 415     splice @{ $lines }, $insertion_point, 0, "\\usepackage{${package}}\n";
 
 423   my $form = $self->{"form"};
 
 425   if (!open(IN, "$form->{templates}/$form->{IN}")) {
 
 426     $self->{"error"} = "$form->{templates}/$form->{IN}: $!";
 
 433   $self->_parse_config_lines(\@lines);
 
 434   $self->_force_mandatory_packages(\@lines) if (ref $self eq 'SL::Template::LaTeX');
 
 436   my $contents = join("", @lines);
 
 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;
 
 445     substr($contents, length($1), length($2)) = "";
 
 448   $self->{"forced_pagebreaks"} = [];
 
 451   if ($self->{use_template_toolkit}) {
 
 452     if ($self->{custom_tag_style}) {
 
 453       $contents = "[% TAGS $self->{tag_start} $self->{tag_end} %]\n" . $contents;
 
 456     my $globals = global_vars();
 
 458     $::form->template->process(\$contents, { %$form, %$globals }, \$new_contents) || die $::form->template->error;
 
 460     $new_contents = $self->parse_block($contents);
 
 462   if (!defined($new_contents)) {
 
 463     $main::lxdebug->leave_sub();
 
 467   binmode OUT, ":utf8";
 
 468   print OUT Unicode::Normalize::normalize('C', $new_contents);
 
 470   if ($form->{"format"} =~ /postscript/i) {
 
 471     return $self->convert_to_postscript();
 
 472   } elsif ($form->{"format"} =~ /pdf/i) {
 
 473     return $self->convert_to_pdf();
 
 479 sub convert_to_postscript {
 
 481   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
 
 483   # Convert the tex file to postscript
 
 484   local $ENV{TEXINPUTS} = ".:" . $form->{cwd} . "/" . $form->{templates} . ":" . $ENV{TEXINPUTS};
 
 486   if (!chdir("$userspath")) {
 
 487     $self->{"error"} = "chdir : $!";
 
 492   $form->{tmpfile} =~ s/\Q$userspath\E\///g;
 
 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";
 
 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: $!";
 
 506       $ENV{HOME} = $old_home;
 
 507       $ENV{openin_any} = $old_openin_any;
 
 508       $self->{"error"} = $form->cleanup($latex);
 
 513   $form->{tmpfile} =~ s/tex$/dvi/;
 
 515   if (system("dvips $form->{tmpfile} -o -q > /dev/null") == -1) {
 
 516     die "system call to dvips failed: $!";
 
 518   $ENV{HOME} = $old_home;
 
 519   $ENV{openin_any} = $old_openin_any;
 
 522     $self->{"error"} = "dvips : $?";
 
 523     $self->cleanup('dvips');
 
 526   $form->{tmpfile} =~ s/dvi$/ps/;
 
 535   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
 
 537   # Convert the tex file to PDF
 
 538   local $ENV{TEXINPUTS} = ".:" . $form->{cwd} . "/" . $form->{templates} . ":" . $ENV{TEXINPUTS};
 
 540   if (!chdir("$userspath")) {
 
 541     $self->{"error"} = "chdir : $!";
 
 546   $form->{tmpfile} =~ s/\Q$userspath\E\///g;
 
 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";
 
 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: $!";
 
 561       $ENV{HOME}     = $old_home;
 
 562       $ENV{openin_any} = $old_openin_any;
 
 563       $self->{error} = $form->cleanup($latex);
 
 568   $ENV{HOME} = $old_home;
 
 569   $ENV{openin_any} = $old_openin_any;
 
 570   $form->{tmpfile} =~ s/tex$/pdf/;
 
 577 sub _get_latex_path {
 
 578   return $::lx_office_conf{applications}->{latex} || 'pdflatex';
 
 581 sub get_mime_type() {
 
 584   if ($self->{"form"}->{"format"} =~ /postscript/i) {
 
 585     return "application/postscript";
 
 587     return "application/pdf";
 
 595 sub parse_and_create_pdf {
 
 596   my ($class, $template_file_name, %params) = @_;
 
 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',
 
 602     DIR    => $::lx_office_conf{paths}->{userspath},
 
 603     UNLINK => $keep_temp ? 0 : 1,,
 
 606   my $old_wd               = getcwd();
 
 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;
 
 615   foreach (keys %params) {
 
 616     croak "The parameter '$_' must not be used." if exists $local_form->{$_};
 
 617     $local_form->{$_} = $params{$_};
 
 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;
 
 625     die $template->{error} unless $result;
 
 628   } or do { $error = $EVAL_ERROR; };
 
 634     chmod(((stat $tex_file_name)[2] & 07777) | 0660, $tex_file_name);
 
 636     my $tmpfile =  $tex_file_name;
 
 637     $tmpfile    =~ s/\.\w+$//;
 
 638     unlink(grep { !m/\.pdf$/ } <$tmpfile.*>);
 
 641   return (error     => $error) if $error;
 
 642   return (file_name => do { $tex_file_name =~ s/tex$/pdf/; $tex_file_name });
 
 648     INSTANCE_CONF   => $::instance_conf,
 
 650     LXCONFIG        => $::lx_office_conf,
 
 651     LXDEBUG         => $::lxdebug,
 
 652     MYCONFIG        => \%::myconfig,