Minimale Erweiterung um PlainTextTemplate, um Variablen in Strings leicht ersetzen...
[kivitendo-erp.git] / SL / Template.pm
1 #====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #====================================================================
8
9 package SimpleTemplate;
10
11 # Parameters:
12 #   1. The template's file name
13 #   2. A reference to the Form object
14 #   3. A reference to the myconfig hash
15 #
16 # Returns:
17 #   A new template object
18 sub new {
19   my $type = shift;
20   my $self = {};
21
22   bless($self, $type);
23   $self->_init(@_);
24
25   return $self;
26 }
27
28 sub _init {
29   my $self = shift;
30
31   $self->{"source"} = shift;
32   $self->{"form"} = shift;
33   $self->{"myconfig"} = shift;
34   $self->{"userspath"} = shift;
35
36   $self->{"error"} = undef;
37 }
38
39 sub cleanup {
40   my ($self) = @_;
41 }
42
43 # Parameters:
44 #   1. A typeglob for the file handle. The output will be written
45 #      to this file handle.
46 #
47 # Returns:
48 #   1 on success and undef or 0 if there was an error. In the latter case
49 #   the calling function can retrieve the error message via $obj->get_error()
50 sub parse {
51   my $self = $_[0];
52   local *OUT = $_[1];
53
54   print(OUT "Hallo!\n");
55 }
56
57 sub get_error {
58   my $self = shift;
59
60   return $self->{"error"};
61 }
62
63 sub uses_temp_file {
64   return 0;
65 }
66
67 1;
68
69 ####
70 #### LaTeXTemplate
71 ####
72
73 package LaTeXTemplate;
74
75 use vars qw(@ISA);
76
77 @ISA = qw(SimpleTemplate);
78
79 sub new {
80   my $type = shift;
81
82   return $type->SUPER::new(@_);
83 }
84
85 sub format_string {
86   my ($self, $variable) = @_;
87   my $form = $self->{"form"};
88
89   my %replace =
90     ('order' => [quotemeta("\\"),
91                  '<pagebreak>',
92                  '&', quotemeta("\n"),
93                  '"', '\$', '%', '_', '#', quotemeta('^'),
94                  '{', '}',  '<', '>', '£', "\r", '±', '\xe1',
95                  ],
96      quotemeta("\\") => '\\textbackslash ',
97      '<pagebreak>'   => '',
98      '"'             => "''",
99      '&'             => '\&',
100      '\$'            => '\$',
101      '%'             => '\%',
102      '_'             => '\_',
103      '#'             => '\#',
104      '{'             => '\{',
105      '}'             => '\}',
106      '<'             => '$<$',
107      '>'             => '$>$',
108      '£'             => '\pounds ',
109      "\r"            => "",
110      '±'             => '$\pm$',
111      '\xe1'          => '$\bullet$',
112      quotemeta('^')  => '\^\\',
113      quotemeta("\n") => '\newline '
114      );
115
116   map({ $variable =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
117
118   # Allow some HTML markup to be converted into the output format's
119   # corresponding markup code, e.g. bold or italic.
120   my %markup_replace = ('b' => 'textbf',
121                         'i' => 'textit',
122                         'u' => 'underline');
123
124   foreach my $key (keys(%markup_replace)) {
125     my $new = $markup_replace{$key};
126     $variable =~ s/\$\<\$${key}\$\>\$(.*?)\$<\$\/${key}\$>\$/\\${new}\{$1\}/gi;
127   }
128
129   $variable =~ s/[\x00-\x1f]//g;
130
131   return $variable;
132 }
133
134 sub substitute_vars {
135   my ($self, $text, @indices) = @_;
136
137   my $form = $self->{"form"};
138
139   while ($text =~ /<\%(.*?)\%>/) {
140     my ($var, @options) = split(/\s+/, $1);
141     my $value = $form->{$var};
142
143     for (my $i = 0; $i < scalar(@indices); $i++) {
144       last unless (ref($value) eq "ARRAY");
145       $value = $value->[$indices[$i]];
146     }
147     $value = $self->format_string($value) unless (grep(/^NOESCAPE$/, @options));
148     substr($text, $-[0], $+[0] - $-[0]) = $value;
149   }
150
151   return $text;
152 }
153
154 sub parse_foreach {
155   my ($self, $var, $text, $start_tag, $end_tag, @indices) = @_;
156
157   my ($form, $new_contents) = ($self->{"form"}, "");
158
159   my $ary = $form->{$var};
160   for (my $i = 0; $i < scalar(@indices); $i++) {
161     last unless (ref($ary) eq "ARRAY");
162     $ary = $ary->[$indices[$i]];
163   }
164
165   my $sum = 0;
166   my $current_page = 1;
167   my ($current_line, $corrent_row) = (0, 1);
168
169   for (my $i = 0; $i < scalar(@{$ary}); $i++) {
170     $form->{"__first__"} = $i == 0;
171     $form->{"__last__"} = ($i + 1) == scalar(@{$ary});
172     $form->{"__odd__"} = (($i + 1) % 2) == 1;
173     $form->{"__counter__"} = $i + 1;
174
175     if ((scalar(@{$form->{"description"}}) == scalar(@{$ary})) &&
176         $self->{"chars_per_line"}) {
177       my $lines =
178         int(length($form->{"description"}->[$i]) / $self->{"chars_per_line"});
179       my $lpp;
180
181       $form->{"description"}->[$i] =~ s/(\\newline\s?)*$//;
182       my $_description = $form->{"description"}->[$i];
183       while ($_description =~ /\\newline/) {
184         $lines++;
185         $_description =~ s/\\newline//;
186       }
187       $lines++;
188
189       if ($current_page == 1) {
190         $lpp = $self->{"lines_on_first_page"};
191       } else {
192         $lpp = $self->{"lines_on_second_page"};
193       }
194
195       # Yes we need a manual page break -- or the user has forced one
196       if ((($current_line + $lines) > $lpp) ||
197           ($form->{"description"}->[$i] =~ /<pagebreak>/)) {
198         my $pb = $self->{"pagebreak_block"};
199
200         # replace the special variables <%sumcarriedforward%>
201         # and <%lastpage%>
202
203         my $psum = $form->format_amount($self->{"myconfig"}, $sum, 2);
204         $pb =~ s/<%sumcarriedforward%>/$psum/g;
205         $pb =~ s/<%lastpage%>/$current_page/g;
206
207         my $new_text = $self->parse_block($pb, (@indices, $i));
208         return undef unless (defined($new_text));
209         $new_contents .= $new_text;
210
211         $current_page++;
212         $current_line = 0;
213       }
214       $current_line += $lines;
215     }
216     if ($i < scalar(@{$form->{"linetotal"}})) {
217       $sum += $form->parse_amount($self->{"myconfig"},
218                                   $form->{"linetotal"}->[$i]);
219     }
220     
221     $form->{"cumulatelinetotal"}[$i] = $form->format_amount($self->{"myconfig"}, $sum, 2);
222     
223     my $new_text = $self->parse_block($text, (@indices, $i));
224     return undef unless (defined($new_text));
225     $new_contents .= $start_tag . $new_text . $end_tag;
226   }
227   map({ delete($form->{"__${_}__"}); } qw(first last odd counter));
228
229   return $new_contents;
230 }
231
232 sub find_end {
233   my ($self, $text, $pos, $var, $not) = @_;
234
235   my $depth = 1;
236   $pos = 0 unless ($pos);
237
238   while ($pos < length($text)) {
239     $pos++;
240
241     next if (substr($text, $pos - 1, 2) ne '<%');
242
243     if ((substr($text, $pos + 1, 2) eq 'if') || (substr($text, $pos + 1, 3) eq 'for')) {
244       $depth++;
245
246     } elsif ((substr($text, $pos + 1, 4) eq 'else') && (1 == $depth)) {
247       if (!$var) {
248         $self->{"error"} = '<%else%> outside of <%if%> / <%ifnot%>.';
249         return undef;
250       }
251
252       my $block = substr($text, 0, $pos - 1);
253       substr($text, 0, $pos - 1) = "";
254       $text =~ s!^<\%[^\%]+\%>!!;
255       $text = '<%if' . ($not ?  " " : "not ") . $var . '%>' . $text;
256
257       return ($block, $text);
258
259     } elsif (substr($text, $pos + 1, 3) eq 'end') {
260       $depth--;
261       if ($depth == 0) {
262         my $block = substr($text, 0, $pos - 1);
263         substr($text, 0, $pos - 1) = "";
264         $text =~ s!^<\%[^\%]+\%>!!;
265
266         return ($block, $text);
267       }
268     }
269   }
270
271   return undef;
272 }
273
274 sub parse_block {
275   $main::lxdebug->enter_sub();
276
277   my ($self, $contents, @indices) = @_;
278
279   my $new_contents = "";
280
281   while ($contents ne "") {
282     my $pos_if = index($contents, '<%if');
283     my $pos_foreach = index($contents, '<%foreach');
284
285     if ((-1 == $pos_if) && (-1 == $pos_foreach)) {
286       $new_contents .= $self->substitute_vars($contents, @indices);
287       last;
288     }
289
290     if ((-1 == $pos_if) || ((-1 != $pos_foreach) && ($pos_if > $pos_foreach))) {
291       $new_contents .= $self->substitute_vars(substr($contents, 0, $pos_foreach), @indices);
292       substr($contents, 0, $pos_foreach) = "";
293
294       if ($contents !~ m|^<\%foreach (.*?)\%>|) {
295         $self->{"error"} = "Malformed <\%foreach\%>.";
296         $main::lxdebug->leave_sub();
297         return undef;
298       }
299
300       my $var = $1;
301
302       substr($contents, 0, length($&)) = "";
303
304       my $block;
305       ($block, $contents) = $self->find_end($contents);
306       if (!$block) {
307         $self->{"error"} = "Unclosed <\%foreach\%>." unless ($self->{"error"});
308         $main::lxdebug->leave_sub();
309         return undef;
310       }
311
312       my $new_text = $self->parse_foreach($var, $block, "", "", @indices);
313       if (!defined($new_text)) {
314         $main::lxdebug->leave_sub();
315         return undef;
316       }
317       $new_contents .= $new_text;
318
319     } else {
320       $new_contents .= $self->substitute_vars(substr($contents, 0, $pos_if), @indices);
321       substr($contents, 0, $pos_if) = "";
322
323       if ($contents !~ m|^<\%if\s*(not)?\s+(.*?)\%>|) {
324         $self->{"error"} = "Malformed <\%if\%>.";
325         $main::lxdebug->leave_sub();
326         return undef;
327       }
328
329       my ($not, $var) = ($1, $2);
330
331       substr($contents, 0, length($&)) = "";
332
333       ($block, $contents) = $self->find_end($contents, 0, $var, $not);
334       if (!$block) {
335         $self->{"error"} = "Unclosed <\%if${not}\%>." unless ($self->{"error"});
336         $main::lxdebug->leave_sub();
337         return undef;
338       }
339
340       my $value = $self->{"form"}->{$var};
341       for (my $i = 0; $i < scalar(@indices); $i++) {
342         last unless (ref($value) eq "ARRAY");
343         $value = $value->[$indices[$i]];
344       }
345
346       if (($not && !$value) || (!$not && $value)) {
347         my $new_text = $self->parse_block($block, @indices);
348         if (!defined($new_text)) {
349           $main::lxdebug->leave_sub();
350           return undef;
351         }
352         $new_contents .= $new_text;
353       }
354     }
355   }
356
357   $main::lxdebug->leave_sub();
358
359   return $new_contents;
360 }
361
362 sub parse {
363   my $self = $_[0];
364   local *OUT = $_[1];
365   my $form = $self->{"form"};
366
367   if (!open(IN, "$form->{templates}/$form->{IN}")) {
368     $self->{"error"} = "$!";
369     return 0;
370   }
371   @_ = <IN>;
372   close(IN);
373
374   my $contents = join("", @_);
375
376   # detect pagebreak block and its parameters
377   if ($contents =~ /<%pagebreak\s+(\d+)\s+(\d+)\s+(\d+)\s*%>(.*?)<%end(\s*pagebreak)?%>/s) {
378     $self->{"chars_per_line"} = $1;
379     $self->{"lines_on_first_page"} = $2;
380     $self->{"lines_on_second_page"} = $3;
381     $self->{"pagebreak_block"} = $4;
382
383     substr($contents, length($`), length($&)) = "";
384   }
385
386   $self->{"forced_pagebreaks"} = [];
387
388   my $new_contents = $self->parse_block($contents);
389   if (!defined($new_contents)) {
390     $main::lxdebug->leave_sub();
391     return 0;
392   }
393
394   print(OUT $new_contents);
395
396   if ($form->{"format"} =~ /postscript/i) {
397     return $self->convert_to_postscript();
398   } elsif ($form->{"format"} =~ /pdf/i) {
399     return $self->convert_to_pdf();
400   } else {
401     return 1;
402   }
403 }
404
405 sub convert_to_postscript {
406   my ($self) = @_;
407   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
408
409   # Convert the tex file to postscript
410
411   if (!chdir("$userspath")) {
412     $self->{"error"} = "chdir : $!";
413     $self->cleanup();
414     return 0;
415   }
416
417   $form->{tmpfile} =~ s/$userspath\///g;
418
419   for (my $run = 1; $run <= 2; $run++) {
420     system("latex --interaction=nonstopmode $form->{tmpfile} " .
421            "> $form->{tmpfile}.err");
422     if ($?) {
423       $self->{"error"} = $form->cleanup();
424       $self->cleanup();
425       return 0;
426     }
427   }
428
429   $form->{tmpfile} =~ s/tex$/dvi/;
430
431   system("dvips $form->{tmpfile} -o -q > /dev/null");
432   if ($?) {
433     $self->{"error"} = "dvips : $!";
434     $self->cleanup();
435     return 0;
436   }
437   $form->{tmpfile} =~ s/dvi$/ps/;
438
439   $self->cleanup();
440
441   return 1;
442 }
443
444 sub convert_to_pdf {
445   my ($self) = @_;
446   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
447
448   # Convert the tex file to PDF
449
450   if (!chdir("$userspath")) {
451     $self->{"error"} = "chdir : $!";
452     $self->cleanup();
453     return 0;
454   }
455
456   $form->{tmpfile} =~ s/$userspath\///g;
457
458   for (my $run = 1; $run <= 2; $run++) {
459     system("pdflatex --interaction=nonstopmode $form->{tmpfile} " .
460            "> $form->{tmpfile}.err");
461     if ($?) {
462       $self->{"error"} = $form->cleanup();
463       $self->cleanup();
464       return 0;
465     }
466   }
467
468   $form->{tmpfile} =~ s/tex$/pdf/;
469
470   $self->cleanup();
471 }
472
473 sub get_mime_type() {
474   my ($self) = @_;
475
476   if ($self->{"form"}->{"format"} =~ /postscript/i) {
477     return "application/postscript";
478   } else {
479     return "application/pdf";
480   }
481 }
482
483 sub uses_temp_file {
484   return 1;
485 }
486
487
488 ####
489 #### HTMLTemplate
490 ####
491
492 package HTMLTemplate;
493
494 use vars qw(@ISA);
495
496 @ISA = qw(LaTeXTemplate);
497
498 sub new {
499   my $type = shift;
500
501   return $type->SUPER::new(@_);
502 }
503
504 sub format_string {
505   my ($self, $variable) = @_;
506   my $form = $self->{"form"};
507
508   my %replace =
509     ('order' => ['<', '>', quotemeta("\n")],
510      '<'             => '&lt;',
511      '>'             => '&gt;',
512      quotemeta("\n") => '<br>',
513      );
514
515   map({ $variable =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
516
517   # Allow some HTML markup to be converted into the output format's
518   # corresponding markup code, e.g. bold or italic.
519   my @markup_replace = ('b', 'i', 's', 'u', 'sub', 'sup');
520
521   foreach my $key (@markup_replace) {
522     $variable =~ s/\&lt;(\/?)${key}\&gt;/<$1${key}>/g;
523   }
524
525   return $variable;
526 }
527
528 sub get_mime_type() {
529   my ($self) = @_;
530
531   if ($self->{"form"}->{"format"} =~ /postscript/i) {
532     return "application/postscript";
533   } elsif ($self->{"form"}->{"format"} =~ /pdf/i) {
534     return "application/pdf";
535   } else {
536     return "text/html";
537   }
538 }
539
540 sub uses_temp_file {
541   my ($self) = @_;
542
543   if ($self->{"form"}->{"format"} =~ /postscript/i) {
544     return 1;
545   } elsif ($self->{"form"}->{"format"} =~ /pdf/i) {
546     return 1;
547   } else {
548     return 0;
549   }
550 }
551
552 sub convert_to_postscript {
553   my ($self) = @_;
554   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
555
556   # Convert the HTML file to postscript
557
558   if (!chdir("$userspath")) {
559     $self->{"error"} = "chdir : $!";
560     $self->cleanup();
561     return 0;
562   }
563
564   $form->{"tmpfile"} =~ s/$userspath\///g;
565   my $psfile = $form->{"tmpfile"};
566   $psfile =~ s/.html/.ps/;
567   if ($psfile eq $form->{"tmpfile"}) {
568     $psfile .= ".ps";
569   }
570
571   system("html2ps -f html2ps-config < $form->{tmpfile} > $psfile");
572   if ($?) {
573     $self->{"error"} = $form->cleanup();
574     $self->cleanup();
575     return 0;
576   }
577
578   $form->{"tmpfile"} = $psfile;
579
580   $self->cleanup();
581
582   return 1;
583 }
584
585 sub convert_to_pdf {
586   my ($self) = @_;
587   my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
588
589   # Convert the HTML file to PDF
590
591   if (!chdir("$userspath")) {
592     $self->{"error"} = "chdir : $!";
593     $self->cleanup();
594     return 0;
595   }
596
597   $form->{"tmpfile"} =~ s/$userspath\///g;
598   my $pdffile = $form->{"tmpfile"};
599   $pdffile =~ s/.html/.pdf/;
600   if ($pdffile eq $form->{"tmpfile"}) {
601     $pdffile .= ".pdf";
602   }
603
604   system("html2ps -f html2ps-config < $form->{tmpfile} | ps2pdf - $pdffile");
605   if ($?) {
606     $self->{"error"} = $form->cleanup();
607     $self->cleanup();
608     return 0;
609   }
610
611   $form->{"tmpfile"} = $pdffile;
612
613   $self->cleanup();
614
615   return 1;
616 }
617
618
619 ####
620 #### PlainTextTemplate
621 ####
622
623 package PlainTextTemplate;
624
625 use vars qw(@ISA);
626
627 @ISA = qw(LaTeXTemplate);
628
629 sub new {
630   my $type = shift;
631
632   return $type->SUPER::new(@_);
633 }
634
635 sub format_string {
636   my ($self, $variable) = @_;
637
638   return $variable;
639 }
640
641 sub get_mime_type {
642   return "text/plain";
643 }
644
645 sub parse {
646 }
647
648 1;
649
650 ####
651 #### OpenDocumentTemplate
652 ####
653
654 package OpenDocumentTemplate;
655
656 use POSIX 'setsid';
657 use vars qw(@ISA);
658
659 use Cwd;
660 # use File::Copy;
661 # use File::Spec;
662 # use File::Temp qw(:mktemp);
663 use IO::File;
664
665 @ISA = qw(SimpleTemplate);
666
667 sub new {
668   my $type = shift;
669
670   $self = $type->SUPER::new(@_);
671
672   foreach my $module (qw(Archive::Zip Text::Iconv)) {
673     eval("use ${module};");
674     if ($@) {
675       $self->{"form"}->error("The Perl module '${module}' could not be " .
676                              "loaded. Support for OpenDocument templates " .
677                              "does not work without it. Please install your " .
678                              "distribution's package or get the module from " .
679                              "CPAN ( http://www.cpan.org ).");
680     }
681   }
682
683   $self->{"rnd"} = int(rand(1000000));
684   $self->{"iconv"} = Text::Iconv->new($main::dbcharset, "UTF-8");
685
686   return $self;
687 }
688
689 sub substitute_vars {
690   my ($self, $text, @indices) = @_;
691
692   my $form = $self->{"form"};
693
694   while ($text =~ /\&lt;\%(.*?)\%\&gt;/) {
695     my $value = $form->{$1};
696
697     for (my $i = 0; $i < scalar(@indices); $i++) {
698       last unless (ref($value) eq "ARRAY");
699       $value = $value->[$indices[$i]];
700     }
701     substr($text, $-[0], $+[0] - $-[0]) = $self->format_string($value);
702   }
703
704   return $text;
705 }
706
707 sub parse_foreach {
708   my ($self, $var, $text, $start_tag, $end_tag, @indices) = @_;
709
710   my ($form, $new_contents) = ($self->{"form"}, "");
711
712   my $ary = $form->{$var};
713   for (my $i = 0; $i < scalar(@indices); $i++) {
714     last unless (ref($ary) eq "ARRAY");
715     $ary = $ary->[$indices[$i]];
716   }
717
718   for (my $i = 0; $i < scalar(@{$ary}); $i++) {
719     $form->{"__first__"} = $i == 0;
720     $form->{"__last__"} = ($i + 1) == scalar(@{$ary});
721     $form->{"__odd__"} = (($i + 1) % 2) == 1;
722     $form->{"__counter__"} = $i + 1;
723     my $new_text = $self->parse_block($text, (@indices, $i));
724     return undef unless (defined($new_text));
725     $new_contents .= $start_tag . $new_text . $end_tag;
726   }
727   map({ delete($form->{"__${_}__"}); } qw(first last odd counter));
728
729   return $new_contents;
730 }
731
732 sub find_end {
733   my ($self, $text, $pos, $var, $not) = @_;
734
735   my $depth = 1;
736   $pos = 0 unless ($pos);
737
738   while ($pos < length($text)) {
739     $pos++;
740
741     next if (substr($text, $pos - 1, 5) ne '&lt;%');
742
743     if ((substr($text, $pos + 4, 2) eq 'if') || (substr($text, $pos + 4, 3) eq 'for')) {
744       $depth++;
745
746     } elsif ((substr($text, $pos + 4, 4) eq 'else') && (1 == $depth)) {
747       if (!$var) {
748         $self->{"error"} = '<%else%> outside of <%if%> / <%ifnot%>.';
749         return undef;
750       }
751
752       my $block = substr($text, 0, $pos - 1);
753       substr($text, 0, $pos - 1) = "";
754       $text =~ s!^\&lt;\%[^\%]+\%\&gt;!!;
755       $text = '&lt;%if' . ($not ?  " " : "not ") . $var . '%&gt;' . $text;
756
757       return ($block, $text);
758
759     } elsif (substr($text, $pos + 4, 3) eq 'end') {
760       $depth--;
761       if ($depth == 0) {
762         my $block = substr($text, 0, $pos - 1);
763         substr($text, 0, $pos - 1) = "";
764         $text =~ s!^\&lt;\%[^\%]+\%\&gt;!!;
765
766         return ($block, $text);
767       }
768     }
769   }
770
771   return undef;
772 }
773
774 sub parse_block {
775   $main::lxdebug->enter_sub();
776
777   my ($self, $contents, @indices) = @_;
778
779   my $new_contents = "";
780
781   while ($contents ne "") {
782     if (substr($contents, 0, 1) eq "<") {
783       $contents =~ m|^<[^>]+>|;
784       my $tag = $&;
785       substr($contents, 0, length($&)) = "";
786
787       if ($tag =~ m|<table:table-row|) {
788         $contents =~ m|^(.*?)(</table:table-row[^>]*>)|;
789         my $table_row = $1;
790         my $end_tag = $2;
791         substr($contents, 0, length($1) + length($end_tag)) = "";
792
793         if ($table_row =~ m|\&lt;\%foreachrow\s+(.*?)\%\&gt;|) {
794           my $var = $1;
795
796           substr($table_row, length($`), length($&)) = "";
797
798           my ($t1, $t2) = $self->find_end($table_row, length($`));
799           if (!$t1) {
800             $self->{"error"} = "Unclosed <\%foreachrow\%>." unless ($self->{"error"});
801             $main::lxdebug->leave_sub();
802             return undef;
803           }
804
805           my $new_text = $self->parse_foreach($var, $t1 . $t2, $tag, $end_tag, @indices);
806           if (!defined($new_text)) {
807             $main::lxdebug->leave_sub();
808             return undef;
809           }
810           $new_contents .= $new_text;
811
812         } else {
813           my $new_text = $self->parse_block($table_row, @indices);
814           if (!defined($new_text)) {
815             $main::lxdebug->leave_sub();
816             return undef;
817           }
818           $new_contents .= $tag . $new_text . $end_tag;
819         }
820
821       } else {
822         $new_contents .= $tag;
823       }
824
825     } else {
826       $contents =~ /^[^<]+/;
827       my $text = $&;
828
829       my $pos_if = index($text, '&lt;%if');
830       my $pos_foreach = index($text, '&lt;%foreach');
831
832       if ((-1 == $pos_if) && (-1 == $pos_foreach)) {
833         substr($contents, 0, length($text)) = "";
834         $new_contents .= $self->substitute_vars($text, @indices);
835         next;
836       }
837
838       if ((-1 == $pos_if) || ((-1 != $pos_foreach) && ($pos_if > $pos_foreach))) {
839         $new_contents .= $self->substitute_vars(substr($contents, 0, $pos_foreach), @indices);
840         substr($contents, 0, $pos_foreach) = "";
841
842         if ($contents !~ m|^\&lt;\%foreach (.*?)\%\&gt;|) {
843           $self->{"error"} = "Malformed <\%foreach\%>.";
844           $main::lxdebug->leave_sub();
845           return undef;
846         }
847
848         my $var = $1;
849
850         substr($contents, 0, length($&)) = "";
851
852         my $block;
853         ($block, $contents) = $self->find_end($contents);
854         if (!$block) {
855           $self->{"error"} = "Unclosed <\%foreach\%>." unless ($self->{"error"});
856           $main::lxdebug->leave_sub();
857           return undef;
858         }
859
860         my $new_text = $self->parse_foreach($var, $block, "", "", @indices);
861         if (!defined($new_text)) {
862           $main::lxdebug->leave_sub();
863           return undef;
864         }
865         $new_contents .= $new_text;
866
867       } else {
868         $new_contents .= $self->substitute_vars(substr($contents, 0, $pos_if), @indices);
869         substr($contents, 0, $pos_if) = "";
870
871         if ($contents !~ m|^\&lt;\%if\s*(not)?\s+(.*?)\%\&gt;|) {
872           $self->{"error"} = "Malformed <\%if\%>.";
873           $main::lxdebug->leave_sub();
874           return undef;
875         }
876
877         my ($not, $var) = ($1, $2);
878
879         substr($contents, 0, length($&)) = "";
880
881         ($block, $contents) = $self->find_end($contents, 0, $var, $not);
882         if (!$block) {
883           $self->{"error"} = "Unclosed <\%if${not}\%>." unless ($self->{"error"});
884           $main::lxdebug->leave_sub();
885           return undef;
886         }
887
888         my $value = $self->{"form"}->{$var};
889         for (my $i = 0; $i < scalar(@indices); $i++) {
890           last unless (ref($value) eq "ARRAY");
891           $value = $value->[$indices[$i]];
892         }
893
894         if (($not && !$value) || (!$not && $value)) {
895           my $new_text = $self->parse_block($block, @indices);
896           if (!defined($new_text)) {
897             $main::lxdebug->leave_sub();
898             return undef;
899           }
900           $new_contents .= $new_text;
901         }
902       }
903     }
904   }
905
906   $main::lxdebug->leave_sub();
907
908   return $new_contents;
909 }
910
911 sub parse {
912   $main::lxdebug->enter_sub();
913
914   my $self = $_[0];
915   local *OUT = $_[1];
916   my $form = $self->{"form"};
917
918   close(OUT);
919
920   my $file_name;
921   if ($form->{"IN"} =~ m|^/|) {
922     $file_name = $form->{"IN"};
923   } else {
924     $file_name = $form->{"templates"} . "/" . $form->{"IN"};
925   }
926
927   my $zip = Archive::Zip->new();
928   if (Archive::Zip::AZ_OK != $zip->read($file_name)) {
929     $self->{"error"} = "File not found/is not a OpenDocument file.";
930     $main::lxdebug->leave_sub();
931     return 0;
932   }
933
934   my $contents = $zip->contents("content.xml");
935   if (!$contents) {
936     $self->{"error"} = "File is not a OpenDocument file.";
937     $main::lxdebug->leave_sub();
938     return 0;
939   }
940
941   my $rnd = $self->{"rnd"};
942   my $new_styles = qq|<style:style style:name="TLXO${rnd}BOLD" style:family="text">
943 <style:text-properties fo:font-weight="bold" style:font-weight-asian="bold" style:font-weight-complex="bold"/>
944 </style:style>
945 <style:style style:name="TLXO${rnd}ITALIC" style:family="text">
946 <style:text-properties fo:font-style="italic" style:font-style-asian="italic" style:font-style-complex="italic"/>
947 </style:style>
948 <style:style style:name="TLXO${rnd}UNDERLINE" style:family="text">
949 <style:text-properties style:text-underline-style="solid" style:text-underline-width="auto" style:text-underline-color="font-color"/>
950 </style:style>
951 <style:style style:name="TLXO${rnd}STRIKETHROUGH" style:family="text">
952 <style:text-properties style:text-line-through-style="solid"/>
953 </style:style>
954 <style:style style:name="TLXO${rnd}SUPER" style:family="text">
955 <style:text-properties style:text-position="super 58%"/>
956 </style:style>
957 <style:style style:name="TLXO${rnd}SUB" style:family="text">
958 <style:text-properties style:text-position="sub 58%"/>
959 </style:style>
960 |;
961
962   $contents =~ s|</office:automatic-styles>|${new_styles}</office:automatic-styles>|;
963   $contents =~ s|[\n\r]||gm;
964
965   my $new_contents = $self->parse_block($contents);
966   if (!defined($new_contents)) {
967     $main::lxdebug->leave_sub();
968     return 0;
969   }
970
971 #   $new_contents =~ s|>|>\n|g;
972
973   $zip->contents("content.xml", $new_contents);
974
975   my $styles = $zip->contents("styles.xml");
976   if ($contents) {
977     my $new_styles = $self->parse_block($styles);
978     if (!defined($new_contents)) {
979       $main::lxdebug->leave_sub();
980       return 0;
981     }
982     $zip->contents("styles.xml", $new_styles);
983   }
984
985   $zip->writeToFileNamed($form->{"tmpfile"}, 1);
986
987   my $res = 1;
988   if ($form->{"format"} =~ /pdf/) {
989     $res = $self->convert_to_pdf();
990   }
991
992   $main::lxdebug->leave_sub();
993   return $res;
994 }
995
996 sub is_xvfb_running {
997   $main::lxdebug->enter_sub();
998
999   my ($self) = @_;
1000
1001   local *IN;
1002   my $dfname = $self->{"userspath"} . "/xvfb_display";
1003   my $display;
1004
1005   $main::lxdebug->message(LXDebug::DEBUG2, "    Looking for $dfname\n");
1006   if ((-f $dfname) && open(IN, $dfname)) {
1007     my $pid = <IN>;
1008     chomp($pid);
1009     $display = <IN>;
1010     chomp($display);
1011     my $xauthority = <IN>;
1012     chomp($xauthority);
1013     close(IN);
1014
1015     $main::lxdebug->message(LXDebug::DEBUG2, "      found with $pid and $display\n");
1016
1017     if ((! -d "/proc/$pid") || !open(IN, "/proc/$pid/cmdline")) {
1018       $main::lxdebug->message(LXDebug::DEBUG2, "  no/wrong process #1\n");
1019       unlink($dfname, $xauthority);
1020       $main::lxdebug->leave_sub();
1021       return undef;
1022     }
1023     my $line = <IN>;
1024     close(IN);
1025     if ($line !~ /xvfb/i) {
1026       $main::lxdebug->message(LXDebug::DEBUG2, "      no/wrong process #2\n");
1027       unlink($dfname, $xauthority);
1028       $main::lxdebug->leave_sub();
1029       return undef;
1030     }
1031
1032     $ENV{"XAUTHORITY"} = $xauthority;
1033     $ENV{"DISPLAY"} = $display;
1034   } else {
1035     $main::lxdebug->message(LXDebug::DEBUG2, "      not found\n");
1036   }
1037
1038   $main::lxdebug->leave_sub();
1039
1040   return $display;
1041 }
1042
1043 sub spawn_xvfb {
1044   $main::lxdebug->enter_sub();
1045
1046   my ($self) = @_;
1047
1048   $main::lxdebug->message(LXDebug::DEBUG2, "spawn_xvfb()\n");
1049
1050   my $display = $self->is_xvfb_running();
1051
1052   if ($display) {
1053     $main::lxdebug->leave_sub();
1054     return $display;
1055   }
1056
1057   $display = 99;
1058   while ( -f "/tmp/.X${display}-lock") {
1059     $display++;
1060   }
1061   $display = ":${display}";
1062   $main::lxdebug->message(LXDebug::DEBUG2, "  display $display\n");
1063
1064   my $mcookie = `mcookie`;
1065   die("Installation error: mcookie not found.") if ($? != 0);
1066   chomp($mcookie);
1067
1068   $main::lxdebug->message(LXDebug::DEBUG2, "  mcookie $mcookie\n");
1069
1070   my $xauthority = "/tmp/.Xauthority-" . $$ . "-" . time() . "-" . int(rand(9999999));
1071   $ENV{"XAUTHORITY"} = $xauthority;
1072
1073   $main::lxdebug->message(LXDebug::DEBUG2, "  xauthority $xauthority\n");
1074
1075   system("xauth add \"${display}\" . \"${mcookie}\"");
1076   if ($? != 0) {
1077     $self->{"error"} = "Conversion to PDF failed because OpenOffice could not be started (xauth: $!)";
1078     $main::lxdebug->leave_sub();
1079     return undef;
1080   }
1081
1082   $main::lxdebug->message(LXDebug::DEBUG2, "  about to fork()\n");
1083
1084   my $pid = fork();
1085   if (0 == $pid) {
1086     $main::lxdebug->message(LXDebug::DEBUG2, "  Child execing\n");
1087     exec($main::xvfb_bin, $display, "-screen", "0", "640x480x8", "-nolisten", "tcp");
1088   }
1089   sleep(3);
1090   $main::lxdebug->message(LXDebug::DEBUG2, "  parent dont sleeping\n");
1091
1092   local *OUT;
1093   my $dfname = $self->{"userspath"} . "/xvfb_display";
1094   if (!open(OUT, ">$dfname")) {
1095     $self->{"error"} = "Conversion to PDF failed because OpenOffice could not be started ($dfname: $!)";
1096     unlink($xauthority);
1097     kill($pid);
1098     $main::lxdebug->leave_sub();
1099     return undef;
1100   }
1101   print(OUT "$pid\n$display\n$xauthority\n");
1102   close(OUT);
1103
1104   $main::lxdebug->message(LXDebug::DEBUG2, "  parent re-testing\n");
1105
1106   if (!$self->is_xvfb_running()) {
1107     $self->{"error"} = "Conversion to PDF failed because OpenOffice could not be started.";
1108     unlink($xauthority, $dfname);
1109     kill($pid);
1110     $main::lxdebug->leave_sub();
1111     return undef;
1112   }
1113
1114   $main::lxdebug->message(LXDebug::DEBUG2, "  spawn OK\n");
1115
1116   $main::lxdebug->leave_sub();
1117
1118   return $display;
1119 }
1120
1121 sub is_openoffice_running {
1122   $main::lxdebug->enter_sub();
1123
1124   system("./scripts/oo-uno-test-conn.py $main::openofficeorg_daemon_port " .
1125          "> /dev/null 2> /dev/null");
1126   my $res = $? == 0;
1127   $main::lxdebug->message(LXDebug::DEBUG2, "  is_openoffice_running(): $?\n");
1128
1129   $main::lxdebug->leave_sub();
1130
1131   return $res;
1132 }
1133
1134 sub spawn_openoffice {
1135   $main::lxdebug->enter_sub();
1136
1137   my ($self) = @_;
1138
1139   $main::lxdebug->message(LXDebug::DEBUG2, "spawn_openoffice()\n");
1140
1141   my ($try, $spawned_oo, $res);
1142
1143   $res = 0;
1144   for ($try = 0; $try < 15; $try++) {
1145     if ($self->is_openoffice_running()) {
1146       $res = 1;
1147       last;
1148     }
1149
1150     if (!$spawned_oo) {
1151       my $pid = fork();
1152       if (0 == $pid) {
1153         $main::lxdebug->message(LXDebug::DEBUG2, "  Child daemonizing\n");
1154         chdir('/');
1155         open(STDIN, '/dev/null');
1156         open(STDOUT, '>/dev/null');
1157         my $new_pid = fork();
1158         exit if ($new_pid);
1159         my $ssres = setsid();
1160         $main::lxdebug->message(LXDebug::DEBUG2, "  Child execing\n");
1161         my @cmdline = ($main::openofficeorg_writer_bin,
1162                        "-minimized", "-norestore", "-nologo", "-nolockcheck",
1163                        "-headless",
1164                        "-accept=socket,host=localhost,port=" .
1165                        $main::openofficeorg_daemon_port . ";urp;");
1166         exec(@cmdline);
1167       }
1168
1169       $main::lxdebug->message(LXDebug::DEBUG2, "  Parent after fork\n");
1170       $spawned_oo = 1;
1171       sleep(3);
1172     }
1173
1174     sleep($try >= 5 ? 2 : 1);
1175   }
1176
1177   if (!$res) {
1178     $self->{"error"} = "Conversion from OpenDocument to PDF failed because " .
1179       "OpenOffice could not be started.";
1180   }
1181
1182   $main::lxdebug->leave_sub();
1183
1184   return $res;
1185 }
1186
1187 sub convert_to_pdf {
1188   $main::lxdebug->enter_sub();
1189
1190   my ($self) = @_;
1191
1192   my $form = $self->{"form"};
1193
1194   my $filename = $form->{"tmpfile"};
1195   $filename =~ s/.odt$//;
1196   if (substr($filename, 0, 1) ne "/") {
1197     $filename = getcwd() . "/${filename}";
1198   }
1199
1200   if (substr($self->{"userspath"}, 0, 1) eq "/") {
1201     $ENV{'HOME'} = $self->{"userspath"};
1202   } else {
1203     $ENV{'HOME'} = getcwd() . "/" . $self->{"userspath"};
1204   }
1205
1206   if (!$self->spawn_xvfb()) {
1207     $main::lxdebug->leave_sub();
1208     return 0;
1209   }
1210
1211   my @cmdline;
1212   if (!$main::openofficeorg_daemon) {
1213     @cmdline = ($main::openofficeorg_writer_bin,
1214                 "-minimized", "-norestore", "-nologo", "-nolockcheck",
1215                 "-headless",
1216                 "file:${filename}.odt",
1217                 "macro://" . (split('/', $filename))[-1] .
1218                 "/Standard.Conversion.ConvertSelfToPDF()");
1219   } else {
1220     if (!$self->spawn_openoffice()) {
1221       $main::lxdebug->leave_sub();
1222       return 0;
1223     }
1224
1225     @cmdline = ("./scripts/oo-uno-convert-pdf.py",
1226                 $main::openofficeorg_daemon_port,
1227                 "${filename}.odt");
1228   }
1229
1230   system(@cmdline);
1231
1232   my $res = $?;
1233   if (0 == $?) {
1234     $form->{"tmpfile"} =~ s/odt$/pdf/;
1235
1236     unlink($filename . ".odt");
1237
1238     $main::lxdebug->leave_sub();
1239     return 1;
1240
1241   }
1242
1243   unlink($filename . ".odt", $filename . ".pdf");
1244   $self->{"error"} = "Conversion from OpenDocument to PDF failed. " .
1245     "Exit code: $res";
1246
1247   $main::lxdebug->leave_sub();
1248   return 0;
1249 }
1250
1251 sub format_string {
1252   my ($self, $variable) = @_;
1253   my $form = $self->{"form"};
1254   my $iconv = $self->{"iconv"};
1255
1256   my %replace =
1257     ('order' => ['&', '<', '>', '"', "'",
1258                  '\x80',        # Euro
1259                  quotemeta("\n"), quotemeta("\r")],
1260      '<'             => '&lt;',
1261      '>'             => '&gt;',
1262      '"'             => '&quot;',
1263      "'"             => '&apos;',
1264      '&'             => '&amp;',
1265      '\x80'          => chr(0xa4), # Euro
1266      quotemeta("\n") => '<text:line-break/>',
1267      quotemeta("\r") => '',
1268      );
1269
1270   map({ $variable =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
1271
1272   # Allow some HTML markup to be converted into the output format's
1273   # corresponding markup code, e.g. bold or italic.
1274   my $rnd = $self->{"rnd"};
1275   my %markup_replace = ("b" => "BOLD", "i" => "ITALIC", "s" => "STRIKETHROUGH",
1276                         "u" => "UNDERLINE", "sup" => "SUPER", "sub" => "SUB");
1277
1278   foreach my $key (keys(%markup_replace)) {
1279     my $value = $markup_replace{$key};
1280     $variable =~ s|\&lt;${key}\&gt;|<text:span text:style-name=\"TLXO${rnd}${value}\">|gi;
1281     $variable =~ s|\&lt;/${key}\&gt;|</text:span>|gi;
1282   }
1283
1284   return $iconv->convert($variable);
1285 }
1286
1287 sub get_mime_type() {
1288   if ($self->{"form"}->{"format"} =~ /pdf/) {
1289     return "application/pdf";
1290   } else {
1291     return "application/vnd.oasis.opendocument.text";
1292   }
1293 }
1294
1295 sub uses_temp_file {
1296   return 1;
1297 }
1298
1299
1300 ##########################################################
1301 ####
1302 #### XMLTemplate
1303 ####
1304 ##########################################################
1305
1306 package XMLTemplate; 
1307
1308 use vars qw(@ISA);
1309
1310 @ISA = qw(HTMLTemplate);
1311
1312 sub new {
1313   #evtl auskommentieren
1314   my $type = shift;
1315
1316   return $type->SUPER::new(@_);
1317 }
1318
1319 sub format_string {
1320   my ($self, $variable) = @_;
1321   my $form = $self->{"form"};
1322
1323   my %replace =
1324     ('order' => ['<', '>', quotemeta("\n")],
1325      '<'             => '&lt;',
1326      '>'             => '&gt;',
1327      quotemeta("\n") => '<br>',
1328      );
1329
1330   map({ $variable =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
1331
1332   # Allow no markup to be converted into the output format
1333   my @markup_replace = ('b', 'i', 's', 'u', 'sub', 'sup');
1334
1335   foreach my $key (@markup_replace) {
1336     $variable =~ s/\&lt;(\/?)${key}\&gt;//g;
1337   }
1338
1339   return $variable;
1340 }
1341
1342 sub get_mime_type() {
1343   my ($self) = @_;
1344
1345   if ($self->{"form"}->{"format"} =~ /elsterwinston/i) {
1346     return "application/xml ";
1347   } elsif ($self->{"form"}->{"format"} =~ /elstertaxbird/i) {
1348     return "application/x-taxbird";
1349   } else {
1350     return "text";
1351   }
1352 }
1353
1354 sub uses_temp_file {
1355   # tempfile needet for XML Output
1356   return 1;
1357 }
1358
1359 1;