diff --git a/system/libs/dwoo/.htaccess b/system/libs/dwoo/.htaccess deleted file mode 100644 index 3418e55a..00000000 --- a/system/libs/dwoo/.htaccess +++ /dev/null @@ -1 +0,0 @@ -deny from all \ No newline at end of file diff --git a/system/libs/dwoo/CHANGELOG b/system/libs/dwoo/CHANGELOG deleted file mode 100644 index b7f2ff88..00000000 --- a/system/libs/dwoo/CHANGELOG +++ /dev/null @@ -1,508 +0,0 @@ -[2010-02-07] 1.1.1 -+ Added {optional} plugin that just prints an optional var without any - notice if it doesn't exist -+ Added Dwoo::setTemplate() for testing purposes mostly -* Fixed an {extends} parsing bug that prevented the use of single-quotes - around the parent template's filename -* Fixed a security issue, if you didn't use a custom compiler factory but - passed the compiler directly to the get method with autoEscape enabled, - the autoEscape was disabled in included templates - Thanks to Fabien - Potencier for notifying me. -* Fixed a bug in {safe} when using variable-variables it would sometimes - corrupt the var name resulting in blank output -* Fixed a bug when accessing array indices that contain a minus sign, it - is now possible to access those using {$var[index-foo]}, - {$var['index-foo']} or {$index="index-foo"} {$var[$index]} -* Fixed a bug in {tif} that didn't work when 0 was given as the true or - false value -* Fixed a bug when using the autoEscape feature with sub-templates (the - compiled sub-template couldn't access the dwoo charset property, - resulting in a fatal error) -* Fixed a property reading bug on objects that implemented __get but not - __isset, implementing __isset is however very much recommended -* Fixed a Dwoo_Data bug in the append method when the index didn't exist - yet it threw a notice -* Fixed a bug when accessing global vars from a sub-template -* Fixed a couple bugs in the {dynamic} plugin with regard to using plugins - within a dynamic block -* Fixed a compilation bug when using a PluginProxy with highly nested calls -* Fixed a {load_templates} bug, plugins used in external templates were not - loaded correctly, same for custom user plugins -* Cached templates now check the source template for modification before - outputting the cached version -* Removed a couple of @-operator calls to file_get_contents - -[2009-07-18] 1.1.0 -! BC Break: Dwoo::initGlobals() is only called once during the Dwoo object - construction. If you had overriden it and need to update global data - before each template is executed you should instead override - Dwoo::initRuntimeVars() and push stuff in the globals array there. Also - be aware that this means captured data, foreach values and so-on will - persist from a parent template to an included one (but the include's - changes will not be reflected on the parent), and from a template - to the next if you render several in series. -+ Added {template} plugin that allows you to define sub-templates and then - call them (works recursively too, good for menus and lists) -+ Added {load_templates} to load external sub-templates into your file -+ Allowed string concatenation assignments with {$foo.="bar"} -+ Allowed access of static properties as {Foo::$bar} -+ Plugins/Helpers that use a dynamic number of arguments through - func_get_args are now working since the compiler lets any arguments in - excess pass through -+ Adapters: CodeIgniter: the adapter by Stefan Verstege has been added to - core and he will be its maintainer from now on -+ Adapters: CakePHP: this adapter is now added to core and is designed to - work with CakePHP 1.2 -* Adapters: Zend: Denis Arh is now appointed maintainer of that part and - fixed a few things since 1.0.1 -* The include_path isn't altered anymore, hopefully saving some stat calls -* User classes extending Dwoo_Template_File are now supported better with - regard to includes - Thanks to the Kayako.com team for the patch -* Objects now act like arrays when you access non-existing properties on - them (i.e. it outputs a notice only if it's output straight, and none - when passed to a function) -* For can now iterate backwards if you input numbers, it won't work with - variables though -* Slight performance improvement with big inheritance trees -* No more double-slashes in template paths since this seemed to cause - slight performance issues -* Fixed a bug with parsing AND/OR keywords in conditionals when they were - followed by round brackets -* Fixed assignments not handling multi-line values correctly -* Fixed parameter parsing issue when a plugin name was all uppercased -* Fixed assignments failing with autoEscape enabled -* Fixed parsing of vars with string keys that was too greedy -* Fixed an optimization causing foreach/for/loop variables not being - accessible when the foreach/.. name was set dynamically -* Fixed parsing of comments that were on top of the file when there are - spaces at the end of it -* Dwoo_Template::$chmod is now enforced for directories as well (#18) -* Many new unit tests to improve code coverage and a bunch of bug fixes - that resulted, but I didn't really keep track of them - -[2008-12-24] 1.0.1 -* Direct assignments like {$foo = 5} now allow spaces around the operator -* Fixed a {foreach} bug with the implode argument -* Fixed modulo operator in if statements -* Fixed date_format handling of negative and small unix timestamps -* Fixed a weird reference bug with ZF and includes.. whatever but thanks - to Denis Arh for the patch - -[2008-10-23] 1.0.0 -! BC Break: Small one that probably won't affect anyone, but it makes the - PluginProxy feature much stronger. Basically if you used a custom one you - will get a fatal error and need to update it to conform to the new - IPluginProxy interface, that's it -+ Compiler: the modifier syntax (|foo) can now be applied on functions and on - complex variables i.e. {$obj->getStuff()|upper} or {lower('foo')|upper} -+ SmartyCompat: Added a {section} plugin but I strongly discourage using it, - it was really made to support legacy templates, since {for} doesn't have to - handle {section}-BC anymore, it has been cleaned up a lot and the last - $skip parameter has been dropped -* The core Dwoo class doesn't need writable compile/cache dirs in the - constructor anymore so you can provide custom ones later through - ->setCompile(/Cache)Dir - thanks to Denis Arh for the patch -* Adapters: Zend: major overhaul thanks to Denis Arh, templates files should - probably be moved in the scripts subfolder after this update though, and - the settings array has changed a bit, you will get warnings if you don't - update the code anyway -* Plugins: improved the dump plugin, it now displays object's properties - and optionally public methods (if the new show_methods arg is set to true) - - thanks to Stephan Wentz for the patch -* Adapters: Zend: Added parameters to provide a custom engine (extends Dwoo) - or a custom data class (extends Dwoo_Data) - thanks to Maxime Merian for - the patch -* Compiler: added Dwoo_Compiler->setNestedCommentsHandling(true) to enable - parsing of nested comments (i.e. {* {* *} *} becomes a valid comment, useful - to comment out big chunks of code containing comments) -* Lines containing only comments and whitespace are now entirely removed -* Removed comments do not mess up the line count anymore (for error messages) -* Fixed parsing bug in {func()->propertyOfReturnedObject} -* Fixed file template class reading from the string compiler factory - thanks - to MrOxiMoron for the patch -* Fixed handling of variable variables that contained non standard characters -* Fixed a 1.0.0beta regression that messed with custom plugin directories - on Windows -* SmartyCompat: Fixed a few bugs in the adapter and processor - thanks to - Stefan Moonen for the patches - -[2008-09-08] 1.0.0beta -! Important note : Dwoo.php should not be included directly anymore, please - read the UPGRADE_NOTES file for more infos on the matter, if you don't - your Dwoo install will most likely break after the update anyway -! BC Break: {include} and {extends} now support the include path properly, - which means that if you include "foo/bar.html" from _any_ template and you - have an include path set on your template object, it will look in all those - paths for foo/bar.html. If you use relative paths, for example - if you include "../foo/bar.html" AND have an include path set, you will now - have a problem, because you can't mix both approaches, otherwise you should - be fine, so to fix this you should convert your relative includes/extends -+ Adapters: Added the Agavi interface for Dwoo - (see /Dwoo/Adapters/Agavi/README) -+ API: Added Dwoo_Compilation_Exception methods getCompiler() and - getTemplate() so you can catch the exception and use those to build a nicer - error view with all the details you want -+ Plugins: Added a mode parameter to {strip} to allow stripping of javascript - code blocks that use "// comments", because without this special mode the - comments result in syntax errors -* The Compiler now ensures that a template starting with get() is now stricter as to what it accepts as a "template", only - Dwoo_ITemplate objects or valid filenames are accepted -* Foreach and other similar plugins that support "else" now only count() - their input before processing when an else block follows -* Various optimizations -* Fixed compiler bug that created a parse error when you had comments in an - extended template -* Fixed extends bug when extending files in other directories using relative - paths -* Fixed parsing bug with "|modifier:param|modifier2} with:colon after it" -* Bug fixed with smarty functions called with no parameters (in compat mode) -* Fixed Dwoo::isArray() check, objects implementing ArrayAccess are now - valid (thanks to Daniel Cousineau for the patch) -* Fixed compiler warning when doing {func()->method()} or {func()->property} -* Fixed compiled/cached files being written in the wrong place when the path - to the template contains "../"s -* Fixed {if} failing with conditions using upper case operators (i.e. AND) - -[2008-08-03] 0.9.3 -+ Adapters: Added the ZendFramework interface for Dwoo - (see /Dwoo/Adapters/ZendFramework/README) -+ Plugins: Added the {a} block plugin to generate tags -+ Syntax: Added the ";" token that allows to group multiple instructions in one - single template tag, example: {if $foo; "> $foo";$bar;/} is equal to: - {if $foo}> {$foo}{$bar}{/} - This also allow block operations such as: - {a http://url.com; "Text" /} which equals to {a http://url.com}Text{/} -+ Syntax: Block plugins that you want to call without content can be - self-closed just like XML tags (e.g. {a "http://url.com" /} ). Be careful not - to close a non-block plugin like that however, since it will close it's - parent block -+ Syntax: Static methods can be called using {Class::method()} -+ Syntax: It is now possible to use a plugin's result as an object and call - a method or read a property from it, i.e. {fetchObject()->doStuff()} -+ API: Added Dwoo_Plugin::paramsToAttributes() utility function to help - with the creation of compilable xml/html-related plugins -+ API: Added Dwoo->setPluginProxy() and Dwoo_IPluginProxy that allow you to - hook into the compiler's plugin subsystem to provide your own plugin calls. - Thanks to Denis Arh for the patch - => http://forum.dwoo.org/viewtopic.php?id=70 -+ API: Dwoo->addPlugin() has a third parameter to mark a plugin as compilable -+ Compiler supports method calls into a method call's parameters -* Dwoo_Compiler::implode_r is now public/static so it can be used in other - places such as plugin proxies -* Syntax: Math expressions in strings are now only allowed when the entire - expression is delimited, e.g. {"/$foo/$bar"} evaluates as just that while - {"/`$foo/$bar`"} will result in "/".($foo/$bar), therefore processing the / - as a division, this is better since URLs using / are far more common than - math in strings - => http://forum.dwoo.org/viewtopic.php?id=50 -* Compiler now allows the use of the right delimiter inside strings (e.g. {"}"}) -* Fixed a bug preventing if blocks containing a {elseif} followed by {else} -* Fixed the Dwoo_ILoader interface and implemented it in Dwoo_Loader now - => http://forum.dwoo.org/viewtopic.php?id=70 -* Fixed a compileId auto-generation creating conflicts -* Include allows paths going in upper levels now such as : "../foo.html" -* Some compiler fixes regarding custom plugins - -[2008-06-28] 0.9.2 -! BC Break: Renamed the {strip} modifier/function to {whitespace}, this does - not affect the strip block, that has been moved off the compiler into a - plugin. Which is why the name conflict had to be resolved. Please report - any issue you might encounter when using the strip block -! BC Break: Changed the function signature of Dwoo_Block_Plugin::postProcessing - it only affects you if you had any custom block plugins, see UPGRADE_NOTES - for more details -! BC Break: Dwoo_ITemplate::cache() must now return the cached file name or - false if caching failed, only affects you if you had a custom template class - and implemented cache() yourself -! BC Break: Dwoo_Loader is not static anymore so anything you did on it directly - will break. Use $dwoo->getLoader()->addDirectory() instead of - Dwoo_Loader::addDirectory() for example -! BC Break: DWOO_COMPILE_DIRECTORY and DWOO_CACHE_DIRECTORY are gone, set those - paths in Dwoo's constructor (i.e. new Dwoo('compiledir', 'cachedir')) if you - need to override the default ones -+ Plugins: Added {dynamic} that allows cached templates to have dynamic - (non-cached) parts, when rendering a cached page, the dynamic parts can still - use the variables you provides -+ Plugins: Added {tif} that acts as a ternary if / allows you to use a ternary - operator inside it -+ API: Added a Dwoo_ILoader interface if you want to provide a custom plugin - loading solution (use $dwoo->setLoader($myLoader)) -+ Added line numbers in compilation errors and improved several error messages -+ Added magic object-access methods to Dwoo_Data, so you can assign values by - doing $data->var = $val; instead of $data->assign('var', $val); -+ Added get()/unassign()/isAssigned() methods to read, remove and check for the - presence of a var inside a Dwoo_Data object -* Plugins: added a fifth 'string $implode' parameter to {foreach}, it prints - whatever you provide it between each item of the foreach, just like implode() -* Plugins: added a fourth 'bool $case_sensitive' parameter to {replace} -* Plugins: added a fourth 'bool $trim' parameter to {capture} that trims - the captured text -* Made the dependency on the hash extension optional -* Fixed compiler bug that prevented method calls combined with named parameters -* Fixed compiler bug that prevented the % shortcut for constants to work within - function calls (basically it only worked as {%CONST}) -* Fixed compiler bug that prevented empty() to be called -* Fixed several modifier parsing bugs - => http://forum.dwoo.org/viewtopic.php?id=27 -* Fixed empty string parsing in modifier applied to variables -* Fixed compiler handling of {template_tag} where there was - no ';' at the end of the php tag -* Allowed method calls to work with named parameters -* Removed checks for methods/properties being present on objects before calling - them since these can be handled by __get() and __call() - => http://forum.dwoo.org/viewtopic.php?id=22 -* Calling {func (params)} (with the space between function and params) is now - allowed - => http://forum.dwoo.org/viewtopic.php?id=21 -* The compiler now allows \r, \n and \t to be parameter splitters as well as - "," and " ". You can therefore split complex function calls on multiple lines -* Converted most of the code to follow PEAR Coding Standards, hopefully this - didn't break anything that the tests missed -* A few other minor or internal changes - -[2008-05-30] 0.9.1 -+ API: Added Dwoo_Compiler->setAutoEscape() and getAutoEscape() to modify the - automatic html entity escaping setting. This is disabled by default, and when - enabled can be overriden with the {safe $var} plugin or the - {auto_escape disable} block plugin. The block plugin can also be used to - enable this mode from within a template -+ Syntax: Mixing named and unnamed parameters is now allowed, as long as the - unnamed ones appear first -+ Syntax: Added {/} shortcut that closes the last opened block -* Optimized scope-handling functions, {loop} and {with} are now slightly faster -* Fixed a bug in {date_format} that prevented anything but unix timestamps to - work -* {literal} and {strip} now follow the LooseOpeningsHandling setting -* Fixed complex variables (i.e. {$_root[$c[$x.0]].0}) parsing bugs -* Fixed $dwoo->addResource() breaking if the resource class was not loaded yet, - autoload should now be called (thanks mike) -* Fixed a block stack bug that messed up {textformat} and possibly usermade - block plugins - -[2008-05-10] 0.9.0 -! BC Break: changed all class names to be PEAR compliant (aka use underscores - to separate words/paths), sorry about that but I better do it now than in - six months -! BC Break: $dwoo->output() and get() have been swapped internally, but it - doesn't change anything for you unless you called output(*, *, *, true) - directly to emulate get(). This was done to reduce some overhead -! BC Break: $dwoo->getTemplate() changed to $dwoo->templateFactory() and - $dwoo->getCurrentTemplate() changed to $dwoo->getTemplate() for consistency - among all classes and factory functions -+ Added a compiled version of Dwoo that loads faster (especially with opcode - caches such as APC), include Dwoo.compiled.php instead of Dwoo.php on - production but if you want to file a bug use Dwoo.php please as it allows - you to get the proper file/line number where an error occurs. Do not remove - all other files however since they are not all included in the compiled - package -+ Plugins: Added {extends} and {block} to handle template inheritance, read - more about it at http://wiki.dwoo.org/index.php/TemplateInheritance -+ Plugins: Added {loop} that combines {foreach} and {with}, see - http://wiki.dwoo.org/index.php/Block:loop for details -+ Plugins: Added {do} that executes whatever you feed it whitout echoing the - result, used internally for extends but you can use it if required -+ Plugins: Added {eol} that prints an end of line character (OS-specific) -+ Syntax: Added shortcut for {$dwoo.const.*} using '%', for example you can use - {%FOO} instead of {$dwoo.const.FOO} -+ Syntax: When using named parameters, typing a parameter name without any - value is the same as typing param=true, for example {foo name="test" bar} and - {foo name="test" bar=true} are equals, can be useful for very complex plugins - with huge amounts of parameters. -+ Syntax: Added support for {$foo+=5}, {$foo="a"}, {$foo++} and {$foo--} -+ Syntax: Added shortcut for $dwoo.*, you can now use {$.foreach.foo} instead - of {$dwoo.foreach.foo} for example, applies to all $dwoo.* vars -+ Syntax: Added $ as a shortcut for current scope, $_ for $_parent and $__ for - $_root -+ API: Added getSource(), getUid() and getResourceIdentifier() to Dwoo_ITemplate -+ API: Added setSecurityPolicy() too Dwoo_ICompiler and modified the arguments - of its compile() method -+ API: Added a bunch of utility functions to Dwoo_Compiler, allowing compiled - plugins to access more of the compiler internals -+ Both cache and compile IDs can now have slashes in them to create subfolders - in the cache/compile dirs -+ Added a DWOO_CHMOD constant that, if set before you include Dwoo, allows you - to define the file mode of all the file/directories Dwoo will write, defaults - to 0777 -+ Added a 'data' argument to {include} to be able to feed data directly into it -* The compiler now throws Dwoo_Compilation_Exception exceptions upon failure - and security problems lead to a Dwoo_Security_Exception being thrown. Runtime - plugin errors and such trigger simple php errors to allow the template - execution to complete -* Fixed a potential concurrency issue (thanks to Rasmus Schultz for the patch) -* Moved all files to Dwoo/Class.php excepted for the core Dwoo.php file -* Various performance improvements, including the removal of a lot of isset() - calls. Doing {$foo} if foo is undefined will now display a PHP warning, but - doing {foreach $foo}..{/foreach} will not however, that way you don't have - to do {if isset($foo)} before the foreach, but automated isset() calls don't - impact performance as much as they did before. -* API: Dwoo_ITemplate->clearCache now requires a Dwoo instance as its first arg, - should not affect you unless you built a custom template class from scratch -* Reworked Dwoo template rendering to avoid variable conflicts with plugins -* {include} now uses the current resource if none is provided instead of using - file as it did before -* Dwoo uses include path instead of absolute includes -* Changed all line endings to Unix (line feed only) and all spaces left have - been converted to tabs (tabspace 4) -* TestFest happened early for Dwoo, lots of new tests and more code covered -* Fixed a regression in the handling of custom class plugins -* Fixed various bugs in the Adapter class and related smarty compatibility - features -* Fixed a classpath rebuilding bug that occured on some UNIX platforms due to - glob() returning false sometimes for empty folders -* Fixed a bug in Dwoo_Security_Policy->getAllowedDirectories(), no security - issue though -* Fixed a bug in Dwoo::setScope affecting {loop} and {with} -* Fixed a parsing bug when doing {"string"|modifier:$var} - -[2008-04-09] 0.3.4 -! BC Break: DWOO_PATH constant changed to DWOO_DIRECTORY -! BC Break: Smarty's @ operator for modifiers is now reversed, for example - $array|reverse will reverse the items of that array while $array|@reverse - will reverse each item of the given array (as if you used array_map) -+ Syntax: Added support for method calls on objects i.e. {$foo->bar()} -+ Added support for smarty security features, see the DwooSecurityPolicy class - and $dwoo->setSecurityPolicy() -+ API: Added a DwooCompiler->setLooseOpeningHandling() method that, if set to - true, allows tags to contain spaces between the opening bracket and the - content. Turned off by default as it allows to compile files containing - css and javascript without the need to escape it through {literal} or \{ -+ Added DWOO_CACHE_DIRECTORY and DWOO_COMPILE_DIRECTORY constants that you can - set before including Dwoo.php to override the defaults (although - Dwoo->setCacheDir/setCompileDir() still work to change that if required) -+ Added the DwooException class -+ Smarty: Added partial support for register_object(), unregister_object() and - get_registered_object(). All features can not be supported by the adapter - though so you might get compatibility warnings -* Fixed {elseif} bug that appeared when multiple elseif tags were used in a row -* Syntax: Improved simple math support to work within variable variables - (i.e. you can do {$array[$index+1]}) and within strings as well. To prevent - this enclose the variables in backticks (i.e. {"$foo/$bar"} will do the math - while {"`$foo`/$bar"} won't as $foo is properly delimited) -* Changed DwooLoader::addDirectory() so that it writes the class paths cache - into DWOO_COMPILE_DIRECTORY, that way you don't have to make your plugin - directory writable -* Made all the error triggering more consistent -* Changed automatic cacheId generation in DwooTemplateFile/String to be faster - -[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 diff --git a/system/libs/dwoo/Dwoo.compiled.php b/system/libs/dwoo/Dwoo.compiled.php deleted file mode 100644 index ed8b4696..00000000 --- a/system/libs/dwoo/Dwoo.compiled.php +++ /dev/null @@ -1 +0,0 @@ - array ( 'class' => 'Dwoo_Template_File', 'compiler' => null ), 'string' => array ( 'class' => 'Dwoo_Template_String', 'compiler' => null ) ); protected $loader = null; protected $template = null; protected $runtimePlugins; public $data; public $scope; protected $scopeTree; protected $stack; protected $curBlock; protected $buffer; protected $pluginProxy; public function __construct($compileDir = null, $cacheDir = null) { if ($compileDir !== null) { $this->setCompileDir($compileDir); } if ($cacheDir !== null) { $this->setCacheDir($cacheDir); } $this->initGlobals(); } public function __clone() { $this->template = null; unset($this->data); } public function output($tpl, $data = array(), Dwoo_ICompiler $compiler = null) { return $this->get($tpl, $data, $compiler, true); } public function get($_tpl, $data = array(), $_compiler = null, $_output = false) { if ($this->template instanceof Dwoo_ITemplate) { $proxy = clone $this; return $proxy->get($_tpl, $data, $_compiler, $_output); } if ($_tpl instanceof Dwoo_ITemplate) { } elseif (is_string($_tpl) && file_exists($_tpl)) { $_tpl = new Dwoo_Template_File($_tpl); } else { throw new Dwoo_Exception('Dwoo->get/Dwoo->output\'s first argument must be a Dwoo_ITemplate (i.e. Dwoo_Template_File) or a valid path to a template file', E_USER_NOTICE); } $this->template = $_tpl; if ($data instanceof Dwoo_IDataProvider) { $this->data = $data->getData(); } elseif (is_array($data)) { $this->data = $data; } else { throw new Dwoo_Exception('Dwoo->get/Dwoo->output\'s data argument must be a Dwoo_IDataProvider object (i.e. Dwoo_Data) or an associative array', E_USER_NOTICE); } $this->globals['template'] = $_tpl->getName(); $this->initRuntimeVars($_tpl); $file = $_tpl->getCachedTemplate($this); $doCache = $file === true; $cacheLoaded = is_string($file); if ($cacheLoaded === true) { if ($_output === true) { include $file; $this->template = null; } else { ob_start(); include $file; $this->template = null; return ob_get_clean(); } } else { if ($doCache === true) { $dynamicId = uniqid(); } $compiledTemplate = $_tpl->getCompiledTemplate($this, $_compiler); $out = include $compiledTemplate; if ($out === false) { $_tpl->forceCompilation(); $compiledTemplate = $_tpl->getCompiledTemplate($this, $_compiler); $out = include $compiledTemplate; } if ($doCache === true) { $out = preg_replace('/(<%|%>|<\?php|<\?|\?>)/', '', $out); if (!class_exists('Dwoo_plugin_dynamic', false)) { $this->getLoader()->loadPlugin('dynamic'); } $out = Dwoo_Plugin_dynamic::unescape($out, $dynamicId, $compiledTemplate); } foreach ($this->filters as $filter) { if (is_array($filter) && $filter[0] instanceof Dwoo_Filter) { $out = call_user_func($filter, $out); } else { $out = call_user_func($filter, $this, $out); } } if ($doCache === true) { $file = $_tpl->cache($this, $out); if ($_output === true) { include $file; $this->template = null; } else { ob_start(); include $file; $this->template = null; return ob_get_clean(); } } else { $this->template = null; if ($_output === true) { echo $out; } return $out; } } } protected function initGlobals() { $this->globals = array ( 'version' => self::VERSION, 'ad' => 'Powered by Dwoo', 'now' => $_SERVER['REQUEST_TIME'], 'charset' => $this->charset, ); } protected function initRuntimeVars(Dwoo_ITemplate $tpl) { $this->runtimePlugins = array(); $this->scope =& $this->data; $this->scopeTree = array(); $this->stack = array(); $this->curBlock = null; $this->buffer = ''; } public function addPlugin($name, $callback, $compilable = false) { $compilable = $compilable ? self::COMPILABLE_PLUGIN : 0; if (is_array($callback)) { if (is_subclass_of(is_object($callback[0]) ? get_class($callback[0]) : $callback[0], 'Dwoo_Block_Plugin')) { $this->plugins[$name] = array('type'=>self::BLOCK_PLUGIN | $compilable, 'callback'=>$callback, 'class'=>(is_object($callback[0]) ? get_class($callback[0]) : $callback[0])); } else { $this->plugins[$name] = array('type'=>self::CLASS_PLUGIN | $compilable, 'callback'=>$callback, 'class'=>(is_object($callback[0]) ? get_class($callback[0]) : $callback[0]), 'function'=>$callback[1]); } } elseif (class_exists($callback, false)) { if (is_subclass_of($callback, 'Dwoo_Block_Plugin')) { $this->plugins[$name] = array('type'=>self::BLOCK_PLUGIN | $compilable, 'callback'=>$callback, 'class'=>$callback); } else { $this->plugins[$name] = array('type'=>self::CLASS_PLUGIN | $compilable, 'callback'=>$callback, 'class'=>$callback, 'function'=>'process'); } } elseif (function_exists($callback)) { $this->plugins[$name] = array('type'=>self::FUNC_PLUGIN | $compilable, 'callback'=>$callback); } else { throw new Dwoo_Exception('Callback could not be processed correctly, please check that the function/class you used exists'); } } public function removePlugin($name) { if (isset($this->plugins[$name])) { unset($this->plugins[$name]); } } public function addFilter($callback, $autoload = false) { if ($autoload) { $class = 'Dwoo_Filter_'.$callback; if (!class_exists($class, false) && !function_exists($class)) { try { $this->getLoader()->loadPlugin($callback); } catch (Dwoo_Exception $e) { if (strstr($callback, 'Dwoo_Filter_')) { throw new Dwoo_Exception('Wrong filter name : '.$callback.', the "Dwoo_Filter_" prefix should not be used, please only use "'.str_replace('Dwoo_Filter_', '', $callback).'"'); } else { throw new Dwoo_Exception('Wrong filter name : '.$callback.', when using autoload the filter must be in one of your plugin dir as "name.php" containg a class or function named "Dwoo_Filter_name"'); } } } if (class_exists($class, false)) { $callback = array(new $class($this), 'process'); } elseif (function_exists($class)) { $callback = $class; } else { throw new Dwoo_Exception('Wrong filter name : '.$callback.', when using autoload the filter must be in one of your plugin dir as "name.php" containg a class or function named "Dwoo_Filter_name"'); } $this->filters[] = $callback; } else { $this->filters[] = $callback; } } public function removeFilter($callback) { if (($index = array_search('Dwoo_Filter_'.$callback, $this->filters, true)) !== false) { unset($this->filters[$index]); } elseif (($index = array_search($callback, $this->filters, true)) !== false) { unset($this->filters[$index]); } else { $class = 'Dwoo_Filter_' . $callback; foreach ($this->filters as $index=>$filter) { if (is_array($filter) && $filter[0] instanceof $class) { unset($this->filters[$index]); break; } } } } public function addResource($name, $class, $compilerFactory = null) { if (strlen($name) < 2) { throw new Dwoo_Exception('Resource names must be at least two-character long to avoid conflicts with Windows paths'); } if (!class_exists($class)) { throw new Dwoo_Exception('Resource class does not exist'); } $interfaces = class_implements($class); if (in_array('Dwoo_ITemplate', $interfaces) === false) { throw new Dwoo_Exception('Resource class must implement Dwoo_ITemplate'); } $this->resources[$name] = array('class'=>$class, 'compiler'=>$compilerFactory); } public function removeResource($name) { unset($this->resources[$name]); if ($name==='file') { $this->resources['file'] = array('class'=>'Dwoo_Template_File', 'compiler'=>null); } } public function setLoader(Dwoo_ILoader $loader) { $this->loader = $loader; } public function getLoader() { if ($this->loader === null) { $this->loader = new Dwoo_Loader($this->getCompileDir()); } return $this->loader; } public function getCustomPlugins() { return $this->plugins; } public function getCacheDir() { if ($this->cacheDir === null) { $this->setCacheDir(dirname(__FILE__).DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR); } return $this->cacheDir; } public function setCacheDir($dir) { $this->cacheDir = rtrim($dir, '/\\').DIRECTORY_SEPARATOR; if (is_writable($this->cacheDir) === false) { throw new Dwoo_Exception('The cache directory must be writable, chmod "'.$this->cacheDir.'" to make it writable'); } } public function getCompileDir() { if ($this->compileDir === null) { $this->setCompileDir(dirname(__FILE__).DIRECTORY_SEPARATOR.'compiled'.DIRECTORY_SEPARATOR); } return $this->compileDir; } public function setCompileDir($dir) { $this->compileDir = rtrim($dir, '/\\').DIRECTORY_SEPARATOR; if (is_writable($this->compileDir) === false) { throw new Dwoo_Exception('The compile directory must be writable, chmod "'.$this->compileDir.'" to make it writable'); } } public function getCacheTime() { return $this->cacheTime; } public function setCacheTime($seconds) { $this->cacheTime = (int) $seconds; } public function getCharset() { return $this->charset; } public function setCharset($charset) { $this->charset = strtolower((string) $charset); } public function getTemplate() { return $this->template; } public function setTemplate(Dwoo_ITemplate $tpl) { $this->template = $tpl; } public function setDefaultCompilerFactory($resourceName, $compilerFactory) { $this->resources[$resourceName]['compiler'] = $compilerFactory; } public function getDefaultCompilerFactory($resourceName) { return $this->resources[$resourceName]['compiler']; } public function setSecurityPolicy(Dwoo_Security_Policy $policy = null) { $this->securityPolicy = $policy; } public function getSecurityPolicy() { return $this->securityPolicy; } public function setPluginProxy(Dwoo_IPluginProxy $pluginProxy) { $this->pluginProxy = $pluginProxy; } public function getPluginProxy() { return $this->pluginProxy; } public function isCached(Dwoo_ITemplate $tpl) { return is_string($tpl->getCachedTemplate($this)); } public function clearCache($olderThan=-1) { $cacheDirs = new RecursiveDirectoryIterator($this->getCacheDir()); $cache = new RecursiveIteratorIterator($cacheDirs); $expired = time() - $olderThan; $count = 0; foreach ($cache as $file) { if ($cache->isDot() || $cache->isDir() || substr($file, -5) !== '.html') { continue; } if ($cache->getCTime() < $expired) { $count += unlink((string) $file) ? 1 : 0; } } return $count; } public function templateFactory($resourceName, $resourceId, $cacheTime = null, $cacheId = null, $compileId = null, Dwoo_ITemplate $parentTemplate = null) { if (isset($this->resources[$resourceName])) { return call_user_func(array($this->resources[$resourceName]['class'], 'templateFactory'), $this, $resourceId, $cacheTime, $cacheId, $compileId, $parentTemplate); } else { throw new Dwoo_Exception('Unknown resource type : '.$resourceName); } } public function isArray($value, $checkIsEmpty=false) { if (is_array($value) === true) { if ($checkIsEmpty === false) { return true; } else { return count($value) > 0; } } elseif ($value instanceof Iterator) { if ($checkIsEmpty === false) { return true; } elseif ($value instanceof Countable) { return count($value) > 0; } else { $value->rewind(); return $value->valid(); } } elseif ($value instanceof ArrayAccess) { if ($checkIsEmpty === false) { return true; } elseif ($value instanceof Countable) { return count($value) > 0; } else { return $value->offsetExists(0); } } return false; } public function triggerError($message, $level=E_USER_NOTICE) { if (!($tplIdentifier = $this->template->getResourceIdentifier())) { $tplIdentifier = $this->template->getResourceName(); } trigger_error('Dwoo error (in '.$tplIdentifier.') : '.$message, $level); } public function addStack($blockName, array $args=array()) { if (isset($this->plugins[$blockName])) { $class = $this->plugins[$blockName]['class']; } else { $class = 'Dwoo_Plugin_'.$blockName; } if ($this->curBlock !== null) { $this->curBlock->buffer(ob_get_contents()); ob_clean(); } else { $this->buffer .= ob_get_contents(); ob_clean(); } $block = new $class($this); $cnt = count($args); if ($cnt===0) { $block->init(); } elseif ($cnt===1) { $block->init($args[0]); } elseif ($cnt===2) { $block->init($args[0], $args[1]); } elseif ($cnt===3) { $block->init($args[0], $args[1], $args[2]); } elseif ($cnt===4) { $block->init($args[0], $args[1], $args[2], $args[3]); } else { call_user_func_array(array($block,'init'), $args); } $this->stack[] = $this->curBlock = $block; return $block; } public function delStack() { $args = func_get_args(); $this->curBlock->buffer(ob_get_contents()); ob_clean(); $cnt = count($args); if ($cnt===0) { $this->curBlock->end(); } elseif ($cnt===1) { $this->curBlock->end($args[0]); } elseif ($cnt===2) { $this->curBlock->end($args[0], $args[1]); } elseif ($cnt===3) { $this->curBlock->end($args[0], $args[1], $args[2]); } elseif ($cnt===4) { $this->curBlock->end($args[0], $args[1], $args[2], $args[3]); } else { call_user_func_array(array($this->curBlock, 'end'), $args); } $tmp = array_pop($this->stack); if (count($this->stack) > 0) { $this->curBlock = end($this->stack); $this->curBlock->buffer($tmp->process()); } else { $this->curBlock = null; echo $tmp->process(); } unset($tmp); } public function getParentBlock(Dwoo_Block_Plugin $block) { $index = array_search($block, $this->stack, true); if ($index !== false && $index > 0) { return $this->stack[$index-1]; } return false; } public function findBlock($type) { if (isset($this->plugins[$type])) { $type = $this->plugins[$type]['class']; } else { $type = 'Dwoo_Plugin_'.str_replace('Dwoo_Plugin_', '', $type); } $keys = array_keys($this->stack); while (($key = array_pop($keys)) !== false) { if ($this->stack[$key] instanceof $type) { return $this->stack[$key]; } } return false; } public function getObjectPlugin($class) { if (isset($this->runtimePlugins[$class])) { return $this->runtimePlugins[$class]; } return $this->runtimePlugins[$class] = new $class($this); } public function classCall($plugName, array $params = array()) { $class = 'Dwoo_Plugin_'.$plugName; $plugin = $this->getObjectPlugin($class); $cnt = count($params); if ($cnt===0) { return $plugin->process(); } elseif ($cnt===1) { return $plugin->process($params[0]); } elseif ($cnt===2) { return $plugin->process($params[0], $params[1]); } elseif ($cnt===3) { return $plugin->process($params[0], $params[1], $params[2]); } elseif ($cnt===4) { return $plugin->process($params[0], $params[1], $params[2], $params[3]); } else { return call_user_func_array(array($plugin, 'process'), $params); } } public function arrayMap($callback, array $params) { if ($params[0] === $this) { $addThis = true; array_shift($params); } if ((is_array($params[0]) || ($params[0] instanceof Iterator && $params[0] instanceof ArrayAccess))) { if (empty($params[0])) { return $params[0]; } $out = array(); $cnt = count($params); if (isset($addThis)) { array_unshift($params, $this); $items = $params[1]; $keys = array_keys($items); if (is_string($callback) === false) { while (($i = array_shift($keys)) !== null) { $out[] = call_user_func_array($callback, array(1=>$items[$i]) + $params); } } elseif ($cnt===1) { while (($i = array_shift($keys)) !== null) { $out[] = $callback($this, $items[$i]); } } elseif ($cnt===2) { while (($i = array_shift($keys)) !== null) { $out[] = $callback($this, $items[$i], $params[2]); } } elseif ($cnt===3) { while (($i = array_shift($keys)) !== null) { $out[] = $callback($this, $items[$i], $params[2], $params[3]); } } else { while (($i = array_shift($keys)) !== null) { $out[] = call_user_func_array($callback, array(1=>$items[$i]) + $params); } } } else { $items = $params[0]; $keys = array_keys($items); if (is_string($callback) === false) { while (($i = array_shift($keys)) !== null) { $out[] = call_user_func_array($callback, array($items[$i]) + $params); } } elseif ($cnt===1) { while (($i = array_shift($keys)) !== null) { $out[] = $callback($items[$i]); } } elseif ($cnt===2) { while (($i = array_shift($keys)) !== null) { $out[] = $callback($items[$i], $params[1]); } } elseif ($cnt===3) { while (($i = array_shift($keys)) !== null) { $out[] = $callback($items[$i], $params[1], $params[2]); } } elseif ($cnt===4) { while (($i = array_shift($keys)) !== null) { $out[] = $callback($items[$i], $params[1], $params[2], $params[3]); } } else { while (($i = array_shift($keys)) !== null) { $out[] = call_user_func_array($callback, array($items[$i]) + $params); } } } return $out; } else { return $params[0]; } } public function readVarInto($varstr, $data, $safeRead = false) { if ($data === null) { return null; } if (is_array($varstr) === false) { preg_match_all('#(\[|->|\.)?((?:[^.[\]-]|-(?!>))+)\]?#i', $varstr, $m); } else { $m = $varstr; } unset($varstr); while (list($k, $sep) = each($m[1])) { if ($sep === '.' || $sep === '[' || $sep === '') { if ((is_array($data) || $data instanceof ArrayAccess) && ($safeRead === false || isset($data[$m[2][$k]]))) { $data = $data[$m[2][$k]]; } else { return null; } } else { if (is_object($data) && ($safeRead === false || isset($data->$m[2][$k]) || is_callable(array($data, '__get')))) { $data = $data->$m[2][$k]; } else { return null; } } } return $data; } public function readParentVar($parentLevels, $varstr = null) { $tree = $this->scopeTree; $cur = $this->data; while ($parentLevels--!==0) { array_pop($tree); } while (($i = array_shift($tree)) !== null) { if (is_object($cur)) { $cur = $cur->$i; } else { $cur = $cur[$i]; } } if ($varstr!==null) { return $this->readVarInto($varstr, $cur); } else { return $cur; } } public function readVar($varstr) { if (is_array($varstr)===true) { $m = $varstr; unset($varstr); } else { if (strstr($varstr, '.') === false && strstr($varstr, '[') === false && strstr($varstr, '->') === false) { if ($varstr === 'dwoo') { return $this->globals; } elseif ($varstr === '__' || $varstr === '_root' ) { return $this->data; $varstr = substr($varstr, 6); } elseif ($varstr === '_' || $varstr === '_parent') { $varstr = '.'.$varstr; $tree = $this->scopeTree; $cur = $this->data; array_pop($tree); while (($i = array_shift($tree)) !== null) { if (is_object($cur)) { $cur = $cur->$i; } else { $cur = $cur[$i]; } } return $cur; } $cur = $this->scope; if (isset($cur[$varstr])) { return $cur[$varstr]; } else { return null; } } if (substr($varstr, 0, 1) === '.') { $varstr = 'dwoo'.$varstr; } preg_match_all('#(\[|->|\.)?((?:[^.[\]-]|-(?!>))+)\]?#i', $varstr, $m); } $i = $m[2][0]; if ($i === 'dwoo') { $cur = $this->globals; array_shift($m[2]); array_shift($m[1]); switch ($m[2][0]) { case 'get': $cur = $_GET; break; case 'post': $cur = $_POST; break; case 'session': $cur = $_SESSION; break; case 'cookies': case 'cookie': $cur = $_COOKIE; break; case 'server': $cur = $_SERVER; break; case 'env': $cur = $_ENV; break; case 'request': $cur = $_REQUEST; break; case 'const': array_shift($m[2]); if (defined($m[2][0])) { return constant($m[2][0]); } else { return null; } } if ($cur !== $this->globals) { array_shift($m[2]); array_shift($m[1]); } } elseif ($i === '__' || $i === '_root') { $cur = $this->data; array_shift($m[2]); array_shift($m[1]); } elseif ($i === '_' || $i === '_parent') { $tree = $this->scopeTree; $cur = $this->data; while (true) { array_pop($tree); array_shift($m[2]); array_shift($m[1]); if (current($m[2]) === '_' || current($m[2]) === '_parent') { continue; } while (($i = array_shift($tree)) !== null) { if (is_object($cur)) { $cur = $cur->$i; } else { $cur = $cur[$i]; } } break; } } else { $cur = $this->scope; } while (list($k, $sep) = each($m[1])) { if ($sep === '.' || $sep === '[' || $sep === '') { if ((is_array($cur) || $cur instanceof ArrayAccess) && isset($cur[$m[2][$k]])) { $cur = $cur[$m[2][$k]]; } else { return null; } } elseif ($sep === '->') { if (is_object($cur)) { $cur = $cur->$m[2][$k]; } else { return null; } } else { return null; } } return $cur; } public function assignInScope($value, $scope) { $tree =& $this->scopeTree; $data =& $this->data; if (!is_string($scope)) { return $this->triggerError('Assignments must be done into strings, ('.gettype($scope).') '.var_export($scope, true).' given', E_USER_ERROR); } if (strstr($scope, '.') === false && strstr($scope, '->') === false) { $this->scope[$scope] = $value; } else { preg_match_all('#(\[|->|\.)?([^.[\]-]+)\]?#i', $scope, $m); $cur =& $this->scope; $last = array(array_pop($m[1]), array_pop($m[2])); while (list($k, $sep) = each($m[1])) { if ($sep === '.' || $sep === '[' || $sep === '') { if (is_array($cur) === false) { $cur = array(); } $cur =& $cur[$m[2][$k]]; } elseif ($sep === '->') { if (is_object($cur) === false) { $cur = new stdClass; } $cur =& $cur->$m[2][$k]; } else { return false; } } if ($last[0] === '.' || $last[0] === '[' || $last[0] === '') { if (is_array($cur) === false) { $cur = array(); } $cur[$last[1]] = $value; } elseif ($last[0] === '->') { if (is_object($cur) === false) { $cur = new stdClass; } $cur->$last[1] = $value; } else { return false; } } } public function setScope($scope, $absolute = false) { $old = $this->scopeTree; if (is_string($scope)===true) { $scope = explode('.', $scope); } if ($absolute===true) { $this->scope =& $this->data; $this->scopeTree = array(); } while (($bit = array_shift($scope)) !== null) { if ($bit === '_' || $bit === '_parent') { array_pop($this->scopeTree); $this->scope =& $this->data; $cnt = count($this->scopeTree); for ($i=0;$i<$cnt;$i++) $this->scope =& $this->scope[$this->scopeTree[$i]]; } elseif ($bit === '__' || $bit === '_root') { $this->scope =& $this->data; $this->scopeTree = array(); } elseif (isset($this->scope[$bit])) { $this->scope =& $this->scope[$bit]; $this->scopeTree[] = $bit; } else { unset($this->scope); $this->scope = null; } } return $old; } public function getData() { return $this->data; } public function &getScope() { return $this->scope; } public function __call($method, $args) { $proxy = $this->getPluginProxy(); if (!$proxy) { throw new Dwoo_Exception('Call to undefined method '.__CLASS__.'::'.$method.'()'); } return call_user_func_array($proxy->getCallback($method), $args); } } interface Dwoo_IPluginProxy { public function handles($name); public function getCode($name, $params); public function getCallback($name); public function getLoader($name); } interface Dwoo_IElseable { } interface Dwoo_ILoader { public function loadPlugin($class, $forceRehash = true); } class Dwoo_Loader implements Dwoo_ILoader { protected $paths = array(); protected $classPath = array(); protected $cacheDir; protected $corePluginDir; public function __construct($cacheDir) { $this->corePluginDir = DWOO_DIRECTORY . 'plugins'; $this->cacheDir = rtrim($cacheDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $cacheFile = $this->cacheDir.'classpath.cache.d'.Dwoo::RELEASE_TAG.'.php'; if (file_exists($cacheFile)) { $classpath = file_get_contents($cacheFile); $this->classPath = unserialize($classpath) + $this->classPath; } else { $this->rebuildClassPathCache($this->corePluginDir, $cacheFile); } } protected function rebuildClassPathCache($path, $cacheFile) { if ($cacheFile!==false) { $tmp = $this->classPath; $this->classPath = array(); } $list = glob(rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . '*'); if (is_array($list)) { foreach ($list as $f) { if (is_dir($f)) { $this->rebuildClassPathCache($f, false); } else { $this->classPath[str_replace(array('function.','block.','modifier.','outputfilter.','filter.','prefilter.','postfilter.','pre.','post.','output.','shared.','helper.'), '', basename($f, '.php'))] = $f; } } } if ($cacheFile!==false) { if (!file_put_contents($cacheFile, serialize($this->classPath))) { throw new Dwoo_Exception('Could not write into '.$cacheFile.', either because the folder is not there (create it) or because of the chmod configuration (please ensure this directory is writable by php), alternatively you can change the directory used with $dwoo->setCompileDir() or provide a custom loader object with $dwoo->setLoader()'); } $this->classPath += $tmp; } } public function loadPlugin($class, $forceRehash = true) { if (!isset($this->classPath[$class]) || !(include $this->classPath[$class])) { if ($forceRehash) { $this->rebuildClassPathCache($this->corePluginDir, $this->cacheDir . 'classpath.cache.d'.Dwoo::RELEASE_TAG.'.php'); foreach ($this->paths as $path=>$file) { $this->rebuildClassPathCache($path, $file); } if (isset($this->classPath[$class])) { include $this->classPath[$class]; } else { throw new Dwoo_Exception('Plugin '.$class.' can not be found, maybe you forgot to bind it if it\'s a custom plugin ?', E_USER_NOTICE); } } else { throw new Dwoo_Exception('Plugin '.$class.' can not be found, maybe you forgot to bind it if it\'s a custom plugin ?', E_USER_NOTICE); } } } public function addDirectory($pluginDirectory) { $pluginDir = realpath($pluginDirectory); if (!$pluginDir) { throw new Dwoo_Exception('Plugin directory does not exist or can not be read : '.$pluginDirectory); } $cacheFile = $this->cacheDir . 'classpath-'.substr(strtr($pluginDir, '/\\:'.PATH_SEPARATOR, '----'), strlen($pluginDir) > 80 ? -80 : 0).'.d'.Dwoo::RELEASE_TAG.'.php'; $this->paths[$pluginDir] = $cacheFile; if (file_exists($cacheFile)) { $classpath = file_get_contents($cacheFile); $this->classPath = unserialize($classpath) + $this->classPath; } else { $this->rebuildClassPathCache($pluginDir, $cacheFile); } } } class Dwoo_Exception extends Exception { } class Dwoo_Security_Policy { const PHP_ENCODE = 1; const PHP_REMOVE = 2; const PHP_ALLOW = 3; const CONST_DISALLOW = false; const CONST_ALLOW = true; protected $allowedPhpFunctions = array ( 'str_repeat', 'number_format', 'htmlentities', 'htmlspecialchars', 'long2ip', 'strlen', 'list', 'empty', 'count', 'sizeof', 'in_array', 'is_array', ); protected $allowedDirectories = array(); protected $phpHandling = self::PHP_REMOVE; protected $constHandling = self::CONST_DISALLOW; public function allowPhpFunction($func) { if (is_array($func)) foreach ($func as $fname) $this->allowedPhpFunctions[strtolower($fname)] = true; else $this->allowedPhpFunctions[strtolower($func)] = true; } public function disallowPhpFunction($func) { if (is_array($func)) foreach ($func as $fname) unset($this->allowedPhpFunctions[strtolower($fname)]); else unset($this->allowedPhpFunctions[strtolower($func)]); } public function getAllowedPhpFunctions() { return $this->allowedPhpFunctions; } public function allowDirectory($path) { if (is_array($path)) foreach ($path as $dir) $this->allowedDirectories[realpath($dir)] = true; else $this->allowedDirectories[realpath($path)] = true; } public function disallowDirectory($path) { if (is_array($path)) foreach ($path as $dir) unset($this->allowedDirectories[realpath($dir)]); else unset($this->allowedDirectories[realpath($path)]); } public function getAllowedDirectories() { return $this->allowedDirectories; } public function setPhpHandling($level = self::PHP_REMOVE) { $this->phpHandling = $level; } public function getPhpHandling() { return $this->phpHandling; } public function setConstantHandling($level = self::CONST_DISALLOW) { $this->constHandling = $level; } public function getConstantHandling() { return $this->constHandling; } } class Dwoo_Security_Exception extends Dwoo_Exception { } interface Dwoo_ICompilable { } interface Dwoo_ICompiler { public function compile(Dwoo $dwoo, Dwoo_ITemplate $template); public function setCustomPlugins(array $customPlugins); public function setSecurityPolicy(Dwoo_Security_Policy $policy = null); } interface Dwoo_IDataProvider { public function getData(); } interface Dwoo_ITemplate { public function getCacheTime(); public function setCacheTime($seconds = null); public function getCachedTemplate(Dwoo $dwoo); public function cache(Dwoo $dwoo, $output); public function clearCache(Dwoo $dwoo, $olderThan = -1); public function getCompiledTemplate(Dwoo $dwoo, Dwoo_ICompiler $compiler = null); public function getName(); public function getResourceName(); public function getResourceIdentifier(); public function getSource(); public function getUid(); public function getCompiler(); public function getIsModifiedCode(); public static function templateFactory(Dwoo $dwoo, $resourceId, $cacheTime = null, $cacheId = null, $compileId = null, Dwoo_ITemplate $parentTemplate = null); } interface Dwoo_ICompilable_Block { } abstract class Dwoo_Plugin { protected $dwoo; public function __construct(Dwoo $dwoo) { $this->dwoo = $dwoo; } public static function paramsToAttributes(array $params, $delim = '\'') { if (isset($params['*'])) { $params = array_merge($params, $params['*']); unset($params['*']); } $out = ''; foreach ($params as $attr=>$val) { $out .= ' '.$attr.'='; if (trim($val, '"\'')=='' || $val=='null') { $out .= str_replace($delim, '\\'.$delim, '""'); } elseif (substr($val, 0, 1) === $delim && substr($val, -1) === $delim) { $out .= str_replace($delim, '\\'.$delim, '"'.substr($val, 1, -1).'"'); } else { $out .= str_replace($delim, '\\'.$delim, '"') . $delim . '.'.$val.'.' . $delim . str_replace($delim, '\\'.$delim, '"'); } } return ltrim($out); } } abstract class Dwoo_Block_Plugin extends Dwoo_Plugin { protected $buffer = ''; public function buffer($input) { $this->buffer .= $input; } public function end() { } public function process() { return $this->buffer; } public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) { return Dwoo_Compiler::PHP_OPEN.$prepend.'$this->addStack("'.$type.'", array('.Dwoo_Compiler::implode_r($compiler->getCompiledParams($params)).'));'.$append.Dwoo_Compiler::PHP_CLOSE; } public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) { return $content . Dwoo_Compiler::PHP_OPEN.$prepend.'$this->delStack();'.$append.Dwoo_Compiler::PHP_CLOSE; } } abstract class Dwoo_Filter { protected $dwoo; public function __construct(Dwoo $dwoo) { $this->dwoo = $dwoo; } abstract public function process($input); } abstract class Dwoo_Processor { protected $compiler; public function __construct(Dwoo_Compiler $compiler) { $this->compiler = $compiler; } abstract public function process($input); } class Dwoo_Template_String implements Dwoo_ITemplate { protected $name; protected $compileId; protected $cacheId; protected $cacheTime; protected $compilationEnforced; protected static $cache = array('cached'=>array(), 'compiled'=>array()); protected $compiler; protected $chmod = 0777; public function __construct($templateString, $cacheTime = null, $cacheId = null, $compileId = null) { $this->template = $templateString; if (function_exists('hash')) { $this->name = hash('md4', $templateString); } else { $this->name = md5($templateString); } $this->cacheTime = $cacheTime; if ($compileId !== null) { $this->compileId = str_replace('../', '__', strtr($compileId, '\\%?=!:;'.PATH_SEPARATOR, '/-------')); } if ($cacheId !== null) { $this->cacheId = str_replace('../', '__', strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------')); } } public function getCacheTime() { return $this->cacheTime; } public function setCacheTime($seconds = null) { $this->cacheTime = $seconds; } public function getChmod() { return $this->chmod; } public function setChmod($mask = null) { $this->chmod = $mask; } public function getName() { return $this->name; } public function getResourceName() { return 'string'; } public function getResourceIdentifier() { return false; } public function getSource() { return $this->template; } public function getUid() { return $this->name; } public function getCompiler() { return $this->compiler; } public function forceCompilation() { $this->compilationEnforced = true; } public function getCachedTemplate(Dwoo $dwoo) { if ($this->cacheTime !== null) { $cacheLength = $this->cacheTime; } else { $cacheLength = $dwoo->getCacheTime(); } if ($cacheLength === 0) { return false; } $cachedFile = $this->getCacheFilename($dwoo); if (isset(self::$cache['cached'][$this->cacheId]) === true && file_exists($cachedFile)) { return $cachedFile; } elseif ($this->compilationEnforced !== true && file_exists($cachedFile) && ($cacheLength === -1 || filemtime($cachedFile) > ($_SERVER['REQUEST_TIME'] - $cacheLength)) && $this->isValidCompiledFile($this->getCompiledFilename($dwoo))) { self::$cache['cached'][$this->cacheId] = true; return $cachedFile; } else { return true; } } public function cache(Dwoo $dwoo, $output) { $cacheDir = $dwoo->getCacheDir(); $cachedFile = $this->getCacheFilename($dwoo); $temp = tempnam($cacheDir, 'temp'); if (!($file = @fopen($temp, 'wb'))) { $temp = $cacheDir . uniqid('temp'); if (!($file = @fopen($temp, 'wb'))) { trigger_error('Error writing temporary file \''.$temp.'\'', E_USER_WARNING); return false; } } fwrite($file, $output); fclose($file); $this->makeDirectory(dirname($cachedFile), $cacheDir); if (!@rename($temp, $cachedFile)) { @unlink($cachedFile); @rename($temp, $cachedFile); } if ($this->chmod !== null) { chmod($cachedFile, $this->chmod); } self::$cache['cached'][$this->cacheId] = true; return $cachedFile; } public function clearCache(Dwoo $dwoo, $olderThan = -1) { $cachedFile = $this->getCacheFilename($dwoo); return !file_exists($cachedFile) || (filectime($cachedFile) < (time() - $olderThan) && unlink($cachedFile)); } public function getCompiledTemplate(Dwoo $dwoo, Dwoo_ICompiler $compiler = null) { $compiledFile = $this->getCompiledFilename($dwoo); if ($this->compilationEnforced !== true && isset(self::$cache['compiled'][$this->compileId]) === true) { } elseif ($this->compilationEnforced !== true && $this->isValidCompiledFile($compiledFile)) { self::$cache['compiled'][$this->compileId] = true; } else { $this->compilationEnforced = false; if ($compiler === null) { $compiler = $dwoo->getDefaultCompilerFactory($this->getResourceName()); if ($compiler === null || $compiler === array('Dwoo_Compiler', 'compilerFactory')) { if (class_exists('Dwoo_Compiler', false) === false) { include DWOO_DIRECTORY . 'Dwoo/Compiler.php'; } $compiler = Dwoo_Compiler::compilerFactory(); } else { $compiler = call_user_func($compiler); } } $this->compiler = $compiler; $compiler->setCustomPlugins($dwoo->getCustomPlugins()); $compiler->setSecurityPolicy($dwoo->getSecurityPolicy()); $this->makeDirectory(dirname($compiledFile), $dwoo->getCompileDir()); file_put_contents($compiledFile, $compiler->compile($dwoo, $this)); if ($this->chmod !== null) { chmod($compiledFile, $this->chmod); } self::$cache['compiled'][$this->compileId] = true; } return $compiledFile; } protected function isValidCompiledFile($file) { return file_exists($file); } public static function templateFactory(Dwoo $dwoo, $resourceId, $cacheTime = null, $cacheId = null, $compileId = null, Dwoo_ITemplate $parentTemplate = null) { return new self($resourceId, $cacheTime, $cacheId, $compileId); } protected function getCompiledFilename(Dwoo $dwoo) { if ($this->compileId===null) { $this->compileId = $this->name; } return $dwoo->getCompileDir() . $this->compileId.'.d'.Dwoo::RELEASE_TAG.'.php'; } protected function getCacheFilename(Dwoo $dwoo) { if ($this->cacheId === null) { if (isset($_SERVER['REQUEST_URI']) === true) { $cacheId = $_SERVER['REQUEST_URI']; } elseif (isset($_SERVER['SCRIPT_FILENAME']) && isset($_SERVER['argv'])) { $cacheId = $_SERVER['SCRIPT_FILENAME'].'-'.implode('-', $_SERVER['argv']); } else { $cacheId = ''; } $this->getCompiledFilename($dwoo); $this->cacheId = str_replace('../', '__', $this->compileId . strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------')); } return $dwoo->getCacheDir() . $this->cacheId.'.html'; } public function getIsModifiedCode() { return null; } protected function makeDirectory($path, $baseDir = null) { if (is_dir($path) === true) { return; } if ($this->chmod === null) { $chmod = 0777; } else { $chmod = $this->chmod; } mkdir($path, $chmod, true); if (strpos(PHP_OS, 'WIN') !== 0 && $baseDir !== null) { $path = strtr(str_replace($baseDir, '', $path), '\\', '/'); $folders = explode('/', trim($path, '/')); foreach ($folders as $folder) { $baseDir .= $folder . DIRECTORY_SEPARATOR; chmod($baseDir, $chmod); } } } } class Dwoo_Template_File extends Dwoo_Template_String { protected $file; protected $includePath = null; protected $resolvedPath = null; public function __construct($file, $cacheTime = null, $cacheId = null, $compileId = null, $includePath = null) { $this->file = $file; $this->name = basename($file); $this->cacheTime = $cacheTime; if ($compileId !== null) { $this->compileId = str_replace('../', '__', strtr($compileId, '\\%?=!:;'.PATH_SEPARATOR, '/-------')); } if ($cacheId !== null) { $this->cacheId = str_replace('../', '__', strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------')); } if (is_string($includePath)) { $this->includePath = array($includePath); } elseif (is_array($includePath)) { $this->includePath = $includePath; } } public function setIncludePath($paths) { if (is_array($paths) === false) { $paths = array($paths); } $this->includePath = $paths; $this->resolvedPath = null; } public function getIncludePath() { return $this->includePath; } protected function isValidCompiledFile($file) { return parent::isValidCompiledFile($file) && (int)$this->getUid() <= filemtime($file); } public function getSource() { return file_get_contents($this->getResourceIdentifier()); } public function getResourceName() { return 'file'; } public function getResourceIdentifier() { if ($this->resolvedPath !== null) { return $this->resolvedPath; } elseif ($this->includePath === null) { return $this->file; } else { foreach ($this->includePath as $path) { $path = rtrim($path, DIRECTORY_SEPARATOR); if (file_exists($path.DIRECTORY_SEPARATOR.$this->file) === true) { $this->resolvedPath = $path . DIRECTORY_SEPARATOR . $this->file; return $this->resolvedPath; } } throw new Dwoo_Exception('Template "'.$this->file.'" could not be found in any of your include path(s)'); } } public function getUid() { return (string) filemtime($this->getResourceIdentifier()); } public static function templateFactory(Dwoo $dwoo, $resourceId, $cacheTime = null, $cacheId = null, $compileId = null, Dwoo_ITemplate $parentTemplate = null) { if (DIRECTORY_SEPARATOR === '\\') { $resourceId = str_replace(array("\t", "\n", "\r", "\f", "\v"), array('\\t', '\\n', '\\r', '\\f', '\\v'), $resourceId); } $resourceId = strtr($resourceId, '\\', '/'); $includePath = null; if (file_exists($resourceId) === false) { if ($parentTemplate === null) { $parentTemplate = $dwoo->getTemplate(); } if ($parentTemplate instanceof Dwoo_Template_File) { if ($includePath = $parentTemplate->getIncludePath()) { if (strstr($resourceId, '../')) { throw new Dwoo_Exception('When using an include path you can not reference a template into a parent directory (using ../)'); } } else { $resourceId = dirname($parentTemplate->getResourceIdentifier()).DIRECTORY_SEPARATOR.$resourceId; if (file_exists($resourceId) === false) { return null; } } } else { return null; } } if ($policy = $dwoo->getSecurityPolicy()) { while (true) { if (preg_match('{^([a-z]+?)://}i', $resourceId)) { throw new Dwoo_Security_Exception('The security policy prevents you to read files from external sources : '.$resourceId.'.'); } if ($includePath) { break; } $resourceId = realpath($resourceId); $dirs = $policy->getAllowedDirectories(); foreach ($dirs as $dir=>$dummy) { if (strpos($resourceId, $dir) === 0) { break 2; } } throw new Dwoo_Security_Exception('The security policy prevents you to read '.$resourceId.''); } } $class = 'Dwoo_Template_File'; if ($parentTemplate) { $class = get_class($parentTemplate); } return new $class($resourceId, $cacheTime, $cacheId, $compileId, $includePath); } protected function getCompiledFilename(Dwoo $dwoo) { if ($this->compileId===null) { $this->compileId = str_replace('../', '__', strtr($this->getResourceIdentifier(), '\\:', '/-')); } return $dwoo->getCompileDir() . $this->compileId.'.d'.Dwoo::RELEASE_TAG.'.php'; } public function getIsModifiedCode() { return '"'.$this->getUid().'" == filemtime('.var_export($this->getResourceIdentifier(), true).')'; } } class Dwoo_Data implements Dwoo_IDataProvider { protected $data = array(); public function getData() { return $this->data; } 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]); } } public function setData(array $data) { $this->data = $data; } 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); } } } 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; } } public function __set($name, $value) { $this->assign($name, $value); } public function assignByRef($name, &$val) { $this->data[$name] =& $val; } 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'); } elseif (!isset($this->data[$name])) { $this->data[$name] = array(); } if ($merge === true && is_array($val)) { $this->data[$name] = $val + $this->data[$name]; } else { $this->data[$name][] = $val; } } } 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; } } public function isAssigned($name) { return isset($this->data[$name]); } public function __isset($name) { return isset($this->data[$name]); } public function unassign($name) { unset($this->data[$name]); } public function __unset($name) { unset($this->data[$name]); } public function get($name) { return $this->__get($name); } public function __get($name) { if (isset($this->data[$name])) { return $this->data[$name]; } else { throw new Dwoo_Exception('Tried to read a value that was not assigned yet : "'.$name.'"'); } } } \ No newline at end of file diff --git a/system/libs/dwoo/Dwoo.php b/system/libs/dwoo/Dwoo.php deleted file mode 100644 index 52573651..00000000 --- a/system/libs/dwoo/Dwoo.php +++ /dev/null @@ -1,1533 +0,0 @@ - - * requirements : - * php 5.2.0 or above (might work below, it's a rough estimate) - * SPL and PCRE extensions (for php versions prior to 5.3.0) - * mbstring extension for some string manipulation plugins (especially if you intend to use UTF-8) - * recommended : - * hash extension (for Dwoo_Template_String - minor performance boost) - * - * project created : - * 2008-01-05 - * - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - */ -class Dwoo -{ - /** - * current version number - * - * @var string - */ - const VERSION = '1.1.1'; - - /** - * unique number of this dwoo release - * - * this can be used by templates classes to check whether the compiled template - * has been compiled before this release or not, so that old templates are - * recompiled automatically when Dwoo is updated - */ - const RELEASE_TAG = 17; - - /**#@+ - * constants that represents all plugin types - * - * these are bitwise-operation-safe values to allow multiple types - * on a single plugin - * - * @var int - */ - const CLASS_PLUGIN = 1; - const FUNC_PLUGIN = 2; - const NATIVE_PLUGIN = 4; - const BLOCK_PLUGIN = 8; - const COMPILABLE_PLUGIN = 16; - const CUSTOM_PLUGIN = 32; - const SMARTY_MODIFIER = 64; - const SMARTY_BLOCK = 128; - const SMARTY_FUNCTION = 256; - const PROXY_PLUGIN = 512; - const TEMPLATE_PLUGIN = 1024; - /**#@-*/ - - /** - * character set of the template, used by string manipulation plugins - * - * it must be lowercase, but setCharset() will take care of that - * - * @see setCharset - * @see getCharset - * @var string - */ - protected $charset = 'utf-8'; - - /** - * global variables that are accessible through $dwoo.* in the templates - * - * default values include: - * - * $dwoo.version - current version number - * $dwoo.ad - a Powered by Dwoo link pointing to dwoo.org - * $dwoo.now - the current time - * $dwoo.template - the current template filename - * $dwoo.charset - the character set used by the template - * - * on top of that, foreach and other plugins can store special values in there, - * see their documentation for more details. - * - * @private - * @var array - */ - public $globals; - - /** - * directory where the compiled templates are stored - * - * defaults to DWOO_COMPILEDIR (= dwoo_dir/compiled by default) - * - * @var string - */ - protected $compileDir; - - /** - * directory where the cached templates are stored - * - * defaults to DWOO_CACHEDIR (= dwoo_dir/cache by default) - * - * @var string - */ - protected $cacheDir; - - /** - * defines how long (in seconds) the cached files must remain valid - * - * can be overriden on a per-template basis - * - * -1 = never delete - * 0 = disabled - * >0 = duration in seconds - * - * @var int - */ - protected $cacheTime = 0; - - /** - * security policy object - * - * @var Dwoo_Security_Policy - */ - protected $securityPolicy = null; - - /** - * stores the custom plugins callbacks - * - * @see addPlugin - * @see removePlugin - * @var array - */ - protected $plugins = array(); - - /** - * stores the filter callbacks - * - * @see addFilter - * @see removeFilter - * @var array - */ - protected $filters = array(); - - /** - * stores the resource types and associated - * classes / compiler classes - * - * @var array - */ - protected $resources = array - ( - 'file' => array - ( - 'class' => 'Dwoo_Template_File', - 'compiler' => null - ), - 'string' => array - ( - 'class' => 'Dwoo_Template_String', - 'compiler' => null - ) - ); - - /** - * the dwoo loader object used to load plugins by this dwoo instance - * - * @var Dwoo_ILoader - */ - protected $loader = null; - - /** - * currently rendered template, set to null when not-rendering - * - * @var Dwoo_ITemplate - */ - protected $template = null; - - /** - * stores the instances of the class plugins during template runtime - * - * @var array - */ - protected $runtimePlugins; - - /** - * stores the data during template runtime - * - * @var array - * @private - */ - public $data; - - /** - * stores the current scope during template runtime - * - * this should ideally not be accessed directly from outside template code - * - * @var mixed - * @private - */ - public $scope; - - /** - * stores the scope tree during template runtime - * - * @var array - */ - protected $scopeTree; - - /** - * stores the block plugins stack during template runtime - * - * @var array - */ - protected $stack; - - /** - * stores the current block plugin at the top of the stack during template runtime - * - * @var Dwoo_Block_Plugin - */ - protected $curBlock; - - /** - * stores the output buffer during template runtime - * - * @var string - */ - protected $buffer; - - /** - * stores plugin proxy - * - * @var Dwoo_IPluginProxy - */ - protected $pluginProxy; - - /** - * constructor, sets the cache and compile dir to the default values if not provided - * - * @param string $compileDir path to the compiled directory, defaults to lib/compiled - * @param string $cacheDir path to the cache directory, defaults to lib/cache - */ - public function __construct($compileDir = null, $cacheDir = null) - { - if ($compileDir !== null) { - $this->setCompileDir($compileDir); - } - if ($cacheDir !== null) { - $this->setCacheDir($cacheDir); - } - $this->initGlobals(); - } - - /** - * resets some runtime variables to allow a cloned object to be used to render sub-templates - */ - public function __clone() - { - $this->template = null; - unset($this->data); - } - - /** - * outputs the template instead of returning it, this is basically a shortcut for get(*, *, *, true) - * - * @see get - * @param mixed $tpl template, can either be a Dwoo_ITemplate object (i.e. Dwoo_Template_File), a valid path to a template, or - * a template as a string it is recommended to provide a Dwoo_ITemplate as it will probably make things faster, - * especially if you render a template multiple times - * @param mixed $data the data to use, can either be a Dwoo_IDataProvider object (i.e. Dwoo_Data) or an associative array. if you're - * rendering the template from cache, it can be left null - * @param Dwoo_ICompiler $compiler the compiler that must be used to compile the template, if left empty a default - * Dwoo_Compiler will be used. - * @return string nothing or the template output if $output is true - */ - public function output($tpl, $data = array(), Dwoo_ICompiler $compiler = null) - { - return $this->get($tpl, $data, $compiler, true); - } - - /** - * returns the given template rendered using the provided data and optional compiler - * - * @param mixed $tpl template, can either be a Dwoo_ITemplate object (i.e. Dwoo_Template_File), a valid path to a template, or - * a template as a string it is recommended to provide a Dwoo_ITemplate as it will probably make things faster, - * especially if you render a template multiple times - * @param mixed $data the data to use, can either be a Dwoo_IDataProvider object (i.e. Dwoo_Data) or an associative array. if you're - * rendering the template from cache, it can be left null - * @param Dwoo_ICompiler $compiler the compiler that must be used to compile the template, if left empty a default - * Dwoo_Compiler will be used. - * @param bool $output flag that defines whether the function returns the output of the template (false, default) or echoes it directly (true) - * @return string nothing or the template output if $output is true - */ - public function get($_tpl, $data = array(), $_compiler = null, $_output = false) - { - // a render call came from within a template, so we need a new dwoo instance in order to avoid breaking this one - if ($this->template instanceof Dwoo_ITemplate) { - $proxy = clone $this; - return $proxy->get($_tpl, $data, $_compiler, $_output); - } - - // auto-create template if required - if ($_tpl instanceof Dwoo_ITemplate) { - // valid, skip - } elseif (is_string($_tpl) && file_exists($_tpl)) { - $_tpl = new Dwoo_Template_File($_tpl); - } else { - throw new Dwoo_Exception('Dwoo->get/Dwoo->output\'s first argument must be a Dwoo_ITemplate (i.e. Dwoo_Template_File) or a valid path to a template file', E_USER_NOTICE); - } - - // save the current template, enters render mode at the same time - // if another rendering is requested it will be proxied to a new Dwoo instance - $this->template = $_tpl; - - // load data - if ($data instanceof Dwoo_IDataProvider) { - $this->data = $data->getData(); - } elseif (is_array($data)) { - $this->data = $data; - } else { - throw new Dwoo_Exception('Dwoo->get/Dwoo->output\'s data argument must be a Dwoo_IDataProvider object (i.e. Dwoo_Data) or an associative array', E_USER_NOTICE); - } - - $this->globals['template'] = $_tpl->getName(); - $this->initRuntimeVars($_tpl); - - // try to get cached template - $file = $_tpl->getCachedTemplate($this); - $doCache = $file === true; - $cacheLoaded = is_string($file); - - if ($cacheLoaded === true) { - // cache is present, run it - if ($_output === true) { - include $file; - $this->template = null; - } else { - ob_start(); - include $file; - $this->template = null; - return ob_get_clean(); - } - } else { - // no cache present - if ($doCache === true) { - $dynamicId = uniqid(); - } - - // render template - $compiledTemplate = $_tpl->getCompiledTemplate($this, $_compiler); - $out = include $compiledTemplate; - - // template returned false so it needs to be recompiled - if ($out === false) { - $_tpl->forceCompilation(); - $compiledTemplate = $_tpl->getCompiledTemplate($this, $_compiler); - $out = include $compiledTemplate; - } - - if ($doCache === true) { - $out = preg_replace('/(<%|%>|<\?php|<\?|\?>)/', '', $out); - if (!class_exists('Dwoo_plugin_dynamic', false)) { - $this->getLoader()->loadPlugin('dynamic'); - } - $out = Dwoo_Plugin_dynamic::unescape($out, $dynamicId, $compiledTemplate); - } - - // process filters - foreach ($this->filters as $filter) { - if (is_array($filter) && $filter[0] instanceof Dwoo_Filter) { - $out = call_user_func($filter, $out); - } else { - $out = call_user_func($filter, $this, $out); - } - } - - if ($doCache === true) { - // building cache - $file = $_tpl->cache($this, $out); - - // run it from the cache to be sure dynamics are rendered - if ($_output === true) { - include $file; - // exit render mode - $this->template = null; - } else { - ob_start(); - include $file; - // exit render mode - $this->template = null; - return ob_get_clean(); - } - } else { - // no need to build cache - // exit render mode - $this->template = null; - // output - if ($_output === true) { - echo $out; - } - return $out; - } - } - } - - /** - * re-initializes the globals array before each template run - * - * this method is only callede once when the Dwoo object is created - */ - protected function initGlobals() - { - $this->globals = array - ( - 'version' => self::VERSION, - 'ad' => 'Powered by Dwoo', - 'now' => $_SERVER['REQUEST_TIME'], - 'charset' => $this->charset, - ); - } - - /** - * re-initializes the runtime variables before each template run - * - * override this method to inject data in the globals array if needed, this - * method is called before each template execution - * - * @param Dwoo_ITemplate $tpl the template that is going to be rendered - */ - protected function initRuntimeVars(Dwoo_ITemplate $tpl) - { - $this->runtimePlugins = array(); - $this->scope =& $this->data; - $this->scopeTree = array(); - $this->stack = array(); - $this->curBlock = null; - $this->buffer = ''; - } - - /* - * --------- settings functions --------- - */ - - /** - * adds a custom plugin that is not in one of the plugin directories - * - * @param string $name the plugin name to be used in the templates - * @param callback $callback the plugin callback, either a function name, - * a class name or an array containing an object - * or class name and a method name - * @param bool $compilable if set to true, the plugin is assumed to be compilable - */ - public function addPlugin($name, $callback, $compilable = false) - { - $compilable = $compilable ? self::COMPILABLE_PLUGIN : 0; - if (is_array($callback)) { - if (is_subclass_of(is_object($callback[0]) ? get_class($callback[0]) : $callback[0], 'Dwoo_Block_Plugin')) { - $this->plugins[$name] = array('type'=>self::BLOCK_PLUGIN | $compilable, 'callback'=>$callback, 'class'=>(is_object($callback[0]) ? get_class($callback[0]) : $callback[0])); - } else { - $this->plugins[$name] = array('type'=>self::CLASS_PLUGIN | $compilable, 'callback'=>$callback, 'class'=>(is_object($callback[0]) ? get_class($callback[0]) : $callback[0]), 'function'=>$callback[1]); - } - } elseif (class_exists($callback, false)) { - if (is_subclass_of($callback, 'Dwoo_Block_Plugin')) { - $this->plugins[$name] = array('type'=>self::BLOCK_PLUGIN | $compilable, 'callback'=>$callback, 'class'=>$callback); - } else { - $this->plugins[$name] = array('type'=>self::CLASS_PLUGIN | $compilable, 'callback'=>$callback, 'class'=>$callback, 'function'=>'process'); - } - } elseif (function_exists($callback)) { - $this->plugins[$name] = array('type'=>self::FUNC_PLUGIN | $compilable, 'callback'=>$callback); - } else { - throw new Dwoo_Exception('Callback could not be processed correctly, please check that the function/class you used exists'); - } - } - - /** - * removes a custom plugin - * - * @param string $name the plugin name - */ - public function removePlugin($name) - { - if (isset($this->plugins[$name])) { - unset($this->plugins[$name]); - } - } - - /** - * adds a filter to this Dwoo instance, it will be used to filter the output of all the templates rendered by this instance - * - * @param mixed $callback a callback or a filter name if it is autoloaded from a plugin directory - * @param bool $autoload if true, the first parameter must be a filter name from one of the plugin directories - */ - public function addFilter($callback, $autoload = false) - { - if ($autoload) { - $class = 'Dwoo_Filter_'.$callback; - - if (!class_exists($class, false) && !function_exists($class)) { - try { - $this->getLoader()->loadPlugin($callback); - } catch (Dwoo_Exception $e) { - if (strstr($callback, 'Dwoo_Filter_')) { - throw new Dwoo_Exception('Wrong filter name : '.$callback.', the "Dwoo_Filter_" prefix should not be used, please only use "'.str_replace('Dwoo_Filter_', '', $callback).'"'); - } else { - throw new Dwoo_Exception('Wrong filter name : '.$callback.', when using autoload the filter must be in one of your plugin dir as "name.php" containg a class or function named "Dwoo_Filter_name"'); - } - } - } - - if (class_exists($class, false)) { - $callback = array(new $class($this), 'process'); - } elseif (function_exists($class)) { - $callback = $class; - } else { - throw new Dwoo_Exception('Wrong filter name : '.$callback.', when using autoload the filter must be in one of your plugin dir as "name.php" containg a class or function named "Dwoo_Filter_name"'); - } - - $this->filters[] = $callback; - } else { - $this->filters[] = $callback; - } - } - - /** - * removes a filter - * - * @param mixed $callback callback or filter name if it was autoloaded - */ - public function removeFilter($callback) - { - if (($index = array_search('Dwoo_Filter_'.$callback, $this->filters, true)) !== false) { - unset($this->filters[$index]); - } elseif (($index = array_search($callback, $this->filters, true)) !== false) { - unset($this->filters[$index]); - } else { - $class = 'Dwoo_Filter_' . $callback; - foreach ($this->filters as $index=>$filter) { - if (is_array($filter) && $filter[0] instanceof $class) { - unset($this->filters[$index]); - break; - } - } - } - } - - /** - * adds a resource or overrides a default one - * - * @param string $name the resource name - * @param string $class the resource class (which must implement Dwoo_ITemplate) - * @param callback $compilerFactory the compiler factory callback, a function that must return a compiler instance used to compile this resource, if none is provided. by default it will produce a Dwoo_Compiler object - */ - public function addResource($name, $class, $compilerFactory = null) - { - if (strlen($name) < 2) { - throw new Dwoo_Exception('Resource names must be at least two-character long to avoid conflicts with Windows paths'); - } - - if (!class_exists($class)) { - throw new Dwoo_Exception('Resource class does not exist'); - } - - $interfaces = class_implements($class); - if (in_array('Dwoo_ITemplate', $interfaces) === false) { - throw new Dwoo_Exception('Resource class must implement Dwoo_ITemplate'); - } - - $this->resources[$name] = array('class'=>$class, 'compiler'=>$compilerFactory); - } - - /** - * removes a custom resource - * - * @param string $name the resource name - */ - public function removeResource($name) - { - unset($this->resources[$name]); - if ($name==='file') { - $this->resources['file'] = array('class'=>'Dwoo_Template_File', 'compiler'=>null); - } - } - - /* - * --------- getters and setters --------- - */ - - /** - * sets the loader object to use to load plugins - * - * @param Dwoo_ILoader $loader loader object - */ - public function setLoader(Dwoo_ILoader $loader) - { - $this->loader = $loader; - } - - /** - * returns the current loader object or a default one if none is currently found - * - * @param Dwoo_ILoader - */ - public function getLoader() - { - if ($this->loader === null) { - $this->loader = new Dwoo_Loader($this->getCompileDir()); - } - - return $this->loader; - } - - /** - * returns the custom plugins loaded - * - * used by the Dwoo_ITemplate classes to pass the custom plugins to their Dwoo_ICompiler instance - * - * @return array - */ - public function getCustomPlugins() - { - return $this->plugins; - } - - /** - * returns the cache directory with a trailing DIRECTORY_SEPARATOR - * - * @return string - */ - public function getCacheDir() - { - if ($this->cacheDir === null) { - $this->setCacheDir(dirname(__FILE__).DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR); - } - - return $this->cacheDir; - } - - /** - * sets the cache directory and automatically appends a DIRECTORY_SEPARATOR - * - * @param string $dir the cache directory - */ - public function setCacheDir($dir) - { - $this->cacheDir = rtrim($dir, '/\\').DIRECTORY_SEPARATOR; - if (is_writable($this->cacheDir) === false) { - throw new Dwoo_Exception('The cache directory must be writable, chmod "'.$this->cacheDir.'" to make it writable'); - } - } - - /** - * returns the compile directory with a trailing DIRECTORY_SEPARATOR - * - * @return string - */ - public function getCompileDir() - { - if ($this->compileDir === null) { - $this->setCompileDir(dirname(__FILE__).DIRECTORY_SEPARATOR.'compiled'.DIRECTORY_SEPARATOR); - } - - return $this->compileDir; - } - - /** - * sets the compile directory and automatically appends a DIRECTORY_SEPARATOR - * - * @param string $dir the compile directory - */ - public function setCompileDir($dir) - { - $this->compileDir = rtrim($dir, '/\\').DIRECTORY_SEPARATOR; - if (is_writable($this->compileDir) === false) { - throw new Dwoo_Exception('The compile directory must be writable, chmod "'.$this->compileDir.'" to make it writable'); - } - } - - /** - * returns the default cache time that is used with templates that do not have a cache time set - * - * @return int the duration in seconds - */ - public function getCacheTime() - { - return $this->cacheTime; - } - - /** - * sets the default cache time to use with templates that do not have a cache time set - * - * @param int $seconds the duration in seconds - */ - public function setCacheTime($seconds) - { - $this->cacheTime = (int) $seconds; - } - - /** - * returns the character set used by the string manipulation plugins - * - * the charset is automatically lowercased - * - * @return string - */ - public function getCharset() - { - return $this->charset; - } - - /** - * sets the character set used by the string manipulation plugins - * - * the charset will be automatically lowercased - * - * @param string $charset the character set - */ - public function setCharset($charset) - { - $this->charset = strtolower((string) $charset); - } - - /** - * returns the current template being rendered, when applicable, or null - * - * @return Dwoo_ITemplate|null - */ - public function getTemplate() - { - return $this->template; - } - - /** - * sets the current template being rendered - * - * @param Dwoo_ITemplate $tpl template object - */ - public function setTemplate(Dwoo_ITemplate $tpl) - { - $this->template = $tpl; - } - - /** - * sets the default compiler factory function for the given resource name - * - * a compiler factory must return a Dwoo_ICompiler object pre-configured to fit your needs - * - * @param string $resourceName the resource name (i.e. file, string) - * @param callback $compilerFactory the compiler factory callback - */ - public function setDefaultCompilerFactory($resourceName, $compilerFactory) - { - $this->resources[$resourceName]['compiler'] = $compilerFactory; - } - - /** - * returns the default compiler factory function for the given resource name - * - * @param string $resourceName the resource name - * @return callback the compiler factory callback - */ - public function getDefaultCompilerFactory($resourceName) - { - return $this->resources[$resourceName]['compiler']; - } - - /** - * sets the security policy object to enforce some php security settings - * - * use this if untrusted persons can modify templates - * - * @param Dwoo_Security_Policy $policy the security policy object - */ - public function setSecurityPolicy(Dwoo_Security_Policy $policy = null) - { - $this->securityPolicy = $policy; - } - - /** - * returns the current security policy object or null by default - * - * @return Dwoo_Security_Policy|null the security policy object if any - */ - public function getSecurityPolicy() - { - return $this->securityPolicy; - } - - /** - * sets the object that must be used as a plugin proxy when plugin can't be found - * by dwoo's loader - * - * @param Dwoo_IPluginProxy $pluginProxy the proxy object - */ - public function setPluginProxy(Dwoo_IPluginProxy $pluginProxy) { - $this->pluginProxy = $pluginProxy; - } - - /** - * returns the current plugin proxy object or null by default - * - * @param Dwoo_IPluginProxy|null the proxy object if any - */ - public function getPluginProxy() { - return $this->pluginProxy; - } - - /* - * --------- util functions --------- - */ - - /** - * [util function] checks whether the given template is cached or not - * - * @param Dwoo_ITemplate $tpl the template object - * @return bool - */ - public function isCached(Dwoo_ITemplate $tpl) - { - return is_string($tpl->getCachedTemplate($this)); - } - - /** - * [util function] clears the cached templates if they are older than the given time - * - * @param int $olderThan minimum time (in seconds) required for a cached template to be cleared - * @return int the amount of templates cleared - */ - public function clearCache($olderThan=-1) - { - $cacheDirs = new RecursiveDirectoryIterator($this->getCacheDir()); - $cache = new RecursiveIteratorIterator($cacheDirs); - $expired = time() - $olderThan; - $count = 0; - foreach ($cache as $file) { - if ($cache->isDot() || $cache->isDir() || substr($file, -5) !== '.html') { - continue; - } - if ($cache->getCTime() < $expired) { - $count += unlink((string) $file) ? 1 : 0; - } - } - return $count; - } - - /** - * [util function] fetches a template object of the given resource - * - * @param string $resourceName the resource name (i.e. file, string) - * @param string $resourceId the resource identifier (i.e. file path) - * @param int $cacheTime the cache time setting for this resource - * @param string $cacheId the unique cache identifier - * @param string $compileId the unique compiler identifier - * @return Dwoo_ITemplate - */ - public function templateFactory($resourceName, $resourceId, $cacheTime = null, $cacheId = null, $compileId = null, Dwoo_ITemplate $parentTemplate = null) - { - if (isset($this->resources[$resourceName])) { - // TODO could be changed to $this->resources[$resourceName]['class']::templateFactory(..) in 5.3 maybe - return call_user_func(array($this->resources[$resourceName]['class'], 'templateFactory'), $this, $resourceId, $cacheTime, $cacheId, $compileId, $parentTemplate); - } else { - throw new Dwoo_Exception('Unknown resource type : '.$resourceName); - } - } - - /** - * [util function] checks if the input is an array or an iterator object, optionally it can also check if it's empty - * - * @param mixed $value the variable to check - * @param bool $checkIsEmpty if true, the function will also check if the array is empty, - * and return true only if it's not empty - * @return bool true if it's an array (and not empty) or false if it's not an array (or if it's empty) - */ - public function isArray($value, $checkIsEmpty=false) - { - if (is_array($value) === true) { - if ($checkIsEmpty === false) { - return true; - } else { - return count($value) > 0; - } - } elseif ($value instanceof Iterator) { - if ($checkIsEmpty === false) { - return true; - } elseif ($value instanceof Countable) { - return count($value) > 0; - } else { - $value->rewind(); - return $value->valid(); - } - } elseif ($value instanceof ArrayAccess) { - if ($checkIsEmpty === false) { - return true; - } elseif ($value instanceof Countable) { - return count($value) > 0; - } else { - return $value->offsetExists(0); - } - } - return false; - } - - /** - * [util function] triggers a dwoo error - * - * @param string $message the error message - * @param int $level the error level, one of the PHP's E_* constants - */ - public function triggerError($message, $level=E_USER_NOTICE) - { - if (!($tplIdentifier = $this->template->getResourceIdentifier())) { - $tplIdentifier = $this->template->getResourceName(); - } - trigger_error('Dwoo error (in '.$tplIdentifier.') : '.$message, $level); - } - - /* - * --------- runtime functions --------- - */ - - /** - * [runtime function] adds a block to the block stack - * - * @param string $blockName the block name (without Dwoo_Plugin_ prefix) - * @param array $args the arguments to be passed to the block's init() function - * @return Dwoo_Block_Plugin the newly created block - */ - public function addStack($blockName, array $args=array()) - { - if (isset($this->plugins[$blockName])) { - $class = $this->plugins[$blockName]['class']; - } else { - $class = 'Dwoo_Plugin_'.$blockName; - } - - if ($this->curBlock !== null) { - $this->curBlock->buffer(ob_get_contents()); - ob_clean(); - } else { - $this->buffer .= ob_get_contents(); - ob_clean(); - } - - $block = new $class($this); - - $cnt = count($args); - if ($cnt===0) { - $block->init(); - } elseif ($cnt===1) { - $block->init($args[0]); - } elseif ($cnt===2) { - $block->init($args[0], $args[1]); - } elseif ($cnt===3) { - $block->init($args[0], $args[1], $args[2]); - } elseif ($cnt===4) { - $block->init($args[0], $args[1], $args[2], $args[3]); - } else { - call_user_func_array(array($block,'init'), $args); - } - - $this->stack[] = $this->curBlock = $block; - return $block; - } - - /** - * [runtime function] removes the plugin at the top of the block stack - * - * calls the block buffer() function, followed by a call to end() - * and finally a call to process() - */ - public function delStack() - { - $args = func_get_args(); - - $this->curBlock->buffer(ob_get_contents()); - ob_clean(); - - $cnt = count($args); - if ($cnt===0) { - $this->curBlock->end(); - } elseif ($cnt===1) { - $this->curBlock->end($args[0]); - } elseif ($cnt===2) { - $this->curBlock->end($args[0], $args[1]); - } elseif ($cnt===3) { - $this->curBlock->end($args[0], $args[1], $args[2]); - } elseif ($cnt===4) { - $this->curBlock->end($args[0], $args[1], $args[2], $args[3]); - } else { - call_user_func_array(array($this->curBlock, 'end'), $args); - } - - $tmp = array_pop($this->stack); - - if (count($this->stack) > 0) { - $this->curBlock = end($this->stack); - $this->curBlock->buffer($tmp->process()); - } else { - $this->curBlock = null; - echo $tmp->process(); - } - - unset($tmp); - } - - /** - * [runtime function] returns the parent block of the given block - * - * @param Dwoo_Block_Plugin $block - * @return Dwoo_Block_Plugin or false if the given block isn't in the stack - */ - public function getParentBlock(Dwoo_Block_Plugin $block) - { - $index = array_search($block, $this->stack, true); - if ($index !== false && $index > 0) { - return $this->stack[$index-1]; - } - return false; - } - - /** - * [runtime function] finds the closest block of the given type, starting at the top of the stack - * - * @param string $type the type of plugin you want to find - * @return Dwoo_Block_Plugin or false if no plugin of such type is in the stack - */ - public function findBlock($type) - { - if (isset($this->plugins[$type])) { - $type = $this->plugins[$type]['class']; - } else { - $type = 'Dwoo_Plugin_'.str_replace('Dwoo_Plugin_', '', $type); - } - - $keys = array_keys($this->stack); - while (($key = array_pop($keys)) !== false) { - if ($this->stack[$key] instanceof $type) { - return $this->stack[$key]; - } - } - return false; - } - - /** - * [runtime function] returns a Dwoo_Plugin of the given class - * - * this is so a single instance of every class plugin is created at each template run, - * allowing class plugins to have "per-template-run" static variables - * - * @private - * @param string $class the class name - * @return mixed an object of the given class - */ - public function getObjectPlugin($class) - { - if (isset($this->runtimePlugins[$class])) { - return $this->runtimePlugins[$class]; - } - return $this->runtimePlugins[$class] = new $class($this); - } - - /** - * [runtime function] calls the process() method of the given class-plugin name - * - * @param string $plugName the class plugin name (without Dwoo_Plugin_ prefix) - * @param array $params an array of parameters to send to the process() method - * @return string the process() return value - */ - public function classCall($plugName, array $params = array()) - { - $class = 'Dwoo_Plugin_'.$plugName; - - $plugin = $this->getObjectPlugin($class); - - $cnt = count($params); - if ($cnt===0) { - return $plugin->process(); - } elseif ($cnt===1) { - return $plugin->process($params[0]); - } elseif ($cnt===2) { - return $plugin->process($params[0], $params[1]); - } elseif ($cnt===3) { - return $plugin->process($params[0], $params[1], $params[2]); - } elseif ($cnt===4) { - return $plugin->process($params[0], $params[1], $params[2], $params[3]); - } else { - return call_user_func_array(array($plugin, 'process'), $params); - } - } - - /** - * [runtime function] calls a php function - * - * @param string $callback the function to call - * @param array $params an array of parameters to send to the function - * @return mixed the return value of the called function - */ - public function arrayMap($callback, array $params) - { - if ($params[0] === $this) { - $addThis = true; - array_shift($params); - } - if ((is_array($params[0]) || ($params[0] instanceof Iterator && $params[0] instanceof ArrayAccess))) { - if (empty($params[0])) { - return $params[0]; - } - - // array map - $out = array(); - $cnt = count($params); - - if (isset($addThis)) { - array_unshift($params, $this); - $items = $params[1]; - $keys = array_keys($items); - - if (is_string($callback) === false) { - while (($i = array_shift($keys)) !== null) { - $out[] = call_user_func_array($callback, array(1=>$items[$i]) + $params); - } - } elseif ($cnt===1) { - while (($i = array_shift($keys)) !== null) { - $out[] = $callback($this, $items[$i]); - } - } elseif ($cnt===2) { - while (($i = array_shift($keys)) !== null) { - $out[] = $callback($this, $items[$i], $params[2]); - } - } elseif ($cnt===3) { - while (($i = array_shift($keys)) !== null) { - $out[] = $callback($this, $items[$i], $params[2], $params[3]); - } - } else { - while (($i = array_shift($keys)) !== null) { - $out[] = call_user_func_array($callback, array(1=>$items[$i]) + $params); - } - } - } else { - $items = $params[0]; - $keys = array_keys($items); - - if (is_string($callback) === false) { - while (($i = array_shift($keys)) !== null) { - $out[] = call_user_func_array($callback, array($items[$i]) + $params); - } - } elseif ($cnt===1) { - while (($i = array_shift($keys)) !== null) { - $out[] = $callback($items[$i]); - } - } elseif ($cnt===2) { - while (($i = array_shift($keys)) !== null) { - $out[] = $callback($items[$i], $params[1]); - } - } elseif ($cnt===3) { - while (($i = array_shift($keys)) !== null) { - $out[] = $callback($items[$i], $params[1], $params[2]); - } - } elseif ($cnt===4) { - while (($i = array_shift($keys)) !== null) { - $out[] = $callback($items[$i], $params[1], $params[2], $params[3]); - } - } else { - while (($i = array_shift($keys)) !== null) { - $out[] = call_user_func_array($callback, array($items[$i]) + $params); - } - } - } - return $out; - } else { - return $params[0]; - } - } - - /** - * [runtime function] reads a variable into the given data array - * - * @param string $varstr the variable string, using dwoo variable syntax (i.e. "var.subvar[subsubvar]->property") - * @param mixed $data the data array or object to read from - * @param bool $safeRead if true, the function will check whether the index exists to prevent any notices from being output - * @return mixed - */ - public function readVarInto($varstr, $data, $safeRead = false) - { - if ($data === null) { - return null; - } - - if (is_array($varstr) === false) { - preg_match_all('#(\[|->|\.)?((?:[^.[\]-]|-(?!>))+)\]?#i', $varstr, $m); - } else { - $m = $varstr; - } - unset($varstr); - - while (list($k, $sep) = each($m[1])) { - if ($sep === '.' || $sep === '[' || $sep === '') { - if ((is_array($data) || $data instanceof ArrayAccess) && ($safeRead === false || isset($data[$m[2][$k]]))) { - $data = $data[$m[2][$k]]; - } else { - return null; - } - } else { - if (is_object($data) && ($safeRead === false || isset($data->$m[2][$k]) || is_callable(array($data, '__get')))) { - $data = $data->$m[2][$k]; - } else { - return null; - } - } - } - - return $data; - } - - /** - * [runtime function] reads a variable into the parent scope - * - * @param int $parentLevels the amount of parent levels to go from the current scope - * @param string $varstr the variable string, using dwoo variable syntax (i.e. "var.subvar[subsubvar]->property") - * @return mixed - */ - public function readParentVar($parentLevels, $varstr = null) - { - $tree = $this->scopeTree; - $cur = $this->data; - - while ($parentLevels--!==0) { - array_pop($tree); - } - - while (($i = array_shift($tree)) !== null) { - if (is_object($cur)) { - $cur = $cur->$i; - } else { - $cur = $cur[$i]; - } - } - - if ($varstr!==null) { - return $this->readVarInto($varstr, $cur); - } else { - return $cur; - } - } - - /** - * [runtime function] reads a variable into the current scope - * - * @param string $varstr the variable string, using dwoo variable syntax (i.e. "var.subvar[subsubvar]->property") - * @return mixed - */ - public function readVar($varstr) - { - if (is_array($varstr)===true) { - $m = $varstr; - unset($varstr); - } else { - if (strstr($varstr, '.') === false && strstr($varstr, '[') === false && strstr($varstr, '->') === false) { - if ($varstr === 'dwoo') { - return $this->globals; - } elseif ($varstr === '__' || $varstr === '_root' ) { - return $this->data; - $varstr = substr($varstr, 6); - } elseif ($varstr === '_' || $varstr === '_parent') { - $varstr = '.'.$varstr; - $tree = $this->scopeTree; - $cur = $this->data; - array_pop($tree); - - while (($i = array_shift($tree)) !== null) { - if (is_object($cur)) { - $cur = $cur->$i; - } else { - $cur = $cur[$i]; - } - } - - return $cur; - } - - $cur = $this->scope; - - if (isset($cur[$varstr])) { - return $cur[$varstr]; - } else { - return null; - } - } - - if (substr($varstr, 0, 1) === '.') { - $varstr = 'dwoo'.$varstr; - } - - preg_match_all('#(\[|->|\.)?((?:[^.[\]-]|-(?!>))+)\]?#i', $varstr, $m); - } - - $i = $m[2][0]; - if ($i === 'dwoo') { - $cur = $this->globals; - array_shift($m[2]); - array_shift($m[1]); - switch ($m[2][0]) { - - case 'get': - $cur = $_GET; - break; - case 'post': - $cur = $_POST; - break; - case 'session': - $cur = $_SESSION; - break; - case 'cookies': - case 'cookie': - $cur = $_COOKIE; - break; - case 'server': - $cur = $_SERVER; - break; - case 'env': - $cur = $_ENV; - break; - case 'request': - $cur = $_REQUEST; - break; - case 'const': - array_shift($m[2]); - if (defined($m[2][0])) { - return constant($m[2][0]); - } else { - return null; - } - - } - if ($cur !== $this->globals) { - array_shift($m[2]); - array_shift($m[1]); - } - } elseif ($i === '__' || $i === '_root') { - $cur = $this->data; - array_shift($m[2]); - array_shift($m[1]); - } elseif ($i === '_' || $i === '_parent') { - $tree = $this->scopeTree; - $cur = $this->data; - - while (true) { - array_pop($tree); - array_shift($m[2]); - array_shift($m[1]); - if (current($m[2]) === '_' || current($m[2]) === '_parent') { - continue; - } - - while (($i = array_shift($tree)) !== null) { - if (is_object($cur)) { - $cur = $cur->$i; - } else { - $cur = $cur[$i]; - } - } - break; - } - } else { - $cur = $this->scope; - } - - while (list($k, $sep) = each($m[1])) { - if ($sep === '.' || $sep === '[' || $sep === '') { - if ((is_array($cur) || $cur instanceof ArrayAccess) && isset($cur[$m[2][$k]])) { - $cur = $cur[$m[2][$k]]; - } else { - return null; - } - } elseif ($sep === '->') { - if (is_object($cur)) { - $cur = $cur->$m[2][$k]; - } else { - return null; - } - } else { - return null; - } - } - - return $cur; - } - - /** - * [runtime function] assign the value to the given variable - * - * @param mixed $value the value to assign - * @param string $scope the variable string, using dwoo variable syntax (i.e. "var.subvar[subsubvar]->property") - * @return bool true if assigned correctly or false if a problem occured while parsing the var string - */ - public function assignInScope($value, $scope) - { - $tree =& $this->scopeTree; - $data =& $this->data; - - if (!is_string($scope)) { - return $this->triggerError('Assignments must be done into strings, ('.gettype($scope).') '.var_export($scope, true).' given', E_USER_ERROR); - } - if (strstr($scope, '.') === false && strstr($scope, '->') === false) { - $this->scope[$scope] = $value; - } else { - // TODO handle _root/_parent scopes ? - preg_match_all('#(\[|->|\.)?([^.[\]-]+)\]?#i', $scope, $m); - - $cur =& $this->scope; - $last = array(array_pop($m[1]), array_pop($m[2])); - - while (list($k, $sep) = each($m[1])) { - if ($sep === '.' || $sep === '[' || $sep === '') { - if (is_array($cur) === false) { - $cur = array(); - } - $cur =& $cur[$m[2][$k]]; - } elseif ($sep === '->') { - if (is_object($cur) === false) { - $cur = new stdClass; - } - $cur =& $cur->$m[2][$k]; - } else { - return false; - } - } - - if ($last[0] === '.' || $last[0] === '[' || $last[0] === '') { - if (is_array($cur) === false) { - $cur = array(); - } - $cur[$last[1]] = $value; - } elseif ($last[0] === '->') { - if (is_object($cur) === false) { - $cur = new stdClass; - } - $cur->$last[1] = $value; - } else { - return false; - } - } - } - - /** - * [runtime function] sets the scope to the given scope string or array - * - * @param mixed $scope a string i.e. "level1.level2" or an array i.e. array("level1", "level2") - * @param bool $absolute if true, the scope is set from the top level scope and not from the current scope - * @return array the current scope tree - */ - public function setScope($scope, $absolute = false) - { - $old = $this->scopeTree; - - if (is_string($scope)===true) { - $scope = explode('.', $scope); - } - - if ($absolute===true) { - $this->scope =& $this->data; - $this->scopeTree = array(); - } - - while (($bit = array_shift($scope)) !== null) { - if ($bit === '_' || $bit === '_parent') { - array_pop($this->scopeTree); - $this->scope =& $this->data; - $cnt = count($this->scopeTree); - for ($i=0;$i<$cnt;$i++) - $this->scope =& $this->scope[$this->scopeTree[$i]]; - } elseif ($bit === '__' || $bit === '_root') { - $this->scope =& $this->data; - $this->scopeTree = array(); - } elseif (isset($this->scope[$bit])) { - $this->scope =& $this->scope[$bit]; - $this->scopeTree[] = $bit; - } else { - unset($this->scope); - $this->scope = null; - } - } - - return $old; - } - - /** - * [runtime function] returns the entire data array - * - * @return array - */ - public function getData() - { - return $this->data; - } - - /** - * [runtime function] returns a reference to the current scope - * - * @return &mixed - */ - public function &getScope() - { - return $this->scope; - } - - /** - * Redirects all calls to unexisting to plugin proxy. - * - * @param string Method name - * @param array List of arguments - * @return mixed - */ - public function __call($method, $args) { - $proxy = $this->getPluginProxy(); - if (!$proxy) { - throw new Dwoo_Exception('Call to undefined method '.__CLASS__.'::'.$method.'()'); - } - return call_user_func_array($proxy->getCallback($method), $args); - } -} diff --git a/system/libs/dwoo/Dwoo/Adapters/Agavi/DwooRenderer.php b/system/libs/dwoo/Dwoo/Adapters/Agavi/DwooRenderer.php deleted file mode 100644 index d532ad7f..00000000 --- a/system/libs/dwoo/Dwoo/Adapters/Agavi/DwooRenderer.php +++ /dev/null @@ -1,196 +0,0 @@ - - * - * ro - * rq - * ct - * us - * tm - * rd - * - * true - * %core.lib_dir%/dwoo_plugins - * - * - * - add dwoo's directory to your include path or include dwooAutoload.php yourself - * either through agavi's autoload.xml (with name="Dwoo") or through your index.php - * - * Notes: - * - you can copy the /Dwoo/Adapters/Agavi/dwoo_plugins directory to your agavi app's - * lib directory, or change the plugin_dir parameter in the output_types.xml file. - * these plugins are agavi-specific helpers that shortens the syntax to call common - * agavi helpers (i18n, routing, ..) - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - */ -class DwooRenderer extends AgaviRenderer implements AgaviIReusableRenderer -{ - /** - * @constant string The directory inside the cache dir where templates will - * be stored in compiled form. - */ - const COMPILE_DIR = 'templates'; - - /** - * @constant string The subdirectory inside the compile dir where templates - * will be stored in compiled form. - */ - const COMPILE_SUBDIR = 'dwoo'; - - /** - * @constant string The directory inside the cache dir where cached content - * will be stored. - */ - const CACHE_DIR = 'dwoo'; - - /** - * @var Dwoo Dwoo template engine. - */ - protected $dwoo = null; - - /** - * @var string A string with the default template file extension, - * including the dot. - */ - protected $defaultExtension = '.html'; - - /** - * stores the (optional) plugin directory to add to the Dwoo_Loader - */ - protected $plugin_dir = null; - - /** - * Pre-serialization callback. - * - * Excludes the Dwoo instance to prevent excessive serialization load. - */ - public function __sleep() - { - $keys = parent::__sleep(); - unset($keys[array_search('dwoo', $keys)]); - return $keys; - } - - /** - * Initialize this Renderer. - * - * @param AgaviContext The current application context. - * @param array An associative array of initialization parameters. - */ - public function initialize(AgaviContext $context, array $parameters = array()) - { - parent::initialize($context, $parameters); - - $this->plugin_dir = $this->getParameter('plugin_dir', $this->plugin_dir); - } - - /** - * provides a custom compiler to the dwoo renderer with optional settings - * you can set in the agavi output_types.xml config file - * - * @return Dwoo_Compiler - */ - public function compilerFactory() - { - if (class_exists('Dwoo_Compiler', false) === false) { - include DWOO_DIRECTORY . 'Dwoo/Compiler.php'; - } - $compiler = Dwoo_Compiler::compilerFactory(); - $compiler->setAutoEscape((bool) $this->getParameter('auto_escape', false)); - return $compiler; - } - - /** - * Grab a cleaned up dwoo instance. - * - * @return Dwoo A Dwoo instance. - */ - protected function getEngine() - { - if($this->dwoo) { - return $this->dwoo; - } - - if(!class_exists('Dwoo')) { - if (file_exists(dirname(__FILE__).'/../../../dwooAutoload.php')) { - // file was dropped with the entire dwoo package - require dirname(__FILE__).'/../../../dwooAutoload.php'; - } else { - // assume the dwoo package is in the include path - require 'dwooAutoload.php'; - } - } - - $parentMode = fileperms(AgaviConfig::get('core.cache_dir')); - - $compileDir = AgaviConfig::get('core.cache_dir') . DIRECTORY_SEPARATOR . self::COMPILE_DIR . DIRECTORY_SEPARATOR . self::COMPILE_SUBDIR; - AgaviToolkit::mkdir($compileDir, $parentMode, true); - - $cacheDir = AgaviConfig::get('core.cache_dir') . DIRECTORY_SEPARATOR . self::CACHE_DIR; - AgaviToolkit::mkdir($cacheDir, $parentMode, true); - - $this->dwoo = new Dwoo($compileDir, $cacheDir); - - if (!empty($this->plugin_dir)) { - $this->dwoo->getLoader()->addDirectory($this->plugin_dir); - } - - $this->dwoo->setDefaultCompilerFactory('file', array($this, 'compilerFactory')); - - return $this->dwoo; - } - - /** - * Render the presentation and return the result. - * - * @param AgaviTemplateLayer The template layer to render. - * @param array The template variables. - * @param array The slots. - * @param array Associative array of additional assigns. - * - * @return string A rendered result. - */ - public function render(AgaviTemplateLayer $layer, array &$attributes = array(), array &$slots = array(), array &$moreAssigns = array()) - { - $engine = $this->getEngine(); - - $data = array(); - if($this->extractVars) { - $data = $attributes; - } else { - $data[$this->varName] = &$attributes; - } - - $data[$this->slotsVarName] =& $slots; - - foreach($this->assigns as $key => $getter) { - $data[$key] = $this->context->$getter(); - } - - foreach($moreAssigns as $key => &$value) { - if(isset($this->moreAssignNames[$key])) { - $key = $this->moreAssignNames[$key]; - } - $data[$key] =& $value; - } - - return $engine->get($layer->getResourceStreamIdentifier(), $data); - } -} \ No newline at end of file diff --git a/system/libs/dwoo/Dwoo/Adapters/Agavi/README b/system/libs/dwoo/Dwoo/Adapters/Agavi/README deleted file mode 100644 index 825ce603..00000000 --- a/system/libs/dwoo/Dwoo/Adapters/Agavi/README +++ /dev/null @@ -1,27 +0,0 @@ -// ------------------------ -// Install notes : -// ------------------------ - - - drop dwoo's directory in app/lib/renderer (create if needed) - - - add a renderer to app/config/output_types.xml as such : - - - ro - rq - ct - us - tm - rd - - true - %core.lib_dir%/dwoo_plugins - - - - add the renderer to app/config/autoload.xml as such : - %core.lib_dir%/renderer/dwoo/Dwoo/Adapter/Agavi/DwooRenderer.php - - - you can copy the /Dwoo/Adapters/Agavi/dwoo_plugins directory to your agavi app's - lib directory, or change the plugin_dir parameter in the output_types.xml file. - these plugins are agavi-specific helpers that shortens the syntax to call common - agavi helpers (i18n, routing, ..) diff --git a/system/libs/dwoo/Dwoo/Adapters/Agavi/dwoo_plugins/t.php b/system/libs/dwoo/Dwoo/Adapters/Agavi/dwoo_plugins/t.php deleted file mode 100644 index d501fb0a..00000000 --- a/system/libs/dwoo/Dwoo/Adapters/Agavi/dwoo_plugins/t.php +++ /dev/null @@ -1,32 +0,0 @@ -Agavi specific plugin - * - * uses AgaviTranslationManager to localize a string - * - *
- *  * string : the string to localize
- * 
- * - * Examples: - * - * {t "Hello"} - * {t $header} - * - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -function Dwoo_Plugin_t_compile(Dwoo_Compiler $compiler, $string) -{ - return '$this->data[\'tm\']->_('.$string.')'; -} \ No newline at end of file diff --git a/system/libs/dwoo/Dwoo/Adapters/Agavi/dwoo_plugins/url.php b/system/libs/dwoo/Dwoo/Adapters/Agavi/dwoo_plugins/url.php deleted file mode 100644 index bb8b222d..00000000 --- a/system/libs/dwoo/Dwoo/Adapters/Agavi/dwoo_plugins/url.php +++ /dev/null @@ -1,54 +0,0 @@ -Agavi specific plugin - * - * uses AgaviRouting to create an url - * - *
- *  * route : the route name, optional (by default the current url is returned)
- *  * params : an array with variables to build the route, optional
- *  * options : an array of options to pass to the routing object, optional
- *  * rest : for convenience, you can just pass named parameters that will be used as
- *           the params array, but you must not provide the params array in this case
- * 
- * - * Examples: - * - * {a url("route.name" array(param="Value", param2=$otherVal))}Here is a link{/a} - *
{* without any parameter it just returns the current url *} - * - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -function Dwoo_Plugin_url_compile(Dwoo_Compiler $compiler, $route = null, $params = null, $options = null, array $rest = array()) -{ - if ($params == 'null') { - if (count($rest)) { - $params = array(); - foreach ($rest as $k=>$v) { - if (is_numeric($k)) { - $params[] = $k.'=>'.$v; - } else { - $params[] = '"'.$k.'"=>'.$v; - } - } - $params = 'array('.implode(', ', $params).')'; - } else { - $params = 'array()'; - } - } - if ($options == 'null') { - $options = 'array()'; - } - return '$this->data[\'ro\']->gen('.$route.', '.$params.', '.$options.')'; -} \ No newline at end of file diff --git a/system/libs/dwoo/Dwoo/Adapters/CakePHP/README b/system/libs/dwoo/Dwoo/Adapters/CakePHP/README deleted file mode 100644 index 46a73fc2..00000000 --- a/system/libs/dwoo/Dwoo/Adapters/CakePHP/README +++ /dev/null @@ -1,33 +0,0 @@ -// CakePHP Dwoo bridge - v0.2 -// ------------------------ -// Installation : -// ------------------------ -// 1. Download and install the dwoo library, preferably on the -// 'vendors' directory of CakePHP. However you can place it -// anywhere you want; if you do, make sure to change the App::import -// line in dwoo.php to include the dwoo library properly. -// -// 2. Place this file in the app/views directory, or on cake/libs/view. -// -// 3. Create the app/tmp/dwoo/cache and app/tmp/dwoo/compile directories -// and make sure they are writable. -// ------------------------ -// Usage example : -// ------------------------ - -// In your controller class you need to change the view property to -// use Dwoo at some point in the execution using : - -$this->view = 'Dwoo'; - -// Or you can also override the view property in your AppController class as such : - -class AppController extends Controller { - public $view = 'Dwoo'; -} - -// If you want another template extension (default is .tpl) you must -// edit the dwoo.php file at line 44 and change it to : -$this->ext = ".html"; - -//{include $templatedir."index.tpl"} \ No newline at end of file diff --git a/system/libs/dwoo/Dwoo/Adapters/CakePHP/dwoo.php b/system/libs/dwoo/Dwoo/Adapters/CakePHP/dwoo.php deleted file mode 100644 index 4a247e3f..00000000 --- a/system/libs/dwoo/Dwoo/Adapters/CakePHP/dwoo.php +++ /dev/null @@ -1,143 +0,0 @@ - 'dwoo/dwooAutoload.php')); - -/** - * Dwoo adapter for CakePHP - * - * Based on SmartyView by Mark John S. Buenconsejo - * - * 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 Mark John S. Buenconsejo - * @author Giangi - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License - * @link http://dwoo.org/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - */ -class DwooView extends View -{ - protected $_sv_template_dir; - protected $_sv_layout_dir; - protected $_sv_compile_dir; - protected $_sv_cache_dir; - protected $_sv_compile_id; - - protected $_dwoo; - - public $sv_processedTpl; - - public function __construct(&$controller) - { - parent::__construct($controller); - - $this->ext = '.tpl'; - - $this->_sv_template_dir = array - ( - VIEWS . $this->viewPath . DS . $this->subDir, - VIEWS . $this->viewPath, - VIEWS - ); - - $this->_sv_layout_dir = array - ( - LAYOUTS . $this->subDir, - VIEWS - ); - - $this->_sv_compile_dir = TMP . 'dwoo' . DS . 'compile'; - $this->_sv_cache_dir = TMP . 'dwoo' . DS . 'cache'; - - $this->_dwoo = new Dwoo($this->_sv_compile_dir, $this->_sv_cache_dir); - - $this->_sv_compile_id = $controller->name; - - $this->_dwoo->sv_this = $this; - $this->_dwoo->setSecurityPolicy(); - - return; - } - - /** - * changes the template directory - */ - public function setTemplateDir($path = VIEW) { - $old = $this->_sv_template_dir; - $this->_sv_template_dir = $path; - - return $old; - } - - public function getTemplateDir() { - return $this->_sv_template_dir ; - } - - public function _render($___viewFn, $___data_for_view, $___play_safe = true, $loadHelpers = true) - { - // let's determine if this is a layout call or a template call - // and change the template dir accordingly - $layout = false; - if(isset($___data_for_view['content_for_layout'])) { - $this->_sv_template_dir = $this->_sv_layout_dir; - $layout = true; - } - - $tpl = new Dwoo_Template_File($___viewFn); - $data = $___data_for_view; - - $data['view'] = $this; - - if ($this->helpers != false && $loadHelpers === true) { - $loadedHelpers = array(); - $loadedHelpers = $this->_loadHelpers($loadedHelpers, $this->helpers); - - foreach (array_keys($loadedHelpers) as $helper) { - $camelBackedHelper = strtolower(substr($helper, 0, 1)) . substr($helper, 1); - - ${$camelBackedHelper} = $loadedHelpers[$helper]; - - if (is_array(${$camelBackedHelper}->helpers) && !empty(${$camelBackedHelper}->helpers)) { - $subHelpers = ${$camelBackedHelper}->helpers; - foreach ($subHelpers as $subHelper) { - ${$camelBackedHelper}->{$subHelper} = $loadedHelpers[$subHelper]; - } - } - - if(isset($this->passedArgs)) { - ${$camelBackedHelper}->passedArgs = $this->passedArgs; - } - - $this->loaded[$camelBackedHelper] = ${$camelBackedHelper}; - - $data[$camelBackedHelper] = ${$camelBackedHelper}; - } - } - - if ($this->helpers != false && $loadHelpers === true) { - foreach ($loadedHelpers as $helper) { - if (is_object($helper)) { - if (is_subclass_of($helper, 'Helper') || is_subclass_of($helper, 'helper')) { - $helper->beforeRender(); - } - } - } - } - - return $this->_dwoo->get($tpl, $data); - } - - public function get(){ - return $this->_dwoo; - } -} diff --git a/system/libs/dwoo/Dwoo/Adapters/CodeIgniter/README b/system/libs/dwoo/Dwoo/Adapters/CodeIgniter/README deleted file mode 100644 index 1cf086f4..00000000 --- a/system/libs/dwoo/Dwoo/Adapters/CodeIgniter/README +++ /dev/null @@ -1,36 +0,0 @@ -CodeIgniter/Dwoo adapater -------------------------- -Integration of Dwoo into Codeigniter (1.7.0 >) - -Links: -Dwoo - http://dwoo.org -CodeIgniter - http://codeigniter.com - -Installation: -1) Extract package into your application directory (i.e. $webroot/application or - $webroot/system/application) -2) Change the parameters in config/dwootemplate.php -3) Create the compile and cache directory you set in your config file in step 2 - and give it the correct rights (chmod 777 when on *nix) -4) Extract/copy the Dwoo package into application/libraries/dwoo -5) Browse to : http://[yoururl]/dwoowelcome - - -Version info -1.0.2 [11-03-2009] Fixed a problem with $data attribute (which Dwoo also used) -1.0.1 [12-11-2008] Removed some & in the dwootemplate - Changed licencse - Changed 'output' in 'get' in the dwootemplate (line 122) -1.0.0 [11-11-2008] Initial release - - -Questions/Remarks? -mail to: stefan.verstege@newmedia.nl -IM me on GTALK: verstege@gmail.com -Contact me on the Dwoo forums: stefanv - ----------[ copyright notice ]----------------------------------------------------------------------- -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. - -License http://dwoo.org/LICENSE Modified BSD License \ No newline at end of file diff --git a/system/libs/dwoo/Dwoo/Adapters/CodeIgniter/config/dwootemplate.php b/system/libs/dwoo/Dwoo/Adapters/CodeIgniter/config/dwootemplate.php deleted file mode 100644 index 0fb0f415..00000000 --- a/system/libs/dwoo/Dwoo/Adapters/CodeIgniter/config/dwootemplate.php +++ /dev/null @@ -1,12 +0,0 @@ -load->library('Dwootemplate'); - $this->dwootemplate->assign('itshowlate', date('H:i:s')); - $this->dwootemplate->display('dwoowelcome.tpl'); - } -} \ No newline at end of file diff --git a/system/libs/dwoo/Dwoo/Adapters/CodeIgniter/libraries/Dwootemplate.php b/system/libs/dwoo/Dwoo/Adapters/CodeIgniter/libraries/Dwootemplate.php deleted file mode 100644 index 68d58efd..00000000 --- a/system/libs/dwoo/Dwoo/Adapters/CodeIgniter/libraries/Dwootemplate.php +++ /dev/null @@ -1,172 +0,0 @@ - - * @copyright Copyright (c) 2008, Stefan Verstege - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://www.newmedia.nl/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - * - * @uses the dwoo package from http://dwoo.org - */ -class Dwootemplate extends Dwoo { - protected $dwoo_data = array(); - - /** - * Constructor for the DwooTemplate engine - * - */ - public function __construct() { - // Call parents constructor - parent::__construct(); - - // Set the config settings - $this->initialize(); - - // Assign some defaults to dwoo - $CI = get_instance(); - $this->dwoo_data = new Dwoo_Data(); - $this->dwoo_data->js_files = array(); - $this->dwoo_data->css_files = array(); - $this->dwoo_data->CI = $CI; - $this->dwoo_data->site_url = $CI->config->site_url(); // so we can get the full path to CI easily - $this->dwoo_data->uniqid = uniqid(); - $this->dwoo_data->timestamp = mktime(); - - log_message('debug', "Dwoo Template Class Initialized"); - } - - - /** - * Assign data to dwoo data object - * - * @param string $key - * @param mixed $value - */ - public function assign($key, $value) { - $this->dwoo_data->$key = $value; - } - - - /** - * Add Javascript files to template - * - * @param string $js - */ - public function add_js($js) { - $current = $this->dwoo_data->js_files; - $current[] = $js; - $this->dwoo_data->js_files = $current; - } - - - /** - * Add Css stylesheets to template - * - * @param string $css - */ - public function add_css($css) { - $current = $this->dwoo_data->css_files; - $current[] = $css; - $this->dwoo_data->css_files = $current; - } - - - /** - * Display or return the compiled template - * Since we assign the results to the standard CI output module - * you can also use the helper from CI in your templates!! - * - * @param string $sTemplate - * @param boolean $return - * @return mixed - */ - public function display($sTemplate, $return = FALSE) { - // Start benchmark - $CI = get_instance(); - $CI->benchmark->mark('dwoo_parse_start'); - - // Check if file exists - if ( !file_exists($this->template_dir . $sTemplate ) ) { - $message = sprintf('Template file \'%s\' not found.', $sTemplate); - show_error($message); - log_message('error', $message); - } - - // Create new template - $tpl = new Dwoo_Template_File($this->template_dir . $sTemplate); - - // render the template - $template = $this->get($tpl, $this->dwoo_data); - - // Finish benchmark - $CI->benchmark->mark('dwoo_parse_end'); - - // Return results or not ? - if ($return == FALSE) { - $CI->output->final_output = $template; - } else { - return $template; - } - } - - - /** - * Toggle Codeigniter profiler on/off - * - */ - public function enable_profiler($toggle = TRUE) { - $CI = get_instance(); - $CI->output->enable_profiler($toggle); - } - - - /** - * Set http header - * - * @example $this->output->set_header("HTTP/1.1 200 OK"); - * @example $this->output->set_header('Last-Modified: '.gmdate('D, d M Y H:i:s', $last_update).' GMT'); - * @param string $header - */ - public function set_header($header) { - $CI = get_instance(); - $CI->output->set_header($header); - } - - - /** - * Set status header - * - * @example $this->output->set_status_header('401'); - * @example // Sets the header as: Unauthorized - * @param string $header - */ - public function set_status_header($header) { - $CI = get_instance(); - $CI->output->set_status_header($header); - } - - - /** - * Assign the dwootemplate config items to the instance - * - */ - private function initialize() { - $CI = get_instance(); - $CI->config->load('dwootemplate', TRUE); - $config = $CI->config->item('dwootemplate'); - foreach ($config as $key => $val) { - $this->$key = $val; - } - } -} \ No newline at end of file diff --git a/system/libs/dwoo/Dwoo/Adapters/CodeIgniter/views/dwoowelcome.tpl b/system/libs/dwoo/Dwoo/Adapters/CodeIgniter/views/dwoowelcome.tpl deleted file mode 100644 index 95cf53ad..00000000 --- a/system/libs/dwoo/Dwoo/Adapters/CodeIgniter/views/dwoowelcome.tpl +++ /dev/null @@ -1,31 +0,0 @@ -{extends "page.tpl"} - -{block "title"} -Welcome to Dwoo-ed CodeIgniter -{/block} - -{block "content"} -

Welcome to Dwoo-ed CodeIgniter!

- -

The page you are looking at is being generated dynamically by CodeIgniter in combination with the 'Smarty-killer' Dwoo template engine. -The page is rendered at {$itshowlate} by the Dwoo_compiler.

- -

If you would like to edit this page you'll find it located at:

-application/views/dwoowelcome.tpl - -

The corresponding controller for this page is found at:

-application/controllers/dwoowelcome.php - -

The library for Dwoo integration can be found at:

-application/libraries/Dwootemplate.php - -

If you are exploring Dwoo for the very first time, you should start by reading the {anchor uri='http://dwoo.org/' title='Dwoo website'}.

-

If you are exploring CodeIgniter for the very first time, you should start by reading the {anchor uri='http://codeigniter.com/user_guide/' title='User Guide'}.

- -
-Usage:
-$this->load->library('Dwootemplate');
-$this->dwootemplate->assign('test', 'test');
-$this->dwootemplate->display('dwoowelcome.tpl');
-
-{/block} \ No newline at end of file diff --git a/system/libs/dwoo/Dwoo/Adapters/CodeIgniter/views/page.tpl b/system/libs/dwoo/Dwoo/Adapters/CodeIgniter/views/page.tpl deleted file mode 100644 index 42a6bfcd..00000000 --- a/system/libs/dwoo/Dwoo/Adapters/CodeIgniter/views/page.tpl +++ /dev/null @@ -1,57 +0,0 @@ - - -{block "title"}Here come the title{/block} - - - - -{block "content"}Here comes the content{/block} - - \ No newline at end of file diff --git a/system/libs/dwoo/Dwoo/Adapters/ZendFramework/PluginProxy.php b/system/libs/dwoo/Dwoo/Adapters/ZendFramework/PluginProxy.php deleted file mode 100644 index d6beeb4c..00000000 --- a/system/libs/dwoo/Dwoo/Adapters/ZendFramework/PluginProxy.php +++ /dev/null @@ -1,96 +0,0 @@ - - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Denis Arh, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Adapters_ZendFramework_PluginProxy implements Dwoo_IPluginProxy -{ - /** - * reference to the zend view owning this proxy - * - * @var Zend_View_Interface - */ - public $view; - - /** - * Dwoo_Adapters_ZendFramework_PluginProxy's constructor. - * - * @param Zend_View_Interface $view - */ - public function __construct(Zend_View_Interface $view) { - $this->view = $view; - } - - /** - * Called from Dwoo_Compiler to check if the requested plugin is available - * - * @param string $name - * @return bool - */ - public function handles($name) { - try { - $this->view->getHelper($name); - } catch (Zend_Loader_PluginLoader_Exception $e) { - return false; - } - - return true; - } - - /** - * returns the code (as a string) to call the plugin - * (this will be executed at runtime inside the Dwoo class) - * - * @param string $name the plugin name - * @param array $params a parameter array, array key "*" is the rest array - * @return string - */ - public function getCode($name, $params) { - return '$this->getPluginProxy()->view->'. $name .'('.Dwoo_Compiler::implode_r($params).')'; - } - - /** - * returns a callback to the plugin, this is used with the reflection API to - * find out about the plugin's parameter names etc. - * - * should you need a rest array (i.e. for ZendFramework helpers) without the - * possibility to edit the plugin's code, you can provide a callback to some - * other function with the correct parameter signature, i.e. : - * - * return array($this, "callbackHelper"); - * // and callbackHelper would be as such: - * public function callbackHelper(array $rest=array()){} - * - * - * @param string $name the plugin name - * @return callback - */ - public function getCallback($name) { - return array($this->view->getHelper($name), $name); - } - - /** - * returns some code that will check if the plugin is loaded and if not load it - * this is optional, if your plugins are autoloaded or whatever, just return an - * empty string - * - * @param string $name the plugin name - * @return string - */ - public function getLoader($name) { - return ''; - } -} \ No newline at end of file diff --git a/system/libs/dwoo/Dwoo/Adapters/ZendFramework/README b/system/libs/dwoo/Dwoo/Adapters/ZendFramework/README deleted file mode 100644 index 51d70943..00000000 --- a/system/libs/dwoo/Dwoo/Adapters/ZendFramework/README +++ /dev/null @@ -1,32 +0,0 @@ -// ------------------------ -// Usage example : -// ------------------------ -// Note that you might need to manually include 'lib/Dwoo.php', -// 'lib/Dwoo/Adapters/ZendFramework/View.php' and -// 'lib/Dwoo/Adapters/ZendFramework/PluginProxy.php' for this to -// work as expected, depending on your ZF setup -// -// If anyone writes a more advanced how-to please let me know -// ------------------------ - -$view = new Dwoo_Adapters_ZendFramework_View(array( - 'compileDir' => 'path/to/compile_dir' // set to null or remove this line to use defaults - 'cacheDir' => 'path/to/cache_dir' // set to null or remove this line to use defaults -)); - -// This allows you to use ZF's helpers as if they were Dwoo plugins (i.e. {doctype} will call the doctype helper) - -$view->setPluginProxy(new Dwoo_Adapters_ZendFramework_PluginProxy(new Zend_View())); - - -// 1. example - used with the Zend Controller - -$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer($view); - -Zend_Controller_Action_HelperBroker::addHelper($viewRenderer); - - -// 2. example - used manually - -$view->assign('foo', 'bar'); -$view->display('foobar.phtml'); \ No newline at end of file diff --git a/system/libs/dwoo/Dwoo/Adapters/ZendFramework/View.php b/system/libs/dwoo/Dwoo/Adapters/ZendFramework/View.php deleted file mode 100644 index faa840cf..00000000 --- a/system/libs/dwoo/Dwoo/Adapters/ZendFramework/View.php +++ /dev/null @@ -1,512 +0,0 @@ - - * @author Stephan Wentz - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - */ -class Dwoo_Adapters_ZendFramework_View extends Zend_View_Abstract -{ - /** - * @var Dwoo - */ - protected $_engine = null; - - /** - * @var Dwoo_Data - */ - protected $_dataProvider = null; - - /** - * @var Dwoo_Compiler - */ - protected $_compiler = null; - - /** - * Changing Filter's scope to play nicely - * - * @var array - */ - protected $_filter = array(); - - - /** - * @var string - */ - protected $_templateFileClass = 'Dwoo_Template_File'; - - /** - * @var array - */ - protected $_templateFileSettings = array(); - - /** - * @var Dwoo_IPluginProxy - */ - protected $_pluginProxy = null; - - /** - * Constructor method. - * See setOptions for $opt details - * - * @see setOptions - * @param array|Zend_Config List of options or Zend_Config instance - */ - public function __construct($opt = array()) - { - - if (is_array($opt)) { - $this->setOptions($opt); - } elseif ($opt instanceof Zend_Config) { - $this->setConfig($opt); - } - - $this->init(); - } - - /** - * Set object state from options array - * - engine = engine class name|engine object|array of options for engine - * - dataProvider = data provider class name|data provider object|array of options for data provider - * - compiler = compiler class name|compiler object|array of options for compiler - * - templateFile = - * - * Array of options: - * - type class name or object for engine, dataProvider or compiler - * - any set* method (compileDir for setCompileDir ...) - * - * @param array $options - * @return Dwoo_Adapters_ZendFramework_View - */ - public function setOptions(array $opt = array()) - { - // BC checks - // TODO remove in 1.1 - if (isset($opt['compileDir']) || isset($opt['compile_dir'])) { - trigger_error('Dwoo ZF Adapter: the compile dir should be set in the $options[\'engine\'][\'compileDir\'] value the adapter settings', E_USER_WARNING); - } - - if (isset($opt['cacheDir']) || isset($opt['cache_dir'])) { - trigger_error('Dwoo ZF Adapter: the cache dir should be set in the $options[\'engine\'][\'cacheDir\'] value the adapter settings', E_USER_WARNING); - } - // end BC - - // Making sure that everything is loaded. - $classes = array('engine', 'dataProvider', 'compiler'); - - // Setting options to Dwoo objects... - foreach ($opt as $type => $settings) { - if (!method_exists($this, 'set' . $type)) { - throw new Dwoo_Exception("Unknown type $type"); - } - - if (is_string($settings) || is_object($settings)) { - call_user_func(array($this, 'set' . $type), $settings); - } elseif (is_array($settings)) { - // Set requested class - if (array_key_exists('type', $settings)) { - call_user_func(array($this, 'set' . $type), $settings['type']); - } - - if (in_array($type, $classes)) { - // Call get so that the class is initialized - $rel = call_user_func(array($this, 'get' . $type)); - - // Call set*() methods so that all the settings are set. - foreach ($settings as $method => $value) { - if (method_exists($rel, 'set' . $method)) { - call_user_func(array($rel, 'set' . $method), $value); - } - } - } elseif ('templateFile' == $type) { - // Remember the settings for the templateFile - $this->_templateFileSettings = $settings; - } - } - } - } - - /** - * Set object state from Zend_Config object - * - * @param Zend_Config $config - * @return Dwoo_Adapters_ZendFramework_View - */ - public function setConfig(Zend_Config $config) - { - return $this->setOptions($config->toArray()); - } - - /** - * Called before template rendering - * - * Binds plugin proxy to the Dwoo. - * - * @see Dwoo_Adapters_ZendFramework_View::getPluginProxy(); - * @see Dwoo::setPluginProxy(); - */ - protected function preRender() - { - $this->getEngine()->setPluginProxy($this->getPluginProxy()); - } - - /** - * Wraper for Dwoo_Data::__set() - * allows to assign variables using the object syntax - * - * @see Dwoo_Data::__set() - * @param string $name the variable name - * @param string $value the value to assign to it - */ - public function __set($name, $value) - { - $this->getDataProvider()->__set($name, $value); - } - - /** - * Sraper for Dwoo_Data::__get() allows to read variables using the object - * syntax - * - * @see Dwoo_Data::__get() - * @param string $name the variable name - * @return mixed - */ - public function __get($name) - { - return $this->getDataProvider()->__get($name); - } - - /** - * Wraper for Dwoo_Data::__isset() - * supports calls to isset($dwooData->var) - * - * @see Dwoo_Data::__isset() - * @param string $name the variable name - */ - public function __isset($name) - { - return $this->getDataProvider()->__isset($name); - } - - /** - * Wraper for Dwoo_Data::_unset() - * supports unsetting variables using the object syntax - * - * @see Dwoo_Data::__unset() - * @param string $name the variable name - */ - public function __unset($name) - { - $this->getDataProvider()->__unset($name); - } - - /** - * Catches clone request and clones data provider - */ - public function __clone() { - $this->setDataProvider(clone $this->getDataProvider()); - } - - /** - * Returns plugin proxy interface - * - * @return Dwoo_IPluginProxy - */ - public function getPluginProxy() - { - if (!$this->_pluginProxy) { - $this->_pluginProxy = new Dwoo_Adapters_ZendFramework_PluginProxy($this); - } - - return $this->_pluginProxy; - } - - /** - * Sets plugin proxy - * - * @param Dwoo_IPluginProxy - * @return Dwoo_Adapters_ZendFramework_View - */ - public function setPluginProxy(Dwoo_IPluginProxy $pluginProxy) - { - $this->_pluginProxy = $pluginProxy; - return $this; - } - - /** - * Sets template engine - * - * @param string|Dwoo Object or name of the class - */ - public function setEngine($engine) - { - // if param given as an object - if ($engine instanceof Dwoo) { - $this->_engine = $engine; - } - // - elseif (is_subclass_of($engine, 'Dwoo') || 'Dwoo' === $engine) { - $this->_engine = new $engine(); - } - else { - throw new Dwoo_Exception("Custom engine must be a subclass of Dwoo"); - } - } - - /** - * Return the Dwoo template engine object - * - * @return Dwoo - */ - public function getEngine() - { - if (null === $this->_engine) { - $this->_engine = new Dwoo(); - } - - return $this->_engine; - } - - /** - * Sets Dwoo data object - * - * @param string|Dwoo_Data Object or name of the class - */ - public function setDataProvider($data) - { - if ($data instanceof Dwoo_IDataProvider) { - $this->_dataProvider = $data; - } - elseif (is_subclass_of($data, 'Dwoo_Data') || 'Dwoo_Data' == $data) { - $this->_dataProvider = new $data(); - } - else { - throw new Dwoo_Exception("Custom data provider must be a subclass of Dwoo_Data or instance of Dwoo_IDataProvider"); - } - } - - /** - * Return the Dwoo data object - * - * @return Dwoo_Data - */ - public function getDataProvider() - { - if (null === $this->_dataProvider) { - $this->_dataProvider = new Dwoo_Data; - } - - return $this->_dataProvider; - } - - - /** - * Sets Dwoo compiler - * - * @param string|Dwoo_Compiler Object or name of the class - */ - public function setCompiler($compiler) - { - - // if param given as an object - if ($compiler instanceof Dwoo_ICompiler) { - $this->_compiler = $compiler; - } - // if param given as a string - elseif (is_subclass_of($compiler, 'Dwoo_Compiler') || 'Dwoo_Compiler' == $compiler) { - $this->_compiler = new $compiler; - } - else { - throw new Dwoo_Exception("Custom compiler must be a subclass of Dwoo_Compiler or instance of Dwoo_ICompiler"); - } - } - - /** - * Return the Dwoo compiler object - * - * @return Dwoo_Data - */ - public function getCompiler() - { - if (null === $this->_compiler) { - $this->_compiler = Dwoo_Compiler::compilerFactory(); - } - - return $this->_compiler; - } - - /** - * Initializes Dwoo_ITemplate type of class and sets properties from _templateFileSettings - * - * @param string Template location - * @return Dwoo_ITemplate - */ - public function getTemplateFile($template) { - $templateFileClass = $this->_templateFileClass; - - $dwooTemplateFile = new $templateFileClass($template); - - if (!($dwooTemplateFile instanceof Dwoo_ITemplate)) { - throw new Dwoo_Exception("Custom templateFile class must be a subclass of Dwoo_ITemplate"); - } - - foreach ($this->_templateFileSettings as $method => $value) { - if (method_exists($dwooTemplateFile, 'set' . $method)) { - call_user_func(array($dwooTemplateFile, 'set' . $method), $value); - } - } - - return $dwooTemplateFile; - } - - /** - * Dwoo_ITemplate type of class - * - * @param string Name of the class - * @return void - */ - public function setTemplateFile($tempateFileClass) { - $this->_templateFileClass = $tempateFileClass; - } - - /** - * Passes data to Dwoo_Data object - * - * @see Dwoo_Data::assign() - * @param array|string $name - * @param mixed $val - * @return Dwoo_Adapters_ZendFramework_View - */ - public function assign($name, $val = null) - { - $this->getDataProvider()->assign($name, $val); - return $this; - } - - /** - * Return list of all assigned variables - * - * @return array - */ - public function getVars() - { - return $this->_dataProvider->getData(); - } - - /** - * Clear all assigned variables - * - * Clears all variables assigned to Zend_View either via {@link assign()} or - * property overloading ({@link __get()}/{@link __set()}). - * - * @return void - * @return Dwoo_Adapters_ZendFramework_View - */ - public function clearVars() - { - $this->getDataProvider()->clear(); - return $this; - } - - /** - * Wraper for parent's render method so preRender method - * can be called (that will bind the plugin proxy to the - * engine. - * - * @see Zend_View_Abstract::render - * @return string The script output. - */ - public function render($name) - { - $this->preRender(); - return parent::render($name); - } - - /** - * Processes a view script and outputs it. Output is then - * passed through filters. - * - * @param string $name The script script name to process. - * @return string The script output. - */ - public function _run() - { - echo $this->_engine->get( - $this->getTemplateFile(func_get_arg(0)), - $this->getDataProvider(), - $this->getCompiler() - ); - } - - /** - * Add plugin path - * - * @param string $dir Directory - * @return Dwoo_Adapters_ZendFramework_View - */ - public function addPluginDir($dir) - { - $this->getEngine()->getLoader()->addDirectory($dir); - return $this; - } - - /** - * Set compile path - * - * @param string $dir Directory - * @return Dwoo_Adapters_ZendFramework_View - */ - public function setCompileDir($dir) - { - $this->getEngine()->setCompileDir($dir); - return $this; - } - - /** - * Set cache path - * - * @param string $dir Directory - * @return Dwoo_Adapters_ZendFramework_View - */ - public function setCacheDir($dir) - { - $this->getEngine()->setCacheDir($dir); - return $this; - } - - /** - * Set cache lifetime - * - * @param string $seconds Lifetime in seconds - * @return Dwoo_Adapters_ZendFramework_View - */ - public function setCacheLifetime($seconds) - { - $this->getEngine()->setCacheTime($seconds); - return $this; - } - - /** - * Set charset - * - * @param string $charset - * @return Dwoo_Adapters_ZendFramework_View - */ - public function setCharset($charset) - { - $this->_engine->setCharset($charset); - return $this; - } -} \ No newline at end of file diff --git a/system/libs/dwoo/Dwoo/Block/Plugin.php b/system/libs/dwoo/Dwoo/Block/Plugin.php deleted file mode 100644 index 5f937360..00000000 --- a/system/libs/dwoo/Dwoo/Block/Plugin.php +++ /dev/null @@ -1,103 +0,0 @@ -init() method, it will receive the parameters that - * are in the template code and is called when the block starts - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -abstract class Dwoo_Block_Plugin extends Dwoo_Plugin -{ - /** - * stores the contents of the block while it runs - * - * @var string - */ - protected $buffer = ''; - - /** - * buffers input, override only if necessary - * - * @var string $input the content that must be buffered - */ - public function buffer($input) - { - $this->buffer .= $input; - } - - // initialization code, receives the parameters from {block param1 param2} - // public function init($arg, $arg, ...); - - /** - * called when the block ends, this is most of the time followed right away by a call - * of process() but not always, so this should be used to do any shutdown operations on the - * block object, if required. - */ - public function end() - { - } - - /** - * called when the block output is required by a parent block - * - * this must read $this->buffer and return it processed - * - * @return string - */ - public function process() - { - return $this->buffer; - } - - /** - * called at compile time to define what the block should output in the compiled template code, happens when the block is declared - * - * basically this will replace the {block arg arg arg} tag in the template - * - * @param Dwoo_Compiler $compiler the compiler instance that calls this function - * @param array $params an array containing original and compiled parameters - * @param string $prepend that is just meant to allow a child class to call - * parent::postProcessing($compiler, $params, "foo();") to add a command before the - * default commands are executed - * @param string $append that is just meant to allow a child class to call - * parent::postProcessing($compiler, $params, null, "foo();") to add a command after the - * default commands are executed - * @param string $type the type is the plugin class name used - */ - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - return Dwoo_Compiler::PHP_OPEN.$prepend.'$this->addStack("'.$type.'", array('.Dwoo_Compiler::implode_r($compiler->getCompiledParams($params)).'));'.$append.Dwoo_Compiler::PHP_CLOSE; - } - - /** - * called at compile time to define what the block should output in the compiled template code, happens when the block is ended - * - * basically this will replace the {/block} tag in the template - * - * @see preProcessing - * @param Dwoo_Compiler $compiler the compiler instance that calls this function - * @param array $params an array containing original and compiled parameters, see preProcessing() for more details - * @param string $prepend that is just meant to allow a child class to call - * parent::postProcessing($compiler, $params, "foo();") to add a command before the - * default commands are executed - * @param string $append that is just meant to allow a child class to call - * parent::postProcessing($compiler, $params, null, "foo();") to add a command after the - * default commands are executed - * @param string $content the entire content of the block being closed - */ - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - return $content . Dwoo_Compiler::PHP_OPEN.$prepend.'$this->delStack();'.$append.Dwoo_Compiler::PHP_CLOSE; - } -} diff --git a/system/libs/dwoo/Dwoo/Compilation/Exception.php b/system/libs/dwoo/Dwoo/Compilation/Exception.php deleted file mode 100644 index 863c7979..00000000 --- a/system/libs/dwoo/Dwoo/Compilation/Exception.php +++ /dev/null @@ -1,38 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Compilation_Exception extends Dwoo_Exception -{ - protected $compiler; - protected $template; - - public function __construct(Dwoo_Compiler $compiler, $message) - { - $this->compiler = $compiler; - $this->template = $compiler->getDwoo()->getTemplate(); - parent::__construct('Compilation error at line '.$compiler->getLine().' in "'.$this->template->getResourceName().':'.$this->template->getResourceIdentifier().'" : '.$message); - } - - public function getCompiler() - { - return $this->compiler; - } - - public function getTemplate() - { - return $this->template; - } -} diff --git a/system/libs/dwoo/Dwoo/Compiler.php b/system/libs/dwoo/Dwoo/Compiler.php deleted file mode 100644 index caf0f798..00000000 --- a/system/libs/dwoo/Dwoo/Compiler.php +++ /dev/null @@ -1,3086 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - */ -class Dwoo_Compiler implements Dwoo_ICompiler -{ - /** - * constant that represents a php opening tag - * - * use it in case it needs to be adjusted - * - * @var string - */ - const PHP_OPEN = ""; - - /** - * boolean flag to enable or disable debugging output - * - * @var bool - */ - public $debug = false; - - /** - * left script delimiter - * - * @var string - */ - protected $ld = '{'; - - /** - * left script delimiter with escaped regex meta characters - * - * @var string - */ - protected $ldr = '\\{'; - - /** - * right script delimiter - * - * @var string - */ - protected $rd = '}'; - - /** - * right script delimiter with escaped regex meta characters - * - * @var string - */ - protected $rdr = '\\}'; - - /** - * defines whether the nested comments should be parsed as nested or not - * - * defaults to false (classic block comment parsing as in all languages) - * - * @var bool - */ - protected $allowNestedComments = false; - - /** - * defines whether opening and closing tags can contain spaces before valid data or not - * - * turn to true if you want to be sloppy with the syntax, but when set to false it allows - * to skip javascript and css tags as long as they are in the form "{ something", which is - * nice. default is false. - * - * @var bool - */ - protected $allowLooseOpenings = false; - - /** - * defines whether the compiler will automatically html-escape variables or not - * - * default is false - * - * @var bool - */ - protected $autoEscape = false; - - /** - * security policy object - * - * @var Dwoo_Security_Policy - */ - protected $securityPolicy; - - /** - * stores the custom plugins registered with this compiler - * - * @var array - */ - protected $customPlugins = array(); - - /** - * stores the template plugins registered with this compiler - * - * @var array - */ - protected $templatePlugins = array(); - - /** - * stores the pre- and post-processors callbacks - * - * @var array - */ - protected $processors = array('pre'=>array(), 'post'=>array()); - - /** - * stores a list of plugins that are used in the currently compiled - * template, and that are not compilable. these plugins will be loaded - * during the template's runtime if required. - * - * it is a 1D array formatted as key:pluginName value:pluginType - * - * @var array - */ - protected $usedPlugins; - - /** - * stores the template undergoing compilation - * - * @var string - */ - protected $template; - - /** - * stores the current pointer position inside the template - * - * @var int - */ - protected $pointer; - - /** - * stores the current line count inside the template for debugging purposes - * - * @var int - */ - protected $line; - - /** - * stores the current template source while compiling it - * - * @var string - */ - protected $templateSource; - - /** - * stores the data within which the scope moves - * - * @var array - */ - protected $data; - - /** - * variable scope of the compiler, set to null if - * it can not be resolved to a static string (i.e. if some - * plugin defines a new scope based on a variable array key) - * - * @var mixed - */ - protected $scope; - - /** - * variable scope tree, that allows to rebuild the current - * scope if required, i.e. when going to a parent level - * - * @var array - */ - protected $scopeTree; - - /** - * block plugins stack, accessible through some methods - * - * @see findBlock - * @see getCurrentBlock - * @see addBlock - * @see addCustomBlock - * @see injectBlock - * @see removeBlock - * @see removeTopBlock - * - * @var array - */ - protected $stack = array(); - - /** - * current block at the top of the block plugins stack, - * accessible through getCurrentBlock - * - * @see getCurrentBlock - * - * @var Dwoo_Block_Plugin - */ - protected $curBlock; - - /** - * current dwoo object that uses this compiler, or null - * - * @var Dwoo - */ - protected $dwoo; - - /** - * holds an instance of this class, used by getInstance when you don't - * provide a custom compiler in order to save resources - * - * @var Dwoo_Compiler - */ - protected static $instance; - - /** - * constructor - * - * saves the created instance so that child templates get the same one - */ - public function __construct() - { - self::$instance = $this; - } - - /** - * sets the delimiters to use in the templates - * - * delimiters can be multi-character strings but should not be one of those as they will - * make it very hard to work with templates or might even break the compiler entirely : "\", "$", "|", ":" and finally "#" only if you intend to use config-vars with the #var# syntax. - * - * @param string $left left delimiter - * @param string $right right delimiter - */ - public function setDelimiters($left, $right) - { - $this->ld = $left; - $this->rd = $right; - $this->ldr = preg_quote($left, '/'); - $this->rdr = preg_quote($right, '/'); - } - - /** - * returns the left and right template delimiters - * - * @return array containing the left and the right delimiters - */ - public function getDelimiters() - { - return array($this->ld, $this->rd); - } - - /** - * sets the way to handle nested comments, if set to true - * {* foo {* some other *} comment *} will be stripped correctly. - * - * if false it will remove {* foo {* some other *} and leave "comment *}" alone, - * this is the default behavior - * - * @param bool $allow allow nested comments or not, defaults to true (but the default internal value is false) - */ - public function setNestedCommentsHandling($allow = true) { - $this->allowNestedComments = (bool) $allow; - } - - /** - * returns the nested comments handling setting - * - * @see setNestedCommentsHandling - * @return bool true if nested comments are allowed - */ - public function getNestedCommentsHandling() { - return $this->allowNestedComments; - } - - /** - * sets the tag openings handling strictness, if set to true, template tags can - * contain spaces before the first function/string/variable such as { $foo} is valid. - * - * if set to false (default setting), { $foo} is invalid but that is however a good thing - * as it allows css (i.e. #foo { color:red; }) to be parsed silently without triggering - * an error, same goes for javascript. - * - * @param bool $allow true to allow loose handling, false to restore default setting - */ - public function setLooseOpeningHandling($allow = false) - { - $this->allowLooseOpenings = (bool) $allow; - } - - /** - * returns the tag openings handling strictness setting - * - * @see setLooseOpeningHandling - * @return bool true if loose tags are allowed - */ - public function getLooseOpeningHandling() - { - return $this->allowLooseOpenings; - } - - /** - * changes the auto escape setting - * - * if enabled, the compiler will automatically html-escape variables, - * unless they are passed through the safe function such as {$var|safe} - * or {safe $var} - * - * default setting is disabled/false - * - * @param bool $enabled set to true to enable, false to disable - */ - public function setAutoEscape($enabled) - { - $this->autoEscape = (bool) $enabled; - } - - /** - * returns the auto escape setting - * - * default setting is disabled/false - * - * @return bool - */ - public function getAutoEscape() - { - return $this->autoEscape; - } - - /** - * adds a preprocessor to the compiler, it will be called - * before the template is compiled - * - * @param mixed $callback either a valid callback to the preprocessor or a simple name if the autoload is set to true - * @param bool $autoload if set to true, the preprocessor is auto-loaded from one of the plugin directories, else you must provide a valid callback - */ - public function addPreProcessor($callback, $autoload = false) - { - if ($autoload) { - $name = str_replace('Dwoo_Processor_', '', $callback); - $class = 'Dwoo_Processor_'.$name; - - if (class_exists($class, false)) { - $callback = array(new $class($this), 'process'); - } elseif (function_exists($class)) { - $callback = $class; - } else { - $callback = array('autoload'=>true, 'class'=>$class, 'name'=>$name); - } - - $this->processors['pre'][] = $callback; - } else { - $this->processors['pre'][] = $callback; - } - } - - /** - * removes a preprocessor from the compiler - * - * @param mixed $callback either a valid callback to the preprocessor or a simple name if it was autoloaded - */ - public function removePreProcessor($callback) - { - if (($index = array_search($callback, $this->processors['pre'], true)) !== false) { - unset($this->processors['pre'][$index]); - } elseif (($index = array_search('Dwoo_Processor_'.str_replace('Dwoo_Processor_', '', $callback), $this->processors['pre'], true)) !== false) { - unset($this->processors['pre'][$index]); - } else { - $class = 'Dwoo_Processor_' . str_replace('Dwoo_Processor_', '', $callback); - foreach ($this->processors['pre'] as $index=>$proc) { - if (is_array($proc) && ($proc[0] instanceof $class) || (isset($proc['class']) && $proc['class'] == $class)) { - unset($this->processors['pre'][$index]); - break; - } - } - } - } - - /** - * adds a postprocessor to the compiler, it will be called - * before the template is compiled - * - * @param mixed $callback either a valid callback to the postprocessor or a simple name if the autoload is set to true - * @param bool $autoload if set to true, the postprocessor is auto-loaded from one of the plugin directories, else you must provide a valid callback - */ - public function addPostProcessor($callback, $autoload = false) - { - if ($autoload) { - $name = str_replace('Dwoo_Processor_', '', $callback); - $class = 'Dwoo_Processor_'.$name; - - if (class_exists($class, false)) { - $callback = array(new $class($this), 'process'); - } elseif (function_exists($class)) { - $callback = $class; - } else { - $callback = array('autoload'=>true, 'class'=>$class, 'name'=>$name); - } - - $this->processors['post'][] = $callback; - } else { - $this->processors['post'][] = $callback; - } - } - - /** - * removes a postprocessor from the compiler - * - * @param mixed $callback either a valid callback to the postprocessor or a simple name if it was autoloaded - */ - public function removePostProcessor($callback) - { - if (($index = array_search($callback, $this->processors['post'], true)) !== false) { - unset($this->processors['post'][$index]); - } elseif (($index = array_search('Dwoo_Processor_'.str_replace('Dwoo_Processor_', '', $callback), $this->processors['post'], true)) !== false) { - unset($this->processors['post'][$index]); - } else { - $class = 'Dwoo_Processor_' . str_replace('Dwoo_Processor_', '', $callback); - foreach ($this->processors['post'] as $index=>$proc) { - if (is_array($proc) && ($proc[0] instanceof $class) || (isset($proc['class']) && $proc['class'] == $class)) { - unset($this->processors['post'][$index]); - break; - } - } - } - } - - /** - * internal function to autoload processors at runtime if required - * - * @param string $class the class/function name - * @param string $name the plugin name (without Dwoo_Plugin_ prefix) - */ - protected function loadProcessor($class, $name) - { - if (!class_exists($class, false) && !function_exists($class)) { - try { - $this->dwoo->getLoader()->loadPlugin($name); - } catch (Dwoo_Exception $e) { - throw new Dwoo_Exception('Processor '.$name.' could not be found in your plugin directories, please ensure it is in a file named '.$name.'.php in the plugin directory'); - } - } - - if (class_exists($class, false)) { - return array(new $class($this), 'process'); - } - - if (function_exists($class)) { - return $class; - } - - throw new Dwoo_Exception('Wrong processor name, when using autoload the processor must be in one of your plugin dir as "name.php" containg a class or function named "Dwoo_Processor_name"'); - } - - /** - * adds an used plugin, this is reserved for use by the {template} plugin - * - * this is required so that plugin loading bubbles up from loaded - * template files to the current one - * - * @private - * @param string $name function name - * @param int $type plugin type (Dwoo::*_PLUGIN) - */ - public function addUsedPlugin($name, $type) - { - $this->usedPlugins[$name] = $type; - } - - /** - * returns all the plugins this template uses - * - * @private - * @return array the list of used plugins in the parsed template - */ - public function getUsedPlugins() - { - return $this->usedPlugins; - } - - /** - * adds a template plugin, this is reserved for use by the {template} plugin - * - * this is required because the template functions are not declared yet - * during compilation, so we must have a way of validating their argument - * signature without using the reflection api - * - * @private - * @param string $name function name - * @param array $params parameter array to help validate the function call - * @param string $uuid unique id of the function - * @param string $body function php code - */ - public function addTemplatePlugin($name, array $params, $uuid, $body = null) - { - $this->templatePlugins[$name] = array('params'=> $params, 'body' => $body, 'uuid' => $uuid); - } - - /** - * returns all the parsed sub-templates - * - * @private - * @return array the parsed sub-templates - */ - public function getTemplatePlugins() - { - return $this->templatePlugins; - } - - /** - * marks a template plugin as being called, which means its source must be included in the compiled template - * - * @param string $name function name - */ - public function useTemplatePlugin($name) - { - $this->templatePlugins[$name]['called'] = true; - } - - /** - * 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->customPlugins = $customPlugins; - } - - /** - * sets the security policy object to enforce some php security settings - * - * use this if untrusted persons can modify templates, - * set it on the Dwoo object as it will be passed onto the compiler automatically - * - * @param Dwoo_Security_Policy $policy the security policy object - */ - public function setSecurityPolicy(Dwoo_Security_Policy $policy = null) - { - $this->securityPolicy = $policy; - } - - /** - * returns the current security policy object or null by default - * - * @return Dwoo_Security_Policy|null the security policy object if any - */ - public function getSecurityPolicy() - { - return $this->securityPolicy; - } - - /** - * sets the pointer position - * - * @param int $position the new pointer position - * @param bool $isOffset if set to true, the position acts as an offset and not an absolute position - */ - public function setPointer($position, $isOffset = false) - { - if ($isOffset) { - $this->pointer += $position; - } else { - $this->pointer = $position; - } - } - - /** - * returns the current pointer position, only available during compilation of a template - * - * @return int - */ - public function getPointer() - { - return $this->pointer; - } - - /** - * sets the line number - * - * @param int $number the new line number - * @param bool $isOffset if set to true, the position acts as an offset and not an absolute position - */ - public function setLine($number, $isOffset = false) - { - if ($isOffset) { - $this->line += $number; - } else { - $this->line = $number; - } - } - - /** - * returns the current line number, only available during compilation of a template - * - * @return int - */ - public function getLine() - { - return $this->line; - } - - /** - * returns the dwoo object that initiated this template compilation, only available during compilation of a template - * - * @return Dwoo - */ - public function getDwoo() - { - return $this->dwoo; - } - - /** - * overwrites the template that is being compiled - * - * @param string $newSource the template source that must replace the current one - * @param bool $fromPointer if set to true, only the source from the current pointer position is replaced - * @return string the template or partial template - */ - public function setTemplateSource($newSource, $fromPointer = false) - { - if ($fromPointer === true) { - $this->templateSource = substr($this->templateSource, 0, $this->pointer) . $newSource; - } else { - $this->templateSource = $newSource; - } - } - - /** - * returns the template that is being compiled - * - * @param mixed $fromPointer if set to true, only the source from the current pointer - * position is returned, if a number is given it overrides the current pointer - * @return string the template or partial template - */ - public function getTemplateSource($fromPointer = false) - { - if ($fromPointer === true) { - return substr($this->templateSource, $this->pointer); - } elseif (is_numeric($fromPointer)) { - return substr($this->templateSource, $fromPointer); - } else { - return $this->templateSource; - } - } - - /** - * resets the compilation pointer, effectively restarting the compilation process - * - * this is useful if a plugin modifies the template source since it might need to be recompiled - */ - public function recompile() - { - $this->setPointer(0); - } - - /** - * compiles the provided string down to php code - * - * @param string $tpl the template to compile - * @return string a compiled php string - */ - public function compile(Dwoo $dwoo, Dwoo_ITemplate $template) - { - // init vars - $tpl = $template->getSource(); - $ptr = 0; - $this->dwoo = $dwoo; - $this->template = $template; - $this->templateSource =& $tpl; - $this->pointer =& $ptr; - - while (true) { - // if pointer is at the beginning, reset everything, that allows a plugin to externally reset the compiler if everything must be reparsed - if ($ptr===0) { - // resets variables - $this->usedPlugins = array(); - $this->data = array(); - $this->scope =& $this->data; - $this->scopeTree = array(); - $this->stack = array(); - $this->line = 1; - $this->templatePlugins = array(); - // add top level block - $compiled = $this->addBlock('topLevelBlock', array(), 0); - $this->stack[0]['buffer'] = ''; - - if ($this->debug) echo 'COMPILER INIT
'; - - if ($this->debug) echo 'PROCESSING PREPROCESSORS ('.count($this->processors['pre']).')
'; - - // runs preprocessors - foreach ($this->processors['pre'] as $preProc) { - if (is_array($preProc) && isset($preProc['autoload'])) { - $preProc = $this->loadProcessor($preProc['class'], $preProc['name']); - } - if (is_array($preProc) && $preProc[0] instanceof Dwoo_Processor) { - $tpl = call_user_func($preProc, $tpl); - } else { - $tpl = call_user_func($preProc, $this, $tpl); - } - } - unset($preProc); - - // show template source if debug - if ($this->debug) echo '
'.print_r(htmlentities($tpl), true).'

'; - - // strips php tags if required by the security policy - if ($this->securityPolicy !== null) { - $search = array('{<\?php.*?\?>}'); - if (ini_get('short_open_tags')) { - $search = array('{<\?.*?\?>}', '{<%.*?%>}'); - } - switch($this->securityPolicy->getPhpHandling()) { - - case Dwoo_Security_Policy::PHP_ALLOW: - break; - case Dwoo_Security_Policy::PHP_ENCODE: - $tpl = preg_replace_callback($search, array($this, 'phpTagEncodingHelper'), $tpl); - break; - case Dwoo_Security_Policy::PHP_REMOVE: - $tpl = preg_replace($search, '', $tpl); - - } - } - } - - $pos = strpos($tpl, $this->ld, $ptr); - - if ($pos === false) { - $this->push(substr($tpl, $ptr), 0); - break; - } elseif (substr($tpl, $pos-1, 1) === '\\' && substr($tpl, $pos-2, 1) !== '\\') { - $this->push(substr($tpl, $ptr, $pos-$ptr-1) . $this->ld); - $ptr = $pos+strlen($this->ld); - } elseif (preg_match('/^'.$this->ldr . ($this->allowLooseOpenings ? '\s*' : '') . 'literal' . ($this->allowLooseOpenings ? '\s*' : '') . $this->rdr.'/s', substr($tpl, $pos), $litOpen)) { - if (!preg_match('/'.$this->ldr . ($this->allowLooseOpenings ? '\s*' : '') . '\/literal' . ($this->allowLooseOpenings ? '\s*' : '') . $this->rdr.'/s', $tpl, $litClose, PREG_OFFSET_CAPTURE, $pos)) { - throw new Dwoo_Compilation_Exception($this, 'The {literal} blocks must be closed explicitly with {/literal}'); - } - $endpos = $litClose[0][1]; - $this->push(substr($tpl, $ptr, $pos-$ptr) . substr($tpl, $pos + strlen($litOpen[0]), $endpos-$pos-strlen($litOpen[0]))); - $ptr = $endpos+strlen($litClose[0][0]); - } else { - if (substr($tpl, $pos-2, 1) === '\\' && substr($tpl, $pos-1, 1) === '\\') { - $this->push(substr($tpl, $ptr, $pos-$ptr-1)); - $ptr = $pos; - } - - $this->push(substr($tpl, $ptr, $pos-$ptr)); - $ptr = $pos; - - $pos += strlen($this->ld); - if ($this->allowLooseOpenings) { - while (substr($tpl, $pos, 1) === ' ') { - $pos+=1; - } - } else { - if (substr($tpl, $pos, 1) === ' ' || substr($tpl, $pos, 1) === "\r" || substr($tpl, $pos, 1) === "\n" || substr($tpl, $pos, 1) === "\t") { - $ptr = $pos; - $this->push($this->ld); - continue; - } - } - - // check that there is an end tag present - if (strpos($tpl, $this->rd, $pos) === false) { - throw new Dwoo_Compilation_Exception($this, 'A template tag was not closed, started with "'.substr($tpl, $ptr, 30).'"'); - } - - - $ptr += strlen($this->ld); - $subptr = $ptr; - - while (true) { - $parsed = $this->parse($tpl, $subptr, null, false, 'root', $subptr); - - // reload loop if the compiler was reset - if ($ptr === 0) { - continue 2; - } - - $len = $subptr - $ptr; - $this->push($parsed, substr_count(substr($tpl, $ptr, $len), "\n")); - $ptr += $len; - - if ($parsed === false) { - break; - } - } - - // adds additional line breaks between php closing and opening tags because the php parser removes those if there is just a single line break - if (substr($this->curBlock['buffer'], -2) === '?>' && preg_match('{^(([\r\n])([\r\n]?))}', substr($tpl, $ptr, 3), $m)) { - if ($m[3] === '') { - $ptr+=1; - $this->push($m[1].$m[1], 1); - } else { - $ptr+=2; - $this->push($m[1]."\n", 2); - } - } - } - } - - $compiled .= $this->removeBlock('topLevelBlock'); - - if ($this->debug) echo 'PROCESSING POSTPROCESSORS
'; - - foreach ($this->processors['post'] as $postProc) { - if (is_array($postProc) && isset($postProc['autoload'])) { - $postProc = $this->loadProcessor($postProc['class'], $postProc['name']); - } - if (is_array($postProc) && $postProc[0] instanceof Dwoo_Processor) { - $compiled = call_user_func($postProc, $compiled); - } else { - $compiled = call_user_func($postProc, $this, $compiled); - } - } - unset($postProc); - - if ($this->debug) echo 'COMPILATION COMPLETE : MEM USAGE : '.memory_get_usage().'
'; - - $output = "usedPlugins as $plugin=>$type) { - if ($type & Dwoo::CUSTOM_PLUGIN) { - continue; - } - - switch($type) { - - case Dwoo::BLOCK_PLUGIN: - case Dwoo::CLASS_PLUGIN: - $output .= "if (class_exists('Dwoo_Plugin_$plugin', false)===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n"; - break; - case Dwoo::FUNC_PLUGIN: - $output .= "if (function_exists('Dwoo_Plugin_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n"; - break; - case Dwoo::SMARTY_MODIFIER: - $output .= "if (function_exists('smarty_modifier_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n"; - break; - case Dwoo::SMARTY_FUNCTION: - $output .= "if (function_exists('smarty_function_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n"; - break; - case Dwoo::SMARTY_BLOCK: - $output .= "if (function_exists('smarty_block_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n"; - break; - case Dwoo::PROXY_PLUGIN: - $output .= $this->getDwoo()->getPluginProxy()->getPreloader($plugin); - break; - default: - throw new Dwoo_Compilation_Exception($this, 'Type error for '.$plugin.' with type'.$type); - - } - } - - foreach ($this->templatePlugins as $function => $attr) { - if (isset($attr['called']) && $attr['called'] === true && !isset($attr['checked'])) { - $this->resolveSubTemplateDependencies($function); - } - } - foreach ($this->templatePlugins as $function) { - if (isset($function['called']) && $function['called'] === true) { - $output .= $function['body'].PHP_EOL; - } - } - - $output .= $compiled."\n?>"; - - $output = preg_replace('/(?\s*)<\?xml#is', '$1', $output); - - if ($this->debug) { - echo '
';
-			$lines = preg_split('{\r\n|\n|
}', highlight_string(($output), true)); - array_shift($lines); - foreach ($lines as $i=>$line) { - echo ($i+1).'. '.$line."\r\n"; - } - } - if ($this->debug) echo '
'; - - $this->template = $this->dwoo = null; - $tpl = null; - - return $output; - } - - /** - * checks what sub-templates are used in every sub-template so that we're sure they are all compiled - * - * @param string $function the sub-template name - */ - protected function resolveSubTemplateDependencies($function) - { - $body = $this->templatePlugins[$function]['body']; - foreach ($this->templatePlugins as $func => $attr) { - if ($func !== $function && !isset($attr['called']) && strpos($body, 'Dwoo_Plugin_'.$func) !== false) { - $this->templatePlugins[$func]['called'] = true; - $this->resolveSubTemplateDependencies($func); - } - } - $this->templatePlugins[$function]['checked'] = true; - } - - /** - * adds compiled content to the current block - * - * @param string $content the content to push - * @param int $lineCount newlines count in content, optional - */ - public function push($content, $lineCount = null) - { - if ($lineCount === null) { - $lineCount = substr_count($content, "\n"); - } - - if ($this->curBlock['buffer'] === null && count($this->stack) > 1) { - // buffer is not initialized yet (the block has just been created) - $this->stack[count($this->stack)-2]['buffer'] .= (string) $content; - $this->curBlock['buffer'] = ''; - } else { - if (!isset($this->curBlock['buffer'])) { - throw new Dwoo_Compilation_Exception($this, 'The template has been closed too early, you probably have an extra block-closing tag somewhere'); - } - // append current content to current block's buffer - $this->curBlock['buffer'] .= (string) $content; - } - $this->line += $lineCount; - } - - /** - * sets the scope - * - * set to null if the scope becomes "unstable" (i.e. too variable or unknown) so that - * variables are compiled in a more evaluative way than just $this->scope['key'] - * - * @param mixed $scope a string i.e. "level1.level2" or an array i.e. array("level1", "level2") - * @param bool $absolute if true, the scope is set from the top level scope and not from the current scope - * @return array the current scope tree - */ - public function setScope($scope, $absolute = false) - { - $old = $this->scopeTree; - - if ($scope===null) { - unset($this->scope); - $this->scope = null; - } - - if (is_array($scope)===false) { - $scope = explode('.', $scope); - } - - if ($absolute===true) { - $this->scope =& $this->data; - $this->scopeTree = array(); - } - - while (($bit = array_shift($scope)) !== null) { - if ($bit === '_parent' || $bit === '_') { - array_pop($this->scopeTree); - reset($this->scopeTree); - $this->scope =& $this->data; - $cnt = count($this->scopeTree); - for ($i=0;$i<$cnt;$i++) - $this->scope =& $this->scope[$this->scopeTree[$i]]; - } elseif ($bit === '_root' || $bit === '__') { - $this->scope =& $this->data; - $this->scopeTree = array(); - } elseif (isset($this->scope[$bit])) { - $this->scope =& $this->scope[$bit]; - $this->scopeTree[] = $bit; - } else { - $this->scope[$bit] = array(); - $this->scope =& $this->scope[$bit]; - $this->scopeTree[] = $bit; - } - } - - return $old; - } - - /** - * adds a block to the top of the block stack - * - * @param string $type block type (name) - * @param array $params the parameters array - * @param int $paramtype the parameters type (see mapParams), 0, 1 or 2 - * @return string the preProcessing() method's output - */ - public function addBlock($type, array $params, $paramtype) - { - $class = 'Dwoo_Plugin_'.$type; - if (class_exists($class, false) === false) { - $this->dwoo->getLoader()->loadPlugin($type); - } - - $params = $this->mapParams($params, array($class, 'init'), $paramtype); - - $this->stack[] = array('type' => $type, 'params' => $params, 'custom' => false, 'class' => $class, 'buffer' => null); - $this->curBlock =& $this->stack[count($this->stack)-1]; - return call_user_func(array($class,'preProcessing'), $this, $params, '', '', $type); - } - - /** - * adds a custom block to the top of the block stack - * - * @param string $type block type (name) - * @param array $params the parameters array - * @param int $paramtype the parameters type (see mapParams), 0, 1 or 2 - * @return string the preProcessing() method's output - */ - public function addCustomBlock($type, array $params, $paramtype) - { - $callback = $this->customPlugins[$type]['callback']; - if (is_array($callback)) { - $class = is_object($callback[0]) ? get_class($callback[0]) : $callback[0]; - } else { - $class = $callback; - } - - $params = $this->mapParams($params, array($class, 'init'), $paramtype); - - $this->stack[] = array('type' => $type, 'params' => $params, 'custom' => true, 'class' => $class, 'buffer' => null); - $this->curBlock =& $this->stack[count($this->stack)-1]; - return call_user_func(array($class,'preProcessing'), $this, $params, '', '', $type); - } - - /** - * injects a block at the top of the plugin stack without calling its preProcessing method - * - * used by {else} blocks to re-add themselves after having closed everything up to their parent - * - * @param string $type block type (name) - * @param array $params parameters array - */ - public function injectBlock($type, array $params) - { - $class = 'Dwoo_Plugin_'.$type; - if (class_exists($class, false) === false) { - $this->dwoo->getLoader()->loadPlugin($type); - } - $this->stack[] = array('type' => $type, 'params' => $params, 'custom' => false, 'class' => $class, 'buffer' => null); - $this->curBlock =& $this->stack[count($this->stack)-1]; - } - - /** - * removes the closest-to-top block of the given type and all other - * blocks encountered while going down the block stack - * - * @param string $type block type (name) - * @return string the output of all postProcessing() method's return values of the closed blocks - */ - public function removeBlock($type) - { - $output = ''; - - $pluginType = $this->getPluginType($type); - if ($pluginType & Dwoo::SMARTY_BLOCK) { - $type = 'smartyinterface'; - } - while (true) { - while ($top = array_pop($this->stack)) { - if ($top['custom']) { - $class = $top['class']; - } else { - $class = 'Dwoo_Plugin_'.$top['type']; - } - if (count($this->stack)) { - $this->curBlock =& $this->stack[count($this->stack)-1]; - $this->push(call_user_func(array($class, 'postProcessing'), $this, $top['params'], '', '', $top['buffer']), 0); - } else { - $null = null; - $this->curBlock =& $null; - $output = call_user_func(array($class, 'postProcessing'), $this, $top['params'], '', '', $top['buffer']); - } - - if ($top['type'] === $type) { - break 2; - } - } - - throw new Dwoo_Compilation_Exception($this, 'Syntax malformation, a block of type "'.$type.'" was closed but was not opened'); - break; - } - - return $output; - } - - /** - * returns a reference to the first block of the given type encountered and - * optionally closes all blocks until it finds it - * - * this is mainly used by {else} plugins to close everything that was opened - * between their parent and themselves - * - * @param string $type the block type (name) - * @param bool $closeAlong whether to close all blocks encountered while going down the block stack or not - * @return &array the array is as such: array('type'=>pluginName, 'params'=>parameter array, - * 'custom'=>bool defining whether it's a custom plugin or not, for internal use) - */ - public function &findBlock($type, $closeAlong = false) - { - if ($closeAlong===true) { - while ($b = end($this->stack)) { - if ($b['type']===$type) { - return $this->stack[key($this->stack)]; - } - $this->push($this->removeTopBlock(), 0); - } - } else { - end($this->stack); - while ($b = current($this->stack)) { - if ($b['type']===$type) { - return $this->stack[key($this->stack)]; - } - prev($this->stack); - } - } - - throw new Dwoo_Compilation_Exception($this, 'A parent block of type "'.$type.'" is required and can not be found'); - } - - /** - * returns a reference to the current block array - * - * @return &array the array is as such: array('type'=>pluginName, 'params'=>parameter array, - * 'custom'=>bool defining whether it's a custom plugin or not, for internal use) - */ - public function &getCurrentBlock() - { - return $this->curBlock; - } - - /** - * removes the block at the top of the stack and calls its postProcessing() method - * - * @return string the postProcessing() method's output - */ - public function removeTopBlock() - { - $o = array_pop($this->stack); - if ($o === null) { - throw new Dwoo_Compilation_Exception($this, 'Syntax malformation, a block of unknown type was closed but was not opened.'); - } - if ($o['custom']) { - $class = $o['class']; - } else { - $class = 'Dwoo_Plugin_'.$o['type']; - } - - $this->curBlock =& $this->stack[count($this->stack)-1]; - - return call_user_func(array($class, 'postProcessing'), $this, $o['params'], '', '', $o['buffer']); - } - - /** - * returns the compiled parameters (for example a variable's compiled parameter will be "$this->scope['key']") out of the given parameter array - * - * @param array $params parameter array - * @return array filtered parameters - */ - public function getCompiledParams(array $params) - { - foreach ($params as $k=>$p) { - if (is_array($p)) { - $params[$k] = $p[0]; - } - } - return $params; - } - - /** - * returns the real parameters (for example a variable's real parameter will be its key, etc) out of the given parameter array - * - * @param array $params parameter array - * @return array filtered parameters - */ - public function getRealParams(array $params) - { - foreach ($params as $k=>$p) { - if (is_array($p)) { - $params[$k] = $p[1]; - } - } - return $params; - } - - /** - * entry point of the parser, it redirects calls to other parse* functions - * - * @param string $in the string within which we must parse something - * @param int $from the starting offset of the parsed area - * @param int $to the ending offset of the parsed area - * @param mixed $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default - * @param string $curBlock the current parser-block being processed - * @param mixed $pointer a reference to a pointer that will be increased by the amount of characters parsed, or null by default - * @return string parsed values - */ - protected function parse($in, $from, $to, $parsingParams = false, $curBlock='', &$pointer = null) - { - if ($to === null) { - $to = strlen($in); - } - $first = substr($in, $from, 1); - - if ($first === false) { - throw new Dwoo_Compilation_Exception($this, 'Unexpected EOF, a template tag was not closed'); - } - - while ($first===" " || $first==="\n" || $first==="\t" || $first==="\r") { - if ($curBlock === 'root' && substr($in, $from, strlen($this->rd)) === $this->rd) { - // end template tag - $pointer += strlen($this->rd); - if ($this->debug) echo 'TEMPLATE PARSING ENDED
'; - return false; - } - $from++; - if ($pointer !== null) { - $pointer++; - } - if ($from >= $to) { - if (is_array($parsingParams)) { - return $parsingParams; - } else { - return ''; - } - } - $first = $in[$from]; - } - - $substr = substr($in, $from, $to-$from); - - if ($this->debug) echo '
PARSE CALL : PARSING "'.htmlentities(substr($in, $from, min($to-$from, 50))).(($to-$from) > 50 ? '...':'').'" @ '.$from.':'.$to.' in '.$curBlock.' : pointer='.$pointer.'
'; - $parsed = ""; - - if ($curBlock === 'root' && $first === '*') { - $src = $this->getTemplateSource(); - $startpos = $this->getPointer() - strlen($this->ld); - if (substr($src, $startpos, strlen($this->ld)) === $this->ld) { - if ($startpos > 0) { - do { - $char = substr($src, --$startpos, 1); - if ($char == "\n") { - $startpos++; - $whitespaceStart = true; - break; - } - } while ($startpos > 0 && ($char == ' ' || $char == "\t")); - } - - if (!isset($whitespaceStart)) { - $startpos = $this->getPointer(); - } else { - $pointer -= $this->getPointer() - $startpos; - } - - if ($this->allowNestedComments && strpos($src, $this->ld.'*', $this->getPointer()) !== false) { - $comOpen = $this->ld.'*'; - $comClose = '*'.$this->rd; - $level = 1; - $start = $startpos; - $ptr = $this->getPointer() + '*'; - - while ($level > 0 && $ptr < strlen($src)) { - $open = strpos($src, $comOpen, $ptr); - $close = strpos($src, $comClose, $ptr); - - if ($open !== false && $close !== false) { - if ($open < $close) { - $ptr = $open + strlen($comOpen); - $level++; - } else { - $ptr = $close + strlen($comClose); - $level--; - } - } elseif ($open !== false) { - $ptr = $open + strlen($comOpen); - $level++; - } elseif ($close !== false) { - $ptr = $close + strlen($comClose); - $level--; - } else { - $ptr = strlen($src); - } - } - $endpos = $ptr - strlen('*'.$this->rd); - } else { - $endpos = strpos($src, '*'.$this->rd, $startpos); - if ($endpos == false) { - throw new Dwoo_Compilation_Exception($this, 'Un-ended comment'); - } - } - $pointer += $endpos - $startpos + strlen('*'.$this->rd); - if (isset($whitespaceStart) && preg_match('#^[\t ]*\r?\n#', substr($src, $endpos+strlen('*'.$this->rd)), $m)) { - $pointer += strlen($m[0]); - $this->curBlock['buffer'] = substr($this->curBlock['buffer'], 0, strlen($this->curBlock['buffer']) - ($this->getPointer() - $startpos - strlen($this->ld))); - } - return false; - } - } - - if ($first==='$') { - // var - $out = $this->parseVar($in, $from, $to, $parsingParams, $curBlock, $pointer); - $parsed = 'var'; - } elseif ($first==='%' && preg_match('#^%[a-z]#i', $substr)) { - // const - $out = $this->parseConst($in, $from, $to, $parsingParams, $curBlock, $pointer); - } elseif ($first==='"' || $first==="'") { - // string - $out = $this->parseString($in, $from, $to, $parsingParams, $curBlock, $pointer); - } elseif (preg_match('/^[a-z][a-z0-9_]*(?:::[a-z][a-z0-9_]*)?('.(is_array($parsingParams)||$curBlock!='root'?'':'\s+[^(]|').'\s*\(|\s*'.$this->rdr.'|\s*;)/i', $substr)) { - // func - $out = $this->parseFunction($in, $from, $to, $parsingParams, $curBlock, $pointer); - $parsed = 'func'; - } elseif ($first === ';') { - // instruction end - if ($this->debug) echo 'END OF INSTRUCTION
'; - if ($pointer !== null) { - $pointer++; - } - return $this->parse($in, $from+1, $to, false, 'root', $pointer); - } elseif ($curBlock === 'root' && preg_match('#^/([a-z][a-z0-9_]*)?#i', $substr, $match)) { - // close block - if (!empty($match[1]) && $match[1] == 'else') { - throw new Dwoo_Compilation_Exception($this, 'Else blocks must not be closed explicitly, they are automatically closed when their parent block is closed'); - } - if (!empty($match[1]) && $match[1] == 'elseif') { - throw new Dwoo_Compilation_Exception($this, 'Elseif blocks must not be closed explicitly, they are automatically closed when their parent block is closed or a new else/elseif block is declared after them'); - } - if ($pointer !== null) { - $pointer += strlen($match[0]); - } - if (empty($match[1])) { - if ($this->curBlock['type'] == 'else' || $this->curBlock['type'] == 'elseif') { - $pointer -= strlen($match[0]); - } - if ($this->debug) echo 'TOP BLOCK CLOSED
'; - return $this->removeTopBlock(); - } else { - if ($this->debug) echo 'BLOCK OF TYPE '.$match[1].' CLOSED
'; - return $this->removeBlock($match[1]); - } - } elseif ($curBlock === 'root' && substr($substr, 0, strlen($this->rd)) === $this->rd) { - // end template tag - if ($this->debug) echo 'TAG PARSING ENDED
'; - $pointer += strlen($this->rd); - return false; - } elseif (is_array($parsingParams) && preg_match('#^([a-z0-9_]+\s*=)(?:\s+|[^=]).*#i', $substr, $match)) { - // named parameter - if ($this->debug) echo 'NAMED PARAM FOUND
'; - $len = strlen($match[1]); - while (substr($in, $from+$len, 1)===' ') { - $len++; - } - if ($pointer !== null) { - $pointer += $len; - } - - $output = array(trim(substr(trim($match[1]), 0, -1)), $this->parse($in, $from+$len, $to, false, 'namedparam', $pointer)); - - $parsingParams[] = $output; - return $parsingParams; - } elseif (preg_match('#^([a-z0-9_]+::\$[a-z0-9_]+)#i', $substr, $match)) { - // static member access - $parsed = 'var'; - if (is_array($parsingParams)) { - $parsingParams[] = array($match[1], $match[1]); - $out = $parsingParams; - } else { - $out = $match[1]; - } - $pointer += strlen($match[1]); - } elseif ($substr!=='' && (is_array($parsingParams) || $curBlock === 'namedparam' || $curBlock === 'condition' || $curBlock === 'expression')) { - // unquoted string, bool or number - $out = $this->parseOthers($in, $from, $to, $parsingParams, $curBlock, $pointer); - } else { - // parse error - throw new Dwoo_Compilation_Exception($this, 'Parse error in "'.substr($in, $from, $to-$from).'"'); - } - - if (empty($out)) { - return ''; - } - - $substr = substr($in, $pointer, $to-$pointer); - - // var parsed, check if any var-extension applies - if ($parsed==='var') { - if (preg_match('#^\s*([/%+*-])\s*([a-z0-9]|\$)#i', $substr, $match)) { - if($this->debug) echo 'PARSING POST-VAR EXPRESSION '.$substr.'
'; - // parse expressions - $pointer += strlen($match[0]) - 1; - if (is_array($parsingParams)) { - if ($match[2] == '$') { - $expr = $this->parseVar($in, $pointer, $to, array(), $curBlock, $pointer); - } else { - $expr = $this->parse($in, $pointer, $to, array(), 'expression', $pointer); - } - $out[count($out)-1][0] .= $match[1] . $expr[0][0]; - $out[count($out)-1][1] .= $match[1] . $expr[0][1]; - } else { - if ($match[2] == '$') { - $expr = $this->parseVar($in, $pointer, $to, false, $curBlock, $pointer); - } else { - $expr = $this->parse($in, $pointer, $to, false, 'expression', $pointer); - } - if (is_array($out) && is_array($expr)) { - $out[0] .= $match[1] . $expr[0]; - $out[1] .= $match[1] . $expr[1]; - } elseif (is_array($out)) { - $out[0] .= $match[1] . $expr; - $out[1] .= $match[1] . $expr; - } elseif (is_array($expr)) { - $out .= $match[1] . $expr[0]; - } else { - $out .= $match[1] . $expr; - } - } - } else if ($curBlock === 'root' && preg_match('#^(\s*(?:[+/*%-.]=|=|\+\+|--)\s*)(.*)#s', $substr, $match)) { - if($this->debug) echo 'PARSING POST-VAR ASSIGNMENT '.$substr.'
'; - // parse assignment - $value = $match[2]; - $operator = trim($match[1]); - if (substr($value, 0, 1) == '=') { - throw new Dwoo_Compilation_Exception($this, 'Unexpected "=" in '.$substr.''); - } - - if ($pointer !== null) { - $pointer += strlen($match[1]); - } - - if ($operator !== '++' && $operator !== '--') { - $parts = array(); - $ptr = 0; - $parts = $this->parse($value, 0, strlen($value), $parts, 'condition', $ptr); - $pointer += $ptr; - - // load if plugin - try { - $this->getPluginType('if'); - } catch (Dwoo_Exception $e) { - throw new Dwoo_Compilation_Exception($this, 'Assignments require the "if" plugin to be accessible'); - } - - $parts = $this->mapParams($parts, array('Dwoo_Plugin_if', 'init'), 1); - $parts = $this->getCompiledParams($parts); - - $value = Dwoo_Plugin_if::replaceKeywords($parts['*'], $this); - $echo = ''; - } else { - $value = array(); - $echo = 'echo '; - } - - if ($this->autoEscape) { - $out = preg_replace('#\(is_string\(\$tmp=(.+?)\) \? htmlspecialchars\(\$tmp, ENT_QUOTES, \$this->charset\) : \$tmp\)#', '$1', $out); - } - $out = Dwoo_Compiler::PHP_OPEN. $echo . $out . $operator . implode(' ', $value) . Dwoo_Compiler::PHP_CLOSE; - } - } - - if ($curBlock !== 'modifier' && ($parsed === 'func' || $parsed === 'var') && preg_match('#^\|@?[a-z0-9_]+(:.*)?#i', $substr, $match)) { - // parse modifier on funcs or vars - $srcPointer = $pointer; - if (is_array($parsingParams)) { - $tmp = $this->replaceModifiers(array(null, null, $out[count($out)-1][0], $match[0]), 'var', $pointer); - $out[count($out)-1][0] = $tmp; - $out[count($out)-1][1] .= substr($substr, $srcPointer, $srcPointer - $pointer); - } else { - $out = $this->replaceModifiers(array(null, null, $out, $match[0]), 'var', $pointer); - } - } - - // func parsed, check if any func-extension applies - if ($parsed==='func' && preg_match('#^->[a-z0-9_]+(\s*\(.+|->[a-z].*)?#is', $substr, $match)) { - // parse method call or property read - $ptr = 0; - - if (is_array($parsingParams)) { - $output = $this->parseMethodCall($out[count($out)-1][1], $match[0], $curBlock, $ptr); - - $out[count($out)-1][0] = $output; - $out[count($out)-1][1] .= substr($match[0], 0, $ptr); - } else { - $out = $this->parseMethodCall($out, $match[0], $curBlock, $ptr); - } - - $pointer += $ptr; - } - - if ($curBlock === 'root' && substr($out, 0, strlen(self::PHP_OPEN)) !== self::PHP_OPEN) { - return self::PHP_OPEN .'echo '.$out.';'. self::PHP_CLOSE; - } else { - return $out; - } - } - - /** - * parses a function call - * - * @param string $in the string within which we must parse something - * @param int $from the starting offset of the parsed area - * @param int $to the ending offset of the parsed area - * @param mixed $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default - * @param string $curBlock the current parser-block being processed - * @param mixed $pointer a reference to a pointer that will be increased by the amount of characters parsed, or null by default - * @return string parsed values - */ - protected function parseFunction($in, $from, $to, $parsingParams = false, $curBlock='', &$pointer = null) - { - $cmdstr = substr($in, $from, $to-$from); - preg_match('/^([a-z][a-z0-9_]*(?:::[a-z][a-z0-9_]*)?)(\s*'.$this->rdr.'|\s*;)?/i', $cmdstr, $match); - - if (empty($match[1])) { - throw new Dwoo_Compilation_Exception($this, 'Parse error, invalid function name : '.substr($cmdstr, 0, 15)); - } - - $func = $match[1]; - - if (!empty($match[2])) { - $cmdstr = $match[1]; - } - - if ($this->debug) echo 'FUNC FOUND ('.$func.')
'; - - $paramsep = ''; - - if (is_array($parsingParams) || $curBlock != 'root') { - $paramspos = strpos($cmdstr, '('); - $paramsep = ')'; - } elseif(preg_match_all('#[a-z0-9_]+(\s*\(|\s+[^(])#i', $cmdstr, $match, PREG_OFFSET_CAPTURE)) { - $paramspos = $match[1][0][1]; - $paramsep = substr($match[1][0][0], -1) === '(' ? ')':''; - if($paramsep === ')') { - $paramspos += strlen($match[1][0][0]) - 1; - if(substr($cmdstr, 0, 2) === 'if' || substr($cmdstr, 0, 6) === 'elseif') { - $paramsep = ''; - if(strlen($match[1][0][0]) > 1) { - $paramspos--; - } - } - } - } else { - $paramspos = false; - } - - $state = 0; - - if ($paramspos === false) { - $params = array(); - - if ($curBlock !== 'root') { - return $this->parseOthers($in, $from, $to, $parsingParams, $curBlock, $pointer); - } - } else { - if ($curBlock === 'condition') { - // load if plugin - $this->getPluginType('if'); - if (Dwoo_Plugin_if::replaceKeywords(array($func), $this) !== array($func)) { - return $this->parseOthers($in, $from, $to, $parsingParams, $curBlock, $pointer); - } - } - $whitespace = strlen(substr($cmdstr, strlen($func), $paramspos-strlen($func))); - $paramstr = substr($cmdstr, $paramspos+1); - if (substr($paramstr, -1, 1) === $paramsep) { - $paramstr = substr($paramstr, 0, -1); - } - - if (strlen($paramstr)===0) { - $params = array(); - $paramstr = ''; - } else { - $ptr = 0; - $params = array(); - if ($func === 'empty') { - $params = $this->parseVar($paramstr, $ptr, strlen($paramstr), $params, 'root', $ptr); - } else { - while ($ptr < strlen($paramstr)) { - while (true) { - if ($ptr >= strlen($paramstr)) { - break 2; - } - - if ($func !== 'if' && $func !== 'elseif' && $paramstr[$ptr] === ')') { - if ($this->debug) echo 'PARAM PARSING ENDED, ")" FOUND, POINTER AT '.$ptr.'
'; - break 2; - } elseif ($paramstr[$ptr] === ';') { - $ptr++; - if ($this->debug) echo 'PARAM PARSING ENDED, ";" FOUND, POINTER AT '.$ptr.'
'; - break 2; - } elseif ($func !== 'if' && $func !== 'elseif' && $paramstr[$ptr] === '/') { - if ($this->debug) echo 'PARAM PARSING ENDED, "/" FOUND, POINTER AT '.$ptr.'
'; - break 2; - } elseif (substr($paramstr, $ptr, strlen($this->rd)) === $this->rd) { - if ($this->debug) echo 'PARAM PARSING ENDED, RIGHT DELIMITER FOUND, POINTER AT '.$ptr.'
'; - break 2; - } - - if ($paramstr[$ptr] === ' ' || $paramstr[$ptr] === ',' || $paramstr[$ptr] === "\r" || $paramstr[$ptr] === "\n" || $paramstr[$ptr] === "\t") { - $ptr++; - } else { - break; - } - } - - if ($this->debug) echo 'FUNC START PARAM PARSING WITH POINTER AT '.$ptr.'
'; - - if ($func === 'if' || $func === 'elseif' || $func === 'tif') { - $params = $this->parse($paramstr, $ptr, strlen($paramstr), $params, 'condition', $ptr); - } else { - $params = $this->parse($paramstr, $ptr, strlen($paramstr), $params, 'function', $ptr); - } - - if ($this->debug) echo 'PARAM PARSED, POINTER AT '.$ptr.' ('.substr($paramstr, $ptr-1, 3).')
'; - } - } - $paramstr = substr($paramstr, 0, $ptr); - $state = 0; - foreach ($params as $k=>$p) { - if (is_array($p) && is_array($p[1])) { - $state |= 2; - } else { - if (($state & 2) && preg_match('#^(["\'])(.+?)\1$#', $p[0], $m)) { - $params[$k] = array($m[2], array('true', 'true')); - } else { - if ($state & 2) { - throw new Dwoo_Compilation_Exception($this, 'You can not use an unnamed parameter after a named one'); - } - $state |= 1; - } - } - } - } - } - - if ($pointer !== null) { - $pointer += (isset($paramstr) ? strlen($paramstr) : 0) + (')' === $paramsep ? 2 : ($paramspos === false ? 0 : 1)) + strlen($func) + (isset($whitespace) ? $whitespace : 0); - if ($this->debug) echo 'FUNC ADDS '.((isset($paramstr) ? strlen($paramstr) : 0) + (')' === $paramsep ? 2 : ($paramspos === false ? 0 : 1)) + strlen($func)).' TO POINTER
'; - } - - if ($curBlock === 'method' || $func === 'do' || strstr($func, '::') !== false) { - $pluginType = Dwoo::NATIVE_PLUGIN; - } else { - $pluginType = $this->getPluginType($func); - } - - // blocks - if ($pluginType & Dwoo::BLOCK_PLUGIN) { - if ($curBlock !== 'root' || is_array($parsingParams)) { - throw new Dwoo_Compilation_Exception($this, 'Block plugins can not be used as other plugin\'s arguments'); - } - if ($pluginType & Dwoo::CUSTOM_PLUGIN) { - return $this->addCustomBlock($func, $params, $state); - } else { - return $this->addBlock($func, $params, $state); - } - } elseif ($pluginType & Dwoo::SMARTY_BLOCK) { - if ($curBlock !== 'root' || is_array($parsingParams)) { - throw new Dwoo_Compilation_Exception($this, 'Block plugins can not be used as other plugin\'s arguments'); - } - - if ($state & 2) { - array_unshift($params, array('__functype', array($pluginType, $pluginType))); - array_unshift($params, array('__funcname', array($func, $func))); - } else { - array_unshift($params, array($pluginType, $pluginType)); - array_unshift($params, array($func, $func)); - } - - return $this->addBlock('smartyinterface', $params, $state); - } - - // funcs - if ($pluginType & Dwoo::NATIVE_PLUGIN || $pluginType & Dwoo::SMARTY_FUNCTION || $pluginType & Dwoo::SMARTY_BLOCK) { - $params = $this->mapParams($params, null, $state); - } elseif ($pluginType & Dwoo::CLASS_PLUGIN) { - if ($pluginType & Dwoo::CUSTOM_PLUGIN) { - $params = $this->mapParams($params, array($this->customPlugins[$func]['class'], $this->customPlugins[$func]['function']), $state); - } else { - $params = $this->mapParams($params, array('Dwoo_Plugin_'.$func, ($pluginType & Dwoo::COMPILABLE_PLUGIN) ? 'compile' : 'process'), $state); - } - } elseif ($pluginType & Dwoo::FUNC_PLUGIN) { - if ($pluginType & Dwoo::CUSTOM_PLUGIN) { - $params = $this->mapParams($params, $this->customPlugins[$func]['callback'], $state); - } else { - $params = $this->mapParams($params, 'Dwoo_Plugin_'.$func.(($pluginType & Dwoo::COMPILABLE_PLUGIN) ? '_compile' : ''), $state); - } - } elseif ($pluginType & Dwoo::SMARTY_MODIFIER) { - $output = 'smarty_modifier_'.$func.'('.implode(', ', $params).')'; - } elseif ($pluginType & Dwoo::PROXY_PLUGIN) { - $params = $this->mapParams($params, $this->getDwoo()->getPluginProxy()->getCallback($func), $state); - } elseif ($pluginType & Dwoo::TEMPLATE_PLUGIN) { - // transforms the parameter array from (x=>array('paramname'=>array(values))) to (paramname=>array(values)) - $map = array(); - foreach ($this->templatePlugins[$func]['params'] as $param=>$defValue) { - if ($param == 'rest') { - $param = '*'; - } - $hasDefault = $defValue !== null; - if ($defValue === 'null') { - $defValue = null; - } elseif ($defValue === 'false') { - $defValue = false; - } elseif ($defValue === 'true') { - $defValue = true; - } elseif (preg_match('#^([\'"]).*?\1$#', $defValue)) { - $defValue = substr($defValue, 1, -1); - } - $map[] = array($param, $hasDefault, $defValue); - } - - $params = $this->mapParams($params, null, $state, $map); - } - - // only keep php-syntax-safe values for non-block plugins - foreach ($params as &$p) { - $p = $p[0]; - } - if ($pluginType & Dwoo::NATIVE_PLUGIN) { - if ($func === 'do') { - if (isset($params['*'])) { - $output = implode(';', $params['*']).';'; - } else { - $output = ''; - } - - if (is_array($parsingParams) || $curBlock !== 'root') { - throw new Dwoo_Compilation_Exception($this, 'Do can not be used inside another function or block'); - } else { - return self::PHP_OPEN.$output.self::PHP_CLOSE; - } - } else { - if (isset($params['*'])) { - $output = $func.'('.implode(', ', $params['*']).')'; - } else { - $output = $func.'()'; - } - } - } elseif ($pluginType & Dwoo::FUNC_PLUGIN) { - if ($pluginType & Dwoo::COMPILABLE_PLUGIN) { - if ($pluginType & Dwoo::CUSTOM_PLUGIN) { - $funcCompiler = $this->customPlugins[$func]['callback']; - } else { - $funcCompiler = 'Dwoo_Plugin_'.$func.'_compile'; - } - array_unshift($params, $this); - $output = call_user_func_array($funcCompiler, $params); - } else { - array_unshift($params, '$this'); - $params = self::implode_r($params); - - if ($pluginType & Dwoo::CUSTOM_PLUGIN) { - $callback = $this->customPlugins[$func]['callback']; - $output = 'call_user_func(\''.$callback.'\', '.$params.')'; - } else { - $output = 'Dwoo_Plugin_'.$func.'('.$params.')'; - } - } - } elseif ($pluginType & Dwoo::CLASS_PLUGIN) { - if ($pluginType & Dwoo::COMPILABLE_PLUGIN) { - if ($pluginType & Dwoo::CUSTOM_PLUGIN) { - $callback = $this->customPlugins[$func]['callback']; - if (!is_array($callback)) { - if (!method_exists($callback, 'compile')) { - throw new Dwoo_Exception('Custom plugin '.$func.' must implement the "compile" method to be compilable, or you should provide a full callback to the method to use'); - } - if (($ref = new ReflectionMethod($callback, 'compile')) && $ref->isStatic()) { - $funcCompiler = array($callback, 'compile'); - } else { - $funcCompiler = array(new $callback, 'compile'); - } - } else { - $funcCompiler = $callback; - } - } else { - $funcCompiler = array('Dwoo_Plugin_'.$func, 'compile'); - array_unshift($params, $this); - } - $output = call_user_func_array($funcCompiler, $params); - } else { - $params = self::implode_r($params); - if ($pluginType & Dwoo::CUSTOM_PLUGIN) { - $callback = $this->customPlugins[$func]['callback']; - if (!is_array($callback)) { - if (!method_exists($callback, 'process')) { - throw new Dwoo_Exception('Custom plugin '.$func.' must implement the "process" method to be usable, or you should provide a full callback to the method to use'); - } - if (($ref = new ReflectionMethod($callback, 'process')) && $ref->isStatic()) { - $output = 'call_user_func(array(\''.$callback.'\', \'process\'), '.$params.')'; - } else { - $output = 'call_user_func(array($this->getObjectPlugin(\''.$callback.'\'), \'process\'), '.$params.')'; - } - } elseif (is_object($callback[0])) { - $output = 'call_user_func(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), '.$params.')'; - } elseif (($ref = new ReflectionMethod($callback[0], $callback[1])) && $ref->isStatic()) { - $output = 'call_user_func(array(\''.$callback[0].'\', \''.$callback[1].'\'), '.$params.')'; - } else { - $output = 'call_user_func(array($this->getObjectPlugin(\''.$callback[0].'\'), \''.$callback[1].'\'), '.$params.')'; - } - if (empty($params)) { - $output = substr($output, 0, -3).')'; - } - } else { - $output = '$this->classCall(\''.$func.'\', array('.$params.'))'; - } - } - } elseif ($pluginType & Dwoo::PROXY_PLUGIN) { - $output = call_user_func(array($this->dwoo->getPluginProxy(), 'getCode'), $func, $params); - } elseif ($pluginType & Dwoo::SMARTY_FUNCTION) { - if (isset($params['*'])) { - $params = self::implode_r($params['*'], true); - } else { - $params = ''; - } - - if ($pluginType & Dwoo::CUSTOM_PLUGIN) { - $callback = $this->customPlugins[$func]['callback']; - if (is_array($callback)) { - if (is_object($callback[0])) { - $output = 'call_user_func_array(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), array(array('.$params.'), $this))'; - } else { - $output = 'call_user_func_array(array(\''.$callback[0].'\', \''.$callback[1].'\'), array(array('.$params.'), $this))'; - } - } else { - $output = $callback.'(array('.$params.'), $this)'; - } - } else { - $output = 'smarty_function_'.$func.'(array('.$params.'), $this)'; - } - } elseif ($pluginType & Dwoo::TEMPLATE_PLUGIN) { - array_unshift($params, '$this'); - $params = self::implode_r($params); - $output = 'Dwoo_Plugin_'.$func.'_'.$this->templatePlugins[$func]['uuid'].'('.$params.')'; - $this->templatePlugins[$func]['called'] = true; - } - - if (is_array($parsingParams)) { - $parsingParams[] = array($output, $output); - return $parsingParams; - } elseif ($curBlock === 'namedparam') { - return array($output, $output); - } else { - return $output; - } - } - - /** - * parses a string - * - * @param string $in the string within which we must parse something - * @param int $from the starting offset of the parsed area - * @param int $to the ending offset of the parsed area - * @param mixed $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default - * @param string $curBlock the current parser-block being processed - * @param mixed $pointer a reference to a pointer that will be increased by the amount of characters parsed, or null by default - * @return string parsed values - */ - protected function parseString($in, $from, $to, $parsingParams = false, $curBlock='', &$pointer = null) - { - $substr = substr($in, $from, $to-$from); - $first = $substr[0]; - - if ($this->debug) echo 'STRING FOUND (in '.htmlentities(substr($in, $from, min($to-$from, 50))).(($to-$from) > 50 ? '...':'').')
'; - $strend = false; - $o = $from+1; - while ($strend === false) { - $strend = strpos($in, $first, $o); - if ($strend === false) { - throw new Dwoo_Compilation_Exception($this, 'Unfinished string, started with '.substr($in, $from, $to-$from)); - } - if (substr($in, $strend-1, 1) === '\\') { - $o = $strend+1; - $strend = false; - } - } - if ($this->debug) echo 'STRING DELIMITED: '.substr($in, $from, $strend+1-$from).'
'; - - $srcOutput = substr($in, $from, $strend+1-$from); - - if ($pointer !== null) { - $pointer += strlen($srcOutput); - } - - $output = $this->replaceStringVars($srcOutput, $first); - - // handle modifiers - if ($curBlock !== 'modifier' && preg_match('#^((?:\|(?:@?[a-z0-9_]+(?::.*)*))+)#i', substr($substr, $strend+1-$from), $match)) { - $modstr = $match[1]; - - if ($curBlock === 'root' && substr($modstr, -1) === '}') { - $modstr = substr($modstr, 0, -1); - } - $modstr = str_replace('\\'.$first, $first, $modstr); - $ptr = 0; - $output = $this->replaceModifiers(array(null, null, $output, $modstr), 'string', $ptr); - - $strend += $ptr; - if ($pointer !== null) { - $pointer += $ptr; - } - $srcOutput .= substr($substr, $strend+1-$from, $ptr); - } - - if (is_array($parsingParams)) { - $parsingParams[] = array($output, substr($srcOutput, 1, -1)); - return $parsingParams; - } elseif ($curBlock === 'namedparam') { - return array($output, substr($srcOutput, 1, -1)); - } else { - return $output; - } - } - - /** - * parses a constant - * - * @param string $in the string within which we must parse something - * @param int $from the starting offset of the parsed area - * @param int $to the ending offset of the parsed area - * @param mixed $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default - * @param string $curBlock the current parser-block being processed - * @param mixed $pointer a reference to a pointer that will be increased by the amount of characters parsed, or null by default - * @return string parsed values - */ - protected function parseConst($in, $from, $to, $parsingParams = false, $curBlock='', &$pointer = null) - { - $substr = substr($in, $from, $to-$from); - - if ($this->debug) { - echo 'CONST FOUND : '.$substr.'
'; - } - - if (!preg_match('#^%([a-z0-9_:]+)#i', $substr, $m)) { - throw new Dwoo_Compilation_Exception($this, 'Invalid constant'); - } - - if ($pointer !== null) { - $pointer += strlen($m[0]); - } - - $output = $this->parseConstKey($m[1], $curBlock); - - if (is_array($parsingParams)) { - $parsingParams[] = array($output, $m[1]); - return $parsingParams; - } elseif ($curBlock === 'namedparam') { - return array($output, $m[1]); - } else { - return $output; - } - } - - /** - * parses a constant - * - * @param string $key the constant to parse - * @param string $curBlock the current parser-block being processed - * @return string parsed constant - */ - protected function parseConstKey($key, $curBlock) - { - if ($this->securityPolicy !== null && $this->securityPolicy->getConstantHandling() === Dwoo_Security_Policy::CONST_DISALLOW) { - return 'null'; - } - - if ($curBlock !== 'root') { - $output = '(defined("'.$key.'") ? '.$key.' : null)'; - } else { - $output = $key; - } - - return $output; - } - - /** - * parses a variable - * - * @param string $in the string within which we must parse something - * @param int $from the starting offset of the parsed area - * @param int $to the ending offset of the parsed area - * @param mixed $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default - * @param string $curBlock the current parser-block being processed - * @param mixed $pointer a reference to a pointer that will be increased by the amount of characters parsed, or null by default - * @return string parsed values - */ - protected function parseVar($in, $from, $to, $parsingParams = false, $curBlock='', &$pointer = null) - { - $substr = substr($in, $from, $to-$from); - - if (preg_match('#(\$?\.?[a-z0-9_:]*(?:(?:(?:\.|->)(?:[a-z0-9_:]+|(?R))|\[(?:[a-z0-9_:]+|(?R)|(["\'])[^\2]*?\2)\]))*)' . // var key - ($curBlock==='root' || $curBlock==='function' || $curBlock==='namedparam' || $curBlock==='condition' || $curBlock==='variable' || $curBlock==='expression' ? '(\(.*)?' : '()') . // method call - ($curBlock==='root' || $curBlock==='function' || $curBlock==='namedparam' || $curBlock==='condition' || $curBlock==='variable' || $curBlock==='delimited_string' ? '((?:(?:[+/*%=-])(?:(?_:-]+(?:\([^)]*\))?|(?'))); - $key = substr($match[1], 1, strrpos($match[1], '->')-1); - $methodCall = substr($match[1], strrpos($match[1], '->')) . $match[3]; - } - - if ($hasModifiers) { - $matchedLength -= strlen($match[5]); - } - - if ($pointer !== null) { - $pointer += $matchedLength; - } - - // replace useless brackets by dot accessed vars - $key = preg_replace('#\[([^$%\[.>-]+)\]#', '.$1', $key); - - // prevent $foo->$bar calls because it doesn't seem worth the trouble - if (strpos($key, '->$') !== false) { - throw new Dwoo_Compilation_Exception($this, 'You can not access an object\'s property using a variable name.'); - } - - if ($this->debug) { - if ($hasMethodCall) { - echo 'METHOD CALL FOUND : $'.$key.substr($methodCall, 0, 30).'
'; - } else { - echo 'VAR FOUND : $'.$key.'
'; - } - } - - $key = str_replace('"', '\\"', $key); - - $cnt=substr_count($key, '$'); - if ($cnt > 0) { - $uid = 0; - $parsed = array($uid => ''); - $current =& $parsed; - $curTxt =& $parsed[$uid++]; - $tree = array(); - $chars = str_split($key, 1); - $inSplittedVar = false; - $bracketCount = 0; - - while (($char = array_shift($chars)) !== null) { - if ($char === '[') { - if (count($tree) > 0) { - $bracketCount++; - } else { - $tree[] =& $current; - $current[$uid] = array($uid+1 => ''); - $current =& $current[$uid++]; - $curTxt =& $current[$uid++]; - continue; - } - } elseif ($char === ']') { - if ($bracketCount > 0) { - $bracketCount--; - } else { - $current =& $tree[count($tree)-1]; - array_pop($tree); - if (current($chars) !== '[' && current($chars) !== false && current($chars) !== ']') { - $current[$uid] = ''; - $curTxt =& $current[$uid++]; - } - continue; - } - } elseif ($char === '$') { - if (count($tree) == 0) { - $curTxt =& $current[$uid++]; - $inSplittedVar = true; - } - } elseif (($char === '.' || $char === '-') && count($tree) == 0 && $inSplittedVar) { - $curTxt =& $current[$uid++]; - $inSplittedVar = false; - } - - $curTxt .= $char; - } - unset($uid, $current, $curTxt, $tree, $chars); - - if ($this->debug) echo 'RECURSIVE VAR REPLACEMENT : '.$key.'
'; - - $key = $this->flattenVarTree($parsed); - - if ($this->debug) echo 'RECURSIVE VAR REPLACEMENT DONE : '.$key.'
'; - - $output = preg_replace('#(^""\.|""\.|\.""$|(\()""\.|\.""(\)))#', '$2$3', '$this->readVar("'.$key.'")'); - } else { - $output = $this->parseVarKey($key, $hasModifiers ? 'modifier' : $curBlock); - } - - // methods - if ($hasMethodCall) { - $ptr = 0; - - $output = $this->parseMethodCall($output, $methodCall, $curBlock, $ptr); - - if ($pointer !== null) { - $pointer += $ptr; - } - $matchedLength += $ptr; - } - - if ($hasExpression) { - // expressions - preg_match_all('#(?:([+/*%=-])(=?-?[%$][a-z0-9.[\]>_:-]+(?:\([^)]*\))?|=?-?[0-9.,]+|\1))#i', $match[4], $expMatch); - - foreach ($expMatch[1] as $k=>$operator) { - if (substr($expMatch[2][$k], 0, 1)==='=') { - $assign = true; - if ($operator === '=') { - throw new Dwoo_Compilation_Exception($this, 'Invalid expression '.$substr.', can not use "==" in expressions'); - } - if ($curBlock !== 'root') { - throw new Dwoo_Compilation_Exception($this, 'Invalid expression '.$substr.', assignments can only be used in top level expressions like {$foo+=3} or {$foo="bar"}'); - } - $operator .= '='; - $expMatch[2][$k] = substr($expMatch[2][$k], 1); - } - - if (substr($expMatch[2][$k], 0, 1)==='-' && strlen($expMatch[2][$k]) > 1) { - $operator .= '-'; - $expMatch[2][$k] = substr($expMatch[2][$k], 1); - } - if (($operator==='+'||$operator==='-') && $expMatch[2][$k]===$operator) { - $output = '('.$output.$operator.$operator.')'; - break; - } elseif (substr($expMatch[2][$k], 0, 1) === '$') { - $output = '('.$output.' '.$operator.' '.$this->parseVar($expMatch[2][$k], 0, strlen($expMatch[2][$k]), false, 'expression').')'; - } elseif (substr($expMatch[2][$k], 0, 1) === '%') { - $output = '('.$output.' '.$operator.' '.$this->parseConst($expMatch[2][$k], 0, strlen($expMatch[2][$k]), false, 'expression').')'; - } elseif (!empty($expMatch[2][$k])) { - $output = '('.$output.' '.$operator.' '.str_replace(',', '.', $expMatch[2][$k]).')'; - } else { - throw new Dwoo_Compilation_Exception($this, 'Unfinished expression '.$substr.', missing var or number after math operator'); - } - } - } - - if ($this->autoEscape === true) { - $output = '(is_string($tmp='.$output.') ? htmlspecialchars($tmp, ENT_QUOTES, $this->charset) : $tmp)'; - } - - // handle modifiers - if ($curBlock !== 'modifier' && $hasModifiers) { - $ptr = 0; - $output = $this->replaceModifiers(array(null, null, $output, $match[5]), 'var', $ptr); - if ($pointer !== null) { - $pointer += $ptr; - } - $matchedLength += $ptr; - } - - if (is_array($parsingParams)) { - $parsingParams[] = array($output, $key); - return $parsingParams; - } elseif ($curBlock === 'namedparam') { - return array($output, $key); - } elseif ($curBlock === 'string' || $curBlock === 'delimited_string') { - return array($matchedLength, $output); - } elseif ($curBlock === 'expression' || $curBlock === 'variable') { - return $output; - } elseif (isset($assign)) { - return self::PHP_OPEN.$output.';'.self::PHP_CLOSE; - } else { - return $output; - } - } else { - if ($curBlock === 'string' || $curBlock === 'delimited_string') { - return array(0, ''); - } else { - throw new Dwoo_Compilation_Exception($this, 'Invalid variable name '.$substr.''); - } - } - } - - /** - * parses any number of chained method calls/property reads - * - * @param string $output the variable or whatever upon which the method are called - * @param string $methodCall method call source, starting at "->" - * @param string $curBlock the current parser-block being processed - * @param int $pointer a reference to a pointer that will be increased by the amount of characters parsed - * @return string parsed call(s)/read(s) - */ - protected function parseMethodCall($output, $methodCall, $curBlock, &$pointer) - { - $ptr = 0; - $len = strlen($methodCall); - - while ($ptr < $len) { - if (strpos($methodCall, '->', $ptr) === $ptr) { - $ptr += 2; - } - - if (in_array($methodCall[$ptr], array(';', '/', ' ', "\t", "\r", "\n", ')', '+', '*', '%', '=', '-', '|')) || substr($methodCall, $ptr, strlen($this->rd)) === $this->rd) { - // break char found - break; - } - - if(!preg_match('/^([a-z0-9_]+)(\(.*?\))?/i', substr($methodCall, $ptr), $methMatch)) { - throw new Dwoo_Compilation_Exception($this, 'Invalid method name : '.substr($methodCall, $ptr, 20)); - } - - if (empty($methMatch[2])) { - // property - if ($curBlock === 'root') { - $output .= '->'.$methMatch[1]; - } else { - $output = '(($tmp = '.$output.') ? $tmp->'.$methMatch[1].' : null)'; - } - $ptr += strlen($methMatch[1]); - } else { - // method - if (substr($methMatch[2], 0, 2) === '()') { - $parsedCall = '->'.$methMatch[1].'()'; - $ptr += strlen($methMatch[1]) + 2; - } else { - $parsedCall = '->'.$this->parseFunction($methodCall, $ptr, strlen($methodCall), false, 'method', $ptr); - } - if ($curBlock === 'root') { - $output .= $parsedCall; - } else { - $output = '(($tmp = '.$output.') ? $tmp'.$parsedCall.' : null)'; - } - } - } - - $pointer += $ptr; - return $output; - } - - /** - * parses a constant variable (a variable that doesn't contain another variable) and preprocesses it to save runtime processing time - * - * @param string $key the variable to parse - * @param string $curBlock the current parser-block being processed - * @return string parsed variable - */ - protected function parseVarKey($key, $curBlock) - { - if ($key === '') { - return '$this->scope'; - } - if (substr($key, 0, 1) === '.') { - $key = 'dwoo'.$key; - } - if (preg_match('#dwoo\.(get|post|server|cookies|session|env|request)((?:\.[a-z0-9_-]+)+)#i', $key, $m)) { - $global = strtoupper($m[1]); - if ($global === 'COOKIES') { - $global = 'COOKIE'; - } - $key = '$_'.$global; - foreach (explode('.', ltrim($m[2], '.')) as $part) - $key .= '['.var_export($part, true).']'; - if ($curBlock === 'root') { - $output = $key; - } else { - $output = '(isset('.$key.')?'.$key.':null)'; - } - } elseif (preg_match('#dwoo\.const\.([a-z0-9_:]+)#i', $key, $m)) { - return $this->parseConstKey($m[1], $curBlock); - } elseif ($this->scope !== null) { - if (strstr($key, '.') === false && strstr($key, '[') === false && strstr($key, '->') === false) { - if ($key === 'dwoo') { - $output = '$this->globals'; - } elseif ($key === '_root' || $key === '__') { - $output = '$this->data'; - } elseif ($key === '_parent' || $key === '_') { - $output = '$this->readParentVar(1)'; - } elseif ($key === '_key') { - $output = '$tmp_key'; - } else { - if ($curBlock === 'root') { - $output = '$this->scope["'.$key.'"]'; - } else { - $output = '(isset($this->scope["'.$key.'"]) ? $this->scope["'.$key.'"] : null)'; - } - } - } else { - preg_match_all('#(\[|->|\.)?((?:[a-z0-9_]|-(?!>))+|(\\\?[\'"])[^\3]*?\3)\]?#i', $key, $m); - - $i = $m[2][0]; - if ($i === '_parent' || $i === '_') { - $parentCnt = 0; - - while (true) { - $parentCnt++; - array_shift($m[2]); - array_shift($m[1]); - if (current($m[2]) === '_parent') { - continue; - } - break; - } - - $output = '$this->readParentVar('.$parentCnt.')'; - } else { - if ($i === 'dwoo') { - $output = '$this->globals'; - array_shift($m[2]); - array_shift($m[1]); - } elseif ($i === '_root' || $i === '__') { - $output = '$this->data'; - array_shift($m[2]); - array_shift($m[1]); - } elseif ($i === '_key') { - $output = '$tmp_key'; - } else { - $output = '$this->scope'; - } - - while (count($m[1]) && $m[1][0] !== '->') { - $m[2][0] = preg_replace('/(^\\\([\'"])|\\\([\'"])$)/x', '$2$3', $m[2][0]); - if(substr($m[2][0], 0, 1) == '"' || substr($m[2][0], 0, 1) == "'") { - $output .= '['.$m[2][0].']'; - } else { - $output .= '["'.$m[2][0].'"]'; - } - array_shift($m[2]); - array_shift($m[1]); - } - - if ($curBlock !== 'root') { - $output = '(isset('.$output.') ? '.$output.':null)'; - } - } - - if (count($m[2])) { - unset($m[0]); - $output = '$this->readVarInto('.str_replace("\n", '', var_export($m, true)).', '.$output.', '.($curBlock == 'root' ? 'false': 'true').')'; - } - } - } else { - preg_match_all('#(\[|->|\.)?((?:[a-z0-9_]|-(?!>))+)\]?#i', $key, $m); - unset($m[0]); - $output = '$this->readVar('.str_replace("\n", '', var_export($m, true)).')'; - } - - return $output; - } - - /** - * flattens a variable tree, this helps in parsing very complex variables such as $var.foo[$foo.bar->baz].baz, - * it computes the contents of the brackets first and works out from there - * - * @param array $tree the variable tree parsed by he parseVar() method that must be flattened - * @param bool $recursed leave that to false by default, it is only for internal use - * @return string flattened tree - */ - protected function flattenVarTree(array $tree, $recursed=false) - { - $out = $recursed ? '".$this->readVarInto(' : ''; - foreach ($tree as $bit) { - if (is_array($bit)) { - $out.='.'.$this->flattenVarTree($bit, false); - } else { - $key = str_replace('"', '\\"', $bit); - - if (substr($key, 0, 1)==='$') { - $out .= '".'.$this->parseVar($key, 0, strlen($key), false, 'variable').'."'; - } else { - $cnt = substr_count($key, '$'); - - if ($this->debug) echo 'PARSING SUBVARS IN : '.$key.'
'; - if ($cnt > 0) { - while (--$cnt >= 0) { - if (isset($last)) { - $last = strrpos($key, '$', - (strlen($key) - $last + 1)); - } else { - $last = strrpos($key, '$'); - } - preg_match('#\$[a-z0-9_]+((?:(?:\.|->)(?:[a-z0-9_]+|(?R))|\[(?:[a-z0-9_]+|(?R))\]))*'. - '((?:(?:[+/*%-])(?:\$[a-z0-9.[\]>_:-]+(?:\([^)]*\))?|[0-9.,]*))*)#i', substr($key, $last), $submatch); - - $len = strlen($submatch[0]); - $key = substr_replace( - $key, - preg_replace_callback( - '#(\$[a-z0-9_]+((?:(?:\.|->)(?:[a-z0-9_]+|(?R))|\[(?:[a-z0-9_]+|(?R))\]))*)'. - '((?:(?:[+/*%-])(?:\$[a-z0-9.[\]>_:-]+(?:\([^)]*\))?|[0-9.,]*))*)#i', - array($this, 'replaceVarKeyHelper'), substr($key, $last, $len) - ), - $last, - $len - ); - if ($this->debug) echo 'RECURSIVE VAR REPLACEMENT DONE : '.$key.'
'; - } - unset($last); - - $out .= $key; - } else { - $out .= $key; - } - } - } - } - $out .= $recursed ? ', true)."' : ''; - return $out; - } - - /** - * helper function that parses a variable - * - * @param array $match the matched variable, array(1=>"string match") - * @return string parsed variable - */ - protected function replaceVarKeyHelper($match) - { - return '".'.$this->parseVar($match[0], 0, strlen($match[0]), false, 'variable').'."'; - } - - /** - * parses various constants, operators or non-quoted strings - * - * @param string $in the string within which we must parse something - * @param int $from the starting offset of the parsed area - * @param int $to the ending offset of the parsed area - * @param mixed $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default - * @param string $curBlock the current parser-block being processed - * @param mixed $pointer a reference to a pointer that will be increased by the amount of characters parsed, or null by default - * @return string parsed values - */ - protected function parseOthers($in, $from, $to, $parsingParams = false, $curBlock='', &$pointer = null) - { - $first = $in[$from]; - $substr = substr($in, $from, $to-$from); - - $end = strlen($substr); - - if ($curBlock === 'condition') { - $breakChars = array('(', ')', ' ', '||', '&&', '|', '&', '>=', '<=', '===', '==', '=', '!==', '!=', '<<', '<', '>>', '>', '^', '~', ',', '+', '-', '*', '/', '%', '!', '?', ':', $this->rd, ';'); - } elseif ($curBlock === 'modifier') { - $breakChars = array(' ', ',', ')', ':', '|', "\r", "\n", "\t", ";", $this->rd); - } elseif ($curBlock === 'expression') { - $breakChars = array('/', '%', '+', '-', '*', ' ', ',', ')', "\r", "\n", "\t", ";", $this->rd); - } else { - $breakChars = array(' ', ',', ')', "\r", "\n", "\t", ";", $this->rd); - } - - $breaker = false; - while (list($k,$char) = each($breakChars)) { - $test = strpos($substr, $char); - if ($test !== false && $test < $end) { - $end = $test; - $breaker = $k; - } - } - - if ($curBlock === 'condition') { - if ($end === 0 && $breaker !== false) { - $end = strlen($breakChars[$breaker]); - } - } - - if ($end !== false) { - $substr = substr($substr, 0, $end); - } - - if ($pointer !== null) { - $pointer += strlen($substr); - } - - $src = $substr; - $substr = trim($substr); - - if (strtolower($substr) === 'false' || strtolower($substr) === 'no' || strtolower($substr) === 'off') { - if ($this->debug) echo 'BOOLEAN(FALSE) PARSED
'; - $substr = 'false'; - } elseif (strtolower($substr) === 'true' || strtolower($substr) === 'yes' || strtolower($substr) === 'on') { - if ($this->debug) echo 'BOOLEAN(TRUE) PARSED
'; - $substr = 'true'; - } elseif ($substr === 'null' || $substr === 'NULL') { - if ($this->debug) echo 'NULL PARSED
'; - $substr = 'null'; - } elseif (is_numeric($substr)) { - $substr = (float) $substr; - if ((int) $substr == $substr) { - $substr = (int) $substr; - } - if ($this->debug) echo 'NUMBER ('.$substr.') PARSED
'; - } elseif (preg_match('{^-?(\d+|\d*(\.\d+))\s*([/*%+-]\s*-?(\d+|\d*(\.\d+)))+$}', $substr)) { - if ($this->debug) echo 'SIMPLE MATH PARSED
'; - $substr = '('.$substr.')'; - } elseif ($curBlock === 'condition' && array_search($substr, $breakChars, true) !== false) { - if ($this->debug) echo 'BREAKCHAR ('.$substr.') PARSED
'; - //$substr = '"'.$substr.'"'; - } else { - $substr = $this->replaceStringVars('\''.str_replace('\'', '\\\'', $substr).'\'', '\'', $curBlock); - - if ($this->debug) echo 'BLABBER ('.$substr.') CASTED AS STRING
'; - } - - if (is_array($parsingParams)) { - $parsingParams[] = array($substr, $src); - return $parsingParams; - } elseif ($curBlock === 'namedparam') { - return array($substr, $src); - } elseif ($curBlock === 'expression') { - return $substr; - } else { - throw new Exception('Something went wrong'); - } - } - - /** - * replaces variables within a parsed string - * - * @param string $string the parsed string - * @param string $first the first character parsed in the string, which is the string delimiter (' or ") - * @param string $curBlock the current parser-block being processed - * @return string the original string with variables replaced - */ - protected function replaceStringVars($string, $first, $curBlock='') - { - $pos = 0; - if ($this->debug) echo 'STRING VAR REPLACEMENT : '.$string.'
'; - // replace vars - while (($pos = strpos($string, '$', $pos)) !== false) { - $prev = substr($string, $pos-1, 1); - if ($prev === '\\') { - $pos++; - continue; - } - - $var = $this->parse($string, $pos, null, false, ($curBlock === 'modifier' ? 'modifier' : ($prev === '`' ? 'delimited_string':'string'))); - $len = $var[0]; - $var = $this->parse(str_replace('\\'.$first, $first, $string), $pos, null, false, ($curBlock === 'modifier' ? 'modifier' : ($prev === '`' ? 'delimited_string':'string'))); - - if ($prev === '`' && substr($string, $pos+$len, 1) === '`') { - $string = substr_replace($string, $first.'.'.$var[1].'.'.$first, $pos-1, $len+2); - } else { - $string = substr_replace($string, $first.'.'.$var[1].'.'.$first, $pos, $len); - } - $pos += strlen($var[1]) + 2; - if ($this->debug) echo 'STRING VAR REPLACEMENT DONE : '.$string.'
'; - } - - // handle modifiers - // TODO Obsolete? - $string = preg_replace_callback('#("|\')\.(.+?)\.\1((?:\|(?:@?[a-z0-9_]+(?:(?::("|\').+?\4|:[^`]*))*))+)#i', array($this, 'replaceModifiers'), $string); - - // replace escaped dollar operators by unescaped ones if required - if ($first==="'") { - $string = str_replace('\\$', '$', $string); - } - - return $string; - } - - /** - * replaces the modifiers applied to a string or a variable - * - * @param array $m the regex matches that must be array(1=>"double or single quotes enclosing a string, when applicable", 2=>"the string or var", 3=>"the modifiers matched") - * @param string $curBlock the current parser-block being processed - * @return string the input enclosed with various function calls according to the modifiers found - */ - protected function replaceModifiers(array $m, $curBlock = null, &$pointer = null) - { - if ($this->debug) echo 'PARSING MODIFIERS : '.$m[3].'
'; - - if ($pointer !== null) { - $pointer += strlen($m[3]); - } - // remove first pipe - $cmdstrsrc = substr($m[3], 1); - // remove last quote if present - if (substr($cmdstrsrc, -1, 1) === $m[1]) { - $cmdstrsrc = substr($cmdstrsrc, 0, -1); - $add = $m[1]; - } - - $output = $m[2]; - - $continue = true; - while (strlen($cmdstrsrc) > 0 && $continue) { - if ($cmdstrsrc[0] === '|') { - $cmdstrsrc = substr($cmdstrsrc, 1); - continue; - } - if ($cmdstrsrc[0] === ' ' || $cmdstrsrc[0] === ';' || substr($cmdstrsrc, 0, strlen($this->rd)) === $this->rd) { - if ($this->debug) echo 'MODIFIER PARSING ENDED, RIGHT DELIMITER or ";" FOUND
'; - $continue = false; - if ($pointer !== null) { - $pointer -= strlen($cmdstrsrc); - } - break; - } - $cmdstr = $cmdstrsrc; - $paramsep = ':'; - if (!preg_match('/^(@{0,2}[a-z][a-z0-9_]*)(:)?/i', $cmdstr, $match)) { - throw new Dwoo_Compilation_Exception($this, 'Invalid modifier name, started with : '.substr($cmdstr, 0, 10)); - } - $paramspos = !empty($match[2]) ? strlen($match[1]) : false; - $func = $match[1]; - - $state = 0; - if ($paramspos === false) { - $cmdstrsrc = substr($cmdstrsrc, strlen($func)); - $params = array(); - if ($this->debug) echo 'MODIFIER ('.$func.') CALLED WITH NO PARAMS
'; - } else { - $paramstr = substr($cmdstr, $paramspos+1); - if (substr($paramstr, -1, 1) === $paramsep) { - $paramstr = substr($paramstr, 0, -1); - } - - $ptr = 0; - $params = array(); - while ($ptr < strlen($paramstr)) { - if ($this->debug) echo 'MODIFIER ('.$func.') START PARAM PARSING WITH POINTER AT '.$ptr.'
'; - if ($this->debug) echo $paramstr.'--'.$ptr.'--'.strlen($paramstr).'--modifier
'; - $params = $this->parse($paramstr, $ptr, strlen($paramstr), $params, 'modifier', $ptr); - if ($this->debug) echo 'PARAM PARSED, POINTER AT '.$ptr.'
'; - - if ($ptr >= strlen($paramstr)) { - if ($this->debug) echo 'PARAM PARSING ENDED, PARAM STRING CONSUMED
'; - break; - } - - if ($paramstr[$ptr] === ' ' || $paramstr[$ptr] === '|' || $paramstr[$ptr] === ';' || substr($paramstr, $ptr, strlen($this->rd)) === $this->rd) { - if ($this->debug) echo 'PARAM PARSING ENDED, " ", "|", RIGHT DELIMITER or ";" FOUND, POINTER AT '.$ptr.'
'; - if ($paramstr[$ptr] !== '|') { - $continue = false; - if ($pointer !== null) { - $pointer -= strlen($paramstr) - $ptr; - } - } - $ptr++; - break; - } - if ($ptr < strlen($paramstr) && $paramstr[$ptr] === ':') { - $ptr++; - } - } - $cmdstrsrc = substr($cmdstrsrc, strlen($func)+1+$ptr); - $paramstr = substr($paramstr, 0, $ptr); - foreach ($params as $k=>$p) { - if (is_array($p) && is_array($p[1])) { - $state |= 2; - } else { - if (($state & 2) && preg_match('#^(["\'])(.+?)\1$#', $p[0], $m)) { - $params[$k] = array($m[2], array('true', 'true')); - } else { - if ($state & 2) { - throw new Dwoo_Compilation_Exception($this, 'You can not use an unnamed parameter after a named one'); - } - $state |= 1; - } - } - } - } - - // check if we must use array_map with this plugin or not - $mapped = false; - if (substr($func, 0, 1) === '@') { - $func = substr($func, 1); - $mapped = true; - } - - $pluginType = $this->getPluginType($func); - - if ($state & 2) { - array_unshift($params, array('value', array($output, $output))); - } else { - array_unshift($params, array($output, $output)); - } - - if ($pluginType & Dwoo::NATIVE_PLUGIN) { - $params = $this->mapParams($params, null, $state); - - $params = $params['*'][0]; - - $params = self::implode_r($params); - - if ($mapped) { - $output = '$this->arrayMap(\''.$func.'\', array('.$params.'))'; - } else { - $output = $func.'('.$params.')'; - } - } elseif ($pluginType & Dwoo::PROXY_PLUGIN) { - $params = $this->mapParams($params, $this->getDwoo()->getPluginProxy()->getCallback($func), $state); - foreach ($params as &$p) - $p = $p[0]; - $output = call_user_func(array($this->dwoo->getPluginProxy(), 'getCode'), $func, $params); - } elseif ($pluginType & Dwoo::SMARTY_MODIFIER) { - $params = $this->mapParams($params, null, $state); - $params = $params['*'][0]; - - $params = self::implode_r($params); - - if ($pluginType & Dwoo::CUSTOM_PLUGIN) { - $callback = $this->customPlugins[$func]['callback']; - if (is_array($callback)) { - if (is_object($callback[0])) { - $output = ($mapped ? '$this->arrayMap' : 'call_user_func_array').'(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), array('.$params.'))'; - } else { - $output = ($mapped ? '$this->arrayMap' : 'call_user_func_array').'(array(\''.$callback[0].'\', \''.$callback[1].'\'), array('.$params.'))'; - } - } elseif ($mapped) { - $output = '$this->arrayMap(\''.$callback.'\', array('.$params.'))'; - } else { - $output = $callback.'('.$params.')'; - } - } elseif ($mapped) { - $output = '$this->arrayMap(\'smarty_modifier_'.$func.'\', array('.$params.'))'; - } else { - $output = 'smarty_modifier_'.$func.'('.$params.')'; - } - } else { - if ($pluginType & Dwoo::CUSTOM_PLUGIN) { - $callback = $this->customPlugins[$func]['callback']; - $pluginName = $callback; - } else { - $pluginName = 'Dwoo_Plugin_'.$func; - - if ($pluginType & Dwoo::CLASS_PLUGIN) { - $callback = array($pluginName, ($pluginType & Dwoo::COMPILABLE_PLUGIN) ? 'compile' : 'process'); - } else { - $callback = $pluginName . (($pluginType & Dwoo::COMPILABLE_PLUGIN) ? '_compile' : ''); - } - } - - $params = $this->mapParams($params, $callback, $state); - - foreach ($params as &$p) - $p = $p[0]; - - if ($pluginType & Dwoo::FUNC_PLUGIN) { - if ($pluginType & Dwoo::COMPILABLE_PLUGIN) { - if ($mapped) { - throw new Dwoo_Compilation_Exception($this, 'The @ operator can not be used on compiled plugins.'); - } - if ($pluginType & Dwoo::CUSTOM_PLUGIN) { - $funcCompiler = $this->customPlugins[$func]['callback']; - } else { - $funcCompiler = 'Dwoo_Plugin_'.$func.'_compile'; - } - array_unshift($params, $this); - $output = call_user_func_array($funcCompiler, $params); - } else { - array_unshift($params, '$this'); - - $params = self::implode_r($params); - if ($mapped) { - $output = '$this->arrayMap(\''.$pluginName.'\', array('.$params.'))'; - } else { - $output = $pluginName.'('.$params.')'; - } - } - } else { - if ($pluginType & Dwoo::COMPILABLE_PLUGIN) { - if ($mapped) { - throw new Dwoo_Compilation_Exception($this, 'The @ operator can not be used on compiled plugins.'); - } - if ($pluginType & Dwoo::CUSTOM_PLUGIN) { - $callback = $this->customPlugins[$func]['callback']; - if (!is_array($callback)) { - if (!method_exists($callback, 'compile')) { - throw new Dwoo_Exception('Custom plugin '.$func.' must implement the "compile" method to be compilable, or you should provide a full callback to the method to use'); - } - if (($ref = new ReflectionMethod($callback, 'compile')) && $ref->isStatic()) { - $funcCompiler = array($callback, 'compile'); - } else { - $funcCompiler = array(new $callback, 'compile'); - } - } else { - $funcCompiler = $callback; - } - } else { - $funcCompiler = array('Dwoo_Plugin_'.$func, 'compile'); - array_unshift($params, $this); - } - $output = call_user_func_array($funcCompiler, $params); - } else { - $params = self::implode_r($params); - - if ($pluginType & Dwoo::CUSTOM_PLUGIN) { - if (is_object($callback[0])) { - $output = ($mapped ? '$this->arrayMap' : 'call_user_func_array').'(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), array('.$params.'))'; - } else { - $output = ($mapped ? '$this->arrayMap' : 'call_user_func_array').'(array(\''.$callback[0].'\', \''.$callback[1].'\'), array('.$params.'))'; - } - } elseif ($mapped) { - $output = '$this->arrayMap(array($this->getObjectPlugin(\'Dwoo_Plugin_'.$func.'\'), \'process\'), array('.$params.'))'; - } else { - $output = '$this->classCall(\''.$func.'\', array('.$params.'))'; - } - } - } - } - } - - if ($curBlock === 'var' || $m[1] === null) { - return $output; - } elseif ($curBlock === 'string' || $curBlock === 'root') { - return $m[1].'.'.$output.'.'.$m[1].(isset($add)?$add:null); - } - } - - /** - * recursively implodes an array in a similar manner as var_export() does but with some tweaks - * to handle pre-compiled values and the fact that we do not need to enclose everything with - * "array" and do not require top-level keys to be displayed - * - * @param array $params the array to implode - * @param bool $recursiveCall if set to true, the function outputs key names for the top level - * @return string the imploded array - */ - public static function implode_r(array $params, $recursiveCall = false) - { - $out = ''; - foreach ($params as $k=>$p) { - if (is_array($p)) { - $out2 = 'array('; - foreach ($p as $k2=>$v) - $out2 .= var_export($k2, true).' => '.(is_array($v) ? 'array('.self::implode_r($v, true).')' : $v).', '; - $p = rtrim($out2, ', ').')'; - } - if ($recursiveCall) { - $out .= var_export($k, true).' => '.$p.', '; - } else { - $out .= $p.', '; - } - } - return rtrim($out, ', '); - } - - /** - * returns the plugin type of a plugin and adds it to the used plugins array if required - * - * @param string $name plugin name, as found in the template - * @return int type as a multi bit flag composed of the Dwoo plugin types constants - */ - protected function getPluginType($name) - { - $pluginType = -1; - - if (($this->securityPolicy === null && (function_exists($name) || strtolower($name) === 'isset' || strtolower($name) === 'empty')) || - ($this->securityPolicy !== null && in_array(strtolower($name), $this->securityPolicy->getAllowedPhpFunctions()) !== false)) { - $phpFunc = true; - } - - while ($pluginType <= 0) { - if (isset($this->templatePlugins[$name])) { - $pluginType = Dwoo::TEMPLATE_PLUGIN | Dwoo::COMPILABLE_PLUGIN; - } elseif (isset($this->customPlugins[$name])) { - $pluginType = $this->customPlugins[$name]['type'] | Dwoo::CUSTOM_PLUGIN; - } elseif (class_exists('Dwoo_Plugin_'.$name, false) !== false) { - if (is_subclass_of('Dwoo_Plugin_'.$name, 'Dwoo_Block_Plugin')) { - $pluginType = Dwoo::BLOCK_PLUGIN; - } else { - $pluginType = Dwoo::CLASS_PLUGIN; - } - $interfaces = class_implements('Dwoo_Plugin_'.$name, false); - if (in_array('Dwoo_ICompilable', $interfaces) !== false || in_array('Dwoo_ICompilable_Block', $interfaces) !== false) { - $pluginType |= Dwoo::COMPILABLE_PLUGIN; - } - } elseif (function_exists('Dwoo_Plugin_'.$name) !== false) { - $pluginType = Dwoo::FUNC_PLUGIN; - } elseif (function_exists('Dwoo_Plugin_'.$name.'_compile')) { - $pluginType = Dwoo::FUNC_PLUGIN | Dwoo::COMPILABLE_PLUGIN; - } elseif (function_exists('smarty_modifier_'.$name) !== false) { - $pluginType = Dwoo::SMARTY_MODIFIER; - } elseif (function_exists('smarty_function_'.$name) !== false) { - $pluginType = Dwoo::SMARTY_FUNCTION; - } elseif (function_exists('smarty_block_'.$name) !== false) { - $pluginType = Dwoo::SMARTY_BLOCK; - } else { - if ($pluginType===-1) { - try { - $this->dwoo->getLoader()->loadPlugin($name, isset($phpFunc)===false); - } catch (Exception $e) { - if (isset($phpFunc)) { - $pluginType = Dwoo::NATIVE_PLUGIN; - } elseif (is_object($this->dwoo->getPluginProxy()) && $this->dwoo->getPluginProxy()->handles($name)) { - $pluginType = Dwoo::PROXY_PLUGIN; - break; - } else { - throw $e; - } - } - } else { - throw new Dwoo_Exception('Plugin "'.$name.'" could not be found'); - } - $pluginType++; - } - } - - if (($pluginType & Dwoo::COMPILABLE_PLUGIN) === 0 && ($pluginType & Dwoo::NATIVE_PLUGIN) === 0 && ($pluginType & Dwoo::PROXY_PLUGIN) === 0) { - $this->addUsedPlugin($name, $pluginType); - } - - return $pluginType; - } - - /** - * allows a plugin to load another one at compile time, this will also mark - * it as used by this template so it will be loaded at runtime (which can be - * useful for compiled plugins that rely on another plugin when their compiled - * code runs) - * - * @param string $name the plugin name - */ - public function loadPlugin($name) { - $this->getPluginType($name); - } - - /** - * runs htmlentities over the matched blocks when the security policy enforces that - * - * @param array $match matched php block - * @return string the htmlentities-converted string - */ - protected function phpTagEncodingHelper($match) - { - return htmlspecialchars($match[0]); - } - - /** - * maps the parameters received from the template onto the parameters required by the given callback - * - * @param array $params the array of parameters - * @param callback $callback the function or method to reflect on to find out the required parameters - * @param int $callType the type of call in the template, 0 = no params, 1 = php-style call, 2 = named parameters call - * @param array $map the parameter map to use, if not provided it will be built from the callback - * @return array parameters sorted in the correct order with missing optional parameters filled - */ - protected function mapParams(array $params, $callback, $callType=2, $map = null) - { - if (!$map) { - $map = $this->getParamMap($callback); - } - - $paramlist = array(); - - // transforms the parameter array from (x=>array('paramname'=>array(values))) to (paramname=>array(values)) - $ps = array(); - foreach ($params as $p) { - if (is_array($p[1])) { - $ps[$p[0]] = $p[1]; - } else { - $ps[] = $p; - } - } - - // loops over the param map and assigns values from the template or default value for unset optional params - while (list($k,$v) = each($map)) { - if ($v[0] === '*') { - // "rest" array parameter, fill every remaining params in it and then break - if (count($ps) === 0) { - if ($v[1]===false) { - throw new Dwoo_Compilation_Exception($this, 'Rest argument missing for '.str_replace(array('Dwoo_Plugin_', '_compile'), '', (is_array($callback) ? $callback[0] : $callback))); - } else { - break; - } - } - $tmp = array(); - $tmp2 = array(); - foreach ($ps as $i=>$p) { - $tmp[$i] = $p[0]; - $tmp2[$i] = $p[1]; - unset($ps[$i]); - } - $paramlist[$v[0]] = array($tmp, $tmp2); - unset($tmp, $tmp2, $i, $p); - break; - } elseif (isset($ps[$v[0]])) { - // parameter is defined as named param - $paramlist[$v[0]] = $ps[$v[0]]; - unset($ps[$v[0]]); - } elseif (isset($ps[$k])) { - // parameter is defined as ordered param - $paramlist[$v[0]] = $ps[$k]; - unset($ps[$k]); - } elseif ($v[1]===false) { - // parameter is not defined and not optional, throw error - if (is_array($callback)) { - if (is_object($callback[0])) { - $name = get_class($callback[0]) . '::' . $callback[1]; - } else { - $name = $callback[0]; - } - } else { - $name = $callback; - } - - throw new Dwoo_Compilation_Exception($this, 'Argument '.$k.'/'.$v[0].' missing for '.str_replace(array('Dwoo_Plugin_', '_compile'), '', $name)); - } elseif ($v[2]===null) { - // enforce lowercased null if default value is null (php outputs NULL with var export) - $paramlist[$v[0]] = array('null', null); - } else { - // outputs default value with var_export - $paramlist[$v[0]] = array(var_export($v[2], true), $v[2]); - } - } - - if (count($ps)) { - foreach ($ps as $i=>$p) { - array_push($paramlist, $p); - } - } - - return $paramlist; - } - - /** - * returns the parameter map of the given callback, it filters out entries typed as Dwoo and Dwoo_Compiler and turns the rest parameter into a "*" - * - * @param callback $callback the function/method to reflect on - * @return array processed parameter map - */ - protected function getParamMap($callback) - { - if (is_null($callback)) { - return array(array('*', true)); - } - if (is_array($callback)) { - $ref = new ReflectionMethod($callback[0], $callback[1]); - } else { - $ref = new ReflectionFunction($callback); - } - - $out = array(); - foreach ($ref->getParameters() as $param) { - if (($class = $param->getClass()) !== null && $class->name === 'Dwoo') { - continue; - } - if (($class = $param->getClass()) !== null && $class->name === 'Dwoo_Compiler') { - continue; - } - if ($param->getName() === 'rest' && $param->isArray() === true) { - $out[] = array('*', $param->isOptional(), null); - } - $out[] = array($param->getName(), $param->isOptional(), $param->isOptional() ? $param->getDefaultValue() : null); - } - - return $out; - } - - /** - * returns a default instance of this compiler, used by default by all Dwoo templates that do not have a - * specific compiler assigned and when you do not override the default compiler factory function - * - * @see Dwoo::setDefaultCompilerFactory() - * @return Dwoo_Compiler - */ - public static function compilerFactory() - { - if (self::$instance === null) { - new self; - } - return self::$instance; - } -} diff --git a/system/libs/dwoo/Dwoo/Data.php b/system/libs/dwoo/Dwoo/Data.php deleted file mode 100644 index c5f292ec..00000000 --- a/system/libs/dwoo/Dwoo/Data.php +++ /dev/null @@ -1,250 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Data implements Dwoo_IDataProvider -{ - /** - * 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 array|string $name clears only one value if you give a name, multiple values if - * you give an array of names, or 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; - } - } - - /** - * allows to assign variables using the object syntax - * - * @param string $name the variable name - * @param string $value the value to assign to it - */ - public function __set($name, $value) - { - $this->assign($name, $value); - } - - /** - * 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'); - } elseif (!isset($this->data[$name])) { - $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; - } - } - - /** - * returns true if the variable has been assigned already, false otherwise - * - * @param string $name the variable name - * @return bool - */ - public function isAssigned($name) - { - return isset($this->data[$name]); - } - - /** - * supports calls to isset($dwooData->var) - * - * @param string $name the variable name - */ - public function __isset($name) - { - return isset($this->data[$name]); - } - - /** - * unassigns/removes a variable - * - * @param string $name the variable name - */ - public function unassign($name) - { - unset($this->data[$name]); - } - - /** - * supports unsetting variables using the object syntax - * - * @param string $name the variable name - */ - public function __unset($name) - { - unset($this->data[$name]); - } - - /** - * returns a variable if it was assigned - * - * @param string $name the variable name - * @return mixed - */ - public function get($name) - { - return $this->__get($name); - } - - /** - * allows to read variables using the object syntax - * - * @param string $name the variable name - * @return mixed - */ - public function __get($name) - { - if (isset($this->data[$name])) { - return $this->data[$name]; - } else { - throw new Dwoo_Exception('Tried to read a value that was not assigned yet : "'.$name.'"'); - } - } -} diff --git a/system/libs/dwoo/Dwoo/Exception.php b/system/libs/dwoo/Dwoo/Exception.php deleted file mode 100644 index 83549bde..00000000 --- a/system/libs/dwoo/Dwoo/Exception.php +++ /dev/null @@ -1,19 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Exception extends Exception -{ -} diff --git a/system/libs/dwoo/Dwoo/Filter.php b/system/libs/dwoo/Dwoo/Filter.php deleted file mode 100644 index 60845723..00000000 --- a/system/libs/dwoo/Dwoo/Filter.php +++ /dev/null @@ -1,44 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -abstract class Dwoo_Filter -{ - /** - * the dwoo instance that runs this filter - * - * @var Dwoo - */ - protected $dwoo; - - /** - * constructor, if you override it, call parent::__construct($dwoo); or assign - * the dwoo instance yourself if you need it - * - * @param Dwoo $dwoo the dwoo instance that runs this plugin - */ - public function __construct(Dwoo $dwoo) - { - $this->dwoo = $dwoo; - } - - /** - * processes the input and returns it filtered - * - * @param string $input the template to process - * @return string - */ - abstract public function process($input); -} diff --git a/system/libs/dwoo/Dwoo/ICompilable.php b/system/libs/dwoo/Dwoo/ICompilable.php deleted file mode 100644 index 02ad54bf..00000000 --- a/system/libs/dwoo/Dwoo/ICompilable.php +++ /dev/null @@ -1,26 +0,0 @@ -public static function compile(Dwoo_Compiler $compiler, $arg, $arg, ...), - * which replaces the process() method (that means compile() should have all arguments it requires). - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -interface Dwoo_ICompilable -{ - // this replaces the process function - //public static function compile(Dwoo_Compiler $compiler, $arg, $arg, ...); -} diff --git a/system/libs/dwoo/Dwoo/ICompilable/Block.php b/system/libs/dwoo/Dwoo/ICompilable/Block.php deleted file mode 100644 index b7f3b542..00000000 --- a/system/libs/dwoo/Dwoo/ICompilable/Block.php +++ /dev/null @@ -1,21 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -interface Dwoo_ICompilable_Block -{ -} diff --git a/system/libs/dwoo/Dwoo/ICompiler.php b/system/libs/dwoo/Dwoo/ICompiler.php deleted file mode 100644 index 68f7d782..00000000 --- a/system/libs/dwoo/Dwoo/ICompiler.php +++ /dev/null @@ -1,49 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -interface Dwoo_ICompiler -{ - /** - * 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(Dwoo $dwoo, Dwoo_ITemplate $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); - - /** - * sets the security policy object to enforce some php security settings - * - * use this if untrusted persons can modify templates, - * set it on the Dwoo object as it will be passed onto the compiler automatically - * - * @param Dwoo_Security_Policy $policy the security policy object - */ - public function setSecurityPolicy(Dwoo_Security_Policy $policy = null); -} diff --git a/system/libs/dwoo/Dwoo/IDataProvider.php b/system/libs/dwoo/Dwoo/IDataProvider.php deleted file mode 100644 index 35d66317..00000000 --- a/system/libs/dwoo/Dwoo/IDataProvider.php +++ /dev/null @@ -1,25 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -interface Dwoo_IDataProvider -{ - /** - * returns the data as an associative array that will be used in the template - * - * @return array - */ - public function getData(); -} diff --git a/system/libs/dwoo/Dwoo/IElseable.php b/system/libs/dwoo/Dwoo/IElseable.php deleted file mode 100644 index 03002585..00000000 --- a/system/libs/dwoo/Dwoo/IElseable.php +++ /dev/null @@ -1,24 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -interface Dwoo_IElseable -{ -} diff --git a/system/libs/dwoo/Dwoo/ILoader.php b/system/libs/dwoo/Dwoo/ILoader.php deleted file mode 100644 index dc0fe44a..00000000 --- a/system/libs/dwoo/Dwoo/ILoader.php +++ /dev/null @@ -1,30 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -interface Dwoo_ILoader -{ - /** - * loads a plugin file - * - * the second parameter is used to avoid permanent rehashing when using php functions, - * however this means that if you have add a plugin that overrides a php function you have - * to delete the classpath.cache file(s) by hand to force a rehash of the plugins - * - * @param string $class the plugin name, without the Dwoo_Plugin_ prefix - * @param bool $forceRehash if true, the class path caches will be rebuilt if the plugin is not found, in case it has just been added, defaults to true - */ - public function loadPlugin($class, $forceRehash = true); -} diff --git a/system/libs/dwoo/Dwoo/IPluginProxy.php b/system/libs/dwoo/Dwoo/IPluginProxy.php deleted file mode 100644 index 3d02fb40..00000000 --- a/system/libs/dwoo/Dwoo/IPluginProxy.php +++ /dev/null @@ -1,65 +0,0 @@ - - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Denis Arh, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -interface Dwoo_IPluginProxy -{ - /** - * returns true or false to say whether the given plugin is handled by this proxy or not - * - * @param string $name the plugin name - * @return bool true if the plugin is known and usable, otherwise false - */ - public function handles($name); - - /** - * returns the code (as a string) to call the plugin - * (this will be executed at runtime inside the Dwoo class) - * - * @param string $name the plugin name - * @param array $params a parameter array, array key "*" is the rest array - * @return string - */ - public function getCode($name, $params); - - /** - * returns a callback to the plugin, this is used with the reflection API to - * find out about the plugin's parameter names etc. - * - * should you need a rest array without the possibility to edit the - * plugin's code, you can provide a callback to some - * other function with the correct parameter signature, i.e. : - * - * return array($this, "callbackHelper"); - * // and callbackHelper would be as such: - * public function callbackHelper(array $rest=array()){} - * - * - * @param string $name the plugin name - * @return callback - */ - public function getCallback($name); - - /** - * returns some code that will check if the plugin is loaded and if not load it - * this is optional, if your plugins are autoloaded or whatever, just return an - * empty string - * - * @param string $name the plugin name - * @return string - */ - public function getLoader($name); -} \ No newline at end of file diff --git a/system/libs/dwoo/Dwoo/ITemplate.php b/system/libs/dwoo/Dwoo/ITemplate.php deleted file mode 100644 index 5c83dcb0..00000000 --- a/system/libs/dwoo/Dwoo/ITemplate.php +++ /dev/null @@ -1,150 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - */ -interface Dwoo_ITemplate -{ - /** - * returns the cache duration for this template - * - * defaults to null if it was not provided - * - * @return int|null - */ - public function getCacheTime(); - - /** - * sets the cache duration for this template - * - * can be used to set it after the object is created if you did not provide - * it in the constructor - * - * @param int $seconds duration of the cache validity for this template, if - * null it defaults to the Dwoo instance's cache time. 0 = disable and - * -1 = infinite cache - */ - public function setCacheTime($seconds = null); - - /** - * 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 - * @return mixed full path of the cached file or false upon failure - */ - public function cache(Dwoo $dwoo, $output); - - /** - * clears the cached template if it's older than the given time - * - * @param Dwoo $dwoo the dwoo instance that was used to cache that template - * @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(Dwoo $dwoo, $olderThan = -1); - - /** - * returns the compiled template file name - * - * @param Dwoo $dwoo the dwoo instance that requests it - * @param Dwoo_ICompiler $compiler the compiler that must be used - * @return string - */ - public function getCompiledTemplate(Dwoo $dwoo, Dwoo_ICompiler $compiler = null); - - /** - * returns the template name - * - * @return string - */ - public function getName(); - - /** - * returns the resource name for this template class - * - * @return string - */ - public function getResourceName(); - - /** - * returns the resource identifier for this template or false if it has no identifier - * - * @return string|false - */ - public function getResourceIdentifier(); - - /** - * returns the template source of this template - * - * @return string - */ - public function getSource(); - - /** - * returns an unique string identifying the current version of this template, - * for example a timestamp of the last modified date or a hash of the template source - * - * @return string - */ - public function getUid(); - - /** - * returns the compiler used by this template, if it was just compiled, or null - * - * @return Dwoo_ICompiler - */ - public function getCompiler(); - - /** - * returns some php code that will check if this template has been modified or not - * - * if the function returns null, the template will be instanciated and then the Uid checked - * - * @return string - */ - public function getIsModifiedCode(); - - /** - * returns a new template object from the given resource identifier, null if no include is - * possible (resource not found), or false if include is not permitted by this resource type - * - * this method should also check if $dwoo->getSecurityPolicy() is null or not and do the - * necessary permission checks if required, if the security policy prevents the template - * generation it should throw a new Dwoo_Security_Exception with a relevant message - * - * @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 - * @param Dwoo_ITemplate $parentTemplate the template that is requesting a new template object (through - * an include, extends or any other plugin) - * @return Dwoo_ITemplate|null|false - */ - public static function templateFactory(Dwoo $dwoo, $resourceId, $cacheTime = null, $cacheId = null, $compileId = null, Dwoo_ITemplate $parentTemplate = null); -} diff --git a/system/libs/dwoo/Dwoo/Loader.php b/system/libs/dwoo/Dwoo/Loader.php deleted file mode 100644 index 437a1285..00000000 --- a/system/libs/dwoo/Dwoo/Loader.php +++ /dev/null @@ -1,147 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - */ -class Dwoo_Loader implements Dwoo_ILoader -{ - /** - * stores the plugin directories - * - * @see addDirectory - * @var array - */ - protected $paths = array(); - - /** - * stores the plugins names/paths relationships - * don't edit this on your own, use addDirectory - * - * @see addDirectory - * @var array - */ - protected $classPath = array(); - - /** - * path where class paths cache files are written - * - * @var string - */ - protected $cacheDir; - - protected $corePluginDir; - - public function __construct($cacheDir) - { - $this->corePluginDir = DWOO_DIRECTORY . 'plugins'; - $this->cacheDir = rtrim($cacheDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; - - // include class paths or rebuild paths if the cache file isn't there - $cacheFile = $this->cacheDir.'classpath.cache.d'.Dwoo::RELEASE_TAG.'.php'; - if (file_exists($cacheFile)) { - $classpath = file_get_contents($cacheFile); - $this->classPath = unserialize($classpath) + $this->classPath; - } else { - $this->rebuildClassPathCache($this->corePluginDir, $cacheFile); - } - } - - /** - * rebuilds class paths, scans the given directory recursively and saves all paths in the given file - * - * @param string $path the plugin path to scan - * @param string $cacheFile the file where to store the plugin paths cache, it will be overwritten - */ - protected function rebuildClassPathCache($path, $cacheFile) - { - if ($cacheFile!==false) { - $tmp = $this->classPath; - $this->classPath = array(); - } - - // iterates over all files/folders - $list = glob(rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . '*'); - if (is_array($list)) { - foreach ($list as $f) { - if (is_dir($f)) { - $this->rebuildClassPathCache($f, false); - } else { - $this->classPath[str_replace(array('function.','block.','modifier.','outputfilter.','filter.','prefilter.','postfilter.','pre.','post.','output.','shared.','helper.'), '', basename($f, '.php'))] = $f; - } - } - } - - // save in file if it's the first call (not recursed) - if ($cacheFile!==false) { - if (!file_put_contents($cacheFile, serialize($this->classPath))) { - throw new Dwoo_Exception('Could not write into '.$cacheFile.', either because the folder is not there (create it) or because of the chmod configuration (please ensure this directory is writable by php), alternatively you can change the directory used with $dwoo->setCompileDir() or provide a custom loader object with $dwoo->setLoader()'); - } - $this->classPath += $tmp; - } - } - - /** - * loads a plugin file - * - * @param string $class the plugin name, without the Dwoo_Plugin_ prefix - * @param bool $forceRehash if true, the class path caches will be rebuilt if the plugin is not found, in case it has just been added, defaults to true - */ - public function loadPlugin($class, $forceRehash = true) - { - // a new class was added or the include failed so we rebuild the cache - if (!isset($this->classPath[$class]) || !(include $this->classPath[$class])) { - if ($forceRehash) { - $this->rebuildClassPathCache($this->corePluginDir, $this->cacheDir . 'classpath.cache.d'.Dwoo::RELEASE_TAG.'.php'); - foreach ($this->paths as $path=>$file) { - $this->rebuildClassPathCache($path, $file); - } - if (isset($this->classPath[$class])) { - include $this->classPath[$class]; - } else { - throw new Dwoo_Exception('Plugin '.$class.' can not be found, maybe you forgot to bind it if it\'s a custom plugin ?', E_USER_NOTICE); - } - } else { - throw new Dwoo_Exception('Plugin '.$class.' can not be found, maybe you forgot to bind it if it\'s a custom plugin ?', E_USER_NOTICE); - } - } - } - - /** - * adds a plugin directory, the plugins found in the new plugin directory - * will take precedence over the other directories (including the default - * dwoo plugin directory), you can use this for example to override plugins - * in a specific directory for a specific application while keeping all your - * usual plugins in the same place for all applications. - * - * TOCOM don't forget that php functions overrides are not rehashed so you - * need to clear the classpath caches by hand when adding those - * - * @param string $pluginDirectory the plugin path to scan - */ - public function addDirectory($pluginDirectory) - { - $pluginDir = realpath($pluginDirectory); - if (!$pluginDir) { - throw new Dwoo_Exception('Plugin directory does not exist or can not be read : '.$pluginDirectory); - } - $cacheFile = $this->cacheDir . 'classpath-'.substr(strtr($pluginDir, '/\\:'.PATH_SEPARATOR, '----'), strlen($pluginDir) > 80 ? -80 : 0).'.d'.Dwoo::RELEASE_TAG.'.php'; - $this->paths[$pluginDir] = $cacheFile; - if (file_exists($cacheFile)) { - $classpath = file_get_contents($cacheFile); - $this->classPath = unserialize($classpath) + $this->classPath; - } else { - $this->rebuildClassPathCache($pluginDir, $cacheFile); - } - } -} diff --git a/system/libs/dwoo/Dwoo/Plugin.php b/system/libs/dwoo/Dwoo/Plugin.php deleted file mode 100644 index 053448c9..00000000 --- a/system/libs/dwoo/Dwoo/Plugin.php +++ /dev/null @@ -1,85 +0,0 @@ -process() method, it will receive the parameters that - * are in the template code - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -abstract class Dwoo_Plugin -{ - /** - * the dwoo instance that runs this plugin - * - * @var Dwoo - */ - protected $dwoo; - - /** - * constructor, if you override it, call parent::__construct($dwoo); or assign - * the dwoo instance yourself if you need it - * - * @param Dwoo $dwoo the dwoo instance that runs this plugin - */ - public function __construct(Dwoo $dwoo) - { - $this->dwoo = $dwoo; - } - - // plugins should always implement : - // public function process($arg, $arg, ...) - // or for block plugins : - // public function init($arg, $arg, ...) - - // this could be enforced with : - // abstract public function process(...); - // if my feature request gets enough interest one day - // see => http://bugs.php.net/bug.php?id=44043 - - /** - * utility function that converts an array of compiled parameters (or rest array) to a string of xml/html tag attributes - * - * this is to be used in preProcessing or postProcessing functions, example : - * $p = $compiler->getCompiledParams($params); - * // get only the rest array as attributes - * $attributes = Dwoo_Plugin::paramsToAttributes($p['*']); - * // get all the parameters as attributes (if there is a rest array, it will be included) - * $attributes = Dwoo_Plugin::paramsToAttributes($p); - * - * @param array $params an array of attributeName=>value items that will be compiled to be ready for inclusion in a php string - * @param string $delim the string delimiter you want to use (defaults to ') - * @return string - */ - public static function paramsToAttributes(array $params, $delim = '\'') - { - if (isset($params['*'])) { - $params = array_merge($params, $params['*']); - unset($params['*']); - } - - $out = ''; - foreach ($params as $attr=>$val) { - $out .= ' '.$attr.'='; - if (trim($val, '"\'')=='' || $val=='null') { - $out .= str_replace($delim, '\\'.$delim, '""'); - } elseif (substr($val, 0, 1) === $delim && substr($val, -1) === $delim) { - $out .= str_replace($delim, '\\'.$delim, '"'.substr($val, 1, -1).'"'); - } else { - $out .= str_replace($delim, '\\'.$delim, '"') . $delim . '.'.$val.'.' . $delim . str_replace($delim, '\\'.$delim, '"'); - } - } - - return ltrim($out); - } -} diff --git a/system/libs/dwoo/Dwoo/Processor.php b/system/libs/dwoo/Dwoo/Processor.php deleted file mode 100644 index e3287f17..00000000 --- a/system/libs/dwoo/Dwoo/Processor.php +++ /dev/null @@ -1,44 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -abstract class Dwoo_Processor -{ - /** - * the compiler instance that runs this processor - * - * @var Dwoo - */ - protected $compiler; - - /** - * constructor, if you override it, call parent::__construct($dwoo); or assign - * the dwoo instance yourself if you need it - * - * @param Dwoo $dwoo the dwoo instance that runs this plugin - */ - public function __construct(Dwoo_Compiler $compiler) - { - $this->compiler = $compiler; - } - - /** - * processes the input and returns it filtered - * - * @param string $input the template to process - * @return string - */ - abstract public function process($input); -} diff --git a/system/libs/dwoo/Dwoo/Security/Exception.php b/system/libs/dwoo/Dwoo/Security/Exception.php deleted file mode 100644 index fbae9447..00000000 --- a/system/libs/dwoo/Dwoo/Security/Exception.php +++ /dev/null @@ -1,19 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Security_Exception extends Dwoo_Exception -{ -} diff --git a/system/libs/dwoo/Dwoo/Security/Policy.php b/system/libs/dwoo/Dwoo/Security/Policy.php deleted file mode 100644 index 8875f6d0..00000000 --- a/system/libs/dwoo/Dwoo/Security/Policy.php +++ /dev/null @@ -1,199 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Security_Policy -{ - /**#@+ - * php handling constants, defaults to PHP_REMOVE - * - * PHP_REMOVE : remove all (+ short tags if your short tags option is on) from the input template - * PHP_ALLOW : leave them as they are - * PHP_ENCODE : run htmlentities over them - * - * @var int - */ - const PHP_ENCODE = 1; - const PHP_REMOVE = 2; - const PHP_ALLOW = 3; - /**#@-*/ - - /**#@+ - * constant handling constants, defaults to CONST_DISALLOW - * - * CONST_DISALLOW : throw an error if {$dwoo.const.*} is used in the template - * CONST_ALLOW : allow {$dwoo.const.*} calls - */ - const CONST_DISALLOW = false; - const CONST_ALLOW = true; - /**#@-*/ - - /** - * php functions that are allowed to be used within the template - * - * @var array - */ - protected $allowedPhpFunctions = array - ( - 'str_repeat', 'number_format', 'htmlentities', 'htmlspecialchars', - 'long2ip', 'strlen', 'list', 'empty', 'count', 'sizeof', 'in_array', 'is_array', - ); - - /** - * paths that are safe to use with include or other file-access plugins - * - * @var array - */ - protected $allowedDirectories = array(); - - /** - * stores the php handling level - * - * defaults to Dwoo_Security_Policy::PHP_REMOVE - * - * @var int - */ - protected $phpHandling = self::PHP_REMOVE; - - /** - * stores the constant handling level - * - * defaults to Dwoo_Security_Policy::CONST_DISALLOW - * - * @var bool - */ - protected $constHandling = self::CONST_DISALLOW; - - /** - * adds a php function to the allowed list - * - * @param mixed $func function name or array of function names - */ - public function allowPhpFunction($func) - { - if (is_array($func)) - foreach ($func as $fname) - $this->allowedPhpFunctions[strtolower($fname)] = true; - else - $this->allowedPhpFunctions[strtolower($func)] = true; - } - - /** - * removes a php function from the allowed list - * - * @param mixed $func function name or array of function names - */ - public function disallowPhpFunction($func) - { - if (is_array($func)) - foreach ($func as $fname) - unset($this->allowedPhpFunctions[strtolower($fname)]); - else - unset($this->allowedPhpFunctions[strtolower($func)]); - } - - /** - * returns the list of php functions allowed to run, note that the function names - * are stored in the array keys and not values - * - * @return array - */ - public function getAllowedPhpFunctions() - { - return $this->allowedPhpFunctions; - } - - /** - * adds a directory to the safelist for includes and other file-access plugins - * - * note that all the includePath directories you provide to the Dwoo_Template_File class - * are automatically marked as safe - * - * @param mixed $path a path name or an array of paths - */ - public function allowDirectory($path) - { - if (is_array($path)) - foreach ($path as $dir) - $this->allowedDirectories[realpath($dir)] = true; - else - $this->allowedDirectories[realpath($path)] = true; - } - - /** - * removes a directory from the safelist - * - * @param mixed $path a path name or an array of paths - */ - public function disallowDirectory($path) - { - if (is_array($path)) - foreach ($path as $dir) - unset($this->allowedDirectories[realpath($dir)]); - else - unset($this->allowedDirectories[realpath($path)]); - } - - /** - * returns the list of safe paths, note that the paths are stored in the array - * keys and not values - * - * @return array - */ - public function getAllowedDirectories() - { - return $this->allowedDirectories; - } - - /** - * sets the php handling level, defaults to REMOVE - * - * @param int $level one of the Dwoo_Security_Policy::PHP_* constants - */ - public function setPhpHandling($level = self::PHP_REMOVE) - { - $this->phpHandling = $level; - } - - /** - * returns the php handling level - * - * @return int the current level, one of the Dwoo_Security_Policy::PHP_* constants - */ - public function getPhpHandling() - { - return $this->phpHandling; - } - - /** - * sets the constant handling level, defaults to CONST_DISALLOW - * - * @param bool $level one of the Dwoo_Security_Policy::CONST_* constants - */ - public function setConstantHandling($level = self::CONST_DISALLOW) - { - $this->constHandling = $level; - } - - /** - * returns the constant handling level - * - * @return bool the current level, one of the Dwoo_Security_Policy::CONST_* constants - */ - public function getConstantHandling() - { - return $this->constHandling; - } -} diff --git a/system/libs/dwoo/Dwoo/Smarty/Adapter.php b/system/libs/dwoo/Dwoo/Smarty/Adapter.php deleted file mode 100644 index b4a620cd..00000000 --- a/system/libs/dwoo/Dwoo/Smarty/Adapter.php +++ /dev/null @@ -1,518 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - */ -class Dwoo_Smarty__Adapter extends Dwoo -{ - // magic get/set/call functions that handle unsupported features - public function __set($p, $v) - { - if ($p==='scope') { - $this->scope = $v; - return; - } - if ($p==='data') { - $this->data = $v; - return; - } - if (array_key_exists($p, $this->compat['properties']) !== false) { - if ($this->show_compat_errors) { - $this->triggerError('Property '.$p.' is not available in the Dwoo_Smarty_Adapter, however it might be implemented in the future, check out http://wiki.dwoo.org/index.php/SmartySupport for more details.', E_USER_NOTICE); - } - $this->compat['properties'][$p] = $v; - } else { - if ($this->show_compat_errors) { - $this->triggerError('Property '.$p.' is not available in the Dwoo_Smarty_Adapter, but it is not listed as such, so you might want to tell me about it at j.boggiano@seld.be', E_USER_NOTICE); - } - } - } - - public function __get($p) - { - if (array_key_exists($p, $this->compat['properties']) !== false) { - if ($this->show_compat_errors) { - $this->triggerError('Property '.$p.' is not available in the Dwoo_Smarty_Adapter, however it might be implemented in the future, check out http://wiki.dwoo.org/index.php/SmartySupport for more details.', E_USER_NOTICE); - } - return $this->compat['properties'][$p]; - } else { - if ($this->show_compat_errors) { - $this->triggerError('Property '.$p.' is not available in the Dwoo_Smarty_Adapter, but it is not listed as such, so you might want to tell me about it at j.boggiano@seld.be', E_USER_NOTICE); - } - } - } - - public function __call($m, $a) - { - if (method_exists($this->dataProvider, $m)) { - call_user_func_array(array($this->dataProvider, $m), $a); - } elseif ($this->show_compat_errors) { - if (array_search($m, $this->compat['methods']) !== false) { - $this->triggerError('Method '.$m.' is not available in the Dwoo_Smarty_Adapter, however it might be implemented in the future, check out http://wiki.dwoo.org/index.php/SmartySupport for more details.', E_USER_NOTICE); - } else { - $this->triggerError('Method '.$m.' is not available in the Dwoo_Smarty_Adapter, but it is not listed as such, so you might want to tell me about it at j.boggiano@seld.be', E_USER_NOTICE); - } - } - } - - // list of unsupported properties and methods - protected $compat = array - ( - 'methods' => array - ( - 'register_resource', 'unregister_resource', 'load_filter', 'clear_compiled_tpl', - 'clear_config', 'get_config_vars', 'config_load' - ), - 'properties' => array - ( - 'cache_handler_func' => null, - 'debugging' => false, - 'error_reporting' => null, - 'debugging_ctrl' => 'NONE', - 'request_vars_order' => 'EGPCS', - 'request_use_auto_globals' => true, - 'use_sub_dirs' => false, - 'autoload_filters' => array(), - 'default_template_handler_func' => '', - 'debug_tpl' => '', - 'cache_modified_check' => false, - 'default_modifiers' => array(), - 'default_resource_type' => 'file', - 'config_overwrite' => true, - 'config_booleanize' => true, - 'config_read_hidden' => false, - 'config_fix_newlines' => true, - 'config_class' => 'Config_File', - ), - ); - - // security vars - public $security = false; - public $trusted_dir = array(); - public $secure_dir = array(); - public $php_handling = SMARTY_PHP_PASSTHRU; - public $security_settings = array - ( - 'PHP_HANDLING' => false, - 'IF_FUNCS' => array - ( - 'list', 'empty', 'count', 'sizeof', - 'in_array', 'is_array', - ), - 'INCLUDE_ANY' => false, - 'PHP_TAGS' => false, - 'MODIFIER_FUNCS' => array(), - 'ALLOW_CONSTANTS' => false - ); - - // paths - public $template_dir = 'templates'; - public $compile_dir = 'templates_c'; - public $config_dir = 'configs'; - public $cache_dir = 'cache'; - public $plugins_dir = array(); - - // misc options - public $left_delimiter = '{'; - public $right_delimiter = '}'; - public $compile_check = true; - public $force_compile = false; - public $caching = 0; - public $cache_lifetime = 3600; - public $compile_id = null; - public $compiler_file = null; - public $compiler_class = null; - - // dwoo/smarty compat layer - public $show_compat_errors = false; - protected $dataProvider; - protected $_filters = array('pre'=>array(), 'post'=>array(), 'output'=>array()); - protected static $tplCache = array(); - protected $compiler = null; - - public function __construct() - { - parent::__construct(); - $this->charset = 'iso-8859-1'; - $this->dataProvider = new Dwoo_Data(); - $this->compiler = new Dwoo_Compiler(); - } - - public function display($filename, $cacheId=null, $compileId=null) - { - $this->fetch($filename, $cacheId, $compileId, true); - } - - public function fetch($filename, $cacheId=null, $compileId=null, $display=false) - { - $this->setCacheDir($this->cache_dir); - $this->setCompileDir($this->compile_dir); - - if ($this->security) { - $policy = new Dwoo_Security_Policy(); - $policy->addPhpFunction(array_merge($this->security_settings['IF_FUNCS'], $this->security_settings['MODIFIER_FUNCS'])); - - $phpTags = $this->security_settings['PHP_HANDLING'] ? SMARTY_PHP_ALLOW : $this->php_handling; - if ($this->security_settings['PHP_TAGS']) { - $phpTags = SMARTY_PHP_ALLOW; - } - switch($phpTags) { - case SMARTY_PHP_ALLOW: - case SMARTY_PHP_PASSTHRU: - $phpTags = Dwoo_Security_Policy::PHP_ALLOW; - break; - case SMARTY_PHP_QUOTE: - $phpTags = Dwoo_Security_Policy::PHP_ENCODE; - break; - case SMARTY_PHP_REMOVE: - default: - $phpTags = Dwoo_Security_Policy::PHP_REMOVE; - break; - } - $policy->setPhpHandling($phpTags); - - $policy->setConstantHandling($this->security_settings['ALLOW_CONSTANTS']); - - if ($this->security_settings['INCLUDE_ANY']) { - $policy->allowDirectory(preg_replace('{^((?:[a-z]:)?[\\\\/]).*}i', '$1', __FILE__)); - } else { - $policy->allowDirectory($this->secure_dir); - } - - $this->setSecurityPolicy($policy); - } - - if (!empty($this->plugins_dir)) { - foreach ($this->plugins_dir as $dir) { - $this->getLoader()->addDirectory(rtrim($dir, '\\/')); - } - } - - $tpl = $this->makeTemplate($filename, $cacheId, $compileId); - if ($this->force_compile) { - $tpl->forceCompilation(); - } - - if ($this->caching > 0) { - $this->cacheTime = $this->cache_lifetime; - } else { - $this->cacheTime = 0; - } - - if ($this->compiler_class !== null) { - if ($this->compiler_file !== null && !class_exists($this->compiler_class, false)) { - include $this->compiler_file; - } - $this->compiler = new $this->compiler_class; - } else { - $this->compiler->addPreProcessor('smarty_compat', true); - $this->compiler->setLooseOpeningHandling(true); - } - - $this->compiler->setDelimiters($this->left_delimiter, $this->right_delimiter); - - return $this->get($tpl, $this->dataProvider, $this->compiler, $display===true); - } - - public function get($_tpl, $data = array(), $_compiler = null, $_output = false) - { - if ($_compiler === null) { - $_compiler = $this->compiler; - } - return parent::get($_tpl, $data, $_compiler, $_output); - } - - public function register_function($name, $callback, $cacheable=true, $cache_attrs=null) - { - if (isset($this->plugins[$name]) && $this->plugins[$name][0] !== self::SMARTY_FUNCTION) { - throw new Dwoo_Exception('Multiple plugins of different types can not share the same name'); - } - $this->plugins[$name] = array('type'=>self::SMARTY_FUNCTION, 'callback'=>$callback); - } - - public function unregister_function($name) - { - unset($this->plugins[$name]); - } - - public function register_block($name, $callback, $cacheable=true, $cache_attrs=null) - { - if (isset($this->plugins[$name]) && $this->plugins[$name][0] !== self::SMARTY_BLOCK) { - throw new Dwoo_Exception('Multiple plugins of different types can not share the same name'); - } - $this->plugins[$name] = array('type'=>self::SMARTY_BLOCK, 'callback'=>$callback); - } - - public function unregister_block($name) - { - unset($this->plugins[$name]); - } - - public function register_modifier($name, $callback) - { - if (isset($this->plugins[$name]) && $this->plugins[$name][0] !== self::SMARTY_MODIFIER) { - throw new Dwoo_Exception('Multiple plugins of different types can not share the same name'); - } - $this->plugins[$name] = array('type'=>self::SMARTY_MODIFIER, 'callback'=>$callback); - } - - public function unregister_modifier($name) - { - unset($this->plugins[$name]); - } - - public function register_prefilter($callback) - { - $processor = new Dwoo_SmartyProcessorAdapter($this->compiler); - $processor->registerCallback($callback); - $this->_filters['pre'][] = $processor; - $this->compiler->addPreProcessor($processor); - } - - public function unregister_prefilter($callback) - { - foreach ($this->_filters['pre'] as $index => $processor) - if ($processor->callback === $callback) { - $this->compiler->removePostProcessor($processor); - unset($this->_filters['pre'][$index]); - } - } - - public function register_postfilter($callback) - { - $processor = new Dwoo_SmartyProcessorAdapter($this->compiler); - $processor->registerCallback($callback); - $this->_filters['post'][] = $processor; - $this->compiler->addPostProcessor($processor); - } - - public function unregister_postfilter($callback) - { - foreach ($this->_filters['post'] as $index => $processor) - if ($processor->callback === $callback) { - $this->compiler->removePostProcessor($processor); - unset($this->_filters['post'][$index]); - } - } - - public function register_outputfilter($callback) - { - $filter = new Dwoo_SmartyFilterAdapter($this); - $filter->registerCallback($callback); - $this->_filters['output'][] = $filter; - $this->addFilter($filter); - } - - public function unregister_outputfilter($callback) - { - foreach ($this->_filters['output'] as $index => $filter) - if ($filter->callback === $callback) { - $this->removeOutputFilter($filter); - unset($this->_filters['output'][$index]); - } - } - - function register_object($object, $object_impl, $allowed = array(), $smarty_args = false, $block_methods = array()) - { - settype($allowed, 'array'); - settype($block_methods, 'array'); - settype($smarty_args, 'boolean'); - - if (!empty($allowed) && $this->show_compat_errors) { - $this->triggerError('You can register objects but can not restrict the method/properties used, this is PHP5, you have proper OOP access restrictions so use them.', E_USER_NOTICE); - } - - if ($smarty_args) { - $this->triggerError('You can register objects but methods will be called using method($arg1, $arg2, $arg3), not as an argument array like smarty did.', E_USER_NOTICE); - } - - if (!empty($block_methods)) { - $this->triggerError('You can register objects but can not use methods as being block methods, you have to build a plugin for that.', E_USER_NOTICE); - } - - $this->dataProvider->assign($object, $object_impl); - } - - function unregister_object($object) - { - $this->dataProvider->clear($object); - } - - function get_registered_object($name) { - $data = $this->dataProvider->getData(); - if (isset($data[$name]) && is_object($data[$name])) { - return $data[$name]; - } else { - trigger_error('Dwoo_Compiler: object "'.$name.'" was not registered or is not an object', E_USER_ERROR); - } - } - - public function template_exists($filename) - { - if (!is_array($this->template_dir)) { - return file_exists($this->template_dir.DIRECTORY_SEPARATOR.$filename); - } else { - foreach ($this->template_dir as $tpl_dir) { - if (file_exists($tpl_dir.DIRECTORY_SEPARATOR.$filename)) { - return true; - } - } - return false; - } - } - - public function is_cached($tpl, $cacheId = null, $compileId = null) - { - return $this->isCached($this->makeTemplate($tpl, $cacheId, $compileId)); - } - - public function append_by_ref($var, &$value, $merge=false) - { - $this->dataProvider->appendByRef($var, $value, $merge); - } - - public function assign_by_ref($name, &$val) - { - $this->dataProvider->assignByRef($name, $val); - } - - public function clear_assign($var) - { - $this->dataProvider->clear($var); - } - - public function clear_all_assign() - { - $this->dataProvider->clear(); - } - - public function get_template_vars($name=null) - { - if ($this->show_compat_errors) { - trigger_error('get_template_vars does not return values by reference, if you try to modify the data that way you should modify your code.', E_USER_NOTICE); - } - - $data = $this->dataProvider->getData(); - if ($name === null) - return $data; - elseif (isset($data[$name])) - return $data[$name]; - return null; - } - - public function clear_all_cache($olderThan = 0) - { - $this->clearCache($olderThan); - } - - public function clear_cache($template, $cacheId = null, $compileId = null, $olderThan = 0) - { - $this->makeTemplate($template, $cacheId, $compileId)->clearCache($olderThan); - } - - public function trigger_error($error_msg, $error_type = E_USER_WARNING) - { - $this->triggerError($error_msg, $error_type); - } - - protected function initGlobals() - { - parent::initGlobals(); - $this->globals['ldelim'] = '{'; - $this->globals['rdelim'] = '}'; - } - - protected function makeTemplate($file, $cacheId, $compileId) - { - if ($compileId === null) - $compileId = $this->compile_id; - - $hash = bin2hex(md5($file.$cacheId.$compileId, true)); - if (!isset(self::$tplCache[$hash])) { - // abs path - if (substr($file, 0, 1) === '/' || substr($file, 1, 1) === ':') { - self::$tplCache[$hash] = new Dwoo_Template_File($file, null, $cacheId, $compileId); - } elseif (is_string($this->template_dir) || is_array($this->template_dir)) { - self::$tplCache[$hash] = new Dwoo_Template_File($file, null, $cacheId, $compileId, $this->template_dir); - } else { - throw new Exception('Unable to load "'.$file.'", check the template_dir'); - } - } - return self::$tplCache[$hash]; - } - - public function triggerError($message, $level=E_USER_NOTICE) - { - if (is_object($this->template)) { - return parent::triggerError($message, $level); - } - trigger_error('Dwoo error : '.$message, $level); - } -} - -class Dwoo_Smarty_Filter_Adapter extends Dwoo_Filter -{ - public $callback; - - public function process($input) - { - return call_user_func($this->callback, $input); - } - - public function registerCallback($callback) - { - $this->callback = $callback; - } -} - -class Dwoo_Smarty_Processor_Adapter extends Dwoo_Processor -{ - public $callback; - - public function process($input) - { - return call_user_func($this->callback, $input); - } - - public function registerCallback($callback) - { - $this->callback = $callback; - } -} - -// cloaks the adapter if possible with the smarty name to fool type-hinted plugins -if (class_exists('Smarty', false) === false) -{ - interface Smarty {} - class Dwoo_Smarty_Adapter extends Dwoo_Smarty__Adapter implements Smarty {} -} -else -{ - class Dwoo_Smarty_Adapter extends Dwoo_Smarty__Adapter {} -} diff --git a/system/libs/dwoo/Dwoo/Template/File.php b/system/libs/dwoo/Dwoo/Template/File.php deleted file mode 100644 index 4dda0f33..00000000 --- a/system/libs/dwoo/Dwoo/Template/File.php +++ /dev/null @@ -1,270 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - */ -class Dwoo_Template_File extends Dwoo_Template_String -{ - /** - * template filename - * - * @var string - */ - protected $file; - - /** - * include path(s) to look into to find this template - * - * @var array - */ - protected $includePath = null; - - /** - * resolved path cache when looking for a file in multiple include paths - * - * this is reset when the include path is changed - * - * @var string - */ - protected $resolvedPath = null; - - /** - * 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 - * @param mixed $includePath a string for a single path to look into for the given file, or an array of paths - */ - public function __construct($file, $cacheTime = null, $cacheId = null, $compileId = null, $includePath = null) - { - $this->file = $file; - $this->name = basename($file); - $this->cacheTime = $cacheTime; - - if ($compileId !== null) { - $this->compileId = str_replace('../', '__', strtr($compileId, '\\%?=!:;'.PATH_SEPARATOR, '/-------')); - } - - if ($cacheId !== null) { - $this->cacheId = str_replace('../', '__', strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------')); - } - - if (is_string($includePath)) { - $this->includePath = array($includePath); - } elseif (is_array($includePath)) { - $this->includePath = $includePath; - } - } - - /** - * sets the include path(s) to where the given template filename must be looked up - * - * @param mixed $paths the path to look into, can be string for a single path or an array of paths - */ - public function setIncludePath($paths) - { - if (is_array($paths) === false) { - $paths = array($paths); - } - - $this->includePath = $paths; - $this->resolvedPath = null; - } - - /** - * return the current include path(s) - * - * @return array - */ - public function getIncludePath() - { - return $this->includePath; - } - - /** - * Checks if compiled file is valid (exists and it's the modification is greater or - * equal to the modification time of the template file) - * - * @param string file - * @return boolean True cache file existance and it's modification time - */ - protected function isValidCompiledFile($file) { - return parent::isValidCompiledFile($file) && (int)$this->getUid() <= filemtime($file); - } - - /** - * returns the template source of this template - * - * @return string - */ - public function getSource() - { - return file_get_contents($this->getResourceIdentifier()); - } - - /** - * 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 getResourceIdentifier() - { - if ($this->resolvedPath !== null) { - return $this->resolvedPath; - } elseif ($this->includePath === null) { - return $this->file; - } else { - foreach ($this->includePath as $path) { - $path = rtrim($path, DIRECTORY_SEPARATOR); - if (file_exists($path.DIRECTORY_SEPARATOR.$this->file) === true) { - $this->resolvedPath = $path . DIRECTORY_SEPARATOR . $this->file; - return $this->resolvedPath; - } - } - - throw new Dwoo_Exception('Template "'.$this->file.'" could not be found in any of your include path(s)'); - } - } - - /** - * returns an unique value identifying the current version of this template, - * in this case it's the unix timestamp of the last modification - * - * @return string - */ - public function getUid() - { - return (string) filemtime($this->getResourceIdentifier()); - } - - /** - * 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 - * @param Dwoo_ITemplate $parentTemplate the template that is requesting a new template object (through - * an include, extends or any other plugin) - * @return Dwoo_Template_File|null - */ - public static function templateFactory(Dwoo $dwoo, $resourceId, $cacheTime = null, $cacheId = null, $compileId = null, Dwoo_ITemplate $parentTemplate = null) - { - if (DIRECTORY_SEPARATOR === '\\') { - $resourceId = str_replace(array("\t", "\n", "\r", "\f", "\v"), array('\\t', '\\n', '\\r', '\\f', '\\v'), $resourceId); - } - $resourceId = strtr($resourceId, '\\', '/'); - - $includePath = null; - - if (file_exists($resourceId) === false) { - if ($parentTemplate === null) { - $parentTemplate = $dwoo->getTemplate(); - } - if ($parentTemplate instanceof Dwoo_Template_File) { - if ($includePath = $parentTemplate->getIncludePath()) { - if (strstr($resourceId, '../')) { - throw new Dwoo_Exception('When using an include path you can not reference a template into a parent directory (using ../)'); - } - } else { - $resourceId = dirname($parentTemplate->getResourceIdentifier()).DIRECTORY_SEPARATOR.$resourceId; - if (file_exists($resourceId) === false) { - return null; - } - } - } else { - return null; - } - } - - if ($policy = $dwoo->getSecurityPolicy()) { - while (true) { - if (preg_match('{^([a-z]+?)://}i', $resourceId)) { - throw new Dwoo_Security_Exception('The security policy prevents you to read files from external sources : '.$resourceId.'.'); - } - - if ($includePath) { - break; - } - - $resourceId = realpath($resourceId); - $dirs = $policy->getAllowedDirectories(); - foreach ($dirs as $dir=>$dummy) { - if (strpos($resourceId, $dir) === 0) { - break 2; - } - } - throw new Dwoo_Security_Exception('The security policy prevents you to read '.$resourceId.''); - } - } - - $class = 'Dwoo_Template_File'; - if ($parentTemplate) { - $class = get_class($parentTemplate); - } - return new $class($resourceId, $cacheTime, $cacheId, $compileId, $includePath); - } - - /** - * returns the full compiled file name and assigns a default value to it if - * required - * - * @param Dwoo $dwoo the dwoo instance that requests the file name - * @return string the full path to the compiled file - */ - protected function getCompiledFilename(Dwoo $dwoo) - { - // no compile id was provided, set default - if ($this->compileId===null) { - $this->compileId = str_replace('../', '__', strtr($this->getResourceIdentifier(), '\\:', '/-')); - } - return $dwoo->getCompileDir() . $this->compileId.'.d'.Dwoo::RELEASE_TAG.'.php'; - } - - /** - * returns some php code that will check if this template has been modified or not - * - * if the function returns null, the template will be instanciated and then the Uid checked - * - * @return string - */ - public function getIsModifiedCode() - { - return '"'.$this->getUid().'" == filemtime('.var_export($this->getResourceIdentifier(), true).')'; - } -} diff --git a/system/libs/dwoo/Dwoo/Template/String.php b/system/libs/dwoo/Dwoo/Template/String.php deleted file mode 100644 index 6fbcaa42..00000000 --- a/system/libs/dwoo/Dwoo/Template/String.php +++ /dev/null @@ -1,497 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - */ -class Dwoo_Template_String implements Dwoo_ITemplate -{ - /** - * 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 md4 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 Dwoo_ICompiler - */ - protected $compiler; - - /** - * chmod value for all files written (cached or compiled ones) - * - * set to null if you don't want any chmod operation to happen - * - * @var int - */ - protected $chmod = 0777; - - /** - * 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 md4 hash of the template - */ - public function __construct($templateString, $cacheTime = null, $cacheId = null, $compileId = null) - { - $this->template = $templateString; - if (function_exists('hash')) { - $this->name = hash('md4', $templateString); - } else { - $this->name = md5($templateString); - } - $this->cacheTime = $cacheTime; - - if ($compileId !== null) { - $this->compileId = str_replace('../', '__', strtr($compileId, '\\%?=!:;'.PATH_SEPARATOR, '/-------')); - } - - if ($cacheId !== null) { - $this->cacheId = str_replace('../', '__', strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------')); - } - } - - /** - * returns the cache duration for this template - * - * defaults to null if it was not provided - * - * @return int|null - */ - public function getCacheTime() - { - return $this->cacheTime; - } - - /** - * sets the cache duration for this template - * - * can be used to set it after the object is created if you did not provide - * it in the constructor - * - * @param int $seconds duration of the cache validity for this template, if - * null it defaults to the Dwoo instance's cache time. 0 = disable and - * -1 = infinite cache - */ - public function setCacheTime($seconds = null) - { - $this->cacheTime = $seconds; - } - - /** - * returns the chmod value for all files written (cached or compiled ones) - * - * defaults to 0777 - * - * @return int|null - */ - public function getChmod() - { - return $this->chmod; - } - - /** - * set the chmod value for all files written (cached or compiled ones) - * - * set to null if you don't want to do any chmod() operation - * - * @param int $mask new bitmask to use for all files - */ - public function setChmod($mask = null) - { - $this->chmod = $mask; - } - - /** - * 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 resource identifier for this template, false here as strings don't have identifiers - * - * @return false - */ - public function getResourceIdentifier() - { - return false; - } - - /** - * returns the template source of this template - * - * @return string - */ - public function getSource() - { - return $this->template; - } - - /** - * returns an unique value identifying the current version of this template, - * in this case it's the md4 hash of the content - * - * @return string - */ - public function getUid() - { - return $this->name; - } - - /** - * returns the compiler used by this template, if it was just compiled, or null - * - * @return Dwoo_ICompiler - */ - 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) - { - if ($this->cacheTime !== null) { - $cacheLength = $this->cacheTime; - } else { - $cacheLength = $dwoo->getCacheTime(); - } - - // file is not cacheable - if ($cacheLength === 0) { - return false; - } - - $cachedFile = $this->getCacheFilename($dwoo); - - if (isset(self::$cache['cached'][$this->cacheId]) === true && file_exists($cachedFile)) { - // already checked, return cache file - return $cachedFile; - } elseif ($this->compilationEnforced !== true && file_exists($cachedFile) && ($cacheLength === -1 || filemtime($cachedFile) > ($_SERVER['REQUEST_TIME'] - $cacheLength)) && $this->isValidCompiledFile($this->getCompiledFilename($dwoo))) { - // cache is still valid and can be loaded - self::$cache['cached'][$this->cacheId] = true; - return $cachedFile; - } else { - // file is cacheable - 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 - * @return mixed full path of the cached file or false upon failure - */ - public function cache(Dwoo $dwoo, $output) - { - $cacheDir = $dwoo->getCacheDir(); - $cachedFile = $this->getCacheFilename($dwoo); - - // the code below is courtesy of Rasmus Schultz, - // thanks for his help on avoiding concurency issues - $temp = tempnam($cacheDir, 'temp'); - if (!($file = @fopen($temp, 'wb'))) { - $temp = $cacheDir . uniqid('temp'); - if (!($file = @fopen($temp, 'wb'))) { - trigger_error('Error writing temporary file \''.$temp.'\'', E_USER_WARNING); - return false; - } - } - - fwrite($file, $output); - fclose($file); - - $this->makeDirectory(dirname($cachedFile), $cacheDir); - if (!@rename($temp, $cachedFile)) { - @unlink($cachedFile); - @rename($temp, $cachedFile); - } - - if ($this->chmod !== null) { - chmod($cachedFile, $this->chmod); - } - - self::$cache['cached'][$this->cacheId] = true; - - return $cachedFile; - } - - /** - * clears the cached template if it's older than the given time - * - * @param Dwoo $dwoo the dwoo instance that was used to cache that template - * @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(Dwoo $dwoo, $olderThan = -1) - { - $cachedFile = $this->getCacheFilename($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 Dwoo_ICompiler $compiler the compiler that must be used - * @return string - */ - public function getCompiledTemplate(Dwoo $dwoo, Dwoo_ICompiler $compiler = null) - { - $compiledFile = $this->getCompiledFilename($dwoo); - - if ($this->compilationEnforced !== true && isset(self::$cache['compiled'][$this->compileId]) === true) { - // already checked, return compiled file - } elseif ($this->compilationEnforced !== true && $this->isValidCompiledFile($compiledFile)) { - // template is compiled - self::$cache['compiled'][$this->compileId] = true; - } else { - // compiles the template - $this->compilationEnforced = false; - - if ($compiler === null) { - $compiler = $dwoo->getDefaultCompilerFactory($this->getResourceName()); - - if ($compiler === null || $compiler === array('Dwoo_Compiler', 'compilerFactory')) { - if (class_exists('Dwoo_Compiler', false) === false) { - include DWOO_DIRECTORY . 'Dwoo/Compiler.php'; - } - $compiler = Dwoo_Compiler::compilerFactory(); - } else { - $compiler = call_user_func($compiler); - } - } - - $this->compiler = $compiler; - - $compiler->setCustomPlugins($dwoo->getCustomPlugins()); - $compiler->setSecurityPolicy($dwoo->getSecurityPolicy()); - $this->makeDirectory(dirname($compiledFile), $dwoo->getCompileDir()); - file_put_contents($compiledFile, $compiler->compile($dwoo, $this)); - if ($this->chmod !== null) { - chmod($compiledFile, $this->chmod); - } - - self::$cache['compiled'][$this->compileId] = true; - } - - return $compiledFile; - } - - /** - * Checks if compiled file is valid (it exists) - * - * @param string file - * @return boolean True cache file existance - */ - protected function isValidCompiledFile($file) { - return file_exists($file); - } - - /** - * returns a new template string object with the resource id being the template source code - * - * @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 - * @param Dwoo_ITemplate $parentTemplate the template that is requesting a new template object (through - * an include, extends or any other plugin) - * @return Dwoo_Template_String - */ - public static function templateFactory(Dwoo $dwoo, $resourceId, $cacheTime = null, $cacheId = null, $compileId = null, Dwoo_ITemplate $parentTemplate = null) - { - return new self($resourceId, $cacheTime, $cacheId, $compileId); - } - - /** - * returns the full compiled file name and assigns a default value to it if - * required - * - * @param Dwoo $dwoo the dwoo instance that requests the file name - * @return string the full path to the compiled file - */ - protected function getCompiledFilename(Dwoo $dwoo) - { - // no compile id was provided, set default - if ($this->compileId===null) { - $this->compileId = $this->name; - } - return $dwoo->getCompileDir() . $this->compileId.'.d'.Dwoo::RELEASE_TAG.'.php'; - } - - /** - * returns the full cached file name and assigns a default value to it if - * required - * - * @param Dwoo $dwoo the dwoo instance that requests the file name - * @return string the full path to the cached file - */ - protected function getCacheFilename(Dwoo $dwoo) - { - // no cache id provided, use request_uri as default - if ($this->cacheId === null) { - if (isset($_SERVER['REQUEST_URI']) === true) { - $cacheId = $_SERVER['REQUEST_URI']; - } elseif (isset($_SERVER['SCRIPT_FILENAME']) && isset($_SERVER['argv'])) { - $cacheId = $_SERVER['SCRIPT_FILENAME'].'-'.implode('-', $_SERVER['argv']); - } else { - $cacheId = ''; - } - // force compiled id generation - $this->getCompiledFilename($dwoo); - - $this->cacheId = str_replace('../', '__', $this->compileId . strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------')); - } - return $dwoo->getCacheDir() . $this->cacheId.'.html'; - } - - /** - * returns some php code that will check if this template has been modified or not - * - * if the function returns null, the template will be instanciated and then the Uid checked - * - * @return string - */ - public function getIsModifiedCode() - { - return null; - } - - /** - * ensures the given path exists - * - * @param string $path any path - * @param string $baseDir the base directory where the directory is created - * ($path must still contain the full path, $baseDir - * is only used for unix permissions) - */ - protected function makeDirectory($path, $baseDir = null) - { - if (is_dir($path) === true) { - return; - } - - if ($this->chmod === null) { - $chmod = 0777; - } else { - $chmod = $this->chmod; - } - mkdir($path, $chmod, true); - - // enforce the correct mode for all directories created - if (strpos(PHP_OS, 'WIN') !== 0 && $baseDir !== null) { - $path = strtr(str_replace($baseDir, '', $path), '\\', '/'); - $folders = explode('/', trim($path, '/')); - foreach ($folders as $folder) { - $baseDir .= $folder . DIRECTORY_SEPARATOR; - chmod($baseDir, $chmod); - } - } - } -} diff --git a/system/libs/dwoo/LICENSE b/system/libs/dwoo/LICENSE deleted file mode 100644 index 55dd4a4c..00000000 --- a/system/libs/dwoo/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2008, Dwoo / Jordi Boggiano -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of Dwoo nor the names of its contributors may be - used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY JORDI BOGGIANO ''AS IS'' AND ANY -EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL JORDI BOGGIANO BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/system/libs/dwoo/README b/system/libs/dwoo/README deleted file mode 100644 index 317179a1..00000000 --- a/system/libs/dwoo/README +++ /dev/null @@ -1,79 +0,0 @@ ------------------------------------------------------------------------------ --- WHAT IS DWOO? readme - version 1.0.0 ------------------------------------------------------------------------------ -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 Modified BSD license. -See the LICENSE file included in the archive or go to the URL below to obtain -a copy. - -http://dwoo.org/LICENSE - ------------------------------------------------------------------------------ --- QUICK START - RUNNING DWOO ------------------------------------------------------------------------------ -/***************************** Basic Example *******************************/ -// Include the main class (it should handle the rest on its own) -include 'path/to/dwooAutoload.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 Dwoo_Template_File('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 Dwoo_Data(); -// 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/dwooAutoload.php'; - -$dwoo = new Dwoo(); -$tpl = new Dwoo_Template_File('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 Dwoo_Data(); - $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 diff --git a/system/libs/dwoo/UPGRADE_NOTES b/system/libs/dwoo/UPGRADE_NOTES deleted file mode 100644 index 5f01896f..00000000 --- a/system/libs/dwoo/UPGRADE_NOTES +++ /dev/null @@ -1,65 +0,0 @@ ------------------------------------------------------------------------------ --- Upgrading to Dwoo v1.0.0beta ------------------------------------------------------------------------------ - -1. Dwoo classes loading ------------------------ - -While everything was previously included by Dwoo.php, this version introduces -an autoload function (dwooAutoload) that handles this automatically. This -means your choices are now : - -a) change your : include 'path/to/Dwoo.php'; - into : include 'path/to/dwooAutoload.php'; - this is the recommended setting, especially during development, so that if you - are seeing a Dwoo error and want to report a bug, you get proper line numbers - with the error and not just "error in Dwoo.compiled.php at line 2" - -b) use the compiled version of Dwoo, this is "experimental" and seems to provide better - performances mostly under windows, with a linux server it might imrpove performances - slightly if you have an opcode cache (APC, xcache, ..) : - include 'path/to/Dwoo.compiled.php'; - -c) load Dwoo classes yourself somehow, as part of your autoload function or - whatever suits you best - ------------------------------------------------------------------------------ --- Upgrading to Dwoo v0.9.2 ------------------------------------------------------------------------------ - -1. Block plugins ----------------- - -This version introduced a backward compatibility break with block plugins, this -was needed to allow compile-time access to the block's (parsed) content, be -very careful if you manipulate this content since it is php code and should remain -so if you don't want syntax errors (which are fatal) during template run. - -Error message : - - Strict Standards: Declaration of Dwoo_Plugin_*::postProcessing() should be compatible with that of Dwoo_Block_Plugin::postProcessing() - -Solution : - - * Change your block plugins postProcessing method declaration to the following : - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - - * Then add "$content" to the beginning of your return value, or modify it if required - -2. Strip modifier ------------------ - -The strip modifier had the same name as the strip block, this worked when the block -was hard coded within the compiler, but with the API change (see above) I was able -to move it to a plugin. Since both plugins don't have the same purpose, there was -a real problem and I had to rename it. The renaming will be handled by the smarty compatibility -layer, but if you used it without smarty compatibility, you should edit your templates. - -3. DWOO_COMPILE_DIRECTORY and DWOO_CACHE_DIRECTORY constants ------------------------------------------------------------- - -If you used those before, you will now get an exception when loading Dwoo. This is done -on purpose to help people to make the transition to the new method of doing it : - - $dwoo = new Dwoo('myCompileDir', 'myCacheDir'); \ No newline at end of file diff --git a/system/libs/dwoo/cache/.gitignore b/system/libs/dwoo/cache/.gitignore deleted file mode 100644 index e69de29b..00000000 diff --git a/system/libs/dwoo/compiled/.gitignore b/system/libs/dwoo/compiled/.gitignore deleted file mode 100644 index e69de29b..00000000 diff --git a/system/libs/dwoo/dwooAutoload.php b/system/libs/dwoo/dwooAutoload.php deleted file mode 100644 index 1352db19..00000000 --- a/system/libs/dwoo/dwooAutoload.php +++ /dev/null @@ -1,12 +0,0 @@ - - * * href : the target URI where the link must point - * * rest : any other attributes you want to add to the tag can be added as named parameters - * - * - * Example : - * - * - * {* Create a simple link out of an url variable and add a special class attribute: *} - * - * {a $url class="external" /} - * - * {* Mark a link as active depending on some other variable : *} - * - * {a $link.url class=tif($link.active "active"); $link.title /} - * - * {* This is similar to: {$link.title} *} - * - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Plugin_a extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block -{ - public function init($href, array $rest=array()) - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - $p = $compiler->getCompiledParams($params); - - $out = Dwoo_Compiler::PHP_OPEN . 'echo \'\';' . Dwoo_Compiler::PHP_CLOSE; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - $p = $compiler->getCompiledParams($params); - - // no content was provided so use the url as display text - if ($content == "") { - // merge into the href if href is a string - if (substr($p['href'], -1) === '"' || substr($p['href'], -1) === '\'') { - return Dwoo_Compiler::PHP_OPEN . 'echo '.substr($p['href'], 0, -1).''.substr($p['href'], -1).';'.Dwoo_Compiler::PHP_CLOSE; - } - // otherwise append - return Dwoo_Compiler::PHP_OPEN . 'echo '.$p['href'].'.\'\';'.Dwoo_Compiler::PHP_CLOSE; - } - - // return content - return $content . ''; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/auto_escape.php b/system/libs/dwoo/plugins/builtin/blocks/auto_escape.php deleted file mode 100644 index e85f4450..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/auto_escape.php +++ /dev/null @@ -1,61 +0,0 @@ - - * * enabled : if set to "on", "enable", true or 1 then the compiler autoescaping is enabled inside this block. set to "off", "disable", false or 0 to disable it - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Plugin_auto_escape extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block -{ - protected static $stack = array(); - - public function init($enabled) - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - $params = $compiler->getCompiledParams($params); - switch(strtolower(trim((string) $params['enabled'], '"\''))) { - - case 'on': - case 'true': - case 'enabled': - case 'enable': - case '1': - $enable = true; - break; - case 'off': - case 'false': - case 'disabled': - case 'disable': - case '0': - $enable = false; - break; - default: - throw new Dwoo_Compilation_Exception($compiler, 'Auto_Escape : Invalid parameter ('.$params['enabled'].'), valid parameters are "enable"/true or "disable"/false'); - - } - - self::$stack[] = $compiler->getAutoEscape(); - $compiler->setAutoEscape($enable); - return ''; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - $compiler->setAutoEscape(array_pop(self::$stack)); - return $content; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/block.php b/system/libs/dwoo/plugins/builtin/blocks/block.php deleted file mode 100644 index b396d9e6..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/block.php +++ /dev/null @@ -1,34 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Plugin_block extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block -{ - public function init($name='') - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - return ''; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - return $content; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/capture.php b/system/libs/dwoo/plugins/builtin/blocks/capture.php deleted file mode 100644 index 43ef3de1..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/capture.php +++ /dev/null @@ -1,61 +0,0 @@ - - * * name : capture name, used to read the value afterwards - * * assign : if set, the value is also saved in the given variable - * * cat : if true, the value is appended to the previous one (if any) instead of overwriting it - * - * If the cat parameter is true, the content - * will be appended to the existing content - * - * Example : - * - * - * {capture "foo"} - * Anything in here won't show, it will be saved for later use.. - * {/capture} - * Output was : {$.capture.foo} - * - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Plugin_capture extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block -{ - public function init($name = 'default', $assign = null, $cat = false, $trim = false) - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - return Dwoo_Compiler::PHP_OPEN.$prepend.'ob_start();'.$append.Dwoo_Compiler::PHP_CLOSE; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - $params = $compiler->getCompiledParams($params); - - $out = $content . Dwoo_Compiler::PHP_OPEN.$prepend."\n".'$tmp = ob_get_clean();'; - if ($params['trim'] !== 'false' && $params['trim'] !== 0) { - $out .= "\n".'$tmp = trim($tmp);'; - } - if ($params['cat'] === 'true' || $params['cat'] === 1) { - $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.Dwoo_Compiler::PHP_CLOSE; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/dynamic.php b/system/libs/dwoo/plugins/builtin/blocks/dynamic.php deleted file mode 100644 index 783eae8d..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/dynamic.php +++ /dev/null @@ -1,65 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Plugin_dynamic extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block -{ - public function init() - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - return ''; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - $output = Dwoo_Compiler::PHP_OPEN . - 'if($doCache) {'."\n\t". - 'echo \''. - str_replace('\'', '\\\'', $content) . - '\';'. - "\n} else {\n\t"; - if(substr($content, 0, strlen(Dwoo_Compiler::PHP_OPEN)) == Dwoo_Compiler::PHP_OPEN) { - $output .= substr($content, strlen(Dwoo_Compiler::PHP_OPEN)); - } else { - $output .= Dwoo_Compiler::PHP_CLOSE . $content; - } - if(substr($output, -strlen(Dwoo_Compiler::PHP_CLOSE)) == Dwoo_Compiler::PHP_CLOSE) { - $output = substr($output, 0, -strlen(Dwoo_Compiler::PHP_CLOSE)); - } else { - $output .= Dwoo_Compiler::PHP_OPEN; - } - $output .= "\n}". Dwoo_Compiler::PHP_CLOSE; - - return $output; - } - - public static function unescape($output, $dynamicId, $compiledFile) - { - $output = preg_replace_callback('/(.+?)<\/dwoo:dynamic_'.$dynamicId.'>/s', array('self', 'unescapePhp'), $output, -1, $count); - // re-add the includes on top of the file - if ($count && preg_match('#/\* template head \*/(.+?)/\* end template head \*/#s', file_get_contents($compiledFile), $m)) { - $output = ''.$output; - } - return $output; - } - - public static function unescapePhp($match) - { - return preg_replace('{<\?php /\*'.$match[1].'\*/ echo \'(.+?)\'; \?>}s', '$1', $match[2]); - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/else.php b/system/libs/dwoo/plugins/builtin/blocks/else.php deleted file mode 100644 index 32f1563f..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/else.php +++ /dev/null @@ -1,63 +0,0 @@ - - * {foreach $array val} - * $array is not empty so we display it's values : {$val} - * {else} - * if this shows, it means that $array is empty or doesn't exist. - * {/foreach} - * - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Plugin_else extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block -{ - public function init() - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - $preContent = ''; - while (true) { - $preContent .= $compiler->removeTopBlock(); - $block =& $compiler->getCurrentBlock(); - $interfaces = class_implements($block['class'], false); - if (in_array('Dwoo_IElseable', $interfaces) !== false) { - break; - } - } - - $params['initialized'] = true; - $compiler->injectBlock($type, $params); - return $preContent; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - if (!isset($params['initialized'])) { - return ''; - } - - $block =& $compiler->getCurrentBlock(); - $block['params']['hasElse'] = Dwoo_Compiler::PHP_OPEN."else {\n".Dwoo_Compiler::PHP_CLOSE . $content . Dwoo_Compiler::PHP_OPEN."\n}".Dwoo_Compiler::PHP_CLOSE; - return ''; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/elseif.php b/system/libs/dwoo/plugins/builtin/blocks/elseif.php deleted file mode 100644 index 14949ace..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/elseif.php +++ /dev/null @@ -1,60 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Plugin_elseif extends Dwoo_Plugin_if implements Dwoo_ICompilable_Block, Dwoo_IElseable -{ - public function init(array $rest) - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - $preContent = ''; - while (true) { - $preContent .= $compiler->removeTopBlock(); - $block =& $compiler->getCurrentBlock(); - $interfaces = class_implements($block['class'], false); - if (in_array('Dwoo_IElseable', $interfaces) !== false) { - break; - } - } - - $params['initialized'] = true; - $compiler->injectBlock($type, $params); - return $preContent; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - if (!isset($params['initialized'])) { - return ''; - } - - $params = $compiler->getCompiledParams($params); - - $pre = Dwoo_Compiler::PHP_OPEN."elseif (".implode(' ', self::replaceKeywords($params['*'], $compiler)).") {\n" . Dwoo_Compiler::PHP_CLOSE; - $post = Dwoo_Compiler::PHP_OPEN."\n}".Dwoo_Compiler::PHP_CLOSE; - - if (isset($params['hasElse'])) { - $post .= $params['hasElse']; - } - - $block =& $compiler->getCurrentBlock(); - $block['params']['hasElse'] = $pre . $content . $post; - return ''; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/for.php b/system/libs/dwoo/plugins/builtin/blocks/for.php deleted file mode 100644 index aeabb2a0..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/for.php +++ /dev/null @@ -1,147 +0,0 @@ - - * * name : for name to access it's iterator variables through {$.for.name.var} see {@link http://wiki.dwoo.org/index.php/IteratorVariables} for details - * * from : array to iterate from (which equals 0) or a number as a start value - * * to : value to stop iterating at (equals count($array) by default if you set an array in from) - * * step : defines the incrementation of the pointer at each iteration - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - */ -class Dwoo_Plugin_for extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block, Dwoo_IElseable -{ - public static $cnt=0; - - public function init($name, $from, $to=null, $step=1, $skip=0) - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - // get block params and save the current template pointer to use it in the postProcessing method - $currentBlock =& $compiler->getCurrentBlock(); - $currentBlock['params']['tplPointer'] = $compiler->getPointer(); - - return ''; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - $params = $compiler->getCompiledParams($params); - $tpl = $compiler->getTemplateSource($params['tplPointer']); - - // assigns params - $from = $params['from']; - $name = $params['name']; - $step = $params['step']; - $to = $params['to']; - - // evaluates which global variables have to be computed - $varName = '$dwoo.for.'.trim($name, '"\'').'.'; - $shortVarName = '$.for.'.trim($name, '"\'').'.'; - $usesAny = strpos($tpl, $varName) !== false || strpos($tpl, $shortVarName) !== false; - $usesFirst = strpos($tpl, $varName.'first') !== false || strpos($tpl, $shortVarName.'first') !== false; - $usesLast = strpos($tpl, $varName.'last') !== false || strpos($tpl, $shortVarName.'last') !== false; - $usesIndex = strpos($tpl, $varName.'index') !== false || strpos($tpl, $shortVarName.'index') !== false; - $usesIteration = $usesFirst || $usesLast || strpos($tpl, $varName.'iteration') !== false || strpos($tpl, $shortVarName.'iteration') !== false; - $usesShow = strpos($tpl, $varName.'show') !== false || strpos($tpl, $shortVarName.'show') !== false; - $usesTotal = $usesLast || strpos($tpl, $varName.'total') !== false || strpos($tpl, $shortVarName.'total') !== false; - - if (strpos($name, '$this->scope[') !== false) { - $usesAny = $usesFirst = $usesLast = $usesIndex = $usesIteration = $usesShow = $usesTotal = true; - } - - // gets foreach id - $cnt = self::$cnt++; - - // builds pre processing output for - $out = Dwoo_Compiler::PHP_OPEN . "\n".'$_for'.$cnt.'_from = '.$from.';'. - "\n".'$_for'.$cnt.'_to = '.$to.';'. - "\n".'$_for'.$cnt.'_step = abs('.$step.');'. - "\n".'if (is_numeric($_for'.$cnt.'_from) && !is_numeric($_for'.$cnt.'_to)) { $this->triggerError(\'For requires the to parameter when using a numerical from\'); }'. - "\n".'$tmp_shows = $this->isArray($_for'.$cnt.'_from, true) || (is_numeric($_for'.$cnt.'_from) && (abs(($_for'.$cnt.'_from - $_for'.$cnt.'_to)/$_for'.$cnt.'_step) !== 0 || $_for'.$cnt.'_from == $_for'.$cnt.'_to));'; - // 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" => $tmp_shows,'; - if ($usesTotal) $out .="\n\t".'"total" => $this->isArray($_for'.$cnt.'_from) ? floor(count($_for'.$cnt.'_from) / $_for'.$cnt.'_step) : (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 for must be looped - $out .= "\n".'if ($tmp_shows)'."\n{"; - // set from/to to correct values if an array was given - $out .= "\n\t".'if ($this->isArray($_for'.$cnt.'_from, true)) { - $_for'.$cnt.'_to = is_numeric($_for'.$cnt.'_to) ? $_for'.$cnt.'_to - $_for'.$cnt.'_step : count($_for'.$cnt.'_from) - 1; - $_for'.$cnt.'_from = 0; - }'; - - // if input are pure numbers it shouldn't reorder them, if it's variables it gets too messy though so in that case a counter should be used - $reverse = false; - $condition = '<='; - $incrementer = '+'; - - if (preg_match('{^(["\']?)([0-9]+)\1$}', $from, $mN1) && preg_match('{^(["\']?)([0-9]+)\1$}', $to, $mN2)) { - $from = (int) $mN1[2]; - $to = (int) $mN2[2]; - if ($from > $to) { - $reverse = true; - $condition = '>='; - $incrementer = '-'; - } - } - - // reverse from and to if needed - if (!$reverse) { - $out .= "\n\t".'if ($_for'.$cnt.'_from > $_for'.$cnt.'_to) { - $tmp = $_for'.$cnt.'_from; - $_for'.$cnt.'_from = $_for'.$cnt.'_to; - $_for'.$cnt.'_to = $tmp; - }'; - } - - $out .= ' - for ($this->scope['.$name.'] = $_for'.$cnt.'_from; $this->scope['.$name.'] '.$condition.' $_for'.$cnt.'_to; $this->scope['.$name.'] '.$incrementer.'= $_for'.$cnt.'_step)'."\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".Dwoo_Compiler::PHP_CLOSE; - - - // build post processing output and cache it - $postOut = Dwoo_Compiler::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".Dwoo_Compiler::PHP_CLOSE; - - if (isset($params['hasElse'])) { - $postOut .= $params['hasElse']; - } - - return $out . $content . $postOut; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/foreach.php b/system/libs/dwoo/plugins/builtin/blocks/foreach.php deleted file mode 100644 index 2c2f9728..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/foreach.php +++ /dev/null @@ -1,152 +0,0 @@ - - * * from : the array that you want to iterate over - * * key : variable name for the key (or for the item if item is not defined) - * * item : variable name for each item - * * name : foreach name to access it's iterator variables through {$.foreach.name.var} see {@link http://wiki.dwoo.org/index.php/IteratorVariables} for details - * - * Example : - * - * - * {foreach $array val} - * {$val.something} - * {/foreach} - * - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - */ -class Dwoo_Plugin_foreach extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block, Dwoo_IElseable -{ - public static $cnt=0; - - public function init($from, $key=null, $item=null, $name='default', $implode=null) - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - // get block params and save the current template pointer to use it in the postProcessing method - $currentBlock =& $compiler->getCurrentBlock(); - $currentBlock['params']['tplPointer'] = $compiler->getPointer(); - - return ''; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - $params = $compiler->getCompiledParams($params); - $tpl = $compiler->getTemplateSource($params['tplPointer']); - - // 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 Dwoo_Compilation_Exception($compiler, 'Foreach item parameter missing'); - } - $name = $params['name']; - - if (substr($val, 0, 1) !== '"' && substr($val, 0, 1) !== '\'') { - throw new Dwoo_Compilation_Exception($compiler, 'Foreach item parameter must be of type string'); - } - if (isset($key) && substr($val, 0, 1) !== '"' && substr($val, 0, 1) !== '\'') { - throw new Dwoo_Compilation_Exception($compiler, 'Foreach key parameter must be of type string'); - } - - // evaluates which global variables have to be computed - $varName = '$dwoo.foreach.'.trim($name, '"\'').'.'; - $shortVarName = '$.foreach.'.trim($name, '"\'').'.'; - $usesAny = strpos($tpl, $varName) !== false || strpos($tpl, $shortVarName) !== false; - $usesFirst = strpos($tpl, $varName.'first') !== false || strpos($tpl, $shortVarName.'first') !== false; - $usesLast = strpos($tpl, $varName.'last') !== false || strpos($tpl, $shortVarName.'last') !== false; - $usesIndex = $usesFirst || strpos($tpl, $varName.'index') !== false || strpos($tpl, $shortVarName.'index') !== false; - $usesIteration = $usesLast || strpos($tpl, $varName.'iteration') !== false || strpos($tpl, $shortVarName.'iteration') !== false; - $usesShow = strpos($tpl, $varName.'show') !== false || strpos($tpl, $shortVarName.'show') !== false; - $usesTotal = $usesLast || strpos($tpl, $varName.'total') !== false || strpos($tpl, $shortVarName.'total') !== false; - - if (strpos($name, '$this->scope[') !== false) { - $usesAny = $usesFirst = $usesLast = $usesIndex = $usesIteration = $usesShow = $usesTotal = true; - } - - // override globals vars if implode is used - if ($params['implode'] !== 'null') { - $implode = $params['implode']; - $usesAny = true; - $usesLast = true; - $usesIteration = true; - $usesTotal = true; - } - - // gets foreach id - $cnt = self::$cnt++; - - // build pre content output - $pre = Dwoo_Compiler::PHP_OPEN . "\n".'$_fh'.$cnt.'_data = '.$src.';'; - // adds foreach properties - if ($usesAny) { - $pre .= "\n".'$this->globals["foreach"]['.$name.'] = array'."\n("; - if ($usesIndex) $pre .="\n\t".'"index" => 0,'; - if ($usesIteration) $pre .="\n\t".'"iteration" => 1,'; - if ($usesFirst) $pre .="\n\t".'"first" => null,'; - if ($usesLast) $pre .="\n\t".'"last" => null,'; - if ($usesShow) $pre .="\n\t".'"show" => $this->isArray($_fh'.$cnt.'_data, true),'; - if ($usesTotal) $pre .="\n\t".'"total" => $this->isArray($_fh'.$cnt.'_data) ? count($_fh'.$cnt.'_data) : 0,'; - $pre.="\n);\n".'$_fh'.$cnt.'_glob =& $this->globals["foreach"]['.$name.'];'; - } - // checks if foreach must be looped - $pre .= "\n".'if ($this->isArray($_fh'.$cnt.'_data'.(isset($params['hasElse']) ? ', true' : '').') === true)'."\n{"; - // iterates over keys - $pre .= "\n\t".'foreach ($_fh'.$cnt.'_data as '.(isset($key)?'$this->scope['.$key.']=>':'').'$this->scope['.$val.'])'."\n\t{"; - // updates properties - if ($usesFirst) { - $pre .= "\n\t\t".'$_fh'.$cnt.'_glob["first"] = (string) ($_fh'.$cnt.'_glob["index"] === 0);'; - } - if ($usesLast) { - $pre .= "\n\t\t".'$_fh'.$cnt.'_glob["last"] = (string) ($_fh'.$cnt.'_glob["iteration"] === $_fh'.$cnt.'_glob["total"]);'; - } - $pre .= "\n/* -- foreach start output */\n".Dwoo_Compiler::PHP_CLOSE; - - // build post content output - $post = Dwoo_Compiler::PHP_OPEN . "\n"; - - if (isset($implode)) { - $post .= '/* -- implode */'."\n".'if (!$_fh'.$cnt.'_glob["last"]) {'. - "\n\t".'echo '.$implode.";\n}\n"; - } - $post .= '/* -- foreach end output */'; - // update properties - if ($usesIndex) { - $post.="\n\t\t".'$_fh'.$cnt.'_glob["index"]+=1;'; - } - if ($usesIteration) { - $post.="\n\t\t".'$_fh'.$cnt.'_glob["iteration"]+=1;'; - } - // end loop - $post .= "\n\t}\n}".Dwoo_Compiler::PHP_CLOSE; - if (isset($params['hasElse'])) { - $post .= $params['hasElse']; - } - - return $pre . $content . $post; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/foreachelse.php b/system/libs/dwoo/plugins/builtin/blocks/foreachelse.php deleted file mode 100644 index fbae0ea1..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/foreachelse.php +++ /dev/null @@ -1,43 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Plugin_foreachelse extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block -{ - public function init() - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - $with =& $compiler->findBlock('foreach', true); - - $params['initialized'] = true; - $compiler->injectBlock($type, $params); - - return ''; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - if (!isset($params['initialized'])) { - return ''; - } - - $block =& $compiler->getCurrentBlock(); - $block['params']['hasElse'] = Dwoo_Compiler::PHP_OPEN."else {\n".Dwoo_Compiler::PHP_CLOSE . $content . Dwoo_Compiler::PHP_OPEN."\n}".Dwoo_Compiler::PHP_CLOSE; - return ''; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/forelse.php b/system/libs/dwoo/plugins/builtin/blocks/forelse.php deleted file mode 100644 index 74bde5ba..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/forelse.php +++ /dev/null @@ -1,43 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Plugin_forelse extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block -{ - public function init() - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - $with =& $compiler->findBlock('for', true); - - $params['initialized'] = true; - $compiler->injectBlock($type, $params); - - return ''; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - if (!isset($params['initialized'])) { - return ''; - } - - $block =& $compiler->getCurrentBlock(); - $block['params']['hasElse'] = Dwoo_Compiler::PHP_OPEN."else {\n".Dwoo_Compiler::PHP_CLOSE . $content . Dwoo_Compiler::PHP_OPEN."\n}".Dwoo_Compiler::PHP_CLOSE; - return ''; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/if.php b/system/libs/dwoo/plugins/builtin/blocks/if.php deleted file mode 100644 index 51cf5365..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/if.php +++ /dev/null @@ -1,180 +0,0 @@ - == - * neq or ne -> != - * gte or ge -> >= - * lte or le -> <= - * gt -> > - * lt -> < - * mod -> % - * not -> ! - * X is [not] div by Y -> (X % Y) == 0 - * X is [not] even [by Y] -> (X % 2) == 0 or ((X/Y) % 2) == 0 - * X is [not] odd [by Y] -> (X % 2) != 0 or ((X/Y) % 2) != 0 - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Plugin_if extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block, Dwoo_IElseable -{ - public function init(array $rest) - { - } - - public static function replaceKeywords(array $params, Dwoo_Compiler $compiler) - { - $p = array(); - - reset($params); - while (list($k,$v) = each($params)) { - $v = (string) $v; - if(substr($v, 0, 1) === '"' || substr($v, 0, 1) === '\'') { - $vmod = strtolower(substr($v, 1, -1)); - } else { - $vmod = strtolower($v); - } - switch($vmod) { - - case 'and': - $p[] = '&&'; - break; - case 'or': - $p[] = '||'; - 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 (isset($params[$k+1]) && strtolower(trim($params[$k+1], '"\'')) === 'not') { - $negate = true; - next($params); - } else { - $negate = false; - } - $ptr = 1+(int)$negate; - if (!isset($params[$k+$ptr])) { - $params[$k+$ptr] = ''; - } else { - $params[$k+$ptr] = trim($params[$k+$ptr], '"\''); - } - switch($params[$k+$ptr]) { - - case 'div': - if (isset($params[$k+$ptr+1]) && strtolower(trim($params[$k+$ptr+1], '"\'')) === 'by') { - $p[] = ' % '.$params[$k+$ptr+2].' '.($negate?'!':'=').'== 0'; - next($params); - next($params); - next($params); - } else { - throw new Dwoo_Compilation_Exception($compiler, 'If : Syntax error : syntax should be "if $a is [not] div by $b", found '.$params[$k-1].' is '.($negate?'not ':'').'div '.$params[$k+$ptr+1].' '.$params[$k+$ptr+2]); - } - break; - case 'even': - $a = array_pop($p); - if (isset($params[$k+$ptr+1]) && strtolower(trim($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]) && strtolower(trim($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 Dwoo_Compilation_Exception($compiler, 'If : Syntax error : syntax should be "if $a is [not] (div|even|odd) [by $b]", found '.$params[$k-1].' is '.$params[$k+$ptr+1]); - - } - break; - case '%': - case 'mod': - $p[] = '%'; - break; - case '!': - case 'not': - $p[] = '!'; - break; - default: - $p[] = $v; - - } - } - - return $p; - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - return ''; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - $params = $compiler->getCompiledParams($params); - - $pre = Dwoo_Compiler::PHP_OPEN.'if ('.implode(' ', self::replaceKeywords($params['*'], $compiler)).") {\n".Dwoo_Compiler::PHP_CLOSE; - - $post = Dwoo_Compiler::PHP_OPEN."\n}".Dwoo_Compiler::PHP_CLOSE; - - if (isset($params['hasElse'])) { - $post .= $params['hasElse']; - } - - return $pre . $content . $post; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/loop.php b/system/libs/dwoo/plugins/builtin/blocks/loop.php deleted file mode 100644 index 026795c6..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/loop.php +++ /dev/null @@ -1,128 +0,0 @@ - - * * from : the array that you want to iterate over - * * name : loop name to access it's iterator variables through {$.loop.name.var} see {@link http://wiki.dwoo.org/index.php/IteratorVariables} for details - * - * Example : - * - * instead of a foreach block such as : - * - * - * {foreach $variable value} - * {$value.foo} {$value.bar} - * {/foreach} - * - * - * you can do : - * - * - * {loop $variable} - * {$foo} {$bar} - * {/loop} - * - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - */ -class Dwoo_Plugin_loop extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block, Dwoo_IElseable -{ - public static $cnt=0; - - public function init($from, $name='default') - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - // get block params and save the current template pointer to use it in the postProcessing method - $currentBlock =& $compiler->getCurrentBlock(); - $currentBlock['params']['tplPointer'] = $compiler->getPointer(); - - return ''; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - $params = $compiler->getCompiledParams($params); - $tpl = $compiler->getTemplateSource($params['tplPointer']); - - // assigns params - $src = $params['from']; - $name = $params['name']; - - // evaluates which global variables have to be computed - $varName = '$dwoo.loop.'.trim($name, '"\'').'.'; - $shortVarName = '$.loop.'.trim($name, '"\'').'.'; - $usesAny = strpos($tpl, $varName) !== false || strpos($tpl, $shortVarName) !== false; - $usesFirst = strpos($tpl, $varName.'first') !== false || strpos($tpl, $shortVarName.'first') !== false; - $usesLast = strpos($tpl, $varName.'last') !== false || strpos($tpl, $shortVarName.'last') !== false; - $usesIndex = $usesFirst || strpos($tpl, $varName.'index') !== false || strpos($tpl, $shortVarName.'index') !== false; - $usesIteration = $usesLast || strpos($tpl, $varName.'iteration') !== false || strpos($tpl, $shortVarName.'iteration') !== false; - $usesShow = strpos($tpl, $varName.'show') !== false || strpos($tpl, $shortVarName.'show') !== false; - $usesTotal = $usesLast || strpos($tpl, $varName.'total') !== false || strpos($tpl, $shortVarName.'total') !== false; - - if (strpos($name, '$this->scope[') !== false) { - $usesAny = $usesFirst = $usesLast = $usesIndex = $usesIteration = $usesShow = $usesTotal = true; - } - - // gets foreach id - $cnt = self::$cnt++; - - // builds pre processing output - $pre = Dwoo_Compiler::PHP_OPEN . "\n".'$_loop'.$cnt.'_data = '.$src.';'; - // adds foreach properties - if ($usesAny) { - $pre .= "\n".'$this->globals["loop"]['.$name.'] = array'."\n("; - if ($usesIndex) $pre .="\n\t".'"index" => 0,'; - if ($usesIteration) $pre .="\n\t".'"iteration" => 1,'; - if ($usesFirst) $pre .="\n\t".'"first" => null,'; - if ($usesLast) $pre .="\n\t".'"last" => null,'; - if ($usesShow) $pre .="\n\t".'"show" => $this->isArray($_loop'.$cnt.'_data, true),'; - if ($usesTotal) $pre .="\n\t".'"total" => $this->isArray($_loop'.$cnt.'_data) ? count($_loop'.$cnt.'_data) : 0,'; - $pre.="\n);\n".'$_loop'.$cnt.'_glob =& $this->globals["loop"]['.$name.'];'; - } - // checks if the loop must be looped - $pre .= "\n".'if ($this->isArray($_loop'.$cnt.'_data'.(isset($params['hasElse']) ? ', true' : '').') === true)'."\n{"; - // iterates over keys - $pre .= "\n\t".'foreach ($_loop'.$cnt.'_data as $tmp_key => $this->scope["-loop-"])'."\n\t{"; - // updates properties - if ($usesFirst) { - $pre .= "\n\t\t".'$_loop'.$cnt.'_glob["first"] = (string) ($_loop'.$cnt.'_glob["index"] === 0);'; - } - if ($usesLast) { - $pre .= "\n\t\t".'$_loop'.$cnt.'_glob["last"] = (string) ($_loop'.$cnt.'_glob["iteration"] === $_loop'.$cnt.'_glob["total"]);'; - } - $pre .= "\n\t\t".'$_loop'.$cnt.'_scope = $this->setScope(array("-loop-"));' . "\n/* -- loop start output */\n".Dwoo_Compiler::PHP_CLOSE; - - // build post processing output and cache it - $post = Dwoo_Compiler::PHP_OPEN . "\n".'/* -- loop end output */'."\n\t\t".'$this->setScope($_loop'.$cnt.'_scope, true);'; - // update properties - if ($usesIndex) { - $post.="\n\t\t".'$_loop'.$cnt.'_glob["index"]+=1;'; - } - if ($usesIteration) { - $post.="\n\t\t".'$_loop'.$cnt.'_glob["iteration"]+=1;'; - } - // end loop - $post .= "\n\t}\n}\n" . Dwoo_Compiler::PHP_CLOSE; - if (isset($params['hasElse'])) { - $post .= $params['hasElse']; - } - - return $pre . $content . $post; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/section.php b/system/libs/dwoo/plugins/builtin/blocks/section.php deleted file mode 100644 index 7daba515..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/section.php +++ /dev/null @@ -1,131 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Plugin_section extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block, Dwoo_IElseable -{ - public static $cnt=0; - - public function init($name, $loop, $start = null, $step = null, $max = null, $show = true) - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - return ''; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - $output = Dwoo_Compiler::PHP_OPEN; - $params = $compiler->getCompiledParams($params); - - // assigns params - $loop = $params['loop']; - $start = $params['start']; - $max = $params['max']; - $name = $params['name']; - $step = $params['step']; - $show = $params['show']; - - // gets unique id - $cnt = self::$cnt++; - - $output .= '$this->globals[\'section\']['.$name.'] = array();'."\n". - '$_section'.$cnt.' =& $this->globals[\'section\']['.$name.'];'."\n"; - - if ($loop !== 'null') { - $output .= '$_section'.$cnt.'[\'loop\'] = is_array($tmp = '.$loop.') ? count($tmp) : max(0, (int) $tmp);'."\n"; - } else { - $output .= '$_section'.$cnt.'[\'loop\'] = 1;'."\n"; - } - - if ($show !== 'null') { - $output .= '$_section'.$cnt.'[\'show\'] = '.$show.";\n"; - } else { - $output .= '$_section'.$cnt.'[\'show\'] = true;'."\n"; - } - - if ($name !== 'null') { - $output .= '$_section'.$cnt.'[\'name\'] = '.$name.";\n"; - } else { - $output .= '$_section'.$cnt.'[\'name\'] = true;'."\n"; - } - - if ($max !== 'null') { - $output .= '$_section'.$cnt.'[\'max\'] = (int)'.$max.";\n". - 'if($_section'.$cnt.'[\'max\'] < 0) { $_section'.$cnt.'[\'max\'] = $_section'.$cnt.'[\'loop\']; }'."\n"; - } else { - $output .= '$_section'.$cnt.'[\'max\'] = $_section'.$cnt.'[\'loop\'];'."\n"; - } - - if ($step !== 'null') { - $output .= '$_section'.$cnt.'[\'step\'] = (int)'.$step.' == 0 ? 1 : (int) '.$step.";\n"; - } else { - $output .= '$_section'.$cnt.'[\'step\'] = 1;'."\n"; - } - - if ($start !== 'null') { - $output .= '$_section'.$cnt.'[\'start\'] = (int)'.$start.";\n"; - } else { - $output .= '$_section'.$cnt.'[\'start\'] = $_section'.$cnt.'[\'step\'] > 0 ? 0 : $_section'.$cnt.'[\'loop\'] - 1;'."\n". - 'if ($_section'.$cnt.'[\'start\'] < 0) { $_section'.$cnt.'[\'start\'] = max($_section'.$cnt.'[\'step\'] > 0 ? 0 : -1, $_section'.$cnt.'[\'loop\'] + $_section'.$cnt.'[\'start\']); } '."\n". - 'else { $_section'.$cnt.'[\'start\'] = min($_section'.$cnt.'[\'start\'], $_section'.$cnt.'[\'step\'] > 0 ? $_section'.$cnt.'[\'loop\'] : $_section'.$cnt.'[\'loop\'] -1); }'."\n"; - } - -/* if ($usesAny) { - $output .= "\n".'$this->globals["section"]['.$name.'] = array'."\n("; - if ($usesIndex) $output .="\n\t".'"index" => 0,'; - if ($usesIteration) $output .="\n\t".'"iteration" => 1,'; - if ($usesFirst) $output .="\n\t".'"first" => null,'; - if ($usesLast) $output .="\n\t".'"last" => null,'; - if ($usesShow) $output .="\n\t".'"show" => ($this->isArray($_for'.$cnt.'_from, true)) || (is_numeric($_for'.$cnt.'_from) && $_for'.$cnt.'_from != $_for'.$cnt.'_to),'; - if ($usesTotal) $output .="\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".'$_section'.$cnt.'[\'glob\'] =& $this->globals["section"]['.$name.'];'."\n\n"; - } -*/ - - $output .= 'if ($_section'.$cnt.'[\'show\']) {'."\n"; - if ($start === 'null' && $step === 'null' && $max === 'null') { - $output .= ' $_section'.$cnt.'[\'total\'] = $_section'.$cnt.'[\'loop\'];'."\n"; - } else { - $output .= ' $_section'.$cnt.'[\'total\'] = min(ceil(($_section'.$cnt.'[\'step\'] > 0 ? $_section'.$cnt.'[\'loop\'] - $_section'.$cnt.'[\'start\'] : $_section'.$cnt.'[\'start\'] + 1) / abs($_section'.$cnt.'[\'step\'])), $_section'.$cnt.'[\'max\']);'."\n"; - } - $output .= ' if ($_section'.$cnt.'[\'total\'] == 0) {'."\n". - ' $_section'.$cnt.'[\'show\'] = false;'."\n". - ' }'."\n". - '} else {'."\n". - ' $_section'.$cnt.'[\'total\'] = 0;'."\n}\n"; - $output .= 'if ($_section'.$cnt.'[\'show\']) {'."\n"; - $output .= "\t".'for ($this->scope['.$name.'] = $_section'.$cnt.'[\'start\'], $_section'.$cnt.'[\'iteration\'] = 1; '. - '$_section'.$cnt.'[\'iteration\'] <= $_section'.$cnt.'[\'total\']; '. - '$this->scope['.$name.'] += $_section'.$cnt.'[\'step\'], $_section'.$cnt.'[\'iteration\']++) {'."\n"; - $output .= "\t\t".'$_section'.$cnt.'[\'rownum\'] = $_section'.$cnt.'[\'iteration\'];'."\n"; - $output .= "\t\t".'$_section'.$cnt.'[\'index_prev\'] = $this->scope['.$name.'] - $_section'.$cnt.'[\'step\'];'."\n"; - $output .= "\t\t".'$_section'.$cnt.'[\'index_next\'] = $this->scope['.$name.'] + $_section'.$cnt.'[\'step\'];'."\n"; - $output .= "\t\t".'$_section'.$cnt.'[\'first\'] = ($_section'.$cnt.'[\'iteration\'] == 1);'."\n"; - $output .= "\t\t".'$_section'.$cnt.'[\'last\'] = ($_section'.$cnt.'[\'iteration\'] == $_section'.$cnt.'[\'total\']);'."\n"; - - $output .= Dwoo_Compiler::PHP_CLOSE . $content . Dwoo_Compiler::PHP_OPEN; - - $output .= "\n\t}\n} " . Dwoo_Compiler::PHP_CLOSE; - - if (isset($params['hasElse'])) { - $output .= $params['hasElse']; - } - - return $output; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/smartyinterface.php b/system/libs/dwoo/plugins/builtin/blocks/smartyinterface.php deleted file mode 100644 index d0e495d4..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/smartyinterface.php +++ /dev/null @@ -1,59 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Plugin_smartyinterface extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block -{ - public function init($__funcname, $__functype, array $rest=array()) {} - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - $params = $compiler->getCompiledParams($params); - $func = $params['__funcname']; - $pluginType = $params['__functype']; - $params = $params['*']; - - if ($pluginType & Dwoo::CUSTOM_PLUGIN) { - $customPlugins = $compiler->getDwoo()->getCustomPlugins(); - $callback = $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.'('; - } - - $paramsOut = ''; - foreach ($params as $i=>$p) { - $paramsOut .= var_export($i, true).' => '.$p.','; - } - - $curBlock =& $compiler->getCurrentBlock(); - $curBlock['params']['postOut'] = Dwoo_Compiler::PHP_OPEN.' $_block_content = ob_get_clean(); $_block_repeat=false; echo '.$callback.'$_tag_stack[count($_tag_stack)-1], $_block_content, $this, $_block_repeat); } array_pop($_tag_stack);'.Dwoo_Compiler::PHP_CLOSE; - - return Dwoo_Compiler::PHP_OPEN.$prepend.' if (!isset($_tag_stack)){ $_tag_stack = array(); } $_tag_stack[] = array('.$paramsOut.'); $_block_repeat=true; '.$callback.'$_tag_stack[count($_tag_stack)-1], null, $this, $_block_repeat); while ($_block_repeat) { ob_start();'.Dwoo_Compiler::PHP_CLOSE; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - return $content . $params['postOut']; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/strip.php b/system/libs/dwoo/plugins/builtin/blocks/strip.php deleted file mode 100644 index dc02933b..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/strip.php +++ /dev/null @@ -1,50 +0,0 @@ - - * * mode : sets the content being stripped, available mode are 'default' or 'js' - * for javascript, which strips the comments to prevent syntax errors - * - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - */ -class Dwoo_Plugin_strip extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block -{ - public function init($mode = "default") - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - return ''; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - $params = $compiler->getCompiledParams($params); - - $mode = trim($params['mode'], '"\''); - switch ($mode) { - case 'js': - case 'javascript': - $content = preg_replace('#(? - * * name : template name - * * rest : list of arguments and optional default values - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.1.0 - * @date 2009-07-18 - * @package Dwoo - */ -class Dwoo_Plugin_template extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block -{ - public function init($name, array $rest = array()) - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - $params = $compiler->getCompiledParams($params); - $parsedParams = array(); - if (!isset($params['*'])) - $params['*'] = array(); - foreach ($params['*'] as $param=>$defValue) { - if (is_numeric($param)) { - $param = $defValue; - $defValue = null; - } - $param = trim($param, '\'"'); - if (!preg_match('#^[a-z0-9_]+$#i', $param)) { - throw new Dwoo_Compilation_Exception($compiler, 'Function : parameter names must contain only A-Z, 0-9 or _'); - } - $parsedParams[$param] = $defValue; - } - $params['name'] = substr($params['name'], 1, -1); - $params['*'] = $parsedParams; - $params['uuid'] = uniqid(); - $compiler->addTemplatePlugin($params['name'], $parsedParams, $params['uuid']); - $currentBlock =& $compiler->getCurrentBlock(); - $currentBlock['params'] = $params; - return ''; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - $paramstr = 'Dwoo $dwoo'; - $init = 'static $_callCnt = 0;'."\n". - '$dwoo->scope[\' '.$params['uuid'].'\'.$_callCnt] = array();'."\n". - '$_scope = $dwoo->setScope(array(\' '.$params['uuid'].'\'.($_callCnt++)));'."\n"; - $cleanup = '/* -- template end output */ $dwoo->setScope($_scope, true);'; - foreach ($params['*'] as $param=>$defValue) { - if ($defValue === null) { - $paramstr.=', $'.$param; - } else { - $paramstr.=', $'.$param.' = '.$defValue; - } - $init .= '$dwoo->scope[\''.$param.'\'] = $'.$param.";\n"; - } - $init .= '/* -- template start output */'; - - $funcName = 'Dwoo_Plugin_'.$params['name'].'_'.$params['uuid']; - - $search = array( - '$this->charset', - '$this->', - '$this,', - ); - $replacement = array( - '$dwoo->getCharset()', - '$dwoo->', - '$dwoo,', - ); - $content = str_replace($search, $replacement, $content); - - $body = 'if (!function_exists(\''.$funcName."')) {\nfunction ".$funcName.'('.$paramstr.') {'."\n$init".Dwoo_Compiler::PHP_CLOSE. - $prepend.$content.$append. - Dwoo_Compiler::PHP_OPEN.$cleanup."\n}\n}"; - $compiler->addTemplatePlugin($params['name'], $params['*'], $params['uuid'], $body); - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/textformat.php b/system/libs/dwoo/plugins/builtin/blocks/textformat.php deleted file mode 100644 index fb0f4229..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/textformat.php +++ /dev/null @@ -1,94 +0,0 @@ - - * * wrap : maximum line length - * * wrap_char : the character(s) to use to break the line - * * wrap_cut : if true, the words that are longer than $wrap are cut instead of overflowing - * * indent : amount of $indent_char to insert before every line - * * indent_char : character(s) to insert before every line - * * indent_first : amount of additional $indent_char to insert before the first line of each paragraphs - * * style : some predefined formatting styles that set up every required variables, can be "email" or "html" - * * assign : if set, the formatted text is assigned to that variable instead of being output - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Plugin_textformat extends Dwoo_Block_Plugin -{ - 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 = '
'; - $indent_char = $indent_char == "\t" ? '    ':' '; - 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); - } - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/topLevelBlock.php b/system/libs/dwoo/plugins/builtin/blocks/topLevelBlock.php deleted file mode 100644 index 95e55767..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/topLevelBlock.php +++ /dev/null @@ -1,32 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -final class Dwoo_Plugin_topLevelBlock extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block -{ - public function init() - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - return '/* end template head */ ob_start(); /* template body */ '.Dwoo_Compiler::PHP_CLOSE; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - return $content . Dwoo_Compiler::PHP_OPEN.' /* end template body */'."\n".'return $this->buffer . ob_get_clean();'; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/with.php b/system/libs/dwoo/plugins/builtin/blocks/with.php deleted file mode 100644 index 8bd46dfc..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/with.php +++ /dev/null @@ -1,76 +0,0 @@ - - * * var : the variable name to move into - * - * Example : - * - * instead of the following : - * - * - * {if $long.boring.prefix} - * {$long.boring.prefix.val} - {$long.boring.prefix.secondVal} - {$long.boring.prefix.thirdVal} - * {/if} - * - * - * you can use : - * - * - * {with $long.boring.prefix} - * {$val} - {$secondVal} - {$thirdVal} - * {/with} - * - * - * 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. - * - * @author Jordi Boggiano - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Plugin_with extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block, Dwoo_IElseable -{ - protected static $cnt=0; - - public function init($var) - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - return ''; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - $rparams = $compiler->getRealParams($params); - $cparams = $compiler->getCompiledParams($params); - - $compiler->setScope($rparams['var']); - - - $pre = Dwoo_Compiler::PHP_OPEN. 'if ('.$cparams['var'].')'."\n{\n". - '$_with'.(self::$cnt).' = $this->setScope("'.$rparams['var'].'");'. - "\n/* -- start with output */\n".Dwoo_Compiler::PHP_CLOSE; - - $post = Dwoo_Compiler::PHP_OPEN. "\n/* -- end with output */\n". - '$this->setScope($_with'.(self::$cnt++).', true);'. - "\n}\n".Dwoo_Compiler::PHP_CLOSE; - - if (isset($params['hasElse'])) { - $post .= $params['hasElse']; - } - - return $pre . $content . $post; - } -} diff --git a/system/libs/dwoo/plugins/builtin/blocks/withelse.php b/system/libs/dwoo/plugins/builtin/blocks/withelse.php deleted file mode 100644 index deffe574..00000000 --- a/system/libs/dwoo/plugins/builtin/blocks/withelse.php +++ /dev/null @@ -1,43 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Plugin_withelse extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block -{ - public function init() - { - } - - public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) - { - $with =& $compiler->findBlock('with', true); - - $params['initialized'] = true; - $compiler->injectBlock($type, $params); - - return ''; - } - - public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content) - { - if (!isset($params['initialized'])) { - return ''; - } - - $block =& $compiler->getCurrentBlock(); - $block['params']['hasElse'] = Dwoo_Compiler::PHP_OPEN."else {\n".Dwoo_Compiler::PHP_CLOSE . $content . Dwoo_Compiler::PHP_OPEN."\n}".Dwoo_Compiler::PHP_CLOSE; - return ''; - } -} diff --git a/system/libs/dwoo/plugins/builtin/filters/html_format.php b/system/libs/dwoo/plugins/builtin/filters/html_format.php deleted file mode 100644 index 18970f48..00000000 --- a/system/libs/dwoo/plugins/builtin/filters/html_format.php +++ /dev/null @@ -1,175 +0,0 @@ - - * @copyright Copyright (c) 2008, Jordi Boggiano - * @license http://dwoo.org/LICENSE Modified BSD License - * @link http://dwoo.org/ - * @version 1.0.0 - * @date 2008-10-23 - * @package Dwoo - */ -class Dwoo_Filter_html_format extends Dwoo_Filter -{ - /** - * 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