1 package SL::Template::OpenDocument;
3 use parent qw(SL::Template::Simple);
11 use SL::Template::OpenDocument::Styles;
16 # use File::Temp qw(:mktemp);
21 my %text_markup_replace = (
31 my ($self, $content, %params) = @_;
33 $content = $::locale->quote_special_chars('Template/OpenDocument', $content);
35 # Allow some HTML markup to be converted into the output format's
36 # corresponding markup code, e.g. bold or italic.
37 foreach my $key (keys(%text_markup_replace)) {
38 my $value = $text_markup_replace{$key};
39 $content =~ s|\<${key}\>|<text:span text:style-name=\"TKIVITENDO${value}\">|gi; #"
40 $content =~ s|\</${key}\>|</text:span>|gi;
47 '</ul>' => '</text:list>',
48 '</ol>' => '</text:list>',
49 '</li>' => '</text:p></text:list-item>',
50 '<b>' => '<text:span text:style-name="TKIVITENDOBOLD">',
51 '</b>' => '</text:span>',
52 '<strong>' => '<text:span text:style-name="TKIVITENDOBOLD">',
53 '</strong>' => '</text:span>',
54 '<i>' => '<text:span text:style-name="TKIVITENDOITALIC">',
55 '</i>' => '</text:span>',
56 '<em>' => '<text:span text:style-name="TKIVITENDOITALIC">',
57 '</em>' => '</text:span>',
58 '<u>' => '<text:span text:style-name="TKIVITENDOUNDERLINE">',
59 '</u>' => '</text:span>',
60 '<s>' => '<text:span text:style-name="TKIVITENDOSTRIKETHROUGH">',
61 '</s>' => '</text:span>',
62 '<sub>' => '<text:span text:style-name="TKIVITENDOSUB">',
63 '</sub>' => '</text:span>',
64 '<sup>' => '<text:span text:style-name="TKIVITENDOSUPER">',
65 '</sup>' => '</text:span>',
66 '<br/>' => '<text:line-break/>',
67 '<br>' => '<text:line-break/>',
71 my ($self, $content, %params) = @_;
74 my $p_start_tag = qq|<text:p text:style-name="@{[ $self->{current_text_style} ]}">|;
78 my (@tags_to_open, @tags_to_close);
79 for (my $idx = scalar(@{ $self->{tag_stack} }) - 1; $idx >= 0; --$idx) {
80 my $tag = $self->{tag_stack}->[$idx];
82 next if $tag =~ m{/>$};
83 last if $tag =~ m{^<table};
85 if ($tag =~ m{^<text:p}) {
91 $suffix = "${tag}${suffix}";
93 $prefix .= '</' . substr($tag, 1);
97 $content =~ s{ ^<p> | </p>$ }{}gx if $in_p;
98 $content =~ s{ \r+ }{}gx;
99 $content =~ s{ \n+ }{ }gx;
100 $content =~ s{ (?:\ |\s)+ }{ }gx;
102 my $ul_start_tag = qq|<text:list xml:id="list@{[ int rand(9999999999999999) ]}" text:style-name="LKIVITENDOitemize@{[ $self->{current_text_style} ]}">|;
103 my $ol_start_tag = qq|<text:list xml:id="list@{[ int rand(9999999999999999) ]}" text:style-name="LKIVITENDOenumerate@{[ $self->{current_text_style} ]}">|;
104 my $ul_li_start_tag = qq|<text:list-item><text:p text:style-name="PKIVITENDOitemize@{[ $self->{current_text_style} ]}">|;
105 my $ol_li_start_tag = qq|<text:list-item><text:p text:style-name="PKIVITENDOenumerate@{[ $self->{current_text_style} ]}">|;
108 if (substr($_, 0, 1) eq '<') {
112 $in_p == 0 ? '</text:p>' : '';
114 } elsif ($_ eq '<p>') {
116 $in_p == 1 ? $p_start_tag : '';
118 } elsif ($_ eq '<ul>') {
119 $self->{used_list_styles}->{itemize}->{$self->{current_text_style}} = 1;
120 $html_replace{'<li>'} = $ul_li_start_tag;
123 } elsif ($_ eq '<ol>') {
124 $self->{used_list_styles}->{enumerate}->{$self->{current_text_style}} = 1;
125 $html_replace{'<li>'} = $ol_li_start_tag;
129 $html_replace{$_} || '';
133 $::locale->quote_special_chars('Template/OpenDocument', HTML::Entities::decode_entities($_));
135 } split(m{(<.*?>)}x, $content);
137 my $out = join('', $prefix, @parts, $suffix);
139 # $::lxdebug->dump(0, "prefix parts suffix", [ $prefix, join('', @parts), $suffix ]);
145 html => \&_format_html,
146 text => \&_format_text,
152 my $self = $type->SUPER::new(@_);
154 $self->set_tag_style('<%', '%>');
155 $self->{quot_re} = '"';
161 my ($self, $var, $text, $start_tag, $end_tag, @indices) = @_;
163 my ($form, $new_contents) = ($self->{"form"}, "");
165 my $ary = $self->_get_loop_variable($var, 1, @indices);
167 for (my $i = 0; $i < scalar(@{$ary || []}); $i++) {
168 $form->{"__first__"} = $i == 0;
169 $form->{"__last__"} = ($i + 1) == scalar(@{$ary});
170 $form->{"__odd__"} = (($i + 1) % 2) == 1;
171 $form->{"__counter__"} = $i + 1;
172 my $new_text = $self->parse_block($text, (@indices, $i));
173 return undef unless (defined($new_text));
174 $new_contents .= $start_tag . $new_text . $end_tag;
176 map({ delete($form->{"__${_}__"}); } qw(first last odd counter));
178 return $new_contents;
182 my ($self, $text, $pos, $var, $not) = @_;
185 $pos = 0 unless ($pos);
187 while ($pos < length($text)) {
190 next if (substr($text, $pos - 1, 5) ne '<%');
192 if ((substr($text, $pos + 4, 2) eq 'if') || (substr($text, $pos + 4, 3) eq 'for')) {
195 } elsif ((substr($text, $pos + 4, 4) eq 'else') && (1 == $depth)) {
197 $self->{"error"} = '<%else%> outside of <%if%> / <%ifnot%>.';
201 my $block = substr($text, 0, $pos - 1);
202 substr($text, 0, $pos - 1) = "";
203 $text =~ s!^\<\%[^\%]+\%\>!!;
204 $text = '<%if' . ($not ? " " : "not ") . $var . '%>' . $text;
206 return ($block, $text);
208 } elsif (substr($text, $pos + 4, 3) eq 'end') {
211 my $block = substr($text, 0, $pos - 1);
212 substr($text, 0, $pos - 1) = "";
213 $text =~ s!^\<\%[^\%]+\%\>!!;
215 return ($block, $text);
224 $main::lxdebug->enter_sub();
226 my ($self, $contents, @indices) = @_;
228 my $new_contents = "";
230 while ($contents ne "") {
231 if (substr($contents, 0, 1) eq "<") {
232 $contents =~ m|^(<[^>]+>)|;
234 substr($contents, 0, length($1)) = "";
236 $self->{current_text_style} = $1 if $tag =~ m|text:style-name\s*=\s*"([^"]+)"|;
238 push @{ $self->{tag_stack} }, $tag;
240 if ($tag =~ m|<table:table-row|) {
241 $contents =~ m|^(.*?)(</table:table-row[^>]*>)|;
245 if ($table_row =~ m|\<\%foreachrow\s+(.*?)\%\>|) {
248 $contents =~ m|^(.*?)(\<\%foreachrow\s+.*?\%\>)|;
249 substr($contents, length($1), length($2)) = "";
251 ($table_row, $contents) = $self->find_end($contents, length($1));
253 $self->{"error"} = "Unclosed <\%foreachrow\%>." unless ($self->{"error"});
254 $main::lxdebug->leave_sub();
258 $contents =~ m|^(.*?)(</table:table-row[^>]*>)|;
262 substr $contents, 0, length($1) + length($2), '';
264 my $new_text = $self->parse_foreach($var, $table_row, $tag, $end_tag, @indices);
265 if (!defined($new_text)) {
266 $main::lxdebug->leave_sub();
269 $new_contents .= $new_text;
272 substr($contents, 0, length($table_row) + length($end_tag)) = "";
273 my $new_text = $self->parse_block($table_row, @indices);
274 if (!defined($new_text)) {
275 $main::lxdebug->leave_sub();
278 $new_contents .= $tag . $new_text . $end_tag;
282 $new_contents .= $tag;
285 if ($tag =~ m{^</ | />$}x) {
286 # $::lxdebug->message(0, "popping top tag is $tag top " . $self->{tag_stack}->[-1]);
287 pop @{ $self->{tag_stack} };
291 $contents =~ /^([^<]+)/;
294 my $pos_if = index($text, '<%if');
295 my $pos_foreach = index($text, '<%foreach');
297 if ((-1 == $pos_if) && (-1 == $pos_foreach)) {
298 substr($contents, 0, length($text)) = "";
299 $new_contents .= $self->substitute_vars($text, @indices);
303 if ((-1 == $pos_if) || ((-1 != $pos_foreach) && ($pos_if > $pos_foreach))) {
304 $new_contents .= $self->substitute_vars(substr($contents, 0, $pos_foreach), @indices);
305 substr($contents, 0, $pos_foreach) = "";
307 if ($contents !~ m|^(\<\%foreach (.*?)\%\>)|) {
308 $self->{"error"} = "Malformed <\%foreach\%>.";
309 $main::lxdebug->leave_sub();
315 substr($contents, 0, length($1)) = "";
318 ($block, $contents) = $self->find_end($contents);
320 $self->{"error"} = "Unclosed <\%foreach\%>." unless ($self->{"error"});
321 $main::lxdebug->leave_sub();
325 my $new_text = $self->parse_foreach($var, $block, "", "", @indices);
326 if (!defined($new_text)) {
327 $main::lxdebug->leave_sub();
330 $new_contents .= $new_text;
333 if (!$self->_parse_block_if(\$contents, \$new_contents, $pos_if, @indices)) {
334 $main::lxdebug->leave_sub();
341 $main::lxdebug->leave_sub();
343 return $new_contents;
347 $main::lxdebug->enter_sub();
350 my $form = $self->{"form"};
355 if ($form->{"IN"} =~ m|^/|) {
356 $file_name = $form->{"IN"};
358 $file_name = $form->{"templates"} . "/" . $form->{"IN"};
361 my $zip = Archive::Zip->new();
362 if (Archive::Zip->AZ_OK != $zip->read($file_name)) {
363 $self->{"error"} = "File not found/is not a OpenDocument file.";
364 $main::lxdebug->leave_sub();
368 my $contents = Encode::decode('utf-8-strict', $zip->contents("content.xml"));
370 $self->{"error"} = "File is not a OpenDocument file.";
371 $main::lxdebug->leave_sub();
375 $self->{current_text_style} = '';
376 $self->{used_list_styles} = {
382 if ($self->{use_template_toolkit}) {
383 my $additional_params = $::form;
385 $::form->template->process(\$contents, $additional_params, \$new_contents) || die $::form->template->error;
387 $self->{tag_stack} = [];
388 $new_contents = $self->parse_block($contents);
390 if (!defined($new_contents)) {
391 $main::lxdebug->leave_sub();
395 my $new_styles = SL::Template::OpenDocument::Styles->get_style('text_basic');
397 foreach my $type (qw(itemize enumerate)) {
398 foreach my $parent (sort { $a cmp $b } keys %{ $self->{used_list_styles}->{$type} }) {
399 $new_styles .= SL::Template::OpenDocument::Styles->get_style('text_list_item', TYPE => $type, PARENT => $parent)
400 . SL::Template::OpenDocument::Styles->get_style("list_${type}", TYPE => $type, PARENT => $parent);
404 # $::lxdebug->dump(0, "new_Styles", $new_styles);
406 $new_contents =~ s|</office:automatic-styles>|${new_styles}</office:automatic-styles>|;
407 $new_contents =~ s|[\n\r]||gm;
409 # $new_contents =~ s|>|>\n|g;
411 $zip->contents("content.xml", Encode::encode('utf-8-strict', $new_contents));
413 my $styles = Encode::decode('utf-8-strict', $zip->contents("styles.xml"));
415 my $new_styles = $self->parse_block($styles);
416 if (!defined($new_contents)) {
417 $main::lxdebug->leave_sub();
420 $zip->contents("styles.xml", Encode::encode('utf-8-strict', $new_styles));
423 $zip->writeToFileNamed($form->{"tmpfile"}, 1);
426 if ($form->{"format"} =~ /pdf/) {
427 $res = $self->convert_to_pdf();
430 $main::lxdebug->leave_sub();
434 sub is_xvfb_running {
435 $main::lxdebug->enter_sub();
440 my $dfname = $self->{"userspath"} . "/xvfb_display";
443 $main::lxdebug->message(LXDebug->DEBUG2(), " Looking for $dfname\n");
444 if ((-f $dfname) && open(IN, $dfname)) {
449 my $xauthority = <IN>;
453 $main::lxdebug->message(LXDebug->DEBUG2(), " found with $pid and $display\n");
455 if ((! -d "/proc/$pid") || !open(IN, "/proc/$pid/cmdline")) {
456 $main::lxdebug->message(LXDebug->DEBUG2(), " no/wrong process #1\n");
457 unlink($dfname, $xauthority);
458 $main::lxdebug->leave_sub();
463 if ($line !~ /xvfb/i) {
464 $main::lxdebug->message(LXDebug->DEBUG2(), " no/wrong process #2\n");
465 unlink($dfname, $xauthority);
466 $main::lxdebug->leave_sub();
470 $ENV{"XAUTHORITY"} = $xauthority;
471 $ENV{"DISPLAY"} = $display;
473 $main::lxdebug->message(LXDebug->DEBUG2(), " not found\n");
476 $main::lxdebug->leave_sub();
482 $main::lxdebug->enter_sub();
486 $main::lxdebug->message(LXDebug->DEBUG2, "spawn_xvfb()\n");
488 my $display = $self->is_xvfb_running();
491 $main::lxdebug->leave_sub();
496 while ( -f "/tmp/.X${display}-lock") {
499 $display = ":${display}";
500 $main::lxdebug->message(LXDebug->DEBUG2(), " display $display\n");
502 my $mcookie = `mcookie`;
503 die("Installation error: mcookie not found.") if ($? != 0);
506 $main::lxdebug->message(LXDebug->DEBUG2(), " mcookie $mcookie\n");
508 my $xauthority = "/tmp/.Xauthority-" . $$ . "-" . time() . "-" . int(rand(9999999));
509 $ENV{"XAUTHORITY"} = $xauthority;
511 $main::lxdebug->message(LXDebug->DEBUG2(), " xauthority $xauthority\n");
513 if (system("xauth add \"${display}\" . \"${mcookie}\"") == -1) {
514 die "system call to xauth failed: $!";
517 $self->{"error"} = "Conversion to PDF failed because OpenOffice could not be started (xauth: $!)";
518 $main::lxdebug->leave_sub();
522 $main::lxdebug->message(LXDebug->DEBUG2(), " about to fork()\n");
526 $main::lxdebug->message(LXDebug->DEBUG2(), " Child execing\n");
527 exec($::lx_office_conf{applications}->{xvfb}, $display, "-screen", "0", "640x480x8", "-nolisten", "tcp");
530 $main::lxdebug->message(LXDebug->DEBUG2(), " parent dont sleeping\n");
533 my $dfname = $self->{"userspath"} . "/xvfb_display";
534 if (!open(OUT, ">", $dfname)) {
535 $self->{"error"} = "Conversion to PDF failed because OpenOffice could not be started ($dfname: $!)";
538 $main::lxdebug->leave_sub();
541 print(OUT "$pid\n$display\n$xauthority\n");
544 $main::lxdebug->message(LXDebug->DEBUG2(), " parent re-testing\n");
546 if (!$self->is_xvfb_running()) {
547 $self->{"error"} = "Conversion to PDF failed because OpenOffice could not be started.";
548 unlink($xauthority, $dfname);
550 $main::lxdebug->leave_sub();
554 $main::lxdebug->message(LXDebug->DEBUG2(), " spawn OK\n");
556 $main::lxdebug->leave_sub();
561 sub _run_python_uno {
562 my ($self, @args) = @_;
564 local $ENV{PYTHONPATH};
565 $ENV{PYTHONPATH} = $::lx_office_conf{environment}->{python_uno_path} . ':' . $ENV{PYTHONPATH} if $::lx_office_conf{environment}->{python_uno_path};
566 my $cmd = $::lx_office_conf{applications}->{python_uno} . ' ' . join(' ', @args);
570 sub is_openoffice_running {
573 $main::lxdebug->enter_sub();
575 my $output = $self->_run_python_uno('./scripts/oo-uno-test-conn.py', $::lx_office_conf{print_templates}->{openofficeorg_daemon_port}, ' 2> /dev/null');
578 my $res = ($? == 0) || $output;
579 $main::lxdebug->message(LXDebug->DEBUG2(), " is_openoffice_running(): res $res\n");
581 $main::lxdebug->leave_sub();
586 sub spawn_openoffice {
587 $main::lxdebug->enter_sub();
591 $main::lxdebug->message(LXDebug->DEBUG2(), "spawn_openoffice()\n");
593 my ($try, $spawned_oo, $res);
596 for ($try = 0; $try < 15; $try++) {
597 if ($self->is_openoffice_running()) {
602 if ($::dispatcher->interface_type eq 'FastCGI') {
603 $::dispatcher->{request}->Detach;
609 $main::lxdebug->message(LXDebug->DEBUG2(), " Child daemonizing\n");
611 if ($::dispatcher->interface_type eq 'FastCGI') {
612 $::dispatcher->{request}->Finish;
613 $::dispatcher->{request}->LastCall;
616 open(STDIN, '/dev/null');
617 open(STDOUT, '>/dev/null');
618 my $new_pid = fork();
620 my $ssres = setsid();
621 $main::lxdebug->message(LXDebug->DEBUG2(), " Child execing\n");
622 my @cmdline = ($::lx_office_conf{applications}->{openofficeorg_writer},
623 "-minimized", "-norestore", "-nologo", "-nolockcheck",
625 "-accept=socket,host=localhost,port=" .
626 $::lx_office_conf{print_templates}->{openofficeorg_daemon_port} . ";urp;");
630 if ($::dispatcher->interface_type eq 'FastCGI') {
631 $::dispatcher->{request}->Attach;
635 $main::lxdebug->message(LXDebug->DEBUG2(), " Parent after fork\n");
640 sleep($try >= 5 ? 2 : 1);
644 $self->{"error"} = "Conversion from OpenDocument to PDF failed because " .
645 "OpenOffice could not be started.";
648 $main::lxdebug->leave_sub();
654 $main::lxdebug->enter_sub();
658 my $form = $self->{"form"};
660 my $filename = $form->{"tmpfile"};
661 $filename =~ s/.odt$//;
662 if (substr($filename, 0, 1) ne "/") {
663 $filename = getcwd() . "/${filename}";
666 if (substr($self->{"userspath"}, 0, 1) eq "/") {
667 $ENV{'HOME'} = $self->{"userspath"};
669 $ENV{'HOME'} = getcwd() . "/" . $self->{"userspath"};
672 if (!$self->spawn_xvfb()) {
673 $main::lxdebug->leave_sub();
677 if (!$::lx_office_conf{print_templates}->{openofficeorg_daemon}) {
678 if (system($::lx_office_conf{applications}->{openofficeorg_writer},
679 "-minimized", "-norestore", "-nologo", "-nolockcheck", "-headless",
680 "file:${filename}.odt",
681 "macro://" . (split('/', $filename))[-1] . "/Standard.Conversion.ConvertSelfToPDF()") == -1) {
682 die "system call to $::lx_office_conf{applications}->{openofficeorg_writer} failed: $!";
685 if (!$self->spawn_openoffice()) {
686 $main::lxdebug->leave_sub();
690 $self->_run_python_uno('./scripts/oo-uno-convert-pdf.py', $::lx_office_conf{print_templates}->{openofficeorg_daemon_port}, "${filename}.odt");
694 if ((0 == $?) || (-f "${filename}.pdf" && -s "${filename}.pdf")) {
695 $form->{"tmpfile"} =~ s/odt$/pdf/;
697 unlink($filename . ".odt");
699 $main::lxdebug->leave_sub();
704 unlink($filename . ".odt", $filename . ".pdf");
705 $self->{"error"} = "Conversion from OpenDocument to PDF failed. " .
708 $main::lxdebug->leave_sub();
713 my ($self, $content, $variable) = @_;
716 $formatters{ $self->{variable_content_types}->{$variable} }
717 // $formatters{ $self->{default_content_type} }
718 // $formatters{ text };
720 return $formatter->($self, $content, variable => $variable);
723 sub get_mime_type() {
726 if ($self->{"form"}->{"format"} =~ /pdf/) {
727 return "application/pdf";
729 return "application/vnd.oasis.opendocument.text";