]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/Text.pm
* Add the ability to have module import options
[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                          # This doesn't work yet; have to figure it out
159                          #'Debbugs::Config' => [qw(:globals :config)],
160                         );
161           while (my ($module,$param) = splice (@modules,0,2)) {
162                print STDERR "Eval $module\n" if $DEBUG;
163                my $code = '';
164                if (not defined $param) {
165                     $code = "use $module;";
166                }
167                else {
168                     $code = "use $module ".(join(',',map {"q($_)"} @{$param})).';';
169                }
170                $safe->reval($code);
171                print STDERR "Error while attempting to eval '$code': $@" if $@;
172           }
173           $safe->permit_only(':base_core',':base_io',':base_mem',':base_loop',
174                              qw(padsv padav padhv padany),
175                              qw(rv2gv refgen srefgen ref),
176                             );
177           $safe->share('$language','%tt_templates','$safe','$variables','%filled_templates');
178           $safe->share('*STDERR');
179           $safe->share('&_fill_in_template');
180           $safe->share('%config');
181           $safe->share('&include');
182           my $root = $safe->root();
183           # load variables into the safe
184           for my $key (keys %{$param{variables}||{}}) {
185                print STDERR "Loading $key\n" if $DEBUG;
186                if (ref($param{variables}{$key})) {
187                     no strict 'refs';
188                     print STDERR $safe->root().'::'.$key,qq(\n) if $DEBUG;
189                     *{"${root}::$key"} = $param{variables}{$key};
190                }
191                else {
192                     no strict 'refs';
193                     ${"${root}::$key"} = $param{variables}{$key};
194                }
195           }
196      }
197      #$safe->deny_only();
198      # perldoc Opcode; for details
199      $language = $param{language};
200      my $tt;
201      if ($tt_type eq 'FILE' and
202          defined $tt_templates{$tt_source} and
203          (stat $tt_source)[9] > $tt_templates{$tt_source}{mtime}
204         ) {
205           $tt = $tt_templates{$tt_source}{template};
206      }
207      else {
208           if ($tt_type eq 'FILE') {
209                $tt_templates{$tt_source}{mtime} =
210                     (stat $tt_source)[9];
211           }
212           $tt = Text::Template->new(TYPE => $tt_type,
213                                     SOURCE => $tt_source,
214                                    );
215           if ($tt_type eq 'FILE') {
216                $tt_templates{$tt_source}{template} = $tt;
217           }
218      }
219      if (not defined $tt) {
220           die "Unable to create Text::Template for $tt_type:$tt_source";
221      }
222      my $ret = $tt->fill_in(#(defined $param{nosafe} and $param{nosafe})?():(HASH=>$param{variables}),
223                             (defined $param{nosafe} and $param{nosafe})?():(SAFE=>$safe),
224                             #SAFE => $safe,
225                             (defined $param{nosafe} and $param{nosafe})?(PACKAGE => 'main'):(),
226                             defined $param{output}?(OUTPUT=>$param{output}):(),
227                            );
228      if (not defined $ret) {
229           print STDERR $Text::Template::ERROR;
230           return '';
231      }
232      if ($DEBUG) {
233           no strict 'refs';
234           no warnings 'uninitialized';
235           my $temp = $param{nosafe}?'main':$safe->{Root};
236           print STDERR "Variables for $param{template}\n";
237           print STDERR "Safe $temp\n";
238           print STDERR map {"$_:${$_}\n"} keys %{"${temp}::"};
239           print STDERR ${"${temp}::search_value"},qq(\n);
240      }
241
242      return $ret;
243 }
244
245 sub _locate_text{
246      my ($template,$language) = @_;
247      $template =~ s/\.tmpl$//g;
248      # if a language doesn't exist, use the en_US template
249      if (not -e $config{template_dir}.'/'.$language.'/'.$template.'.tmpl') {
250           $language = 'en_US';
251      }
252      my $loc = $config{template_dir}.'/'.$language.'/'.$template.'.tmpl';
253      if (not -e $loc) {
254           print STDERR "Unable to locate template $loc\n";
255           return undef;
256      }
257      return $loc;
258 }
259
260 1;