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
+ API: Added Dwoo_Compiler->setAutoEscape() and getAutoEscape() to modify the
automatic html entity escaping setting. This is disabled by default, and when
......
......@@ -47,18 +47,15 @@ class Dwoo_Data implements Dwoo_IDataProvider
*/
public function clear($name = null)
{
if($name === null)
{
if ($name === null) {
$this->data = array();
}
elseif(is_array($name))
{
foreach($name as $index)
} elseif (is_array($name)) {
foreach ($name as $index)
unset($this->data[$index]);
}
else
} else {
unset($this->data[$name]);
}
}
/**
* overwrites the entire data with the given array
......@@ -79,10 +76,11 @@ class Dwoo_Data implements Dwoo_IDataProvider
public function mergeData(array $data)
{
$args = func_get_args();
while(list(,$v) = each($args))
if(is_array($v))
while (list(,$v) = each($args))
if (is_array($v)) {
$this->data = array_merge($this->data, $v);
}
}
/**
* assigns a value or an array of values to the data object
......@@ -94,15 +92,14 @@ class Dwoo_Data implements Dwoo_IDataProvider
*/
public function assign($name, $val = null)
{
if(is_array($name))
{
if (is_array($name)) {
reset($name);
while(list($k,$v) = each($name))
while (list($k,$v) = each($name))
$this->data[$k] = $v;
}
else
} else {
$this->data[$name] = $val;
}
}
/**
* assigns a value by reference to the data object
......@@ -127,30 +124,33 @@ class Dwoo_Data implements Dwoo_IDataProvider
*/
public function append($name, $val = null, $merge = false)
{
if(is_array($name))
{
foreach($name as $key=>$val)
if (is_array($name))
{
if(isset($this->data[$key]) && !is_array($this->data[$key]))
foreach ($name as $key=>$val) {
if (isset($this->data[$key]) && !is_array($this->data[$key])) {
settype($this->data[$key], 'array');
}
if($merge === true && is_array($val))
if ($merge === true && is_array($val)) {
$this->data[$key] = $val + $this->data[$key];
else
} else {
$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');
}
if($merge === true && is_array($val))
if ($merge === true && is_array($val)) {
$this->data[$name] = $val + $this->data[$name];
else
} else {
$this->data[$name][] = $val;
}
}
}
/**
* appends a value by reference to the data object
......@@ -162,12 +162,13 @@ class Dwoo_Data implements Dwoo_IDataProvider
*/
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');
}
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;
}
else
......
......@@ -48,7 +48,7 @@ class Dwoo_Loader
*/
public static function rebuildClassPathCache($path, $cacheFile)
{
if($cacheFile!==false)
if ($cacheFile!==false)
{
$tmp = self::$classpath;
self::$classpath = array();
......@@ -56,19 +56,19 @@ class Dwoo_Loader
// iterates over all files/folders
$list = glob($path.DIRECTORY_SEPARATOR.'*');
if(is_array($list))
foreach($list as $f)
if (is_array($list))
foreach ($list as $f)
{
if(is_dir($f))
if (is_dir($f))
self::rebuildClassPathCache($f, false);
else
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)
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)');
self::$classpath += $tmp;
}
......@@ -83,14 +83,14 @@ class Dwoo_Loader
public static function loadPlugin($class, $forceRehash = true)
{
// 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');
foreach(self::$paths as $path=>$file)
foreach (self::$paths as $path=>$file)
self::rebuildClassPathCache($path, $file);
if(isset(self::$classpath[$class]))
if (isset(self::$classpath[$class]))
include self::$classpath[$class];
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);
......@@ -114,11 +114,11 @@ class Dwoo_Loader
*/
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';
self::$paths[$pluginDir] = $cacheFile;
if(file_exists($cacheFile))
if (file_exists($cacheFile))
include $cacheFile;
else
Dwoo_Loader::rebuildClassPathCache($pluginDir, $cacheFile);
......
......@@ -88,8 +88,8 @@ class Dwoo_Security_Policy
*/
public function allowPhpFunction($func)
{
if(is_array($func))
foreach($func as $fname)
if (is_array($func))
foreach ($func as $fname)
$this->allowedPhpFunctions[strtolower($fname)] = true;
else
$this->allowedPhpFunctions[strtolower($func)] = true;
......@@ -102,8 +102,8 @@ class Dwoo_Security_Policy
*/
public function disallowPhpFunction($func)
{
if(is_array($func))
foreach($func as $fname)
if (is_array($func))
foreach ($func as $fname)
unset($this->allowedPhpFunctions[strtolower($fname)]);
else
unset($this->allowedPhpFunctions[strtolower($func)]);
......@@ -127,8 +127,8 @@ class Dwoo_Security_Policy
*/
public function allowDirectory($path)
{
if(is_array($path))
foreach($path as $dir)
if (is_array($path))
foreach ($path as $dir)
$this->allowedDirectories[realpath($dir)] = true;
else
$this->allowedDirectories[realpath($path)] = true;
......@@ -141,8 +141,8 @@ class Dwoo_Security_Policy
*/
public function disallowDirectory($path)
{
if(is_array($path))
foreach($path as $dir)
if (is_array($path))
foreach ($path as $dir)
unset($this->allowedDirectories[realpath($dir)]);
else
unset($this->allowedDirectories[realpath($path)]);
......
......@@ -47,13 +47,11 @@ class Dwoo_Template_File extends Dwoo_Template_String
$this->name = basename($file);
$this->cacheTime = $cacheTime;
if($compileId !== null)
{
if ($compileId !== null) {
$this->compileId = strtr($compileId, '\\%?=!:;'.PATH_SEPARATOR, '/-------');
}
if($cacheId !== null)
{
if ($cacheId !== null) {
$this->cacheId = strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------');
}
}
......@@ -70,12 +68,10 @@ class Dwoo_Template_File extends Dwoo_Template_String
$compiledFile = $this->getCompiledFilename($dwoo);
// 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
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;
}
// compiles the template
......@@ -83,19 +79,18 @@ class Dwoo_Template_File extends Dwoo_Template_String
{
$this->compilationEnforced = false;
if($compiler === null)
{
if ($compiler === null) {
$compiler = $dwoo->getDefaultCompilerFactory('string');
if($compiler === null || $compiler === array('Dwoo_Compiler', 'compilerFactory'))
{
if(class_exists('Dwoo_Compiler', false) === false)
if ($compiler === null || $compiler === array('Dwoo_Compiler', 'compilerFactory')) {
if (class_exists('Dwoo_Compiler', false) === false) {
include 'Dwoo/Compiler.php';
$compiler = Dwoo_Compiler::compilerFactory();
}
else
$compiler = Dwoo_Compiler::compilerFactory();
} else {
$compiler = call_user_func($compiler);
}
}
$this->compiler = $compiler;
......@@ -171,26 +166,25 @@ class Dwoo_Template_File extends Dwoo_Template_String
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);
if(file_exists($resourceId) === false)
{
if (file_exists($resourceId) === false) {
$tpl = $dwoo->getTemplate();
if($tpl instanceof Dwoo_Template_File)
{
if ($tpl instanceof Dwoo_Template_File) {
$resourceId = dirname($tpl->getResourceIdentifier()).DIRECTORY_SEPARATOR.$resourceId;
if(file_exists($resourceId) === false)
if (file_exists($resourceId) === false) {
return null;
}
else
} else {
return null;
}
}
// prevent template recursion if security is in effect
if($policy = $dwoo->getSecurityPolicy())
{
if ($policy = $dwoo->getSecurityPolicy()) {
$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 new Dwoo_Template_File($resourceId, $cacheTime, $cacheId, $compileId);
}
......@@ -205,8 +199,7 @@ class Dwoo_Template_File extends Dwoo_Template_String
protected function getCompiledFilename(Dwoo $dwoo)
{
// 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));
}
return $dwoo->getCompileDir() . $this->compileId.'.d'.Dwoo::RELEASE_TAG.'.php';
......
......@@ -99,13 +99,11 @@ class Dwoo_Template_String implements Dwoo_ITemplate
$this->name = hash('md4', $templateString);
$this->cacheTime = $cacheTime;
if($compileId !== null)
{
if ($compileId !== null) {
$this->compileId = strtr($compileId, '\\%?=!:;'.PATH_SEPARATOR, '/-------');
}
if($cacheId !== null)
{
if ($cacheId !== null) {
$this->cacheId = strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------');
}
}
......@@ -218,24 +216,22 @@ class Dwoo_Template_String implements Dwoo_ITemplate
public function getCachedTemplate(Dwoo $dwoo)
{
$cachedFile = $this->getCacheFilename($dwoo);
if($this->cacheTime !== null)
if ($this->cacheTime !== null) {
$cacheLength = $this->cacheTime;
else
} else {
$cacheLength = $dwoo->getCacheTime();
}
// file is not cacheable
if($cacheLength === 0)
{
if ($cacheLength === 0) {
return false;
}
// 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;
}
// 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;
return $cachedFile;
}
......@@ -260,11 +256,9 @@ class Dwoo_Template_String implements Dwoo_ITemplate
// the code below is courtesy of Rasmus Schultz,
// thanks for his help on avoiding concurency issues
$temp = tempnam($cacheDir, 'temp');
if(!($file = @fopen($temp, 'wb')))
{
if (!($file = @fopen($temp, 'wb'))) {
$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);
return false;
}
......@@ -274,8 +268,7 @@ class Dwoo_Template_String implements Dwoo_ITemplate
fclose($file);
$this->makeDirectory(dirname($cachedFile));
if(!@rename($temp, $cachedFile))
{
if (!@rename($temp, $cachedFile)) {
@unlink($cachedFile);
@rename($temp, $cachedFile);
}
......@@ -313,12 +306,10 @@ class Dwoo_Template_String implements Dwoo_ITemplate
$compiledFile = $this->getCompiledFilename($dwoo);
// 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
elseif($this->compilationEnforced !== true && file_exists($compiledFile)===true)
{
elseif ($this->compilationEnforced !== true && file_exists($compiledFile)===true) {
self::$cache['compiled'][$this->compileId] = true;
}
// compiles the template
......@@ -326,19 +317,18 @@ class Dwoo_Template_String implements Dwoo_ITemplate
{
$this->compilationEnforced = false;
if($compiler === null)
{
if ($compiler === null) {
$compiler = $dwoo->getDefaultCompilerFactory('string');
if($compiler === null || $compiler === array('Dwoo_Compiler', 'compilerFactory'))
{
if(class_exists('Dwoo_Compiler', false) === false)
if ($compiler === null || $compiler === array('Dwoo_Compiler', 'compilerFactory')) {
if (class_exists('Dwoo_Compiler', false) === false) {
include 'Dwoo/Compiler.php';
$compiler = Dwoo_Compiler::compilerFactory();
}
else
$compiler = Dwoo_Compiler::compilerFactory();
} else {
$compiler = call_user_func($compiler);
}
}
$this->compiler = $compiler;
......@@ -383,8 +373,7 @@ class Dwoo_Template_String implements Dwoo_ITemplate
protected function getCompiledFilename(Dwoo $dwoo)
{
// no compile id was provided, set default
if($this->compileId===null)
{
if ($this->compileId===null) {
$this->compileId = $this->name;
}
return $dwoo->getCompileDir() . $this->compileId.'.d'.Dwoo::RELEASE_TAG.'.php';
......@@ -400,12 +389,12 @@ class Dwoo_Template_String implements Dwoo_ITemplate
protected function getCacheFilename(Dwoo $dwoo)
{
// no cache id provided, use request_uri as default
if($this->cacheId === null)
{
if(isset($_SERVER['REQUEST_URI']) === true)
if ($this->cacheId === null) {
if (isset($_SERVER['REQUEST_URI']) === true) {
$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']);
}
$this->cacheId = strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------');
}
return $dwoo->getCacheDir() . $this->cacheId.'.html';
......@@ -418,8 +407,9 @@ class Dwoo_Template_String implements Dwoo_ITemplate
*/
protected function makeDirectory($path)
{
if(is_dir($path) === true)
if (is_dir($path) === true) {
return;
}
mkdir($path, DWOO_CHMOD, true);
}
......
......@@ -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)
{
$params = $compiler->getCompiledParams($params);
switch(strtolower(trim((string) $params['enabled'], '"\'')))
{
switch(strtolower(trim((string) $params['enabled'], '"\''))) {
case 'on':
case 'true':
case 'enabled':
......
......@@ -52,10 +52,10 @@ class Dwoo_Plugin_capture extends Dwoo_Block_Plugin implements Dwoo_ICompilable_
$params = $compiler->getCompiledParams($params);
$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;';
}
if($params['assign'] !== "null") {
if ($params['assign'] !== "null") {
$out .= "\n".'$this->scope['.$params['assign'].'] = $tmp;';
}
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
{
$block =& $compiler->getCurrentBlock();
$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();
$block =& $compiler->getCurrentBlock();
}
......@@ -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='')
{
if(isset($params['postOutput']))
if (isset($params['postOutput'])) {
return $params['postOutput'];
}
}
}
......@@ -36,17 +36,19 @@ class Dwoo_Plugin_elseif extends Dwoo_Plugin_if implements Dwoo_ICompilable_Bloc
$currentBlock =& $compiler->getCurrentBlock();
$currentBlock['params']['postOutput'] = Dwoo_Compiler::PHP_OPEN."\n}".Dwoo_Compiler::PHP_CLOSE;
if($out === '')
if ($out === '') {
$out = Dwoo_Compiler::PHP_OPEN."\n}";
else
} else {
$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='')
{
if(isset($params['postOutput']))
if (isset($params['postOutput'])) {
return $params['postOutput'];
}
}
}
......@@ -64,50 +64,53 @@ class Dwoo_Plugin_for extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Bloc
"\n".'$_for'.$cnt.'_to = '.$to.';'.
"\n".'$_for'.$cnt.'_step = abs('.$step.');'.
"\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
if($usesAny)
{
if ($usesAny) {
$out .= "\n".'$this->globals["for"]['.$name.'] = array'."\n(";
if($usesIndex) $out .="\n\t".'"index" => 0,';
if($usesIteration) $out .="\n\t".'"iteration" => 1,';
if($usesFirst) $out .="\n\t".'"first" => 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($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 ($usesIndex) $out .="\n\t".'"index" => 0,';
if ($usesIteration) $out .="\n\t".'"iteration" => 1,';
if ($usesFirst) $out .="\n\t".'"first" => 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 ($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.'];';
}
// 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
$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.'_to = is_numeric($_for'.$cnt.'_to) ? $_for'.$cnt.'_to - $_for'.$cnt.'_step : count($_for'.$cnt.'_src)-1;
}
$_for'.$cnt.'_keys = array();
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)
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'.$cnt.'_keys[] = $tmp;
} 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;
}
foreach($_for'.$cnt.'_keys as $this->scope['.$name.'])'."\n\t{";
foreach ($_for'.$cnt.'_keys as $this->scope['.$name.'])'."\n\t{";
// updates properties
if($usesIndex)
if ($usesIndex) {
$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);';
if($usesLast)
}
if ($usesLast) {
$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;
// build post processing output and cache it
$postOut = Dwoo_Compiler::PHP_OPEN . '// -- for end output';
// update properties
if($usesIteration)
if ($usesIteration) {
$postOut.="\n\t\t".'$_for'.$cnt.'_glob["iteration"]+=1;';
}
// end loop
$postOut .= "\n\t}\n}\n";
......
......@@ -50,24 +50,24 @@ class Dwoo_Plugin_foreach extends Dwoo_Block_Plugin implements Dwoo_ICompilable_
// assigns params
$src = $params['from'];
if($params['item'] !== 'null')
{
if($params['key'] !== 'null')
if ($params['item'] !== 'null') {
if ($params['key'] !== 'null') {
$key = $params['key'];
$val = $params['item'];
}
elseif($params['key'] !== 'null')
{
$val = $params['item'];
} elseif ($params['key'] !== 'null') {
$val = $params['key'];
}
else
} else {
throw new Dwoo_Compilation_Exception('Foreach <em>item</em> parameter missing');
}
$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');
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');
}
// evaluates which global variables have to be computed
$varName = '$dwoo.foreach.'.trim($name, '"\'').'.';
......@@ -86,35 +86,38 @@ class Dwoo_Plugin_foreach extends Dwoo_Block_Plugin implements Dwoo_ICompilable_
// builds pre processing output
$out = Dwoo_Compiler::PHP_OPEN . "\n".'$_fh'.$cnt.'_data = '.$src.';';
// adds foreach properties
if($usesAny)
{
if ($usesAny) {
$out .= "\n".'$this->globals["foreach"]['.$name.'] = array'."\n(";
if($usesIndex) $out .="\n\t".'"index" => 0,';
if($usesIteration) $out .="\n\t".'"iteration" => 1,';
if($usesFirst) $out .="\n\t".'"first" => null,';
if($usesLast) $out .="\n\t".'"last" => null,';
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 ($usesIndex) $out .="\n\t".'"index" => 0,';
if ($usesIteration) $out .="\n\t".'"iteration" => 1,';
if ($usesFirst) $out .="\n\t".'"first" => null,';
if ($usesLast) $out .="\n\t".'"last" => null,';
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,';
$out.="\n);\n".'$_fh'.$cnt.'_glob =& $this->globals["foreach"]['.$name.'];';
}
// 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
$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
if($usesFirst)
if ($usesFirst) {
$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// -- foreach start output\n".Dwoo_Compiler::PHP_CLOSE;
// build post processing output and cache it
$postOut = Dwoo_Compiler::PHP_OPEN . "\n".'// -- foreach end output';
// update properties
if($usesIndex)
if ($usesIndex) {
$postOut.="\n\t\t".'$_fh'.$cnt.'_glob["index"]+=1;';
if($usesIteration)
}
if ($usesIteration) {
$postOut.="\n\t\t".'$_fh'.$cnt.'_glob["iteration"]+=1;';
}
// end loop
$postOut .= "\n\t}\n}\n";
......
......@@ -33,10 +33,11 @@ class Dwoo_Plugin_foreachelse extends Dwoo_Block_Plugin implements Dwoo_ICompila
$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));
else
} else {
$out .= Dwoo_Compiler::PHP_OPEN;
}
return $out . "else\n{" . Dwoo_Compiler::PHP_CLOSE;
}
......
......@@ -33,10 +33,11 @@ class Dwoo_Plugin_forelse extends Dwoo_Block_Plugin implements Dwoo_ICompilable_
$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));
else
} else {
$out .= Dwoo_Compiler::PHP_OPEN;
}
return $out . "else\n{" . Dwoo_Compiler::PHP_CLOSE;
}
......
......@@ -44,10 +44,8 @@ class Dwoo_Plugin_if extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block
$params = $params['*'];
while(list($k,$v) = each($params))
{
switch($v)
{
while (list($k,$v) = each($params)) {
switch($v) {
case '"<<"':
case '">>"':
case '"&&"':
......@@ -100,53 +98,44 @@ class Dwoo_Plugin_if extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block
$p[] = '!==';
break;
case '"is"':
if($params[$k+1] === '"not"')
{
if ($params[$k+1] === '"not"') {
$negate = true;
next($params);
}
else
} else {
$negate = false;
}
$ptr = 1+(int)$negate;
switch($params[$k+$ptr])
{
switch($params[$k+$ptr]) {
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';
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]);
}
break;
case '"even"':
$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];
$p[] = '('.$a .' / '.$b.') % 2 '.($negate?'!':'=').'== 0';
next($params);
next($params);
}
else
{
} else {
$p[] = $a.' % 2 '.($negate?'!':'=').'== 0';
}
next($params);
break;
case '"odd"':
$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];
$p[] = '('.$a .' / '.$b.') % 2 '.($negate?'=':'!').'== 0';
next($params);
next($params);
}
else
{
} else {
$p[] = $a.' % 2 '.($negate?'=':'!').'== 0';
}
next($params);
......@@ -176,7 +165,7 @@ class Dwoo_Plugin_if extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block
$currentBlock =& $compiler->getCurrentBlock();
$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='')
......
......@@ -77,35 +77,38 @@ class Dwoo_Plugin_loop extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Blo
// builds pre processing output
$out = Dwoo_Compiler::PHP_OPEN . "\n".'$_loop'.$cnt.'_data = '.$src.';';
// adds foreach properties
if($usesAny)
{
if ($usesAny) {
$out .= "\n".'$this->globals["loop"]['.$name.'] = array'."\n(";
if($usesIndex) $out .="\n\t".'"index" => 0,';
if($usesIteration) $out .="\n\t".'"iteration" => 1,';
if($usesFirst) $out .="\n\t".'"first" => null,';
if($usesLast) $out .="\n\t".'"last" => null,';
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 ($usesIndex) $out .="\n\t".'"index" => 0,';
if ($usesIteration) $out .="\n\t".'"iteration" => 1,';
if ($usesFirst) $out .="\n\t".'"first" => null,';
if ($usesLast) $out .="\n\t".'"last" => null,';
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,';
$out.="\n);\n".'$_loop'.$cnt.'_glob =& $this->globals["loop"]['.$name.'];';
}
// 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
$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
if($usesFirst)
if ($usesFirst) {
$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.'_scope = $this->setScope(array("-loop-"));' . "\n// -- loop start output\n".Dwoo_Compiler::PHP_CLOSE;
// 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);';
// update properties
if($usesIndex)
if ($usesIndex) {
$postOut.="\n\t\t".'$_loop'.$cnt.'_glob["index"]+=1;';
if($usesIteration)
}
if ($usesIteration) {
$postOut.="\n\t\t".'$_loop'.$cnt.'_glob["iteration"]+=1;';
}
// end loop
$postOut .= "\n\t}\n}\n";
......
......@@ -30,33 +30,31 @@ class Dwoo_Plugin_smartyinterface extends Dwoo_Block_Plugin implements Dwoo_ICom
$pluginType = $params['__functype'];
$params = $params['*'];
if($pluginType & Dwoo::CUSTOM_PLUGIN)
{
if ($pluginType & Dwoo::CUSTOM_PLUGIN) {
$customPlugins = $compiler->getDwoo()->getCustomPlugins();
$callback = $customPlugins[$func]['callback'];
if(is_array($callback))
{
if(is_object($callback[0]))
if (is_array($callback)) {
if (is_object($callback[0])) {
$callback = '$this->customPlugins[\''.$func.'\'][0]->'.$callback[1].'(';
else
} else {
$callback = ''.$callback[0].'::'.$callback[1].'(';
}
else
} else {
$callback = $callback.'(';
}
else
} else {
$callback = 'smarty_block_'.$func.'(';
}
$paramsOut = '';
foreach($params as $i=>$p)
{
foreach ($params as $i=>$p) {
$paramsOut .= var_export($i, true).' => '.$p.',';
}
$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;
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='')
......
......@@ -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="")
{
if($indent_char === 'tab')
if ($indent_char === 'tab') {
$indent_char = "\t";
}
switch($style)
{
switch($style) {
case 'email':
$wrap = 72;
$indent_first = 0;
......@@ -70,10 +70,10 @@ class Dwoo_Plugin_textformat extends Dwoo_Block_Plugin
// gets paragraphs
$pgs = explode("\n", str_replace(array("\r\n", "\r"), "\n", $this->buffer));
while(list($i,) = each($pgs))
{
if(empty($pgs[$i]))
while (list($i,) = each($pgs)) {
if (empty($pgs[$i])) {
continue;
}
// removes line breaks and extensive white space
$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
);
}
if($this->assign !== '')
if ($this->assign !== '') {
$this->dwoo->assignInScope(implode($this->wrapChar . $this->wrapChar, $pgs), $this->assign);
else
} else {
return implode($this->wrapChar . $this->wrapChar, $pgs);
}
}
}
......@@ -61,7 +61,7 @@ class Dwoo_Plugin_with extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Blo
$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;
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='')
......
......@@ -33,10 +33,11 @@ class Dwoo_Plugin_withelse extends Dwoo_Block_Plugin implements Dwoo_ICompilable
$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));
else
} else {
$out .= Dwoo_Compiler::PHP_OPEN;
}
return $out . "else\n{" . Dwoo_Compiler::PHP_CLOSE;
}
......
......@@ -71,15 +71,15 @@ class Dwoo_Filter_html_format extends Dwoo_Filter
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
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];
}
// 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]);
}
// it's the closing tag
if($input[0][1]=="/"){
if ($input[0][1]=="/"){
return self::closeTag($input[1],$input[3],$input[2]);
}
// opening tag
......@@ -99,13 +99,11 @@ class Dwoo_Filter_html_format extends Dwoo_Filter
$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(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);
}
// 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;
}
// normal block tag
......@@ -113,8 +111,7 @@ class Dwoo_Filter_html_format extends Dwoo_Filter
{
$result = "\n".$tabs . $tag;
if(!empty($add))
{
if (!empty($add)) {
$result .= "\n".$tabs."\t".str_replace("\n","\n\t".$tabs,$add);
}
}
......@@ -137,16 +134,12 @@ class Dwoo_Filter_html_format extends Dwoo_Filter
$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(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);
}
else
{
} else {
$result = "\n".$tabs.$tag;
if(!empty($add))
{
if (!empty($add)) {
$result .= "\n".$tabs."\t".str_replace("\n","\n\t".$tabs,$add);
}
}
......@@ -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 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;
if(!empty($add))
{
if (!empty($add)) {
$result .= str_replace("\n","\n".$tabs,$add);
}
}
else
{
} else {
$result = "\n".$tabs.$tag;
if(!empty($add))
{
if (!empty($add)) {
$result .= "\n".$tabs.str_replace("\n","\n".$tabs,$add);
}
}
......
......@@ -24,21 +24,22 @@
*/
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 mb_convert_case((string) $value,MB_CASE_TITLE, $dwoo->getCharset());
}
else
return mb_convert_case((string) $value,MB_CASE_TITLE, $dwoo->getCharset());
} else
{
$bits = explode(' ', (string) $value);
$out = '';
while(list(,$v) = each($bits))
if(preg_match('#^[^0-9]+$#', $v))
while (list(,$v) = each($bits))
if (preg_match('#^[^0-9]+$#', $v)) {
$out .= ' '.mb_convert_case($v, MB_CASE_TITLE, $dwoo->getCharset());
else
} else {
$out .= ' '.$v;
}
return substr($out, 1);
}
......
......@@ -24,8 +24,9 @@
*/
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)';
else
} else {
return 'mb_strlen('.$value.', $this->charset)';
}
}
......@@ -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)
{
// init counter
if(!isset($this->counters[$name]))
{
if (!isset($this->counters[$name])) {
$this->counters[$name] = array
(
'count' => $start===null ? 1 : (int) $start,
......@@ -48,29 +47,35 @@ class Dwoo_Plugin_counter extends Dwoo_Plugin
else
{
// override setting if present
if($skip !== null)
if ($skip !== null) {
$this->counters[$name]['skip'] = (int) $skip;
}
if($direction !== null)
if ($direction !== null) {
$this->counters[$name]['direction'] = strtolower($direction)==='down' ? -1 : 1;
}
if($print !== null)
if ($print !== null) {
$this->counters[$name]['print'] = (bool) $print;
}
if($assign !== null)
if ($assign !== null) {
$this->counters[$name]['assign'] = (string) $assign;
}
if($start !== null)
if ($start !== null) {
$this->counters[$name]['count'] = (int) $start;
else
} else {
$this->counters[$name]['count'] += ($this->counters[$name]['skip'] * $this->counters[$name]['direction']);
}
}
$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']);
elseif($this->counters[$name]['print'] === true)
} elseif ($this->counters[$name]['print'] === true) {
return $out;
}
}
}
......@@ -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)
{
if($values !== null)
{
if(is_string($values))
if ($values !== null) {
if (is_string($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]['values'] = array_values($values);
}
elseif(isset($this->cycles[$name]))
{
} elseif (isset($this->cycles[$name])) {
$values = $this->cycles[$name]['values'];
}
if($reset)
if ($reset) {
$this->cycles[$name]['index'] = 0;
}
if($print)
if ($print) {
$out = $values[$this->cycles[$name]['index']];
else
} else {
$out = null;
}
if($advance)
{
if($this->cycles[$name]['index'] >= count($values)-1)
if ($advance) {
if ($this->cycles[$name]['index'] >= count($values)-1) {
$this->cycles[$name]['index'] = 0;
else
} else {
$this->cycles[$name]['index']++;
}
}
if($assign !== null)
if ($assign !== null) {
$this->dwoo->assignInScope($assign, $out);
else
} else {
return $out;
}
}
}
......@@ -25,35 +25,34 @@
*/
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
if(preg_match('#^\d{10}$#', $value)===0)
if (preg_match('#^\d{10}$#', $value)===0) {
$value = strtotime($value);
}
elseif(!empty($default))
} elseif (!empty($default))
{
// 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);
else
} else {
$value = $default;
}
else
} else {
return '';
}
// 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_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_to[] = sprintf('%\' 2d', date('j', $value));
}
if(strpos($format, '%l') !== false)
{
if (strpos($format, '%l') !== false) {
$_win_from[] = '%l';
$_win_to[] = sprintf('%\' 2d', date('h', $value));
}
......
......@@ -32,7 +32,7 @@ class Dwoo_Plugin_dump extends Dwoo_Plugin
$out = '<div style="background:#aaa; padding:5px; margin:5px; color:#000;">dump';
}
if(!is_array($var)) {
if (!is_array($var)) {
return $this->exportVar('', $var);
}
......@@ -55,7 +55,7 @@ class Dwoo_Plugin_dump extends Dwoo_Plugin
foreach ($var as $i=>$v) {
if (is_array($v) || (is_object($v) && $v instanceof Iterator)) {
$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>';
} else {
$out .= ':<div style="padding-left:20px;">'.$this->export($v, $scope).'</div>';
......
......@@ -25,8 +25,9 @@
*/
function Dwoo_Plugin_escape(Dwoo $dwoo, $value='', $format='html', $charset=null)
{
if($charset === null)
if ($charset === null) {
$charset = $dwoo->getCharset();
}
switch($format)
{
......@@ -50,7 +51,7 @@ function Dwoo_Plugin_escape(Dwoo $dwoo, $value='', $format='html', $charset=null
case 'hexentity':
$out = '';
$cnt = strlen((string) $value);
for($i=0; $i < $cnt; $i++)
for ($i=0; $i < $cnt; $i++)
$out .= '&#x' . bin2hex((string) $value[$i]) . ';';
return $out;
case 'javascript':
......
......@@ -31,14 +31,16 @@
*/
function Dwoo_Plugin_eval(Dwoo $dwoo, $var, $assign = null)
{
if($var == '')
if ($var == '') {
return;
}
$tpl = new Dwoo_Template_String($var);
$out = $dwoo->get($var, $dwoo->readVar('_parent'));
if($assign !== null)
if ($assign !== null) {
$dwoo->assignInScope($out, $assign);
else
} else {
return $out;
}
}
......@@ -34,46 +34,39 @@ class Dwoo_Plugin_extends extends Dwoo_Plugin implements Dwoo_ICompilable
self::$l = preg_quote($l);
self::$r = preg_quote($r);
if($compiler->getLooseOpeningHandling())
{
if ($compiler->getLooseOpeningHandling()) {
self::$l .= '\s*';
self::$r = '\s*'.self::$r;
}
$inheritanceTree = array(array('source'=>$compiler->getTemplateSource()));
while(!empty($file))
{
if($file === '""' || $file === "''" || (substr($file, 0, 1) !== '"' && substr($file, 0, 1) !== '"'))
{
while (!empty($file)) {
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');
return;
}
if(preg_match('#^["\']([a-z]{2,}):(.*?)["\']$#i', $file, $m))
{
if (preg_match('#^["\']([a-z]{2,}):(.*?)["\']$#i', $file, $m)) {
$resource = $m[1];
$identifier = $m[2];
}
else
{
} else {
$resource = 'file';
$identifier = substr($file, 1, -1);
}
if($resource === 'file' && $policy = $compiler->getSecurityPolicy())
{
while(true)
{
if(preg_match('{^([a-z]+?)://}i', $identifier))
if ($resource === 'file' && $policy = $compiler->getSecurityPolicy()) {
while (true) {
if (preg_match('{^([a-z]+?)://}i', $identifier)) {
throw new Dwoo_Security_Exception('The security policy prevents you to read files from external sources.');
}
$identifier = realpath($identifier);
$dirs = $policy->getAllowedDirectories();
foreach($dirs as $dir=>$dummy)
{
if(strpos($identifier, $dir) === 0)
foreach ($dirs as $dir=>$dummy) {
if (strpos($identifier, $dir) === 0) {
break 2;
}
}
throw new Dwoo_Security_Exception('The security policy prevents you to read <em>'.$identifier.'</em>');
}
}
......@@ -84,40 +77,42 @@ 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>');
}
if($parent === null)
if ($parent === null) {
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.');
}
$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');
}
$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];
else
} else {
$file = false;
}
}
while(true)
{
while (true) {
$parent = array_pop($inheritanceTree);
$child = end($inheritanceTree);
self::$childSource = $child['source'];
self::$lastReplacement = count($inheritanceTree) === 1;
if(!isset($newSource))
if (!isset($newSource)) {
$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 = $l.'do extendsCheck("'.$parent['resource'].':'.$parent['identifier'].'" "'.str_replace('"', '\\"', $parent['uid']).'")'.$r.$newSource;
if(self::$lastReplacement)
if (self::$lastReplacement) {
break;
}
}
$compiler->setTemplateSource($newSource);
$compiler->setPointer(0);
......@@ -125,22 +120,21 @@ class Dwoo_Plugin_extends extends Dwoo_Plugin implements Dwoo_ICompilable
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);
$r = stripslashes(self::$r);
if(self::$lastReplacement)
if (self::$lastReplacement) {
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;
}
else
{
if(self::$lastReplacement)
} else {
if (self::$lastReplacement) {
return $matches[3];
else
} else {
return $matches[0];
}
}
}
}
......@@ -31,9 +31,9 @@ try {
} 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);
}
if($tpl === null)
if ($tpl === null)
$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);
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,23 +24,24 @@
*/
function Dwoo_Plugin_fetch(Dwoo $dwoo, $file, $assign = null)
{
if($file === '')
if ($file === '') {
return;
}
if($policy = $dwoo->getSecurityPolicy())
{
while(true)
if ($policy = $dwoo->getSecurityPolicy())
{
if(preg_match('{^([a-z]+?)://}i', $file))
while (true) {
if (preg_match('{^([a-z]+?)://}i', $file)) {
return $dwoo->triggerError('The security policy prevents you to read files from external sources.', E_USER_WARNING);
}
$file = realpath($file);
$dirs = $policy->getAllowedDirectories();
foreach($dirs as $dir=>$dummy)
{
if(strpos($file, $dir) === 0)
foreach ($dirs as $dir=>$dummy) {
if (strpos($file, $dir) === 0) {
break 2;
}
}
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)
$out = file_get_contents($file);
if($assign !== null)
if ($assign !== null) {
$dwoo->assignInScope($out, $assign);
else
} else {
return $out;
}
}
......@@ -29,35 +29,35 @@
*/
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;
}
if(preg_match('#^([a-z]{2,}):(.*)#i', $file, $m))
if (preg_match('#^([a-z]{2,}):(.*)#i', $file, $m))
{
$resource = $m[1];
$identifier = $m[2];
}
else
} else
{
// get the current template's resource
$resource = $dwoo->getTemplate()->getResourceName();
$identifier = $file;
}
if($resource === 'file' && $policy = $dwoo->getSecurityPolicy())
{
while(true)
if ($resource === 'file' && $policy = $dwoo->getSecurityPolicy())
{
if(preg_match('{^([a-z]+?)://}i', $identifier))
while (true) {
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>.');
}
$identifier = realpath($identifier);
$dirs = $policy->getAllowedDirectories();
foreach($dirs as $dir=>$dummy)
{
if(strpos($identifier, $dir) === 0)
foreach ($dirs as $dir=>$dummy) {
if (strpos($identifier, $dir) === 0) {
break 2;
}
}
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 =
$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;
elseif($include === false)
} elseif ($include === false) {
$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;
elseif($dwoo->isArray($cache_time))
} elseif ($dwoo->isArray($cache_time)) {
$vars = $cache_time;
else
} else {
$vars = $dwoo->readVar($data);
}
if(count($rest))
if (count($rest))
{
$vars = $rest + $vars;
}
$out = $dwoo->get($include, $vars);
if($assign !== null)
if ($assign !== null) {
$dwoo->assignInScope($out, $assign);
else
} else {
return $out;
}
}
......@@ -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)
{
if(empty($address))
if (empty($address)) {
return '';
if(empty($text))
}
if (empty($text)) {
$text = $address;
}
// build address string
$address .= '?';
if(!empty($subject))
if (!empty($subject)) {
$address .= 'subject='.rawurlencode($subject).'&';
if(!empty($cc))
}
if (!empty($cc)) {
$address .= 'cc='.rawurlencode($cc).'&';
if(!empty($bcc))
}
if (!empty($bcc)) {
$address .= 'bcc='.rawurlencode($bcc).'&';
if(!empty($newsgroup))
}
if (!empty($newsgroup)) {
$address .= 'newsgroups='.rawurlencode($newsgroups).'&';
if(!empty($followupto))
}
if (!empty($followupto)) {
$address .= 'followupto='.rawurlencode($followupto).'&';
}
$address = rtrim($address, '?&');
......@@ -86,18 +93,19 @@ function Dwoo_Plugin_mailto(Dwoo $dwoo, $address, $text=null, $subject=null, $en
break;
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);
}
$out = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;';
$len = strlen($address);
for ($i=0; $i<$len; $i++)
{
if(preg_match('#\w#', $address[$i]))
for ($i=0; $i<$len; $i++) {
if (preg_match('#\w#', $address[$i])) {
$out .= '%'.bin2hex($address[$i]);
else
} else {
$out .= $address[$i];
}
}
$out .= '" '.$extra.'>';
$len = strlen($text);
for ($i=0; $i<$len; $i++)
......
......@@ -65,8 +65,7 @@ function Dwoo_Plugin_math_compile(Dwoo_Compiler $compiler, $equation, $format=''
$out = '';
$ptr = 1;
$allowcomma = 0;
while(strlen($equation) > 0)
{
while (strlen($equation) > 0) {
$substr = substr($equation, 0, $ptr);
// allowed string
if (array_search($substr, $allowed) !== false) {
......@@ -80,31 +79,31 @@ function Dwoo_Plugin_math_compile(Dwoo_Compiler $compiler, $equation, $format=''
$equation = substr($equation, $ptr);
$ptr = 0;
$allowcomma++;
if($allowcomma === 1) {
if ($allowcomma === 1) {
$allowed[] = ',';
}
}
// variable
elseif(isset($rest[$substr]))
{
elseif (isset($rest[$substr])) {
$out.=$rest[$substr];
$equation = substr($equation, $ptr);
$ptr = 0;
}
// pre-replaced variable
elseif($substr === $open)
{
elseif ($substr === $open) {
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);
}
$out.=substr($m[0], 0, -2);
$equation = substr($equation, strlen($m[0])+2);
$ptr = 0;
}
// opening parenthesis
elseif ($substr==='(') {
if($allowcomma>0)
if ($allowcomma>0) {
$allowcomma++;
}
$out.=$substr;
$equation = substr($equation, $ptr);
......@@ -112,9 +111,9 @@ function Dwoo_Plugin_math_compile(Dwoo_Compiler $compiler, $equation, $format=''
}
// closing parenthesis
elseif ($substr===')') {
if($allowcomma>0) {
if ($allowcomma>0) {
$allowcomma--;
if($allowcomma===0) {
if ($allowcomma===0) {
array_pop($allowed);
}
}
......@@ -127,15 +126,15 @@ function Dwoo_Plugin_math_compile(Dwoo_Compiler $compiler, $equation, $format=''
elseif ($ptr >= strlen($equation)) {
throw new Dwoo_Compilation_Exception('Math : Syntax error or variable undefined in equation '.$equationSrc.' at '.$substr);
return;
}
else
{
} else {
$ptr++;
}
}
if($format !== '\'\'')
if ($format !== '\'\'') {
$out = 'sprintf('.$format.', '.$out.')';
if($assign !== '\'\'')
}
if ($assign !== '\'\'') {
return '($this->assignInScope('.$out.', '.$assign.'))';
}
return '('.$out.')';
}
......@@ -26,10 +26,11 @@
function Dwoo_Plugin_regex_replace(Dwoo $dwoo, $value, $search, $replace)
{
// 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);
}
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]);
}
......
......@@ -24,8 +24,9 @@
*/
function Dwoo_Plugin_reverse(Dwoo $dwoo, $value, $preserve_keys=false)
{
if(is_array($value))
if (is_array($value)) {
return array_reverse($value, $preserve_keys);
else
} else {
return implode('',array_reverse(str_split((string) $value,1)));
}
}
......@@ -24,8 +24,9 @@
*/
function Dwoo_Plugin_strip_tags_compile(Dwoo_Compiler $compiler, $value, $addspace=true)
{
if($addspace==='true')
if ($addspace==='true') {
return "preg_replace('#<[^>]*>#', ' ', $value)";
else
} else {
return "strip_tags($value)";
}
}
......@@ -27,20 +27,24 @@
*/
function Dwoo_Plugin_truncate(Dwoo $dwoo, $value, $length=80, $etc='...', $break=false, $middle=false)
{
if($length == 0)
if ($length == 0) {
return '';
}
$value = (string) $value;
$etc = (string) $etc;
$length = (int) $length;
if(strlen($value) < $length)
if (strlen($value) < $length) {
return $value;
}
$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));
if($middle === false)
}
if ($middle === false) {
return substr($value, 0, $length) . $etc;
}
return substr($value, 0, ceil($length/2)) . $etc . substr($value, -floor($length/2));
}
......@@ -31,11 +31,12 @@
function Dwoo_Plugin_array_compile(Dwoo_Compiler $compiler, array $rest=array())
{
$out = array();
foreach($rest as $k=>$v)
if(is_numeric($k))
foreach ($rest as $k=>$v)
if (is_numeric($k)) {
$out[] = $k.'=>'.$v;
else
} else {
$out[] = '"'.$k.'"=>'.$v;
}
return 'array('.implode(', ', $out).')';
}
......@@ -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);
}
return preg_replace($smarty, $dwoo, $input);
}
......@@ -64,65 +65,72 @@ class Dwoo_Processor_smarty_compat extends Dwoo_Processor
{
$params = array();
$index = 1;
while(!empty($matches[$index]) && $index < 13)
{
while (!empty($matches[$index]) && $index < 13) {
$params[$matches[$index]] = $matches[$index+1];
$index += 2;
}
$params['content'] = $matches[13];
if(isset($matches[14]) && !empty($matches[14]))
if (isset($matches[14]) && !empty($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');
}
$name = $params['name'];
if(isset($params['loop']))
if (isset($params['loop'])) {
$loops = $params['loop'];
}
if(isset($params['max']))
if (isset($params['max'])) {
$max = $params['max'];
}
if(isset($params['start']))
if (isset($params['start'])) {
$start = $params['start'];
}
if(isset($params['step']))
if (isset($params['step'])) {
$step = $params['step'];
}
if (!isset($loops))
$loops = null;
if (!isset($max) || $max < 0)
{
if(is_numeric($loops))
if (!isset($max) || $max < 0) {
if (is_numeric($loops)) {
$max = $loops;
else
} else {
$max = 'null';
}
}
if (!isset($step))
$step = 1;
if (!isset($start))
$start = $loops - 1;
elseif(!is_numeric($loops))
elseif (!is_numeric($loops)) {
$start = 0;
}
list($l, $r) = $this->compiler->getDelimiters();
if(is_numeric($loops))
{
if(isset($params['start']) && isset($params['loop']) && !isset($params['max']))
if (is_numeric($loops)) {
if (isset($params['start']) && isset($params['loop']) && !isset($params['max'])) {
$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;
}
else
} else {
$output = $l.'for '.$name.' '.$loops.' '.($start+floor($max/$step)).' '.$step.' '.$start.$r;
}
$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.'/for'.$r;
......
......@@ -107,7 +107,7 @@ FOObartoplevelContent2
baz"));
}
public function testIf()
public function testIf ()
{
$tpl = new Dwoo_Template_String('{if "BAR"==reverse($foo|reverse|upper)}true{/if}');
$tpl->forceCompilation();
......@@ -135,11 +135,11 @@ baz"));
$this->assertEquals('true', $this->dwoo->get($tpl, array(), $this->compiler));
// 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());
}
public function testIfElseif()
public function testIfElseif ()
{
$tpl = new Dwoo_Template_String('{if "BAR" == "bar"}true{elseif "BAR"=="BAR"}false{/if}');
$tpl->forceCompilation();
......@@ -147,7 +147,7 @@ baz"));
$this->assertEquals('false', $this->dwoo->get($tpl, array(), $this->compiler));
// 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());
}
......@@ -179,7 +179,7 @@ baz"));
$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->forceCompilation();
......@@ -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));
// 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);
}
......@@ -221,7 +221,7 @@ baz"));
$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)
$fixCall = new Dwoo_Plugin_foreach($this->dwoo);
$fixCall = new Dwoo_Plugin_foreach ($this->dwoo);
$fixCall->init('');
}
......@@ -235,13 +235,13 @@ baz"));
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->forceCompilation();
$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->forceCompilation();
......
......@@ -34,8 +34,7 @@ class CallTests extends PHPUnit_Framework_TestCase
$this->dwoo->removePlugin('test');
}
public function testFullCustomClassPluginByClassMethodCallback()
{
public function testFullCustomClassPluginByClassMethodCallback() {
$this->dwoo->addPlugin('test', array('plugin_full_custom', 'process'));
$tpl = new Dwoo_Template_String('{test "xxx"}');
$tpl->forceCompilation();
......
......@@ -237,8 +237,9 @@ class CompilerTests extends PHPUnit_Framework_TestCase
public function testConstants()
{
if(!defined('TEST'))
if (!defined('TEST')) {
define('TEST', 'Test');
}
$tpl = new Dwoo_Template_String('{$dwoo.const.TEST} {$dwoo.const.Dwoo::FUNC_PLUGIN*$dwoo.const.Dwoo::BLOCK_PLUGIN}');
$tpl->forceCompilation();
......@@ -247,8 +248,9 @@ class CompilerTests extends PHPUnit_Framework_TestCase
public function testShortConstants()
{
if(!defined('TEST'))
if (!defined('TEST')) {
define('TEST', 'Test');
}
$tpl = new Dwoo_Template_String('{%TEST} {$dwoo.const.Dwoo::FUNC_PLUGIN*%Dwoo::BLOCK_PLUGIN}');
$tpl->forceCompilation();
......
<?php
error_reporting(E_ALL|E_STRICT);
if(!ini_get('date.timezone'))
if (!ini_get('date.timezone'))
date_default_timezone_set('CET');
define('DWOO_CACHE_DIRECTORY', dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR.'cache');
define('DWOO_COMPILE_DIRECTORY', dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR.'compiled');
......@@ -17,9 +17,8 @@ class DwooTests extends PHPUnit_Framework_TestSuite {
$suite = new self('Dwoo - Unit Tests Report');
foreach(new DirectoryIterator(dirname(__FILE__)) as $file) {
if(!$file->isDot() && !$file->isDir() && (string) $file !== 'DwooTests.php' && substr((string) $file, -4) === '.php')
{
foreach (new DirectoryIterator(dirname(__FILE__)) as $file) {
if (!$file->isDot() && !$file->isDir() && (string) $file !== 'DwooTests.php' && substr((string) $file, -4) === '.php') {
require_once $file->getPathname();
$suite->addTestSuite(basename($file, '.php'));
}
......@@ -28,23 +27,22 @@ class DwooTests extends PHPUnit_Framework_TestSuite {
return $suite;
}
protected function tearDown()
{
protected function tearDown() {
$this->clearDir(TEST_DIRECTORY.'/temp/compiled', true);
}
protected function clearDir($path, $emptyOnly=false)
{
if(is_dir($path))
{
foreach(glob($path.'/*') as $f)
if (is_dir($path)) {
foreach (glob($path.'/*') as $f)
$this->clearDir($f);
if(!$emptyOnly)
if (!$emptyOnly) {
rmdir($path);
}
else
} else {
unlink($path);
}
}
}
// Evaluates two strings and ignores differences in line endings (\r\n == \n == \r)
......
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