Tripletail

 view release on metacpan or  search on metacpan

lib/Tripletail/Template.pm  view on Meta::CPAN

# -----------------------------------------------------------------------------
# Tripletail::Template - テンプレートを扱う
# -----------------------------------------------------------------------------
package Tripletail::Template;
use strict;
use warnings;
use File::Spec::Functions;
use Tripletail;
use Tripletail::Template::Node;

our %_REL2ABS_CACHE;

1;

sub __rel2abs
{
	my $path = shift;
	my $base = shift;
	$_REL2ABS_CACHE{"$path\0$base"} ||= File::Spec::Functions::rel2abs($path, $base);
}

sub _new {
	my $class = shift;
	my $this = bless {} => $class;

	$this->{root} = Tripletail::Template::Node->_new(
        undef, undef, undef, $TL->INI->get(Template => allow_unexpanded_tags => 'false'));

	$this->{basepath} = $TL->INI->get_reloc('Template' => 'basepath', '.');
	if( !File::Spec::Functions::file_name_is_absolute($this->{basepath}) )
	{
		my $cwd = $TL::CWD || $TL->_cwd;
		$this->{basepath} = __rel2abs($this->{basepath}, $cwd);
	}
	$this->{rootpath} = $TL->INI->get_reloc('Template' => 'rootpath', '/');
	if( !File::Spec::Functions::file_name_is_absolute($this->{rootpath}) )
	{
		my $cwd = $TL::CWD || $TL->_cwd;
		$this->{rootpath} = __rel2abs($this->{rootpath}, $cwd);
	}

	$TL->getDebug->_templateLog(
		node => $this->{root},
		type => 'new'
	);

	if(defined($_[0])) {
		$this->loadTemplate(@_);
	}

	$this;
}

sub _checkPathIsAcceptable {
	my $this = shift;
	my $path = shift;
	
	if( $this->{rootpath} eq '/' )
	{
		return; # void.
	}

	# rootpathチェック
	my @rootpath = File::Spec::Functions::splitdir(
		File::Spec::Functions::canonpath($this->{rootpath})
	);
	length $rootpath[-1] or pop @rootpath;
	@rootpath && length $rootpath[-1] or pop @rootpath;

	$path = File::Spec::Functions::canonpath($path);
	my @path = File::Spec::Functions::splitdir($path);

	my @abspath;
	foreach my $dir (@path) {
		if($dir eq '..') {
			pop(@abspath);
			next;
		}
		push(@abspath, $dir);
	}

	for(my $i = 0; $i < @rootpath; $i++) {
		if($rootpath[$i] ne $abspath[$i]) {
            die __PACKAGE__."#_checkPathIsAcceptable: file [$path] is not allowed to be loaded ".



( run in 1.412 second using v1.01-cache-2.11-cpan-a9496e3eb41 )