]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/Text.pm
* Add template system
[debbugs.git] / Debbugs / Text.pm
1 # This module is part of debbugs, and is released
2 # under the terms of the GPL version 2, or any later
3 # version at your option.
4 # See the file README and COPYING for more information.
5 #
6 # Copyright 2007 by Don Armstrong <don@donarmstrong.com>.
7
8 package Debbugs::Text;
9
10 use warnings;
11 use strict;
12
13 =head1 NAME
14
15 Debbugs::Text -- General routines for text templates
16
17 =head1 SYNOPSIS
18
19 use Debbugs::Text qw(:templates);
20 print fill_in_template(template => 'cgi/foo');
21
22 =head1 DESCRIPTION
23
24 This module is a replacement for parts of common.pl; subroutines in
25 common.pl will be gradually phased out and replaced with equivalent
26 (or better) functionality here.
27
28 =head1 BUGS
29
30 None known.
31
32 =cut
33
34
35 use vars qw($DEBUG $VERSION @EXPORT_OK %EXPORT_TAGS @EXPORT @ISA);
36 use base qw(Exporter);
37
38 BEGIN {
39      $VERSION = 1.00;
40      $DEBUG = 0 unless defined $DEBUG;
41
42      @EXPORT = ();
43      %EXPORT_TAGS = (templates => [qw(fill_in_template)],
44                     );
45      @EXPORT_OK = ();
46      Exporter::export_ok_tags(qw(templates));
47      $EXPORT_TAGS{all} = [@EXPORT_OK];
48 }
49
50 use Safe;
51 use Text::Template;
52
53 use Storable qw(dclone);
54
55 use Debbugs::Config qw(:config);
56
57 use Params::Validate qw(:types validate_with);
58 use Carp;
59 use IO::File;
60 use Data::Dumper;
61
62 =head2 fill_in_template
63
64      print fill_in_template(template => 'template_name',
65                             variables => \%variables,
66                             language  => '..'
67                            );
68
69 Reads a template from disk (if it hasn't already been read in) and
70 fills the template in.
71
72 =cut
73
74 our %tt_templates;
75 our %filled_templates;
76 our $safe;
77 our $language;
78 sub fill_in_template{
79      my %param = validate_with(params => \@_,
80                                spec   => {template => SCALAR|HANDLE|SCALARREF,
81                                           variables => {type => HASHREF,
82                                                         default => {},
83                                                        },
84                                           language  => {type => SCALAR,
85                                                         default => 'en_US',
86                                                        },
87                                           output    => {type => HANDLE,
88                                                         optional => 1,
89                                                        },
90                                           safe      => {type => OBJECT,
91                                                         optional => 1,
92                                                        },
93                                          },
94                               );
95      return _fill_in_template(@param{qw(template variables language safe output)});
96 }
97
98
99 sub include {
100      my $template = shift;
101      $filled_templates{$template}++;
102      print STDERR "include template $template language $language safe $safe\n" if $DEBUG;
103      # Die if we're in a template loop
104      die "Template loop with $template" if $filled_templates{$template} > 10;
105      my $filled_tmpl;
106      eval {
107           $filled_tmpl = Debbugs::Text::_fill_in_template($template,
108                                                           {},
109                                                           $language,
110                                                           $safe,
111                                                           undef,
112                                                           1
113                                                          );
114      };
115      if ($@) {
116           print STDERR "failed to fill template $template: $@";
117      }
118      print STDERR "failed to fill template $template\n" if $filled_tmpl eq '' and $DEBUG;
119      print STDERR "template $template '$filled_tmpl'\n" if $DEBUG;
120      $filled_templates{$template}--;
121      return $filled_tmpl;
122 };
123
124 sub _fill_in_template{
125      my %param;
126      @param{qw(template variables language safe output nosafe)} = @_;
127      print STDERR "_fill template $param{template} language $param{language} safe $param{safe}\n"
128           if $DEBUG;
129
130      # Get the text
131      my $tt_type = '';
132      my $tt_source;
133      if (ref($param{template}) eq 'GLOB' or
134          ref(\$param{template}) eq 'GLOB') {
135           $tt_type = 'FILE_HANDLE';
136           $tt_source = $param{template};
137      }
138      elsif (ref($param{template}) eq 'SCALAR') {
139           $tt_type = 'STRING';
140           $tt_source = ${$param{template}};
141      }
142      else {
143           $tt_type = 'FILE';
144           $tt_source = _locate_text($param{template},$param{language});
145      }
146      if (not defined $tt_source) {
147           die "Unable to find template $param{template} with language $param{language}";
148      }
149
150      if (defined $param{safe}) {
151           $safe = $param{safe};
152      }
153      else {
154           print STDERR "Created new safe\n" if $DEBUG;
155           $safe = Safe->new() or die "Unable to create safe compartment";
156           $safe->deny_only();
157           my @modules = ('Text::Template' => undef,
158                         );
159           while (my ($module,$param) = splice (@modules,0,2)) {
160                print STDERR "Eval $module\n" if $DEBUG;
161                $safe->reval("use $module;");
162                print STDERR "Error while attempting to 'use $module;' $@" if $@;
163           }
164           $safe->permit_only(':base_core',':base_io',':base_mem',':base_loop',
165                              qw(padsv padav padhv padany),
166                              qw(rv2gv refgen srefgen ref),
167                             );
168           $safe->share('$language','%tt_templates','$safe','$variables','%filled_templates');
169           $safe->share('*STDERR');
170           $safe->share('&_fill_in_template');
171           $safe->share('%config');
172           $safe->share('&include');
173           my $root = $safe->root();
174           # load variables into the safe
175           for my $key (keys %{$param{variables}||{}}) {
176                print STDERR "Loading $key\n" if $DEBUG;
177                if (ref($param{variables}{$key})) {
178                     no strict 'refs';
179                     print STDERR $safe->root().'::'.$key,qq(\n) if $DEBUG;
180                     *{"${root}::$key"} = $param{variables}{$key};
181                }
182                else {
183                     no strict 'refs';
184                     ${"${root}::$key"} = $param{variables}{$key};
185                }
186           }
187      }
188      #$safe->deny_only();
189      # perldoc Opcode; for details
190      $language = $param{language};
191      my $tt;
192      if ($tt_type eq 'FILE' and
193          defined $tt_templates{$tt_source} and
194          (stat $tt_source)[9] > $tt_templates{$tt_source}{mtime}
195         ) {
196           $tt = $tt_templates{$tt_source}{template};
197      }
198      else {
199           if ($tt_type eq 'FILE') {
200                $tt_templates{$tt_source}{mtime} =
201                     (stat $tt_source)[9];
202           }
203           $tt = Text::Template->new(TYPE => $tt_type,
204                                     SOURCE => $tt_source,
205                                    );
206           if ($tt_type eq 'FILE') {
207                $tt_templates{$tt_source}{template} = $tt;
208           }
209      }
210      if (not defined $tt) {
211           die "Unable to create Text::Template for $tt_type:$tt_source";
212      }
213      my $ret = $tt->fill_in(#(defined $param{nosafe} and $param{nosafe})?():(HASH=>$param{variables}),
214                             (defined $param{nosafe} and $param{nosafe})?():(SAFE=>$safe),
215                             #SAFE => $safe,
216                             (defined $param{nosafe} and $param{nosafe})?(PACKAGE => 'main'):(),
217                             defined $param{output}?(OUTPUT=>$param{output}):(),
218                            );
219      if (not defined $ret) {
220           print STDERR $Text::Template::ERROR;
221           return '';
222      }
223      if ($DEBUG) {
224           no strict 'refs';
225           no warnings 'uninitialized';
226           my $temp = $param{nosafe}?'main':$safe->{Root};
227           print STDERR "Variables for $param{template}\n";
228           print STDERR "Safe $temp\n";
229           print STDERR map {"$_:${$_}\n"} keys %{"${temp}::"};
230           print STDERR ${"${temp}::search_value"},qq(\n);
231      }
232
233      return $ret;
234 }
235
236 sub _locate_text{
237      my ($template,$language) = @_;
238      $template =~ s/\.tmpl$//g;
239      # if a language doesn't exist, use the en_US template
240      if (not -e $config{template_dir}.'/'.$language.'/'.$template.'.tmpl') {
241           $language = 'en_US';
242      }
243      my $loc = $config{template_dir}.'/'.$language.'/'.$template.'.tmpl';
244      if (not -e $loc) {
245           print STDERR "Unable to locate tmeplate $loc";
246           return undef;
247      }
248      return $loc;
249 }
250
251 1;