1 package SL::Template::LaTeX;
3 use parent qw(SL::Template::Simple);
9 use English qw(-no_match_vars);
12 use List::MoreUtils qw(any);
13 use Unicode::Normalize qw();
18 my $self = $type->SUPER::new(@_);
24 my ($self, $variable) = @_;
26 $variable = $main::locale->quote_special_chars('Template/LaTeX', $variable);
28 # Allow some HTML markup to be converted into the output format's
29 # corresponding markup code, e.g. bold or italic.
30 my %markup_replace = ('b' => 'textbf',
34 foreach my $key (keys(%markup_replace)) {
35 my $new = $markup_replace{$key};
36 $variable =~ s/\$\<\$${key}\$\>\$(.*?)\$<\$\/${key}\$>\$/\\${new}\{$1\}/gi;
39 $variable =~ s/[\x00-\x1f]//g;
45 my ($self, $var, $text, $start_tag, $end_tag, @indices) = @_;
47 my ($form, $new_contents) = ($self->{"form"}, "");
49 my $ary = $self->_get_loop_variable($var, 1, @indices);
53 my ($current_line, $corrent_row) = (0, 1);
54 my $description_array = $self->_get_loop_variable("description", 1);
55 my $longdescription_array = $self->_get_loop_variable("longdescription", 1);
56 my $linetotal_array = $self->_get_loop_variable("linetotal", 1);
58 $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal} = [];
60 # forech block hasn't given us an array. ignore
61 return $new_contents unless ref $ary eq 'ARRAY';
63 for (my $i = 0; $i < scalar(@{$ary}); $i++) {
65 $form->{"__first__"} = $i == 0;
66 $form->{"__last__"} = ($i + 1) == scalar(@{$ary});
67 $form->{"__odd__"} = (($i + 1) % 2) == 1;
68 $form->{"__counter__"} = $i + 1;
70 #everything from here to the next marker should be removed after the release of 2.7.0
71 if ( ref $description_array eq 'ARRAY'
72 && scalar @{$description_array} == scalar @{$ary}
73 && $self->{"chars_per_line"} != 0)
75 my $lines = int(length($description_array->[$i]) / $self->{"chars_per_line"});
78 $description_array->[$i] =~ s/(\\newline\s?)*$//;
79 $lines++ while ($description_array->[$i] =~ m/\\newline/g);
82 if ($current_page == 1) {
83 $lpp = $self->{"lines_on_first_page"};
85 $lpp = $self->{"lines_on_second_page"};
88 # Yes we need a manual page break -- or the user has forced one
89 if ( (($current_line + $lines) > $lpp)
90 || ($description_array->[$i] =~ /<pagebreak>/)
91 || ( ref $longdescription_array eq 'ARRAY'
92 && $longdescription_array->[$i] =~ /<pagebreak>/)) {
93 my $pb = $self->{"pagebreak_block"};
95 # replace the special variables <%sumcarriedforward%>
98 my $psum = $form->format_amount($self->{"myconfig"}, $sum, 2);
99 $pb =~ s/$self->{tag_start_qm}sumcarriedforward$self->{tag_end_qm}/$psum/g;
100 $pb =~ s/$self->{tag_start_qm}lastpage$self->{tag_end_qm}/$current_page/g;
102 my $new_text = $self->parse_block($pb, (@indices, $i));
103 return undef unless (defined($new_text));
104 $new_contents .= $new_text;
109 $current_line += $lines;
111 #stop removing code here.
113 if ( ref $linetotal_array eq 'ARRAY'
114 && $i < scalar(@{$linetotal_array})) {
115 $sum += $form->parse_amount($self->{"myconfig"}, $linetotal_array->[$i]);
118 $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal}->[$i] = $form->format_amount($self->{"myconfig"}, $sum, 2);
120 my $new_text = $self->parse_block($text, (@indices, $i));
121 return undef unless (defined($new_text));
122 $new_contents .= $start_tag . $new_text . $end_tag;
124 map({ delete($form->{"__${_}__"}); } qw(first last odd counter));
126 return $new_contents;
130 my ($self, $text, $pos, $var, $not) = @_;
132 my $tag_start_len = length $self->{tag_start};
135 $pos = 0 unless ($pos);
137 while ($pos < length($text)) {
140 next if (substr($text, $pos - 1, length($self->{tag_start})) ne $self->{tag_start});
142 my $keyword_pos = $pos - 1 + $tag_start_len;
144 if ((substr($text, $keyword_pos, 2) eq 'if') || (substr($text, $keyword_pos, 7) eq 'foreach')) {
147 } elsif ((substr($text, $keyword_pos, 4) eq 'else') && (1 == $depth)) {
150 "$self->{tag_start}else$self->{tag_end} outside of "
151 . "$self->{tag_start}if$self->{tag_end} / "
152 . "$self->{tag_start}ifnot$self->{tag_end}.";
156 my $block = substr($text, 0, $pos - 1);
157 substr($text, 0, $pos - 1) = "";
158 $text =~ s!^$self->{tag_start_qm}.+?$self->{tag_end_qm}!!;
159 $text = $self->{tag_start} . 'if' . ($not ? " " : "not ") . $var . $self->{tag_end} . $text;
161 return ($block, $text);
163 } elsif (substr($text, $keyword_pos, 3) eq 'end') {
166 my $block = substr($text, 0, $pos - 1);
167 substr($text, 0, $pos - 1) = "";
168 $text =~ s!^$self->{tag_start_qm}.+?$self->{tag_end_qm}!!;
170 return ($block, $text);
179 $main::lxdebug->enter_sub();
181 my ($self, $contents, @indices) = @_;
183 my $new_contents = "";
185 while ($contents ne "") {
186 my $pos_if = index($contents, $self->{tag_start} . 'if');
187 my $pos_foreach = index($contents, $self->{tag_start} . 'foreach');
189 if ((-1 == $pos_if) && (-1 == $pos_foreach)) {
190 $new_contents .= $self->substitute_vars($contents, @indices);
194 if ((-1 == $pos_if) || ((-1 != $pos_foreach) && ($pos_if > $pos_foreach))) {
195 $new_contents .= $self->substitute_vars(substr($contents, 0, $pos_foreach), @indices);
196 substr($contents, 0, $pos_foreach) = "";
198 if ($contents !~ m|^$self->{tag_start_qm}foreach (.+?)$self->{tag_end_qm}|) {
199 $self->{"error"} = "Malformed $self->{tag_start}foreach$self->{tag_end}.";
200 $main::lxdebug->leave_sub();
206 substr($contents, 0, length($&)) = "";
209 ($block, $contents) = $self->find_end($contents);
211 $self->{"error"} = "Unclosed $self->{tag_start}foreach$self->{tag_end}." unless ($self->{"error"});
212 $main::lxdebug->leave_sub();
216 my $new_text = $self->parse_foreach($var, $block, "", "", @indices);
217 if (!defined($new_text)) {
218 $main::lxdebug->leave_sub();
221 $new_contents .= $new_text;
224 if (!$self->_parse_block_if(\$contents, \$new_contents, $pos_if, @indices)) {
225 $main::lxdebug->leave_sub();
231 $main::lxdebug->leave_sub();
233 return $new_contents;
236 sub parse_first_line {
238 my $line = shift || "";
240 if ($line =~ m/([^\s]+)set-tag-style([^\s]+)/) {
242 $self->{error} = "The tag start and end markers must not be equal.";
246 $self->set_tag_style($1, $2);
252 sub _parse_config_option {
259 my ($key, $value) = split m/\s*=\s*/, $line, 2;
261 if ($key eq 'tag-style') {
262 $self->set_tag_style(split(m/\s+/, $value, 2));
264 if ($key eq 'use-template-toolkit') {
265 $self->set_use_template_toolkit($value);
269 sub _parse_config_lines {
273 my ($comment_start, $comment_end) = ("", "");
275 if (ref $self eq 'SL::Template::LaTeX') {
276 $comment_start = '\s*%';
277 } elsif (ref $self eq 'SL::Template::HTML') {
278 $comment_start = '\s*<!--';
279 $comment_end = '(?:--)?>\s*';
281 $comment_start = '\s*\#';
284 my $num_lines = scalar @{ $lines };
287 while ($i < $num_lines) {
288 my $line = $lines->[$i];
290 if ($line !~ m/^${comment_start}\s*config\s*:(.*?)${comment_end}$/i) {
295 $self->_parse_config_option($1);
296 splice @{ $lines }, $i, 1;
301 sub _force_mandatory_packages {
305 my (%used_packages, $document_start_line, $last_usepackage_line);
307 foreach my $i (0 .. scalar @{ $lines } - 1) {
308 if ($lines->[$i] =~ m/\\usepackage[^\{]*{(.*?)}/) {
309 $used_packages{$1} = 1;
310 $last_usepackage_line = $i;
312 } elsif ($lines->[$i] =~ m/\\begin\{document\}/) {
313 $document_start_line = $i;
319 my $insertion_point = defined($document_start_line) ? $document_start_line
320 : defined($last_usepackage_line) ? $last_usepackage_line
321 : scalar @{ $lines } - 1;
323 foreach my $package (qw(textcomp)) {
324 next if $used_packages{$package};
325 splice @{ $lines }, $insertion_point, 0, "\\usepackage{${package}}\n";
333 my $form = $self->{"form"};
335 if (!open(IN, "$form->{templates}/$form->{IN}")) {
336 $self->{"error"} = "$form->{templates}/$form->{IN}: $!";
339 binmode IN, ":utf8" if $::locale->is_utf8;
343 $self->_parse_config_lines(\@lines);
344 $self->_force_mandatory_packages(\@lines) if (ref $self eq 'SL::Template::LaTeX');
346 my $contents = join("", @lines);
348 # detect pagebreak block and its parameters
349 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) {
350 $self->{"chars_per_line"} = $1;
351 $self->{"lines_on_first_page"} = $2;
352 $self->{"lines_on_second_page"} = $3;
353 $self->{"pagebreak_block"} = $4;
355 substr($contents, length($`), length($&)) = "";
358 $self->{"forced_pagebreaks"} = [];
361 if ($self->{use_template_toolkit}) {
362 if ($self->{custom_tag_style}) {
363 $contents = "[% TAGS $self->{tag_start} $self->{tag_end} %]\n" . $contents;
366 $::form->init_template->process(\$contents, $form, \$new_contents) || die $::form->template->error;
368 $new_contents = $self->parse_block($contents);
370 if (!defined($new_contents)) {
371 $main::lxdebug->leave_sub();
375 if ($::locale->is_utf8) {
376 binmode OUT, ":utf8";
377 print OUT Unicode::Normalize::normalize('C', $new_contents);
380 print OUT $new_contents;
383 if ($form->{"format"} =~ /postscript/i) {
384 return $self->convert_to_postscript();
385 } elsif ($form->{"format"} =~ /pdf/i) {
386 return $self->convert_to_pdf();
392 sub convert_to_postscript {
394 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
396 # Convert the tex file to postscript
397 local $ENV{TEXINPUTS} = ".:" . $form->{cwd} . "/" . $form->{templates} . ":" . $ENV{TEXINPUTS};
399 if (!chdir("$userspath")) {
400 $self->{"error"} = "chdir : $!";
405 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
407 my $latex = $self->_get_latex_path();
408 my $old_home = $ENV{HOME};
409 my $old_openin_any = $ENV{openin_any};
410 $ENV{HOME} = $userspath =~ m|^/| ? $userspath : getcwd();
411 $ENV{openin_any} = "p";
413 for (my $run = 1; $run <= 2; $run++) {
414 system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
415 "> $form->{tmpfile}.err");
417 $ENV{HOME} = $old_home;
418 $ENV{openin_any} = $old_openin_any;
419 $self->{"error"} = $form->cleanup($latex);
424 $form->{tmpfile} =~ s/tex$/dvi/;
426 system("dvips $form->{tmpfile} -o -q > /dev/null");
427 $ENV{HOME} = $old_home;
428 $ENV{openin_any} = $old_openin_any;
431 $self->{"error"} = "dvips : $!";
432 $self->cleanup('dvips');
435 $form->{tmpfile} =~ s/dvi$/ps/;
444 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
446 # Convert the tex file to PDF
447 local $ENV{TEXINPUTS} = ".:" . $form->{cwd} . "/" . $form->{templates} . ":" . $ENV{TEXINPUTS};
449 if (!chdir("$userspath")) {
450 $self->{"error"} = "chdir : $!";
455 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
457 my $latex = $self->_get_latex_path();
458 my $old_home = $ENV{HOME};
459 my $old_openin_any = $ENV{openin_any};
460 $ENV{HOME} = $userspath =~ m|^/| ? $userspath : getcwd();
461 $ENV{openin_any} = "p";
463 for (my $run = 1; $run <= 2; $run++) {
464 system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
465 "> $form->{tmpfile}.err");
467 $ENV{HOME} = $old_home;
468 $ENV{openin_any} = $old_openin_any;
469 $self->{error} = $form->cleanup($latex);
474 $ENV{HOME} = $old_home;
475 $ENV{openin_any} = $old_openin_any;
476 $form->{tmpfile} =~ s/tex$/pdf/;
483 sub _get_latex_path {
484 return $::lx_office_conf{applications}->{latex} || 'pdflatex';
487 sub get_mime_type() {
490 if ($self->{"form"}->{"format"} =~ /postscript/i) {
491 return "application/postscript";
493 return "application/pdf";
501 sub parse_and_create_pdf {
502 my ($class, $template_file_name, %params) = @_;
504 my $keep_temp = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
505 my ($tex_fh, $tex_file_name) = File::Temp::tempfile(
506 'kivitendo-printXXXXXX',
508 DIR => $::lx_office_conf{paths}->{userspath},
509 UNLINK => $keep_temp ? 0 : 1,,
512 my $old_wd = getcwd();
514 my $local_form = Form->new('');
515 $local_form->{cwd} = $old_wd;
516 $local_form->{IN} = $template_file_name;
517 $local_form->{tmpdir} = $::lx_office_conf{paths}->{userspath};
518 $local_form->{tmpfile} = $tex_file_name;
519 $local_form->{templates} = $::myconfig{templates};
521 foreach (keys %params) {
522 croak "The parameter '$_' must not be used." if exists $local_form->{$_};
523 $local_form->{$_} = $params{$_};
528 my $template = SL::Template::LaTeX->new($template_file_name, $local_form, \%::myconfig, $::lx_office_conf{paths}->{userspath});
529 my $result = $template->parse($tex_fh) && $template->convert_to_pdf;
531 die $template->{error} unless $result;
534 } or do { $error = $EVAL_ERROR; };
540 chmod(((stat $tex_file_name)[2] & 07777) | 0660, $tex_file_name);
542 my $tmpfile = $tex_file_name;
543 $tmpfile =~ s/\.\w+$//;
544 unlink(grep { !m/\.pdf$/ } <$tmpfile.*>);
547 return (error => $error) if $error;
548 return (file_name => do { $tex_file_name =~ s/tex$/pdf/; $tex_file_name });