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 ($self, $content, %params) = @_;
72 $content =~ s{ \r+ }{}gx;
73 $content =~ s{ \n+ }{ }gx;
74 $content =~ s{ (?:\ |\s)+ }{ }gx;
75 $content =~ s{ (?:\ |\s)+$ }{}gx;
76 $content =~ s{ (?: <br/?> )+$ }{}gx;
78 my @parts = grep { $_ } map {
79 if (substr($_, 0, 1) eq '<') {
81 $html_replace{$_} || '';
84 $::locale->quote_special_chars('Template/LaTeX', HTML::Entities::decode_entities($_));
86 } split(m{(<.*?>)}x, $content);
88 $content = join '', @parts;
89 $content =~ s{ (?: [\n\s] | \\newline )+$ }{}gx;
95 html => \&_format_html,
96 text => \&_format_text,
102 my $self = $type->SUPER::new(@_);
108 my ($self, $content, $variable) = @_;
111 $formatters{ $self->{variable_content_types}->{$variable} }
112 // $formatters{ $self->{default_content_type} }
113 // $formatters{ text };
115 return $formatter->($self, $content, variable => $variable);
119 my ($self, $var, $text, $start_tag, $end_tag, @indices) = @_;
121 my ($form, $new_contents) = ($self->{"form"}, "");
123 my $ary = $self->_get_loop_variable($var, 1, @indices);
126 my $current_page = 1;
127 my ($current_line, $corrent_row) = (0, 1);
128 my $description_array = $self->_get_loop_variable("description", 1);
129 my $longdescription_array = $self->_get_loop_variable("longdescription", 1);
130 my $linetotal_array = $self->_get_loop_variable("linetotal", 1);
132 $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal} = [];
134 # forech block hasn't given us an array. ignore
135 return $new_contents unless ref $ary eq 'ARRAY';
137 for (my $i = 0; $i < scalar(@{$ary}); $i++) {
139 $form->{"__first__"} = $i == 0;
140 $form->{"__last__"} = ($i + 1) == scalar(@{$ary});
141 $form->{"__odd__"} = (($i + 1) % 2) == 1;
142 $form->{"__counter__"} = $i + 1;
144 #everything from here to the next marker should be removed after the release of 2.7.0
145 if ( ref $description_array eq 'ARRAY'
146 && scalar @{$description_array} == scalar @{$ary}
147 && $self->{"chars_per_line"} != 0)
149 my $lines = int(length($description_array->[$i]) / $self->{"chars_per_line"});
152 $description_array->[$i] =~ s/(\\newline\s?)*$//;
153 $lines++ while ($description_array->[$i] =~ m/\\newline/g);
156 if ($current_page == 1) {
157 $lpp = $self->{"lines_on_first_page"};
159 $lpp = $self->{"lines_on_second_page"};
162 # Yes we need a manual page break -- or the user has forced one
163 if ( (($current_line + $lines) > $lpp)
164 || ($description_array->[$i] =~ /<pagebreak>/)
165 || ( ref $longdescription_array eq 'ARRAY'
166 && $longdescription_array->[$i] =~ /<pagebreak>/)) {
167 my $pb = $self->{"pagebreak_block"};
169 # replace the special variables <%sumcarriedforward%>
172 my $psum = $form->format_amount($self->{"myconfig"}, $sum, 2);
173 $pb =~ s/$self->{tag_start_qm}sumcarriedforward$self->{tag_end_qm}/$psum/g;
174 $pb =~ s/$self->{tag_start_qm}lastpage$self->{tag_end_qm}/$current_page/g;
176 my $new_text = $self->parse_block($pb, (@indices, $i));
177 return undef unless (defined($new_text));
178 $new_contents .= $new_text;
183 $current_line += $lines;
185 #stop removing code here.
187 if ( ref $linetotal_array eq 'ARRAY'
188 && $i < scalar(@{$linetotal_array})) {
189 $sum += $form->parse_amount($self->{"myconfig"}, $linetotal_array->[$i]);
192 $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal}->[$i] = $form->format_amount($self->{"myconfig"}, $sum, 2);
194 my $new_text = $self->parse_block($text, (@indices, $i));
195 return undef unless (defined($new_text));
196 $new_contents .= $start_tag . $new_text . $end_tag;
198 map({ delete($form->{"__${_}__"}); } qw(first last odd counter));
200 return $new_contents;
204 my ($self, $text, $pos, $var, $not) = @_;
206 my $tag_start_len = length $self->{tag_start};
209 $pos = 0 unless ($pos);
211 while ($pos < length($text)) {
214 next if (substr($text, $pos - 1, length($self->{tag_start})) ne $self->{tag_start});
216 my $keyword_pos = $pos - 1 + $tag_start_len;
218 if ((substr($text, $keyword_pos, 2) eq 'if') || (substr($text, $keyword_pos, 7) eq 'foreach')) {
221 } elsif ((substr($text, $keyword_pos, 4) eq 'else') && (1 == $depth)) {
224 "$self->{tag_start}else$self->{tag_end} outside of "
225 . "$self->{tag_start}if$self->{tag_end} / "
226 . "$self->{tag_start}ifnot$self->{tag_end}.";
230 my $block = substr($text, 0, $pos - 1);
231 substr($text, 0, $pos - 1) = "";
232 $text =~ s!^$self->{tag_start_qm}.+?$self->{tag_end_qm}!!;
233 $text = $self->{tag_start} . 'if' . ($not ? " " : "not ") . $var . $self->{tag_end} . $text;
235 return ($block, $text);
237 } elsif (substr($text, $keyword_pos, 3) eq 'end') {
240 my $block = substr($text, 0, $pos - 1);
241 substr($text, 0, $pos - 1) = "";
242 $text =~ s!^$self->{tag_start_qm}.+?$self->{tag_end_qm}!!;
244 return ($block, $text);
253 $main::lxdebug->enter_sub();
255 my ($self, $contents, @indices) = @_;
257 my $new_contents = "";
259 while ($contents ne "") {
260 my $pos_if = index($contents, $self->{tag_start} . 'if');
261 my $pos_foreach = index($contents, $self->{tag_start} . 'foreach');
263 if ((-1 == $pos_if) && (-1 == $pos_foreach)) {
264 $new_contents .= $self->substitute_vars($contents, @indices);
268 if ((-1 == $pos_if) || ((-1 != $pos_foreach) && ($pos_if > $pos_foreach))) {
269 $new_contents .= $self->substitute_vars(substr($contents, 0, $pos_foreach), @indices);
270 substr($contents, 0, $pos_foreach) = "";
272 if ($contents !~ m|^$self->{tag_start_qm}foreach (.+?)$self->{tag_end_qm}|) {
273 $self->{"error"} = "Malformed $self->{tag_start}foreach$self->{tag_end}.";
274 $main::lxdebug->leave_sub();
280 substr($contents, 0, length($&)) = "";
283 ($block, $contents) = $self->find_end($contents);
285 $self->{"error"} = "Unclosed $self->{tag_start}foreach$self->{tag_end}." unless ($self->{"error"});
286 $main::lxdebug->leave_sub();
290 my $new_text = $self->parse_foreach($var, $block, "", "", @indices);
291 if (!defined($new_text)) {
292 $main::lxdebug->leave_sub();
295 $new_contents .= $new_text;
298 if (!$self->_parse_block_if(\$contents, \$new_contents, $pos_if, @indices)) {
299 $main::lxdebug->leave_sub();
305 $main::lxdebug->leave_sub();
307 return $new_contents;
310 sub parse_first_line {
312 my $line = shift || "";
314 if ($line =~ m/([^\s]+)set-tag-style([^\s]+)/) {
316 $self->{error} = "The tag start and end markers must not be equal.";
320 $self->set_tag_style($1, $2);
326 sub _parse_config_option {
333 my ($key, $value) = split m/\s*=\s*/, $line, 2;
335 if ($key eq 'tag-style') {
336 $self->set_tag_style(split(m/\s+/, $value, 2));
338 if ($key eq 'use-template-toolkit') {
339 $self->set_use_template_toolkit($value);
343 sub _parse_config_lines {
347 my ($comment_start, $comment_end) = ("", "");
349 if (ref $self eq 'SL::Template::LaTeX') {
350 $comment_start = '\s*%';
351 } elsif (ref $self eq 'SL::Template::HTML') {
352 $comment_start = '\s*<!--';
353 $comment_end = '(?:--)?>\s*';
355 $comment_start = '\s*\#';
358 my $num_lines = scalar @{ $lines };
361 while ($i < $num_lines) {
362 my $line = $lines->[$i];
364 if ($line !~ m/^${comment_start}\s*config\s*:(.*?)${comment_end}$/i) {
369 $self->_parse_config_option($1);
370 splice @{ $lines }, $i, 1;
375 sub _force_mandatory_packages {
379 my (%used_packages, $document_start_line, $last_usepackage_line);
381 foreach my $i (0 .. scalar @{ $lines } - 1) {
382 if ($lines->[$i] =~ m/\\usepackage[^\{]*{(.*?)}/) {
383 $used_packages{$1} = 1;
384 $last_usepackage_line = $i;
386 } elsif ($lines->[$i] =~ m/\\begin\{document\}/) {
387 $document_start_line = $i;
393 my $insertion_point = defined($document_start_line) ? $document_start_line
394 : defined($last_usepackage_line) ? $last_usepackage_line
395 : scalar @{ $lines } - 1;
397 foreach my $package (qw(textcomp ulem)) {
398 next if $used_packages{$package};
399 splice @{ $lines }, $insertion_point, 0, "\\usepackage{${package}}\n";
407 my $form = $self->{"form"};
409 if (!open(IN, "$form->{templates}/$form->{IN}")) {
410 $self->{"error"} = "$form->{templates}/$form->{IN}: $!";
417 $self->_parse_config_lines(\@lines);
418 $self->_force_mandatory_packages(\@lines) if (ref $self eq 'SL::Template::LaTeX');
420 my $contents = join("", @lines);
422 # detect pagebreak block and its parameters
423 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) {
424 $self->{"chars_per_line"} = $1;
425 $self->{"lines_on_first_page"} = $2;
426 $self->{"lines_on_second_page"} = $3;
427 $self->{"pagebreak_block"} = $4;
429 substr($contents, length($`), length($&)) = "";
432 $self->{"forced_pagebreaks"} = [];
435 if ($self->{use_template_toolkit}) {
436 if ($self->{custom_tag_style}) {
437 $contents = "[% TAGS $self->{tag_start} $self->{tag_end} %]\n" . $contents;
440 $::form->init_template->process(\$contents, $form, \$new_contents) || die $::form->template->error;
442 $new_contents = $self->parse_block($contents);
444 if (!defined($new_contents)) {
445 $main::lxdebug->leave_sub();
449 binmode OUT, ":utf8";
450 print OUT Unicode::Normalize::normalize('C', $new_contents);
452 if ($form->{"format"} =~ /postscript/i) {
453 return $self->convert_to_postscript();
454 } elsif ($form->{"format"} =~ /pdf/i) {
455 return $self->convert_to_pdf();
461 sub convert_to_postscript {
463 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
465 # Convert the tex file to postscript
466 local $ENV{TEXINPUTS} = ".:" . $form->{cwd} . "/" . $form->{templates} . ":" . $ENV{TEXINPUTS};
468 if (!chdir("$userspath")) {
469 $self->{"error"} = "chdir : $!";
474 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
476 my $latex = $self->_get_latex_path();
477 my $old_home = $ENV{HOME};
478 my $old_openin_any = $ENV{openin_any};
479 $ENV{HOME} = $userspath =~ m|^/| ? $userspath : getcwd();
480 $ENV{openin_any} = "p";
482 for (my $run = 1; $run <= 2; $run++) {
483 system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
484 "> $form->{tmpfile}.err");
486 $ENV{HOME} = $old_home;
487 $ENV{openin_any} = $old_openin_any;
488 $self->{"error"} = $form->cleanup($latex);
493 $form->{tmpfile} =~ s/tex$/dvi/;
495 system("dvips $form->{tmpfile} -o -q > /dev/null");
496 $ENV{HOME} = $old_home;
497 $ENV{openin_any} = $old_openin_any;
500 $self->{"error"} = "dvips : $!";
501 $self->cleanup('dvips');
504 $form->{tmpfile} =~ s/dvi$/ps/;
513 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
515 # Convert the tex file to PDF
516 local $ENV{TEXINPUTS} = ".:" . $form->{cwd} . "/" . $form->{templates} . ":" . $ENV{TEXINPUTS};
518 if (!chdir("$userspath")) {
519 $self->{"error"} = "chdir : $!";
524 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
526 my $latex = $self->_get_latex_path();
527 my $old_home = $ENV{HOME};
528 my $old_openin_any = $ENV{openin_any};
529 $ENV{HOME} = $userspath =~ m|^/| ? $userspath : getcwd();
530 $ENV{openin_any} = "p";
532 for (my $run = 1; $run <= 2; $run++) {
533 system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
534 "> $form->{tmpfile}.err");
536 $ENV{HOME} = $old_home;
537 $ENV{openin_any} = $old_openin_any;
538 $self->{error} = $form->cleanup($latex);
543 $ENV{HOME} = $old_home;
544 $ENV{openin_any} = $old_openin_any;
545 $form->{tmpfile} =~ s/tex$/pdf/;
552 sub _get_latex_path {
553 return $::lx_office_conf{applications}->{latex} || 'pdflatex';
556 sub get_mime_type() {
559 if ($self->{"form"}->{"format"} =~ /postscript/i) {
560 return "application/postscript";
562 return "application/pdf";
570 sub parse_and_create_pdf {
571 my ($class, $template_file_name, %params) = @_;
573 my $keep_temp = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
574 my ($tex_fh, $tex_file_name) = File::Temp::tempfile(
575 'kivitendo-printXXXXXX',
577 DIR => $::lx_office_conf{paths}->{userspath},
578 UNLINK => $keep_temp ? 0 : 1,,
581 my $old_wd = getcwd();
583 my $local_form = Form->new('');
584 $local_form->{cwd} = $old_wd;
585 $local_form->{IN} = $template_file_name;
586 $local_form->{tmpdir} = $::lx_office_conf{paths}->{userspath};
587 $local_form->{tmpfile} = $tex_file_name;
588 $local_form->{templates} = SL::DB::Default->get->templates;
590 foreach (keys %params) {
591 croak "The parameter '$_' must not be used." if exists $local_form->{$_};
592 $local_form->{$_} = $params{$_};
597 my $template = SL::Template::LaTeX->new(file_name => $template_file_name, form => $local_form);
598 my $result = $template->parse($tex_fh) && $template->convert_to_pdf;
600 die $template->{error} unless $result;
603 } or do { $error = $EVAL_ERROR; };
609 chmod(((stat $tex_file_name)[2] & 07777) | 0660, $tex_file_name);
611 my $tmpfile = $tex_file_name;
612 $tmpfile =~ s/\.\w+$//;
613 unlink(grep { !m/\.pdf$/ } <$tmpfile.*>);
616 return (error => $error) if $error;
617 return (file_name => do { $tex_file_name =~ s/tex$/pdf/; $tex_file_name });