]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/Text.pm
Drop more unused variables
[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 Exporter qw(import);
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      push @ISA,qw(Safe::Hole::User);
49 }
50
51 use Safe;
52 use Safe::Hole;
53 use Text::Template;
54
55 use Storable qw(dclone);
56
57 use Debbugs::Config qw(:config);
58
59 use Params::Validate qw(:types validate_with);
60 use Carp;
61 use IO::File;
62 use Data::Dumper;
63
64 our %tt_templates;
65 our %filled_templates;
66 our $safe;
67 our $language;
68
69 # This function is what is called when someone does include('foo/bar')
70 # {include('foo/bar')}
71
72 sub include {
73      my $template = shift;
74      $filled_templates{$template}++;
75      print STDERR "include template $template language $language safe $safe\n" if $DEBUG;
76      # Die if we're in a template loop
77      die "Template loop with $template" if $filled_templates{$template} > 10;
78      my $filled_tmpl = '';
79      eval {
80           $filled_tmpl = fill_in_template(template  => $template,
81                                           variables => {},
82                                           language  => $language,
83                                           safe      => $safe,
84                                          );
85      };
86      if ($@) {
87           print STDERR "failed to fill template $template: $@";
88      }
89      print STDERR "failed to fill template $template\n" if $filled_tmpl eq '' and $DEBUG;
90      print STDERR "template $template '$filled_tmpl'\n" if $DEBUG;
91      $filled_templates{$template}--;
92      return $filled_tmpl;
93 };
94
95
96 =head2 fill_in_template
97
98      print fill_in_template(template => 'template_name',
99                             variables => \%variables,
100                             language  => '..'
101                            );
102
103 Reads a template from disk (if it hasn't already been read in) and
104 fills the template in.
105
106 =cut
107
108
109 sub fill_in_template{
110      my %param = validate_with(params => \@_,
111                                spec   => {template => SCALAR|HANDLE|SCALARREF,
112                                           variables => {type => HASHREF,
113                                                         default => {},
114                                                        },
115                                           language  => {type => SCALAR,
116                                                         default => 'en_US',
117                                                        },
118                                           output    => {type => HANDLE,
119                                                         optional => 1,
120                                                        },
121                                           safe      => {type => OBJECT|UNDEF,
122                                                         optional => 1,
123                                                        },
124                                           hole_var  => {type => HASHREF,
125                                                         optional => 1,
126                                                        },
127                                          },
128                               );
129      #@param{qw(template variables language safe output hole_var no_safe)} = @_;
130      if ($DEBUG) {
131           print STDERR "fill_in_template ";
132           print STDERR join(" ",map {exists $param{$_}?"$_:$param{$_}":()} keys %param);
133           print STDERR "\n";
134      }
135
136      # Get the text
137      my $tt_type = '';
138      my $tt_source;
139      if (ref($param{template}) eq 'GLOB' or
140          ref(\$param{template}) eq 'GLOB') {
141           $tt_type = 'FILE_HANDLE';
142           $tt_source = $param{template};
143           binmode($tt_source,":encoding(UTF-8)");
144      }
145      elsif (ref($param{template}) eq 'SCALAR') {
146           $tt_type = 'STRING';
147           $tt_source = ${$param{template}};
148      }
149      else {
150           $tt_type = 'FILE';
151           $tt_source = _locate_text($param{template},$param{language});
152      }
153      if (not defined $tt_source) {
154           die "Unable to find template $param{template} with language $param{language}";
155      }
156
157 #      if (defined $param{safe}) {
158 #         $safe = $param{safe};
159 #      }
160 #      else {
161 #         print STDERR "Created new safe\n" if $DEBUG;
162 #         $safe = Safe->new() or die "Unable to create safe compartment";
163 #         $safe->permit_only(':base_core',':base_loop',':base_mem',
164 #                            qw(padsv padav padhv padany),
165 #                            qw(rv2gv refgen srefgen ref),
166 #                            qw(caller require entereval),
167 #                            qw(gmtime time sprintf prtf),
168 #                            qw(sort),
169 #                           );
170 #         $safe->share('*STDERR');
171 #         $safe->share('%config');
172 #         $hole->wrap(\&Debbugs::Text::include,$safe,'&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 #         for my $key (keys %{exists $param{hole_var}?$param{hole_var}:{}}) {
188 #              print STDERR "Wraping $key as $param{hole_var}{$key}\n" if $DEBUG;
189 #              $hole->wrap($param{hole_var}{$key},$safe,$key);
190 #         }
191 #      }
192      $language = $param{language};
193      my $tt;
194      if ($tt_type eq 'FILE' and
195          defined $tt_templates{$tt_source} and
196          ($tt_templates{$tt_source}{mtime} + 60) < time and
197          (stat $tt_source)[9] <= $tt_templates{$tt_source}{mtime}
198         ) {
199           $tt = $tt_templates{$tt_source}{template};
200      }
201      else {
202          my $passed_source = $tt_source;
203          my $passed_type = $tt_type;
204           if ($tt_type eq 'FILE') {
205                $tt_templates{$tt_source}{mtime} =
206                     (stat $tt_source)[9];
207                $passed_source = IO::File->new($tt_source,'r');
208                binmode($passed_source,":encoding(UTF-8)");
209                $passed_type = 'FILEHANDLE';
210           }
211           $tt = Text::Template->new(TYPE => $passed_type,
212                                     SOURCE => $passed_source,
213                                     UNTAINT => 1,
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(#SAFE => $safe,
223                             PACKAGE => 'DTT',
224                             HASH => {%{$param{variables}//{}},
225                                      (map {my $t = $_; $t =~ s/^\&//; ($t => $param{hole_var}{$_})}
226                                       keys %{$param{hole_var}//{}}),
227                                      include => \&Debbugs::Text::include,
228                                      config  => \%config,
229                                     },
230                             defined $param{output}?(OUTPUT=>$param{output}):(),
231                            );
232      if (not defined $ret) {
233           print STDERR $Text::Template::ERROR;
234           return '';
235      }
236      if ($DEBUG) {
237           no strict 'refs';
238           no warnings 'uninitialized';
239 #         my $temp = $param{nosafe}?'main':$safe->{Root};
240           print STDERR "Variables for $param{template}\n";
241 #         print STDERR "Safe $temp\n";
242 #         print STDERR map {"$_: ".*{$_}."\n"} keys %{"${temp}::"};
243      }
244
245      return $ret;
246 }
247
248 sub _locate_text{
249      my ($template,$language) = @_;
250      $template =~ s/\.tmpl$//g;
251      # if a language doesn't exist, use the en_US template
252      if (not -e $config{template_dir}.'/'.$language.'/'.$template.'.tmpl') {
253           $language = 'en_US';
254      }
255      my $loc = $config{template_dir}.'/'.$language.'/'.$template.'.tmpl';
256      if (not -e $loc) {
257           print STDERR "Unable to locate template $loc\n";
258           return undef;
259      }
260      return $loc;
261 }
262
263 1;