98fba05927f834cd9f6ff6a197b7e7b714bd676b
[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 POSIX 'setsid';
7
8 use SL::Iconv;
9
10 use Cwd;
11 # use File::Copy;
12 # use File::Spec;
13 # use File::Temp qw(:mktemp);
14 use IO::File;
15
16 use strict;
17
18 sub new {
19   my $type = shift;
20
21   my $self = $type->SUPER::new(@_);
22
23   $self->{"rnd"}   = int(rand(1000000));
24   $self->{"iconv"} = SL::Iconv->new($main::dbcharset, "UTF-8");
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 = $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 = $self->parse_block($contents);
263   if (!defined($new_contents)) {
264     $main::lxdebug->leave_sub();
265     return 0;
266   }
267
268 #   $new_contents =~ s|>|>\n|g;
269
270   $zip->contents("content.xml", $new_contents);
271
272   my $styles = $zip->contents("styles.xml");
273   if ($contents) {
274     my $new_styles = $self->parse_block($styles);
275     if (!defined($new_contents)) {
276       $main::lxdebug->leave_sub();
277       return 0;
278     }
279     $zip->contents("styles.xml", $new_styles);
280   }
281
282   $zip->writeToFileNamed($form->{"tmpfile"}, 1);
283
284   my $res = 1;
285   if ($form->{"format"} =~ /pdf/) {
286     $res = $self->convert_to_pdf();
287   }
288
289   $main::lxdebug->leave_sub();
290   return $res;
291 }
292
293 sub is_xvfb_running {
294   $main::lxdebug->enter_sub();
295
296   my ($self) = @_;
297
298   local *IN;
299   my $dfname = $self->{"userspath"} . "/xvfb_display";
300   my $display;
301
302   $main::lxdebug->message(LXDebug->DEBUG2(), "    Looking for $dfname\n");
303   if ((-f $dfname) && open(IN, $dfname)) {
304     my $pid = <IN>;
305     chomp($pid);
306     $display = <IN>;
307     chomp($display);
308     my $xauthority = <IN>;
309     chomp($xauthority);
310     close(IN);
311
312     $main::lxdebug->message(LXDebug->DEBUG2(), "      found with $pid and $display\n");
313
314     if ((! -d "/proc/$pid") || !open(IN, "/proc/$pid/cmdline")) {
315       $main::lxdebug->message(LXDebug->DEBUG2(), "  no/wrong process #1\n");
316       unlink($dfname, $xauthority);
317       $main::lxdebug->leave_sub();
318       return undef;
319     }
320     my $line = <IN>;
321     close(IN);
322     if ($line !~ /xvfb/i) {
323       $main::lxdebug->message(LXDebug->DEBUG2(), "      no/wrong process #2\n");
324       unlink($dfname, $xauthority);
325       $main::lxdebug->leave_sub();
326       return undef;
327     }
328
329     $ENV{"XAUTHORITY"} = $xauthority;
330     $ENV{"DISPLAY"} = $display;
331   } else {
332     $main::lxdebug->message(LXDebug->DEBUG2(), "      not found\n");
333   }
334
335   $main::lxdebug->leave_sub();
336
337   return $display;
338 }
339
340 sub spawn_xvfb {
341   $main::lxdebug->enter_sub();
342
343   my ($self) = @_;
344
345   $main::lxdebug->message(LXDebug->DEBUG2, "spawn_xvfb()\n");
346
347   my $display = $self->is_xvfb_running();
348
349   if ($display) {
350     $main::lxdebug->leave_sub();
351     return $display;
352   }
353
354   $display = 99;
355   while ( -f "/tmp/.X${display}-lock") {
356     $display++;
357   }
358   $display = ":${display}";
359   $main::lxdebug->message(LXDebug->DEBUG2(), "  display $display\n");
360
361   my $mcookie = `mcookie`;
362   die("Installation error: mcookie not found.") if ($? != 0);
363   chomp($mcookie);
364
365   $main::lxdebug->message(LXDebug->DEBUG2(), "  mcookie $mcookie\n");
366
367   my $xauthority = "/tmp/.Xauthority-" . $$ . "-" . time() . "-" . int(rand(9999999));
368   $ENV{"XAUTHORITY"} = $xauthority;
369
370   $main::lxdebug->message(LXDebug->DEBUG2(), "  xauthority $xauthority\n");
371
372   system("xauth add \"${display}\" . \"${mcookie}\"");
373   if ($? != 0) {
374     $self->{"error"} = "Conversion to PDF failed because OpenOffice could not be started (xauth: $!)";
375     $main::lxdebug->leave_sub();
376     return undef;
377   }
378
379   $main::lxdebug->message(LXDebug->DEBUG2(), "  about to fork()\n");
380
381   my $pid = fork();
382   if (0 == $pid) {
383     $main::lxdebug->message(LXDebug->DEBUG2(), "  Child execing\n");
384     exec($main::xvfb_bin, $display, "-screen", "0", "640x480x8", "-nolisten", "tcp");
385   }
386   sleep(3);
387   $main::lxdebug->message(LXDebug->DEBUG2(), "  parent dont sleeping\n");
388
389   local *OUT;
390   my $dfname = $self->{"userspath"} . "/xvfb_display";
391   if (!open(OUT, ">$dfname")) {
392     $self->{"error"} = "Conversion to PDF failed because OpenOffice could not be started ($dfname: $!)";
393     unlink($xauthority);
394     kill($pid);
395     $main::lxdebug->leave_sub();
396     return undef;
397   }
398   print(OUT "$pid\n$display\n$xauthority\n");
399   close(OUT);
400
401   $main::lxdebug->message(LXDebug->DEBUG2(), "  parent re-testing\n");
402
403   if (!$self->is_xvfb_running()) {
404     $self->{"error"} = "Conversion to PDF failed because OpenOffice could not be started.";
405     unlink($xauthority, $dfname);
406     kill($pid);
407     $main::lxdebug->leave_sub();
408     return undef;
409   }
410
411   $main::lxdebug->message(LXDebug->DEBUG2(), "  spawn OK\n");
412
413   $main::lxdebug->leave_sub();
414
415   return $display;
416 }
417
418 sub is_openoffice_running {
419   $main::lxdebug->enter_sub();
420
421   my $output = `./scripts/oo-uno-test-conn.py $main::openofficeorg_daemon_port 2> /dev/null`;
422   chomp $output;
423
424   my $res = ($? == 0) || $output;
425   $main::lxdebug->message(LXDebug->DEBUG2(), "  is_openoffice_running(): res $res\n");
426
427   $main::lxdebug->leave_sub();
428
429   return $res;
430 }
431
432 sub spawn_openoffice {
433   $main::lxdebug->enter_sub();
434
435   my ($self) = @_;
436
437   $main::lxdebug->message(LXDebug->DEBUG2(), "spawn_openoffice()\n");
438
439   my ($try, $spawned_oo, $res);
440
441   $res = 0;
442   for ($try = 0; $try < 15; $try++) {
443     if ($self->is_openoffice_running()) {
444       $res = 1;
445       last;
446     }
447
448     if (!$spawned_oo) {
449       my $pid = fork();
450       if (0 == $pid) {
451         $main::lxdebug->message(LXDebug->DEBUG2(), "  Child daemonizing\n");
452         chdir('/');
453         open(STDIN, '/dev/null');
454         open(STDOUT, '>/dev/null');
455         my $new_pid = fork();
456         exit if ($new_pid);
457         my $ssres = setsid();
458         $main::lxdebug->message(LXDebug->DEBUG2(), "  Child execing\n");
459         my @cmdline = ($main::openofficeorg_writer_bin,
460                        "-minimized", "-norestore", "-nologo", "-nolockcheck",
461                        "-headless",
462                        "-accept=socket,host=localhost,port=" .
463                        $main::openofficeorg_daemon_port . ";urp;");
464         exec(@cmdline);
465       }
466
467       $main::lxdebug->message(LXDebug->DEBUG2(), "  Parent after fork\n");
468       $spawned_oo = 1;
469       sleep(3);
470     }
471
472     sleep($try >= 5 ? 2 : 1);
473   }
474
475   if (!$res) {
476     $self->{"error"} = "Conversion from OpenDocument to PDF failed because " .
477       "OpenOffice could not be started.";
478   }
479
480   $main::lxdebug->leave_sub();
481
482   return $res;
483 }
484
485 sub convert_to_pdf {
486   $main::lxdebug->enter_sub();
487
488   my ($self) = @_;
489
490   my $form = $self->{"form"};
491
492   my $filename = $form->{"tmpfile"};
493   $filename =~ s/.odt$//;
494   if (substr($filename, 0, 1) ne "/") {
495     $filename = getcwd() . "/${filename}";
496   }
497
498   if (substr($self->{"userspath"}, 0, 1) eq "/") {
499     $ENV{'HOME'} = $self->{"userspath"};
500   } else {
501     $ENV{'HOME'} = getcwd() . "/" . $self->{"userspath"};
502   }
503
504   if (!$self->spawn_xvfb()) {
505     $main::lxdebug->leave_sub();
506     return 0;
507   }
508
509   my @cmdline;
510   if (!$main::openofficeorg_daemon) {
511     @cmdline = ($main::openofficeorg_writer_bin,
512                 "-minimized", "-norestore", "-nologo", "-nolockcheck",
513                 "-headless",
514                 "file:${filename}.odt",
515                 "macro://" . (split('/', $filename))[-1] .
516                 "/Standard.Conversion.ConvertSelfToPDF()");
517   } else {
518     if (!$self->spawn_openoffice()) {
519       $main::lxdebug->leave_sub();
520       return 0;
521     }
522
523     @cmdline = ("./scripts/oo-uno-convert-pdf.py",
524                 $main::openofficeorg_daemon_port,
525                 "${filename}.odt");
526   }
527
528   system(@cmdline);
529
530   my $res = $?;
531   if ((0 == $?) || (-f "${filename}.pdf" && -s "${filename}.pdf")) {
532     $form->{"tmpfile"} =~ s/odt$/pdf/;
533
534     unlink($filename . ".odt");
535
536     $main::lxdebug->leave_sub();
537     return 1;
538
539   }
540
541   unlink($filename . ".odt", $filename . ".pdf");
542   $self->{"error"} = "Conversion from OpenDocument to PDF failed. " .
543     "Exit code: $res";
544
545   $main::lxdebug->leave_sub();
546   return 0;
547 }
548
549 sub format_string {
550   my ($self, $variable) = @_;
551   my $form = $self->{"form"};
552   my $iconv = $self->{"iconv"};
553
554   $variable = $main::locale->quote_special_chars('Template/OpenDocument', $variable);
555
556   # Allow some HTML markup to be converted into the output format's
557   # corresponding markup code, e.g. bold or italic.
558   my $rnd = $self->{"rnd"};
559   my %markup_replace = ("b" => "BOLD", "i" => "ITALIC", "s" => "STRIKETHROUGH",
560                         "u" => "UNDERLINE", "sup" => "SUPER", "sub" => "SUB");
561
562   foreach my $key (keys(%markup_replace)) {
563     my $value = $markup_replace{$key};
564     $variable =~ s|\&lt;${key}\&gt;|<text:span text:style-name=\"TLXO${rnd}${value}\">|gi; #"
565     $variable =~ s|\&lt;/${key}\&gt;|</text:span>|gi;
566   }
567
568   return $iconv->convert($variable);
569 }
570
571 sub get_mime_type() {
572   my ($self) = @_;
573
574   if ($self->{"form"}->{"format"} =~ /pdf/) {
575     return "application/pdf";
576   } else {
577     return "application/vnd.oasis.opendocument.text";
578   }
579 }
580
581 sub uses_temp_file {
582   return 1;
583 }
584
585 1;