]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/Text.pm
* allow sort
[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      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 $hole = Safe::Hole->new({});
68 our $language;
69
70 # This function is what is called when someone does include('foo/bar')
71 # {include('foo/bar')}
72
73 sub include {
74      my $template = shift;
75      $filled_templates{$template}++;
76      print STDERR "include template $template language $language safe $safe\n" if $DEBUG;
77      # Die if we're in a template loop
78      die "Template loop with $template" if $filled_templates{$template} > 10;
79      my $filled_tmpl = '';
80      eval {
81           $filled_tmpl = fill_in_template(template  => $template,
82                                           variables => {},
83                                           language  => $language,
84                                           safe      => $safe,
85                                          );
86      };
87      if ($@) {
88           print STDERR "failed to fill template $template: $@";
89      }
90      print STDERR "failed to fill template $template\n" if $filled_tmpl eq '' and $DEBUG;
91      print STDERR "template $template '$filled_tmpl'\n" if $DEBUG;
92      $filled_templates{$template}--;
93      return $filled_tmpl;
94 };
95
96
97 =head2 fill_in_template
98
99      print fill_in_template(template => 'template_name',
100                             variables => \%variables,
101                             language  => '..'
102                            );
103
104 Reads a template from disk (if it hasn't already been read in) and
105 fills the template in.
106
107 =cut
108
109
110 sub fill_in_template{
111      my %param = validate_with(params => \@_,
112                                spec   => {template => SCALAR|HANDLE|SCALARREF,
113                                           variables => {type => HASHREF,
114                                                         default => {},
115                                                        },
116                                           language  => {type => SCALAR,
117                                                         default => 'en_US',
118                                                        },
119                                           output    => {type => HANDLE,
120                                                         optional => 1,
121                                                        },
122                                           safe      => {type => OBJECT,
123                                                         optional => 1,
124                                                        },
125                                           hole_var  => {type => HASHREF,
126                                                         optional => 1,
127                                                        },
128                                          },
129                               );
130      #@param{qw(template variables language safe output hole_var no_safe)} = @_;
131      if ($DEBUG) {
132           print STDERR "fill_in_template ";
133           print STDERR join(" ",map {exists $param{$_}?"$_:$param{$_}":()} keys %param);
134           print STDERR "\n";
135      }
136
137      # Get the text
138      my $tt_type = '';
139      my $tt_source;
140      if (ref($param{template}) eq 'GLOB' or
141          ref(\$param{template}) eq 'GLOB') {
142           $tt_type = 'FILE_HANDLE';
143           $tt_source = $param{template};
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          (stat $tt_source)[9] <= $tt_templates{$tt_source}{mtime}
197         ) {
198           $tt = $tt_templates{$tt_source}{template};
199      }
200      else {
201           if ($tt_type eq 'FILE') {
202                $tt_templates{$tt_source}{mtime} =
203                     (stat $tt_source)[9];
204           }
205           $tt = Text::Template->new(TYPE => $tt_type,
206                                     SOURCE => $tt_source,
207                                     UNTAINT => 1,
208                                    );
209           if ($tt_type eq 'FILE') {
210                $tt_templates{$tt_source}{template} = $tt;
211           }
212      }
213      if (not defined $tt) {
214           die "Unable to create Text::Template for $tt_type:$tt_source";
215      }
216      my $ret = $tt->fill_in(SAFE => $safe,
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      }
231
232      return $ret;
233 }
234
235 sub _locate_text{
236      my ($template,$language) = @_;
237      $template =~ s/\.tmpl$//g;
238      # if a language doesn't exist, use the en_US template
239      if (not -e $config{template_dir}.'/'.$language.'/'.$template.'.tmpl') {
240           $language = 'en_US';
241      }
242      my $loc = $config{template_dir}.'/'.$language.'/'.$template.'.tmpl';
243      if (not -e $loc) {
244           print STDERR "Unable to locate template $loc\n";
245           return undef;
246      }
247      return $loc;
248 }
249
250 1;