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