Commit 1e246992 by Seldaek

git-svn-id: svn://dwoo.org/dwoo/trunk@80 0598d79b-80c4-4d41-97ba-ac86fbbd088b

parent e1e75fed
[2008--] 0.9.2
* Converted most of the code to follow PEAR Coding Standards, hopefully this
didn't break anything that the tests missed
[2008-05-30] 0.9.1 [2008-05-30] 0.9.1
+ API: Added Dwoo_Compiler->setAutoEscape() and getAutoEscape() to modify the + API: Added Dwoo_Compiler->setAutoEscape() and getAutoEscape() to modify the
automatic html entity escaping setting. This is disabled by default, and when automatic html entity escaping setting. This is disabled by default, and when
......
...@@ -47,17 +47,14 @@ class Dwoo_Data implements Dwoo_IDataProvider ...@@ -47,17 +47,14 @@ class Dwoo_Data implements Dwoo_IDataProvider
*/ */
public function clear($name = null) public function clear($name = null)
{ {
if($name === null) if ($name === null) {
{
$this->data = array(); $this->data = array();
} } elseif (is_array($name)) {
elseif(is_array($name)) foreach ($name as $index)
{
foreach($name as $index)
unset($this->data[$index]); unset($this->data[$index]);
} } else {
else
unset($this->data[$name]); unset($this->data[$name]);
}
} }
/** /**
...@@ -79,9 +76,10 @@ class Dwoo_Data implements Dwoo_IDataProvider ...@@ -79,9 +76,10 @@ class Dwoo_Data implements Dwoo_IDataProvider
public function mergeData(array $data) public function mergeData(array $data)
{ {
$args = func_get_args(); $args = func_get_args();
while(list(,$v) = each($args)) while (list(,$v) = each($args))
if(is_array($v)) if (is_array($v)) {
$this->data = array_merge($this->data, $v); $this->data = array_merge($this->data, $v);
}
} }
/** /**
...@@ -94,14 +92,13 @@ class Dwoo_Data implements Dwoo_IDataProvider ...@@ -94,14 +92,13 @@ class Dwoo_Data implements Dwoo_IDataProvider
*/ */
public function assign($name, $val = null) public function assign($name, $val = null)
{ {
if(is_array($name)) if (is_array($name)) {
{
reset($name); reset($name);
while(list($k,$v) = each($name)) while (list($k,$v) = each($name))
$this->data[$k] = $v; $this->data[$k] = $v;
} } else {
else
$this->data[$name] = $val; $this->data[$name] = $val;
}
} }
/** /**
...@@ -127,28 +124,31 @@ class Dwoo_Data implements Dwoo_IDataProvider ...@@ -127,28 +124,31 @@ class Dwoo_Data implements Dwoo_IDataProvider
*/ */
public function append($name, $val = null, $merge = false) public function append($name, $val = null, $merge = false)
{ {
if(is_array($name)) if (is_array($name))
{ {
foreach($name as $key=>$val) foreach ($name as $key=>$val) {
{ if (isset($this->data[$key]) && !is_array($this->data[$key])) {
if(isset($this->data[$key]) && !is_array($this->data[$key]))
settype($this->data[$key], 'array'); settype($this->data[$key], 'array');
}
if($merge === true && is_array($val)) if ($merge === true && is_array($val)) {
$this->data[$key] = $val + $this->data[$key]; $this->data[$key] = $val + $this->data[$key];
else } else {
$this->data[$key][] = $val; $this->data[$key][] = $val;
}
} }
} }
elseif($val !== null) elseif ($val !== null)
{ {
if(isset($this->data[$name]) && !is_array($this->data[$name])) if (isset($this->data[$name]) && !is_array($this->data[$name])) {
settype($this->data[$name], 'array'); settype($this->data[$name], 'array');
}
if($merge === true && is_array($val)) if ($merge === true && is_array($val)) {
$this->data[$name] = $val + $this->data[$name]; $this->data[$name] = $val + $this->data[$name];
else } else {
$this->data[$name][] = $val; $this->data[$name][] = $val;
}
} }
} }
...@@ -162,12 +162,13 @@ class Dwoo_Data implements Dwoo_IDataProvider ...@@ -162,12 +162,13 @@ class Dwoo_Data implements Dwoo_IDataProvider
*/ */
public function appendByRef($name, &$val, $merge = false) public function appendByRef($name, &$val, $merge = false)
{ {
if(isset($this->data[$name]) && !is_array($this->data[$name])) if (isset($this->data[$name]) && !is_array($this->data[$name])) {
settype($this->data[$name], 'array'); settype($this->data[$name], 'array');
}
if($merge === true && is_array($val)) if ($merge === true && is_array($val))
{ {
foreach($val as $key => &$val) foreach ($val as $key => &$val)
$this->data[$name][$key] =& $val; $this->data[$name][$key] =& $val;
} }
else else
......
...@@ -48,7 +48,7 @@ class Dwoo_Loader ...@@ -48,7 +48,7 @@ class Dwoo_Loader
*/ */
public static function rebuildClassPathCache($path, $cacheFile) public static function rebuildClassPathCache($path, $cacheFile)
{ {
if($cacheFile!==false) if ($cacheFile!==false)
{ {
$tmp = self::$classpath; $tmp = self::$classpath;
self::$classpath = array(); self::$classpath = array();
...@@ -56,19 +56,19 @@ class Dwoo_Loader ...@@ -56,19 +56,19 @@ class Dwoo_Loader
// iterates over all files/folders // iterates over all files/folders
$list = glob($path.DIRECTORY_SEPARATOR.'*'); $list = glob($path.DIRECTORY_SEPARATOR.'*');
if(is_array($list)) if (is_array($list))
foreach($list as $f) foreach ($list as $f)
{ {
if(is_dir($f)) if (is_dir($f))
self::rebuildClassPathCache($f, false); self::rebuildClassPathCache($f, false);
else else
self::$classpath[str_replace(array('function.','block.','modifier.','outputfilter.','filter.','prefilter.','postfilter.','pre.','post.','output.','shared.','helper.'), '', basename($f,'.php'))] = $f; self::$classpath[str_replace(array('function.','block.','modifier.','outputfilter.','filter.','prefilter.','postfilter.','pre.','post.','output.','shared.','helper.'), '', basename($f,'.php'))] = $f;
} }
// save in file if it's the first call (not recursed) // save in file if it's the first call (not recursed)
if($cacheFile!==false) if ($cacheFile!==false)
{ {
if(!file_put_contents($cacheFile, '<?php Dwoo_Loader::$classpath = '.var_export(self::$classpath, true).' + Dwoo_Loader::$classpath; ?>')) if (!file_put_contents($cacheFile, '<?php Dwoo_Loader::$classpath = '.var_export(self::$classpath, true).' + Dwoo_Loader::$classpath; ?>'))
throw new Dwoo_Exception('Could not write into '.$cacheFile.', either because the folder is not there (create it) or because of the chmod configuration (please ensure this directory is writable by php)'); throw new Dwoo_Exception('Could not write into '.$cacheFile.', either because the folder is not there (create it) or because of the chmod configuration (please ensure this directory is writable by php)');
self::$classpath += $tmp; self::$classpath += $tmp;
} }
...@@ -83,14 +83,14 @@ class Dwoo_Loader ...@@ -83,14 +83,14 @@ class Dwoo_Loader
public static function loadPlugin($class, $forceRehash = true) public static function loadPlugin($class, $forceRehash = true)
{ {
// a new class was added or the include failed so we rebuild the cache // a new class was added or the include failed so we rebuild the cache
if(!isset(self::$classpath[$class]) || !include self::$classpath[$class]) if (!isset(self::$classpath[$class]) || !include self::$classpath[$class])
{ {
if($forceRehash) if ($forceRehash)
{ {
self::rebuildClassPathCache(DWOO_DIRECTORY . 'plugins', DWOO_COMPILE_DIRECTORY . DIRECTORY_SEPARATOR . 'classpath.cache.php'); self::rebuildClassPathCache(DWOO_DIRECTORY . 'plugins', DWOO_COMPILE_DIRECTORY . DIRECTORY_SEPARATOR . 'classpath.cache.php');
foreach(self::$paths as $path=>$file) foreach (self::$paths as $path=>$file)
self::rebuildClassPathCache($path, $file); self::rebuildClassPathCache($path, $file);
if(isset(self::$classpath[$class])) if (isset(self::$classpath[$class]))
include self::$classpath[$class]; include self::$classpath[$class];
else else
throw new Dwoo_Exception('Plugin <em>'.$class.'</em> can not be found, maybe you forgot to bind it if it\'s a custom plugin ?', E_USER_NOTICE); throw new Dwoo_Exception('Plugin <em>'.$class.'</em> can not be found, maybe you forgot to bind it if it\'s a custom plugin ?', E_USER_NOTICE);
...@@ -114,11 +114,11 @@ class Dwoo_Loader ...@@ -114,11 +114,11 @@ class Dwoo_Loader
*/ */
public static function addDirectory($pluginDir) public static function addDirectory($pluginDir)
{ {
if(!isset(self::$paths[$pluginDir])) if (!isset(self::$paths[$pluginDir]))
{ {
$cacheFile = DWOO_COMPILE_DIRECTORY . DIRECTORY_SEPARATOR . 'classpath-'.substr(strtr($pluginDir, ':/\\.', '----'), strlen($pluginDir) > 80 ? -80 : 0).'.cache.php'; $cacheFile = DWOO_COMPILE_DIRECTORY . DIRECTORY_SEPARATOR . 'classpath-'.substr(strtr($pluginDir, ':/\\.', '----'), strlen($pluginDir) > 80 ? -80 : 0).'.cache.php';
self::$paths[$pluginDir] = $cacheFile; self::$paths[$pluginDir] = $cacheFile;
if(file_exists($cacheFile)) if (file_exists($cacheFile))
include $cacheFile; include $cacheFile;
else else
Dwoo_Loader::rebuildClassPathCache($pluginDir, $cacheFile); Dwoo_Loader::rebuildClassPathCache($pluginDir, $cacheFile);
......
...@@ -88,8 +88,8 @@ class Dwoo_Security_Policy ...@@ -88,8 +88,8 @@ class Dwoo_Security_Policy
*/ */
public function allowPhpFunction($func) public function allowPhpFunction($func)
{ {
if(is_array($func)) if (is_array($func))
foreach($func as $fname) foreach ($func as $fname)
$this->allowedPhpFunctions[strtolower($fname)] = true; $this->allowedPhpFunctions[strtolower($fname)] = true;
else else
$this->allowedPhpFunctions[strtolower($func)] = true; $this->allowedPhpFunctions[strtolower($func)] = true;
...@@ -102,8 +102,8 @@ class Dwoo_Security_Policy ...@@ -102,8 +102,8 @@ class Dwoo_Security_Policy
*/ */
public function disallowPhpFunction($func) public function disallowPhpFunction($func)
{ {
if(is_array($func)) if (is_array($func))
foreach($func as $fname) foreach ($func as $fname)
unset($this->allowedPhpFunctions[strtolower($fname)]); unset($this->allowedPhpFunctions[strtolower($fname)]);
else else
unset($this->allowedPhpFunctions[strtolower($func)]); unset($this->allowedPhpFunctions[strtolower($func)]);
...@@ -127,8 +127,8 @@ class Dwoo_Security_Policy ...@@ -127,8 +127,8 @@ class Dwoo_Security_Policy
*/ */
public function allowDirectory($path) public function allowDirectory($path)
{ {
if(is_array($path)) if (is_array($path))
foreach($path as $dir) foreach ($path as $dir)
$this->allowedDirectories[realpath($dir)] = true; $this->allowedDirectories[realpath($dir)] = true;
else else
$this->allowedDirectories[realpath($path)] = true; $this->allowedDirectories[realpath($path)] = true;
...@@ -141,8 +141,8 @@ class Dwoo_Security_Policy ...@@ -141,8 +141,8 @@ class Dwoo_Security_Policy
*/ */
public function disallowDirectory($path) public function disallowDirectory($path)
{ {
if(is_array($path)) if (is_array($path))
foreach($path as $dir) foreach ($path as $dir)
unset($this->allowedDirectories[realpath($dir)]); unset($this->allowedDirectories[realpath($dir)]);
else else
unset($this->allowedDirectories[realpath($path)]); unset($this->allowedDirectories[realpath($path)]);
......
...@@ -47,13 +47,11 @@ class Dwoo_Template_File extends Dwoo_Template_String ...@@ -47,13 +47,11 @@ class Dwoo_Template_File extends Dwoo_Template_String
$this->name = basename($file); $this->name = basename($file);
$this->cacheTime = $cacheTime; $this->cacheTime = $cacheTime;
if($compileId !== null) if ($compileId !== null) {
{
$this->compileId = strtr($compileId, '\\%?=!:;'.PATH_SEPARATOR, '/-------'); $this->compileId = strtr($compileId, '\\%?=!:;'.PATH_SEPARATOR, '/-------');
} }
if($cacheId !== null) if ($cacheId !== null) {
{
$this->cacheId = strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------'); $this->cacheId = strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------');
} }
} }
...@@ -70,12 +68,10 @@ class Dwoo_Template_File extends Dwoo_Template_String ...@@ -70,12 +68,10 @@ class Dwoo_Template_File extends Dwoo_Template_String
$compiledFile = $this->getCompiledFilename($dwoo); $compiledFile = $this->getCompiledFilename($dwoo);
// already checked, return compiled file // already checked, return compiled file
if($this->compilationEnforced !== true && isset(self::$cache['compiled'][$this->compileId]) === true) if ($this->compilationEnforced !== true && isset(self::$cache['compiled'][$this->compileId]) === true) {
{
} }
// template is compiled and has not been modified since the compilation // template is compiled and has not been modified since the compilation
elseif($this->compilationEnforced !== true && file_exists($compiledFile)===true && filemtime($this->file) <= filemtime($compiledFile)) elseif ($this->compilationEnforced !== true && file_exists($compiledFile)===true && filemtime($this->file) <= filemtime($compiledFile)) {
{
self::$cache['compiled'][$this->compileId] = true; self::$cache['compiled'][$this->compileId] = true;
} }
// compiles the template // compiles the template
...@@ -83,18 +79,17 @@ class Dwoo_Template_File extends Dwoo_Template_String ...@@ -83,18 +79,17 @@ class Dwoo_Template_File extends Dwoo_Template_String
{ {
$this->compilationEnforced = false; $this->compilationEnforced = false;
if($compiler === null) if ($compiler === null) {
{
$compiler = $dwoo->getDefaultCompilerFactory('string'); $compiler = $dwoo->getDefaultCompilerFactory('string');
if($compiler === null || $compiler === array('Dwoo_Compiler', 'compilerFactory')) if ($compiler === null || $compiler === array('Dwoo_Compiler', 'compilerFactory')) {
{ if (class_exists('Dwoo_Compiler', false) === false) {
if(class_exists('Dwoo_Compiler', false) === false)
include 'Dwoo/Compiler.php'; include 'Dwoo/Compiler.php';
}
$compiler = Dwoo_Compiler::compilerFactory(); $compiler = Dwoo_Compiler::compilerFactory();
} } else {
else
$compiler = call_user_func($compiler); $compiler = call_user_func($compiler);
}
} }
$this->compiler = $compiler; $this->compiler = $compiler;
...@@ -171,25 +166,24 @@ class Dwoo_Template_File extends Dwoo_Template_String ...@@ -171,25 +166,24 @@ class Dwoo_Template_File extends Dwoo_Template_String
public static function templateFactory(Dwoo $dwoo, $resourceId, $cacheTime = null, $cacheId = null, $compileId = null) public static function templateFactory(Dwoo $dwoo, $resourceId, $cacheTime = null, $cacheId = null, $compileId = null)
{ {
$resourceId = str_replace(array("\t", "\n", "\r"), array('\\t', '\\n', '\\r'), $resourceId); $resourceId = str_replace(array("\t", "\n", "\r"), array('\\t', '\\n', '\\r'), $resourceId);
if(file_exists($resourceId) === false) if (file_exists($resourceId) === false) {
{
$tpl = $dwoo->getTemplate(); $tpl = $dwoo->getTemplate();
if($tpl instanceof Dwoo_Template_File) if ($tpl instanceof Dwoo_Template_File) {
{
$resourceId = dirname($tpl->getResourceIdentifier()).DIRECTORY_SEPARATOR.$resourceId; $resourceId = dirname($tpl->getResourceIdentifier()).DIRECTORY_SEPARATOR.$resourceId;
if(file_exists($resourceId) === false) if (file_exists($resourceId) === false) {
return null; return null;
} }
else } else {
return null; return null;
}
} }
// prevent template recursion if security is in effect // prevent template recursion if security is in effect
if($policy = $dwoo->getSecurityPolicy()) if ($policy = $dwoo->getSecurityPolicy()) {
{
$tpl = $dwoo->getTemplate(); $tpl = $dwoo->getTemplate();
if($tpl instanceof Dwoo_Template_File && $resourceId === $tpl->getResourceIdentifier()) if ($tpl instanceof Dwoo_Template_File && $resourceId === $tpl->getResourceIdentifier()) {
return $dwoo->triggerError('You can not include a template into itself', E_USER_WARNING); return $dwoo->triggerError('You can not include a template into itself', E_USER_WARNING);
}
} }
return new Dwoo_Template_File($resourceId, $cacheTime, $cacheId, $compileId); return new Dwoo_Template_File($resourceId, $cacheTime, $cacheId, $compileId);
...@@ -205,8 +199,7 @@ class Dwoo_Template_File extends Dwoo_Template_String ...@@ -205,8 +199,7 @@ class Dwoo_Template_File extends Dwoo_Template_String
protected function getCompiledFilename(Dwoo $dwoo) protected function getCompiledFilename(Dwoo $dwoo)
{ {
// no compile id was provided, set default // no compile id was provided, set default
if($this->compileId===null) if ($this->compileId===null) {
{
$this->compileId = implode('/', array_slice(explode('/', strtr($this->file, '\\', '/')), -3)); $this->compileId = implode('/', array_slice(explode('/', strtr($this->file, '\\', '/')), -3));
} }
return $dwoo->getCompileDir() . $this->compileId.'.d'.Dwoo::RELEASE_TAG.'.php'; return $dwoo->getCompileDir() . $this->compileId.'.d'.Dwoo::RELEASE_TAG.'.php';
......
...@@ -99,13 +99,11 @@ class Dwoo_Template_String implements Dwoo_ITemplate ...@@ -99,13 +99,11 @@ class Dwoo_Template_String implements Dwoo_ITemplate
$this->name = hash('md4', $templateString); $this->name = hash('md4', $templateString);
$this->cacheTime = $cacheTime; $this->cacheTime = $cacheTime;
if($compileId !== null) if ($compileId !== null) {
{
$this->compileId = strtr($compileId, '\\%?=!:;'.PATH_SEPARATOR, '/-------'); $this->compileId = strtr($compileId, '\\%?=!:;'.PATH_SEPARATOR, '/-------');
} }
if($cacheId !== null) if ($cacheId !== null) {
{
$this->cacheId = strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------'); $this->cacheId = strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------');
} }
} }
...@@ -218,24 +216,22 @@ class Dwoo_Template_String implements Dwoo_ITemplate ...@@ -218,24 +216,22 @@ class Dwoo_Template_String implements Dwoo_ITemplate
public function getCachedTemplate(Dwoo $dwoo) public function getCachedTemplate(Dwoo $dwoo)
{ {
$cachedFile = $this->getCacheFilename($dwoo); $cachedFile = $this->getCacheFilename($dwoo);
if($this->cacheTime !== null) if ($this->cacheTime !== null) {
$cacheLength = $this->cacheTime; $cacheLength = $this->cacheTime;
else } else {
$cacheLength = $dwoo->getCacheTime(); $cacheLength = $dwoo->getCacheTime();
}
// file is not cacheable // file is not cacheable
if($cacheLength === 0) if ($cacheLength === 0) {
{
return false; return false;
} }
// already checked, return cache file // already checked, return cache file
if(isset(self::$cache['cached'][$this->cacheId]) === true && file_exists($cachedFile)) if (isset(self::$cache['cached'][$this->cacheId]) === true && file_exists($cachedFile)) {
{
return $cachedFile; return $cachedFile;
} }
// cache is still valid and can be loaded // cache is still valid and can be loaded
elseif($this->compilationEnforced !== true && file_exists($cachedFile) && ($cacheLength === -1 || filemtime($cachedFile) > ($_SERVER['REQUEST_TIME'] - $cacheLength))) elseif ($this->compilationEnforced !== true && file_exists($cachedFile) && ($cacheLength === -1 || filemtime($cachedFile) > ($_SERVER['REQUEST_TIME'] - $cacheLength))) {
{
self::$cache['cached'][$this->cacheId] = true; self::$cache['cached'][$this->cacheId] = true;
return $cachedFile; return $cachedFile;
} }
...@@ -260,11 +256,9 @@ class Dwoo_Template_String implements Dwoo_ITemplate ...@@ -260,11 +256,9 @@ class Dwoo_Template_String implements Dwoo_ITemplate
// the code below is courtesy of Rasmus Schultz, // the code below is courtesy of Rasmus Schultz,
// thanks for his help on avoiding concurency issues // thanks for his help on avoiding concurency issues
$temp = tempnam($cacheDir, 'temp'); $temp = tempnam($cacheDir, 'temp');
if(!($file = @fopen($temp, 'wb'))) if (!($file = @fopen($temp, 'wb'))) {
{
$temp = $cacheDir . DIRECTORY_SEPARATOR . uniqid('temp'); $temp = $cacheDir . DIRECTORY_SEPARATOR . uniqid('temp');
if(!($file = @fopen($temp, 'wb'))) if (!($file = @fopen($temp, 'wb'))) {
{
trigger_error('Error writing temporary file \''.$temp.'\'', E_USER_WARNING); trigger_error('Error writing temporary file \''.$temp.'\'', E_USER_WARNING);
return false; return false;
} }
...@@ -274,8 +268,7 @@ class Dwoo_Template_String implements Dwoo_ITemplate ...@@ -274,8 +268,7 @@ class Dwoo_Template_String implements Dwoo_ITemplate
fclose($file); fclose($file);
$this->makeDirectory(dirname($cachedFile)); $this->makeDirectory(dirname($cachedFile));
if(!@rename($temp, $cachedFile)) if (!@rename($temp, $cachedFile)) {
{
@unlink($cachedFile); @unlink($cachedFile);
@rename($temp, $cachedFile); @rename($temp, $cachedFile);
} }
...@@ -313,12 +306,10 @@ class Dwoo_Template_String implements Dwoo_ITemplate ...@@ -313,12 +306,10 @@ class Dwoo_Template_String implements Dwoo_ITemplate
$compiledFile = $this->getCompiledFilename($dwoo); $compiledFile = $this->getCompiledFilename($dwoo);
// already checked, return compiled file // already checked, return compiled file
if($this->compilationEnforced !== true && isset(self::$cache['compiled'][$this->compileId]) === true) if ($this->compilationEnforced !== true && isset(self::$cache['compiled'][$this->compileId]) === true) {
{
} }
// template is compiled // template is compiled
elseif($this->compilationEnforced !== true && file_exists($compiledFile)===true) elseif ($this->compilationEnforced !== true && file_exists($compiledFile)===true) {
{
self::$cache['compiled'][$this->compileId] = true; self::$cache['compiled'][$this->compileId] = true;
} }
// compiles the template // compiles the template
...@@ -326,18 +317,17 @@ class Dwoo_Template_String implements Dwoo_ITemplate ...@@ -326,18 +317,17 @@ class Dwoo_Template_String implements Dwoo_ITemplate
{ {
$this->compilationEnforced = false; $this->compilationEnforced = false;
if($compiler === null) if ($compiler === null) {
{
$compiler = $dwoo->getDefaultCompilerFactory('string'); $compiler = $dwoo->getDefaultCompilerFactory('string');
if($compiler === null || $compiler === array('Dwoo_Compiler', 'compilerFactory')) if ($compiler === null || $compiler === array('Dwoo_Compiler', 'compilerFactory')) {
{ if (class_exists('Dwoo_Compiler', false) === false) {
if(class_exists('Dwoo_Compiler', false) === false)
include 'Dwoo/Compiler.php'; include 'Dwoo/Compiler.php';
}
$compiler = Dwoo_Compiler::compilerFactory(); $compiler = Dwoo_Compiler::compilerFactory();
} } else {
else
$compiler = call_user_func($compiler); $compiler = call_user_func($compiler);
}
} }
$this->compiler = $compiler; $this->compiler = $compiler;
...@@ -383,8 +373,7 @@ class Dwoo_Template_String implements Dwoo_ITemplate ...@@ -383,8 +373,7 @@ class Dwoo_Template_String implements Dwoo_ITemplate
protected function getCompiledFilename(Dwoo $dwoo) protected function getCompiledFilename(Dwoo $dwoo)
{ {
// no compile id was provided, set default // no compile id was provided, set default
if($this->compileId===null) if ($this->compileId===null) {
{
$this->compileId = $this->name; $this->compileId = $this->name;
} }
return $dwoo->getCompileDir() . $this->compileId.'.d'.Dwoo::RELEASE_TAG.'.php'; return $dwoo->getCompileDir() . $this->compileId.'.d'.Dwoo::RELEASE_TAG.'.php';
...@@ -400,12 +389,12 @@ class Dwoo_Template_String implements Dwoo_ITemplate ...@@ -400,12 +389,12 @@ class Dwoo_Template_String implements Dwoo_ITemplate
protected function getCacheFilename(Dwoo $dwoo) protected function getCacheFilename(Dwoo $dwoo)
{ {
// no cache id provided, use request_uri as default // no cache id provided, use request_uri as default
if($this->cacheId === null) if ($this->cacheId === null) {
{ if (isset($_SERVER['REQUEST_URI']) === true) {
if(isset($_SERVER['REQUEST_URI']) === true)
$cacheId = $_SERVER['REQUEST_URI']; $cacheId = $_SERVER['REQUEST_URI'];
elseif(isset($_SERVER['SCRIPT_FILENAME']) && isset($_SERVER['argv'])) } elseif (isset($_SERVER['SCRIPT_FILENAME']) && isset($_SERVER['argv'])) {
$cacheId = $_SERVER['SCRIPT_FILENAME'].'-'.implode('-', $_SERVER['argv']); $cacheId = $_SERVER['SCRIPT_FILENAME'].'-'.implode('-', $_SERVER['argv']);
}
$this->cacheId = strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------'); $this->cacheId = strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------');
} }
return $dwoo->getCacheDir() . $this->cacheId.'.html'; return $dwoo->getCacheDir() . $this->cacheId.'.html';
...@@ -418,8 +407,9 @@ class Dwoo_Template_String implements Dwoo_ITemplate ...@@ -418,8 +407,9 @@ class Dwoo_Template_String implements Dwoo_ITemplate
*/ */
protected function makeDirectory($path) protected function makeDirectory($path)
{ {
if(is_dir($path) === true) if (is_dir($path) === true) {
return; return;
}
mkdir($path, DWOO_CHMOD, true); mkdir($path, DWOO_CHMOD, true);
} }
......
...@@ -32,8 +32,7 @@ class Dwoo_Plugin_auto_escape extends Dwoo_Block_Plugin implements Dwoo_ICompila ...@@ -32,8 +32,7 @@ class Dwoo_Plugin_auto_escape extends Dwoo_Block_Plugin implements Dwoo_ICompila
public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend='', $append='', $type) public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend='', $append='', $type)
{ {
$params = $compiler->getCompiledParams($params); $params = $compiler->getCompiledParams($params);
switch(strtolower(trim((string) $params['enabled'], '"\''))) switch(strtolower(trim((string) $params['enabled'], '"\''))) {
{
case 'on': case 'on':
case 'true': case 'true':
case 'enabled': case 'enabled':
......
...@@ -52,10 +52,10 @@ class Dwoo_Plugin_capture extends Dwoo_Block_Plugin implements Dwoo_ICompilable_ ...@@ -52,10 +52,10 @@ class Dwoo_Plugin_capture extends Dwoo_Block_Plugin implements Dwoo_ICompilable_
$params = $compiler->getCompiledParams($params); $params = $compiler->getCompiledParams($params);
$out = Dwoo_Compiler::PHP_OPEN.$prepend."\n".'$tmp = ob_get_clean();'; $out = Dwoo_Compiler::PHP_OPEN.$prepend."\n".'$tmp = ob_get_clean();';
if($params['cat'] === 'true') { if ($params['cat'] === 'true') {
$out .= "\n".'$tmp = $this->readVar(\'dwoo.capture.\'.'.$params['name'].') . $tmp;'; $out .= "\n".'$tmp = $this->readVar(\'dwoo.capture.\'.'.$params['name'].') . $tmp;';
} }
if($params['assign'] !== "null") { if ($params['assign'] !== "null") {
$out .= "\n".'$this->scope['.$params['assign'].'] = $tmp;'; $out .= "\n".'$this->scope['.$params['assign'].'] = $tmp;';
} }
return $out . "\n".'$this->globals[\'capture\']['.$params['name'].'] = $tmp;'.$append.Dwoo_Compiler::PHP_CLOSE; return $out . "\n".'$this->globals[\'capture\']['.$params['name'].'] = $tmp;'.$append.Dwoo_Compiler::PHP_CLOSE;
......
...@@ -42,8 +42,7 @@ class Dwoo_Plugin_else extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Blo ...@@ -42,8 +42,7 @@ class Dwoo_Plugin_else extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Blo
{ {
$block =& $compiler->getCurrentBlock(); $block =& $compiler->getCurrentBlock();
$out = ''; $out = '';
while($block['type'] !== 'if' && $block['type'] !== 'foreach' && $block['type'] !== 'for' && $block['type'] !== 'with' && $block['type'] !== 'loop') while ($block['type'] !== 'if' && $block['type'] !== 'foreach' && $block['type'] !== 'for' && $block['type'] !== 'with' && $block['type'] !== 'loop') {
{
$out .= $compiler->removeTopBlock(); $out .= $compiler->removeTopBlock();
$block =& $compiler->getCurrentBlock(); $block =& $compiler->getCurrentBlock();
} }
...@@ -60,7 +59,8 @@ class Dwoo_Plugin_else extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Blo ...@@ -60,7 +59,8 @@ class Dwoo_Plugin_else extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Blo
public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend='', $append='') public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend='', $append='')
{ {
if(isset($params['postOutput'])) if (isset($params['postOutput'])) {
return $params['postOutput']; return $params['postOutput'];
}
} }
} }
<?php <?php
/** /**
* Acts as a php elseif block, allowing you to add one more condition * Acts as a php elseif block, allowing you to add one more condition
* if the previous one(s) didn't match. See the {if} plugin for syntax details * if the previous one(s) didn't match. See the {if} plugin for syntax details
* *
* This software is provided 'as-is', without any express or implied warranty. * This software is provided 'as-is', without any express or implied warranty.
...@@ -36,17 +36,19 @@ class Dwoo_Plugin_elseif extends Dwoo_Plugin_if implements Dwoo_ICompilable_Bloc ...@@ -36,17 +36,19 @@ class Dwoo_Plugin_elseif extends Dwoo_Plugin_if implements Dwoo_ICompilable_Bloc
$currentBlock =& $compiler->getCurrentBlock(); $currentBlock =& $compiler->getCurrentBlock();
$currentBlock['params']['postOutput'] = Dwoo_Compiler::PHP_OPEN."\n}".Dwoo_Compiler::PHP_CLOSE; $currentBlock['params']['postOutput'] = Dwoo_Compiler::PHP_OPEN."\n}".Dwoo_Compiler::PHP_CLOSE;
if($out === '') if ($out === '') {
$out = Dwoo_Compiler::PHP_OPEN."\n}"; $out = Dwoo_Compiler::PHP_OPEN."\n}";
else } else {
$out = substr($out, 0, -strlen(Dwoo_Compiler::PHP_CLOSE)); $out = substr($out, 0, -strlen(Dwoo_Compiler::PHP_CLOSE));
}
return $out . " elseif(".implode(' ', self::replaceKeywords($params, $compiler)).") {\n" . Dwoo_Compiler::PHP_CLOSE; return $out . " elseif (".implode(' ', self::replaceKeywords($params, $compiler)).") {\n" . Dwoo_Compiler::PHP_CLOSE;
} }
public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend='', $append='') public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend='', $append='')
{ {
if(isset($params['postOutput'])) if (isset($params['postOutput'])) {
return $params['postOutput']; return $params['postOutput'];
}
} }
} }
...@@ -64,50 +64,53 @@ class Dwoo_Plugin_for extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Bloc ...@@ -64,50 +64,53 @@ class Dwoo_Plugin_for extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Bloc
"\n".'$_for'.$cnt.'_to = '.$to.';'. "\n".'$_for'.$cnt.'_to = '.$to.';'.
"\n".'$_for'.$cnt.'_step = abs('.$step.');'. "\n".'$_for'.$cnt.'_step = abs('.$step.');'.
"\n".'$_for'.$cnt.'_skip = abs('.$skip.');'. "\n".'$_for'.$cnt.'_skip = abs('.$skip.');'.
"\n".'if(is_numeric($_for'.$cnt.'_from) && !is_numeric($_for'.$cnt.'_to)) { $this->triggerError(\'For requires the <em>to</em> parameter when using a numerical <em>from</em>\'); }'; "\n".'if (is_numeric($_for'.$cnt.'_from) && !is_numeric($_for'.$cnt.'_to)) { $this->triggerError(\'For requires the <em>to</em> parameter when using a numerical <em>from</em>\'); }';
// adds foreach properties // adds foreach properties
if($usesAny) if ($usesAny) {
{
$out .= "\n".'$this->globals["for"]['.$name.'] = array'."\n("; $out .= "\n".'$this->globals["for"]['.$name.'] = array'."\n(";
if($usesIndex) $out .="\n\t".'"index" => 0,'; if ($usesIndex) $out .="\n\t".'"index" => 0,';
if($usesIteration) $out .="\n\t".'"iteration" => 1,'; if ($usesIteration) $out .="\n\t".'"iteration" => 1,';
if($usesFirst) $out .="\n\t".'"first" => null,'; if ($usesFirst) $out .="\n\t".'"first" => null,';
if($usesLast) $out .="\n\t".'"last" => null,'; if ($usesLast) $out .="\n\t".'"last" => null,';
if($usesShow) $out .="\n\t".'"show" => ($this->isArray($_for'.$cnt.'_from, true)) || (is_numeric($_for'.$cnt.'_from) && $_for'.$cnt.'_from != $_for'.$cnt.'_to),'; if ($usesShow) $out .="\n\t".'"show" => ($this->isArray($_for'.$cnt.'_from, true)) || (is_numeric($_for'.$cnt.'_from) && $_for'.$cnt.'_from != $_for'.$cnt.'_to),';
if($usesTotal) $out .="\n\t".'"total" => $this->isArray($_for'.$cnt.'_from) ? count($_for'.$cnt.'_from) - $_for'.$cnt.'_skip : (is_numeric($_for'.$cnt.'_from) ? abs(($_for'.$cnt.'_to + 1 - $_for'.$cnt.'_from)/$_for'.$cnt.'_step) : 0),'; if ($usesTotal) $out .="\n\t".'"total" => $this->isArray($_for'.$cnt.'_from) ? count($_for'.$cnt.'_from) - $_for'.$cnt.'_skip : (is_numeric($_for'.$cnt.'_from) ? abs(($_for'.$cnt.'_to + 1 - $_for'.$cnt.'_from)/$_for'.$cnt.'_step) : 0),';
$out.="\n);\n".'$_for'.$cnt.'_glob =& $this->globals["for"]['.$name.'];'; $out.="\n);\n".'$_for'.$cnt.'_glob =& $this->globals["for"]['.$name.'];';
} }
// checks if foreach must be looped // checks if foreach must be looped
$out .= "\n".'if($this->isArray($_for'.$cnt.'_from, true) || (is_numeric($_for'.$cnt.'_from) && abs(($_for'.$cnt.'_from - $_for'.$cnt.'_to)/$_for'.$cnt.'_step) !== 0))'."\n{"; $out .= "\n".'if ($this->isArray($_for'.$cnt.'_from, true) || (is_numeric($_for'.$cnt.'_from) && abs(($_for'.$cnt.'_from - $_for'.$cnt.'_to)/$_for'.$cnt.'_step) !== 0))'."\n{";
// iterates over keys // iterates over keys
$out .= "\n\t".'if($this->isArray($_for'.$cnt.'_from, true)) { $out .= "\n\t".'if ($this->isArray($_for'.$cnt.'_from, true)) {
$_for'.$cnt.'_from = 0; $_for'.$cnt.'_from = 0;
$_for'.$cnt.'_to = is_numeric($_for'.$cnt.'_to) ? $_for'.$cnt.'_to - $_for'.$cnt.'_step : count($_for'.$cnt.'_src)-1; $_for'.$cnt.'_to = is_numeric($_for'.$cnt.'_to) ? $_for'.$cnt.'_to - $_for'.$cnt.'_step : count($_for'.$cnt.'_src)-1;
} }
$_for'.$cnt.'_keys = array(); $_for'.$cnt.'_keys = array();
if(($_for'.$cnt.'_from + $_for'.$cnt.'_skip) <= $_for'.$cnt.'_to) { if (($_for'.$cnt.'_from + $_for'.$cnt.'_skip) <= $_for'.$cnt.'_to) {
for($tmp=($_for'.$cnt.'_from + $_for'.$cnt.'_skip); $tmp <= $_for'.$cnt.'_to; $tmp += $_for'.$cnt.'_step) for ($tmp=($_for'.$cnt.'_from + $_for'.$cnt.'_skip); $tmp <= $_for'.$cnt.'_to; $tmp += $_for'.$cnt.'_step)
$_for'.$cnt.'_keys[] = $tmp; $_for'.$cnt.'_keys[] = $tmp;
} else { } else {
for($tmp=($_for'.$cnt.'_from - $_for'.$cnt.'_skip); $tmp > $_for'.$cnt.'_to; $tmp -= $_for'.$cnt.'_step) for ($tmp=($_for'.$cnt.'_from - $_for'.$cnt.'_skip); $tmp > $_for'.$cnt.'_to; $tmp -= $_for'.$cnt.'_step)
$_for'.$cnt.'_keys[] = $tmp; $_for'.$cnt.'_keys[] = $tmp;
} }
foreach($_for'.$cnt.'_keys as $this->scope['.$name.'])'."\n\t{"; foreach ($_for'.$cnt.'_keys as $this->scope['.$name.'])'."\n\t{";
// updates properties // updates properties
if($usesIndex) if ($usesIndex) {
$out.="\n\t\t".'$_for'.$cnt.'_glob["index"] = $this->scope['.$name.'];'; $out.="\n\t\t".'$_for'.$cnt.'_glob["index"] = $this->scope['.$name.'];';
if($usesFirst) }
if ($usesFirst) {
$out .= "\n\t\t".'$_for'.$cnt.'_glob["first"] = (string) ($_for'.$cnt.'_glob["iteration"] === 1);'; $out .= "\n\t\t".'$_for'.$cnt.'_glob["first"] = (string) ($_for'.$cnt.'_glob["iteration"] === 1);';
if($usesLast) }
if ($usesLast) {
$out .= "\n\t\t".'$_for'.$cnt.'_glob["last"] = (string) ($_for'.$cnt.'_glob["iteration"] === $_for'.$cnt.'_glob["total"]);'; $out .= "\n\t\t".'$_for'.$cnt.'_glob["last"] = (string) ($_for'.$cnt.'_glob["iteration"] === $_for'.$cnt.'_glob["total"]);';
}
$out .= "\n// -- for start output\n".Dwoo_Compiler::PHP_CLOSE; $out .= "\n// -- for start output\n".Dwoo_Compiler::PHP_CLOSE;
// build post processing output and cache it // build post processing output and cache it
$postOut = Dwoo_Compiler::PHP_OPEN . '// -- for end output'; $postOut = Dwoo_Compiler::PHP_OPEN . '// -- for end output';
// update properties // update properties
if($usesIteration) if ($usesIteration) {
$postOut.="\n\t\t".'$_for'.$cnt.'_glob["iteration"]+=1;'; $postOut.="\n\t\t".'$_for'.$cnt.'_glob["iteration"]+=1;';
}
// end loop // end loop
$postOut .= "\n\t}\n}\n"; $postOut .= "\n\t}\n}\n";
......
...@@ -50,24 +50,24 @@ class Dwoo_Plugin_foreach extends Dwoo_Block_Plugin implements Dwoo_ICompilable_ ...@@ -50,24 +50,24 @@ class Dwoo_Plugin_foreach extends Dwoo_Block_Plugin implements Dwoo_ICompilable_
// assigns params // assigns params
$src = $params['from']; $src = $params['from'];
if($params['item'] !== 'null') if ($params['item'] !== 'null') {
{ if ($params['key'] !== 'null') {
if($params['key'] !== 'null')
$key = $params['key']; $key = $params['key'];
}
$val = $params['item']; $val = $params['item'];
} } elseif ($params['key'] !== 'null') {
elseif($params['key'] !== 'null')
{
$val = $params['key']; $val = $params['key'];
} } else {
else
throw new Dwoo_Compilation_Exception('Foreach <em>item</em> parameter missing'); throw new Dwoo_Compilation_Exception('Foreach <em>item</em> parameter missing');
}
$name = $params['name']; $name = $params['name'];
if(substr($val,0,1) !== '"' && substr($val,0,1) !== '\'') if (substr($val,0,1) !== '"' && substr($val,0,1) !== '\'') {
throw new Dwoo_Compilation_Exception('Foreach <em>item</em> parameter must be of type string'); throw new Dwoo_Compilation_Exception('Foreach <em>item</em> parameter must be of type string');
if(isset($key) && substr($val,0,1) !== '"' && substr($val,0,1) !== '\'') }
if (isset($key) && substr($val,0,1) !== '"' && substr($val,0,1) !== '\'') {
throw new Dwoo_Compilation_Exception('Foreach <em>key</em> parameter must be of type string'); throw new Dwoo_Compilation_Exception('Foreach <em>key</em> parameter must be of type string');
}
// evaluates which global variables have to be computed // evaluates which global variables have to be computed
$varName = '$dwoo.foreach.'.trim($name, '"\'').'.'; $varName = '$dwoo.foreach.'.trim($name, '"\'').'.';
...@@ -86,35 +86,38 @@ class Dwoo_Plugin_foreach extends Dwoo_Block_Plugin implements Dwoo_ICompilable_ ...@@ -86,35 +86,38 @@ class Dwoo_Plugin_foreach extends Dwoo_Block_Plugin implements Dwoo_ICompilable_
// builds pre processing output // builds pre processing output
$out = Dwoo_Compiler::PHP_OPEN . "\n".'$_fh'.$cnt.'_data = '.$src.';'; $out = Dwoo_Compiler::PHP_OPEN . "\n".'$_fh'.$cnt.'_data = '.$src.';';
// adds foreach properties // adds foreach properties
if($usesAny) if ($usesAny) {
{
$out .= "\n".'$this->globals["foreach"]['.$name.'] = array'."\n("; $out .= "\n".'$this->globals["foreach"]['.$name.'] = array'."\n(";
if($usesIndex) $out .="\n\t".'"index" => 0,'; if ($usesIndex) $out .="\n\t".'"index" => 0,';
if($usesIteration) $out .="\n\t".'"iteration" => 1,'; if ($usesIteration) $out .="\n\t".'"iteration" => 1,';
if($usesFirst) $out .="\n\t".'"first" => null,'; if ($usesFirst) $out .="\n\t".'"first" => null,';
if($usesLast) $out .="\n\t".'"last" => null,'; if ($usesLast) $out .="\n\t".'"last" => null,';
if($usesShow) $out .="\n\t".'"show" => $this->isArray($_fh'.$cnt.'_data, true, true),'; if ($usesShow) $out .="\n\t".'"show" => $this->isArray($_fh'.$cnt.'_data, true, true),';
if($usesTotal) $out .="\n\t".'"total" => $this->isArray($_fh'.$cnt.'_data) ? count($_fh'.$cnt.'_data) : 0,'; if ($usesTotal) $out .="\n\t".'"total" => $this->isArray($_fh'.$cnt.'_data) ? count($_fh'.$cnt.'_data) : 0,';
$out.="\n);\n".'$_fh'.$cnt.'_glob =& $this->globals["foreach"]['.$name.'];'; $out.="\n);\n".'$_fh'.$cnt.'_glob =& $this->globals["foreach"]['.$name.'];';
} }
// checks if foreach must be looped // checks if foreach must be looped
$out .= "\n".'if($this->isArray($_fh'.$cnt.'_data, true, true) === true)'."\n{"; $out .= "\n".'if ($this->isArray($_fh'.$cnt.'_data, true, true) === true)'."\n{";
// iterates over keys // iterates over keys
$out .= "\n\t".'foreach($_fh'.$cnt.'_data as '.(isset($key)?'$this->scope['.$key.']=>':'').'$this->scope['.$val.'])'."\n\t{"; $out .= "\n\t".'foreach ($_fh'.$cnt.'_data as '.(isset($key)?'$this->scope['.$key.']=>':'').'$this->scope['.$val.'])'."\n\t{";
// updates properties // updates properties
if($usesFirst) if ($usesFirst) {
$out .= "\n\t\t".'$_fh'.$cnt.'_glob["first"] = (string) ($_fh'.$cnt.'_glob["index"] === 0);'; $out .= "\n\t\t".'$_fh'.$cnt.'_glob["first"] = (string) ($_fh'.$cnt.'_glob["index"] === 0);';
if($usesLast) }
if ($usesLast) {
$out .= "\n\t\t".'$_fh'.$cnt.'_glob["last"] = (string) ($_fh'.$cnt.'_glob["iteration"] === $_fh'.$cnt.'_glob["total"]);'; $out .= "\n\t\t".'$_fh'.$cnt.'_glob["last"] = (string) ($_fh'.$cnt.'_glob["iteration"] === $_fh'.$cnt.'_glob["total"]);';
}
$out .= "\n// -- foreach start output\n".Dwoo_Compiler::PHP_CLOSE; $out .= "\n// -- foreach start output\n".Dwoo_Compiler::PHP_CLOSE;
// build post processing output and cache it // build post processing output and cache it
$postOut = Dwoo_Compiler::PHP_OPEN . "\n".'// -- foreach end output'; $postOut = Dwoo_Compiler::PHP_OPEN . "\n".'// -- foreach end output';
// update properties // update properties
if($usesIndex) if ($usesIndex) {
$postOut.="\n\t\t".'$_fh'.$cnt.'_glob["index"]+=1;'; $postOut.="\n\t\t".'$_fh'.$cnt.'_glob["index"]+=1;';
if($usesIteration) }
if ($usesIteration) {
$postOut.="\n\t\t".'$_fh'.$cnt.'_glob["iteration"]+=1;'; $postOut.="\n\t\t".'$_fh'.$cnt.'_glob["iteration"]+=1;';
}
// end loop // end loop
$postOut .= "\n\t}\n}\n"; $postOut .= "\n\t}\n}\n";
......
...@@ -33,10 +33,11 @@ class Dwoo_Plugin_foreachelse extends Dwoo_Block_Plugin implements Dwoo_ICompila ...@@ -33,10 +33,11 @@ class Dwoo_Plugin_foreachelse extends Dwoo_Block_Plugin implements Dwoo_ICompila
$compiler->injectBlock($type, $params, 1); $compiler->injectBlock($type, $params, 1);
if(substr($out, -strlen(Dwoo_Compiler::PHP_CLOSE)) === Dwoo_Compiler::PHP_CLOSE) if (substr($out, -strlen(Dwoo_Compiler::PHP_CLOSE)) === Dwoo_Compiler::PHP_CLOSE) {
$out = substr($out, 0, -strlen(Dwoo_Compiler::PHP_CLOSE)); $out = substr($out, 0, -strlen(Dwoo_Compiler::PHP_CLOSE));
else } else {
$out .= Dwoo_Compiler::PHP_OPEN; $out .= Dwoo_Compiler::PHP_OPEN;
}
return $out . "else\n{" . Dwoo_Compiler::PHP_CLOSE; return $out . "else\n{" . Dwoo_Compiler::PHP_CLOSE;
} }
......
...@@ -33,10 +33,11 @@ class Dwoo_Plugin_forelse extends Dwoo_Block_Plugin implements Dwoo_ICompilable_ ...@@ -33,10 +33,11 @@ class Dwoo_Plugin_forelse extends Dwoo_Block_Plugin implements Dwoo_ICompilable_
$compiler->injectBlock($type, $params, 1); $compiler->injectBlock($type, $params, 1);
if(substr($out, -strlen(Dwoo_Compiler::PHP_CLOSE)) === Dwoo_Compiler::PHP_CLOSE) if (substr($out, -strlen(Dwoo_Compiler::PHP_CLOSE)) === Dwoo_Compiler::PHP_CLOSE) {
$out = substr($out, 0, -strlen(Dwoo_Compiler::PHP_CLOSE)); $out = substr($out, 0, -strlen(Dwoo_Compiler::PHP_CLOSE));
else } else {
$out .= Dwoo_Compiler::PHP_OPEN; $out .= Dwoo_Compiler::PHP_OPEN;
}
return $out . "else\n{" . Dwoo_Compiler::PHP_CLOSE; return $out . "else\n{" . Dwoo_Compiler::PHP_CLOSE;
} }
......
...@@ -44,10 +44,8 @@ class Dwoo_Plugin_if extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block ...@@ -44,10 +44,8 @@ class Dwoo_Plugin_if extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block
$params = $params['*']; $params = $params['*'];
while(list($k,$v) = each($params)) while (list($k,$v) = each($params)) {
{ switch($v) {
switch($v)
{
case '"<<"': case '"<<"':
case '">>"': case '">>"':
case '"&&"': case '"&&"':
...@@ -100,53 +98,44 @@ class Dwoo_Plugin_if extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block ...@@ -100,53 +98,44 @@ class Dwoo_Plugin_if extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block
$p[] = '!=='; $p[] = '!==';
break; break;
case '"is"': case '"is"':
if($params[$k+1] === '"not"') if ($params[$k+1] === '"not"') {
{
$negate = true; $negate = true;
next($params); next($params);
} } else {
else
$negate = false; $negate = false;
}
$ptr = 1+(int)$negate; $ptr = 1+(int)$negate;
switch($params[$k+$ptr]) switch($params[$k+$ptr]) {
{
case '"div"': case '"div"':
if(isset($params[$k+$ptr+1]) && $params[$k+$ptr+1] === '"by"') if (isset($params[$k+$ptr+1]) && $params[$k+$ptr+1] === '"by"') {
{
$p[] = ' % '.$params[$k+$ptr+2].' '.($negate?'!':'=').'== 0'; $p[] = ' % '.$params[$k+$ptr+2].' '.($negate?'!':'=').'== 0';
next($params); next($params);
next($params); next($params);
next($params); next($params);
} } else {
else
throw new Dwoo_Compilation_Exception('If : Syntax error : syntax should be "if $a is [not] div by $b", found '.$params[$k-1].' is '.($negate?'not ':'').'div '.$params[$k+$ptr+1].' '.$params[$k+$ptr+2]); throw new Dwoo_Compilation_Exception('If : Syntax error : syntax should be "if $a is [not] div by $b", found '.$params[$k-1].' is '.($negate?'not ':'').'div '.$params[$k+$ptr+1].' '.$params[$k+$ptr+2]);
}
break; break;
case '"even"': case '"even"':
$a = array_pop($p); $a = array_pop($p);
if(isset($params[$k+$ptr+1]) && $params[$k+$ptr+1] === '"by"') if (isset($params[$k+$ptr+1]) && $params[$k+$ptr+1] === '"by"') {
{
$b = $params[$k+$ptr+2]; $b = $params[$k+$ptr+2];
$p[] = '('.$a .' / '.$b.') % 2 '.($negate?'!':'=').'== 0'; $p[] = '('.$a .' / '.$b.') % 2 '.($negate?'!':'=').'== 0';
next($params); next($params);
next($params); next($params);
} } else {
else
{
$p[] = $a.' % 2 '.($negate?'!':'=').'== 0'; $p[] = $a.' % 2 '.($negate?'!':'=').'== 0';
} }
next($params); next($params);
break; break;
case '"odd"': case '"odd"':
$a = array_pop($p); $a = array_pop($p);
if(isset($params[$k+$ptr+1]) && $params[$k+$ptr+1] === '"by"') if (isset($params[$k+$ptr+1]) && $params[$k+$ptr+1] === '"by"') {
{
$b = $params[$k+$ptr+2]; $b = $params[$k+$ptr+2];
$p[] = '('.$a .' / '.$b.') % 2 '.($negate?'=':'!').'== 0'; $p[] = '('.$a .' / '.$b.') % 2 '.($negate?'=':'!').'== 0';
next($params); next($params);
next($params); next($params);
} } else {
else
{
$p[] = $a.' % 2 '.($negate?'=':'!').'== 0'; $p[] = $a.' % 2 '.($negate?'=':'!').'== 0';
} }
next($params); next($params);
...@@ -176,7 +165,7 @@ class Dwoo_Plugin_if extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block ...@@ -176,7 +165,7 @@ class Dwoo_Plugin_if extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block
$currentBlock =& $compiler->getCurrentBlock(); $currentBlock =& $compiler->getCurrentBlock();
$currentBlock['params']['postOutput'] = Dwoo_Compiler::PHP_OPEN."\n}".Dwoo_Compiler::PHP_CLOSE; $currentBlock['params']['postOutput'] = Dwoo_Compiler::PHP_OPEN."\n}".Dwoo_Compiler::PHP_CLOSE;
return Dwoo_Compiler::PHP_OPEN.'if('.implode(' ', self::replaceKeywords($params, $compiler)).") {\n".Dwoo_Compiler::PHP_CLOSE; return Dwoo_Compiler::PHP_OPEN.'if ('.implode(' ', self::replaceKeywords($params, $compiler)).") {\n".Dwoo_Compiler::PHP_CLOSE;
} }
public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend='', $append='') public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend='', $append='')
......
...@@ -77,35 +77,38 @@ class Dwoo_Plugin_loop extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Blo ...@@ -77,35 +77,38 @@ class Dwoo_Plugin_loop extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Blo
// builds pre processing output // builds pre processing output
$out = Dwoo_Compiler::PHP_OPEN . "\n".'$_loop'.$cnt.'_data = '.$src.';'; $out = Dwoo_Compiler::PHP_OPEN . "\n".'$_loop'.$cnt.'_data = '.$src.';';
// adds foreach properties // adds foreach properties
if($usesAny) if ($usesAny) {
{
$out .= "\n".'$this->globals["loop"]['.$name.'] = array'."\n("; $out .= "\n".'$this->globals["loop"]['.$name.'] = array'."\n(";
if($usesIndex) $out .="\n\t".'"index" => 0,'; if ($usesIndex) $out .="\n\t".'"index" => 0,';
if($usesIteration) $out .="\n\t".'"iteration" => 1,'; if ($usesIteration) $out .="\n\t".'"iteration" => 1,';
if($usesFirst) $out .="\n\t".'"first" => null,'; if ($usesFirst) $out .="\n\t".'"first" => null,';
if($usesLast) $out .="\n\t".'"last" => null,'; if ($usesLast) $out .="\n\t".'"last" => null,';
if($usesShow) $out .="\n\t".'"show" => $this->isArray($_loop'.$cnt.'_data, true, true),'; if ($usesShow) $out .="\n\t".'"show" => $this->isArray($_loop'.$cnt.'_data, true, true),';
if($usesTotal) $out .="\n\t".'"total" => $this->isArray($_loop'.$cnt.'_data) ? count($_loop'.$cnt.'_data) : 0,'; if ($usesTotal) $out .="\n\t".'"total" => $this->isArray($_loop'.$cnt.'_data) ? count($_loop'.$cnt.'_data) : 0,';
$out.="\n);\n".'$_loop'.$cnt.'_glob =& $this->globals["loop"]['.$name.'];'; $out.="\n);\n".'$_loop'.$cnt.'_glob =& $this->globals["loop"]['.$name.'];';
} }
// checks if foreach must be looped // checks if foreach must be looped
$out .= "\n".'if($this->isArray($_loop'.$cnt.'_data, true, true) === true)'."\n{"; $out .= "\n".'if ($this->isArray($_loop'.$cnt.'_data, true, true) === true)'."\n{";
// iterates over keys // iterates over keys
$out .= "\n\t".'foreach($_loop'.$cnt.'_data as $tmp_key => $this->scope["-loop-"])'."\n\t{"; $out .= "\n\t".'foreach ($_loop'.$cnt.'_data as $tmp_key => $this->scope["-loop-"])'."\n\t{";
// updates properties // updates properties
if($usesFirst) if ($usesFirst) {
$out .= "\n\t\t".'$_loop'.$cnt.'_glob["first"] = (string) ($_loop'.$cnt.'_glob["index"] === 0);'; $out .= "\n\t\t".'$_loop'.$cnt.'_glob["first"] = (string) ($_loop'.$cnt.'_glob["index"] === 0);';
if($usesLast) }
if ($usesLast) {
$out .= "\n\t\t".'$_loop'.$cnt.'_glob["last"] = (string) ($_loop'.$cnt.'_glob["iteration"] === $_loop'.$cnt.'_glob["total"]);'; $out .= "\n\t\t".'$_loop'.$cnt.'_glob["last"] = (string) ($_loop'.$cnt.'_glob["iteration"] === $_loop'.$cnt.'_glob["total"]);';
}
$out .= "\n\t\t".'$_loop'.$cnt.'_scope = $this->setScope(array("-loop-"));' . "\n// -- loop start output\n".Dwoo_Compiler::PHP_CLOSE; $out .= "\n\t\t".'$_loop'.$cnt.'_scope = $this->setScope(array("-loop-"));' . "\n// -- loop start output\n".Dwoo_Compiler::PHP_CLOSE;
// build post processing output and cache it // build post processing output and cache it
$postOut = Dwoo_Compiler::PHP_OPEN . "\n".'// -- loop end output'."\n\t\t".'$this->setScope($_loop'.$cnt.'_scope, true);'; $postOut = Dwoo_Compiler::PHP_OPEN . "\n".'// -- loop end output'."\n\t\t".'$this->setScope($_loop'.$cnt.'_scope, true);';
// update properties // update properties
if($usesIndex) if ($usesIndex) {
$postOut.="\n\t\t".'$_loop'.$cnt.'_glob["index"]+=1;'; $postOut.="\n\t\t".'$_loop'.$cnt.'_glob["index"]+=1;';
if($usesIteration) }
if ($usesIteration) {
$postOut.="\n\t\t".'$_loop'.$cnt.'_glob["iteration"]+=1;'; $postOut.="\n\t\t".'$_loop'.$cnt.'_glob["iteration"]+=1;';
}
// end loop // end loop
$postOut .= "\n\t}\n}\n"; $postOut .= "\n\t}\n}\n";
......
...@@ -30,33 +30,31 @@ class Dwoo_Plugin_smartyinterface extends Dwoo_Block_Plugin implements Dwoo_ICom ...@@ -30,33 +30,31 @@ class Dwoo_Plugin_smartyinterface extends Dwoo_Block_Plugin implements Dwoo_ICom
$pluginType = $params['__functype']; $pluginType = $params['__functype'];
$params = $params['*']; $params = $params['*'];
if($pluginType & Dwoo::CUSTOM_PLUGIN) if ($pluginType & Dwoo::CUSTOM_PLUGIN) {
{
$customPlugins = $compiler->getDwoo()->getCustomPlugins(); $customPlugins = $compiler->getDwoo()->getCustomPlugins();
$callback = $customPlugins[$func]['callback']; $callback = $customPlugins[$func]['callback'];
if(is_array($callback)) if (is_array($callback)) {
{ if (is_object($callback[0])) {
if(is_object($callback[0]))
$callback = '$this->customPlugins[\''.$func.'\'][0]->'.$callback[1].'('; $callback = '$this->customPlugins[\''.$func.'\'][0]->'.$callback[1].'(';
else } else {
$callback = ''.$callback[0].'::'.$callback[1].'('; $callback = ''.$callback[0].'::'.$callback[1].'(';
} }
else } else {
$callback = $callback.'('; $callback = $callback.'(';
} }
else } else {
$callback = 'smarty_block_'.$func.'('; $callback = 'smarty_block_'.$func.'(';
}
$paramsOut = ''; $paramsOut = '';
foreach($params as $i=>$p) foreach ($params as $i=>$p) {
{
$paramsOut .= var_export($i, true).' => '.$p.','; $paramsOut .= var_export($i, true).' => '.$p.',';
} }
$curBlock =& $compiler->getCurrentBlock(); $curBlock =& $compiler->getCurrentBlock();
$curBlock['params']['postOut'] = Dwoo_Compiler::PHP_OPEN.' $_block_content = ob_get_clean(); $_block_repeat=false; echo '.$callback.'$_tag_stack[count($_tag_stack)-1], $_block_content, $this, $_block_repeat); } array_pop($_tag_stack);'.Dwoo_Compiler::PHP_CLOSE; $curBlock['params']['postOut'] = Dwoo_Compiler::PHP_OPEN.' $_block_content = ob_get_clean(); $_block_repeat=false; echo '.$callback.'$_tag_stack[count($_tag_stack)-1], $_block_content, $this, $_block_repeat); } array_pop($_tag_stack);'.Dwoo_Compiler::PHP_CLOSE;
return Dwoo_Compiler::PHP_OPEN.$prepend.' if(!isset($_tag_stack)){ $_tag_stack = array(); } $_tag_stack[] = array('.$paramsOut.'); $_block_repeat=true; '.$callback.'$_tag_stack[count($_tag_stack)-1], null, $this, $_block_repeat); while ($_block_repeat) { ob_start();'.Dwoo_Compiler::PHP_CLOSE; return Dwoo_Compiler::PHP_OPEN.$prepend.' if (!isset($_tag_stack)){ $_tag_stack = array(); } $_tag_stack[] = array('.$paramsOut.'); $_block_repeat=true; '.$callback.'$_tag_stack[count($_tag_stack)-1], null, $this, $_block_repeat); while ($_block_repeat) { ob_start();'.Dwoo_Compiler::PHP_CLOSE;
} }
public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend='', $append='') public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend='', $append='')
......
...@@ -41,11 +41,11 @@ class Dwoo_Plugin_textformat extends Dwoo_Block_Plugin ...@@ -41,11 +41,11 @@ class Dwoo_Plugin_textformat extends Dwoo_Block_Plugin
public function init($wrap=80, $wrap_char="\r\n", $wrap_cut=false, $indent=0, $indent_char=" ", $indent_first=0, $style="", $assign="") public function init($wrap=80, $wrap_char="\r\n", $wrap_cut=false, $indent=0, $indent_char=" ", $indent_first=0, $style="", $assign="")
{ {
if($indent_char === 'tab') if ($indent_char === 'tab') {
$indent_char = "\t"; $indent_char = "\t";
}
switch($style) switch($style) {
{
case 'email': case 'email':
$wrap = 72; $wrap = 72;
$indent_first = 0; $indent_first = 0;
...@@ -70,10 +70,10 @@ class Dwoo_Plugin_textformat extends Dwoo_Block_Plugin ...@@ -70,10 +70,10 @@ class Dwoo_Plugin_textformat extends Dwoo_Block_Plugin
// gets paragraphs // gets paragraphs
$pgs = explode("\n", str_replace(array("\r\n", "\r"), "\n", $this->buffer)); $pgs = explode("\n", str_replace(array("\r\n", "\r"), "\n", $this->buffer));
while(list($i,) = each($pgs)) while (list($i,) = each($pgs)) {
{ if (empty($pgs[$i])) {
if(empty($pgs[$i]))
continue; continue;
}
// removes line breaks and extensive white space // removes line breaks and extensive white space
$pgs[$i] = preg_replace(array('#\s+#', '#^\s*(.+?)\s*$#m'), array(' ', '$1'), str_replace("\n", '', $pgs[$i])); $pgs[$i] = preg_replace(array('#\s+#', '#^\s*(.+?)\s*$#m'), array(' ', '$1'), str_replace("\n", '', $pgs[$i]));
...@@ -88,9 +88,10 @@ class Dwoo_Plugin_textformat extends Dwoo_Block_Plugin ...@@ -88,9 +88,10 @@ class Dwoo_Plugin_textformat extends Dwoo_Block_Plugin
); );
} }
if($this->assign !== '') if ($this->assign !== '') {
$this->dwoo->assignInScope(implode($this->wrapChar . $this->wrapChar, $pgs), $this->assign); $this->dwoo->assignInScope(implode($this->wrapChar . $this->wrapChar, $pgs), $this->assign);
else } else {
return implode($this->wrapChar . $this->wrapChar, $pgs); return implode($this->wrapChar . $this->wrapChar, $pgs);
}
} }
} }
...@@ -61,7 +61,7 @@ class Dwoo_Plugin_with extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Blo ...@@ -61,7 +61,7 @@ class Dwoo_Plugin_with extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Blo
$params =& $compiler->getCurrentBlock(); $params =& $compiler->getCurrentBlock();
$params['params']['postOutput'] = Dwoo_Compiler::PHP_OPEN."\n// -- end with output\n".'$this->setScope($_with'.(self::$cnt).', true);'."\n}\n".Dwoo_Compiler::PHP_CLOSE; $params['params']['postOutput'] = Dwoo_Compiler::PHP_OPEN."\n// -- end with output\n".'$this->setScope($_with'.(self::$cnt).', true);'."\n}\n".Dwoo_Compiler::PHP_CLOSE;
return Dwoo_Compiler::PHP_OPEN.'if('.$cparams['var'].')'."\n{\n".'$_with'.(self::$cnt++).' = $this->setScope("'.$rparams['var'].'");'."\n// -- start with output\n".Dwoo_Compiler::PHP_CLOSE; return Dwoo_Compiler::PHP_OPEN.'if ('.$cparams['var'].')'."\n{\n".'$_with'.(self::$cnt++).' = $this->setScope("'.$rparams['var'].'");'."\n// -- start with output\n".Dwoo_Compiler::PHP_CLOSE;
} }
public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend='', $append='') public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend='', $append='')
......
...@@ -33,10 +33,11 @@ class Dwoo_Plugin_withelse extends Dwoo_Block_Plugin implements Dwoo_ICompilable ...@@ -33,10 +33,11 @@ class Dwoo_Plugin_withelse extends Dwoo_Block_Plugin implements Dwoo_ICompilable
$compiler->injectBlock($type, $params, 1); $compiler->injectBlock($type, $params, 1);
if(substr($out, -strlen(Dwoo_Compiler::PHP_CLOSE)) === Dwoo_Compiler::PHP_CLOSE) if (substr($out, -strlen(Dwoo_Compiler::PHP_CLOSE)) === Dwoo_Compiler::PHP_CLOSE) {
$out = substr($out, 0, -strlen(Dwoo_Compiler::PHP_CLOSE)); $out = substr($out, 0, -strlen(Dwoo_Compiler::PHP_CLOSE));
else } else {
$out .= Dwoo_Compiler::PHP_OPEN; $out .= Dwoo_Compiler::PHP_OPEN;
}
return $out . "else\n{" . Dwoo_Compiler::PHP_CLOSE; return $out . "else\n{" . Dwoo_Compiler::PHP_CLOSE;
} }
......
...@@ -71,15 +71,15 @@ class Dwoo_Filter_html_format extends Dwoo_Filter ...@@ -71,15 +71,15 @@ class Dwoo_Filter_html_format extends Dwoo_Filter
protected static function tagDispatcher($input) protected static function tagDispatcher($input)
{ {
// textarea, pre, code tags and comments are to be left alone to avoid any non-wanted whitespace inside them so it just outputs them as they were // textarea, pre, code tags and comments are to be left alone to avoid any non-wanted whitespace inside them so it just outputs them as they were
if(substr($input[1],0,9) == "<textarea" || substr($input[1],0,4) == "<pre" || substr($input[1],0,5) == "<code" || substr($input[1],0,4) == "<!--" || substr($input[1],0,9) == "<![CDATA[") { if (substr($input[1],0,9) == "<textarea" || substr($input[1],0,4) == "<pre" || substr($input[1],0,5) == "<code" || substr($input[1],0,4) == "<!--" || substr($input[1],0,9) == "<![CDATA[") {
return $input[1] . $input[3]; return $input[1] . $input[3];
} }
// closing textarea, code and pre tags and self-closed tags (i.e. <br />) are printed as singleTags because we didn't use openTag for the formers and the latter is a single tag // closing textarea, code and pre tags and self-closed tags (i.e. <br />) are printed as singleTags because we didn't use openTag for the formers and the latter is a single tag
if(substr($input[1],0,10) == "</textarea" || substr($input[1],0,5) == "</pre" || substr($input[1],0,6) == "</code" || substr($input[1],-2) == "/>") { if (substr($input[1],0,10) == "</textarea" || substr($input[1],0,5) == "</pre" || substr($input[1],0,6) == "</code" || substr($input[1],-2) == "/>") {
return self::singleTag($input[1],$input[3],$input[2]); return self::singleTag($input[1],$input[3],$input[2]);
} }
// it's the closing tag // it's the closing tag
if($input[0][1]=="/"){ if ($input[0][1]=="/"){
return self::closeTag($input[1],$input[3],$input[2]); return self::closeTag($input[1],$input[3],$input[2]);
} }
// opening tag // opening tag
...@@ -99,13 +99,11 @@ class Dwoo_Filter_html_format extends Dwoo_Filter ...@@ -99,13 +99,11 @@ class Dwoo_Filter_html_format extends Dwoo_Filter
$tabs = str_pad('',self::$tabCount++,"\t"); $tabs = str_pad('',self::$tabCount++,"\t");
// if it's one of those tag it's inline so it does not require a leading line break // if it's one of those tag it's inline so it does not require a leading line break
if(preg_match('#^<(a|label|option|textarea|h1|h2|h3|h4|h5|h6|strong|b|em|i|abbr|acronym|cite|span|sub|sup|u|s|title)(?: [^>]*|)>#', $tag)) if (preg_match('#^<(a|label|option|textarea|h1|h2|h3|h4|h5|h6|strong|b|em|i|abbr|acronym|cite|span|sub|sup|u|s|title)(?: [^>]*|)>#', $tag)) {
{
$result = $tag . $whitespace . str_replace("\n","\n".$tabs,$add); $result = $tag . $whitespace . str_replace("\n","\n".$tabs,$add);
} }
// it's the doctype declaration so no line break here either // it's the doctype declaration so no line break here either
elseif(substr($tag,0,9) == '<!DOCTYPE') elseif (substr($tag,0,9) == '<!DOCTYPE') {
{
$result = $tabs . $tag; $result = $tabs . $tag;
} }
// normal block tag // normal block tag
...@@ -113,8 +111,7 @@ class Dwoo_Filter_html_format extends Dwoo_Filter ...@@ -113,8 +111,7 @@ class Dwoo_Filter_html_format extends Dwoo_Filter
{ {
$result = "\n".$tabs . $tag; $result = "\n".$tabs . $tag;
if(!empty($add)) if (!empty($add)) {
{
$result .= "\n".$tabs."\t".str_replace("\n","\n\t".$tabs,$add); $result .= "\n".$tabs."\t".str_replace("\n","\n\t".$tabs,$add);
} }
} }
...@@ -137,16 +134,12 @@ class Dwoo_Filter_html_format extends Dwoo_Filter ...@@ -137,16 +134,12 @@ class Dwoo_Filter_html_format extends Dwoo_Filter
$tabs = str_pad('',--self::$tabCount,"\t"); $tabs = str_pad('',--self::$tabCount,"\t");
// if it's one of those tag it's inline so it does not require a leading line break // if it's one of those tag it's inline so it does not require a leading line break
if(preg_match('#^</(a|label|option|textarea|h1|h2|h3|h4|h5|h6|strong|b|em|i|abbr|acronym|cite|span|sub|sup|u|s|title)>#', $tag)) if (preg_match('#^</(a|label|option|textarea|h1|h2|h3|h4|h5|h6|strong|b|em|i|abbr|acronym|cite|span|sub|sup|u|s|title)>#', $tag)) {
{
$result = $tag . $whitespace . str_replace("\n","\n".$tabs,$add); $result = $tag . $whitespace . str_replace("\n","\n".$tabs,$add);
} } else {
else
{
$result = "\n".$tabs.$tag; $result = "\n".$tabs.$tag;
if(!empty($add)) if (!empty($add)) {
{
$result .= "\n".$tabs."\t".str_replace("\n","\n\t".$tabs,$add); $result .= "\n".$tabs."\t".str_replace("\n","\n\t".$tabs,$add);
} }
} }
...@@ -169,21 +162,16 @@ class Dwoo_Filter_html_format extends Dwoo_Filter ...@@ -169,21 +162,16 @@ class Dwoo_Filter_html_format extends Dwoo_Filter
// if it's img, br it's inline so it does not require a leading line break // if it's img, br it's inline so it does not require a leading line break
// if it's a closing textarea, code or pre tag, it does not require a leading line break either or it creates whitespace at the end of those blocks // if it's a closing textarea, code or pre tag, it does not require a leading line break either or it creates whitespace at the end of those blocks
if(preg_match('#^<(img|br|/textarea|/pre|/code)(?: [^>]*|)>#', $tag)) if (preg_match('#^<(img|br|/textarea|/pre|/code)(?: [^>]*|)>#', $tag)) {
{
$result = $tag.$whitespace; $result = $tag.$whitespace;
if(!empty($add)) if (!empty($add)) {
{
$result .= str_replace("\n","\n".$tabs,$add); $result .= str_replace("\n","\n".$tabs,$add);
} }
} } else {
else
{
$result = "\n".$tabs.$tag; $result = "\n".$tabs.$tag;
if(!empty($add)) if (!empty($add)) {
{
$result .= "\n".$tabs.str_replace("\n","\n".$tabs,$add); $result .= "\n".$tabs.str_replace("\n","\n".$tabs,$add);
} }
} }
......
...@@ -24,21 +24,22 @@ ...@@ -24,21 +24,22 @@
*/ */
function Dwoo_Plugin_capitalize(Dwoo $dwoo, $value, $numwords=false) function Dwoo_Plugin_capitalize(Dwoo $dwoo, $value, $numwords=false)
{ {
if($numwords || preg_match('#^[^0-9]+$#',$value)) if ($numwords || preg_match('#^[^0-9]+$#',$value))
{ {
if($dwoo->getCharset() === 'iso-8859-1') if ($dwoo->getCharset() === 'iso-8859-1') {
return ucwords((string) $value); return ucwords((string) $value);
}
return mb_convert_case((string) $value,MB_CASE_TITLE, $dwoo->getCharset()); return mb_convert_case((string) $value,MB_CASE_TITLE, $dwoo->getCharset());
} } else
else
{ {
$bits = explode(' ', (string) $value); $bits = explode(' ', (string) $value);
$out = ''; $out = '';
while(list(,$v) = each($bits)) while (list(,$v) = each($bits))
if(preg_match('#^[^0-9]+$#', $v)) if (preg_match('#^[^0-9]+$#', $v)) {
$out .= ' '.mb_convert_case($v, MB_CASE_TITLE, $dwoo->getCharset()); $out .= ' '.mb_convert_case($v, MB_CASE_TITLE, $dwoo->getCharset());
else } else {
$out .= ' '.$v; $out .= ' '.$v;
}
return substr($out, 1); return substr($out, 1);
} }
......
...@@ -24,8 +24,9 @@ ...@@ -24,8 +24,9 @@
*/ */
function Dwoo_Plugin_count_characters_compile(Dwoo_Compiler $compiler, $value, $count_spaces=false) function Dwoo_Plugin_count_characters_compile(Dwoo_Compiler $compiler, $value, $count_spaces=false)
{ {
if($count_spaces==='false') if ($count_spaces==='false') {
return 'preg_match_all(\'#[^\s\pZ]#u\', '.$value.', $tmp)'; return 'preg_match_all(\'#[^\s\pZ]#u\', '.$value.', $tmp)';
else } else {
return 'mb_strlen('.$value.', $this->charset)'; return 'mb_strlen('.$value.', $this->charset)';
}
} }
...@@ -33,8 +33,7 @@ class Dwoo_Plugin_counter extends Dwoo_Plugin ...@@ -33,8 +33,7 @@ class Dwoo_Plugin_counter extends Dwoo_Plugin
public function process($name = 'default', $start = null, $skip = null, $direction = null, $print = null, $assign = null) public function process($name = 'default', $start = null, $skip = null, $direction = null, $print = null, $assign = null)
{ {
// init counter // init counter
if(!isset($this->counters[$name])) if (!isset($this->counters[$name])) {
{
$this->counters[$name] = array $this->counters[$name] = array
( (
'count' => $start===null ? 1 : (int) $start, 'count' => $start===null ? 1 : (int) $start,
...@@ -48,29 +47,35 @@ class Dwoo_Plugin_counter extends Dwoo_Plugin ...@@ -48,29 +47,35 @@ class Dwoo_Plugin_counter extends Dwoo_Plugin
else else
{ {
// override setting if present // override setting if present
if($skip !== null) if ($skip !== null) {
$this->counters[$name]['skip'] = (int) $skip; $this->counters[$name]['skip'] = (int) $skip;
}
if($direction !== null) if ($direction !== null) {
$this->counters[$name]['direction'] = strtolower($direction)==='down' ? -1 : 1; $this->counters[$name]['direction'] = strtolower($direction)==='down' ? -1 : 1;
}
if($print !== null) if ($print !== null) {
$this->counters[$name]['print'] = (bool) $print; $this->counters[$name]['print'] = (bool) $print;
}
if($assign !== null) if ($assign !== null) {
$this->counters[$name]['assign'] = (string) $assign; $this->counters[$name]['assign'] = (string) $assign;
}
if($start !== null) if ($start !== null) {
$this->counters[$name]['count'] = (int) $start; $this->counters[$name]['count'] = (int) $start;
else } else {
$this->counters[$name]['count'] += ($this->counters[$name]['skip'] * $this->counters[$name]['direction']); $this->counters[$name]['count'] += ($this->counters[$name]['skip'] * $this->counters[$name]['direction']);
}
} }
$out = $this->counters[$name]['count']; $out = $this->counters[$name]['count'];
if($this->counters[$name]['assign'] !== null) if ($this->counters[$name]['assign'] !== null) {
$this->dwoo->assignInScope($out, $this->counters[$name]['assign']); $this->dwoo->assignInScope($out, $this->counters[$name]['assign']);
elseif($this->counters[$name]['print'] === true) } elseif ($this->counters[$name]['print'] === true) {
return $out; return $out;
}
} }
} }
...@@ -33,40 +33,42 @@ class Dwoo_Plugin_cycle extends Dwoo_Plugin ...@@ -33,40 +33,42 @@ class Dwoo_Plugin_cycle extends Dwoo_Plugin
public function process($name = 'default', $values = null, $print = true, $advance = true, $delimiter = ',', $assign = null, $reset = false) public function process($name = 'default', $values = null, $print = true, $advance = true, $delimiter = ',', $assign = null, $reset = false)
{ {
if($values !== null) if ($values !== null) {
{ if (is_string($values)) {
if(is_string($values))
$values = explode($delimiter, $values); $values = explode($delimiter, $values);
}
if(!isset($this->cycles[$name]) || $this->cycles[$name]['values'] !== $values) if (!isset($this->cycles[$name]) || $this->cycles[$name]['values'] !== $values) {
$this->cycles[$name]['index'] = 0; $this->cycles[$name]['index'] = 0;
}
$this->cycles[$name]['values'] = array_values($values); $this->cycles[$name]['values'] = array_values($values);
} } elseif (isset($this->cycles[$name])) {
elseif(isset($this->cycles[$name]))
{
$values = $this->cycles[$name]['values']; $values = $this->cycles[$name]['values'];
} }
if($reset) if ($reset) {
$this->cycles[$name]['index'] = 0; $this->cycles[$name]['index'] = 0;
}
if($print) if ($print) {
$out = $values[$this->cycles[$name]['index']]; $out = $values[$this->cycles[$name]['index']];
else } else {
$out = null; $out = null;
}
if($advance) if ($advance) {
{ if ($this->cycles[$name]['index'] >= count($values)-1) {
if($this->cycles[$name]['index'] >= count($values)-1)
$this->cycles[$name]['index'] = 0; $this->cycles[$name]['index'] = 0;
else } else {
$this->cycles[$name]['index']++; $this->cycles[$name]['index']++;
}
} }
if($assign !== null) if ($assign !== null) {
$this->dwoo->assignInScope($assign, $out); $this->dwoo->assignInScope($assign, $out);
else } else {
return $out; return $out;
}
} }
} }
...@@ -25,35 +25,34 @@ ...@@ -25,35 +25,34 @@
*/ */
function Dwoo_Plugin_date_format(Dwoo $dwoo, $value, $format='%b %e, %Y', $default=null) function Dwoo_Plugin_date_format(Dwoo $dwoo, $value, $format='%b %e, %Y', $default=null)
{ {
if(!empty($value)) if (!empty($value))
{ {
// convert if it's not a valid unix timestamp // convert if it's not a valid unix timestamp
if(preg_match('#^\d{10}$#', $value)===0) if (preg_match('#^\d{10}$#', $value)===0) {
$value = strtotime($value); $value = strtotime($value);
} }
elseif(!empty($default)) } elseif (!empty($default))
{ {
// convert if it's not a valid unix timestamp // convert if it's not a valid unix timestamp
if(preg_match('#^\d{10}$#', $default)===0) if (preg_match('#^\d{10}$#', $default)===0) {
$value = strtotime($default); $value = strtotime($default);
else } else {
$value = $default; $value = $default;
} }
else } else {
return ''; return '';
}
// Credits for that windows compat block to Monte Ohrt who made smarty's date_format plugin // Credits for that windows compat block to Monte Ohrt who made smarty's date_format plugin
if(DIRECTORY_SEPARATOR == '\\') if (DIRECTORY_SEPARATOR == '\\')
{ {
$_win_from = array('%D', '%h', '%n', '%r', '%R', '%t', '%T'); $_win_from = array('%D', '%h', '%n', '%r', '%R', '%t', '%T');
$_win_to = array('%m/%d/%y', '%b', "\n", '%I:%M:%S %p', '%H:%M', "\t", '%H:%M:%S'); $_win_to = array('%m/%d/%y', '%b', "\n", '%I:%M:%S %p', '%H:%M', "\t", '%H:%M:%S');
if(strpos($format, '%e') !== false) if (strpos($format, '%e') !== false) {
{
$_win_from[] = '%e'; $_win_from[] = '%e';
$_win_to[] = sprintf('%\' 2d', date('j', $value)); $_win_to[] = sprintf('%\' 2d', date('j', $value));
} }
if(strpos($format, '%l') !== false) if (strpos($format, '%l') !== false) {
{
$_win_from[] = '%l'; $_win_from[] = '%l';
$_win_to[] = sprintf('%\' 2d', date('h', $value)); $_win_to[] = sprintf('%\' 2d', date('h', $value));
} }
......
...@@ -32,7 +32,7 @@ class Dwoo_Plugin_dump extends Dwoo_Plugin ...@@ -32,7 +32,7 @@ class Dwoo_Plugin_dump extends Dwoo_Plugin
$out = '<div style="background:#aaa; padding:5px; margin:5px; color:#000;">dump'; $out = '<div style="background:#aaa; padding:5px; margin:5px; color:#000;">dump';
} }
if(!is_array($var)) { if (!is_array($var)) {
return $this->exportVar('', $var); return $this->exportVar('', $var);
} }
...@@ -55,7 +55,7 @@ class Dwoo_Plugin_dump extends Dwoo_Plugin ...@@ -55,7 +55,7 @@ class Dwoo_Plugin_dump extends Dwoo_Plugin
foreach ($var as $i=>$v) { foreach ($var as $i=>$v) {
if (is_array($v) || (is_object($v) && $v instanceof Iterator)) { if (is_array($v) || (is_object($v) && $v instanceof Iterator)) {
$out .= $i.' ('.(is_array($v) ? 'array':'object:'.get_class($v)).')'; $out .= $i.' ('.(is_array($v) ? 'array':'object:'.get_class($v)).')';
if($v===$scope) { if ($v===$scope) {
$out .= ' (current scope):<div style="background:#ccc;padding-left:20px;">'.$this->export($v, $scope).'</div>'; $out .= ' (current scope):<div style="background:#ccc;padding-left:20px;">'.$this->export($v, $scope).'</div>';
} else { } else {
$out .= ':<div style="padding-left:20px;">'.$this->export($v, $scope).'</div>'; $out .= ':<div style="padding-left:20px;">'.$this->export($v, $scope).'</div>';
......
...@@ -25,8 +25,9 @@ ...@@ -25,8 +25,9 @@
*/ */
function Dwoo_Plugin_escape(Dwoo $dwoo, $value='', $format='html', $charset=null) function Dwoo_Plugin_escape(Dwoo $dwoo, $value='', $format='html', $charset=null)
{ {
if($charset === null) if ($charset === null) {
$charset = $dwoo->getCharset(); $charset = $dwoo->getCharset();
}
switch($format) switch($format)
{ {
...@@ -50,7 +51,7 @@ function Dwoo_Plugin_escape(Dwoo $dwoo, $value='', $format='html', $charset=null ...@@ -50,7 +51,7 @@ function Dwoo_Plugin_escape(Dwoo $dwoo, $value='', $format='html', $charset=null
case 'hexentity': case 'hexentity':
$out = ''; $out = '';
$cnt = strlen((string) $value); $cnt = strlen((string) $value);
for($i=0; $i < $cnt; $i++) for ($i=0; $i < $cnt; $i++)
$out .= '&#x' . bin2hex((string) $value[$i]) . ';'; $out .= '&#x' . bin2hex((string) $value[$i]) . ';';
return $out; return $out;
case 'javascript': case 'javascript':
......
...@@ -31,14 +31,16 @@ ...@@ -31,14 +31,16 @@
*/ */
function Dwoo_Plugin_eval(Dwoo $dwoo, $var, $assign = null) function Dwoo_Plugin_eval(Dwoo $dwoo, $var, $assign = null)
{ {
if($var == '') if ($var == '') {
return; return;
}
$tpl = new Dwoo_Template_String($var); $tpl = new Dwoo_Template_String($var);
$out = $dwoo->get($var, $dwoo->readVar('_parent')); $out = $dwoo->get($var, $dwoo->readVar('_parent'));
if($assign !== null) if ($assign !== null) {
$dwoo->assignInScope($out, $assign); $dwoo->assignInScope($out, $assign);
else } else {
return $out; return $out;
}
} }
...@@ -34,45 +34,38 @@ class Dwoo_Plugin_extends extends Dwoo_Plugin implements Dwoo_ICompilable ...@@ -34,45 +34,38 @@ class Dwoo_Plugin_extends extends Dwoo_Plugin implements Dwoo_ICompilable
self::$l = preg_quote($l); self::$l = preg_quote($l);
self::$r = preg_quote($r); self::$r = preg_quote($r);
if($compiler->getLooseOpeningHandling()) if ($compiler->getLooseOpeningHandling()) {
{
self::$l .= '\s*'; self::$l .= '\s*';
self::$r = '\s*'.self::$r; self::$r = '\s*'.self::$r;
} }
$inheritanceTree = array(array('source'=>$compiler->getTemplateSource())); $inheritanceTree = array(array('source'=>$compiler->getTemplateSource()));
while(!empty($file)) while (!empty($file)) {
{ if ($file === '""' || $file === "''" || (substr($file, 0, 1) !== '"' && substr($file, 0, 1) !== '"')) {
if($file === '""' || $file === "''" || (substr($file, 0, 1) !== '"' && substr($file, 0, 1) !== '"'))
{
throw new Dwoo_Compilation_Exception('Extends : The file name must be a non-empty string'); throw new Dwoo_Compilation_Exception('Extends : The file name must be a non-empty string');
return; return;
} }
if(preg_match('#^["\']([a-z]{2,}):(.*?)["\']$#i', $file, $m)) if (preg_match('#^["\']([a-z]{2,}):(.*?)["\']$#i', $file, $m)) {
{
$resource = $m[1]; $resource = $m[1];
$identifier = $m[2]; $identifier = $m[2];
} } else {
else
{
$resource = 'file'; $resource = 'file';
$identifier = substr($file, 1, -1); $identifier = substr($file, 1, -1);
} }
if($resource === 'file' && $policy = $compiler->getSecurityPolicy()) if ($resource === 'file' && $policy = $compiler->getSecurityPolicy()) {
{ while (true) {
while(true) if (preg_match('{^([a-z]+?)://}i', $identifier)) {
{
if(preg_match('{^([a-z]+?)://}i', $identifier))
throw new Dwoo_Security_Exception('The security policy prevents you to read files from external sources.'); throw new Dwoo_Security_Exception('The security policy prevents you to read files from external sources.');
}
$identifier = realpath($identifier); $identifier = realpath($identifier);
$dirs = $policy->getAllowedDirectories(); $dirs = $policy->getAllowedDirectories();
foreach($dirs as $dir=>$dummy) foreach ($dirs as $dir=>$dummy) {
{ if (strpos($identifier, $dir) === 0) {
if(strpos($identifier, $dir) === 0)
break 2; break 2;
}
} }
throw new Dwoo_Security_Exception('The security policy prevents you to read <em>'.$identifier.'</em>'); throw new Dwoo_Security_Exception('The security policy prevents you to read <em>'.$identifier.'</em>');
} }
...@@ -84,39 +77,41 @@ class Dwoo_Plugin_extends extends Dwoo_Plugin implements Dwoo_ICompilable ...@@ -84,39 +77,41 @@ class Dwoo_Plugin_extends extends Dwoo_Plugin implements Dwoo_ICompilable
throw new Dwoo_Compilation_Exception('Extends : Resource <em>'.$resource.'</em> was not added to Dwoo, can not include <em>'.$identifier.'</em>'); throw new Dwoo_Compilation_Exception('Extends : Resource <em>'.$resource.'</em> was not added to Dwoo, can not include <em>'.$identifier.'</em>');
} }
if($parent === null) if ($parent === null) {
throw new Dwoo_Compilation_Exception('Extends : Resource "'.$resource.':'.$identifier.'" was not found.'); throw new Dwoo_Compilation_Exception('Extends : Resource "'.$resource.':'.$identifier.'" was not found.');
elseif($parent === false) } elseif ($parent === false) {
throw new Dwoo_Compilation_Exception('Extends : Extending "'.$resource.':'.$identifier.'" was not allowed for an unknown reason.'); throw new Dwoo_Compilation_Exception('Extends : Extending "'.$resource.':'.$identifier.'" was not allowed for an unknown reason.');
}
$newParent = array('source'=>$parent->getSource(), 'resource'=>$resource, 'identifier'=>$identifier, 'uid'=>$parent->getUid()); $newParent = array('source'=>$parent->getSource(), 'resource'=>$resource, 'identifier'=>$identifier, 'uid'=>$parent->getUid());
if(array_search($newParent, $inheritanceTree, true) !== false) if (array_search($newParent, $inheritanceTree, true) !== false) {
{
throw new Dwoo_Compilation_Exception('Extends : Recursive template inheritance detected'); throw new Dwoo_Compilation_Exception('Extends : Recursive template inheritance detected');
} }
$inheritanceTree[] = $newParent; $inheritanceTree[] = $newParent;
if(preg_match('/^'.self::$l.'extends\s+(?:file=)?\s*(\S+?)'.self::$r.'/i', $parent->getSource(), $match)) if (preg_match('/^'.self::$l.'extends\s+(?:file=)?\s*(\S+?)'.self::$r.'/i', $parent->getSource(), $match)) {
$file = (substr($match[1], 0, 1) !== '"' && substr($match[1], 0, 1) !== '"') ? '"'.str_replace('"', '\\"', $match[1]).'"' : $match[1]; $file = (substr($match[1], 0, 1) !== '"' && substr($match[1], 0, 1) !== '"') ? '"'.str_replace('"', '\\"', $match[1]).'"' : $match[1];
else } else {
$file = false; $file = false;
}
} }
while(true) while (true) {
{
$parent = array_pop($inheritanceTree); $parent = array_pop($inheritanceTree);
$child = end($inheritanceTree); $child = end($inheritanceTree);
self::$childSource = $child['source']; self::$childSource = $child['source'];
self::$lastReplacement = count($inheritanceTree) === 1; self::$lastReplacement = count($inheritanceTree) === 1;
if(!isset($newSource)) if (!isset($newSource)) {
$newSource = $parent['source']; $newSource = $parent['source'];
}
$newSource = preg_replace_callback('/'.self::$l.'block (["\']?)(.+?)\1'.self::$r.'(?:\r?\n?)(.*?)(?:\r?\n?)'.self::$l.'\/block'.self::$r.'/is', array('Dwoo_Plugin_extends', 'replaceBlock'), $newSource); $newSource = preg_replace_callback('/'.self::$l.'block (["\']?)(.+?)\1'.self::$r.'(?:\r?\n?)(.*?)(?:\r?\n?)'.self::$l.'\/block'.self::$r.'/is', array('Dwoo_Plugin_extends', 'replaceBlock'), $newSource);
$newSource = $l.'do extendsCheck("'.$parent['resource'].':'.$parent['identifier'].'" "'.str_replace('"', '\\"', $parent['uid']).'")'.$r.$newSource; $newSource = $l.'do extendsCheck("'.$parent['resource'].':'.$parent['identifier'].'" "'.str_replace('"', '\\"', $parent['uid']).'")'.$r.$newSource;
if(self::$lastReplacement) if (self::$lastReplacement) {
break; break;
}
} }
$compiler->setTemplateSource($newSource); $compiler->setTemplateSource($newSource);
...@@ -125,22 +120,21 @@ class Dwoo_Plugin_extends extends Dwoo_Plugin implements Dwoo_ICompilable ...@@ -125,22 +120,21 @@ class Dwoo_Plugin_extends extends Dwoo_Plugin implements Dwoo_ICompilable
protected static function replaceBlock(array $matches) protected static function replaceBlock(array $matches)
{ {
if(preg_match('/'.self::$l.'block (["\']?)'.preg_quote($matches[2]).'\1'.self::$r.'(?:\r?\n?)(.*?)(?:\r?\n?)'.self::$l.'\/block'.self::$r.'/is', self::$childSource, $override)) if (preg_match('/'.self::$l.'block (["\']?)'.preg_quote($matches[2]).'\1'.self::$r.'(?:\r?\n?)(.*?)(?:\r?\n?)'.self::$l.'\/block'.self::$r.'/is', self::$childSource, $override)) {
{
$l = stripslashes(self::$l); $l = stripslashes(self::$l);
$r = stripslashes(self::$r); $r = stripslashes(self::$r);
if(self::$lastReplacement) if (self::$lastReplacement) {
return preg_replace('/'.self::$l.'\$dwoo\.parent'.self::$r.'/is', $matches[3], $override[2]); return preg_replace('/'.self::$l.'\$dwoo\.parent'.self::$r.'/is', $matches[3], $override[2]);
else } else {
return $l.'block '.$matches[1].$matches[2].$matches[1].$r.preg_replace('/'.self::$l.'\$dwoo\.parent'.self::$r.'/is', $matches[3], $override[2]).$l.'/block'.$r; return $l.'block '.$matches[1].$matches[2].$matches[1].$r.preg_replace('/'.self::$l.'\$dwoo\.parent'.self::$r.'/is', $matches[3], $override[2]).$l.'/block'.$r;
} }
else } else {
{ if (self::$lastReplacement) {
if(self::$lastReplacement)
return $matches[3]; return $matches[3];
else } else {
return $matches[0]; return $matches[0];
}
} }
} }
} }
...@@ -31,9 +31,9 @@ try { ...@@ -31,9 +31,9 @@ try {
} catch (Dwoo_Exception $e) { } catch (Dwoo_Exception $e) {
$this->triggerError(\'Extends : Resource <em>'.$resource.'</em> was not added to Dwoo, can not include <em>'.$identifier.'</em>\', E_USER_WARNING); $this->triggerError(\'Extends : Resource <em>'.$resource.'</em> was not added to Dwoo, can not include <em>'.$identifier.'</em>\', E_USER_WARNING);
} }
if($tpl === null) if ($tpl === null)
$this->triggerError(\'Extends : Resource "'.$resource.':'.$identifier.'" was not found.\', E_USER_WARNING); $this->triggerError(\'Extends : Resource "'.$resource.':'.$identifier.'" was not found.\', E_USER_WARNING);
elseif($tpl === false) elseif ($tpl === false)
$this->triggerError(\'Include : Extending "'.$resource.':'.$identifier.'" was not allowed for an unknown reason.\', E_USER_WARNING); $this->triggerError(\'Include : Extending "'.$resource.':'.$identifier.'" was not allowed for an unknown reason.\', E_USER_WARNING);
if($tpl->getUid() !== "'.substr($uid, 1, -1).'") { ob_end_clean(); return false; }'; if ($tpl->getUid() !== "'.substr($uid, 1, -1).'") { ob_end_clean(); return false; }';
} }
...@@ -24,22 +24,23 @@ ...@@ -24,22 +24,23 @@
*/ */
function Dwoo_Plugin_fetch(Dwoo $dwoo, $file, $assign = null) function Dwoo_Plugin_fetch(Dwoo $dwoo, $file, $assign = null)
{ {
if($file === '') if ($file === '') {
return; return;
}
if($policy = $dwoo->getSecurityPolicy()) if ($policy = $dwoo->getSecurityPolicy())
{ {
while(true) while (true) {
{ if (preg_match('{^([a-z]+?)://}i', $file)) {
if(preg_match('{^([a-z]+?)://}i', $file))
return $dwoo->triggerError('The security policy prevents you to read files from external sources.', E_USER_WARNING); return $dwoo->triggerError('The security policy prevents you to read files from external sources.', E_USER_WARNING);
}
$file = realpath($file); $file = realpath($file);
$dirs = $policy->getAllowedDirectories(); $dirs = $policy->getAllowedDirectories();
foreach($dirs as $dir=>$dummy) foreach ($dirs as $dir=>$dummy) {
{ if (strpos($file, $dir) === 0) {
if(strpos($file, $dir) === 0)
break 2; break 2;
}
} }
return $dwoo->triggerError('The security policy prevents you to read <em>'.$file.'</em>', E_USER_WARNING); return $dwoo->triggerError('The security policy prevents you to read <em>'.$file.'</em>', E_USER_WARNING);
} }
...@@ -48,8 +49,9 @@ function Dwoo_Plugin_fetch(Dwoo $dwoo, $file, $assign = null) ...@@ -48,8 +49,9 @@ function Dwoo_Plugin_fetch(Dwoo $dwoo, $file, $assign = null)
$out = file_get_contents($file); $out = file_get_contents($file);
if($assign !== null) if ($assign !== null) {
$dwoo->assignInScope($out, $assign); $dwoo->assignInScope($out, $assign);
else } else {
return $out; return $out;
}
} }
...@@ -29,34 +29,34 @@ ...@@ -29,34 +29,34 @@
*/ */
function Dwoo_Plugin_include(Dwoo $dwoo, $file, $cache_time = null, $cache_id = null, $compile_id = null, $data = '_root', $assign = null, array $rest = array()) function Dwoo_Plugin_include(Dwoo $dwoo, $file, $cache_time = null, $cache_id = null, $compile_id = null, $data = '_root', $assign = null, array $rest = array())
{ {
if($file === '') if ($file === '') {
return; return;
}
if(preg_match('#^([a-z]{2,}):(.*)#i', $file, $m)) if (preg_match('#^([a-z]{2,}):(.*)#i', $file, $m))
{ {
$resource = $m[1]; $resource = $m[1];
$identifier = $m[2]; $identifier = $m[2];
} } else
else
{ {
// get the current template's resource // get the current template's resource
$resource = $dwoo->getTemplate()->getResourceName(); $resource = $dwoo->getTemplate()->getResourceName();
$identifier = $file; $identifier = $file;
} }
if($resource === 'file' && $policy = $dwoo->getSecurityPolicy()) if ($resource === 'file' && $policy = $dwoo->getSecurityPolicy())
{ {
while(true) while (true) {
{ if (preg_match('{^([a-z]+?)://}i', $identifier)) {
if(preg_match('{^([a-z]+?)://}i', $identifier))
throw new Dwoo_Security_Exception('The security policy prevents you to read files from external sources : <em>'.$identifier.'</em>.'); throw new Dwoo_Security_Exception('The security policy prevents you to read files from external sources : <em>'.$identifier.'</em>.');
}
$identifier = realpath($identifier); $identifier = realpath($identifier);
$dirs = $policy->getAllowedDirectories(); $dirs = $policy->getAllowedDirectories();
foreach($dirs as $dir=>$dummy) foreach ($dirs as $dir=>$dummy) {
{ if (strpos($identifier, $dir) === 0) {
if(strpos($identifier, $dir) === 0)
break 2; break 2;
}
} }
throw new Dwoo_Security_Exception('The security policy prevents you to read <em>'.$identifier.'</em>'); throw new Dwoo_Security_Exception('The security policy prevents you to read <em>'.$identifier.'</em>');
} }
...@@ -68,27 +68,30 @@ function Dwoo_Plugin_include(Dwoo $dwoo, $file, $cache_time = null, $cache_id = ...@@ -68,27 +68,30 @@ function Dwoo_Plugin_include(Dwoo $dwoo, $file, $cache_time = null, $cache_id =
$dwoo->triggerError('Include : Resource <em>'.$resource.'</em> was not added to Dwoo, can not include <em>'.$identifier.'</em>', E_USER_WARNING); $dwoo->triggerError('Include : Resource <em>'.$resource.'</em> was not added to Dwoo, can not include <em>'.$identifier.'</em>', E_USER_WARNING);
} }
if($include === null) if ($include === null) {
return; return;
elseif($include === false) } elseif ($include === false) {
$dwoo->triggerError('Include : Including "'.$resource.':'.$identifier.'" was not allowed for an unknown reason.', E_USER_WARNING); $dwoo->triggerError('Include : Including "'.$resource.':'.$identifier.'" was not allowed for an unknown reason.', E_USER_WARNING);
}
if($dwoo->isArray($data)) if ($dwoo->isArray($data)) {
$vars = $data; $vars = $data;
elseif($dwoo->isArray($cache_time)) } elseif ($dwoo->isArray($cache_time)) {
$vars = $cache_time; $vars = $cache_time;
else } else {
$vars = $dwoo->readVar($data); $vars = $dwoo->readVar($data);
}
if(count($rest)) if (count($rest))
{ {
$vars = $rest + $vars; $vars = $rest + $vars;
} }
$out = $dwoo->get($include, $vars); $out = $dwoo->get($include, $vars);
if($assign !== null) if ($assign !== null) {
$dwoo->assignInScope($out, $assign); $dwoo->assignInScope($out, $assign);
else } else {
return $out; return $out;
}
} }
...@@ -31,24 +31,31 @@ ...@@ -31,24 +31,31 @@
*/ */
function Dwoo_Plugin_mailto(Dwoo $dwoo, $address, $text=null, $subject=null, $encode=null, $cc=null, $bcc=null, $newsgroups=null, $followupto=null, $extra=null) function Dwoo_Plugin_mailto(Dwoo $dwoo, $address, $text=null, $subject=null, $encode=null, $cc=null, $bcc=null, $newsgroups=null, $followupto=null, $extra=null)
{ {
if(empty($address)) if (empty($address)) {
return ''; return '';
if(empty($text)) }
if (empty($text)) {
$text = $address; $text = $address;
}
// build address string // build address string
$address .= '?'; $address .= '?';
if(!empty($subject)) if (!empty($subject)) {
$address .= 'subject='.rawurlencode($subject).'&'; $address .= 'subject='.rawurlencode($subject).'&';
if(!empty($cc)) }
if (!empty($cc)) {
$address .= 'cc='.rawurlencode($cc).'&'; $address .= 'cc='.rawurlencode($cc).'&';
if(!empty($bcc)) }
if (!empty($bcc)) {
$address .= 'bcc='.rawurlencode($bcc).'&'; $address .= 'bcc='.rawurlencode($bcc).'&';
if(!empty($newsgroup)) }
if (!empty($newsgroup)) {
$address .= 'newsgroups='.rawurlencode($newsgroups).'&'; $address .= 'newsgroups='.rawurlencode($newsgroups).'&';
if(!empty($followupto)) }
if (!empty($followupto)) {
$address .= 'followupto='.rawurlencode($followupto).'&'; $address .= 'followupto='.rawurlencode($followupto).'&';
}
$address = rtrim($address, '?&'); $address = rtrim($address, '?&');
...@@ -86,17 +93,18 @@ function Dwoo_Plugin_mailto(Dwoo $dwoo, $address, $text=null, $subject=null, $en ...@@ -86,17 +93,18 @@ function Dwoo_Plugin_mailto(Dwoo $dwoo, $address, $text=null, $subject=null, $en
break; break;
case 'hex': case 'hex':
if(strpos($address, '?') !== false) if (strpos($address, '?') !== false) {
$dwoo->triggerError('Mailto: Hex encoding is not possible with extra attributes, use one of : <em>js, jscharcode or none</em>.', E_USER_WARNING); $dwoo->triggerError('Mailto: Hex encoding is not possible with extra attributes, use one of : <em>js, jscharcode or none</em>.', E_USER_WARNING);
}
$out = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;'; $out = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;';
$len = strlen($address); $len = strlen($address);
for ($i=0; $i<$len; $i++) for ($i=0; $i<$len; $i++) {
{ if (preg_match('#\w#', $address[$i])) {
if(preg_match('#\w#', $address[$i]))
$out .= '%'.bin2hex($address[$i]); $out .= '%'.bin2hex($address[$i]);
else } else {
$out .= $address[$i]; $out .= $address[$i];
}
} }
$out .= '" '.$extra.'>'; $out .= '" '.$extra.'>';
$len = strlen($text); $len = strlen($text);
......
...@@ -65,8 +65,7 @@ function Dwoo_Plugin_math_compile(Dwoo_Compiler $compiler, $equation, $format='' ...@@ -65,8 +65,7 @@ function Dwoo_Plugin_math_compile(Dwoo_Compiler $compiler, $equation, $format=''
$out = ''; $out = '';
$ptr = 1; $ptr = 1;
$allowcomma = 0; $allowcomma = 0;
while(strlen($equation) > 0) while (strlen($equation) > 0) {
{
$substr = substr($equation, 0, $ptr); $substr = substr($equation, 0, $ptr);
// allowed string // allowed string
if (array_search($substr, $allowed) !== false) { if (array_search($substr, $allowed) !== false) {
...@@ -80,31 +79,31 @@ function Dwoo_Plugin_math_compile(Dwoo_Compiler $compiler, $equation, $format='' ...@@ -80,31 +79,31 @@ function Dwoo_Plugin_math_compile(Dwoo_Compiler $compiler, $equation, $format=''
$equation = substr($equation, $ptr); $equation = substr($equation, $ptr);
$ptr = 0; $ptr = 0;
$allowcomma++; $allowcomma++;
if($allowcomma === 1) { if ($allowcomma === 1) {
$allowed[] = ','; $allowed[] = ',';
} }
} }
// variable // variable
elseif(isset($rest[$substr])) elseif (isset($rest[$substr])) {
{
$out.=$rest[$substr]; $out.=$rest[$substr];
$equation = substr($equation, $ptr); $equation = substr($equation, $ptr);
$ptr = 0; $ptr = 0;
} }
// pre-replaced variable // pre-replaced variable
elseif($substr === $open) elseif ($substr === $open) {
{
preg_match('#.*\((?:[^()]*?|(?R))\)'.str_replace('.', '\\.', $close).'#', substr($equation, 2), $m); preg_match('#.*\((?:[^()]*?|(?R))\)'.str_replace('.', '\\.', $close).'#', substr($equation, 2), $m);
if(empty($m)) if (empty($m)) {
preg_match('#.*?'.str_replace('.', '\\.', $close).'#', substr($equation, 2), $m); preg_match('#.*?'.str_replace('.', '\\.', $close).'#', substr($equation, 2), $m);
}
$out.=substr($m[0], 0, -2); $out.=substr($m[0], 0, -2);
$equation = substr($equation, strlen($m[0])+2); $equation = substr($equation, strlen($m[0])+2);
$ptr = 0; $ptr = 0;
} }
// opening parenthesis // opening parenthesis
elseif ($substr==='(') { elseif ($substr==='(') {
if($allowcomma>0) if ($allowcomma>0) {
$allowcomma++; $allowcomma++;
}
$out.=$substr; $out.=$substr;
$equation = substr($equation, $ptr); $equation = substr($equation, $ptr);
...@@ -112,9 +111,9 @@ function Dwoo_Plugin_math_compile(Dwoo_Compiler $compiler, $equation, $format='' ...@@ -112,9 +111,9 @@ function Dwoo_Plugin_math_compile(Dwoo_Compiler $compiler, $equation, $format=''
} }
// closing parenthesis // closing parenthesis
elseif ($substr===')') { elseif ($substr===')') {
if($allowcomma>0) { if ($allowcomma>0) {
$allowcomma--; $allowcomma--;
if($allowcomma===0) { if ($allowcomma===0) {
array_pop($allowed); array_pop($allowed);
} }
} }
...@@ -127,15 +126,15 @@ function Dwoo_Plugin_math_compile(Dwoo_Compiler $compiler, $equation, $format='' ...@@ -127,15 +126,15 @@ function Dwoo_Plugin_math_compile(Dwoo_Compiler $compiler, $equation, $format=''
elseif ($ptr >= strlen($equation)) { elseif ($ptr >= strlen($equation)) {
throw new Dwoo_Compilation_Exception('Math : Syntax error or variable undefined in equation '.$equationSrc.' at '.$substr); throw new Dwoo_Compilation_Exception('Math : Syntax error or variable undefined in equation '.$equationSrc.' at '.$substr);
return; return;
} } else {
else
{
$ptr++; $ptr++;
} }
} }
if($format !== '\'\'') if ($format !== '\'\'') {
$out = 'sprintf('.$format.', '.$out.')'; $out = 'sprintf('.$format.', '.$out.')';
if($assign !== '\'\'') }
if ($assign !== '\'\'') {
return '($this->assignInScope('.$out.', '.$assign.'))'; return '($this->assignInScope('.$out.', '.$assign.'))';
}
return '('.$out.')'; return '('.$out.')';
} }
...@@ -26,10 +26,11 @@ ...@@ -26,10 +26,11 @@
function Dwoo_Plugin_regex_replace(Dwoo $dwoo, $value, $search, $replace) function Dwoo_Plugin_regex_replace(Dwoo $dwoo, $value, $search, $replace)
{ {
// Credits for this to Monte Ohrt who made smarty's regex_replace modifier // Credits for this to Monte Ohrt who made smarty's regex_replace modifier
if(($pos = strpos($search,"\0")) !== false) if (($pos = strpos($search,"\0")) !== false) {
$search = substr($search,0,$pos); $search = substr($search,0,$pos);
}
if(preg_match('#([a-z\s]+)$#i', $search, $m) && strpos($m[0], 'e') !== false) { if (preg_match('#([a-z\s]+)$#i', $search, $m) && strpos($m[0], 'e') !== false) {
$search = substr($search, 0, -strlen($m[0])) . str_replace('e', '', $m[0]); $search = substr($search, 0, -strlen($m[0])) . str_replace('e', '', $m[0]);
} }
......
...@@ -24,8 +24,9 @@ ...@@ -24,8 +24,9 @@
*/ */
function Dwoo_Plugin_reverse(Dwoo $dwoo, $value, $preserve_keys=false) function Dwoo_Plugin_reverse(Dwoo $dwoo, $value, $preserve_keys=false)
{ {
if(is_array($value)) if (is_array($value)) {
return array_reverse($value, $preserve_keys); return array_reverse($value, $preserve_keys);
else } else {
return implode('',array_reverse(str_split((string) $value,1))); return implode('',array_reverse(str_split((string) $value,1)));
}
} }
...@@ -24,8 +24,9 @@ ...@@ -24,8 +24,9 @@
*/ */
function Dwoo_Plugin_strip_tags_compile(Dwoo_Compiler $compiler, $value, $addspace=true) function Dwoo_Plugin_strip_tags_compile(Dwoo_Compiler $compiler, $value, $addspace=true)
{ {
if($addspace==='true') if ($addspace==='true') {
return "preg_replace('#<[^>]*>#', ' ', $value)"; return "preg_replace('#<[^>]*>#', ' ', $value)";
else } else {
return "strip_tags($value)"; return "strip_tags($value)";
}
} }
...@@ -27,20 +27,24 @@ ...@@ -27,20 +27,24 @@
*/ */
function Dwoo_Plugin_truncate(Dwoo $dwoo, $value, $length=80, $etc='...', $break=false, $middle=false) function Dwoo_Plugin_truncate(Dwoo $dwoo, $value, $length=80, $etc='...', $break=false, $middle=false)
{ {
if($length == 0) if ($length == 0) {
return ''; return '';
}
$value = (string) $value; $value = (string) $value;
$etc = (string) $etc; $etc = (string) $etc;
$length = (int) $length; $length = (int) $length;
if(strlen($value) < $length) if (strlen($value) < $length) {
return $value; return $value;
}
$length = max($length - strlen($etc), 0); $length = max($length - strlen($etc), 0);
if($break === false && $middle === false) if ($break === false && $middle === false) {
$value = preg_replace('#\s*(\S*)?$#', '', substr($value, 0, $length+1)); $value = preg_replace('#\s*(\S*)?$#', '', substr($value, 0, $length+1));
if($middle === false) }
if ($middle === false) {
return substr($value, 0, $length) . $etc; return substr($value, 0, $length) . $etc;
}
return substr($value, 0, ceil($length/2)) . $etc . substr($value, -floor($length/2)); return substr($value, 0, ceil($length/2)) . $etc . substr($value, -floor($length/2));
} }
...@@ -31,11 +31,12 @@ ...@@ -31,11 +31,12 @@
function Dwoo_Plugin_array_compile(Dwoo_Compiler $compiler, array $rest=array()) function Dwoo_Plugin_array_compile(Dwoo_Compiler $compiler, array $rest=array())
{ {
$out = array(); $out = array();
foreach($rest as $k=>$v) foreach ($rest as $k=>$v)
if(is_numeric($k)) if (is_numeric($k)) {
$out[] = $k.'=>'.$v; $out[] = $k.'=>'.$v;
else } else {
$out[] = '"'.$k.'"=>'.$v; $out[] = '"'.$k.'"=>'.$v;
}
return 'array('.implode(', ', $out).')'; return 'array('.implode(', ', $out).')';
} }
...@@ -54,8 +54,9 @@ class Dwoo_Processor_smarty_compat extends Dwoo_Processor ...@@ -54,8 +54,9 @@ class Dwoo_Processor_smarty_compat extends Dwoo_Processor
' ?>', ' ?>',
); );
if(preg_match('{\|@([a-z][a-z0-9_]*)}i', $input, $matches)) if (preg_match('{\|@([a-z][a-z0-9_]*)}i', $input, $matches)) {
trigger_error('The Smarty Compatibility Module has detected that you use |@'.$matches[1].' in your template, this might lead to problems as Dwoo interprets the @ operator differently than Smarty, see http://wiki.dwoo.org/index.php/Syntax#The_.40_Operator', E_USER_NOTICE); trigger_error('The Smarty Compatibility Module has detected that you use |@'.$matches[1].' in your template, this might lead to problems as Dwoo interprets the @ operator differently than Smarty, see http://wiki.dwoo.org/index.php/Syntax#The_.40_Operator', E_USER_NOTICE);
}
return preg_replace($smarty, $dwoo, $input); return preg_replace($smarty, $dwoo, $input);
} }
...@@ -64,65 +65,72 @@ class Dwoo_Processor_smarty_compat extends Dwoo_Processor ...@@ -64,65 +65,72 @@ class Dwoo_Processor_smarty_compat extends Dwoo_Processor
{ {
$params = array(); $params = array();
$index = 1; $index = 1;
while(!empty($matches[$index]) && $index < 13) while (!empty($matches[$index]) && $index < 13) {
{
$params[$matches[$index]] = $matches[$index+1]; $params[$matches[$index]] = $matches[$index+1];
$index += 2; $index += 2;
} }
$params['content'] = $matches[13]; $params['content'] = $matches[13];
if(isset($matches[14]) && !empty($matches[14])) if (isset($matches[14]) && !empty($matches[14])) {
$params['altcontent'] = $matches[14]; $params['altcontent'] = $matches[14];
}
if(empty($params['name'])) if (empty($params['name'])) {
throw new Dwoo_Compilation_Exception('Missing parameter <em>name</em> for section tag'); throw new Dwoo_Compilation_Exception('Missing parameter <em>name</em> for section tag');
}
$name = $params['name']; $name = $params['name'];
if(isset($params['loop'])) if (isset($params['loop'])) {
$loops = $params['loop']; $loops = $params['loop'];
}
if(isset($params['max'])) if (isset($params['max'])) {
$max = $params['max']; $max = $params['max'];
}
if(isset($params['start'])) if (isset($params['start'])) {
$start = $params['start']; $start = $params['start'];
}
if(isset($params['step'])) if (isset($params['step'])) {
$step = $params['step']; $step = $params['step'];
}
if (!isset($loops)) if (!isset($loops))
$loops = null; $loops = null;
if (!isset($max) || $max < 0) if (!isset($max) || $max < 0) {
{ if (is_numeric($loops)) {
if(is_numeric($loops))
$max = $loops; $max = $loops;
else } else {
$max = 'null'; $max = 'null';
}
} }
if (!isset($step)) if (!isset($step))
$step = 1; $step = 1;
if (!isset($start)) if (!isset($start))
$start = $loops - 1; $start = $loops - 1;
elseif(!is_numeric($loops)) elseif (!is_numeric($loops)) {
$start = 0; $start = 0;
}
list($l, $r) = $this->compiler->getDelimiters(); list($l, $r) = $this->compiler->getDelimiters();
if(is_numeric($loops)) if (is_numeric($loops)) {
{ if (isset($params['start']) && isset($params['loop']) && !isset($params['max'])) {
if(isset($params['start']) && isset($params['loop']) && !isset($params['max']))
$output = $l.'for '.$name.' '.$start.' '.($loops-$step).' '.$step.$r; $output = $l.'for '.$name.' '.$start.' '.($loops-$step).' '.$step.$r;
else } else {
$output = $l.'for '.$name.' '.$start.' '.($start+floor($step*$max+($step>0?-1:1))).' '.$step.$r; $output = $l.'for '.$name.' '.$start.' '.($start+floor($step*$max+($step>0?-1:1))).' '.$step.$r;
} }
else } else {
$output = $l.'for '.$name.' '.$loops.' '.($start+floor($max/$step)).' '.$step.' '.$start.$r; $output = $l.'for '.$name.' '.$loops.' '.($start+floor($max/$step)).' '.$step.' '.$start.$r;
}
$output .= str_replace('['.trim($name, '"\'').']', '[$'.trim($name, '"\'').']', $params['content']); $output .= str_replace('['.trim($name, '"\'').']', '[$'.trim($name, '"\'').']', $params['content']);
if(isset($params['altcontent'])) if (isset($params['altcontent'])) {
$output .= $l.'forelse'.$r.$params['altcontent']; $output .= $l.'forelse'.$r.$params['altcontent'];
}
$output .= $l.'/for'.$r; $output .= $l.'/for'.$r;
......
...@@ -107,7 +107,7 @@ FOObartoplevelContent2 ...@@ -107,7 +107,7 @@ FOObartoplevelContent2
baz")); baz"));
} }
public function testIf() public function testIf ()
{ {
$tpl = new Dwoo_Template_String('{if "BAR"==reverse($foo|reverse|upper)}true{/if}'); $tpl = new Dwoo_Template_String('{if "BAR"==reverse($foo|reverse|upper)}true{/if}');
$tpl->forceCompilation(); $tpl->forceCompilation();
...@@ -135,11 +135,11 @@ baz")); ...@@ -135,11 +135,11 @@ baz"));
$this->assertEquals('true', $this->dwoo->get($tpl, array(), $this->compiler)); $this->assertEquals('true', $this->dwoo->get($tpl, array(), $this->compiler));
// fixes the init call not being called (which is normal) // fixes the init call not being called (which is normal)
$fixCall = new Dwoo_Plugin_if($this->dwoo); $fixCall = new Dwoo_Plugin_if ($this->dwoo);
$fixCall->init(array()); $fixCall->init(array());
} }
public function testIfElseif() public function testIfElseif ()
{ {
$tpl = new Dwoo_Template_String('{if "BAR" == "bar"}true{elseif "BAR"=="BAR"}false{/if}'); $tpl = new Dwoo_Template_String('{if "BAR" == "bar"}true{elseif "BAR"=="BAR"}false{/if}');
$tpl->forceCompilation(); $tpl->forceCompilation();
...@@ -147,7 +147,7 @@ baz")); ...@@ -147,7 +147,7 @@ baz"));
$this->assertEquals('false', $this->dwoo->get($tpl, array(), $this->compiler)); $this->assertEquals('false', $this->dwoo->get($tpl, array(), $this->compiler));
// fixes the init call not being called (which is normal) // fixes the init call not being called (which is normal)
$fixCall = new Dwoo_Plugin_elseif($this->dwoo); $fixCall = new Dwoo_Plugin_elseif ($this->dwoo);
$fixCall->init(array()); $fixCall->init(array());
} }
...@@ -179,7 +179,7 @@ baz")); ...@@ -179,7 +179,7 @@ baz"));
$this->assertEquals('true', $this->dwoo->get($tpl, array('moo'=>'i'), $this->compiler)); $this->assertEquals('true', $this->dwoo->get($tpl, array('moo'=>'i'), $this->compiler));
} }
public function testFor() public function testFor ()
{ {
$tpl = new Dwoo_Template_String('{for name=i from=$sub}{$i}.{$sub[$i]}{/for}'); $tpl = new Dwoo_Template_String('{for name=i from=$sub}{$i}.{$sub[$i]}{/for}');
$tpl->forceCompilation(); $tpl->forceCompilation();
...@@ -187,7 +187,7 @@ baz")); ...@@ -187,7 +187,7 @@ baz"));
$this->assertEquals('0.foo1.bar2.baz3.qux', $this->dwoo->get($tpl, array('sub'=>array('foo','bar','baz','qux')), $this->compiler)); $this->assertEquals('0.foo1.bar2.baz3.qux', $this->dwoo->get($tpl, array('sub'=>array('foo','bar','baz','qux')), $this->compiler));
// fixes the init call not being called (which is normal) // fixes the init call not being called (which is normal)
$fixCall = new Dwoo_Plugin_for($this->dwoo); $fixCall = new Dwoo_Plugin_for ($this->dwoo);
$fixCall->init(null,null); $fixCall->init(null,null);
} }
...@@ -221,7 +221,7 @@ baz")); ...@@ -221,7 +221,7 @@ baz"));
$this->assertEquals('0.foo1.bar', $this->dwoo->get($tpl, array('sub'=>array('foo','bar')), $this->compiler)); $this->assertEquals('0.foo1.bar', $this->dwoo->get($tpl, array('sub'=>array('foo','bar')), $this->compiler));
// fixes the init call not being called (which is normal) // fixes the init call not being called (which is normal)
$fixCall = new Dwoo_Plugin_foreach($this->dwoo); $fixCall = new Dwoo_Plugin_foreach ($this->dwoo);
$fixCall->init(''); $fixCall->init('');
} }
...@@ -235,13 +235,13 @@ baz")); ...@@ -235,13 +235,13 @@ baz"));
public function testForeachDwoo() public function testForeachDwoo()
{ {
// Item only, key arg is mapped to it just as foreach($foo as $item) // Item only, key arg is mapped to it just as foreach ($foo as $item)
$tpl = new Dwoo_Template_String('{foreach $sub item}{$item}{/foreach}'); $tpl = new Dwoo_Template_String('{foreach $sub item}{$item}{/foreach}');
$tpl->forceCompilation(); $tpl->forceCompilation();
$this->assertEquals('foobar', $this->dwoo->get($tpl, array('sub'=>array('foo','bar')), $this->compiler)); $this->assertEquals('foobar', $this->dwoo->get($tpl, array('sub'=>array('foo','bar')), $this->compiler));
// Item and key used, key is second just as foreach($foo as $key=>$item) // Item and key used, key is second just as foreach ($foo as $key=>$item)
$tpl = new Dwoo_Template_String('{foreach $sub key item}{$key}.{$item}{/foreach}'); $tpl = new Dwoo_Template_String('{foreach $sub key item}{$key}.{$item}{/foreach}');
$tpl->forceCompilation(); $tpl->forceCompilation();
......
...@@ -34,8 +34,7 @@ class CallTests extends PHPUnit_Framework_TestCase ...@@ -34,8 +34,7 @@ class CallTests extends PHPUnit_Framework_TestCase
$this->dwoo->removePlugin('test'); $this->dwoo->removePlugin('test');
} }
public function testFullCustomClassPluginByClassMethodCallback() public function testFullCustomClassPluginByClassMethodCallback() {
{
$this->dwoo->addPlugin('test', array('plugin_full_custom', 'process')); $this->dwoo->addPlugin('test', array('plugin_full_custom', 'process'));
$tpl = new Dwoo_Template_String('{test "xxx"}'); $tpl = new Dwoo_Template_String('{test "xxx"}');
$tpl->forceCompilation(); $tpl->forceCompilation();
...@@ -55,7 +54,7 @@ class CallTests extends PHPUnit_Framework_TestCase ...@@ -55,7 +54,7 @@ class CallTests extends PHPUnit_Framework_TestCase
} }
public function testCustomObjectPluginByObjectMethodCallback() public function testCustomObjectPluginByObjectMethodCallback()
{ {
$this->dwoo->addPlugin('test', array(new plugin_full_custom(), 'process')); $this->dwoo->addPlugin('test', array(new plugin_full_custom(), 'process'));
$tpl = new Dwoo_Template_String('{test "xxx"}'); $tpl = new Dwoo_Template_String('{test "xxx"}');
$tpl->forceCompilation(); $tpl->forceCompilation();
......
...@@ -237,8 +237,9 @@ class CompilerTests extends PHPUnit_Framework_TestCase ...@@ -237,8 +237,9 @@ class CompilerTests extends PHPUnit_Framework_TestCase
public function testConstants() public function testConstants()
{ {
if(!defined('TEST')) if (!defined('TEST')) {
define('TEST', 'Test'); define('TEST', 'Test');
}
$tpl = new Dwoo_Template_String('{$dwoo.const.TEST} {$dwoo.const.Dwoo::FUNC_PLUGIN*$dwoo.const.Dwoo::BLOCK_PLUGIN}'); $tpl = new Dwoo_Template_String('{$dwoo.const.TEST} {$dwoo.const.Dwoo::FUNC_PLUGIN*$dwoo.const.Dwoo::BLOCK_PLUGIN}');
$tpl->forceCompilation(); $tpl->forceCompilation();
...@@ -247,8 +248,9 @@ class CompilerTests extends PHPUnit_Framework_TestCase ...@@ -247,8 +248,9 @@ class CompilerTests extends PHPUnit_Framework_TestCase
public function testShortConstants() public function testShortConstants()
{ {
if(!defined('TEST')) if (!defined('TEST')) {
define('TEST', 'Test'); define('TEST', 'Test');
}
$tpl = new Dwoo_Template_String('{%TEST} {$dwoo.const.Dwoo::FUNC_PLUGIN*%Dwoo::BLOCK_PLUGIN}'); $tpl = new Dwoo_Template_String('{%TEST} {$dwoo.const.Dwoo::FUNC_PLUGIN*%Dwoo::BLOCK_PLUGIN}');
$tpl->forceCompilation(); $tpl->forceCompilation();
......
<?php <?php
error_reporting(E_ALL|E_STRICT); error_reporting(E_ALL|E_STRICT);
if(!ini_get('date.timezone')) if (!ini_get('date.timezone'))
date_default_timezone_set('CET'); date_default_timezone_set('CET');
define('DWOO_CACHE_DIRECTORY', dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR.'cache'); define('DWOO_CACHE_DIRECTORY', dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR.'cache');
define('DWOO_COMPILE_DIRECTORY', dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR.'compiled'); define('DWOO_COMPILE_DIRECTORY', dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR.'compiled');
...@@ -17,9 +17,8 @@ class DwooTests extends PHPUnit_Framework_TestSuite { ...@@ -17,9 +17,8 @@ class DwooTests extends PHPUnit_Framework_TestSuite {
$suite = new self('Dwoo - Unit Tests Report'); $suite = new self('Dwoo - Unit Tests Report');
foreach(new DirectoryIterator(dirname(__FILE__)) as $file) { foreach (new DirectoryIterator(dirname(__FILE__)) as $file) {
if(!$file->isDot() && !$file->isDir() && (string) $file !== 'DwooTests.php' && substr((string) $file, -4) === '.php') if (!$file->isDot() && !$file->isDir() && (string) $file !== 'DwooTests.php' && substr((string) $file, -4) === '.php') {
{
require_once $file->getPathname(); require_once $file->getPathname();
$suite->addTestSuite(basename($file, '.php')); $suite->addTestSuite(basename($file, '.php'));
} }
...@@ -28,22 +27,21 @@ class DwooTests extends PHPUnit_Framework_TestSuite { ...@@ -28,22 +27,21 @@ class DwooTests extends PHPUnit_Framework_TestSuite {
return $suite; return $suite;
} }
protected function tearDown() protected function tearDown() {
{
$this->clearDir(TEST_DIRECTORY.'/temp/compiled', true); $this->clearDir(TEST_DIRECTORY.'/temp/compiled', true);
} }
protected function clearDir($path, $emptyOnly=false) protected function clearDir($path, $emptyOnly=false)
{ {
if(is_dir($path)) if (is_dir($path)) {
{ foreach (glob($path.'/*') as $f)
foreach(glob($path.'/*') as $f)
$this->clearDir($f); $this->clearDir($f);
if(!$emptyOnly) if (!$emptyOnly) {
rmdir($path); rmdir($path);
} }
else } else {
unlink($path); unlink($path);
}
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment