blib/lib/Template/Provider.pm untested

filter: Statementstmt 0.0% 0 / 412 Branchbran 0.0% 0 / 260 Conditioncond 0.0% 0 / 85 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 41 Podpod 0.0% 0 / 20 totaltotal 0.0% 0 / 818 CC 126 SCAR 48.2
CC
126
Cov
0%
_compile
306.0
_load
240.0
_init
210.0
CRAP 124.5
1 #============================================================= -*-Perl-*-
2 #
3 # Template::Provider
4 #
5 # DESCRIPTION
6 # This module implements a class which handles the loading, compiling
7 # and caching of templates. Multiple Template::Provider objects can
8 # be stacked and queried in turn to effect a Chain-of-Command between
9 # them. A provider will attempt to return the requested template,
10 # an error (STATUS_ERROR) or decline to provide the template
11 # (STATUS_DECLINE), allowing subsequent providers to attempt to
12 # deliver it. See 'Design Patterns' for further details.
13 #
14 # AUTHORS
15 # Andy Wardley <abw@wardley.org>
16 #
17 # Refactored by Bill Moseley for v2.19 to add negative caching (i.e.
18 # tracking templates that are NOTFOUND so that we can decline quickly)
19 # and to provide better support for subclassing the provider.
20 #
21 # COPYRIGHT
22 # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved.
23 #
24 # This module is free software; you can redistribute it and/or
25 # modify it under the same terms as Perl itself.
26 #
27 # WARNING:
28 # This code is ugly and contorted and is being totally re-written for TT3.
29 # In particular, we'll be throwing errors rather than messing around
30 # returning (value, status) pairs. With the benefit of hindsight, that
31 # was a really bad design decision on my part. I deserve to be knocked
32 # to the ground and kicked around a bit by hoards of angry TT developers
33 # for that one. Bill's refactoring has made the module easier to subclass,
34 # (so you can ease off the kicking now), but it really needs to be totally
35 # redesigned and rebuilt from the ground up along with the bits of TT that
36 # use it. -- abw 2007/04/27
37 #============================================================================
38  
39 package Template::Provider;
40  
41 use strict;
42 use warnings;
43 use base 'Template::Base';
44 use Template::Config;
45 use Template::Constants;
46 use Template::Document;
47 use File::Basename;
48 use File::Spec;
49  
50 use constant PREV => 0;
51 use constant NAME => 1; # template name -- indexed by this name in LOOKUP
52 use constant DATA => 2; # Compiled template
53 use constant LOAD => 3; # mtime of template
54 use constant NEXT => 4; # link to next item in cache linked list
55 use constant STAT => 5; # Time last stat()ed
56 use constant MSWin32 => $^O eq 'MSWin32';
57  
58 our $VERSION = '3.100';
59 our $DEBUG = 0 unless defined $DEBUG;
60 our $ERROR = '';
61  
62 # name of document class
63 our $DOCUMENT = 'Template::Document' unless defined $DOCUMENT;
64  
65 # maximum time between performing stat() on file to check staleness
66 our $STAT_TTL = 1 unless defined $STAT_TTL;
67  
68 # maximum number of directories in an INCLUDE_PATH, to prevent runaways
69 our $MAX_DIRS = 64 unless defined $MAX_DIRS;
70  
71 # UNICODE is supported in versions of Perl from 5.007 onwards
72 our $UNICODE = $] > 5.007 ? 1 : 0;
73  
74 my $boms = [
75 'UTF-8' => "\x{ef}\x{bb}\x{bf}",
76 'UTF-32BE' => "\x{0}\x{0}\x{fe}\x{ff}",
77 'UTF-32LE' => "\x{ff}\x{fe}\x{0}\x{0}",
78 'UTF-16BE' => "\x{fe}\x{ff}",
79 'UTF-16LE' => "\x{ff}\x{fe}",
80 ];
81  
82 # regex to match relative paths
83 our $RELATIVE_PATH = qr[(?:^|/)\.+/];
84  
85 #========================================================================
86 # -- PUBLIC METHODS --
87 #========================================================================
88  
89 #------------------------------------------------------------------------
90 # fetch($name)
91 #
92 # Returns a compiled template for the name specified by parameter.
93 # The template is returned from the internal cache if it exists, or
94 # loaded and then subsequently cached. The ABSOLUTE and RELATIVE
95 # configuration flags determine if absolute (e.g. '/something...')
96 # and/or relative (e.g. './something') paths should be honoured. The
97 # INCLUDE_PATH is otherwise used to find the named file. $name may
98 # also be a reference to a text string containing the template text,
99 # or a file handle from which the content is read. The compiled
100 # template is not cached in these latter cases given that there is no
101 # filename to cache under. A subsequent call to store($name,
102 # $compiled) can be made to cache the compiled template for future
103 # fetch() calls, if necessary.
104 #
105 # Returns a compiled template or (undef, STATUS_DECLINED) if the
106 # template could not be found. On error (e.g. the file was found
107 # but couldn't be read or parsed), the pair ($error, STATUS_ERROR)
108 # is returned. The TOLERANT configuration option can be set to
109 # downgrade any errors to STATUS_DECLINE.
110 #------------------------------------------------------------------------
111  
112 sub fetch {
113 my ($self, $name) = @_;
114 my ($data, $error);
115  
116  
117 if (ref $name) {
118 # $name can be a reference to a scalar, GLOB or file handle
119 ($data, $error) = $self->_load($name);
120 ($data, $error) = $self->_compile($data)
121 unless $error;
122 $data = $data->{ data }
123 unless $error;
124 }
125 elsif (File::Spec->file_name_is_absolute($name)) {
126 # absolute paths (starting '/') allowed if ABSOLUTE set
127 ($data, $error) = $self->{ ABSOLUTE }
128 ? $self->_fetch($name)
129 : $self->{ TOLERANT }
130 ? (undef, Template::Constants::STATUS_DECLINED)
131 : ("$name: absolute paths are not allowed (set ABSOLUTE option)",
132 Template::Constants::STATUS_ERROR);
133 }
134 elsif ($name =~ m/$RELATIVE_PATH/o) {
135 # anything starting "./" is relative to cwd, allowed if RELATIVE set
136 ($data, $error) = $self->{ RELATIVE }
137 ? $self->_fetch($name)
138 : $self->{ TOLERANT }
139 ? (undef, Template::Constants::STATUS_DECLINED)
140 : ("$name: relative paths are not allowed (set RELATIVE option)",
141 Template::Constants::STATUS_ERROR);
142 }
143 else {
144 # otherwise, it's a file name relative to INCLUDE_PATH
145 ($data, $error) = $self->{ INCLUDE_PATH }
146 ? $self->_fetch_path($name)
147 : (undef, Template::Constants::STATUS_DECLINED);
148 }
149  
150 return ($data, $error);
151 }
152  
153  
154 #------------------------------------------------------------------------
155 # store($name, $data)
156 #
157 # Store a compiled template ($data) in the cached as $name.
158 # Returns compiled template
159 #------------------------------------------------------------------------
160  
161 sub store {
162 my ($self, $name, $data, $mtime) = @_;
163 $self->_store($name, {
164 data => $data,
165 load => 0,
166 mtime => $mtime
167 });
168 }
169  
170  
171 #------------------------------------------------------------------------
172 # load($name)
173 #
174 # Load a template without parsing/compiling it, suitable for use with
175 # the INSERT directive. There's some duplication with fetch() and at
176 # some point this could be reworked to integrate them a little closer.
177 #------------------------------------------------------------------------
178  
179 sub load {
180 my ($self, $name) = @_;
181 my ($data, $error);
182 my $path = $name;
183  
184 if (File::Spec->file_name_is_absolute($name)) {
185 # absolute paths (starting '/') allowed if ABSOLUTE set
186 $error = "$name: absolute paths are not allowed (set ABSOLUTE option)"
187 unless $self->{ ABSOLUTE };
188 }
189 elsif ($name =~ m[$RELATIVE_PATH]o) {
190 # anything starting "./" is relative to cwd, allowed if RELATIVE set
191 $error = "$name: relative paths are not allowed (set RELATIVE option)"
192 unless $self->{ RELATIVE };
193 }
194 else {
195 INCPATH: {
196 # otherwise, it's a file name relative to INCLUDE_PATH
197 my $paths = $self->paths()
198 || return ($self->error(), Template::Constants::STATUS_ERROR);
199  
200 foreach my $dir (@$paths) {
201 $path = File::Spec->catfile($dir, $name);
202 last INCPATH
203 if defined $self->_template_modified($path);
204 }
205 undef $path; # not found
206 }
207 }
208  
209 # Now fetch the content
210 ($data, $error) = $self->_template_content($path)
211 if defined $path && !$error;
212  
213 if ($error) {
214 return $self->{ TOLERANT }
215 ? (undef, Template::Constants::STATUS_DECLINED)
216 : ($error, Template::Constants::STATUS_ERROR);
217 }
218 elsif (! defined $path) {
219 return (undef, Template::Constants::STATUS_DECLINED);
220 }
221 else {
222 return ($data, Template::Constants::STATUS_OK);
223 }
224 }
225  
226  
227  
228 #------------------------------------------------------------------------
229 # include_path(\@newpath)
230 #
231 # Accessor method for the INCLUDE_PATH setting. If called with an
232 # argument, this method will replace the existing INCLUDE_PATH with
233 # the new value.
234 #------------------------------------------------------------------------
235  
236 sub include_path {
237 my ($self, $path) = @_;
238 $self->{ INCLUDE_PATH } = $path if $path;
239 return $self->{ INCLUDE_PATH };
240 }
241  
242  
243 #------------------------------------------------------------------------
244 # paths()
245 #
246 # Evaluates the INCLUDE_PATH list, ignoring any blank entries, and
247 # calling and subroutine or object references to return dynamically
248 # generated path lists. Returns a reference to a new list of paths
249 # or undef on error.
250 #------------------------------------------------------------------------
251  
252 sub paths {
253 my $self = shift;
254 my @ipaths = @{ $self->{ INCLUDE_PATH } };
255 my (@opaths, $dpaths, $dir);
256 my $count = $MAX_DIRS;
257  
258 while (@ipaths && --$count) {
259 $dir = shift @ipaths || next;
260  
261 # $dir can be a sub or object ref which returns a reference
262 # to a dynamically generated list of search paths.
263  
264 if (ref $dir eq 'CODE') {
265 eval { $dpaths = &$dir() };
266 if ($@) {
267 chomp $@;
268 return $self->error($@);
269 }
270 unshift(@ipaths, @$dpaths);
271 next;
272 }
273 elsif (ref($dir) && UNIVERSAL::can($dir, 'paths')) {
274 $dpaths = $dir->paths()
275 || return $self->error($dir->error());
276 unshift(@ipaths, @$dpaths);
277 next;
278 }
279 else {
280 push(@opaths, $dir);
281 }
282 }
283 return $self->error("INCLUDE_PATH exceeds $MAX_DIRS directories")
284 if @ipaths;
285  
286 return \@opaths;
287 }
288  
289  
290 #------------------------------------------------------------------------
291 # DESTROY
292 #
293 # The provider cache is implemented as a doubly linked list which Perl
294 # cannot free by itself due to the circular references between NEXT <=>
295 # PREV items. This cleanup method walks the list deleting all the NEXT/PREV
296 # references, allowing the proper cleanup to occur and memory to be
297 # repooled.
298 #------------------------------------------------------------------------
299  
300 sub DESTROY {
301 my $self = shift;
302 my ($slot, $next);
303  
304 $slot = $self->{ HEAD };
305 while ($slot) {
306 $next = $slot->[ NEXT ];
307 undef $slot->[ PREV ];
308 undef $slot->[ NEXT ];
309 $slot = $next;
310 }
311 undef $self->{ HEAD };
312 undef $self->{ TAIL };
313 }
314  
315  
316  
317  
318 #========================================================================
319 # -- PRIVATE METHODS --
320 #========================================================================
321  
322 #------------------------------------------------------------------------
323 # _init()
324 #
325 # Initialise the cache.
326 #------------------------------------------------------------------------
327  
328 sub _init {
329 my ($self, $params) = @_;
330 my $size = $params->{ CACHE_SIZE };
331 my $path = $params->{ INCLUDE_PATH } || '.';
332 my $cdir = $params->{ COMPILE_DIR } || '';
333 my $dlim = $params->{ DELIMITER };
334 my $debug;
335  
336 # tweak delim to ignore C:/
337 unless (defined $dlim) {
338 $dlim = MSWin32 ? qr/:(?!\\|\/)/ : qr/:/;
339 }
340  
341 # coerce INCLUDE_PATH to an array ref, if not already so
342 $path = [ split(/$dlim/, $path) ]
343 unless ref $path eq 'ARRAY';
344  
345 # don't allow a CACHE_SIZE 1 because it breaks things and the
346 # additional checking isn't worth it
347 $size = 2
348 if defined $size && ($size == 1 || $size < 0);
349  
350 if (defined ($debug = $params->{ DEBUG })) {
351 $self->{ DEBUG } = $debug & ( Template::Constants::DEBUG_PROVIDER
352 | Template::Constants::DEBUG_FLAGS );
353 }
354 else {
355 $self->{ DEBUG } = $DEBUG;
356 }
357  
358 if ($self->{ DEBUG }) {
359 local $" = ', ';
360 $self->debug(
361 "creating cache of ",
362 defined $size ? $size : 'unlimited',
363 " slots for [ @$path ]"
364 );
365 }
366  
367 # create COMPILE_DIR and sub-directories representing each INCLUDE_PATH
368 # element in which to store compiled files
369 if ($cdir) {
370 require File::Path;
371 foreach my $dir (@$path) {
372 next if ref $dir;
373 my $wdir = $dir;
374 $wdir =~ tr[:][]d if MSWin32;
375 {
376 no warnings 'syntax';
377 $wdir = each %{ { $wdir => undef } } if ${^TAINT}; #untaint
378 }
379 $wdir = File::Spec->catfile($cdir, $wdir);
380 File::Path::mkpath($wdir) unless -d $wdir;
381 }
382 }
383  
384 $self->{ LOOKUP } = { };
385 $self->{ NOTFOUND } = { }; # Tracks templates *not* found.
386 $self->{ SLOTS } = 0;
387 $self->{ SIZE } = $size;
388 $self->{ INCLUDE_PATH } = $path;
389 $self->{ DELIMITER } = $dlim;
390 $self->{ COMPILE_DIR } = $cdir;
391 $self->{ COMPILE_EXT } = $params->{ COMPILE_EXT } || '';
392 $self->{ ABSOLUTE } = $params->{ ABSOLUTE } || 0;
393 $self->{ RELATIVE } = $params->{ RELATIVE } || 0;
394 $self->{ TOLERANT } = $params->{ TOLERANT } || 0;
395 $self->{ DOCUMENT } = $params->{ DOCUMENT } || $DOCUMENT;
396 $self->{ PARSER } = $params->{ PARSER };
397 $self->{ DEFAULT } = $params->{ DEFAULT };
398 $self->{ ENCODING } = $params->{ ENCODING };
399 # $self->{ PREFIX } = $params->{ PREFIX };
400 $self->{ STAT_TTL } = $params->{ STAT_TTL } || $STAT_TTL;
401 $self->{ PARAMS } = $params;
402  
403 # look for user-provided UNICODE parameter or use default from package var
404 $self->{ UNICODE } = defined $params->{ UNICODE }
405 ? $params->{ UNICODE } : $UNICODE;
406  
407 return $self;
408 }
409  
410  
411 #------------------------------------------------------------------------
412 # _fetch($name, $t_name)
413 #
414 # Fetch a file from cache or disk by specification of an absolute or
415 # relative filename. No search of the INCLUDE_PATH is made. If the
416 # file is found and loaded, it is compiled and cached.
417 # Call with:
418 # $name = path to search (possible prefixed by INCLUDE_PATH)
419 # $t_name = template name
420 #------------------------------------------------------------------------
421  
422 sub _fetch {
423 my ($self, $name, $t_name) = @_;
424 my $stat_ttl = $self->{ STAT_TTL };
425  
426 $self->debug("_fetch($name)") if $self->{ DEBUG };
427  
428 # First see if the named template is in the memory cache
429 if ((my $slot = $self->{ LOOKUP }->{ $name })) {
430 # Test if cache is fresh, and reload/compile if not.
431 my ($data, $error) = $self->_refresh($slot);
432  
433 return $error
434 ? ( $data, $error ) # $data may contain error text
435 : $slot->[ DATA ]; # returned document object
436 }
437  
438 # Otherwise, see if we already know the template is not found
439 if (my $last_stat_time = $self->{ NOTFOUND }->{ $name }) {
440 my $expires_in = $last_stat_time + $stat_ttl - time;
441 if ($expires_in > 0) {
442 $self->debug(" file [$name] in negative cache. Expires in $expires_in seconds")
443 if $self->{ DEBUG };
444 return (undef, Template::Constants::STATUS_DECLINED);
445 }
446 else {
447 delete $self->{ NOTFOUND }->{ $name };
448 }
449 }
450  
451 my($template,$error);
452 my $uncompiled_template_mtime = $self->_template_modified( $name ); # does template exist?
453  
454 # some templates like Provider::FromDATA does not provide mtime information
455 $uncompiled_template_mtime = 0 unless defined $uncompiled_template_mtime;
456  
457 # Is there an up-to-date compiled version on disk?
458 if (my $template_mtime = $self->_compiled_is_current($name, $uncompiled_template_mtime)) {
459 # require() the compiled template.
460 my $compiled_template = $self->_load_compiled( $self->_compiled_filename($name) );
461  
462 # Store and return the compiled template
463 return $self->store( $name, $compiled_template, $template_mtime ) if $compiled_template;
464  
465 # Problem loading compiled template:
466 # warn and continue to fetch source template
467 warn($self->error(), "\n");
468 }
469  
470 # load template from source
471 ($template, $error) = $self->_load($name, $t_name);
472  
473 if ($error) {
474 # Template could not be fetched. Add to the negative/notfound cache.
475 $self->{ NOTFOUND }->{ $name } = time;
476 return ( $template, $error );
477 }
478  
479 # compile template source
480 ($template, $error) = $self->_compile($template, $self->_compiled_filename($name) );
481  
482 if ($error) {
483 # return any compile time error
484 return ($template, $error);
485 }
486 else {
487 # Store compiled template and return it
488 return $self->store($name, $template->{data}) ;
489 }
490 }
491  
492  
493 #------------------------------------------------------------------------
494 # _fetch_path($name)
495 #
496 # Fetch a file from cache or disk by specification of an absolute cache
497 # name (e.g. 'header') or filename relative to one of the INCLUDE_PATH
498 # directories. If the file isn't already cached and can be found and
499 # loaded, it is compiled and cached under the full filename.
500 #------------------------------------------------------------------------
501  
502 sub _fetch_path {
503 my ($self, $name) = @_;
504  
505 $self->debug("_fetch_path($name)") if $self->{ DEBUG };
506  
507 # the template may have been stored using a non-filename name
508 # so look for the plain name in the cache first
509 if ((my $slot = $self->{ LOOKUP }->{ $name })) {
510 # cached entry exists, so refresh slot and extract data
511 my ($data, $error) = $self->_refresh($slot);
512  
513 return $error
514 ? ($data, $error)
515 : ($slot->[ DATA ], $error );
516 }
517  
518 my $paths = $self->paths
519 || return ( $self->error, Template::Constants::STATUS_ERROR );
520  
521 # search the INCLUDE_PATH for the file, in cache or on disk
522 foreach my $dir (@$paths) {
523 my $path = File::Spec->catfile($dir, $name);
524  
525 $self->debug("searching path: $path\n") if $self->{ DEBUG };
526  
527 my ($data, $error) = $self->_fetch( $path, $name );
528  
529 # Return if no error or if a serious error.
530 return ( $data, $error )
531 if !$error || $error == Template::Constants::STATUS_ERROR;
532  
533 }
534  
535 # not found in INCLUDE_PATH, now try DEFAULT
536 return $self->_fetch_path( $self->{DEFAULT} )
537 if defined $self->{DEFAULT} && $name ne $self->{DEFAULT};
538  
539 # We could not handle this template name
540 return (undef, Template::Constants::STATUS_DECLINED);
541 }
542  
543 sub _compiled_filename {
544 my ($self, $file) = @_;
545  
546 return $self->{ COMPILEDPATH }{$file} if $self->{ COMPILEDPATH }{$file};
547  
548 my ($compext, $compdir) = @$self{ qw( COMPILE_EXT COMPILE_DIR ) };
549 my ($path, $compiled);
550  
551 return undef
552 unless $compext || $compdir;
553  
554 $path = $file;
555 $path or die "invalid filename: $path";
556 $path =~ tr[:][]d if MSWin32;
557  
558  
559 $compiled = "$path$compext";
560 $self->{ COMPILEDPATH }{$file} = $compiled = File::Spec->catfile($compdir, $compiled) if length $compdir;
561  
562 return $compiled;
563 }
564  
565 sub _load_compiled {
566 my ($self, $file) = @_;
567  
568 # Implicitly Relative paths are not supported
569 # by "require" and invoke @INC traversal, where relative
570 # paths only traditionally worked prior to Perl 5.26
571 # due to the presence of '.' in @INC
572 #
573 # Given load_compiled never wants to traverse @INC, forcing
574 # an absolute path for the loaded file and the INC key is
575 # sensible.
576 #
577 # NB: %INC Keys are always identical to their respective
578 # "require" invocations regardless of OS, and the only time
579 # one needs to care about slash direction is when dealing
580 # with Module::Name -> Module/Name.pm translation.
581 my $fpath = File::Spec->rel2abs( $file );
582  
583 return $self->error("compiled template missing path") unless defined $fpath;
584  
585 ($fpath) = $fpath =~ /^(.*)$/s;
586  
587 # load compiled template via require(); we zap any
588 # %INC entry to ensure it is reloaded (we don't
589 # want 1 returned by require() to say it's in memory)
590 delete $INC{ $fpath };
591 my $compiled;
592 eval { $compiled = require $fpath; };
593 return $@
594 ? $self->error("compiled template $fpath: $@")
595 : $compiled;
596 }
597  
598 #------------------------------------------------------------------------
599 # _load($name, $alias)
600 #
601 # Load template text from a string ($name = scalar ref), GLOB or file
602 # handle ($name = ref), or from an absolute filename ($name = scalar).
603 # Returns a hash array containing the following items:
604 # name filename or $alias, if provided, or 'input text', etc.
605 # text template text
606 # time modification time of file, or current time for handles/strings
607 # load time file was loaded (now!)
608 #
609 # On error, returns ($error, STATUS_ERROR), or (undef, STATUS_DECLINED)
610 # if TOLERANT is set.
611 #------------------------------------------------------------------------
612  
613 sub _load {
614 my ($self, $name, $alias) = @_;
615 my ($data, $error);
616 my $tolerant = $self->{ TOLERANT };
617 my $now = time;
618  
619 $alias = $name unless defined $alias or ref $name;
620  
621 $self->debug("_load($name, ", defined $alias ? $alias : '<no alias>',
622 ')') if $self->{ DEBUG };
623  
624 # SCALAR ref is the template text
625 if (ref $name eq 'SCALAR') {
626 # $name can be a SCALAR reference to the input text...
627 return {
628 name => defined $alias ? $alias : 'input text',
629 path => defined $alias ? $alias : 'input text',
630 text => $$name,
631 time => $now,
632 load => 0,
633 };
634 }
635  
636 # Otherwise, assume GLOB as a file handle
637 if (ref $name) {
638 local $/;
639 my $text = <$name>;
640 $text = $self->_decode_unicode($text) if $self->{ UNICODE };
641 return {
642 name => defined $alias ? $alias : 'input file handle',
643 path => defined $alias ? $alias : 'input file handle',
644 text => $text,
645 time => $now,
646 load => 0,
647 };
648 }
649  
650 # Otherwise, it's the name of the template
651 if ( defined $self->_template_modified( $name ) ) { # does template exist?
652 my ($text, $error, $mtime ) = $self->_template_content( $name );
653 unless ( $error ) {
654 $text = $self->_decode_unicode($text) if $self->{ UNICODE };
655 return {
656 name => $alias,
657 path => $name,
658 text => $text,
659 time => $mtime,
660 load => $now,
661 };
662 }
663  
664 return ( $error, Template::Constants::STATUS_ERROR )
665 unless $tolerant;
666 }
667  
668 # Unable to process template, pass onto the next Provider.
669 return (undef, Template::Constants::STATUS_DECLINED);
670 }
671  
672  
673 #------------------------------------------------------------------------
674 # _refresh(\@slot)
675 #
676 # Private method called to mark a cache slot as most recently used.
677 # A reference to the slot array should be passed by parameter. The
678 # slot is relocated to the head of the linked list. If the file from
679 # which the data was loaded has been updated since it was compiled, then
680 # it is re-loaded from disk and re-compiled.
681 #------------------------------------------------------------------------
682  
683 sub _refresh {
684 my ($self, $slot) = @_;
685 my $stat_ttl = $self->{ STAT_TTL };
686 my ($head, $file, $data, $error);
687  
688 $self->debug(
689 "_refresh([ ",
690 join(', ', map { defined $_ ? $_ : '<undef>' } @$slot),
691 '])'
692 ) if $self->{ DEBUG };
693  
694 # if it's more than $STAT_TTL seconds since we last performed a
695 # stat() on the file then we need to do it again and see if the file
696 # time has changed
697 my $now = time;
698 my $expires_in_sec = $slot->[ STAT ] + $stat_ttl - $now;
699  
700 if ( $expires_in_sec <= 0 ) { # Time to check!
701 $slot->[ STAT ] = $now;
702  
703 # Grab mtime of template.
704 # Seems like this should be abstracted to compare to
705 # just ask for a newer compiled template (if it's newer)
706 # and let that check for a newer template source.
707 my $template_mtime = $self->_template_modified( $slot->[ NAME ] );
708 if ( ! defined $template_mtime || ( $template_mtime != $slot->[ LOAD ] )) {
709 $self->debug("refreshing cache file ", $slot->[ NAME ])
710 if $self->{ DEBUG };
711  
712 ($data, $error) = $self->_load($slot->[ NAME ], $slot->[ DATA ]->{ name });
713 ($data, $error) = $self->_compile($data, $self->_compiled_filename($slot->[ NAME ]))
714 unless $error;
715  
716 if ($error) {
717 # if the template failed to load/compile then we wipe out the
718 # STAT entry. This forces the provider to try and reload it
719 # each time instead of using the previously cached version
720 # until $STAT_TTL is next up
721 $slot->[ STAT ] = 0;
722 }
723 else {
724 $slot->[ DATA ] = $data->{ data };
725 $slot->[ LOAD ] = $data->{ time };
726 }
727 }
728  
729 } elsif ( $self->{ DEBUG } ) {
730 $self->debug( sprintf('STAT_TTL not met for file [%s]. Expires in %d seconds',
731 $slot->[ NAME ], $expires_in_sec ) );
732 }
733  
734 # Move this slot to the head of the list
735 unless( $self->{ HEAD } == $slot ) {
736 # remove existing slot from usage chain...
737 if ($slot->[ PREV ]) {
738 $slot->[ PREV ]->[ NEXT ] = $slot->[ NEXT ];
739 }
740 else {
741 $self->{ HEAD } = $slot->[ NEXT ];
742 }
743 if ($slot->[ NEXT ]) {
744 $slot->[ NEXT ]->[ PREV ] = $slot->[ PREV ];
745 }
746 else {
747 $self->{ TAIL } = $slot->[ PREV ];
748 }
749  
750 # ..and add to start of list
751 $head = $self->{ HEAD };
752 $head->[ PREV ] = $slot if $head;
753 $slot->[ PREV ] = undef;
754 $slot->[ NEXT ] = $head;
755 $self->{ HEAD } = $slot;
756 }
757  
758 return ($data, $error);
759 }
760  
761  
762  
763 #------------------------------------------------------------------------
764 # _store($name, $data)
765 #
766 # Private method called to add a data item to the cache. If the cache
767 # size limit has been reached then the oldest entry at the tail of the
768 # list is removed and its slot relocated to the head of the list and
769 # reused for the new data item. If the cache is under the size limit,
770 # or if no size limit is defined, then the item is added to the head
771 # of the list.
772 # Returns compiled template
773 #------------------------------------------------------------------------
774  
775 sub _store {
776 my ($self, $name, $data, $compfile) = @_;
777 my $size = $self->{ SIZE };
778 my ($slot, $head);
779  
780 # Return if memory cache disabled. (overriding code should also check)
781 # $$$ What's the expected behaviour of store()? Can't tell from the
782 # docs if you can call store() when SIZE = 0.
783 return $data->{data} if defined $size and !$size;
784  
785 # check the modification time -- extra stat here
786 my $load = $data->{ mtime } || $self->_modified($name);
787  
788 # extract the compiled template from the data hash
789 $data = $data->{ data };
790 $self->debug("_store($name, $data)") if $self->{ DEBUG };
791  
792 if (defined $size && $self->{ SLOTS } >= $size) {
793 # cache has reached size limit, so reuse oldest entry
794 $self->debug("reusing oldest cache entry (size limit reached: $size)\nslots: $self->{ SLOTS }") if $self->{ DEBUG };
795  
796 # remove entry from tail of list
797 $slot = $self->{ TAIL };
798 $slot->[ PREV ]->[ NEXT ] = undef;
799 $self->{ TAIL } = $slot->[ PREV ];
800  
801 # remove name lookup for old node
802 delete $self->{ LOOKUP }->{ $slot->[ NAME ] };
803  
804 # add modified node to head of list
805 $head = $self->{ HEAD };
806 $head->[ PREV ] = $slot if $head;
807 @$slot = ( undef, $name, $data, $load, $head, time );
808 $self->{ HEAD } = $slot;
809  
810 # add name lookup for new node
811 $self->{ LOOKUP }->{ $name } = $slot;
812 }
813 else {
814 # cache is under size limit, or none is defined
815  
816 $self->debug("adding new cache entry") if $self->{ DEBUG };
817  
818 # add new node to head of list
819 $head = $self->{ HEAD };
820 $slot = [ undef, $name, $data, $load, $head, time ];
821 $head->[ PREV ] = $slot if $head;
822 $self->{ HEAD } = $slot;
823 $self->{ TAIL } = $slot unless $self->{ TAIL };
824  
825 # add lookup from name to slot and increment nslots
826 $self->{ LOOKUP }->{ $name } = $slot;
827 $self->{ SLOTS }++;
828 }
829  
830 return $data;
831 }
832  
833  
834 #------------------------------------------------------------------------
835 # _compile($data)
836 #
837 # Private method called to parse the template text and compile it into
838 # a runtime form. Creates and delegates a Template::Parser object to
839 # handle the compilation, or uses a reference passed in PARSER. On
840 # success, the compiled template is stored in the 'data' item of the
841 # $data hash and returned. On error, ($error, STATUS_ERROR) is returned,
842 # or (undef, STATUS_DECLINED) if the TOLERANT flag is set.
843 # The optional $compiled parameter may be passed to specify
844 # the name of a compiled template file to which the generated Perl
845 # code should be written. Errors are (for now...) silently
846 # ignored, assuming that failures to open a file for writing are
847 # intentional (e.g directory write permission).
848 #------------------------------------------------------------------------
849  
850 sub _compile {
851 my ($self, $data, $compfile) = @_;
852 my $text = $data->{ text };
853 my ($parsedoc, $error);
854  
855 $self->debug("_compile($data, ",
856 defined $compfile ? $compfile : '<no compfile>', ')')
857 if $self->{ DEBUG };
858  
859 my $parser = $self->{ PARSER }
860 ||= Template::Config->parser($self->{ PARAMS })
861 || return (Template::Config->error(), Template::Constants::STATUS_ERROR);
862  
863 # discard the template text - we don't need it any more
864 delete $data->{ text };
865  
866 # call parser to compile template into Perl code
867 if ($parsedoc = $parser->parse($text, $data)) {
868  
869 $parsedoc->{ METADATA } = {
870 'name' => $data->{ name },
871 'modtime' => $data->{ 'time' },
872 %{ $parsedoc->{ METADATA } },
873 };
874  
875 # write the Perl code to the file $compfile, if defined
876 if ($compfile) {
877 my $basedir = &File::Basename::dirname($compfile);
878 {
879 no warnings 'syntax';
880 $basedir = each %{ { $basedir => undef } } if ${^TAINT}; #untaint
881 }
882  
883 unless (-d $basedir) {
884 eval { File::Path::mkpath($basedir) };
885 $error = "failed to create compiled templates directory: $basedir ($@)"
886 if ($@);
887 }
888  
889 unless ($error) {
890 my $docclass = $self->{ DOCUMENT };
891 $error = 'cache failed to write '
892 . &File::Basename::basename($compfile)
893 . ': ' . $docclass->error()
894 unless $docclass->write_perl_file($compfile, $parsedoc);
895 }
896  
897 # set atime and mtime of newly compiled file, don't bother
898 # if time is undef
899 if (!defined($error) && defined $data->{ 'time' }) {
900 my $cfile = do {
901 no warnings 'syntax';
902 each %{ { $compfile => undef } };
903 };
904 if (!length $cfile) {
905 return(
906 "invalid filename: $compfile",
907 Template::Constants::STATUS_ERROR
908 );
909 };
910  
911 my $ctime = $data->{ time };
912 if (!length $ctime || $ctime =~ tr{0-9}{}c) {
913 return(
914 "invalid time: $ctime",
915 Template::Constants::STATUS_ERROR
916 );
917 }
918 utime($ctime, $ctime, $cfile);
919  
920 $self->debug(" cached compiled template to file [$compfile]")
921 if $self->{ DEBUG };
922 }
923 }
924  
925 unless ($error) {
926 return $data ## RETURN ##
927 if $data->{ data } = $DOCUMENT->new($parsedoc);
928 $error = $Template::Document::ERROR;
929 }
930 }
931 else {
932 $error = Template::Exception->new(
933 'parse', "$data->{ name } " .
934 $parser->error()
935 );
936 }
937  
938 # return STATUS_ERROR, or STATUS_DECLINED if we're being tolerant
939 return $self->{ TOLERANT }
940 ? (undef, Template::Constants::STATUS_DECLINED)
941 : ($error, Template::Constants::STATUS_ERROR)
942 }
943  
944 #------------------------------------------------------------------------
945 # _compiled_is_current( $template_name )
946 #
947 # Returns true if $template_name and its compiled name
948 # exist and they have the same mtime.
949 #------------------------------------------------------------------------
950  
951 sub _compiled_is_current {
952 my ( $self, $template_name, $uncompiled_template_mtime ) = @_;
953  
954 my $compiled_name = $self->_compiled_filename($template_name);
955 return unless defined $compiled_name;
956  
957 my $compiled_mtime = (stat($compiled_name))[9];
958 return unless defined $compiled_mtime;
959  
960 my $template_mtime = $uncompiled_template_mtime || $self->_template_modified( $template_name ) or return;
961 return unless defined $template_mtime;
962  
963 # This was >= in the 2.15, but meant that downgrading
964 # a source template would not get picked up.
965 return $compiled_mtime == $template_mtime ? $template_mtime : 0;
966 }
967  
968  
969 #------------------------------------------------------------------------
970 # _template_modified($path)
971 #
972 # Returns the last modified time of the $path.
973 # Returns undef if the path does not exist.
974 # Override if templates are not on disk, for example
975 #------------------------------------------------------------------------
976  
977 sub _template_modified {
978 my $self = shift;
979 my $template = shift || return;
980 return (stat( $template ))[9];
981 }
982  
983 #------------------------------------------------------------------------
984 # _template_content($path)
985 #
986 # Fetches content pointed to by $path.
987 # Returns the content in scalar context.
988 # Returns ($data, $error, $mtime) in list context where
989 # $data - content
990 # $error - error string if there was an error, otherwise undef
991 # $mtime - last modified time from calling stat() on the path
992 #------------------------------------------------------------------------
993  
994 sub _template_content {
995 my ($self, $path) = @_;
996  
997 return (undef, "No path specified to fetch content from ")
998 unless $path;
999  
1000 my $data;
1001 my $mod_date;
1002 my $error;
1003  
1004 local *FH;
1005 if(-d $path) {
1006 $error = "$path: not a file";
1007 }
1008 elsif (open(FH, "<", $path)) {
1009 local $/;
1010 binmode(FH);
1011 $data = <FH>;
1012 $mod_date = (stat($path))[9];
1013 close(FH);
1014 }
1015 else {
1016 $error = "$path: $!";
1017 }
1018  
1019 return wantarray
1020 ? ( $data, $error, $mod_date )
1021 : $data;
1022 }
1023  
1024  
1025 #------------------------------------------------------------------------
1026 # _modified($name)
1027 # _modified($name, $time)
1028 #
1029 # When called with a single argument, it returns the modification time
1030 # of the named template. When called with a second argument it returns
1031 # true if $name has been modified since $time.
1032 #------------------------------------------------------------------------
1033  
1034 sub _modified {
1035 my ($self, $name, $time) = @_;
1036 my $load = $self->_template_modified($name);
1037 return $time ? 1 : 0 unless defined $load;
1038  
1039 return $time
1040 ? $load > $time
1041 : $load;
1042 }
1043  
1044 #------------------------------------------------------------------------
1045 # _decode_unicode
1046 #
1047 # Decodes encoded unicode text that starts with a BOM and
1048 # turns it into perl's internal representation
1049 #------------------------------------------------------------------------
1050  
1051 sub _decode_unicode {
1052 my $self = shift;
1053 my $string = shift;
1054 return undef unless defined $string;
1055  
1056 use bytes;
1057 require Encode;
1058  
1059 return $string if Encode::is_utf8( $string );
1060  
1061 # try all the BOMs in order looking for one (order is important
1062 # 32bit BOMs look like 16bit BOMs)
1063  
1064 my $count = 0;
1065  
1066 while ($count < @{ $boms }) {
1067 my $enc = $boms->[$count++];
1068 my $bom = $boms->[$count++];
1069  
1070 # does the string start with the bom?
1071 if ($bom eq substr($string, 0, length($bom))) {
1072 # decode it and hand it back
1073 return Encode::decode($enc, substr($string, length($bom)), 1);
1074 }
1075 }
1076  
1077 return $self->{ ENCODING }
1078 ? Encode::decode( $self->{ ENCODING }, $string )
1079 : $string;
1080 }
1081  
1082  
1083 1;
1084  
1085 __END__