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 Scalar::Util qw(blessed);
15 use Unicode::Normalize qw();
18 use SL::System::Process;
20 my %text_markup_replace = (
27 my ($self, $content, %params) = @_;
29 $content = $::locale->quote_special_chars('Template/LaTeX', $content);
31 # Allow some HTML markup to be converted into the output format's
32 # corresponding markup code, e.g. bold or italic.
33 foreach my $key (keys(%text_markup_replace)) {
34 my $new = $text_markup_replace{$key};
35 $content =~ s/\$\<\$${key}\$\>\$(.*?)\$<\$\/${key}\$>\$/\\${new}\{$1\}/gi;
38 $content =~ s/[\x00-\x1f]//g;
45 '<ul>' => "\\begin{itemize} ",
46 '</ul>' => "\\end{itemize} ",
47 '<ol>' => "\\begin{enumerate} ",
48 '</ol>' => "\\end{enumerate} ",
53 '<strong>' => "\\textbf{",
57 '<em>' => "\\textit{",
59 '<u>' => "\\underline{",
63 '<sub>' => "\\textsubscript{",
65 '<sup>' => "\\textsuperscript{",
67 '<br/>' => "\\newline ",
68 '<br>' => "\\newline ",
72 my ($to_replace) = @_;
74 my $vspace = '\vspace*{0.5cm}';
75 return $vspace x (length($to_replace) / length($html_replace{'<br>'}));
79 my ($self, $content, %params) = @_;
81 $content =~ s{ \r+ }{}gx;
82 $content =~ s{ \n+ }{ }gx;
83 $content =~ s{ (?:\ |\s)+ }{ }gx;
84 $content =~ s{ (?:\ |\s)+$ }{}gx;
85 $content =~ s{ (?: <br/?> )+$ }{}gx;
86 $content =~ s{ <ul>\s*</ul> | <ol>\s*</ol> }{}igx;
87 $content =~ s{ (?: <p>\s*</p>\s* )+ \Z }{}imgx;
89 my @parts = grep { $_ } map {
90 if (substr($_, 0, 1) eq '<') {
92 $html_replace{$_} || '';
95 $::locale->quote_special_chars('Template/LaTeX', HTML::Entities::decode_entities($_));
97 } split(m{(<.*?>)}x, $content);
99 $content = join '', @parts;
100 $content =~ s{ (?: [\n\s] | \\newline )+ $ }{}gx; # remove line breaks at the end of the text
101 $content =~ s{ ^ \s+ }{}gx; # remove white space at the start of the text
102 $content =~ s{ ^ ( \\newline \ )+ }{ _lb_to_space($1) }gxe; # convert line breaks at the start of the text to vertical space
103 $content =~ s{ ( \n\n+ ) ( \\newline \ )+ }{ $1 . _lb_to_space($2) }gxe; # convert line breaks at the start of a paragraph to vertical space
104 $content =~ s{ ( \\end\{ [^\}]+ \} \h* ) ( \\newline \ )+ }{ $1 . _lb_to_space($2) }gxe; # convert line breaks after LaTeX environments like lists to vertical space
105 $content =~ s{ ^ \h+ \\newline }{\\newline}gmx;
106 $content =~ s{ \n\n \h* \\newline \h* }{\n\n}gmx;
112 html => \&_format_html,
113 text => \&_format_text,
119 my $self = $type->SUPER::new(@_);
125 my ($self, $content, $variable) = @_;
128 $formatters{ $self->{variable_content_types}->{$variable} }
129 // $formatters{ $self->{default_content_type} }
130 // $formatters{ text };
132 $content =~ s{[^\p{Print}\n]|\p{Cf}}{}g;
133 $variable =~ s{[^\p{Print}\n]|\p{Cf}}{}g;
135 return $formatter->($self, $content, variable => $variable);
139 my ($self, $var, $text, $start_tag, $end_tag, @indices) = @_;
141 my ($form, $new_contents) = ($self->{"form"}, "");
143 my $ary = $self->_get_loop_variable($var, 1, @indices);
146 my $current_page = 1;
147 my ($current_line, $corrent_row) = (0, 1);
148 my $description_array = $self->_get_loop_variable("description", 1);
149 my $longdescription_array = $self->_get_loop_variable("longdescription", 1);
150 my $linetotal_array = $self->_get_loop_variable("linetotal", 1);
152 $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal} = [];
154 # forech block hasn't given us an array. ignore
155 return $new_contents unless ref $ary eq 'ARRAY';
157 for (my $i = 0; $i < scalar(@{$ary}); $i++) {
159 $form->{"__first__"} = $i == 0;
160 $form->{"__last__"} = ($i + 1) == scalar(@{$ary});
161 $form->{"__odd__"} = (($i + 1) % 2) == 1;
162 $form->{"__counter__"} = $i + 1;
164 #everything from here to the next marker should be removed after the release of 2.7.0
165 if ( ref $description_array eq 'ARRAY'
166 && scalar @{$description_array} == scalar @{$ary}
167 && $self->{"chars_per_line"} != 0)
169 my $lines = int(length($description_array->[$i]) / $self->{"chars_per_line"});
172 $description_array->[$i] =~ s/(\\newline\s?)*$//;
173 $lines++ while ($description_array->[$i] =~ m/\\newline/g);
176 if ($current_page == 1) {
177 $lpp = $self->{"lines_on_first_page"};
179 $lpp = $self->{"lines_on_second_page"};
182 # Yes we need a manual page break -- or the user has forced one
183 if ( (($current_line + $lines) > $lpp)
184 || ($description_array->[$i] =~ /<pagebreak>/)
185 || ( ref $longdescription_array eq 'ARRAY'
186 && $longdescription_array->[$i] =~ /<pagebreak>/)) {
187 my $pb = $self->{"pagebreak_block"};
189 # replace the special variables <%sumcarriedforward%>
192 my $psum = $form->format_amount($self->{"myconfig"}, $sum, 2);
193 $pb =~ s/$self->{tag_start_qm}sumcarriedforward$self->{tag_end_qm}/$psum/g;
194 $pb =~ s/$self->{tag_start_qm}lastpage$self->{tag_end_qm}/$current_page/g;
196 my $new_text = $self->parse_block($pb, (@indices, $i));
197 return undef unless (defined($new_text));
198 $new_contents .= $new_text;
203 $current_line += $lines;
205 #stop removing code here.
207 if ( ref $linetotal_array eq 'ARRAY'
208 && $i < scalar(@{$linetotal_array})) {
209 $sum += $form->parse_amount($self->{"myconfig"}, $linetotal_array->[$i]);
212 $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal}->[$i] = $form->format_amount($self->{"myconfig"}, $sum, 2);
214 my $new_text = $self->parse_block($text, (@indices, $i));
215 return undef unless (defined($new_text));
216 $new_contents .= $start_tag . $new_text . $end_tag;
218 map({ delete($form->{"__${_}__"}); } qw(first last odd counter));
220 return $new_contents;
224 my ($self, $text, $pos, $var, $not) = @_;
226 my $tag_start_len = length $self->{tag_start};
229 $pos = 0 unless ($pos);
231 while ($pos < length($text)) {
234 next if (substr($text, $pos - 1, length($self->{tag_start})) ne $self->{tag_start});
236 my $keyword_pos = $pos - 1 + $tag_start_len;
238 if ((substr($text, $keyword_pos, 2) eq 'if') || (substr($text, $keyword_pos, 7) eq 'foreach')) {
241 } elsif ((substr($text, $keyword_pos, 4) eq 'else') && (1 == $depth)) {
244 "$self->{tag_start}else$self->{tag_end} outside of "
245 . "$self->{tag_start}if$self->{tag_end} / "
246 . "$self->{tag_start}ifnot$self->{tag_end}.";
250 my $block = substr($text, 0, $pos - 1);
251 substr($text, 0, $pos - 1) = "";
252 $text =~ s!^$self->{tag_start_qm}.+?$self->{tag_end_qm}!!;
253 $text = $self->{tag_start} . 'if' . ($not ? " " : "not ") . $var . $self->{tag_end} . $text;
255 return ($block, $text);
257 } elsif (substr($text, $keyword_pos, 3) eq 'end') {
260 my $block = substr($text, 0, $pos - 1);
261 substr($text, 0, $pos - 1) = "";
262 $text =~ s!^$self->{tag_start_qm}.+?$self->{tag_end_qm}!!;
264 return ($block, $text);
273 $main::lxdebug->enter_sub();
275 my ($self, $contents, @indices) = @_;
277 my $new_contents = "";
279 while ($contents ne "") {
280 my $pos_if = index($contents, $self->{tag_start} . 'if');
281 my $pos_foreach = index($contents, $self->{tag_start} . 'foreach');
283 if ((-1 == $pos_if) && (-1 == $pos_foreach)) {
284 $new_contents .= $self->substitute_vars($contents, @indices);
288 if ((-1 == $pos_if) || ((-1 != $pos_foreach) && ($pos_if > $pos_foreach))) {
289 $new_contents .= $self->substitute_vars(substr($contents, 0, $pos_foreach), @indices);
290 substr($contents, 0, $pos_foreach) = "";
292 if ($contents !~ m|^($self->{tag_start_qm}foreach (.+?)$self->{tag_end_qm})|) {
293 $self->{"error"} = "Malformed $self->{tag_start}foreach$self->{tag_end}.";
294 $main::lxdebug->leave_sub();
300 substr($contents, 0, length($1)) = "";
303 ($block, $contents) = $self->find_end($contents);
305 $self->{"error"} = "Unclosed $self->{tag_start}foreach$self->{tag_end}." unless ($self->{"error"});
306 $main::lxdebug->leave_sub();
310 my $new_text = $self->parse_foreach($var, $block, "", "", @indices);
311 if (!defined($new_text)) {
312 $main::lxdebug->leave_sub();
315 $new_contents .= $new_text;
318 if (!$self->_parse_block_if(\$contents, \$new_contents, $pos_if, @indices)) {
319 $main::lxdebug->leave_sub();
325 $main::lxdebug->leave_sub();
327 return $new_contents;
330 sub parse_first_line {
332 my $line = shift || "";
334 if ($line =~ m/([^\s]+)set-tag-style([^\s]+)/) {
336 $self->{error} = "The tag start and end markers must not be equal.";
340 $self->set_tag_style($1, $2);
346 sub _parse_config_option {
353 my ($key, $value) = split m/\s*=\s*/, $line, 2;
355 if ($key eq 'tag-style') {
356 $self->set_tag_style(split(m/\s+/, $value, 2));
358 if ($key eq 'use-template-toolkit') {
359 $self->set_use_template_toolkit($value);
363 sub _parse_config_lines {
367 my ($comment_start, $comment_end) = ("", "");
369 if (ref $self eq 'SL::Template::LaTeX') {
370 $comment_start = '\s*%';
371 } elsif (ref $self eq 'SL::Template::HTML') {
372 $comment_start = '\s*<!--';
373 $comment_end = '(?:--)?>\s*';
375 $comment_start = '\s*\#';
378 my $num_lines = scalar @{ $lines };
381 while ($i < $num_lines) {
382 my $line = $lines->[$i];
384 if ($line !~ m/^${comment_start}\s*config\s*:(.*?)${comment_end}$/i) {
389 $self->_parse_config_option($1);
390 splice @{ $lines }, $i, 1;
395 sub _embed_file_directive {
396 my ($self, $file) = @_;
398 # { source => $xmlfile,
399 # name => 'factur-x.xml',
400 # description => $::locale->text('Factur-X/ZUGFeRD invoice'), }
402 my $file_name = blessed($file->{source}) && $file->{source}->can('filename') ? $file->{source}->filename : "" . $file->{source}->filename;
403 my $embed_name = $file->{name} // $file_name;
404 $embed_name =~ s{.*/}{};
406 my $embed_name_ascii = $::locale->quote_special_chars('filenames', $embed_name);
407 $embed_name_ascii =~ s{[^a-z0-9!@#$%^&*(){}[\],.+'"=_-]+}{}gi;
412 my ($name, $value) = @_;
413 return if ($value // '') eq '';
414 push @options, sprintf('%s={%s}', $name, $value); # TODO: escaping
417 $add_opt->('filespec', $embed_name_ascii);
418 $add_opt->('ucfilespec', $embed_name);
419 $add_opt->('desc', $file->{description});
420 $add_opt->('afrelationship', $file->{relationship});
421 $add_opt->('mimetype', $file->{mime_type});
423 return sprintf('\embedfile[%s]{%s}', join(',', @options), $file_name);
426 sub _force_mandatory_packages {
427 my ($self, @lines) = @_;
431 my @required_packages = qw(textcomp ulem);
432 push @required_packages, 'embedfile' if $self->{pdf_a};
434 foreach my $line (@lines) {
435 if ($line =~ m/\\usepackage[^\{]*{(.*?)}/) {
436 $used_packages{$1} = 1;
438 } elsif ($line =~ m/\\begin\{document\}/) {
439 if ($self->{pdf_a} && $self->{pdf_a}->{xmp}) {
440 my $version = $self->{pdf_a}->{version} // '3a';
441 my $xmp_file_name = $self->{userspath} . "/pdfa.xmp";
442 my $out = IO::File->new($xmp_file_name, ">:encoding(utf-8)") || croak "Error creating ${xmp_file_name}: $!";
443 $out->print(Encode::encode('utf-8', $self->{pdf_a}->{xmp}));
447 "\\usepackage[a-${version},mathxmp]{pdfx}[2018/12/22]\n",
448 "\\usepackage[genericmode]{tagpdf}\n",
449 "\\tagpdfsetup{activate-all}\n",
450 "\\hypersetup{pdfstartview=}\n",
454 push @new_lines, map { "\\usepackage{$_}\n" } grep { !$used_packages{$_} } @required_packages;
455 push @new_lines, $line;
456 push @new_lines, map { $self->_embed_file_directive($_) } @{ $self->{pdf_attachments} // [] };
461 push @new_lines, $line;
470 my $form = $self->{"form"};
472 if (!open(IN, "$form->{templates}/$form->{IN}")) {
473 $self->{"error"} = "$form->{templates}/$form->{IN}: $!";
480 $self->_parse_config_lines(\@lines);
481 @lines = $self->_force_mandatory_packages(@lines) if (ref $self eq 'SL::Template::LaTeX');
483 my $contents = join("", @lines);
485 # detect pagebreak block and its parameters
486 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) {
487 $self->{"chars_per_line"} = $3;
488 $self->{"lines_on_first_page"} = $4;
489 $self->{"lines_on_second_page"} = $5;
490 $self->{"pagebreak_block"} = $6;
492 substr($contents, length($1), length($2)) = "";
495 $self->{"forced_pagebreaks"} = [];
498 if ($self->{use_template_toolkit}) {
499 if ($self->{custom_tag_style}) {
500 $contents = "[% TAGS $self->{tag_start} $self->{tag_end} %]\n" . $contents;
503 my $globals = global_vars();
505 $::form->template->process(\$contents, { %$form, %$globals }, \$new_contents) || die $::form->template->error;
507 $new_contents = $self->parse_block($contents);
509 if (!defined($new_contents)) {
510 $main::lxdebug->leave_sub();
514 binmode OUT, ":utf8";
515 print OUT Unicode::Normalize::normalize('C', $new_contents);
517 if ($form->{"format"} =~ /postscript/i) {
518 return $self->convert_to_postscript();
519 } elsif ($form->{"format"} =~ /pdf/i) {
520 return $self->convert_to_pdf();
526 sub _texinputs_path {
527 my ($self, $templates_path) = @_;
529 my $exe_dir = SL::System::Process::exe_dir();
530 $templates_path = $exe_dir . '/' . $templates_path unless $templates_path =~ m{^/};
532 return join(':', grep({ $_ } ('.', $exe_dir . '/texmf', $exe_dir . '/users', $templates_path, $ENV{TEXINPUTS})), '');
535 sub convert_to_postscript {
537 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
539 # Convert the tex file to postscript
540 local $ENV{TEXINPUTS} = $self->_texinputs_path($form->{templates});
542 if (!chdir("$userspath")) {
543 $self->{"error"} = "chdir : $!";
548 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
550 my $latex = $self->_get_latex_path();
551 my $old_home = $ENV{HOME};
552 my $old_openin_any = $ENV{openin_any};
553 $ENV{HOME} = $userspath =~ m|^/| ? $userspath : getcwd();
554 $ENV{openin_any} = "r";
556 for (my $run = 1; $run <= 2; $run++) {
557 if (system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
558 "> $form->{tmpfile}.err") == -1) {
559 die "system call to $latex failed: $!";
562 $ENV{HOME} = $old_home;
563 $ENV{openin_any} = $old_openin_any;
564 $self->{"error"} = $form->cleanup($latex);
569 $form->{tmpfile} =~ s/tex$/dvi/;
571 if (system("dvips $form->{tmpfile} -o -q > /dev/null") == -1) {
572 die "system call to dvips failed: $!";
574 $ENV{HOME} = $old_home;
575 $ENV{openin_any} = $old_openin_any;
578 $self->{"error"} = "dvips : $?";
579 $self->cleanup('dvips');
582 $form->{tmpfile} =~ s/dvi$/ps/;
591 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
593 # Convert the tex file to PDF
594 local $ENV{TEXINPUTS} = $self->_texinputs_path($form->{templates});
596 if (!chdir("$userspath")) {
597 $self->{"error"} = "chdir : $!";
602 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
604 my $latex = $self->_get_latex_path();
605 my $old_home = $ENV{HOME};
606 my $old_openin_any = $ENV{openin_any};
607 $ENV{HOME} = $userspath =~ m|^/| ? $userspath : getcwd();
608 $ENV{openin_any} = "r";
610 for (my $run = 1; $run <= 2; $run++) {
611 if (system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
612 "> $form->{tmpfile}.err") == -1) {
613 die "system call to $latex failed: $!";
617 $ENV{HOME} = $old_home;
618 $ENV{openin_any} = $old_openin_any;
619 $self->{error} = $form->cleanup($latex);
624 $ENV{HOME} = $old_home;
625 $ENV{openin_any} = $old_openin_any;
626 $form->{tmpfile} =~ s/tex$/pdf/;
633 sub _get_latex_path {
634 return $::lx_office_conf{applications}->{latex} || 'pdflatex';
637 sub get_mime_type() {
640 if ($self->{"form"}->{"format"} =~ /postscript/i) {
641 return "application/postscript";
643 return "application/pdf";
651 sub parse_and_create_pdf {
652 my ($class, $template_file_name, %params) = @_;
654 my $userspath = delete($params{userspath}) || $::lx_office_conf{paths}->{userspath};
655 my $keep_temp = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
656 my ($tex_fh, $tex_file_name) = File::Temp::tempfile(
657 'kivitendo-printXXXXXX',
660 UNLINK => $keep_temp ? 0 : 1,,
663 my $old_wd = getcwd();
665 my $local_form = Form->new('');
666 $local_form->{cwd} = $old_wd;
667 $local_form->{IN} = $template_file_name;
668 $local_form->{tmpdir} = $userspath;
669 $local_form->{tmpfile} = $tex_file_name;
670 $local_form->{templates} = SL::DB::Default->get->templates;
672 foreach (keys %params) {
673 croak "The parameter '$_' must not be used." if exists $local_form->{$_};
674 $local_form->{$_} = $params{$_};
679 my $template = SL::Template::LaTeX->new(file_name => $template_file_name, form => $local_form, userspath => $userspath);
680 my $result = $template->parse($tex_fh) && $template->convert_to_pdf;
682 die $template->{error} unless $result;
685 } or do { $error = $EVAL_ERROR; };
691 chmod(((stat $tex_file_name)[2] & 07777) | 0660, $tex_file_name);
693 my $tmpfile = $tex_file_name;
694 $tmpfile =~ s/\.\w+$//;
695 unlink(grep { !m/\.pdf$/ } <$tmpfile.*>);
698 return (error => $error) if $error;
699 return (file_name => do { $tex_file_name =~ s/tex$/pdf/; $tex_file_name });
705 INSTANCE_CONF => $::instance_conf,
707 LXCONFIG => $::lx_office_conf,
708 LXDEBUG => $::lxdebug,
709 MYCONFIG => \%::myconfig,