Commit e31da1c6 by Seldaek

First Import / 0.3.3

git-svn-id: svn://dwoo.org/dwoo/trunk@2 0598d79b-80c4-4d41-97ba-ac86fbbd088b
parent 4693e5a6
[2008-03-19] 0.3.3
+ Syntax: Added support for $dwoo.const.CONSTANT and
$dwoo.const.Class::CONSTANT to read PHP constants from the template
+ Syntax: Added support for on/off/yes/no, that work as aliases for true/false
+ Syntax: Added the $dwoo.charset global variable
+ Plugins: Added {withelse} and made {with} compatible with {else} also
+ API: Added left/right delimiters customization, see DwooCompiler->setDelimiters()
+ API: Added DwooCompiler->triggerError()
+ API: Added Dwoo->clearCache() and DwooITemplate->clearCache() methods
+ Smarty: The smartyCompat prefilter converts {section} tags into {for} tags on the
fly, however it's not guaranteed to work with *all* section tags, let me know if
it breaks for you
* {with} now skips the entire block if it's variable doesn't exist, so by
itself it acts as if you would do {if $var}{with $var}{/with}{/if}
* Each resource has a compiler factory function assigned to it, allowing you to
easily provide a custom compiler without loading it on every page
* OutputFilters are now simply called Filters (they still use DwooFilter)
* Pre/PostFilters have become Pre/PostProcessors (they now use DwooProcessor)
* Compiler: Fixed parsing bug that prevented function names of 1character
* Compiler: Changed internal handling of variables to fix some errors being
thrown with specific cases
* Reorganized Dwoo/DwooCompiler and fully commented all the core classes
and interfaces
[2008-03-09] 0.3.2
+ Added access to superglobals through $dwoo.get.value, $dwoo.post.value,
etc.
+ Added outputFilters to Dwoo (use Dwoo->addOutputFilter and
Dwoo->removeOutputFilter)
+ Added preFilters and postFilters to DwooCompiler (use
DwooCompiler->addPreFilter, etc)
+ Added a html_format output filter that intends properly the html code,
use it only on full page templates
+ Plugins: Added {for} and {forelse} which allow to loop over an array or to
loop over a range of numbers
+ Plugins: Added {mailto}, {counter}, {eval}, {fetch} and {include}
+ Syntax : Enhanced support for implicit math operations,
{$var+$var2*var3+5} now works. Operations are executed from left to right
though, there is no operator priority. (i.e. 1+1*2 = (1+1)*2 = 4, not 3)
+ API: Added resources support through DwooITemplate implementations and
Dwoo->addResource()
+ API: Added Dwoo->getTemplate() to get the currently running template object
+ API: Added DwooCompiler::getInstance() to use only one compiler object when
rendering from the default compiler and to provide you with a singleton if
it's easier, however the class is not a singleton in the sense that it can
be instantiated separately
+ API: Added a factory method on DwooITemplate to support resources creation
+ Added a release tag so that all compiled templates are forced to recompile
after an update, however it is recommended to cleanup your "compiled"
directory now and then as each release uses new filenames
+ Added an abstract DwooFilter class that you can extend to build filters
* PHP function calls are now case insensitive
* Syntax: The compiler now parses expressions before modifiers, allowing for
{$var/2|number_format} for example
* DwooTemplateFile now extends DwooTemplateString instead of the other way
around as it was before
* {else} is now a general purpose plugin that can act as 'else' for foreach,
for and if/elseif, foreachelse is still available though
[2008-03-05] 0.3.1
+ Added {cycle} function
+ Syntax : Enabled support for associative arrays using
array(key="value", key2=5) for example, which you can assign or use in a
foreach directly
+ Syntax : Added support for {$var +-/*% X} (i.e. {$var + 4}), useful for
simple math operations without the math plugin
+ API : Added append/appendByRef to DwooData
+ Completely rebuilt DwooSmartyAdapter, it should "work" and fail silently if
you use a non supported function now, however you can set
$smarty->show_compat_errors=true; on it to receive notices about unsupported
features that you use
* Bug fixed in {literal} parsing
* Bug fixed in smarty functions handling
* API : Moved Plugin types constants to Dwoo so the compiler doesn't have to
be loaded unles really required
* API : Moved globals and var reinitialization in Dwoo into their own methods
so that child classes can easily add globals
* Some improvements in the compiler output
* Some changes in the cache handling of DwooTemplateFile
- Special thanks to Andrew Collins that found many of the bugs fixed in this
release
[2008-03-02] 0.3.0
+ Full template cache support
+ DwooTemplateString class to load templates from a string
+ Dwoo::VERSION constant
+ {dump} plugin to print out variables
+ Unit tests (with PHPUnit) covering 73% of the codebase right now, which
should help reducing regression bugs in the next versions.
+ Started commenting (with phpdocs) properly all the classes, should be
complete for 0.4.0
* {capture} is now compilable and has a new boolean flag to append output into
the target variable instead of overwriting
* {foreach} supports direct input (instead of only variables), allowing
constructs like {foreach array(a,b,c) val}{$val}{/foreach} for example that
would output abc.
* pre/postProcessing functions in block plugins now receive an array of named
parameters instead of numbered
* Major refactoring of DwooTemplateFile and DwooCompiler
* Cleaned up members visibility in Dwoo/DwooCompiler
* Fixes in the compiler parsing and general variables handling
* Multiple bugfixes here and there thanks to the unit tests
* Optimized {foreach} a lot
[2008-02-19] 0.2.1
* Compiler fixes for argument parsing and handling of Smarty plugins
[2008-02-14] 0.2.0
+ Added support for plugins made for Smarty (that includes modifiers,
functions and blocks). Not thoroughly tested.
+ Major API changes in the way Dwoo must be run, it's now much more
flexible and should not change too much in the future.
+ Added support for custom plugins, filters should come in the next version
although the API to register them is already in.
[2008-02-08] 0.1.0
Initial release
\ No newline at end of file
This diff is collapsed. Click to expand it.
<?php
/**
* dwoo data object, use it for complex data assignments or if you want to easily pass it
* around multiple functions to avoid passing an array by reference
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooData implements DwooIDataProvider
{
/**
* data array
*
* @var array
*/
protected $data = array();
/**
* returns the data array
*
* @return array
*/
public function getData()
{
return $this->data;
}
/**
* clears a the entire data or only the given key
*
* @param string $name clears only that value if set or clears the entire data if left null
*/
public function clear($name = null)
{
if($name === null)
{
$this->data = array();
}
elseif(is_array($name))
{
foreach($name as $index)
unset($this->data[$index]);
}
else
unset($this->data[$name]);
}
/**
* overwrites the entire data with the given array
*
* @param array $data the new data array to use
*/
public function setData(array $data)
{
$this->data = $data;
}
/**
* merges the given array(s) with the current data with array_merge
*
* @param array $data the array to merge
* @param array $data2 $data3 ... other arrays to merge, optional, etc.
*/
public function mergeData(array $data)
{
$args = func_get_args();
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
*
* @param array|string $name an associative array of multiple (index=>value) or a string
* that is the index to use, i.e. a value assigned to "foo" will be
* accessible in the template through {$foo}
* @param mixed $val the value to assign, or null if $name was an array
*/
public function assign($name, $val = null)
{
if(is_array($name))
{
reset($name);
while(list($k,$v) = each($name))
$this->data[$k] = $v;
}
else
$this->data[$name] = $val;
}
/**
* assigns a value by reference to the data object
*
* @param string $name the index to use, i.e. a value assigned to "foo" will be
* accessible in the template through {$foo}
* @param mixed $val the value to assign by reference
*/
public function assignByRef($name, &$val)
{
$this->data[$name] =& $val;
}
/**
* appends values or an array of values to the data object
*
* @param array|string $name an associative array of multiple (index=>value) or a string
* that is the index to use, i.e. a value assigned to "foo" will be
* accessible in the template through {$foo}
* @param mixed $val the value to assign, or null if $name was an array
* @param bool $merge true to merge data or false to append, defaults to false
*/
public function append($name, $val = null, $merge = false)
{
if(is_array($name))
{
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))
$this->data[$key] = $val + $this->data[$key];
else
$this->data[$key][] = $val;
}
}
elseif($val !== null)
{
if(isset($this->data[$name]) && !is_array($this->data[$name]))
settype($this->data[$name], 'array');
if($merge === true && is_array($val))
$this->data[$name] = $val + $this->data[$name];
else
$this->data[$name][] = $val;
}
}
/**
* appends a value by reference to the data object
*
* @param string $name the index to use, i.e. a value assigned to "foo" will be
* accessible in the template through {$foo}
* @param mixed $val the value to append by reference
* @param bool $merge true to merge data or false to append, defaults to false
*/
public function appendByRef($name, &$val, $merge = false)
{
if(isset($this->data[$name]) && !is_array($this->data[$name]))
settype($this->data[$name], 'array');
if($merge === true && is_array($val))
{
foreach($val as $key => &$val)
$this->data[$name][$key] =& $val;
}
else
$this->data[$name][] =& $val;
}
}
?>
\ No newline at end of file
<?php
/**
* interface that represents a dwoo data object
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
interface DwooIDataProvider
{
/**
* returns the data as an associative array that will be used in the template
*
* @return array
*/
public function getData();
}
/**
* interface that represents a dwoo template
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
interface DwooITemplate
{
/**
* returns the cache duration for this template
*
* defaults to null if it was not provided
*
* @return int|null
*/
public function getCacheTime();
/**
* returns the cached template output file name, true if it's cache-able but not cached
* or false if it's not cached
*
* @param Dwoo $dwoo the dwoo instance that requests it
* @return string|bool
*/
public function getCachedTemplate(Dwoo $dwoo);
/**
* caches the provided output into the cache file
*
* @param Dwoo $dwoo the dwoo instance that requests it
* @param string $output the template output
*/
public function cache(Dwoo $dwoo, $output);
/**
* clears the cached template if it's older than the given time
*
* @param int $olderThan minimum time (in seconds) required for the cache to be cleared
* @return bool true if the cache was not present or if it was deleted, false if it remains there
*/
public function clearCache($olderThan=0);
/**
* returns the compiled template file name
*
* @param Dwoo $dwoo the dwoo instance that requests it
* @param DwooICompiler $compiler the compiler that must be used, if null a
* DwooCompiler will be used by default
* @return string
*/
public function getCompiledTemplate(Dwoo $dwoo, DwooICompiler $compiler);
/**
* returns the template name
*
* @return string
*/
public function getName();
/**
* returns the resource name for this template class
*
* @return string
*/
public function getResourceName();
/**
* returns the compiler used by this template, if it was just compiled, or null
*
* @return DwooICompiler
*/
public function getCompiler();
/**
* returns a new template object from the given include name, null if no include is
* possible (resource not found), or false if include is not permitted by this resource type
*
* @param mixed $resourceId the resource identifier
* @param int $cacheTime duration of the cache validity for this template,
* if null it defaults to the Dwoo instance that will
* render this template
* @param string $cacheId the unique cache identifier of this page or anything else that
* makes this template's content unique, if null it defaults
* to the current url
* @param string $compileId the unique compiled identifier, which is used to distinguish this
* template from others, if null it defaults to the filename+bits of the path
* @return DwooITemplate|null|false
*/
public static function templateFactory(Dwoo $dwoo, $resourceId, $cacheTime = null, $cacheId = null, $compileId = null);
}
/**
* interface that represents a dwoo compiler
*
* while implementing this is enough to interact with Dwoo/DwooTemplates, it is not
* sufficient to interact with DwooPlugins, however the main purpose of creating a
* new compiler would be to interact with other/different plugins, that is why this
* interface has been left with the minimum requirements.
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
interface DwooICompiler
{
/**
* compiles the provided string down to php code
*
* @param string $templateStr the template to compile
* @return string a compiled php code string
*/
public function compile($template);
/**
* adds the custom plugins loaded into Dwoo to the compiler so it can load them
*
* @see Dwoo::addPlugin
* @param array $customPlugins an array of custom plugins
*/
public function setCustomPlugins(array $customPlugins);
}
?>
This diff is collapsed. Click to expand it.
<?php
/**
* represents a Dwoo template contained in a file
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooTemplateFile extends DwooTemplateString
{
/**
* template filename
*
* @var string
*/
protected $file;
/**
* creates a template from a file
*
* @param string $file the path to the template file, make sure it exists
* @param int $cacheTime duration of the cache validity for this template,
* if null it defaults to the Dwoo instance that will
* render this template
* @param string $cacheId the unique cache identifier of this page or anything else that
* makes this template's content unique, if null it defaults
* to the current url
* @param string $compileId the unique compiled identifier, which is used to distinguish this
* template from others, if null it defaults to the filename+bits of the path
*/
public function __construct($file, $cacheTime = null, $cacheId = null, $compileId = null)
{
$this->file = realpath($file);
$this->name = basename($file);
$this->cacheTime = $cacheTime;
// no compile id provided, generate a kind of unique kind of readable one from the filename
if($compileId === null)
{
$parts = explode('/', strtr($file, '\\.', '/_'));
$compileId = array_pop($parts);
$compileId = substr(array_pop($parts), 0, 5) .'_'. $compileId;
$compileId = substr(array_pop($parts), 0, 5) .'_'. $compileId;
}
$this->compileId = $compileId;
// no cache id provided, use request_uri
if($cacheId === null)
{
$cacheId = bin2hex(md5($_SERVER['REQUEST_URI'], true));
}
$this->cacheId = $this->compileId . $cacheId;
}
/**
* returns the compiled template file name
*
* @param Dwoo $dwoo the dwoo instance that requests it
* @param DwooICompiler $compiler the compiler that must be used, if null a
* DwooCompiler will be used by default
* @return string
*/
public function getCompiledTemplate(Dwoo $dwoo, DwooICompiler $compiler)
{
$compiledFile = $dwoo->getCompileDir() . $this->compileId.'.'.Dwoo::RELEASE_TAG.'.dwoo';
// already checked, return compiled file
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))
{
self::$cache['compiled'][$this->compileId] = true;
}
// compiles the template
else
{
$this->compilationEnforced = false;
$this->compiler = $compiler;
$compiler->setCustomPlugins($dwoo->getCustomPlugins());
file_put_contents($compiledFile, $compiler->compile(file_get_contents($this->file)));
touch($compiledFile, max($_SERVER['REQUEST_TIME'], filemtime($this->file)));
self::$cache['compiled'][$this->compileId] = true;
}
return $compiledFile;
}
/**
* returns the resource name for this template class
*
* @return string
*/
public function getResourceName()
{
return 'file';
}
/**
* returns this template's source filename
*
* @return string
*/
public function getFilename()
{
return $this->file;
}
/**
* returns a new template object from the given include name, null if no include is
* possible (resource not found), or false if include is not permitted by this resource type
*
* @param Dwoo $dwoo the dwoo instance requiring it
* @param mixed $resourceId the filename (relative to this template's dir) of the template to include
* @param int $cacheTime duration of the cache validity for this template,
* if null it defaults to the Dwoo instance that will
* render this template
* @param string $cacheId the unique cache identifier of this page or anything else that
* makes this template's content unique, if null it defaults
* to the current url
* @param string $compileId the unique compiled identifier, which is used to distinguish this
* template from others, if null it defaults to the filename+bits of the path
* @return DwooTemplateFile|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);
// TODO check for recursion here if security is enabled
if(file_exists($resourceId))
return new self($resourceId, $cacheTime, $cacheId, $compileId);
$tpl = $dwoo->getCurrentTemplate();
if($tpl instanceof DwooTemplateFile)
{
$file = dirname($tpl->getFilename()).DIRECTORY_SEPARATOR.$resourceId;
if(file_exists($file))
return new self($file, $cacheTime, $cacheId, $compileId);
}
return null;
}
}
?>
\ No newline at end of file
<?php
/**
* represents a Dwoo template contained in a string
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooTemplateString implements DwooITemplate
{
/**
* template name
*
* @var string
*/
protected $name;
/**
* template compilation id
*
* @var string
*/
protected $compileId;
/**
* template cache id, if not provided in the constructor, it is set to
* the md5 hash of the request_uri. it is however highly recommended to
* provide one that will fit your needs.
*
* in all cases, the compilation id is prepended to the cache id to separate
* templates with similar cache ids from one another
*
* @var string
*/
protected $cacheId;
/**
* validity duration of the generated cache file (in seconds)
*
* set to -1 for infinite cache, 0 to disable and null to inherit the Dwoo instance's cache time
*
* @var int
*/
protected $cacheTime;
/**
* boolean flag that defines whether the compilation should be enforced (once) or
* not use this if you have issues with the compiled templates not being updated
* but if you do need this it's most likely that you should file a bug report
*
* @var bool
*/
protected $compilationEnforced;
/**
* caches the results of the file checks to save some time when the same
* templates is rendered several times
*
* @var array
*/
protected static $cache = array('cached'=>array(), 'compiled'=>array());
/**
* holds the compiler that built this template
*
* @var DwooICompiler
*/
protected $compiler;
/**
* creates a template from a string
*
* @param string $templateString the template to use
* @param int $cacheTime duration of the cache validity for this template,
* if null it defaults to the Dwoo instance that will
* render this template, set to -1 for infinite cache or 0 to disable
* @param string $cacheId the unique cache identifier of this page or anything else that
* makes this template's content unique, if null it defaults
* to the current url
* @param string $compileId the unique compiled identifier, which is used to distinguish this
* template from others, if null it defaults to the md5 hash of the template
*/
public function __construct($templateString, $cacheTime = null, $cacheId = null, $compileId = null)
{
$this->template = $templateString;
$this->name = bin2hex(md5($templateString, true));
$this->cacheTime = $cacheTime;
// no compile id provided, set it to an md5 hash of the template
if($compileId === null)
{
$compileId = $this->name;
}
$this->compileId = $compileId;
// no cache id provided, use request_uri
if($cacheId === null)
{
$cacheId = bin2hex(md5($_SERVER['REQUEST_URI'], true));
}
$this->cacheId = $this->compileId . $cacheId;
}
/**
* returns the cache duration for this template
*
* defaults to null if it was not provided
*
* @return int|null
*/
public function getCacheTime()
{
return $this->cacheTime;
}
/**
* returns the template name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* returns the resource name for this template class
*
* @return string
*/
public function getResourceName()
{
return 'string';
}
/**
* returns the compiler used by this template, if it was just compiled, or null
*
* @return DwooICompiler
*/
public function getCompiler()
{
return $this->compiler;
}
/**
* marks this template as compile-forced, which means it will be recompiled even if it
* was already saved and wasn't modified since the last compilation. do not use this in production,
* it's only meant to be used in development (and the development of dwoo particularly)
*/
public function forceCompilation()
{
$this->compilationEnforced = true;
}
/**
* returns the cached template output file name, true if it's cache-able but not cached
* or false if it's not cached
*
* @param Dwoo $dwoo the dwoo instance that requests it
* @return string|bool
*/
public function getCachedTemplate(Dwoo $dwoo)
{
$cachedFile = $dwoo->getCacheDir() . $this->cacheId.'.dwoo';
if($this->cacheTime !== null)
$cacheLength = $this->cacheTime;
else
$cacheLength = $dwoo->getCacheTime();
// file is not cacheable
if($cacheLength === 0)
{
return false;
}
// already checked, return cache file
if(isset(self::$cache['cached'][$this->cacheId]) === true)
{
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)))
{
self::$cache['cached'][$this->cacheId] = true;
return $cachedFile;
}
// file is cacheable
else
{
return true;
}
}
/**
* caches the provided output into the cache file
*
* @param Dwoo $dwoo the dwoo instance that requests it
* @param string $output the template output
*/
public function cache(Dwoo $dwoo, $output)
{
$cachedFile = $dwoo->getCacheDir() . $this->cacheId.'.dwoo';
file_put_contents($cachedFile, $output);
touch($cachedFile, $_SERVER['REQUEST_TIME']);
self::$cache['cached'][$this->cacheId] = true;
}
/**
* clears the cached template if it's older than the given time
*
* @param int $olderThan minimum time (in seconds) required for the cache to be cleared
* @return bool true if the cache was not present or if it was deleted, false if it remains there
*/
public function clearCache($olderThan=0)
{
$cachedFile = $dwoo->getCacheDir() . $this->cacheId.'.dwoo';
return !file_exists($cachedFile) || (filectime($cachedFile) < (time() - $olderThan) && unlink($cachedFile));
}
/**
* returns the compiled template file name
*
* @param Dwoo $dwoo the dwoo instance that requests it
* @param DwooICompiler $compiler the compiler that must be used, if null a
* DwooCompiler will be used by default
* @return string
*/
public function getCompiledTemplate(Dwoo $dwoo, DwooICompiler $compiler)
{
$compiledFile = $dwoo->getCompileDir() . $this->compileId.'.'.Dwoo::RELEASE_TAG.'.dwoo';
// already checked, return compiled file
if($this->compilationEnforced !== true && isset(self::$cache['compiled'][$this->compileId]) === true)
{
}
// template is compiled
elseif($this->compilationEnforced !== true && file_exists($compiledFile)===true)
{
self::$cache['compiled'][$this->compileId] = true;
}
// compiles the template
else
{
$this->compilationEnforced = false;
$this->compiler = $compiler;
$compiler->setCustomPlugins($dwoo->getCustomPlugins());
file_put_contents($compiledFile, $compiler->compile($this->template));
touch($compiledFile, $_SERVER['REQUEST_TIME']);
self::$cache['compiled'][$this->compileId] = true;
}
return $compiledFile;
}
/**
* returns false as this template type does not support inclusions
*
* @param mixed $resourceId the filename (relative to this template's dir) of the template to include
* @param int $cacheTime duration of the cache validity for this template,
* if null it defaults to the Dwoo instance that will
* render this template
* @param string $cacheId the unique cache identifier of this page or anything else that
* makes this template's content unique, if null it defaults
* to the current url
* @param string $compileId the unique compiled identifier, which is used to distinguish this
* template from others, if null it defaults to the filename+bits of the path
* @return false
*/
public static function templateFactory(Dwoo $dwoo, $resourceId, $cacheTime = null, $cacheId = null, $compileId = null)
{
return false;
}
}
?>
\ No newline at end of file
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
-----------------------------------------------------------------------------
-- WHAT IS DWOO? readme - version 0.3.2
-----------------------------------------------------------------------------
Dwoo is a PHP5 Template Engine that was started in early 2008. The idea came
from the fact that Smarty, a well known template engine, is getting older and
older. It carries the weight of it's age, having old features that are
inconsistent compared to newer ones, being written for PHP4 its Object
Oriented aspect doesn't take advantage of PHP5's more advanced features in
the area, etc. Hence Dwoo was born, hoping to provide a more up to date and
stronger engine.
So far it has proven to be faster than Smarty in many areas, and it provides
a compatibility layer to allow developers that have been using Smarty for
years to switch their application over to Dwoo progressively.
-----------------------------------------------------------------------------
-- DOCUMENTATION
-----------------------------------------------------------------------------
Dwoo's website to get the latest version is at http://dwoo.org/
The wiki/documentation pages are available at http://wiki.dwoo.org/
-----------------------------------------------------------------------------
-- LICENSE
-----------------------------------------------------------------------------
Dwoo is released under the GNU Lesser General Public License version 3.0.
See the LICENSE file included in the archive or go to the URL below to obtain
a copy.
http://www.gnu.org/licenses/lgpl.html
-----------------------------------------------------------------------------
-- QUICK START - RUNNING DWOO
-----------------------------------------------------------------------------
/***************************** Basic Example *******************************/
// Include the main class (it should handle the rest on its own)
include 'path/to/Dwoo.php';
// Create the controller, this is reusable
$dwoo = new Dwoo();
// Load a template file (name it as you please), this is reusable
// if you want to render multiple times the same template with different data
$tpl = new DwooTemplateFile('path/to/index.tpl');
// Create a data set, if you don't like this you can directly input an
// associative array in $dwoo->output()
$data = new DwooData();
// Fill it with some data
$data->assign('foo', 'BAR');
$data->assign('bar', 'BAZ');
// Outputs the result ...
$dwoo->output($tpl, $data);
// ... or get it to use it somewhere else
$dwoo->get($tpl, $data);
/***************************** Loop Example *******************************/
// To loop over multiple articles of a blog for instance, if you have a
// template file representing an article, you could do the following :
include 'path/to/Dwoo.php';
$dwoo = new Dwoo();
$tpl = new DwooTemplateFile('path/to/article.tpl');
$pageContent = '';
// Loop over articles that have been retrieved from the DB
foreach($articles as $article) {
// Either associate variables one by one
$data = new DwooData();
$data->assign('title', $article['title'];
$data->assign('content', $article['content']);
$pageContent .= $dwoo->get($tpl, $data);
// Or use the article directly (which is a lot easier in this case)
$pageContent .= $dwoo->get($tpl, $article);
}
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooPlugin_capture extends DwooBlockPlugin implements DwooICompilableBlock
{
public function init($name = 'default', $assign = null, $cat = false)
{
}
public static function preProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='', $type)
{
return DwooCompiler::PHP_OPEN.$prepend.'ob_start();'.$append.DwooCompiler::PHP_CLOSE;
}
public static function postProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='')
{
$params = $compiler->getCompiledParams($params);
$out = DwooCompiler::PHP_OPEN.$prepend."\n".'$tmp = ob_get_clean();';
if($params['cat'] === 'true') {
$out .= "\n".'$tmp = $this->readVar(\'dwoo.capture.\'.'.$params['name'].') . $tmp;';
}
if($params['assign'] !== "null") {
$out .= "\n".'$this->scope['.$params['assign'].'] = $tmp;';
}
return $out . "\n".'$this->globals[\'capture\']['.$params['name'].'] = $tmp;'.$append.DwooCompiler::PHP_CLOSE;
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooPlugin_else extends DwooBlockPlugin implements DwooICompilableBlock
{
public function init()
{
}
public static function preProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='', $type)
{
$block =& $compiler->getCurrentBlock();
$out = '';
while($block['type'] !== 'if' && $block['type'] !== 'foreach' && $block['type'] !== 'for' && $block['type'] !== 'with')
{
$out .= $compiler->removeTopBlock();
$block =& $compiler->getCurrentBlock();
}
$out .= $block['params']['postOutput'];
$block['params']['postOutput'] = '';
$out = substr($out, 0, -strlen(DwooCompiler::PHP_CLOSE));
$currentBlock =& $compiler->getCurrentBlock();
$currentBlock['params']['postOutput'] = DwooCompiler::PHP_OPEN."\n}".DwooCompiler::PHP_CLOSE;
return $out . "else {\n".DwooCompiler::PHP_CLOSE;
}
public static function postProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='')
{
if(isset($params['postOutput']))
return $params['postOutput'];
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooPlugin_elseif extends DwooPlugin_if implements DwooICompilableBlock
{
public function init(array $rest)
{
}
public static function preProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='', $type)
{
$if =& $compiler->findBlock('if', true);
$out = $if['params']['postOutput'];
$if['params']['postOutput'] = '';
$compiler->injectBlock($type, $params, 1);
$currentBlock =& $compiler->getCurrentBlock();
$currentBlock['params']['postOutput'] = DwooCompiler::PHP_OPEN."\n}".DwooCompiler::PHP_CLOSE;
$out = substr($out, 0, -strlen(DwooCompiler::PHP_CLOSE));
return $out . "elseif(".implode(' ', self::replaceKeywords($params, $compiler)).") {\n" . DwooCompiler::PHP_CLOSE;
}
public static function postProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='')
{
if(isset($params['postOutput']))
return $params['postOutput'];
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooPlugin_for extends DwooBlockPlugin implements DwooICompilableBlock
{
public static $cnt=0;
public function init($name, $from, $to=null, $step=1, $skip=0)
{
}
public static function preProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='', $type)
{
// TODO pad the range to 1000 or something if security is enabled
$params = $compiler->getCompiledParams($params);
$tpl = $compiler->getTemplateSource(true);
// assigns params
$from = $params['from'];
$name = $params['name'];
$step = $params['step'];
$skip = $params['skip'];
$to = $params['to'];
// evaluates which global variables have to be computed
$varName = '$dwoo.for.'.trim($name, '"\'').'.';
$usesAny = strpos($tpl, $varName) !== false;
$usesFirst = strpos($tpl, $varName.'first') !== false;
$usesLast = strpos($tpl, $varName.'last') !== false;
$usesIndex = strpos($tpl, $varName.'index') !== false;
$usesIteration = $usesFirst || $usesLast || strpos($tpl, $varName.'iteration') !== false;
$usesShow = strpos($tpl, $varName.'show') !== false;
$usesTotal = $usesLast || strpos($tpl, $varName.'total') !== false;
// gets foreach id
$cnt = self::$cnt++;
// builds pre processing output for
$out = DwooCompiler::PHP_OPEN . "\n".'$_for'.$cnt.'_from = $_for'.$cnt.'_src = '.$from.';'.
"\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>\'); }';
// adds foreach properties
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),';
$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{";
// iterates over keys
$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)
$_for'.$cnt.'_keys[] = $tmp;
} else {
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{";
// updates properties
if($usesIndex)
$out.="\n\t\t".'$_for'.$cnt.'_glob["index"] = $this->scope['.$name.'];';
if($usesFirst)
$out .= "\n\t\t".'$_for'.$cnt.'_glob["first"] = (string) ($_for'.$cnt.'_glob["iteration"] === 1);';
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".DwooCompiler::PHP_CLOSE;
// build post processing output and cache it
$postOut = DwooCompiler::PHP_OPEN . '// -- for end output';
// update properties
if($usesIteration)
$postOut.="\n\t\t".'$_for'.$cnt.'_glob["iteration"]+=1;';
// end loop
$postOut .= "\n\t}\n}\n";
// get block params and save the post-processing output already
$currentBlock =& $compiler->getCurrentBlock();
$currentBlock['params']['postOutput'] = $postOut . DwooCompiler::PHP_CLOSE;
return $out;
}
public static function postProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='')
{
return $params['postOutput'];
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooPlugin_foreach extends DwooBlockPlugin implements DwooICompilableBlock
{
public static $cnt=0;
public function init($from, $key=null, $item=null, $name='default')
{
}
public static function preProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='', $type)
{
$params = $compiler->getCompiledParams($params);
$tpl = $compiler->getTemplateSource(true);
// assigns params
$src = $params['from'];
if($params['item'] !== 'null')
{
if($params['key'] !== 'null')
$key = $params['key'];
$val = $params['item'];
}
elseif($params['key'] !== 'null')
{
$val = $params['key'];
}
else
throw new Exception('Parameter 3/item missing for foreach', E_USER_NOTICE);
$name = $params['name'];
if(substr($val,0,1) !== '"' && substr($val,0,1) !== '\'')
$compiler->triggerError('Foreach <em>value</em> parameter must be of type string', E_USER_ERROR);
if(isset($key) && substr($val,0,1) !== '"' && substr($val,0,1) !== '\'')
$compiler->triggerError('Foreach <em>key</em> parameter must be of type string', E_USER_ERROR);
// evaluates which global variables have to be computed
$varName = '$dwoo.foreach.'.trim($name, '"\'').'.';
$usesAny = strpos($tpl, $varName) !== false;
$usesFirst = strpos($tpl, $varName.'first') !== false;
$usesLast = strpos($tpl, $varName.'last') !== false;
$usesIndex = $usesFirst || strpos($tpl, $varName.'index') !== false;
$usesIteration = $usesLast || strpos($tpl, $varName.'iteration') !== false;
$usesShow = strpos($tpl, $varName.'show') !== false;
$usesTotal = $usesLast || strpos($tpl, $varName.'total') !== false;
// gets foreach id
$cnt = self::$cnt++;
// builds pre processing output
$out = DwooCompiler::PHP_OPEN . "\n".'$_fh'.$cnt.'_data = '.$src.';';
// adds foreach properties
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),';
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)'."\n{";
// iterates over keys
$out .= "\n\t".'foreach($_fh'.$cnt.'_data as '.(isset($key)?'$this->scope['.$key.']=>':'').'$this->scope['.$val.'])'."\n\t{";
// updates properties
if($usesFirst)
$out .= "\n\t\t".'$_fh'.$cnt.'_glob["first"] = (string) ($_fh'.$cnt.'_glob["index"] === 0);';
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".DwooCompiler::PHP_CLOSE;
// build post processing output and cache it
$postOut = DwooCompiler::PHP_OPEN . "\n".'// -- foreach end output';
// update properties
if($usesIndex)
$postOut.="\n\t\t".'$_fh'.$cnt.'_glob["index"]+=1;';
if($usesIteration)
$postOut.="\n\t\t".'$_fh'.$cnt.'_glob["iteration"]+=1;';
// end loop
$postOut .= "\n\t}\n}\n";
// get block params and save the post-processing output already
$currentBlock =& $compiler->getCurrentBlock();
$currentBlock['params']['postOutput'] = $postOut . DwooCompiler::PHP_CLOSE;
return $out;
}
public static function postProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='')
{
return $params['postOutput'];
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooPlugin_foreachelse extends DwooBlockPlugin implements DwooICompilableBlock
{
public function init()
{
}
public static function preProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='', $type)
{
$foreach =& $compiler->findBlock('foreach', true);
$out = $foreach['params']['postOutput'];
$foreach['params']['postOutput'] = '';
$compiler->injectBlock($type, $params, 1);
if(substr($out, -strlen(DwooCompiler::PHP_CLOSE)) === DwooCompiler::PHP_CLOSE)
$out = substr($out, 0, -strlen(DwooCompiler::PHP_CLOSE));
else
$out .= DwooCompiler::PHP_OPEN;
return $out . "else\n{" . DwooCompiler::PHP_CLOSE;
}
public static function postProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='')
{
return DwooCompiler::PHP_OPEN.'}'.DwooCompiler::PHP_CLOSE;
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooPlugin_forelse extends DwooBlockPlugin implements DwooICompilableBlock
{
public function init()
{
}
public static function preProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='', $type)
{
$foreach =& $compiler->findBlock('for', true);
$out = $foreach['params']['postOutput'];
$foreach['params']['postOutput'] = '';
$compiler->injectBlock($type, $params, 1);
if(substr($out, -strlen(DwooCompiler::PHP_CLOSE)) === DwooCompiler::PHP_CLOSE)
$out = substr($out, 0, -strlen(DwooCompiler::PHP_CLOSE));
else
$out .= DwooCompiler::PHP_OPEN;
return $out . "else\n{" . DwooCompiler::PHP_CLOSE;
}
public static function postProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='')
{
return DwooCompiler::PHP_OPEN.'}'.DwooCompiler::PHP_CLOSE;
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooPlugin_if extends DwooBlockPlugin implements DwooICompilableBlock
{
public function init(array $rest) {}
public static function replaceKeywords($params, DwooCompiler $compiler)
{
$params = $compiler->getCompiledParams($params);
$p = array();
$params = $params['*'];
while(list($k,$v) = each($params))
{
switch($v)
{
case '"<<"':
case '">>"':
case '"&&"':
case '"||"':
case '"|"':
case '"^"':
case '"&"':
case '"~"':
case '"("':
case '")"':
case '","':
case '"+"':
case '"-"':
case '"*"':
case '"/"':
$p[] = trim($v, '"');
break;
case '"=="':
case '"eq"':
$p[] = '==';
break;
case '"<>"':
case '"!="':
case '"ne"':
case '"neq"':
$p[] = '!=';
break;
case '">="':
case '"gte"':
case '"ge"':
$p[] = '>=';
break;
case '"<="':
case '"lte"':
case '"le"':
$p[] = '<=';
break;
case '">"':
case '"gt"':
$p[] = '>';
break;
case '"<"':
case '"lt"':
$p[] = '<';
break;
case '"==="':
$p[] = '===';
break;
case '"!=="':
$p[] = '!==';
break;
case '"is"':
if($params[$k+1] === '"not"')
{
$negate = true;
next($params);
}
else
$negate = false;
$ptr = 1+(int)$negate;
switch($params[$k+$ptr])
{
case '"div"':
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
throw new Exception('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], E_USER_NOTICE);
break;
case '"even"':
$a = array_pop($p);
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
{
$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"')
{
$b = $params[$k+$ptr+2];
$p[] = '('.$a .' / '.$b.') % 2 '.($negate?'=':'!').'== 0';
next($params);
next($params);
}
else
{
$p[] = $a.' % 2 '.($negate?'=':'!').'== 0';
}
next($params);
break;
default:
throw new Exception('Syntax error : syntax should be "if $a is [not] (div|even|odd) [by $b]", found '.$params[$k-1].' is '.$params[$k+$ptr+1], E_USER_NOTICE);
}
break;
case '"%"':
case '"mod"':
$p[] = '%';
break;
case '"!"':
case '"not"':
$p[] = '!';
break;
default:
$p[] = $v;
}
}
return $p;
}
public static function preProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='', $type)
{
$currentBlock =& $compiler->getCurrentBlock();
$currentBlock['params']['postOutput'] = DwooCompiler::PHP_OPEN."\n}".DwooCompiler::PHP_CLOSE;
return DwooCompiler::PHP_OPEN.'if('.implode(' ', self::replaceKeywords($params, $compiler)).") {\n".DwooCompiler::PHP_CLOSE;
}
public static function postProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='')
{
return $params['postOutput'];
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooPlugin_smartyinterface extends DwooPlugin
{
public function init($__funcname, $__functype, array $rest=array()) {}
public static function preProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='', $type)
{
$params = $compiler->getCompiledParams($params);
$func = $params['__funcname'];
$pluginType = $params['__functype'];
$params = $params['*'];
if($pluginType & Dwoo::CUSTOM_PLUGIN)
{
$callback = $compiler->customPlugins[$func]['callback'];
if(is_array($callback))
{
if(is_object($callback[0]))
$callback = '$this->customPlugins[\''.$func.'\'][0]->'.$callback[1].'(';
else
$callback = ''.$callback[0].'::'.$callback[1].'(';
}
else
$callback = $callback.'(';
}
else
$callback = 'smarty_block_'.$func.'(';
$compiler->curBlock['params']['postOut'] = DwooCompiler::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);'.DwooCompiler::PHP_CLOSE;
return DwooCompiler::PHP_OPEN.$prepend.' $_tag_stack[] = '.var_export($params,true).'; $_block_repeat=true; '.$callback.'$_tag_stack[count($_tag_stack)-1], null, $this, $_block_repeat); while ($_block_repeat) { ob_start();'.DwooCompiler::PHP_CLOSE;
}
public static function postProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='')
{
return $params['postOut'];
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooPlugin_textformat extends DwooBlockPlugin
{
protected $wrap;
protected $wrapChar;
protected $wrapCut;
protected $indent;
protected $indChar;
protected $indFirst;
protected $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')
$indent_char = "\t";
switch($style)
{
case 'email':
$wrap = 72;
$indent_first = 0;
break;
case 'html':
$wrap_char = '<br />';
$indent_char = $indent_char == "\t" ? '&nbsp;&nbsp;&nbsp;&nbsp;':'&nbsp;';
break;
}
$this->wrap = (int) $wrap;
$this->wrapChar = (string) $wrap_char;
$this->wrapCut = (bool) $wrap_cut;
$this->indent = (int) $indent;
$this->indChar = (string) $indent_char;
$this->indFirst = (int) $indent_first + $this->indent;
$this->assign = (string) $assign;
}
public function process()
{
// gets paragraphs
$pgs = explode("\n", str_replace(array("\r\n", "\r"), "\n", $this->buffer));
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]));
// wordwraps + indents lines
$pgs[$i] = str_repeat($this->indChar, $this->indFirst) .
wordwrap(
$pgs[$i],
max($this->wrap - $this->indent, 1),
$this->wrapChar . str_repeat($this->indChar, $this->indent),
$this->wrapCut
);
}
if($this->assign !== '')
$this->dwoo->assignInScope(implode($this->wrapChar . $this->wrapChar, $pgs), $this->assign);
else
return implode($this->wrapChar . $this->wrapChar, $pgs);
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
final class DwooPlugin_topLevelBlock extends DwooBlockPlugin
{
public function init()
{
}
public static function preProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='', $type)
{
return 'ob_start(); $this->addStack("topLevelBlock");'.DwooCompiler::PHP_CLOSE;
}
public static function postProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='')
{
return DwooCompiler::PHP_OPEN.'$this->delStack(); return ob_get_clean();';
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooPlugin_with extends DwooBlockPlugin implements DwooICompilableBlock
{
protected static $cnt=0;
public function init($var)
{
}
public static function preProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='', $type)
{
$rparams = $compiler->getRealParams($params);
$cparams = $compiler->getCompiledParams($params);
$c = $rparams['var'];
$compiler->setScope($c);
if(empty($c))
throw new Exception('With requires one parameter : <em>var</em> - the variable to use as the active scope inside the {with} block');
$params =& $compiler->getCurrentBlock();
$params['params']['postOutput'] = DwooCompiler::PHP_OPEN."\n// -- end with output\n".'$this->forceScope($_with'.(self::$cnt).');'."\n}\n".DwooCompiler::PHP_CLOSE;
return DwooCompiler::PHP_OPEN.'if('.$cparams['var'].')'."\n{\n".'$_with'.(self::$cnt++).' = $this->setScope("'.$c.'");'."\n// -- start with output\n".DwooCompiler::PHP_CLOSE;
}
public static function postProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='')
{
return $params['postOutput'];
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooPlugin_withelse extends DwooBlockPlugin implements DwooICompilableBlock
{
public function init()
{
}
public static function preProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='', $type)
{
$foreach =& $compiler->findBlock('with', true);
$out = $foreach['params']['postOutput'];
$foreach['params']['postOutput'] = '';
$compiler->injectBlock($type, $params, 1);
if(substr($out, -strlen(DwooCompiler::PHP_CLOSE)) === DwooCompiler::PHP_CLOSE)
$out = substr($out, 0, -strlen(DwooCompiler::PHP_CLOSE));
else
$out .= DwooCompiler::PHP_OPEN;
return $out . "else\n{" . DwooCompiler::PHP_CLOSE;
}
public static function postProcessing(DwooCompiler $compiler, array $params, $prepend='', $append='')
{
return DwooCompiler::PHP_OPEN.'}'.DwooCompiler::PHP_CLOSE;
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooFilter_html_format extends DwooFilter
{
/**
* tab count to auto-indent the source
*
* @var int
*/
protected static $tabCount = -1;
/**
* stores the additional data (following a tag) of the last call to open/close/singleTag
*
* @var string
*/
protected static $lastCallAdd = '';
/**
* formats the input using the singleTag/closeTag/openTag functions
*
* It is auto indenting the whole code, excluding <textarea>, <code> and <pre> tags that must be kept intact.
* Those tags must however contain only htmlentities-escaped text for everything to work properly.
* Inline tags are presented on a single line with their content
*
* @param Dwoo $dwoo the dwoo instance rendering this
* @param string $input the xhtml to format
* @return string formatted xhtml
*/
public function process($input)
{
self::$tabCount = -1;
// auto indent all but textareas & pre (or we have weird tabs inside)
$input = preg_replace_callback("#(<[^>]+>)(\s*)([^<]*)#", array('self', 'tagDispatcher'), $input);
return $input;
}
/**
* helper function for format()'s preg_replace call
*
* @param array $input array of matches (1=>tag, 2=>whitespace(optional), 3=>additional non-html content)
* @return string the indented tag
*/
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[") {
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) == "/>") {
return self::singleTag($input[1],$input[3],$input[2]);
}
// it's the closing tag
if($input[0][1]=="/"){
return self::closeTag($input[1],$input[3],$input[2]);
}
// opening tag
return self::openTag($input[1],$input[3],$input[2]);
}
/**
* returns an open tag and adds a tab into the auto indenting
*
* @param string $tag content of the tag
* @param string $add additional data (anything before the following tag)
* @param string $whitespace white space between the tag and the additional data
* @return string
*/
protected static function openTag($tag,$add,$whitespace)
{
$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))
{
$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')
{
$result = $tabs . $tag;
}
// normal block tag
else
{
$result = "\n".$tabs . $tag;
if(!empty($add))
{
$result .= "\n".$tabs."\t".str_replace("\n","\n\t".$tabs,$add);
}
}
self::$lastCallAdd = $add;
return $result;
}
/**
* returns a closing tag and removes a tab from the auto indenting
*
* @param string $tag content of the tag
* @param string $add additional data (anything before the following tag)
* @param string $whitespace white space between the tag and the additional data
* @return string
*/
protected static function closeTag($tag,$add,$whitespace)
{
$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))
{
$result = $tag . $whitespace . str_replace("\n","\n".$tabs,$add);
}
else
{
$result = "\n".$tabs.$tag;
if(!empty($add))
{
$result .= "\n".$tabs."\t".str_replace("\n","\n\t".$tabs,$add);
}
}
self::$lastCallAdd = $add;
return $result;
}
/**
* returns a single tag with auto indenting
*
* @param string $tag content of the tag
* @param string $add additional data (anything before the following tag)
* @return string
*/
protected static function singleTag($tag,$add,$whitespace)
{
$tabs = str_pad('',self::$tabCount,"\t");
// 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))
{
$result = $tag.$whitespace;
if(!empty($add))
{
$result .= str_replace("\n","\n".$tabs,$add);
}
}
else
{
$result = "\n".$tabs.$tag;
if(!empty($add))
{
$result .= "\n".$tabs.str_replace("\n","\n".$tabs,$add);
}
}
self::$lastCallAdd = $add;
return $result;
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_assign_compile(DwooCompiler $compiler, $value, $var)
{
return '$this->assignInScope('.$value.', '.$var.')';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_capitalize(Dwoo $dwoo, $value, $numwords=false)
{
if($numwords || preg_match('#^[^0-9]+$#',$value))
{
if($dwoo->getCharset() === 'iso-8859-1')
return ucwords((string) $value);
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))
$out .= ' '.mb_convert_case($v, MB_CASE_TITLE, $dwoo->getCharset());
else
$out .= ' '.$v;
return substr($out, 1);
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_cat_compile(DwooCompiler $compiler, $value, array $rest)
{
return '('.$value.').('.implode(').(', $rest).')';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_count_characters_compile(DwooCompiler $compiler, $value, $count_spaces=false)
{
if($count_spaces==='false')
return 'preg_match_all(\'#[^\s\pZ]#u\', '.$value.', $tmp)';
else
return 'mb_strlen('.$value.', $this->charset)';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_count_paragraphs_compile(DwooCompiler $compiler, $value)
{
return '(preg_match_all(\'#[\r\n]+#\', '.$value.', $tmp)+1)';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_count_sentences_compile(DwooCompiler $compiler, $value)
{
return "preg_match_all('#[\w\pL]\.(?![\w\pL])#u', $value, \$tmp)";
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_count_words_compile(DwooCompiler $compiler, $value)
{
return 'preg_match_all(strcasecmp($this->charset, \'utf-8\')===0 ? \'#[\w\pL]+#u\' : \'#\w+#\', '.$value.', $tmp)';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooPlugin_counter extends DwooPlugin
{
protected $counters = array();
public function process($name = 'default', $start = null, $skip = null, $direction = null, $print = null, $assign = null)
{
// init counter
if(!isset($this->counters[$name]))
{
$this->counters[$name] = array
(
'count' => $start===null ? 1 : (int) $start,
'skip' => $skip===null ? 1 : (int) $skip,
'print' => $print===null ? true : (bool) $print,
'assign' => $assign===null ? null : (string) $assign,
'direction' => strtolower($direction)==='down' ? -1 : 1,
);
}
// increment
else
{
// override setting if present
if($skip !== null)
$this->counters[$name]['skip'] = (int) $skip;
if($direction !== null)
$this->counters[$name]['direction'] = strtolower($direction)==='down' ? -1 : 1;
if($print !== null)
$this->counters[$name]['print'] = (bool) $print;
if($assign !== null)
$this->counters[$name]['assign'] = (string) $assign;
if($start !== null)
$this->counters[$name]['count'] = (int) $start;
else
$this->counters[$name]['count'] += ($this->counters[$name]['skip'] * $this->counters[$name]['direction']);
}
$out = $this->counters[$name]['count'];
if($this->counters[$name]['assign'] !== null)
$this->dwoo->assignInScope($out, $this->counters[$name]['assign']);
elseif($this->counters[$name]['print'] === true)
return $out;
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooPlugin_cycle extends DwooPlugin
{
protected $cycles = array();
public function process($name = 'default', $values = null, $print = true, $advance = true, $delimiter = ',', $assign = null, $reset = false)
{
if($values !== null)
{
if(is_string($values))
$values = explode($delimiter, $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]))
{
$values = $this->cycles[$name]['values'];
}
if($reset)
$this->cycles[$name]['index'] = 0;
if($print)
$out = $values[$this->cycles[$name]['index']];
else
$out = null;
if($advance)
{
if($this->cycles[$name]['index'] >= count($values)-1)
$this->cycles[$name]['index'] = 0;
else
$this->cycles[$name]['index']++;
}
if($assign !== null)
$this->dwoo->assignInScope($assign, $out);
else
return $out;
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_date_format(Dwoo $dwoo, $value, $format='%b %e, %Y', $default=null)
{
if(!empty($value))
{
// don't convert if it's a valid unix timestamp
if(preg_match('#^\d{10}$#', $value)===false)
$value = strtotime($value);
}
elseif(!empty($default))
{
// don't convert if it's a valid unix timestamp
if(preg_match('#^\d{10}$#', $default)===false)
$value = strtotime($default);
}
else
return '';
// Credits for that windows compat block to Monte Ohrt who made smarty's date_format plugin
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)
{
$_win_from[] = '%e';
$_win_to[] = sprintf('%\' 2d', date('j', $value));
}
if(strpos($format, '%l') !== false)
{
$_win_from[] = '%l';
$_win_to[] = sprintf('%\' 2d', date('h', $value));
}
$format = str_replace($_win_from, $_win_to, $format);
}
return strftime($format, $value);
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_default_compile(DwooCompiler $compiler, $value, $default='')
{
return '(($tmp = '.$value.')===null||$tmp===\'\' ? '.$default.' : $tmp)';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooPlugin_dump extends DwooPlugin
{
public function process($var = '$')
{
if ($var === '$') {
$var = $this->dwoo->getData();
$out = '<div style="background:#aaa; padding:5px; margin:5px;">data';
} else {
$out = '<div style="background:#aaa; padding:5px; margin:5px;">dump';
}
if(!is_array($var)) {
return $this->exportVar('', $var);
}
$scope = $this->dwoo->getScope();
if ($var === $scope) {
$out .= ' (current scope): <div style="background:#ccc;">';
} else {
$out .= ':<div style="padding-left:20px;">';
}
$out .= $this->export($var, $scope);
return $out .'</div></div>';
}
protected function export($var, $scope)
{
$out = '';
foreach ($var as $i=>$v) {
if (is_array($v)) {
$out .= $i;
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>';
}
} else {
$out .= $this->exportVar($i.' = ', $v);
}
}
return $out;
}
protected function exportVar($i, $v)
{
if (is_string($v) || is_bool($v) || is_numeric($v)) {
return $i.var_export($v, true).'<br />';
} elseif (is_null($v)) {
return $i.'null<br />';
} elseif (is_object($v)) {
return $i.'object('.get_class($v).')<br />';
} elseif (is_resource($v)) {
return $i.'resource('.get_resource_type($v).')<br />';
} else {
return $i.var_export($v, true).'<br />';
}
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_escape(Dwoo $dwoo, $value='', $format='html', $charset=null)
{
if($charset === null)
$charset = $dwoo->getCharset();
switch($format)
{
case 'html':
return htmlspecialchars((string) $value, ENT_QUOTES, $charset);
case 'htmlall':
return htmlentities((string) $value, ENT_QUOTES, $charset);
case 'url':
return rawurlencode((string) $value);
case 'urlpathinfo':
return str_replace('%2F', '/', rawurlencode((string) $value));
case 'quotes':
return preg_replace("#(?<!\\\\)'#", "\\'", (string) $value);
case 'hex':
$out = '';
$cnt = strlen((string) $value);
for ($i=0; $i < $cnt; $i++) {
$out .= '%' . bin2hex((string) $value[$i]);
}
return $out;
case 'hexentity':
$out = '';
$cnt = strlen((string) $value);
for($i=0; $i < $cnt; $i++)
$out .= '&#x' . bin2hex((string) $value[$i]) . ';';
return $out;
case 'javascript':
return strtr((string) $value, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/'));
case 'mail':
return str_replace(array('@', '.'), array('&nbsp;(AT)&nbsp;', '&nbsp;(DOT)&nbsp;'), (string) $value);
default:
throw new Exception('Escape\'s format argument must be one of : html, htmlall, url, urlpathinfo, hex, hexentity, javascript or mail, "'.$format.'" given.');
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_eval(Dwoo $dwoo, $var, $assign = null)
{
// TOCOM eval is bad, warn people that they should not use it as a full template for DB-templates, they better extend DwooITemplate for that
if($var == '')
return;
$tpl = new DwooTemplateString($var);
$out = $dwoo->get($var, $dwoo->readVar('_parent'));
if($assign !== null)
$dwoo->assignInScope($out, $assign);
else
return $out;
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_fetch(Dwoo $dwoo, $file, $assign = null)
{
if($file === '')
return;
// TODO check for security here on http/ftp + secure dirs
$file = str_replace(array("\t", "\n", "\r"), array('\\t', '\\n', '\\r'), $file);
$out = file_get_contents($file);
if($assign !== null)
$dwoo->assignInScope($out, $assign);
else
return $out;
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_include(Dwoo $dwoo, $file, $cache_time = null, $cache_id = null, $compile_id = null, $assign = null, array $rest = array())
{
if($file === '')
return;
if(preg_match('#^([a-z]{2,}):(.*)#i', $file, $m))
{
$include = $dwoo->getTemplate($m[1], $m[2], $cache_time, $cache_id, $compile_id);
}
else
{
$include = $dwoo->getTemplate('file', $file, $cache_time, $cache_id, $compile_id);
}
if($include === null)
return;
elseif($include === false)
throw new Exception('Include not permitted.', E_USER_ERROR);
if(count($rest))
{
$vars = $rest;
}
else
{
$vars = $dwoo->readVar('_parent');
}
$out = $dwoo->get($include, $vars);
if($assign !== null)
$dwoo->assignInScope($out, $assign);
else
return $out;
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_indent_compile(DwooCompiler $compiler, $value, $by=4, $char=' ')
{
return "preg_replace('#^#m', '".str_repeat(substr($char, 1, -1), trim($by, '"\''))."', $value)";
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_isset_compile(DwooCompiler $compiler, $var)
{
return '('.$var.' !== null)';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_lower_compile(DwooCompiler $compiler, $value)
{
return 'mb_strtolower((string) '.$value.', $this->charset)';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_mailto(Dwoo $dwoo, $address, $text=null, $subject=null, $encode=null, $cc=null, $bcc=null, $newsgroups=null, $followupto=null, $extra=null)
{
if(empty($address))
return '';
if(empty($text))
$text = $address;
// build address string
$address .= '?';
if(!empty($subject))
$address .= 'subject='.rawurlencode($subject).'&';
if(!empty($cc))
$address .= 'cc='.rawurlencode($cc).'&';
if(!empty($bcc))
$address .= 'bcc='.rawurlencode($bcc).'&';
if(!empty($newsgroup))
$address .= 'newsgroups='.rawurlencode($newsgroups).'&';
if(!empty($followupto))
$address .= 'followupto='.rawurlencode($followupto).'&';
$address = rtrim($address, '?&');
// output
switch($encode)
{
case 'none':
case null:
return '<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>';
case 'js':
case 'javascript':
$str = 'document.write(\'<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>\');';
$len = strlen($str);
$out = '';
for ($i=0; $i<$len; $i++)
$out .= '%'.bin2hex($str[$i]);
return '<script type="text/javascript">eval(unescape(\''.$out.'\'));</script>';
break;
case 'javascript_charcode':
case 'js_charcode':
case 'jscharcode':
case 'jschar':
$str = '<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>';
$len = strlen($str);
$out = '<script type="text/javascript">'."\n<!--\ndocument.write(String.fromCharCode(";
for ($i=0; $i<$len; $i++)
$out .= ord($str[$i]).',';
return rtrim($out, ',') . "));\n-->\n</script>\n";
break;
case 'hex':
if(strpos($address, '?') !== false)
throw new Exception('Hex encoding is not possible with extra attributes.', E_USER_NOTICE);
$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]))
$out .= '%'.bin2hex($address[$i]);
else
$out .= $address[$i];
}
$out .= '" '.$extra.'>';
$len = strlen($text);
for ($i=0; $i<$len; $i++)
$out .= '&#x'.bin2hex($text[$i]);
return $out.'</a>';
default:
$dwoo->throwError('Mailto: <em>encode</em> argument is invalid, it must be one of : <em>none (= no value), js, js_charcode or hex</em>');
}
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_math_compile(DwooCompiler $compiler, $equation, $format='', $assign='', array $rest=array())
{
// TODO add assign support
/**
* Holds the allowed function, characters, operators and constants
*/
$allowed = array
(
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'+', '-', '/', '*', '.', ' ', '<<', '>>', '%', '&', '^', '|', '~',
'abs(', 'ceil(', 'floor(', 'exp(', 'log10(',
'cos(', 'sin(', 'sqrt(', 'tan(',
'M_PI', 'INF', 'M_E',
);
/**
* Holds the functions that can accept multiple arguments
*/
$funcs = array
(
'round(', 'log(', 'pow(',
'max(', 'min(', 'rand(',
);
$equation = $equationSrc = str_ireplace(array('pi', 'M_PI()', 'inf', ' e '), array('M_PI', 'M_PI', 'INF', ' M_E '), $equation);
$delim = $equation[0];
$open = $delim.'.';
$close = '.'.$delim;
$equation = substr($equation, 1, -1);
$out = '';
$ptr = 1;
$allowcomma = 0;
while(strlen($equation) > 0)
{
$substr = substr($equation, 0, $ptr);
// allowed string
if (array_search($substr, $allowed) !== false) {
$out.=$substr;
$equation = substr($equation, $ptr);
$ptr = 0;
}
// allowed func
elseif (array_search($substr, $funcs) !== false) {
$out.=$substr;
$equation = substr($equation, $ptr);
$ptr = 0;
$allowcomma++;
if($allowcomma === 1) {
$allowed[] = ',';
}
}
// variable
elseif(isset($rest[$substr]))
{
$out.=$rest[$substr];
$equation = substr($equation, $ptr);
$ptr = 0;
}
// pre-replaced variable
elseif($substr === $open)
{
preg_match('#.*\((?:[^()]*?|(?R))\)'.str_replace('.', '\\.', $close).'#', substr($equation, 2), $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)
$allowcomma++;
$out.=$substr;
$equation = substr($equation, $ptr);
$ptr = 0;
}
// closing parenthesis
elseif ($substr===')') {
if($allowcomma>0) {
$allowcomma--;
if($allowcomma===0) {
array_pop($allowed);
}
}
$out.=$substr;
$equation = substr($equation, $ptr);
$ptr = 0;
}
// parse error if we've consumed the entire equation without finding anything valid
elseif ($ptr >= strlen($equation)) {
throw new Exception('Syntax error or variable undefined in equation '.$equationSrc.' at '.$substr, E_USER_NOTICE);
return;
}
else
{
$ptr++;
}
}
if($format != '\'\'')
return '(sprintf('.$format.', '.$out.'))';
return '('.$out.')';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_nl2br_compile(DwooCompiler $compiler, $value)
{
return 'nl2br((string) '.$value.')';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_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)
$search = substr($search,0,$pos);
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]);
}
return preg_replace($search, $replace, $value);
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_replace_compile(DwooCompiler $compiler, $value, $search, $replace)
{
return 'str_replace('.$search.', '.$replace.', '.$value.')';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_reverse(Dwoo $dwoo, $value)
{
if(is_array($value))
return array_reverse($value, true);
else
return implode('',array_reverse(str_split((string) $value,1)));
}
?>
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_spacify_compile(DwooCompiler $compiler, $value, $space_char=' ')
{
return 'implode('.$space_char.', str_split('.$value.', 1))';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_string_format_compile(DwooCompiler $compiler, $value, $format)
{
return 'sprintf('.$format.','.$value.')';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_strip_compile(DwooCompiler $compiler, $value, $with=' ')
{
return "preg_replace('#\s+#'.(strcasecmp(\$this->charset, 'utf-8')===0?'u':''), $with, $value)";
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_strip_tags_compile(DwooCompiler $compiler, $value, $addspace=true)
{
if($addspace==='true')
return "preg_replace('#<[^>]*>#', ' ', $value)";
else
return "strip_tags($value)";
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_truncate(Dwoo $dwoo, $value, $length=80, $etc='...', $break=false, $middle=false)
{
if($length == 0)
return '';
$value = (string) $value;
$etc = (string) $etc;
$length = (int) $length;
if(strlen($value) < $length)
return $value;
$length = max($length - strlen($etc), 0);
if($break === false && $middle === false)
$value = preg_replace('#\s*(\S*)?$#', '', substr($value, 0, $length+1));
if($middle === false)
return substr($value, 0, $length) . $etc;
return substr($value, 0, ceil($length/2)) . $etc . substr($value, -floor($length/2));
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_upper_compile(DwooCompiler $compiler, $value)
{
return 'mb_strtoupper((string) '.$value.', $this->charset)';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_wordwrap_compile(DwooCompiler $compiler, $value, $length=80, $break="\n", $cut=false)
{
return 'wordwrap('.$value.','.$length.','.$break.','.$cut.')';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
function DwooPlugin_array_compile(DwooCompiler $compiler, array $rest=array())
{
$out = array();
foreach($rest as $k=>$v)
if(is_numeric($k))
$out[] = $k.'=>'.$v;
else
$out[] = '"'.$k.'"=>'.$v;
return 'array('.implode(', ', $out).')';
}
?>
\ No newline at end of file
<?php
/**
* TOCOM
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* This file is released under the LGPL
* "GNU Lesser General Public License"
* More information can be found here:
* {@link http://www.gnu.org/copyleft/lesser.html}
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 0.3.3
* @date 2008-03-19
* @package Dwoo
*/
class DwooProcessor_smarty_compat extends DwooProcessor
{
public function process($input)
{
list($l, $r) = $this->compiler->getDelimiters();
$rl = preg_quote($l);
$rr = preg_quote($r);
$sectionParam = '(?:(name|loop|start|step|max|show)\s*=\s*(\S+))?\s*';
$input = preg_replace_callback('{'.$rl.'section '.str_repeat($sectionParam, 6).$rr.'(.+?)(?:'.$rl.'sectionelse'.$rr.'(.+?))?'.$rl.'/section'.$rr.'}is', array($this, 'convertSection'), $input);
$input = str_replace('$smarty.section.', '$smarty.for.', $input);
$smarty = array
(
$l.'ldelim'.$r,
$l.'rdelim'.$r,
$l.'$smarty.ldelim'.$r,
$l.'$smarty.rdelim'.$r,
'$smarty.',
'{php}',
'{/php}',
);
$dwoo = array
(
'\\'.$l,
$r,
'\\'.$l,
$r,
'$dwoo.',
'<?php ',
' ?>',
);
return str_replace($smarty, $dwoo, $input);
}
protected function convertSection(array $matches)
{
$params = array();
$index = 1;
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]))
$params['altcontent'] = $matches[14];
if(empty($params['name']))
$this->compiler->triggerError('Missing parameter <em>name</em> for section tag');
$name = $params['name'];
if(isset($params['loop']))
$loops = $params['loop'];
if(isset($params['max']))
$max = $params['max'];
if(isset($params['start']))
$start = $params['start'];
if(isset($params['step']))
$step = $params['step'];
if (!isset($loops))
$loops = null;
if (!isset($max) || $max < 0)
{
if(is_numeric($loops))
$max = $loops;
else
$max = 'null';
}
if (!isset($step))
$step = 1;
if (!isset($start))
$start = $loops - 1;
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']))
$output = $l.'for '.$name.' '.$start.' '.($loops-$step).' '.$step.$r;
else
$output = $l.'for '.$name.' '.$start.' '.($start+floor($step*$max+($step>0?-1:1))).' '.$step.$r;
}
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']))
$output .= $l.'forelse'.$r.$params['altcontent'];
$output .= $l.'/for'.$r;
return $output;
}
}
?>
\ No newline at end of file
<?php
require_once dirname(dirname(__FILE__)).'/DwooCompiler.php';
class CompilerTests extends PHPUnit_Framework_TestCase
{
protected $compiler;
protected $dwoo;
public function __construct()
{
// extend this class and override this in your constructor to test a modded compiler
$this->compiler = new DwooCompiler();
$this->dwoo = new Dwoo();
}
public function testVarReplacement()
{
$tpl = new DwooTemplateString('{$foo}');
$tpl->forceCompilation();
$this->assertEquals('bar', $this->dwoo->get($tpl, array('foo'=>'bar'), $this->compiler));
}
public function testModifier()
{
$tpl = new DwooTemplateString('{$foo|upper}');
$tpl->forceCompilation();
$this->assertEquals('BAR', $this->dwoo->get($tpl, array('foo'=>'bar'), $this->compiler));
}
public function testModifierArgs()
{
$tpl = new DwooTemplateString('{$foo|spacify:"-"|upper}');
$tpl->forceCompilation();
$this->assertEquals('B-A-R', $this->dwoo->get($tpl, array('foo'=>'bar'), $this->compiler));
}
public function testDwooFunc()
{
$tpl = new DwooTemplateString('{upper($foo)}');
$tpl->forceCompilation();
$this->assertEquals('BAR', $this->dwoo->get($tpl, array('foo'=>'bar'), $this->compiler));
}
public function testDwooLoose()
{
$tpl = new DwooTemplateString('{upper $foo}');
$tpl->forceCompilation();
$this->assertEquals('BAR', $this->dwoo->get($tpl, array('foo'=>'bar'), $this->compiler));
}
public function testNamedParameter()
{
$tpl = new DwooTemplateString('{upper value=$foo}');
$tpl->forceCompilation();
$this->assertEquals('BAR', $this->dwoo->get($tpl, array('foo'=>'bar'), $this->compiler));
}
public function testNamedParameter2()
{
$tpl = new DwooTemplateString('{replace value=$foo search="BAR"|lower replace="BAR"}');
$tpl->forceCompilation();
$this->assertEquals('BAR', $this->dwoo->get($tpl, array('foo'=>'bar'), $this->compiler));
}
public function testNamedParameter3()
{
$tpl = new DwooTemplateString('{assign value=reverse(array(foo=3,boo=5, 3=4)) var=arr}{foreach $arr k v}{$k}{$v}{/foreach}');
$tpl->forceCompilation();
$this->assertEquals('34boo5foo3', $this->dwoo->get($tpl, array(), $this->compiler));
}
public function testRecursiveCall()
{
$tpl = new DwooTemplateString('{lower(reverse(upper($foo)))}');
$tpl->forceCompilation();
$this->assertEquals('rab', $this->dwoo->get($tpl, array('foo'=>'bar'), $this->compiler));
}
public function testComplexRecursiveCall()
{
$tpl = new DwooTemplateString('{lower reverse($foo|reverse|upper)}');
$tpl->forceCompilation();
$this->assertEquals('bar', $this->dwoo->get($tpl, array('foo'=>'BaR'), $this->compiler));
}
public function testComplexRecursiveCall2()
{
$tpl = new DwooTemplateString('{str_repeat "AB`$foo|reverse|spacify:o`CD" 3}');
$tpl->forceCompilation();
$this->assertEquals('AB3o2o1CDAB3o2o1CDAB3o2o1CD', $this->dwoo->get($tpl, array('foo'=>'123'), $this->compiler));
}
public function testStrip()
{
$tpl = new DwooTemplateString("{strip}a\nb\nc{/strip}a\nb\nc");
$tpl->forceCompilation();
$this->assertEquals("abca\nb\nc", $this->dwoo->get($tpl, array(), $this->compiler));
}
public function testWhitespace()
{
$tpl = new DwooTemplateString("{\$foo}{\$foo}\n{\$foo}\n\n{\$foo}\n\n\n{\$foo}");
$tpl->forceCompilation();
$this->assertEquals("aa\na\n\na\n\n\na", $this->dwoo->get($tpl, array('foo'=>'a'), $this->compiler));
}
public function testLiteral()
{
$tpl = new DwooTemplateString('{literal}{$foo}{hurray}{/literal}');
$tpl->forceCompilation();
$this->assertEquals('{$foo}{hurray}', $this->dwoo->get($tpl, array(), $this->compiler));
}
public function testEscaping()
{
$tpl = new DwooTemplateString('\{foo\{bar\\\\{$var}}{"tes\}t"}{"foo\"lol\"bar"}');
$tpl->forceCompilation();
$this->assertEquals('{foo{bar\\1}tes}tfoo"lol"bar', $this->dwoo->get($tpl, array('var'=>1), $this->compiler));
}
public function testFunctions()
{
$tpl = new DwooTemplateString('{dump()}{dump( )}{dump}');
$tpl->forceCompilation();
$this->assertEquals('<div style="background:#aaa; padding:5px; margin:5px;">data (current scope): <div style="background:#ccc;"></div></div><div style="background:#aaa; padding:5px; margin:5px;">data (current scope): <div style="background:#ccc;"></div></div><div style="background:#aaa; padding:5px; margin:5px;">data (current scope): <div style="background:#ccc;"></div></div>', $this->dwoo->get($tpl, array(), $this->compiler));
}
public function testExpressions()
{
$tpl = new DwooTemplateString('{$foo+5} {$foo+$foo} {$foo+3*$foo} {$foo*$foo+4*$foo} {$foo*2/2|number_format} {$foo*2/3|number_format:1} {number_format $foo*2/3 1}');
$tpl->forceCompilation();
$this->assertEquals("10 10 40 145 5 3.3 3.3", $this->dwoo->get($tpl, array('foo'=>5), $this->compiler));
}
public function testNonExpressions()
{
$tpl = new DwooTemplateString('{"$foo/$foo"}');
$tpl->forceCompilation();
$this->assertEquals("5/5", $this->dwoo->get($tpl, array('foo'=>5), $this->compiler));
}
public function testConstants()
{
if(!defined('TEST'))
define('TEST', 'Test');
$tpl = new DwooTemplateString('{$dwoo.const.TEST} {$dwoo.const.Dwoo::FUNC_PLUGIN*$dwoo.const.Dwoo::BLOCK_PLUGIN}');
$tpl->forceCompilation();
$this->assertEquals(TEST.' '.(Dwoo::FUNC_PLUGIN*Dwoo::BLOCK_PLUGIN), $this->dwoo->get($tpl, array(), $this->compiler));
}
public function testAltDelimiters()
{
$tpl = new DwooTemplateString('{"test"} <%"test"%> <%"foo{lol}\%>"%>');
$tpl->forceCompilation();
$this->compiler->setDelimiters('<%', '%>');
$this->assertEquals('{"test"} test foo{lol}%>', $this->dwoo->get($tpl, array(), $this->compiler));
$tpl = new DwooTemplateString('d"O"b');
$tpl->forceCompilation();
$this->compiler->setDelimiters('d', 'b');
$this->assertEquals('O', $this->dwoo->get($tpl, array(), $this->compiler));
$tpl = new DwooTemplateString('<!-- "O" --> \<!-- ');
$tpl->forceCompilation();
$this->compiler->setDelimiters('<!-- ', ' -->');
$this->assertEquals('O <!-- ', $this->dwoo->get($tpl, array(), $this->compiler));
$this->compiler->setDelimiters('{', '}');
}
public function testNumberedIndexes()
{
$tpl = new DwooTemplateString('{$100}-{$150}-{$0}');
$tpl->forceCompilation();
$this->assertEquals('bar-foo-', $this->dwoo->get($tpl, array('100'=>'bar', 150=>'foo'), $this->compiler));
}
public function testParseBool()
{
$tpl = new DwooTemplateString('{if (true === yes && true === on) && (false===off && false===no)}okay{/if}');
$tpl->forceCompilation();
$this->assertEquals('okay', $this->dwoo->get($tpl, array(), $this->compiler));
}
}
?>
\ No newline at end of file
<?php
require_once dirname(dirname(__FILE__)).'/DwooCompiler.php';
class CoreTests extends PHPUnit_Framework_TestCase
{
protected $compiler;
protected $dwoo;
public function __construct()
{
$this->compiler = new DwooCompiler();
$this->dwoo = new Dwoo();
}
public function testCoverConstructorsEtc()
{
// extend this class and override this in your constructor to test a modded compiler
$this->compiler = new DwooCompiler();
$this->dwoo = new Dwoo();
DwooLoader::rebuildClassPathCache(DWOO_PATH.'plugins', DWOO_PATH.'cache');
}
public function testReadVar()
{
$tpl = new DwooTemplateString('{$foo.$bar[$baz->qux][moo]}{with $foo}{$a.b.moo}{/with}{$baz->qux}');
$tpl->forceCompilation();
$Obj = new stdClass;
$Obj->qux = 'b';
$data = array(
'foo'=>array('a' => array('b'=>array('moo'=>'Yay!'))),
'bar'=>'a',
'baz'=>$Obj,
);
$this->assertEquals("Yay!Yay!b", $this->dwoo->get($tpl, $data, $this->compiler));
$this->assertEquals('Yay!aaab', $this->dwoo->readVar('foo.a.b.moo') . $this->dwoo->readVar('bar') . $this->dwoo->readVar('_root.bar') . $this->dwoo->readVar('_parent.bar') . $this->dwoo->readVar('baz->qux'));
$this->assertEquals($data, $this->dwoo->readVar('_root'));
$this->assertEquals($data, $this->dwoo->readVar('_parent'));
}
public function testReadParentVar()
{
$tpl = new DwooTemplateString('{assign "Yay!" a.b->qux}{$a.b->qux}');
$tpl->forceCompilation();
$this->assertEquals("Yay!", $this->dwoo->get($tpl, array('bar'=>'a'), $this->compiler));
$this->assertEquals('a', $this->dwoo->readParentVar(2, 'bar'));
}
public function testAssignVarInScope()
{
$tpl = new DwooTemplateString('{assign "Yay!" a.b->qux}{$a.b->qux}');
$tpl->forceCompilation();
$Obj = new stdClass;
$Obj->qux = 'Noes:(';
$this->assertEquals("Yay!", $this->dwoo->get($tpl, array('a'=>array('b'=>$Obj)), $this->compiler));
$tpl = new DwooTemplateString('{assign "Yay!" a->b.qux}{$a->b.qux}');
$tpl->forceCompilation();
$Obj = new stdClass;
$Obj->b = array('qux'=>'Noes:(');
$this->assertEquals("Yay!", $this->dwoo->get($tpl, array('a'=>$Obj), $this->compiler));
}
public function testPhpCall()
{
$tpl = new DwooTemplateString('{"foo"|strtoupper}');
$tpl->forceCompilation();
$this->compiler->addPhpFunction('strtoupper');
$this->assertEquals("FOO", $this->dwoo->get($tpl, array(), $this->compiler));
$tpl = new DwooTemplateString('{foreach $foo|count p}{$p}{/foreach}');
$tpl->forceCompilation();
$this->assertEquals("21", $this->dwoo->get($tpl, array('foo'=>array('a'=>array(1,2), 'b'=>array(2))), $this->compiler));
}
public function testClassCall()
{
$tpl = new DwooTemplateString('{dump $foo.b.0}');
$tpl->forceCompilation();
$this->assertEquals("2<br />", $this->dwoo->get($tpl, array('foo'=>array('a'=>array(1,2), 'b'=>array(2))), $this->compiler));
}
public function testSuperGlobals()
{
$_GET[5] = 'Yay';
$tpl = new DwooTemplateString('{$dwoo.get.5} {$dwoo.get.$foo}');
$tpl->forceCompilation();
$this->assertEquals("Yay Yay", $this->dwoo->get($tpl, array('foo'=>5), $this->compiler));
}
public function testGettersSetters()
{
$this->dwoo->setCacheTime(5);
$this->assertEquals(5, $this->dwoo->getCacheTime());
$this->dwoo->setCacheTime(0);
$this->dwoo->setCharset('foo');
$this->assertEquals('foo', $this->dwoo->getCharset());
$this->dwoo->setCharset('utf-8');
$this->dwoo->setDefaultCompilerFactory('file', 'Moo');
$this->assertEquals('Moo', $this->dwoo->getDefaultCompilerFactory('file'));
$this->dwoo->setDefaultCompilerFactory('file', array('DwooCompiler', 'compilerFactory'));
}
public function testAddAndRemoveResource()
{
$this->dwoo->addResource('news', 'DwooTemplateFile', array('DwooCompiler', 'compilerFactory'));
$tpl = new DwooTemplateString('{include file="news:'.DWOO_PATH.'tests/resources/test.html" foo=3 bar=4}');
$tpl->forceCompilation();
$this->assertEquals("34", $this->dwoo->get($tpl, array()));
$this->dwoo->removeResource('news');
$this->dwoo->addResource('file', 'DwooTemplateString', 'Fake');
$this->dwoo->removeResource('file');
$tpl = new DwooTemplateString('{include file="'.DWOO_PATH.'tests/resources/test.html" foo=3 bar=4}');
$tpl->forceCompilation();
$this->assertEquals("34", $this->dwoo->get($tpl, array()));
}
public function testTemplateFile()
{
$tpl = new DwooTemplateFile(DWOO_PATH.'tests/resources/test.html');
$tpl->forceCompilation();
$this->assertEquals("12", $this->dwoo->get($tpl, array('foo'=>1, 'bar'=>2)));
}
public function testTemplateString()
{
$tpl = new DwooTemplateString('foo', 13);
$this->assertEquals("13", $tpl->getCacheTime());
$this->assertEquals(null, $tpl->getCompiler());
$this->assertEquals(false, DwooTemplateString::templateFactory($this->dwoo, 'foo', 5));
}
}
?>
\ No newline at end of file
<?php
require_once dirname(dirname(__FILE__)).'/DwooCompiler.php';
class DataTests extends PHPUnit_Framework_TestCase
{
protected $compiler;
protected $dwoo;
public function __construct()
{
// extend this class and override this in your constructor to test a modded compiler
$this->compiler = new DwooCompiler();
$this->dwoo = new Dwoo();
}
public function testDwooData()
{
// test simple assign
$tpl = new DwooTemplateString('{$var}{$var2}{$var3}{$var4}');
$tpl->forceCompilation();
$data = new DwooData();
$data->setData(array('foo'));
$this->assertEquals(array('foo'), $data->getData());
$data->mergeData(array('baz'),array('bar', 'boo'=>'moo'));
$this->assertEquals(array('foo', 'baz', 'bar', 'boo'=>'moo'), $data->getData());
$data->clear();
$this->assertEquals(array(), $data->getData());
$data->assign('var', '1');
$data->assign(array('var2'=>'1', 'var3'=>1));
$ref = 0;
$data->assignByRef('var4', $ref);
$ref = 1;
$this->assertEquals('1111', $this->dwoo->get($tpl, $data, $this->compiler));
}
}
?>
\ No newline at end of file
<?php
require_once dirname(dirname(__FILE__)).'/Dwoo.php';
class DwooTests {
public static function suite() {
PHPUnit_Util_Filter::addDirectoryToWhitelist(DWOO_PATH.'plugins/builtin');
PHPUnit_Util_Filter::addFileToWhitelist(DWOO_PATH.'Dwoo.php');
PHPUnit_Util_Filter::addFileToWhitelist(DWOO_PATH.'DwooCompiler.php');
PHPUnit_Util_Filter::addFileToWhitelist(DWOO_PATH.'DwooData.php');
PHPUnit_Util_Filter::addFileToWhitelist(DWOO_PATH.'DwooInterfaces.php');
PHPUnit_Util_Filter::addFileToWhitelist(DWOO_PATH.'DwooPlugin.php');
PHPUnit_Util_Filter::addFileToWhitelist(DWOO_PATH.'DwooSmartyAdapter.php');
PHPUnit_Util_Filter::addFileToWhitelist(DWOO_PATH.'DwooTemplateFile.php');
PHPUnit_Util_Filter::addFileToWhitelist(DWOO_PATH.'DwooTemplateString.php');
$suite = new PHPUnit_Framework_TestSuite('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')
{
require_once $file->getPathname();
$suite->addTestSuite(basename($file, '.php'));
}
}
return $suite;
}
}
?>
\ No newline at end of file
<?php
require_once dirname(dirname(__FILE__)).'/DwooCompiler.php';
class FiltersTests extends PHPUnit_Framework_TestCase
{
protected $compiler;
protected $dwoo;
public function __construct()
{
// extend this class and override this in your constructor to test a modded compiler
$this->compiler = new DwooCompiler();
$this->dwoo = new Dwoo();
}
public function testHtmlFormat()
{
$tpl = new DwooTemplateString("<html><body><div><p>a<em>b</em>c<hr /></p><textarea>a\n b</textarea></div></body><html>");
$tpl->forceCompilation();
$dwoo = new Dwoo();
$dwoo->addFilter('html_format', true);
$this->assertEquals(str_replace("\r", '', <<<SNIPPET
<html>
<body>
<div>
<p>
a<em>b</em>c
<hr />
</p><textarea>a
b</textarea>
</div>
</body>
<html>
SNIPPET
), $dwoo->get($tpl, array(), $this->compiler));
}
public function testSmartyCompat()
{
$tpl = new DwooTemplateString('{ldelim}{$smarty.version}{rdelim}');
$tpl->forceCompilation();
$this->assertEquals('{'.Dwoo::VERSION.'}', $this->dwoo->get($tpl, array(), $this->compiler));
}
}
?>
\ No newline at end of file
<?php
require_once dirname(dirname(__FILE__)).'/DwooCompiler.php';
class HelperTests extends PHPUnit_Framework_TestCase
{
protected $compiler;
protected $dwoo;
public function __construct()
{
// extend this class and override this in your constructor to test a modded compiler
$this->compiler = new DwooCompiler();
$this->dwoo = new Dwoo();
}
public function testArray()
{
$tpl = new DwooTemplateString('{if array(3,foo, "bar",$baz|upper) === $test}true{/if}');
$tpl->forceCompilation();
$this->assertEquals('true', $this->dwoo->get($tpl, array('test'=>array(3, "foo", "bar", "BAZ"), 'baz'=>'baz'), $this->compiler));
}
public function testAssociativeArray()
{
$tpl = new DwooTemplateString('{if array(hoy=3,5="foo",bar=moo) === $test}true{/if}');
$tpl->forceCompilation();
$this->assertEquals('true', $this->dwoo->get($tpl, array('test'=>array("hoy"=>3, 5=>"foo", "bar"=>"moo"), 'baz'=>'baz'), $this->compiler));
}
}
?>
\ No newline at end of file
To run those tests you have to get the latest version of PHPUnit : http://www.phpunit.de/
Then simply run it with those parameters : --verbose DwooTests /path/to/dwoo/tests/DwooTests.php
That will run the entire test suite, checking all plugins and most of the compiler.
\ No newline at end of file
<?php
require_once dirname(dirname(__FILE__)).'/DwooCompiler.php';
require DWOO_PATH.'DwooSmartyAdapter.php';
class SmartyTests extends PHPUnit_Framework_TestCase
{
protected $dwoo;
public function __construct()
{
// extend this class and override this in your constructor to test a modded compiler
$this->dwoo = new DwooSmartyAdapter();
$this->dwoo->template_dir = DWOO_PATH.'tests/resources/';
$this->dwoo->compile_dir = DWOO_PATH.'compiled/';
$this->dwoo->cache_dir = DWOO_PATH.'cache/';
$this->dwoo->config_dir = DWOO_PATH.'configs/';
}
public function testSmartyCompat()
{
$this->assertEquals('{'.Dwoo::VERSION.'}', $this->dwoo->fetch('smartytest.html'));
}
}
?>
\ No newline at end of file
{include file="test.tpl" foo=3 bar=4}
\ No newline at end of file
{ldelim}{$smarty.version}{rdelim}
\ No newline at end of file
{$foo}{$bar}
\ No newline at end of file
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