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;
77 if (substr($_, 0, 1) eq '<') {
79 $html_replace{$_} || '';
82 $::locale->quote_special_chars('Template/LaTeX', HTML::Entities::decode_entities($_));
84 } split(m{(<.*?>)}x, $content);
86 return join('', @parts);
90 html => \&_format_html,
91 text => \&_format_text,
97 my $self = $type->SUPER::new(@_);
103 my ($self, $content, $variable) = @_;
106 $formatters{ $self->{variable_content_types}->{$variable} }
107 // $formatters{ $self->{default_content_type} }
108 // $formatters{ text };
110 return $formatter->($self, $content, variable => $variable);
114 my ($self, $var, $text, $start_tag, $end_tag, @indices) = @_;
116 my ($form, $new_contents) = ($self->{"form"}, "");
118 my $ary = $self->_get_loop_variable($var, 1, @indices);
121 my $current_page = 1;
122 my ($current_line, $corrent_row) = (0, 1);
123 my $description_array = $self->_get_loop_variable("description", 1);
124 my $longdescription_array = $self->_get_loop_variable("longdescription", 1);
125 my $linetotal_array = $self->_get_loop_variable("linetotal", 1);
127 $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal} = [];
129 # forech block hasn't given us an array. ignore
130 return $new_contents unless ref $ary eq 'ARRAY';
132 for (my $i = 0; $i < scalar(@{$ary}); $i++) {
134 $form->{"__first__"} = $i == 0;
135 $form->{"__last__"} = ($i + 1) == scalar(@{$ary});
136 $form->{"__odd__"} = (($i + 1) % 2) == 1;
137 $form->{"__counter__"} = $i + 1;
139 #everything from here to the next marker should be removed after the release of 2.7.0
140 if ( ref $description_array eq 'ARRAY'
141 && scalar @{$description_array} == scalar @{$ary}
142 && $self->{"chars_per_line"} != 0)
144 my $lines = int(length($description_array->[$i]) / $self->{"chars_per_line"});
147 $description_array->[$i] =~ s/(\\newline\s?)*$//;
148 $lines++ while ($description_array->[$i] =~ m/\\newline/g);
151 if ($current_page == 1) {
152 $lpp = $self->{"lines_on_first_page"};
154 $lpp = $self->{"lines_on_second_page"};
157 # Yes we need a manual page break -- or the user has forced one
158 if ( (($current_line + $lines) > $lpp)
159 || ($description_array->[$i] =~ /<pagebreak>/)
160 || ( ref $longdescription_array eq 'ARRAY'
161 && $longdescription_array->[$i] =~ /<pagebreak>/)) {
162 my $pb = $self->{"pagebreak_block"};
164 # replace the special variables <%sumcarriedforward%>
167 my $psum = $form->format_amount($self->{"myconfig"}, $sum, 2);
168 $pb =~ s/$self->{tag_start_qm}sumcarriedforward$self->{tag_end_qm}/$psum/g;
169 $pb =~ s/$self->{tag_start_qm}lastpage$self->{tag_end_qm}/$current_page/g;
171 my $new_text = $self->parse_block($pb, (@indices, $i));
172 return undef unless (defined($new_text));
173 $new_contents .= $new_text;
178 $current_line += $lines;
180 #stop removing code here.
182 if ( ref $linetotal_array eq 'ARRAY'
183 && $i < scalar(@{$linetotal_array})) {
184 $sum += $form->parse_amount($self->{"myconfig"}, $linetotal_array->[$i]);
187 $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal}->[$i] = $form->format_amount($self->{"myconfig"}, $sum, 2);
189 my $new_text = $self->parse_block($text, (@indices, $i));
190 return undef unless (defined($new_text));
191 $new_contents .= $start_tag . $new_text . $end_tag;
193 map({ delete($form->{"__${_}__"}); } qw(first last odd counter));
195 return $new_contents;
199 my ($self, $text, $pos, $var, $not) = @_;
201 my $tag_start_len = length $self->{tag_start};
204 $pos = 0 unless ($pos);
206 while ($pos < length($text)) {
209 next if (substr($text, $pos - 1, length($self->{tag_start})) ne $self->{tag_start});
211 my $keyword_pos = $pos - 1 + $tag_start_len;
213 if ((substr($text, $keyword_pos, 2) eq 'if') || (substr($text, $keyword_pos, 7) eq 'foreach')) {
216 } elsif ((substr($text, $keyword_pos, 4) eq 'else') && (1 == $depth)) {
219 "$self->{tag_start}else$self->{tag_end} outside of "
220 . "$self->{tag_start}if$self->{tag_end} / "
221 . "$self->{tag_start}ifnot$self->{tag_end}.";
225 my $block = substr($text, 0, $pos - 1);
226 substr($text, 0, $pos - 1) = "";
227 $text =~ s!^$self->{tag_start_qm}.+?$self->{tag_end_qm}!!;
228 $text = $self->{tag_start} . 'if' . ($not ? " " : "not ") . $var . $self->{tag_end} . $text;
230 return ($block, $text);
232 } elsif (substr($text, $keyword_pos, 3) eq 'end') {
235 my $block = substr($text, 0, $pos - 1);
236 substr($text, 0, $pos - 1) = "";
237 $text =~ s!^$self->{tag_start_qm}.+?$self->{tag_end_qm}!!;
239 return ($block, $text);
248 $main::lxdebug->enter_sub();
250 my ($self, $contents, @indices) = @_;
252 my $new_contents = "";
254 while ($contents ne "") {
255 my $pos_if = index($contents, $self->{tag_start} . 'if');
256 my $pos_foreach = index($contents, $self->{tag_start} . 'foreach');
258 if ((-1 == $pos_if) && (-1 == $pos_foreach)) {
259 $new_contents .= $self->substitute_vars($contents, @indices);
263 if ((-1 == $pos_if) || ((-1 != $pos_foreach) && ($pos_if > $pos_foreach))) {
264 $new_contents .= $self->substitute_vars(substr($contents, 0, $pos_foreach), @indices);
265 substr($contents, 0, $pos_foreach) = "";
267 if ($contents !~ m|^$self->{tag_start_qm}foreach (.+?)$self->{tag_end_qm}|) {
268 $self->{"error"} = "Malformed $self->{tag_start}foreach$self->{tag_end}.";
269 $main::lxdebug->leave_sub();
275 substr($contents, 0, length($&)) = "";
278 ($block, $contents) = $self->find_end($contents);
280 $self->{"error"} = "Unclosed $self->{tag_start}foreach$self->{tag_end}." unless ($self->{"error"});
281 $main::lxdebug->leave_sub();
285 my $new_text = $self->parse_foreach($var, $block, "", "", @indices);
286 if (!defined($new_text)) {
287 $main::lxdebug->leave_sub();
290 $new_contents .= $new_text;
293 if (!$self->_parse_block_if(\$contents, \$new_contents, $pos_if, @indices)) {
294 $main::lxdebug->leave_sub();
300 $main::lxdebug->leave_sub();
302 return $new_contents;
305 sub parse_first_line {
307 my $line = shift || "";
309 if ($line =~ m/([^\s]+)set-tag-style([^\s]+)/) {
311 $self->{error} = "The tag start and end markers must not be equal.";
315 $self->set_tag_style($1, $2);
321 sub _parse_config_option {
328 my ($key, $value) = split m/\s*=\s*/, $line, 2;
330 if ($key eq 'tag-style') {
331 $self->set_tag_style(split(m/\s+/, $value, 2));
333 if ($key eq 'use-template-toolkit') {
334 $self->set_use_template_toolkit($value);
338 sub _parse_config_lines {
342 my ($comment_start, $comment_end) = ("", "");
344 if (ref $self eq 'SL::Template::LaTeX') {
345 $comment_start = '\s*%';
346 } elsif (ref $self eq 'SL::Template::HTML') {
347 $comment_start = '\s*<!--';
348 $comment_end = '(?:--)?>\s*';
350 $comment_start = '\s*\#';
353 my $num_lines = scalar @{ $lines };
356 while ($i < $num_lines) {
357 my $line = $lines->[$i];
359 if ($line !~ m/^${comment_start}\s*config\s*:(.*?)${comment_end}$/i) {
364 $self->_parse_config_option($1);
365 splice @{ $lines }, $i, 1;
370 sub _force_mandatory_packages {
374 my (%used_packages, $document_start_line, $last_usepackage_line);
376 foreach my $i (0 .. scalar @{ $lines } - 1) {
377 if ($lines->[$i] =~ m/\\usepackage[^\{]*{(.*?)}/) {
378 $used_packages{$1} = 1;
379 $last_usepackage_line = $i;
381 } elsif ($lines->[$i] =~ m/\\begin\{document\}/) {
382 $document_start_line = $i;
388 my $insertion_point = defined($document_start_line) ? $document_start_line
389 : defined($last_usepackage_line) ? $last_usepackage_line
390 : scalar @{ $lines } - 1;
392 foreach my $package (qw(textcomp ulem)) {
393 next if $used_packages{$package};
394 splice @{ $lines }, $insertion_point, 0, "\\usepackage{${package}}\n";
402 my $form = $self->{"form"};
404 if (!open(IN, "$form->{templates}/$form->{IN}")) {
405 $self->{"error"} = "$form->{templates}/$form->{IN}: $!";
412 $self->_parse_config_lines(\@lines);
413 $self->_force_mandatory_packages(\@lines) if (ref $self eq 'SL::Template::LaTeX');
415 my $contents = join("", @lines);
417 # detect pagebreak block and its parameters
418 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) {
419 $self->{"chars_per_line"} = $1;
420 $self->{"lines_on_first_page"} = $2;
421 $self->{"lines_on_second_page"} = $3;
422 $self->{"pagebreak_block"} = $4;
424 substr($contents, length($`), length($&)) = "";
427 $self->{"forced_pagebreaks"} = [];
430 if ($self->{use_template_toolkit}) {
431 if ($self->{custom_tag_style}) {
432 $contents = "[% TAGS $self->{tag_start} $self->{tag_end} %]\n" . $contents;
435 $::form->init_template->process(\$contents, $form, \$new_contents) || die $::form->template->error;
437 $new_contents = $self->parse_block($contents);
439 if (!defined($new_contents)) {
440 $main::lxdebug->leave_sub();
444 binmode OUT, ":utf8";
445 print OUT Unicode::Normalize::normalize('C', $new_contents);
447 if ($form->{"format"} =~ /postscript/i) {
448 return $self->convert_to_postscript();
449 } elsif ($form->{"format"} =~ /pdf/i) {
450 return $self->convert_to_pdf();
456 sub convert_to_postscript {
458 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
460 # Convert the tex file to postscript
461 local $ENV{TEXINPUTS} = ".:" . $form->{cwd} . "/" . $form->{templates} . ":" . $ENV{TEXINPUTS};
463 if (!chdir("$userspath")) {
464 $self->{"error"} = "chdir : $!";
469 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
471 my $latex = $self->_get_latex_path();
472 my $old_home = $ENV{HOME};
473 my $old_openin_any = $ENV{openin_any};
474 $ENV{HOME} = $userspath =~ m|^/| ? $userspath : getcwd();
475 $ENV{openin_any} = "p";
477 for (my $run = 1; $run <= 2; $run++) {
478 system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
479 "> $form->{tmpfile}.err");
481 $ENV{HOME} = $old_home;
482 $ENV{openin_any} = $old_openin_any;
483 $self->{"error"} = $form->cleanup($latex);
488 $form->{tmpfile} =~ s/tex$/dvi/;
490 system("dvips $form->{tmpfile} -o -q > /dev/null");
491 $ENV{HOME} = $old_home;
492 $ENV{openin_any} = $old_openin_any;
495 $self->{"error"} = "dvips : $!";
496 $self->cleanup('dvips');
499 $form->{tmpfile} =~ s/dvi$/ps/;
508 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
510 # Convert the tex file to PDF
511 local $ENV{TEXINPUTS} = ".:" . $form->{cwd} . "/" . $form->{templates} . ":" . $ENV{TEXINPUTS};
513 if (!chdir("$userspath")) {
514 $self->{"error"} = "chdir : $!";
519 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
521 my $latex = $self->_get_latex_path();
522 my $old_home = $ENV{HOME};
523 my $old_openin_any = $ENV{openin_any};
524 $ENV{HOME} = $userspath =~ m|^/| ? $userspath : getcwd();
525 $ENV{openin_any} = "p";
527 for (my $run = 1; $run <= 2; $run++) {
528 system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
529 "> $form->{tmpfile}.err");
531 $ENV{HOME} = $old_home;
532 $ENV{openin_any} = $old_openin_any;
533 $self->{error} = $form->cleanup($latex);
538 $ENV{HOME} = $old_home;
539 $ENV{openin_any} = $old_openin_any;
540 $form->{tmpfile} =~ s/tex$/pdf/;
547 sub _get_latex_path {
548 return $::lx_office_conf{applications}->{latex} || 'pdflatex';
551 sub get_mime_type() {
554 if ($self->{"form"}->{"format"} =~ /postscript/i) {
555 return "application/postscript";
557 return "application/pdf";
565 sub parse_and_create_pdf {
566 my ($class, $template_file_name, %params) = @_;
568 my $keep_temp = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
569 my ($tex_fh, $tex_file_name) = File::Temp::tempfile(
570 'kivitendo-printXXXXXX',
572 DIR => $::lx_office_conf{paths}->{userspath},
573 UNLINK => $keep_temp ? 0 : 1,,
576 my $old_wd = getcwd();
578 my $local_form = Form->new('');
579 $local_form->{cwd} = $old_wd;
580 $local_form->{IN} = $template_file_name;
581 $local_form->{tmpdir} = $::lx_office_conf{paths}->{userspath};
582 $local_form->{tmpfile} = $tex_file_name;
583 $local_form->{templates} = SL::DB::Default->get->templates;
585 foreach (keys %params) {
586 croak "The parameter '$_' must not be used." if exists $local_form->{$_};
587 $local_form->{$_} = $params{$_};
592 my $template = SL::Template::LaTeX->new(file_name => $template_file_name, form => $local_form);
593 my $result = $template->parse($tex_fh) && $template->convert_to_pdf;
595 die $template->{error} unless $result;
598 } or do { $error = $EVAL_ERROR; };
604 chmod(((stat $tex_file_name)[2] & 07777) | 0660, $tex_file_name);
606 my $tmpfile = $tex_file_name;
607 $tmpfile =~ s/\.\w+$//;
608 unlink(grep { !m/\.pdf$/ } <$tmpfile.*>);
611 return (error => $error) if $error;
612 return (file_name => do { $tex_file_name =~ s/tex$/pdf/; $tex_file_name });