#!/usr/bin/perl -pw
# written for use with S9Y smarty replacement
# expects already extract()ed $tpl array in current var namespace
#-- lets first unify $variables.index/$CONST into php syntax:
# some are called twice to catch multiple instances in a single smarty tag
s/(\{[^}]*)\$CONST.(\w+)([^}]*})/$1\@$2$3/g;
s/(\{[^}]*)\$CONST.(\w+)([^}]*})/$1\@$2$3/g; # optional, we had $CONST as local array anyhow
s/(\{[^}]*)\$(\w+)\.(\w+)([^}]*})/$1\$$2\['$3'\]$4/g;
s/(\{[^}]*)\$(\w+)\.(\w+)([^}]*})/$1\$$2\['$3'\]$4/g;
s/(\{[^}]*)\$(\w+)\.(\w+)([^}]*})/$1\$$2\['$3'\]$4/g;
s/(\{[^}]*)\$(\w+)\.(\w+)\.(\w+)([^}]*})/$1\$$2\['$3'\]\['$4'\]$5/g;
$VAR = "[\\\$\\@][\\w\\[\\]\\']+"; # shortcut for further regexs
#-- s9y
s/\{serendipity_hookPlugin hook="(\w+)"}/<? serendipity_plugin_api::hook_event('$1', \$GLOBALS\['template'\]); ?>/;
s/\{serendipity_printSidebar side="(\w+)"}/<? echo serendipity_plugin_api::generate_plugins('$1'); ?>/;
s/\{serendipity_printComments entry=($VAR) mode=($VAR)}/<? echo serendipity_smarty_printComments(array('entry'=>$1, 'mode'=>$2, \$this)); ?>/;
$PARAM = '(\w+)="(\$?\w+)"';
s/\{serendipity_(\w+) +$PARAM(?: +$PARAM)* *}/<?= serendipity_smarty_$1(array('$2'=>"$3", '$4'=>"$5", '$6'=>"$7"), \$this); ?>/g;
#-- variables
s/\{($VAR) *}/<?= $1 ?>/g;
s/\{($VAR) *\| *\@default\:($VAR|\w+) *}/<?= isset($1) ? ($1) : ($2) ?>/g; # ???
#-- variables with functions, just a basic set here, and no chain handling
s/\{($VAR) *\| *\@formatTime\:($VAR|\w+) *}/<?= strftime($2, $1) ?>/g;
s/\{($VAR) *\| *\@sprintf\:($VAR|\w+) *}/<?= sprintf($2, $1) ?>/g;
s/\{($VAR) *\| *\@(makeFilename) *}/<?= serendipity_makeFilename($1) ?>/g;
#s/\{($VAR) *\| *\@(\w+) *}/<?= smarty_$2($1) ?>/g; # other plain functions ???
#-- if blocks
s/(\{\w*if[^}]+)( not )([^}]+})/ ! /g;
s/(\{\w*if[^}]+)( and )([^}]+})/ && /g;
s/(\{\w*if[^}]+)( or )([^}]+})/ || /g;
s/\{if +(.+?) *}/<? if ($1): ?>/g; # more difficult expressions need rework
s/\{else?if +(.+?) *}/<? elseif ($1): ?>/g;
s/\{else *}/<? else: ?>/g;
s/\{\/if *}/<? endif; ?>/g;
#-- foreach blocks
s/\{foreach +from=($VAR) +item="?(\w+)"? key="(\w+)"( [\w="]+)* *}/<? if (count($1)) foreach ($1 as \$$3 => \$$2) \{\{ \$_foreach++; ?>/;
s/\{foreach +from=($VAR) +item="?(\w+)"?( [\w="]+)* *}/<? if (count($1)) foreach ($1 as \$$2) \{\{ \$_foreach++; ?>/;
#s/\{foreach +from=($VAR) +item="?(\w+)\.(\w+)"?.*?}/<? foreach ($1 as \$$2\['$3'\]) \{\{ ?>/;
s/\{foreachelse *}/<? \}\} else \{\{ #foreachelse ?>/g;
s/\{\/foreach *}/<? \}\} #endforeach ?>/g;
s/\{cycle +values="(.+?)" *}/<? \$_cycle = split(", *", "$1"); echo \$_cycle[\$_foreach \% count(\$_cycle)]; \{\{ ?>/;