Unterstützung für andere Datenbankencodings als Unicode/UTF-8 entfernt
[kivitendo-erp.git] / SL / Template / OpenDocument.pm
1 package SL::Template::OpenDocument;
2
3 use parent qw(SL::Template::Simple);
4
5 use Archive::Zip;
6 use Encode;
7 use POSIX 'setsid';
8
9 use SL::Iconv;
10
11 use Cwd;
12 # use File::Copy;
13 # use File::Spec;
14 # use File::Temp qw(:mktemp);
15 use IO::File;
16
17 use strict;
18
19 sub new {
20   my $type = shift;
21
22   my $self = $type->SUPER::new(@_);
23
24   $self->{"rnd"}   = int(rand(1000000));
25
26   $self->set_tag_style('<%', '%>');
27   $self->{quot_re} = '"';
28
29   return $self;
30 }
31
32 sub parse_foreach {
33   my ($self, $var, $text, $start_tag, $end_tag, @indices) = @_;
34
35   my ($form, $new_contents) = ($self->{"form"}, "");
36
37   my $ary = $self->_get_loop_variable($var, 1, @indices);
38
39   for (my $i = 0; $i < scalar(@{$ary || []}); $i++) {
40     $form->{"__first__"} = $i == 0;
41     $form->{"__last__"} = ($i + 1) == scalar(@{$ary});
42     $form->{"__odd__"} = (($i + 1) % 2) == 1;
43     $form->{"__counter__"} = $i + 1;
44     my $new_text = $self->parse_block($text, (@indices, $i));
45     return undef unless (defined($new_text));
46     $new_contents .= $start_tag . $new_text . $end_tag;
47   }
48   map({ delete($form->{"__${_}__"}); } qw(first last odd counter));
49
50   return $new_contents;
51 }
52
53 sub find_end {
54   my ($self, $text, $pos, $var, $not) = @_;
55
56   my $depth = 1;
57   $pos = 0 unless ($pos);
58
59   while ($pos < length($text)) {
60     $pos++;
61
62     next if (substr($text, $pos - 1, 5) ne '&lt;%');
63
64     if ((substr($text, $pos + 4, 2) eq 'if') || (substr($text, $pos + 4, 3) eq 'for')) {
65       $depth++;
66
67     } elsif ((substr($text, $pos + 4, 4) eq 'else') && (1 == $depth)) {
68       if (!$var) {
69         $self->{"error"} = '<%else%> outside of <%if%> / <%ifnot%>.';
70         return undef;
71       }
72
73       my $block = substr($text, 0, $pos - 1);
74       substr($text, 0, $pos - 1) = "";
75       $text =~ s!^\&lt;\%[^\%]+\%\&gt;!!;
76       $text = '&lt;%if' . ($not ?  " " : "not ") . $var . '%&gt;' . $text;
77
78       return ($block, $text);
79
80     } elsif (substr($text, $pos + 4, 3) eq 'end') {
81       $depth--;
82       if ($depth == 0) {
83         my $block = substr($text, 0, $pos - 1);
84         substr($text, 0, $pos - 1) = "";
85         $text =~ s!^\&lt;\%[^\%]+\%\&gt;!!;
86
87         return ($block, $text);
88       }
89     }
90   }
91
92   return undef;
93 }
94
95 sub parse_block {
96   $main::lxdebug->enter_sub();
97
98   my ($self, $contents, @indices) = @_;
99
100   my $new_contents = "";
101
102   while ($contents ne "") {
103     if (substr($contents, 0, 1) eq "<") {
104       $contents =~ m|^<[^>]+>|;
105       my $tag = $&;
106       substr($contents, 0, length($&)) = "";
107
108       if ($tag =~ m|<table:table-row|) {
109         $contents =~ m|^(.*?)(</table:table-row[^>]*>)|;
110         my $table_row = $1;
111         my $end_tag = $2;
112
113         if ($table_row =~ m|\&lt;\%foreachrow\s+(.*?)\%\&gt;|) {
114           my $var = $1;
115
116           $contents =~ m|\&lt;\%foreachrow\s+.*?\%\&gt;|;
117           substr($contents, length($`), length($&)) = "";
118
119           ($table_row, $contents) = $self->find_end($contents, length($`));
120           if (!$table_row) {
121             $self->{"error"} = "Unclosed <\%foreachrow\%>." unless ($self->{"error"});
122             $main::lxdebug->leave_sub();
123             return undef;
124           }
125
126           $contents   =~ m|^(.*?)(</table:table-row[^>]*>)|;
127           $table_row .=  $1;
128           $end_tag    =  $2;
129
130           substr $contents, 0, length($&), '';
131
132           my $new_text = $self->parse_foreach($var, $table_row, $tag, $end_tag, @indices);
133           if (!defined($new_text)) {
134             $main::lxdebug->leave_sub();
135             return undef;
136           }
137           $new_contents .= $new_text;
138
139         } else {
140           substr($contents, 0, length($table_row) + length($end_tag)) = "";
141           my $new_text = $self->parse_block($table_row, @indices);
142           if (!defined($new_text)) {
143             $main::lxdebug->leave_sub();
144             return undef;
145           }
146           $new_contents .= $tag . $new_text . $end_tag;
147         }
148
149       } else {
150         $new_contents .= $tag;
151       }
152
153     } else {
154       $contents =~ /^[^<]+/;
155       my $text = $&;
156
157       my $pos_if = index($text, '&lt;%if');
158       my $pos_foreach = index($text, '&lt;%foreach');
159
160       if ((-1 == $pos_if) && (-1 == $pos_foreach)) {
161         substr($contents, 0, length($text)) = "";
162         $new_contents .= $self->substitute_vars($text, @indices);
163         next;
164       }
165
166       if ((-1 == $pos_if) || ((-1 != $pos_foreach) && ($pos_if > $pos_foreach))) {
167         $new_contents .= $self->substitute_vars(substr($contents, 0, $pos_foreach), @indices);
168         substr($contents, 0, $pos_foreach) = "";
169
170         if ($contents !~ m|^\&lt;\%foreach (.*?)\%\&gt;|) {
171           $self->{"error"} = "Malformed <\%foreach\%>.";
172           $main::lxdebug->leave_sub();
173           return undef;
174         }
175
176         my $var = $1;
177
178         substr($contents, 0, length($&)) = "";
179
180         my $block;
181         ($block, $contents) = $self->find_end($contents);
182         if (!$block) {
183           $self->{"error"} = "Unclosed <\%foreach\%>." unless ($self->{"error"});
184           $main::lxdebug->leave_sub();
185           return undef;
186         }
187
188         my $new_text = $self->parse_foreach($var, $block, "", "", @indices);
189         if (!defined($new_text)) {
190           $main::lxdebug->leave_sub();
191           return undef;
192         }
193         $new_contents .= $new_text;
194
195       } else {
196         if (!$self->_parse_block_if(\$contents, \$new_contents, $pos_if, @indices)) {
197           $main::lxdebug->leave_sub();
198           return undef;
199         }
200       }
201     }
202   }
203
204   $main::lxdebug->leave_sub();
205
206   return $new_contents;
207 }
208
209 sub parse {
210   $main::lxdebug->enter_sub();
211   my $self = $_[0];
212   local *OUT = $_[1];
213   my $form = $self->{"form"};
214
215   close(OUT);
216
217   my $file_name;
218   if ($form->{"IN"} =~ m|^/|) {
219     $file_name = $form->{"IN"};
220   } else {
221     $file_name = $form->{"templates"} . "/" . $form->{"IN"};
222   }
223
224   my $zip = Archive::Zip->new();
225   if (Archive::Zip->AZ_OK != $zip->read($file_name)) {
226     $self->{"error"} = "File not found/is not a OpenDocument file.";
227     $main::lxdebug->leave_sub();
228     return 0;
229   }
230
231   my $contents = Encode::decode('utf-8-strict', $zip->contents("content.xml"));
232   if (!$contents) {
233     $self->{"error"} = "File is not a OpenDocument file.";
234     $main::lxdebug->leave_sub();
235     return 0;
236   }
237
238   my $rnd = $self->{"rnd"};
239   my $new_styles = qq|<style:style style:name="TLXO${rnd}BOLD" style:family="text">
240 <style:text-properties fo:font-weight="bold" style:font-weight-asian="bold" style:font-weight-complex="bold"/>
241 </style:style>
242 <style:style style:name="TLXO${rnd}ITALIC" style:family="text">
243 <style:text-properties fo:font-style="italic" style:font-style-asian="italic" style:font-style-complex="italic"/>
244 </style:style>
245 <style:style style:name="TLXO${rnd}UNDERLINE" style:family="text">
246 <style:text-properties style:text-underline-style="solid" style:text-underline-width="auto" style:text-underline-color="font-color"/>
247 </style:style>
248 <style:style style:name="TLXO${rnd}STRIKETHROUGH" style:family="text">
249 <style:text-properties style:text-line-through-style="solid"/>
250 </style:style>
251 <style:style style:name="TLXO${rnd}SUPER" style:family="text">
252 <style:text-properties style:text-position="super 58%"/>
253 </style:style>
254 <style:style style:name="TLXO${rnd}SUB" style:family="text">
255 <style:text-properties style:text-position="sub 58%"/>
256 </style:style>
257 |;
258
259   $contents =~ s|</office:automatic-styles>|${new_styles}</office:automatic-styles>|;
260   $contents =~ s|[\n\r]||gm;
261
262   my $new_contents;
263   if ($self->{use_template_toolkit}) {
264     my $additional_params = $::form;
265
266     $::form->init_template->process(\$contents, $additional_params, \$new_contents) || die $::form->template->error;
267   } else {
268     $new_contents = $self->parse_block($contents);
269   }
270   if (!defined($new_contents)) {
271     $main::lxdebug->leave_sub();
272     return 0;
273   }
274
275 #   $new_contents =~ s|>|>\n|g;
276
277   $zip->contents("content.xml", Encode::encode('utf-8-strict', $new_contents));
278
279   my $styles = Encode::decode('utf-8-strict', $zip->contents("styles.xml"));
280   if ($contents) {
281     my $new_styles = $self->parse_block($styles);
282     if (!defined($new_contents)) {
283       $main::lxdebug->leave_sub();
284       return 0;
285     }
286     $zip->contents("styles.xml", Encode::encode('utf-8-strict', $new_styles));
287   }
288
289   $zip->writeToFileNamed($form->{"tmpfile"}, 1);
290
291   my $res = 1;
292   if ($form->{"format"} =~ /pdf/) {
293     $res = $self->convert_to_pdf();
294   }
295
296   $main::lxdebug->leave_sub();
297   return $res;
298 }
299
300 sub is_xvfb_running {
301   $main::lxdebug->enter_sub();
302
303   my ($self) = @_;
304
305   local *IN;
306   my $dfname = $self->{"userspath"} . "/xvfb_display";
307   my $display;
308
309   $main::lxdebug->message(LXDebug->DEBUG2(), "    Looking for $dfname\n");
310   if ((-f $dfname) && open(IN, $dfname)) {
311     my $pid = <IN>;
312     chomp($pid);
313     $display = <IN>;
314     chomp($display);
315     my $xauthority = <IN>;
316     chomp($xauthority);
317     close(IN);
318
319     $main::lxdebug->message(LXDebug->DEBUG2(), "      found with $pid and $display\n");
320
321     if ((! -d "/proc/$pid") || !open(IN, "/proc/$pid/cmdline")) {
322       $main::lxdebug->message(LXDebug->DEBUG2(), "  no/wrong process #1\n");
323       unlink($dfname, $xauthority);
324       $main::lxdebug->leave_sub();
325       return undef;
326     }
327     my $line = <IN>;
328     close(IN);
329     if ($line !~ /xvfb/i) {
330       $main::lxdebug->message(LXDebug->DEBUG2(), "      no/wrong process #2\n");
331       unlink($dfname, $xauthority);
332       $main::lxdebug->leave_sub();
333       return undef;
334     }
335
336     $ENV{"XAUTHORITY"} = $xauthority;
337     $ENV{"DISPLAY"} = $display;
338   } else {
339     $main::lxdebug->message(LXDebug->DEBUG2(), "      not found\n");
340   }
341
342   $main::lxdebug->leave_sub();
343
344   return $display;
345 }
346
347 sub spawn_xvfb {
348   $main::lxdebug->enter_sub();
349
350   my ($self) = @_;
351
352   $main::lxdebug->message(LXDebug->DEBUG2, "spawn_xvfb()\n");
353
354   my $display = $self->is_xvfb_running();
355
356   if ($display) {
357     $main::lxdebug->leave_sub();
358     return $display;
359   }
360
361   $display = 99;
362   while ( -f "/tmp/.X${display}-lock") {
363     $display++;
364   }
365   $display = ":${display}";
366   $main::lxdebug->message(LXDebug->DEBUG2(), "  display $display\n");
367
368   my $mcookie = `mcookie`;
369   die("Installation error: mcookie not found.") if ($? != 0);
370   chomp($mcookie);
371
372   $main::lxdebug->message(LXDebug->DEBUG2(), "  mcookie $mcookie\n");
373
374   my $xauthority = "/tmp/.Xauthority-" . $$ . "-" . time() . "-" . int(rand(9999999));
375   $ENV{"XAUTHORITY"} = $xauthority;
376
377   $main::lxdebug->message(LXDebug->DEBUG2(), "  xauthority $xauthority\n");
378
379   system("xauth add \"${display}\" . \"${mcookie}\"");
380   if ($? != 0) {
381     $self->{"error"} = "Conversion to PDF failed because OpenOffice could not be started (xauth: $!)";
382     $main::lxdebug->leave_sub();
383     return undef;
384   }
385
386   $main::lxdebug->message(LXDebug->DEBUG2(), "  about to fork()\n");
387
388   my $pid = fork();
389   if (0 == $pid) {
390     $main::lxdebug->message(LXDebug->DEBUG2(), "  Child execing\n");
391     exec($::lx_office_conf{applications}->{xvfb}, $display, "-screen", "0", "640x480x8", "-nolisten", "tcp");
392   }
393   sleep(3);
394   $main::lxdebug->message(LXDebug->DEBUG2(), "  parent dont sleeping\n");
395
396   local *OUT;
397   my $dfname = $self->{"userspath"} . "/xvfb_display";
398   if (!open(OUT, ">", $dfname)) {
399     $self->{"error"} = "Conversion to PDF failed because OpenOffice could not be started ($dfname: $!)";
400     unlink($xauthority);
401     kill($pid);
402     $main::lxdebug->leave_sub();
403     return undef;
404   }
405   print(OUT "$pid\n$display\n$xauthority\n");
406   close(OUT);
407
408   $main::lxdebug->message(LXDebug->DEBUG2(), "  parent re-testing\n");
409
410   if (!$self->is_xvfb_running()) {
411     $self->{"error"} = "Conversion to PDF failed because OpenOffice could not be started.";
412     unlink($xauthority, $dfname);
413     kill($pid);
414     $main::lxdebug->leave_sub();
415     return undef;
416   }
417
418   $main::lxdebug->message(LXDebug->DEBUG2(), "  spawn OK\n");
419
420   $main::lxdebug->leave_sub();
421
422   return $display;
423 }
424
425 sub _run_python_uno {
426   my ($self, @args) = @_;
427
428   local $ENV{PYTHONPATH};
429   $ENV{PYTHONPATH} = $::lx_office_conf{environment}->{python_uno_path} . ':' . $ENV{PYTHONPATH} if $::lx_office_conf{environment}->{python_uno_path};
430   my $cmd          = $::lx_office_conf{applications}->{python_uno} . ' ' . join(' ', @args);
431   return `$cmd`;
432 }
433
434 sub is_openoffice_running {
435   my ($self) = @_;
436
437   $main::lxdebug->enter_sub();
438
439   my $output = $self->_run_python_uno('./scripts/oo-uno-test-conn.py', $::lx_office_conf{print_templates}->{openofficeorg_daemon_port}, ' 2> /dev/null');
440   chomp $output;
441
442   my $res = ($? == 0) || $output;
443   $main::lxdebug->message(LXDebug->DEBUG2(), "  is_openoffice_running(): res $res\n");
444
445   $main::lxdebug->leave_sub();
446
447   return $res;
448 }
449
450 sub spawn_openoffice {
451   $main::lxdebug->enter_sub();
452
453   my ($self) = @_;
454
455   $main::lxdebug->message(LXDebug->DEBUG2(), "spawn_openoffice()\n");
456
457   my ($try, $spawned_oo, $res);
458
459   $res = 0;
460   for ($try = 0; $try < 15; $try++) {
461     if ($self->is_openoffice_running()) {
462       $res = 1;
463       last;
464     }
465
466     if ($::dispatcher->interface_type eq 'FastCGI') {
467       $::dispatcher->{request}->Detach;
468     }
469
470     if (!$spawned_oo) {
471       my $pid = fork();
472       if (0 == $pid) {
473         $main::lxdebug->message(LXDebug->DEBUG2(), "  Child daemonizing\n");
474
475         if ($::dispatcher->interface_type eq 'FastCGI') {
476           $::dispatcher->{request}->Finish;
477           $::dispatcher->{request}->LastCall;
478         }
479         chdir('/');
480         open(STDIN, '/dev/null');
481         open(STDOUT, '>/dev/null');
482         my $new_pid = fork();
483         exit if ($new_pid);
484         my $ssres = setsid();
485         $main::lxdebug->message(LXDebug->DEBUG2(), "  Child execing\n");
486         my @cmdline = ($::lx_office_conf{applications}->{openofficeorg_writer},
487                        "-minimized", "-norestore", "-nologo", "-nolockcheck",
488                        "-headless",
489                        "-accept=socket,host=localhost,port=" .
490                        $::lx_office_conf{print_templates}->{openofficeorg_daemon_port} . ";urp;");
491         exec(@cmdline);
492       } else {
493         # parent
494         if ($::dispatcher->interface_type eq 'FastCGI') {
495           $::dispatcher->{request}->Attach;
496         }
497       }
498
499       $main::lxdebug->message(LXDebug->DEBUG2(), "  Parent after fork\n");
500       $spawned_oo = 1;
501       sleep(3);
502     }
503
504     sleep($try >= 5 ? 2 : 1);
505   }
506
507   if (!$res) {
508     $self->{"error"} = "Conversion from OpenDocument to PDF failed because " .
509       "OpenOffice could not be started.";
510   }
511
512   $main::lxdebug->leave_sub();
513
514   return $res;
515 }
516
517 sub convert_to_pdf {
518   $main::lxdebug->enter_sub();
519
520   my ($self) = @_;
521
522   my $form = $self->{"form"};
523
524   my $filename = $form->{"tmpfile"};
525   $filename =~ s/.odt$//;
526   if (substr($filename, 0, 1) ne "/") {
527     $filename = getcwd() . "/${filename}";
528   }
529
530   if (substr($self->{"userspath"}, 0, 1) eq "/") {
531     $ENV{'HOME'} = $self->{"userspath"};
532   } else {
533     $ENV{'HOME'} = getcwd() . "/" . $self->{"userspath"};
534   }
535
536   if (!$self->spawn_xvfb()) {
537     $main::lxdebug->leave_sub();
538     return 0;
539   }
540
541   if (!$::lx_office_conf{print_templates}->{openofficeorg_daemon}) {
542     system($::lx_office_conf{applications}->{openofficeorg_writer},
543            "-minimized", "-norestore", "-nologo", "-nolockcheck", "-headless",
544            "file:${filename}.odt",
545            "macro://" . (split('/', $filename))[-1] . "/Standard.Conversion.ConvertSelfToPDF()");
546   } else {
547     if (!$self->spawn_openoffice()) {
548       $main::lxdebug->leave_sub();
549       return 0;
550     }
551
552     $self->_run_python_uno('./scripts/oo-uno-convert-pdf.py', $::lx_office_conf{print_templates}->{openofficeorg_daemon_port}, "${filename}.odt");
553   }
554
555   my $res = $?;
556   if ((0 == $?) || (-f "${filename}.pdf" && -s "${filename}.pdf")) {
557     $form->{"tmpfile"} =~ s/odt$/pdf/;
558
559     unlink($filename . ".odt");
560
561     $main::lxdebug->leave_sub();
562     return 1;
563
564   }
565
566   unlink($filename . ".odt", $filename . ".pdf");
567   $self->{"error"} = "Conversion from OpenDocument to PDF failed. " .
568     "Exit code: $res";
569
570   $main::lxdebug->leave_sub();
571   return 0;
572 }
573
574 sub format_string {
575   my ($self, $variable) = @_;
576   my $form = $self->{"form"};
577
578   $variable = $main::locale->quote_special_chars('Template/OpenDocument', $variable);
579
580   # Allow some HTML markup to be converted into the output format's
581   # corresponding markup code, e.g. bold or italic.
582   my $rnd = $self->{"rnd"};
583   my %markup_replace = ("b" => "BOLD", "i" => "ITALIC", "s" => "STRIKETHROUGH",
584                         "u" => "UNDERLINE", "sup" => "SUPER", "sub" => "SUB");
585
586   foreach my $key (keys(%markup_replace)) {
587     my $value = $markup_replace{$key};
588     $variable =~ s|\&lt;${key}\&gt;|<text:span text:style-name=\"TLXO${rnd}${value}\">|gi; #"
589     $variable =~ s|\&lt;/${key}\&gt;|</text:span>|gi;
590   }
591
592   return $variable;
593 }
594
595 sub get_mime_type() {
596   my ($self) = @_;
597
598   if ($self->{"form"}->{"format"} =~ /pdf/) {
599     return "application/pdf";
600   } else {
601     return "application/vnd.oasis.opendocument.text";
602   }
603 }
604
605 sub uses_temp_file {
606   return 1;
607 }
608
609 1;