####################################################################
#
# ANY CHANGE MADE HERE WILL BE LOST !
#
# This file was generated using Parse::Yapp version <<$version>>.
# Don't edit this file, edit template.skel.pm and template.yp instead.
#
####################################################################
package VMXTemplate::Parser;
use strict;
use base qw(Parse::Yapp::Driver);
<<$driver>>
VMXTemplate::Utils::import();
<<$head>>
sub new
{
my $class = shift;
$class = ref($class) || $class;
my ($compiler) = @_;
return bless $class->SUPER::new(
yyversion => '<<$version>>',
yystates =>
<<$states>>,
yyrules =>
<<$rules>>,
#line 30 "template.skel.pm"
compiler => $compiler,
lexer => undef,
@_
), $class;
}
sub _Lexer
{
my ($parser) = shift;
return $parser->{lexer}->read_token;
}
sub _error
{
my ($self) = @_;
$self->{lexer}->warn('Unexpected ' . $self->YYCurtok . ($self->YYCurval ? ' ' . $self->YYCurval : ''));
$self->{lexer}->skip_error;
}
sub compile
{
my ($self, $text) = @_;
$self->{lexer} ||= new VMXTemplate::Lexer($self, $self->{compiler}->{options});
$self->{lexer}->set_code($text);
$self->{functions} = {
main => {
name => 'main',
args => [],
body => '',
line => 0,
pos => 0,
},
};
$self->YYParse(yylex => \&_Lexer, yyerror => \&_error);
if (!$self->{functions}->{main}->{body})
{
# Parse error?
delete $self->{functions}->{main};
}
return "use VMXTemplate::Utils;\n".
"our \$FUNCTIONS = { ".join(", ", map { "$_ => 1" } keys %{$self->{functions}})." };\n".
join("\n", map { $_->{body} } values %{$self->{functions}})
}
package VMXTemplate::Lexer;
# Possible tokens consisting of special characters
my $chartokens = '+ - = * / % ! , . < > ( ) { } [ ] & .. || && == != <= >= =>';
# Reserved keywords
my $keywords_str = 'OR XOR AND NOT IF ELSE ELSIF ELSEIF END SET FOR FOREACH FUNCTION BLOCK MACRO';
sub new
{
my $class = shift;
$class = ref($class) || $class;
my ($options) = @_;
my $self = bless {
options => $options,
# Input
code => '',
eaten => '',
lineno => 0,
# Preprocessed keyword tokens
nchar => {},
lens => [],
keywords => { map { $_ => 1 } split / /, $keywords_str },
# Last directive start position, directive and substitution start/end counters
last_start => 0,
last_start_line => 0,
in_code => 0,
in_subst => 0,
}, $class;
foreach (split(/ /, $chartokens))
{
$self->{nchar}{length($_)}{$_} = 1;
}
# Add code fragment finishing tokens
$self->{nchar}{length($self->{options}->{end_code})}{$self->{options}->{end_code}} = 1;
if ($self->{options}->{end_subst})
{
$self->{nchar}{length($self->{options}->{end_subst})}{$self->{options}->{end_subst}} = 1;
}
# Reverse-sort lengths
$self->{lens} = [ sort { $b <=> $a } keys %{$self->{nchar}} ];
return $self;
}
sub set_code
{
my $self = shift;
my ($code) = @_;
$self->{code} = $code;
$self->{eaten} = '';
$self->{lineno} = $self->{in_code} = $self->{in_subst} = 0;
$self->{last_start} = $self->{last_start_line} = 0;
}
sub eat
{
my $self = shift;
my ($len) = @_;
my $str = substr($self->{code}, 0, $len, '');
$self->{eaten} .= $str;
$self->{lineno} += ($str =~ tr/\n/\n/);
return $str;
}
sub pos
{
my $self = shift;
use bytes;
return length $self->{eaten};
}
sub line
{
my $self = shift;
return $self->{lineno};
}
sub skip_error
{
my ($self) = @_;
$self->{code} = substr($self->{eaten}, $self->{last_start}+1, length($self->{eaten}), '') . $self->{code};
$self->{lineno} = $self->{last_start_line};
$self->{in_code} = $self->{in_subst} = 0;
}
sub read_token
{
my $self = shift;
if (!length $self->{code})
{
# End of code
return;
}
if ($self->{in_code} <= 0 && $self->{in_subst} <= 0)
{
my $r;
my $code_pos = index($self->{code}, $self->{options}->{begin_code});
my $subst_pos = index($self->{code}, $self->{options}->{begin_subst});
if ($code_pos == -1 && $subst_pos == -1)
{
# No more directives
$r = [ 'literal', [ "'".addcslashes($self->eat(length $self->{code}), "'\\")."'", 1 ] ];
}
elsif ($subst_pos == -1 || $code_pos >= 0 && $subst_pos > $code_pos)
{
# Code starts closer
if ($code_pos > 0)
{
# We didn't yet reach the code beginning
my $str = $self->eat($code_pos);
if ($self->{options}->{eat_code_line})
{
$str =~ s/\n[ \t]*$/\n/s;
}
$r = [ 'literal', [ "'".addcslashes($str, "'\\")."'", 1 ] ];
}
else
{
# We are at the code beginning
my $i = length $self->{options}->{begin_code};
if ($self->{code} =~ /^.{$i}([ \t]+)/s)
{
$i += length $1;
}
if ($i < length($self->{code}) && substr($self->{code}, $i, 1) eq '#')
{
# Strip comment and retry
$i = index($self->{code}, $self->{options}->{end_code}, $i);
$i = $i >= 0 ? $i+length($self->{options}->{end_code}) : length $self->{code};
$self->eat($i);
return $self->read_token();
}
$r = [ '', $t);
}
}
elsif ($self->{in_subst})
{
$self->{in_subst}++ if $t eq $self->{options}->{begin_subst};
$self->{in_subst}-- if $t eq $self->{options}->{end_subst};
if (!$self->{in_subst})
{
return ('}}', $t);
}
}
return ($t, undef);
}
}
# Unknown character
$self->warn("Unexpected character '".substr($self->{code}, 0, 1)."'");
return ('error', undef);
}
}
sub errorinfo
{
my $self = shift;
my $linestart = rindex($self->{eaten}, "\n");
my $lineend = index($self->{code}, "\n");
$lineend = length($self->{code}) if $lineend < 0;
my $line = substr($self->{eaten}, $linestart+1) . '^^^' . substr($self->{code}, 0, $lineend);
return ' in '.$self->{options}->{input_filename}.', line '.($self->{lineno}+1).
', byte '.$self->pos.', marked by ^^^ in '.$line;
}
sub warn
{
my $self = shift;
my ($text) = @_;
$self->{options}->error($text.$self->errorinfo());
}
package VMXTemplate::Utils;
use Encode;
use base qw(Exporter);
our @EXPORT = qw(
TS_UNIX TS_DB TS_DB_DATE TS_MW TS_EXIF TS_ORACLE TS_ISO_8601 TS_RFC822
timestamp plural_ru strlimit htmlspecialchars strip_tags strip_unsafe_tags
addcslashes requote quotequote sql_quote regex_replace str_replace
array_slice array_div encode_json trim html_pbr array_items utf8on
exec_subst exec_pairs exec_is_array exec_get exec_cmp
);
use constant {
TS_UNIX => 0,
TS_DB => 1,
TS_DB_DATE => 2,
TS_MW => 3,
TS_EXIF => 4,
TS_ORACLE => 5,
TS_ISO_8601 => 6,
TS_RFC822 => 7,
};
my @Mon = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
my %mon = qw(jan 0 feb 1 mar 2 apr 3 may 4 jun 5 jul 6 aug 7 sep 8 oct 9 nov 10 dec 11);
my @Wday = qw(Sun Mon Tue Wed Thu Fri Sat);
our $safe_tags = 'div|blockquote|span|a|b|i|u|p|h1|h2|h3|h4|h5|h6|strike|strong|small|big|blink|center|ol|pre|sub|sup|font|br|table|tr|td|th|tbody|tfoot|thead|tt|ul|li|em|img|marquee|cite';
# Date parser for some common formats
sub timestamp
{
my ($ts, $format) = @_;
require POSIX;
if (int($ts) eq $ts)
{
# TS_UNIX or Epoch
$ts = time if !$ts;
}
elsif ($ts =~ /^\D*(\d{4,}?)\D*(\d{2})\D*(\d{2})\D*(?:(\d{2})\D*(\d{2})\D*(\d{2})\D*([\+\- ]\d{2}\D*)?)?$/so)
{
# TS_DB, TS_DB_DATE, TS_MW, TS_EXIF, TS_ISO_8601
$ts = POSIX::mktime($6||0, $5||0, $4||0, $3, $2-1, $1-1900);
}
elsif ($ts =~ /^\s*(\d\d?)-(...)-(\d\d(?:\d\d)?)\s*(\d\d)\.(\d\d)\.(\d\d)/so)
{
# TS_ORACLE
$ts = POSIX::mktime($6, $5, $4, int($1), $mon{lc $2}, $3 < 100 ? $3 : $3-1900);
}
elsif ($ts =~ /^\s*..., (\d\d?) (...) (\d{4,}) (\d\d):(\d\d):(\d\d)\s*([\+\- ]\d\d)\s*$/so)
{
# TS_RFC822
$ts = POSIX::mktime($6, $5, $4, int($1), $mon{lc $2}, $3-1900);
}
else
{
# Bogus value, return undef
return undef;
}
if (!$format)
{
# TS_UNIX
return $ts;
}
elsif ($format == TS_MW)
{
return POSIX::strftime("%Y%m%d%H%M%S", localtime($ts));
}
elsif ($format == TS_DB)
{
return POSIX::strftime("%Y-%m-%d %H:%M:%S", localtime($ts));
}
elsif ($format == TS_DB_DATE)
{
return POSIX::strftime("%Y-%m-%d", localtime($ts));
}
elsif ($format == TS_ISO_8601)
{
return POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", localtime($ts));
}
elsif ($format == TS_EXIF)
{
return POSIX::strftime("%Y:%m:%d %H:%M:%S", localtime($ts));
}
elsif ($format == TS_RFC822)
{
my @l = localtime($ts);
return POSIX::strftime($Wday[$l[6]].", %d ".$Mon[$l[4]]." %Y %H:%M:%S %z", @l);
}
elsif ($format == TS_ORACLE)
{
my @l = localtime($ts);
return POSIX::strftime("%d-".$Mon[$l[4]]."-%Y %H.%M.%S %p", @l);
}
return $ts;
}
# Select one of 3 plural forms for russian language
sub plural_ru
{
my ($count, $one, $few, $many) = @_;
my $sto = $count % 100;
if ($sto >= 10 && $sto <= 20)
{
return $many;
}
my $r = $count % 10;
if ($r == 1)
{
return $one;
}
elsif ($r >= 2 && $r <= 4)
{
return $few;
}
return $many;
}
# Limit string to $maxlen
sub strlimit
{
my ($str, $maxlen, $dots) = @_;
if (!$maxlen || $maxlen < 1 || length($str) <= $maxlen)
{
return $str;
}
$str = substr($str, 0, $maxlen);
my $p = rindex($str, ' ');
if ($p < 0 || (my $pt = rindex($str, "\t")) > $p)
{
$p = $pt;
}
if ($p > 0)
{
$str = substr($str, 0, $p);
}
return $str . (defined $dots ? $dots : '...');
}
# Escape HTML special chars
sub htmlspecialchars
{
local $_ = $_[0];
s/&/&/gso;
s/</gso;
s/>/>/gso;
s/\"/"/gso;
s/\'/'/gso;
return $_;
}
# Replace (some) tags with whitespace
sub strip_tags
{
my ($str, $allowed) = @_;
my $allowed = $allowed ? '(?!/?('.$allowed.'))' : '';
$str =~ s/(<$allowed\/?[a-z][a-z0-9-]*(\s+[^<>]*)?>\s*)+/ /gis;
return $str;
}
# Strip unsafe tags
sub strip_unsafe_tags
{
return strip_tags($_[0], $safe_tags);
}
# Add '\' before specified chars
sub addcslashes
{
my ($str, $escape) = @_;
$str =~ s/([$escape])/\\$1/gs;
return $str;
}
# Quote regexp-special characters in $_[0]
sub requote
{
"\Q$_[0]\E";
}
# Escape quotes in C style, also \n and \r
sub quotequote
{
my ($a) = @_;
$a =~ s/[\\\'\"]/\\$&/gso;
$a =~ s/\n/\\n/gso;
$a =~ s/\r/\\r/gso;
return $a;
}
# Escape quotes in SQL or CSV style (" --> "")
sub sql_quote
{
my ($a) = @_;
$a =~ s/\"/\"\"/gso;
return $a;
}
# Replace regular expression, returning result
sub regex_replace
{
my ($re, $repl, $s) = @_;
$re = qr/$re/s if !ref $re;
# Escape \ @ $ % /, but allow $n replacements ($1 $2 $3 ...)
$repl =~ s!([\\\@\%/]|\$(?\!\d))!\\$1!gso;
eval("\$s =~ s/\$re/$repl/gs");
return $s;
}
# Replace strings
sub str_replace
{
my ($str, $repl, $s) = @_;
$s =~ s/\Q$str\E/$repl/gs;
return $s;
}
# extract elements from array
# array_slice([], 0, 10)
# array_slice([], 2)
# array_slice([], 0, -1)
sub array_slice
{
my ($array, $from, $to) = @_;
return $array unless $from;
$to ||= 0;
$from += @$array if $from < 0;
$to += @$array if $to <= 0;
return [ @$array[$from..$to] ];
}
# extract each $div'th element from array, starting with $mod
# array_div([], 2)
# array_div([], 2, 1)
sub array_div
{
my ($array, $div, $mod) = @_;
return $array unless $div;
$mod ||= 0;
return [ @$array[grep { $_ % $div == $mod } 0..$#$array] ];
}
# JSON encoding
sub encode_json
{
require JSON;
*encode_json = *JSON::encode_json;
goto &JSON::encode_json;
}
# Remove whitespace from the beginning and the end of the line
sub trim
{
local $_ = $_[0];
if ($_[1])
{
s/^$_[1]//s;
s/$_[1]$//s;
}
else
{
s/^\s+//so;
s/\s+$//so;
}
$_;
}
# htmlspecialchars + turn \n into
sub html_pbr
{
my ($s) = @_;
$s = htmlspecialchars($s);
$s =~ s/\n/
/gso;
return $s;
}
# helper - returns array elements or just scalar, if it's not an arrayref
sub array_items
{
ref($_[0]) && $_[0] =~ /ARRAY/ ? @{$_[0]} : (defined $_[0] ? ($_[0]) : ());
}
# recursive utf8_on and return result
sub utf8on
{
if (ref($_[0]) && $_[0] =~ /HASH/so)
{
utf8on($_[0]->{$_}) for keys %{$_[0]};
}
elsif (ref($_[0]) && $_[0] =~ /ARRAY/so)
{
utf8on($_) for @{$_[0]};
}
else
{
Encode::_utf8_on($_[0]);
}
return $_[0];
}
# function subst()
sub exec_subst
{
my $str = shift;
$str =~ s/(? ..., value => ... }, ... ]
sub exec_pairs
{
my $hash = shift;
return [ map { { key => $_, value => $hash->{$_} } } sort keys %{ $hash || {} } ];
}
# check if the argument is an arrayref
sub exec_is_array
{
return ref $_[1] && $_[1] =~ /ARRAY/;
}
# get array or hash element
sub exec_get
{
defined $_[1] && ref $_[0] || return $_[0];
$_[0] =~ /ARRAY/ && return $_[0]->[$_[1]];
return $_[0]->{$_[1]};
}
# type-dependent comparison
sub exec_cmp
{
my ($a, $b) = @_;
my $n = grep /^-?\d+(\.\d+)?$/, $a, $b;
return $n ? $a <=> $b : $a cmp $b;
}
package VMXTemplate::Exception;
sub new
{
my $class = shift;
$class = ref($class) || $class;
my ($msg) = @_;
return bless { message => $msg }, $class;
}
package VMXTemplate::Options;
VMXTemplate::Utils::import();
sub new
{
my $class = shift;
$class = ref($class) || $class;
my ($options) = @_;
my $self = bless {
begin_code => '', # instruction end
begin_subst => '{', # substitution start (set to '' to turn off)
end_subst => '}', # substitution end (set to '' to turn off)
no_code_subst => 0, # only evaluate instructions, but ignore their results
eat_code_line => 1, # remove the "extra" lines which contain instructions only
root => '.', # directory with templates
cache_dir => undef, # compiled templates cache directory
reload => 1, # 0 means to not check for new versions of cached templates
filters => [], # filters to run on output of every template
use_utf8 => 1, # use UTF-8 for all string operations on template variables
raise_error => 0, # die() on fatal template errors
log_error => 0, # send errors to standard error output
print_error => 0, # print fatal template errors
strip_space => 0, # strip spaces from beginning and end of each line
auto_escape => undef, # "safe mode" (use 's' for HTML) - automatically escapes substituted
# values via this functions if not escaped explicitly
compiletime_functions => {},# custom compile-time functions (code generators)
input_filename => '',
errors => [],
}, $class;
$self->set($options);
return $self;
}
sub set
{
my ($self, $options) = @_;
for (keys %$options)
{
if (exists $self->{$_} && $_ ne 'errors')
{
$self->{$_} = $options->{$_};
}
}
$self->{filters} = [] if ref $self->{filters} ne 'ARRAY';
if ($self->{strip_space} && !grep { $_ eq 'strip_space' } @{$self->{filters}})
{
push @{$self->{filters}}, 'strip_space';
}
if (!$self->{begin_subst} || !$self->{end_subst})
{
$self->{begin_subst} = undef;
$self->{end_subst} = undef;
$self->{no_code_subst} = 0;
}
$self->{cache_dir} =~ s!/*$!/!so;
if (!-w $self->{cache_dir})
{
die new VMXTemplate::Exception('VMXTemplate: cache_dir='.$self->{cache_dir}.' is not writable');
}
$self->{root} =~ s!/*$!/!so;
}
sub get_errors
{
my ($self) = @_;
if ($self->{print_error} && @{$self->{errors}})
{
return '