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
106 html => \&_format_html,
107 text => \&_format_text,
113 my $self = $type->SUPER::new(@_);
119 my ($self, $content, $variable) = @_;
122 $formatters{ $self->{variable_content_types}->{$variable} }
123 // $formatters{ $self->{default_content_type} }
124 // $formatters{ text };
126 return $formatter->($self, $content, variable => $variable);
130 my ($self, $var, $text, $start_tag, $end_tag, @indices) = @_;
132 my ($form, $new_contents) = ($self->{"form"}, "");
134 my $ary = $self->_get_loop_variable($var, 1, @indices);
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);
143 $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal} = [];
145 # forech block hasn't given us an array. ignore
146 return $new_contents unless ref $ary eq 'ARRAY';
148 for (my $i = 0; $i < scalar(@{$ary}); $i++) {
150 $form->{"__first__"} = $i == 0;
151 $form->{"__last__"} = ($i + 1) == scalar(@{$ary});
152 $form->{"__odd__"} = (($i + 1) % 2) == 1;
153 $form->{"__counter__"} = $i + 1;
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)
160 my $lines = int(length($description_array->[$i]) / $self->{"chars_per_line"});
163 $description_array->[$i] =~ s/(\\newline\s?)*$//;
164 $lines++ while ($description_array->[$i] =~ m/\\newline/g);
167 if ($current_page == 1) {
168 $lpp = $self->{"lines_on_first_page"};
170 $lpp = $self->{"lines_on_second_page"};
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"};
180 # replace the special variables <%sumcarriedforward%>
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;
187 my $new_text = $self->parse_block($pb, (@indices, $i));
188 return undef unless (defined($new_text));
189 $new_contents .= $new_text;
194 $current_line += $lines;
196 #stop removing code here.
198 if ( ref $linetotal_array eq 'ARRAY'
199 && $i < scalar(@{$linetotal_array})) {
200 $sum += $form->parse_amount($self->{"myconfig"}, $linetotal_array->[$i]);
203 $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal}->[$i] = $form->format_amount($self->{"myconfig"}, $sum, 2);
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;
209 map({ delete($form->{"__${_}__"}); } qw(first last odd counter));
211 return $new_contents;
215 my ($self, $text, $pos, $var, $not) = @_;
217 my $tag_start_len = length $self->{tag_start};
220 $pos = 0 unless ($pos);
222 while ($pos < length($text)) {
225 next if (substr($text, $pos - 1, length($self->{tag_start})) ne $self->{tag_start});
227 my $keyword_pos = $pos - 1 + $tag_start_len;
229 if ((substr($text, $keyword_pos, 2) eq 'if') || (substr($text, $keyword_pos, 7) eq 'foreach')) {
232 } elsif ((substr($text, $keyword_pos, 4) eq 'else') && (1 == $depth)) {
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}.";
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;
246 return ($block, $text);
248 } elsif (substr($text, $keyword_pos, 3) eq 'end') {
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}!!;
255 return ($block, $text);
264 $main::lxdebug->enter_sub();
266 my ($self, $contents, @indices) = @_;
268 my $new_contents = "";
270 while ($contents ne "") {
271 my $pos_if = index($contents, $self->{tag_start} . 'if');
272 my $pos_foreach = index($contents, $self->{tag_start} . 'foreach');
274 if ((-1 == $pos_if) && (-1 == $pos_foreach)) {
275 $new_contents .= $self->substitute_vars($contents, @indices);
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) = "";
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();
291 substr($contents, 0, length($1)) = "";
294 ($block, $contents) = $self->find_end($contents);
296 $self->{"error"} = "Unclosed $self->{tag_start}foreach$self->{tag_end}." unless ($self->{"error"});
297 $main::lxdebug->leave_sub();
301 my $new_text = $self->parse_foreach($var, $block, "", "", @indices);
302 if (!defined($new_text)) {
303 $main::lxdebug->leave_sub();
306 $new_contents .= $new_text;
309 if (!$self->_parse_block_if(\$contents, \$new_contents, $pos_if, @indices)) {
310 $main::lxdebug->leave_sub();
316 $main::lxdebug->leave_sub();
318 return $new_contents;
321 sub parse_first_line {
323 my $line = shift || "";
325 if ($line =~ m/([^\s]+)set-tag-style([^\s]+)/) {
327 $self->{error} = "The tag start and end markers must not be equal.";
331 $self->set_tag_style($1, $2);
337 sub _parse_config_option {
344 my ($key, $value) = split m/\s*=\s*/, $line, 2;
346 if ($key eq 'tag-style') {
347 $self->set_tag_style(split(m/\s+/, $value, 2));
349 if ($key eq 'use-template-toolkit') {
350 $self->set_use_template_toolkit($value);
354 sub _parse_config_lines {
358 my ($comment_start, $comment_end) = ("", "");
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*';
366 $comment_start = '\s*\#';
369 my $num_lines = scalar @{ $lines };
372 while ($i < $num_lines) {
373 my $line = $lines->[$i];
375 if ($line !~ m/^${comment_start}\s*config\s*:(.*?)${comment_end}$/i) {
380 $self->_parse_config_option($1);
381 splice @{ $lines }, $i, 1;
386 sub _force_mandatory_packages {
390 my (%used_packages, $document_start_line, $last_usepackage_line);
392 foreach my $i (0 .. scalar @{ $lines } - 1) {
393 if ($lines->[$i] =~ m/\\usepackage[^\{]*{(.*?)}/) {
394 $used_packages{$1} = 1;
395 $last_usepackage_line = $i;
397 } elsif ($lines->[$i] =~ m/\\begin\{document\}/) {
398 $document_start_line = $i;
404 my $insertion_point = defined($document_start_line) ? $document_start_line
405 : defined($last_usepackage_line) ? $last_usepackage_line
406 : scalar @{ $lines } - 1;
408 foreach my $package (qw(textcomp ulem)) {
409 next if $used_packages{$package};
410 splice @{ $lines }, $insertion_point, 0, "\\usepackage{${package}}\n";
418 my $form = $self->{"form"};
420 if (!open(IN, "$form->{templates}/$form->{IN}")) {
421 $self->{"error"} = "$form->{templates}/$form->{IN}: $!";
428 $self->_parse_config_lines(\@lines);
429 $self->_force_mandatory_packages(\@lines) if (ref $self eq 'SL::Template::LaTeX');
431 my $contents = join("", @lines);
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;
440 substr($contents, length($1), length($2)) = "";
443 $self->{"forced_pagebreaks"} = [];
446 if ($self->{use_template_toolkit}) {
447 if ($self->{custom_tag_style}) {
448 $contents = "[% TAGS $self->{tag_start} $self->{tag_end} %]\n" . $contents;
451 my $globals = global_vars();
453 $::form->init_template->process(\$contents, { %$form, %$globals }, \$new_contents) || die $::form->template->error;
455 $new_contents = $self->parse_block($contents);
457 if (!defined($new_contents)) {
458 $main::lxdebug->leave_sub();
462 binmode OUT, ":utf8";
463 print OUT Unicode::Normalize::normalize('C', $new_contents);
465 if ($form->{"format"} =~ /postscript/i) {
466 return $self->convert_to_postscript();
467 } elsif ($form->{"format"} =~ /pdf/i) {
468 return $self->convert_to_pdf();
474 sub convert_to_postscript {
476 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
478 # Convert the tex file to postscript
479 local $ENV{TEXINPUTS} = ".:" . $form->{cwd} . "/" . $form->{templates} . ":" . $ENV{TEXINPUTS};
481 if (!chdir("$userspath")) {
482 $self->{"error"} = "chdir : $!";
487 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
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";
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: $!";
501 $ENV{HOME} = $old_home;
502 $ENV{openin_any} = $old_openin_any;
503 $self->{"error"} = $form->cleanup($latex);
508 $form->{tmpfile} =~ s/tex$/dvi/;
510 if (system("dvips $form->{tmpfile} -o -q > /dev/null") == -1) {
511 die "system call to dvips failed: $!";
513 $ENV{HOME} = $old_home;
514 $ENV{openin_any} = $old_openin_any;
517 $self->{"error"} = "dvips : $?";
518 $self->cleanup('dvips');
521 $form->{tmpfile} =~ s/dvi$/ps/;
530 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
532 # Convert the tex file to PDF
533 local $ENV{TEXINPUTS} = ".:" . $form->{cwd} . "/" . $form->{templates} . ":" . $ENV{TEXINPUTS};
535 if (!chdir("$userspath")) {
536 $self->{"error"} = "chdir : $!";
541 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
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";
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: $!";
556 $ENV{HOME} = $old_home;
557 $ENV{openin_any} = $old_openin_any;
558 $self->{error} = $form->cleanup($latex);
563 $ENV{HOME} = $old_home;
564 $ENV{openin_any} = $old_openin_any;
565 $form->{tmpfile} =~ s/tex$/pdf/;
572 sub _get_latex_path {
573 return $::lx_office_conf{applications}->{latex} || 'pdflatex';
576 sub get_mime_type() {
579 if ($self->{"form"}->{"format"} =~ /postscript/i) {
580 return "application/postscript";
582 return "application/pdf";
590 sub parse_and_create_pdf {
591 my ($class, $template_file_name, %params) = @_;
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',
597 DIR => $::lx_office_conf{paths}->{userspath},
598 UNLINK => $keep_temp ? 0 : 1,,
601 my $old_wd = getcwd();
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;
610 foreach (keys %params) {
611 croak "The parameter '$_' must not be used." if exists $local_form->{$_};
612 $local_form->{$_} = $params{$_};
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;
620 die $template->{error} unless $result;
623 } or do { $error = $EVAL_ERROR; };
629 chmod(((stat $tex_file_name)[2] & 07777) | 0660, $tex_file_name);
631 my $tmpfile = $tex_file_name;
632 $tmpfile =~ s/\.\w+$//;
633 unlink(grep { !m/\.pdf$/ } <$tmpfile.*>);
636 return (error => $error) if $error;
637 return (file_name => do { $tex_file_name =~ s/tex$/pdf/; $tex_file_name });
643 INSTANCE_CONF => $::instance_conf,
645 LXCONFIG => $::lx_office_conf,
646 LXDEBUG => $::lxdebug,
647 MYCONFIG => \%::myconfig,