Weitere Sonderzeichen escapen.
[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 #### OpenDocumentTemplate
621 ####
622
623 package OpenDocumentTemplate;
624
625 use POSIX 'setsid';
626 use vars qw(@ISA);
627
628 use Cwd;
629 # use File::Copy;
630 # use File::Spec;
631 # use File::Temp qw(:mktemp);
632 use IO::File;
633
634 @ISA = qw(SimpleTemplate);
635
636 sub new {
637   my $type = shift;
638
639   $self = $type->SUPER::new(@_);
640
641   foreach my $module (qw(Archive::Zip Text::Iconv)) {
642     eval("use ${module};");
643     if ($@) {
644       $self->{"form"}->error("The Perl module '${module}' could not be " .
645                              "loaded. Support for OpenDocument templates " .
646                              "does not work without it. Please install your " .
647                              "distribution's package or get the module from " .
648                              "CPAN ( http://www.cpan.org ).");
649     }
650   }
651
652   $self->{"rnd"} = int(rand(1000000));
653   $self->{"iconv"} = Text::Iconv->new($main::dbcharset, "UTF-8");
654
655   return $self;
656 }
657
658 sub substitute_vars {
659   my ($self, $text, @indices) = @_;
660
661   my $form = $self->{"form"};
662
663   while ($text =~ /\&lt;\%(.*?)\%\&gt;/) {
664     my $value = $form->{$1};
665
666     for (my $i = 0; $i < scalar(@indices); $i++) {
667       last unless (ref($value) eq "ARRAY");
668       $value = $value->[$indices[$i]];
669     }
670     substr($text, $-[0], $+[0] - $-[0]) = $self->format_string($value);
671   }
672
673   return $text;
674 }
675
676 sub parse_foreach {
677   my ($self, $var, $text, $start_tag, $end_tag, @indices) = @_;
678
679   my ($form, $new_contents) = ($self->{"form"}, "");
680
681   my $ary = $form->{$var};
682   for (my $i = 0; $i < scalar(@indices); $i++) {
683     last unless (ref($ary) eq "ARRAY");
684     $ary = $ary->[$indices[$i]];
685   }
686
687   for (my $i = 0; $i < scalar(@{$ary}); $i++) {
688     $form->{"__first__"} = $i == 0;
689     $form->{"__last__"} = ($i + 1) == scalar(@{$ary});
690     $form->{"__odd__"} = (($i + 1) % 2) == 1;
691     $form->{"__counter__"} = $i + 1;
692     my $new_text = $self->parse_block($text, (@indices, $i));
693     return undef unless (defined($new_text));
694     $new_contents .= $start_tag . $new_text . $end_tag;
695   }
696   map({ delete($form->{"__${_}__"}); } qw(first last odd counter));
697
698   return $new_contents;
699 }
700
701 sub find_end {
702   my ($self, $text, $pos, $var, $not) = @_;
703
704   my $depth = 1;
705   $pos = 0 unless ($pos);
706
707   while ($pos < length($text)) {
708     $pos++;
709
710     next if (substr($text, $pos - 1, 5) ne '&lt;%');
711
712     if ((substr($text, $pos + 4, 2) eq 'if') || (substr($text, $pos + 4, 3) eq 'for')) {
713       $depth++;
714
715     } elsif ((substr($text, $pos + 4, 4) eq 'else') && (1 == $depth)) {
716       if (!$var) {
717         $self->{"error"} = '<%else%> outside of <%if%> / <%ifnot%>.';
718         return undef;
719       }
720
721       my $block = substr($text, 0, $pos - 1);
722       substr($text, 0, $pos - 1) = "";
723       $text =~ s!^\&lt;\%[^\%]+\%\&gt;!!;
724       $text = '&lt;%if' . ($not ?  " " : "not ") . $var . '%&gt;' . $text;
725
726       return ($block, $text);
727
728     } elsif (substr($text, $pos + 4, 3) eq 'end') {
729       $depth--;
730       if ($depth == 0) {
731         my $block = substr($text, 0, $pos - 1);
732         substr($text, 0, $pos - 1) = "";
733         $text =~ s!^\&lt;\%[^\%]+\%\&gt;!!;
734
735         return ($block, $text);
736       }
737     }
738   }
739
740   return undef;
741 }
742
743 sub parse_block {
744   $main::lxdebug->enter_sub();
745
746   my ($self, $contents, @indices) = @_;
747
748   my $new_contents = "";
749
750   while ($contents ne "") {
751     if (substr($contents, 0, 1) eq "<") {
752       $contents =~ m|^<[^>]+>|;
753       my $tag = $&;
754       substr($contents, 0, length($&)) = "";
755
756       if ($tag =~ m|<table:table-row|) {
757         $contents =~ m|^(.*?)(</table:table-row[^>]*>)|;
758         my $table_row = $1;
759         my $end_tag = $2;
760         substr($contents, 0, length($1) + length($end_tag)) = "";
761
762         if ($table_row =~ m|\&lt;\%foreachrow\s+(.*?)\%\&gt;|) {
763           my $var = $1;
764
765           substr($table_row, length($`), length($&)) = "";
766
767           my ($t1, $t2) = $self->find_end($table_row, length($`));
768           if (!$t1) {
769             $self->{"error"} = "Unclosed <\%foreachrow\%>." unless ($self->{"error"});
770             $main::lxdebug->leave_sub();
771             return undef;
772           }
773
774           my $new_text = $self->parse_foreach($var, $t1 . $t2, $tag, $end_tag, @indices);
775           if (!defined($new_text)) {
776             $main::lxdebug->leave_sub();
777             return undef;
778           }
779           $new_contents .= $new_text;
780
781         } else {
782           my $new_text = $self->parse_block($table_row, @indices);
783           if (!defined($new_text)) {
784             $main::lxdebug->leave_sub();
785             return undef;
786           }
787           $new_contents .= $tag . $new_text . $end_tag;
788         }
789
790       } else {
791         $new_contents .= $tag;
792       }
793
794     } else {
795       $contents =~ /^[^<]+/;
796       my $text = $&;
797
798       my $pos_if = index($text, '&lt;%if');
799       my $pos_foreach = index($text, '&lt;%foreach');
800
801       if ((-1 == $pos_if) && (-1 == $pos_foreach)) {
802         substr($contents, 0, length($text)) = "";
803         $new_contents .= $self->substitute_vars($text, @indices);
804         next;
805       }
806
807       if ((-1 == $pos_if) || ((-1 != $pos_foreach) && ($pos_if > $pos_foreach))) {
808         $new_contents .= $self->substitute_vars(substr($contents, 0, $pos_foreach), @indices);
809         substr($contents, 0, $pos_foreach) = "";
810
811         if ($contents !~ m|^\&lt;\%foreach (.*?)\%\&gt;|) {
812           $self->{"error"} = "Malformed <\%foreach\%>.";
813           $main::lxdebug->leave_sub();
814           return undef;
815         }
816
817         my $var = $1;
818
819         substr($contents, 0, length($&)) = "";
820
821         my $block;
822         ($block, $contents) = $self->find_end($contents);
823         if (!$block) {
824           $self->{"error"} = "Unclosed <\%foreach\%>." unless ($self->{"error"});
825           $main::lxdebug->leave_sub();
826           return undef;
827         }
828
829         my $new_text = $self->parse_foreach($var, $block, "", "", @indices);
830         if (!defined($new_text)) {
831           $main::lxdebug->leave_sub();
832           return undef;
833         }
834         $new_contents .= $new_text;
835
836       } else {
837         $new_contents .= $self->substitute_vars(substr($contents, 0, $pos_if), @indices);
838         substr($contents, 0, $pos_if) = "";
839
840         if ($contents !~ m|^\&lt;\%if\s*(not)?\s+(.*?)\%\&gt;|) {
841           $self->{"error"} = "Malformed <\%if\%>.";
842           $main::lxdebug->leave_sub();
843           return undef;
844         }
845
846         my ($not, $var) = ($1, $2);
847
848         substr($contents, 0, length($&)) = "";
849
850         ($block, $contents) = $self->find_end($contents, 0, $var, $not);
851         if (!$block) {
852           $self->{"error"} = "Unclosed <\%if${not}\%>." unless ($self->{"error"});
853           $main::lxdebug->leave_sub();
854           return undef;
855         }
856
857         my $value = $self->{"form"}->{$var};
858         for (my $i = 0; $i < scalar(@indices); $i++) {
859           last unless (ref($value) eq "ARRAY");
860           $value = $value->[$indices[$i]];
861         }
862
863         if (($not && !$value) || (!$not && $value)) {
864           my $new_text = $self->parse_block($block, @indices);
865           if (!defined($new_text)) {
866             $main::lxdebug->leave_sub();
867             return undef;
868           }
869           $new_contents .= $new_text;
870         }
871       }
872     }
873   }
874
875   $main::lxdebug->leave_sub();
876
877   return $new_contents;
878 }
879
880 sub parse {
881   $main::lxdebug->enter_sub();
882
883   my $self = $_[0];
884   local *OUT = $_[1];
885   my $form = $self->{"form"};
886
887   close(OUT);
888
889   my $file_name;
890   if ($form->{"IN"} =~ m|^/|) {
891     $file_name = $form->{"IN"};
892   } else {
893     $file_name = $form->{"templates"} . "/" . $form->{"IN"};
894   }
895
896   my $zip = Archive::Zip->new();
897   if (Archive::Zip::AZ_OK != $zip->read($file_name)) {
898     $self->{"error"} = "File not found/is not a OpenDocument file.";
899     $main::lxdebug->leave_sub();
900     return 0;
901   }
902
903   my $contents = $zip->contents("content.xml");
904   if (!$contents) {
905     $self->{"error"} = "File is not a OpenDocument file.";
906     $main::lxdebug->leave_sub();
907     return 0;
908   }
909
910   my $rnd = $self->{"rnd"};
911   my $new_styles = qq|<style:style style:name="TLXO${rnd}BOLD" style:family="text">
912 <style:text-properties fo:font-weight="bold" style:font-weight-asian="bold" style:font-weight-complex="bold"/>
913 </style:style>
914 <style:style style:name="TLXO${rnd}ITALIC" style:family="text">
915 <style:text-properties fo:font-style="italic" style:font-style-asian="italic" style:font-style-complex="italic"/>
916 </style:style>
917 <style:style style:name="TLXO${rnd}UNDERLINE" style:family="text">
918 <style:text-properties style:text-underline-style="solid" style:text-underline-width="auto" style:text-underline-color="font-color"/>
919 </style:style>
920 <style:style style:name="TLXO${rnd}STRIKETHROUGH" style:family="text">
921 <style:text-properties style:text-line-through-style="solid"/>
922 </style:style>
923 <style:style style:name="TLXO${rnd}SUPER" style:family="text">
924 <style:text-properties style:text-position="super 58%"/>
925 </style:style>
926 <style:style style:name="TLXO${rnd}SUB" style:family="text">
927 <style:text-properties style:text-position="sub 58%"/>
928 </style:style>
929 |;
930
931   $contents =~ s|</office:automatic-styles>|${new_styles}</office:automatic-styles>|;
932   $contents =~ s|[\n\r]||gm;
933
934   my $new_contents = $self->parse_block($contents);
935   if (!defined($new_contents)) {
936     $main::lxdebug->leave_sub();
937     return 0;
938   }
939
940 #   $new_contents =~ s|>|>\n|g;
941
942   $zip->contents("content.xml", $new_contents);
943
944   my $styles = $zip->contents("styles.xml");
945   if ($contents) {
946     my $new_styles = $self->parse_block($styles);
947     if (!defined($new_contents)) {
948       $main::lxdebug->leave_sub();
949       return 0;
950     }
951     $zip->contents("styles.xml", $new_styles);
952   }
953
954   $zip->writeToFileNamed($form->{"tmpfile"}, 1);
955
956   my $res = 1;
957   if ($form->{"format"} =~ /pdf/) {
958     $res = $self->convert_to_pdf();
959   }
960
961   $main::lxdebug->leave_sub();
962   return $res;
963 }
964
965 sub is_xvfb_running {
966   $main::lxdebug->enter_sub();
967
968   my ($self) = @_;
969
970   local *IN;
971   my $dfname = $self->{"userspath"} . "/xvfb_display";
972   my $display;
973
974   $main::lxdebug->message(LXDebug::DEBUG2, "    Looking for $dfname\n");
975   if ((-f $dfname) && open(IN, $dfname)) {
976     my $pid = <IN>;
977     chomp($pid);
978     $display = <IN>;
979     chomp($display);
980     my $xauthority = <IN>;
981     chomp($xauthority);
982     close(IN);
983
984     $main::lxdebug->message(LXDebug::DEBUG2, "      found with $pid and $display\n");
985
986     if ((! -d "/proc/$pid") || !open(IN, "/proc/$pid/cmdline")) {
987       $main::lxdebug->message(LXDebug::DEBUG2, "  no/wrong process #1\n");
988       unlink($dfname, $xauthority);
989       $main::lxdebug->leave_sub();
990       return undef;
991     }
992     my $line = <IN>;
993     close(IN);
994     if ($line !~ /xvfb/i) {
995       $main::lxdebug->message(LXDebug::DEBUG2, "      no/wrong process #2\n");
996       unlink($dfname, $xauthority);
997       $main::lxdebug->leave_sub();
998       return undef;
999     }
1000
1001     $ENV{"XAUTHORITY"} = $xauthority;
1002     $ENV{"DISPLAY"} = $display;
1003   } else {
1004     $main::lxdebug->message(LXDebug::DEBUG2, "      not found\n");
1005   }
1006
1007   $main::lxdebug->leave_sub();
1008
1009   return $display;
1010 }
1011
1012 sub spawn_xvfb {
1013   $main::lxdebug->enter_sub();
1014
1015   my ($self) = @_;
1016
1017   $main::lxdebug->message(LXDebug::DEBUG2, "spawn_xvfb()\n");
1018
1019   my $display = $self->is_xvfb_running();
1020
1021   if ($display) {
1022     $main::lxdebug->leave_sub();
1023     return $display;
1024   }
1025
1026   $display = 99;
1027   while ( -f "/tmp/.X${display}-lock") {
1028     $display++;
1029   }
1030   $display = ":${display}";
1031   $main::lxdebug->message(LXDebug::DEBUG2, "  display $display\n");
1032
1033   my $mcookie = `mcookie`;
1034   die("Installation error: mcookie not found.") if ($? != 0);
1035   chomp($mcookie);
1036
1037   $main::lxdebug->message(LXDebug::DEBUG2, "  mcookie $mcookie\n");
1038
1039   my $xauthority = "/tmp/.Xauthority-" . $$ . "-" . time() . "-" . int(rand(9999999));
1040   $ENV{"XAUTHORITY"} = $xauthority;
1041
1042   $main::lxdebug->message(LXDebug::DEBUG2, "  xauthority $xauthority\n");
1043
1044   system("xauth add \"${display}\" . \"${mcookie}\"");
1045   if ($? != 0) {
1046     $self->{"error"} = "Conversion to PDF failed because OpenOffice could not be started (xauth: $!)";
1047     $main::lxdebug->leave_sub();
1048     return undef;
1049   }
1050
1051   $main::lxdebug->message(LXDebug::DEBUG2, "  about to fork()\n");
1052
1053   my $pid = fork();
1054   if (0 == $pid) {
1055     $main::lxdebug->message(LXDebug::DEBUG2, "  Child execing\n");
1056     exec($main::xvfb_bin, $display, "-screen", "0", "640x480x8", "-nolisten", "tcp");
1057   }
1058   sleep(3);
1059   $main::lxdebug->message(LXDebug::DEBUG2, "  parent dont sleeping\n");
1060
1061   local *OUT;
1062   my $dfname = $self->{"userspath"} . "/xvfb_display";
1063   if (!open(OUT, ">$dfname")) {
1064     $self->{"error"} = "Conversion to PDF failed because OpenOffice could not be started ($dfname: $!)";
1065     unlink($xauthority);
1066     kill($pid);
1067     $main::lxdebug->leave_sub();
1068     return undef;
1069   }
1070   print(OUT "$pid\n$display\n$xauthority\n");
1071   close(OUT);
1072
1073   $main::lxdebug->message(LXDebug::DEBUG2, "  parent re-testing\n");
1074
1075   if (!$self->is_xvfb_running()) {
1076     $self->{"error"} = "Conversion to PDF failed because OpenOffice could not be started.";
1077     unlink($xauthority, $dfname);
1078     kill($pid);
1079     $main::lxdebug->leave_sub();
1080     return undef;
1081   }
1082
1083   $main::lxdebug->message(LXDebug::DEBUG2, "  spawn OK\n");
1084
1085   $main::lxdebug->leave_sub();
1086
1087   return $display;
1088 }
1089
1090 sub is_openoffice_running {
1091   $main::lxdebug->enter_sub();
1092
1093   system("./scripts/oo-uno-test-conn.py $main::openofficeorg_daemon_port " .
1094          "> /dev/null 2> /dev/null");
1095   my $res = $? == 0;
1096   $main::lxdebug->message(LXDebug::DEBUG2, "  is_openoffice_running(): $?\n");
1097
1098   $main::lxdebug->leave_sub();
1099
1100   return $res;
1101 }
1102
1103 sub spawn_openoffice {
1104   $main::lxdebug->enter_sub();
1105
1106   my ($self) = @_;
1107
1108   $main::lxdebug->message(LXDebug::DEBUG2, "spawn_openoffice()\n");
1109
1110   my ($try, $spawned_oo, $res);
1111
1112   $res = 0;
1113   for ($try = 0; $try < 15; $try++) {
1114     if ($self->is_openoffice_running()) {
1115       $res = 1;
1116       last;
1117     }
1118
1119     if (!$spawned_oo) {
1120       my $pid = fork();
1121       if (0 == $pid) {
1122         $main::lxdebug->message(LXDebug::DEBUG2, "  Child daemonizing\n");
1123         chdir('/');
1124         open(STDIN, '/dev/null');
1125         open(STDOUT, '>/dev/null');
1126         my $new_pid = fork();
1127         exit if ($new_pid);
1128         my $ssres = setsid();
1129         $main::lxdebug->message(LXDebug::DEBUG2, "  Child execing\n");
1130         my @cmdline = ($main::openofficeorg_writer_bin,
1131                        "-minimized", "-norestore", "-nologo", "-nolockcheck",
1132                        "-headless",
1133                        "-accept=socket,host=localhost,port=" .
1134                        $main::openofficeorg_daemon_port . ";urp;");
1135         exec(@cmdline);
1136       }
1137
1138       $main::lxdebug->message(LXDebug::DEBUG2, "  Parent after fork\n");
1139       $spawned_oo = 1;
1140       sleep(3);
1141     }
1142
1143     sleep($try >= 5 ? 2 : 1);
1144   }
1145
1146   if (!$res) {
1147     $self->{"error"} = "Conversion from OpenDocument to PDF failed because " .
1148       "OpenOffice could not be started.";
1149   }
1150
1151   $main::lxdebug->leave_sub();
1152
1153   return $res;
1154 }
1155
1156 sub convert_to_pdf {
1157   $main::lxdebug->enter_sub();
1158
1159   my ($self) = @_;
1160
1161   my $form = $self->{"form"};
1162
1163   my $filename = $form->{"tmpfile"};
1164   $filename =~ s/.odt$//;
1165   if (substr($filename, 0, 1) ne "/") {
1166     $filename = getcwd() . "/${filename}";
1167   }
1168
1169   if (substr($self->{"userspath"}, 0, 1) eq "/") {
1170     $ENV{'HOME'} = $self->{"userspath"};
1171   } else {
1172     $ENV{'HOME'} = getcwd() . "/" . $self->{"userspath"};
1173   }
1174
1175   if (!$self->spawn_xvfb()) {
1176     $main::lxdebug->leave_sub();
1177     return 0;
1178   }
1179
1180   my @cmdline;
1181   if (!$main::openofficeorg_daemon) {
1182     @cmdline = ($main::openofficeorg_writer_bin,
1183                 "-minimized", "-norestore", "-nologo", "-nolockcheck",
1184                 "-headless",
1185                 "file:${filename}.odt",
1186                 "macro://" . (split('/', $filename))[-1] .
1187                 "/Standard.Conversion.ConvertSelfToPDF()");
1188   } else {
1189     if (!$self->spawn_openoffice()) {
1190       $main::lxdebug->leave_sub();
1191       return 0;
1192     }
1193
1194     @cmdline = ("./scripts/oo-uno-convert-pdf.py",
1195                 $main::openofficeorg_daemon_port,
1196                 "${filename}.odt");
1197   }
1198
1199   system(@cmdline);
1200
1201   my $res = $?;
1202   if (0 == $?) {
1203     $form->{"tmpfile"} =~ s/odt$/pdf/;
1204
1205     unlink($filename . ".odt");
1206
1207     $main::lxdebug->leave_sub();
1208     return 1;
1209
1210   }
1211
1212   unlink($filename . ".odt", $filename . ".pdf");
1213   $self->{"error"} = "Conversion from OpenDocument to PDF failed. " .
1214     "Exit code: $res";
1215
1216   $main::lxdebug->leave_sub();
1217   return 0;
1218 }
1219
1220 sub format_string {
1221   my ($self, $variable) = @_;
1222   my $form = $self->{"form"};
1223   my $iconv = $self->{"iconv"};
1224
1225   my %replace =
1226     ('order' => ['&', '<', '>', '"', "'",
1227                  '\x80',        # Euro
1228                  quotemeta("\n"), quotemeta("\r")],
1229      '<'             => '&lt;',
1230      '>'             => '&gt;',
1231      '"'             => '&quot;',
1232      "'"             => '&apos;',
1233      '&'             => '&amp;',
1234      '\x80'          => chr(0xa4), # Euro
1235      quotemeta("\n") => '<text:line-break/>',
1236      quotemeta("\r") => '',
1237      );
1238
1239   map({ $variable =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
1240
1241   # Allow some HTML markup to be converted into the output format's
1242   # corresponding markup code, e.g. bold or italic.
1243   my $rnd = $self->{"rnd"};
1244   my %markup_replace = ("b" => "BOLD", "i" => "ITALIC", "s" => "STRIKETHROUGH",
1245                         "u" => "UNDERLINE", "sup" => "SUPER", "sub" => "SUB");
1246
1247   foreach my $key (keys(%markup_replace)) {
1248     my $value = $markup_replace{$key};
1249     $variable =~ s|\&lt;${key}\&gt;|<text:span text:style-name=\"TLXO${rnd}${value}\">|gi;
1250     $variable =~ s|\&lt;/${key}\&gt;|</text:span>|gi;
1251   }
1252
1253   return $iconv->convert($variable);
1254 }
1255
1256 sub get_mime_type() {
1257   if ($self->{"form"}->{"format"} =~ /pdf/) {
1258     return "application/pdf";
1259   } else {
1260     return "application/vnd.oasis.opendocument.text";
1261   }
1262 }
1263
1264 sub uses_temp_file {
1265   return 1;
1266 }
1267
1268
1269 ##########################################################
1270 ####
1271 #### XMLTemplate
1272 ####
1273 ##########################################################
1274
1275 package XMLTemplate; 
1276
1277 use vars qw(@ISA);
1278
1279 @ISA = qw(HTMLTemplate);
1280
1281 sub new {
1282   #evtl auskommentieren
1283   my $type = shift;
1284
1285   return $type->SUPER::new(@_);
1286 }
1287
1288 sub format_string {
1289   my ($self, $variable) = @_;
1290   my $form = $self->{"form"};
1291
1292   my %replace =
1293     ('order' => ['<', '>', quotemeta("\n")],
1294      '<'             => '&lt;',
1295      '>'             => '&gt;',
1296      quotemeta("\n") => '<br>',
1297      );
1298
1299   map({ $variable =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
1300
1301   # Allow no markup to be converted into the output format
1302   my @markup_replace = ('b', 'i', 's', 'u', 'sub', 'sup');
1303
1304   foreach my $key (@markup_replace) {
1305     $variable =~ s/\&lt;(\/?)${key}\&gt;//g;
1306   }
1307
1308   return $variable;
1309 }
1310
1311 sub get_mime_type() {
1312   my ($self) = @_;
1313
1314   if ($self->{"form"}->{"format"} =~ /elsterwinston/i) {
1315     return "application/xml ";
1316   } elsif ($self->{"form"}->{"format"} =~ /elstertaxbird/i) {
1317     return "application/x-taxbird";
1318   } else {
1319     return "text";
1320   }
1321 }
1322
1323 sub uses_temp_file {
1324   # tempfile needet for XML Output
1325   return 1;
1326 }
1327
1328 1;