* removed never used lib - dwoo

This commit is contained in:
slawkens1 2017-10-15 21:32:21 +02:00
parent 7caca74d57
commit 3f1c638a14
112 changed files with 0 additions and 13178 deletions

View File

@ -1 +0,0 @@
deny from all

View File

@ -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 <?xml will not
conflict with php using the short_open_tag=On setting
* Complex arrays keys can be read using {$var["Long|Key*With.some)Crap"]},
however since it is really bad practice I won't spend time fixing edge
cases, which are $ and '/" characters inside the string. Those will break
it and that's it.. if you really care feel free to send a patch
* Dwoo->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 <a> 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 <?php echo "foo" ?>{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

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -1,196 +0,0 @@
<?php
/**
* Dwoo adapter for Agavi
*
* Install instructions :
* - download dwoo from dwoo.org and unzip it somewhere in your agavi app
* - add a renderer to your output_types.xml as such :
* <renderer name="dwoo" class="DwooRenderer">
* <parameter name="assigns">
* <parameter name="routing">ro</parameter>
* <parameter name="request">rq</parameter>
* <parameter name="controller">ct</parameter>
* <parameter name="user">us</parameter>
* <parameter name="translation_manager">tm</parameter>
* <parameter name="request_data">rd</parameter>
* </parameter>
* <parameter name="extract_vars">true</parameter>
* <parameter name="plugin_dir">%core.lib_dir%/dwoo_plugins</parameter>
* </renderer>
*
* - 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 <j.boggiano@seld.be>
* @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);
}
}

View File

@ -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 :
<renderer name="dwoo" class="DwooRenderer">
<parameter name="assigns">
<parameter name="routing">ro</parameter>
<parameter name="request">rq</parameter>
<parameter name="controller">ct</parameter>
<parameter name="user">us</parameter>
<parameter name="translation_manager">tm</parameter>
<parameter name="request_data">rd</parameter>
</parameter>
<parameter name="extract_vars">true</parameter>
<parameter name="plugin_dir">%core.lib_dir%/dwoo_plugins</parameter>
</renderer>
- add the renderer to app/config/autoload.xml as such :
<autoload name="DwooRenderer">%core.lib_dir%/renderer/dwoo/Dwoo/Adapter/Agavi/DwooRenderer.php</autoload>
- 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, ..)

View File

@ -1,32 +0,0 @@
<?php
/**
* <strong>Agavi specific plugin</strong>
*
* uses AgaviTranslationManager to localize a string
*
* <pre>
* * string : the string to localize
* </pre>
*
* Examples:
* <code>
* {t "Hello"}
* {t $header}
* </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 <j.boggiano@seld.be>
* @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.')';
}

View File

@ -1,54 +0,0 @@
<?php
/**
* <strong>Agavi specific plugin</strong>
*
* uses AgaviRouting to create an url
*
* <pre>
* * 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
* </pre>
*
* Examples:
* <code>
* {a url("route.name" array(param="Value", param2=$otherVal))}Here is a link{/a}
* <form action="{url}"> {* without any parameter it just returns the current url *}
* </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 <j.boggiano@seld.be>
* @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.')';
}

View File

@ -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"}

View File

@ -1,143 +0,0 @@
<?php
App::import('vendor', 'dwoo', array("file" => 'dwoo/dwooAutoload.php'));
/**
* Dwoo adapter for CakePHP
*
* Based on SmartyView by Mark John S. Buenconsejo <mjwork@simpleteq.com>
*
* 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 <mjwork@simpleteq.com>
* @author Giangi <giangi@qwerg.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @link http://dwoo.org/
* @version 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;
}
}

View File

@ -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

View File

@ -1,12 +0,0 @@
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
// The name of the directory where templates are located.
$config['template_dir'] = dirname(FCPATH) . '/../application/views/';
// The directory where compiled templates are located
$config['compileDir'] = dirname(FCPATH) . '/../compile/';
//This tells Dwoo whether or not to cache the output of the templates to the $cache_dir.
$config['caching'] = 0;
$config['cacheDir'] = dirname(FCPATH) . '/../cache/';
$config['cacheTime'] = 0;

View File

@ -1,16 +0,0 @@
<?php
class Dwoowelcome extends Controller {
function __construct()
{
parent::Controller();
}
function index()
{
$this->load->library('Dwootemplate');
$this->dwootemplate->assign('itshowlate', date('H:i:s'));
$this->dwootemplate->display('dwoowelcome.tpl');
}
}

View File

@ -1,172 +0,0 @@
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
require "dwoo/dwooAutoload.php";
/**
* Creates an template interface from Codeigniter to DWOO.
*
* 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 Stefan Verstege <stefan.verstege@newmedia.nl>
* @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;
}
}
}

View File

@ -1,31 +0,0 @@
{extends "page.tpl"}
{block "title"}
Welcome to Dwoo-ed CodeIgniter
{/block}
{block "content"}
<h1>Welcome to Dwoo-ed CodeIgniter!</h1>
<p>The page you are looking at is being generated dynamically by <b>CodeIgniter</b> in combination with the 'Smarty-killer' <b>Dwoo</b> template engine.
The page is rendered at {$itshowlate} by the Dwoo_compiler.</p>
<p>If you would like to edit this page you'll find it located at:</p>
<code>application/views/dwoowelcome.tpl</code>
<p>The corresponding controller for this page is found at:</p>
<code>application/controllers/dwoowelcome.php</code>
<p>The library for Dwoo integration can be found at:</p>
<code>application/libraries/Dwootemplate.php</code>
<p>If you are exploring Dwoo for the very first time, you should start by reading the {anchor uri='http://dwoo.org/' title='Dwoo website'}.</p>
<p>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'}.</p>
<pre>
<b>Usage</b>:
$this->load->library('Dwootemplate');
$this->dwootemplate->assign('test', 'test');
$this->dwootemplate->display('dwoowelcome.tpl');
</pre>
{/block}

View File

@ -1,57 +0,0 @@
<html>
<head>
<title>{block "title"}Here come the title{/block}</title>
<style type="text/css">
body {
background-color: #fff;
margin: 40px;
font-family: Lucida Grande, Verdana, Sans-serif;
font-size: 14px;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 16px;
font-weight: bold;
margin: 24px 0 2px 0;
padding: 5px 0 6px 0;
}
code {
font-family: Monaco, Verdana, Sans-serif;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
pre {
font-family: Monaco, Verdana, Sans-serif;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #B9BAA4;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
</style>
</head>
<body>
{block "content"}Here comes the content{/block}
</body>
</html>

View File

@ -1,96 +0,0 @@
<?php
/**
* PluginProxy class for Zend View
*
* 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 Denis Arh <denis@arh.cc>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @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. :
* <code>
* return array($this, "callbackHelper");
* // and callbackHelper would be as such:
* public function callbackHelper(array $rest=array()){}
* </code>
*
* @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 '';
}
}

View File

@ -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');

View File

@ -1,512 +0,0 @@
<?php
/**
* Dwoo adapter for ZendFramework
*
* 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 Denis Arh <denis@arh.cc>
* @author Stephan Wentz <stephan@wentz.it>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @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;
}
}

View File

@ -1,103 +0,0 @@
<?php
/**
* base class for block plugins
*
* you have to implement the <em>init()</em> 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 <j.boggiano@seld.be>
* @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 <em>process()</em> 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;
}
}

View File

@ -1,38 +0,0 @@
<?php
/**
* dwoo compilation exception class
*
* 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 <j.boggiano@seld.be>
* @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;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,250 +0,0 @@
<?php
/**
* dwoo data object, use it for complex data assignments or if you want to easily pass it
* around multiple functions to avoid passing an array by reference
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @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.'"');
}
}
}

View File

@ -1,19 +0,0 @@
<?php
/**
* main dwoo exception class
*
* 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 <j.boggiano@seld.be>
* @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
{
}

View File

@ -1,44 +0,0 @@
<?php
/**
* base class for filters
*
* 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 <j.boggiano@seld.be>
* @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);
}

View File

@ -1,26 +0,0 @@
<?php
/**
* interface that represents a compilable plugin
*
* implement this to notify the compiler that this plugin does not need to be loaded at runtime.
*
* to implement it right, you must implement <em>public static function compile(Dwoo_Compiler $compiler, $arg, $arg, ...)</em>,
* which replaces the <em>process()</em> method (that means <em>compile()</em> 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 <j.boggiano@seld.be>
* @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, ...);
}

View File

@ -1,21 +0,0 @@
<?php
/**
* interface that represents a compilable block plugin
*
* implement this to notify the compiler that this plugin does not need to be loaded at runtime.
*
* 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 <j.boggiano@seld.be>
* @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
{
}

View File

@ -1,49 +0,0 @@
<?php
/**
* interface that represents a dwoo compiler
*
* while implementing this is enough to interact with Dwoo/Dwoo_Templates, it is not
* sufficient to interact with Dwoo_Plugins, however the main purpose of creating a
* new compiler would be to interact with other/different plugins, that is why this
* interface has been left with the minimum requirements.
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @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);
}

View File

@ -1,25 +0,0 @@
<?php
/**
* interface that represents a dwoo data object
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @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();
}

View File

@ -1,24 +0,0 @@
<?php
/**
* interface that represents a block plugin that supports the else functionality
*
* the else block will enter an "hasElse" parameter inside the parameters array
* of the closest parent implementing this interface, the hasElse parameter contains
* the else output that should be appended to the block's content (see foreach or other
* block for examples)
*
* 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 <j.boggiano@seld.be>
* @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
{
}

View File

@ -1,30 +0,0 @@
<?php
/**
* interface for dwoo plugin loaders
*
* 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 <j.boggiano@seld.be>
* @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);
}

View File

@ -1,65 +0,0 @@
<?php
/**
* interface that represents a dwoo plugin proxy
*
* 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 Denis Arh <denis@arh.cc>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @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. :
* <code>
* return array($this, "callbackHelper");
* // and callbackHelper would be as such:
* public function callbackHelper(array $rest=array()){}
* </code>
*
* @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);
}

View File

@ -1,150 +0,0 @@
<?php
/**
* interface that represents a dwoo template
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @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);
}

View File

@ -1,147 +0,0 @@
<?php
/**
* handles plugin loading and caching of plugins names/paths relationships
*
* 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 <j.boggiano@seld.be>
* @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 <em>'.$class.'</em> 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 <em>'.$class.'</em> 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);
}
}
}

View File

@ -1,85 +0,0 @@
<?php
/**
* base plugin class
*
* you have to implement the <em>process()</em> 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 <j.boggiano@seld.be>
* @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);
}
}

View File

@ -1,44 +0,0 @@
<?php
/**
* base class for processors
*
* 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 <j.boggiano@seld.be>
* @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);
}

View File

@ -1,19 +0,0 @@
<?php
/**
* dwoo security exception class
*
* 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 <j.boggiano@seld.be>
* @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
{
}

View File

@ -1,199 +0,0 @@
<?php
/**
* represents the security settings of a dwoo instance, it can be passed around to different dwoo instances
*
* 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 <j.boggiano@seld.be>
* @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 <?php ?> (+ 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;
}
}

View File

@ -1,518 +0,0 @@
<?php
if (!defined('DIR_SEP')) {
define('DIR_SEP', DIRECTORY_SEPARATOR);
}
if (!defined('SMARTY_PHP_PASSTHRU')) {
define('SMARTY_PHP_PASSTHRU', 0);
define('SMARTY_PHP_QUOTE', 1);
define('SMARTY_PHP_REMOVE', 2);
define('SMARTY_PHP_ALLOW', 3);
}
if (class_exists('Dwoo_Compiler', false) === false) {
require dirname(dirname(__FILE__)) . '/Compiler.php';
}
/**
* a Smarty compatibility layer for Dwoo
*
* 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 <j.boggiano@seld.be>
* @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 {}
}

View File

@ -1,270 +0,0 @@
<?php
/**
* represents a Dwoo template contained in a file
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @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 : <em>'.$resourceId.'</em>.');
}
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 <em>'.$resourceId.'</em>');
}
}
$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).')';
}
}

View File

@ -1,497 +0,0 @@
<?php
/**
* represents a Dwoo template contained in a string
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @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);
}
}
}
}

View File

@ -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.

View File

@ -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);
}

View File

@ -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');

View File

View File

View File

@ -1,12 +0,0 @@
<?php
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Dwoo.php';
function dwooAutoload($class)
{
if (substr($class, 0, 5) === 'Dwoo_') {
include DWOO_DIRECTORY . strtr($class, '_', DIRECTORY_SEPARATOR).'.php';
}
}
spl_autoload_register('dwooAutoload');

View File

@ -1,67 +0,0 @@
<?php
/**
* Outputs a html &lt;a&gt; tag
* <pre>
* * 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
* </pre>
*
* Example :
*
* <code>
* {* 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: <a href="{$link.url}" class="{if $link.active}active{/if}">{$link.title}</a> *}
* </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 <j.boggiano@seld.be>
* @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 \'<a '.self::paramsToAttributes($p);
return $out.'>\';' . 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 </a> 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).'</a>'.substr($p['href'], -1).';'.Dwoo_Compiler::PHP_CLOSE;
}
// otherwise append
return Dwoo_Compiler::PHP_OPEN . 'echo '.$p['href'].'.\'</a>\';'.Dwoo_Compiler::PHP_CLOSE;
}
// return content
return $content . '</a>';
}
}

View File

@ -1,61 +0,0 @@
<?php
/**
* Overrides the compiler auto-escape setting within the block
* <pre>
* * 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
* </pre>
* 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 <j.boggiano@seld.be>
* @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;
}
}

View File

@ -1,34 +0,0 @@
<?php
/**
* This is used only when rendering a template that has blocks but is not extending anything,
* it doesn't do anything by itself and should not be used outside of template inheritance context,
* see {@link http://wiki.dwoo.org/index.php/TemplateInheritance} to read more about 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 <j.boggiano@seld.be>
* @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;
}
}

View File

@ -1,61 +0,0 @@
<?php
/**
* Captures all the output within this block and saves it into {$.capture.default} by default,
* or {$.capture.name} if you provide another name.
* <pre>
* * 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
* </pre>
* If the cat parameter is true, the content
* will be appended to the existing content
*
* Example :
*
* <code>
* {capture "foo"}
* Anything in here won't show, it will be saved for later use..
* {/capture}
* Output was : {$.capture.foo}
* </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 <j.boggiano@seld.be>
* @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;
}
}

View File

@ -1,65 +0,0 @@
<?php
/**
* Marks the contents of the block as dynamic. Which means that it will not be cached.
*
* 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 <j.boggiano@seld.be>
* @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 \'<dwoo:dynamic_\'.$dynamicId.\'>'.
str_replace('\'', '\\\'', $content) .
'</dwoo:dynamic_\'.$dynamicId.\'>\';'.
"\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.')>(.+?)<\/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 = '<?php '.$m[1].' ?>'.$output;
}
return $output;
}
public static function unescapePhp($match)
{
return preg_replace('{<\?php /\*'.$match[1].'\*/ echo \'(.+?)\'; \?>}s', '$1', $match[2]);
}
}

View File

@ -1,63 +0,0 @@
<?php
/**
* Generic else block, it supports all builtin optional-display blocks which are if/for/foreach/loop/with
*
* If any of those block contains an else statement, the content between {else} and {/block} (you do not
* need to close the else block) will be shown if the block's condition has no been met
*
* Example :
*
* <code>
* {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}
* </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 <j.boggiano@seld.be>
* @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 '';
}
}

View File

@ -1,60 +0,0 @@
<?php
/**
* Acts as a php elseif block, allowing you to add one more condition
* if the previous one(s) didn't match. See the {if} plugin for syntax details
*
* 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 <j.boggiano@seld.be>
* @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 '';
}
}

View File

@ -1,147 +0,0 @@
<?php
/**
* Similar to the php for block
* <pre>
* * 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
* </pre>
* 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 <j.boggiano@seld.be>
* @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 <em>to</em> parameter when using a numerical <em>from</em>\'); }'.
"\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;
}
}

View File

@ -1,152 +0,0 @@
<?php
/**
* Similar to the php foreach block, loops over an array
*
* Note that if you don't provide the item parameter, the key will act as item
* <pre>
* * 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
* </pre>
* Example :
*
* <code>
* {foreach $array val}
* {$val.something}
* {/foreach}
* </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 <j.boggiano@seld.be>
* @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 <em>item</em> parameter missing');
}
$name = $params['name'];
if (substr($val, 0, 1) !== '"' && substr($val, 0, 1) !== '\'') {
throw new Dwoo_Compilation_Exception($compiler, 'Foreach <em>item</em> parameter must be of type string');
}
if (isset($key) && substr($val, 0, 1) !== '"' && substr($val, 0, 1) !== '\'') {
throw new Dwoo_Compilation_Exception($compiler, 'Foreach <em>key</em> 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;
}
}

View File

@ -1,43 +0,0 @@
<?php
/**
* This plugin serves as a {else} block specifically for the {foreach} plugin.
*
* 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 <j.boggiano@seld.be>
* @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 '';
}
}

View File

@ -1,43 +0,0 @@
<?php
/**
* This plugin serves as a {else} block specifically for the {for} plugin.
*
* 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 <j.boggiano@seld.be>
* @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 '';
}
}

View File

@ -1,180 +0,0 @@
<?php
/**
* Conditional block, the syntax is very similar to the php one, allowing () || && and
* other php operators. Additional operators and their equivalent php syntax are as follow :
*
* eq -> ==
* 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 <j.boggiano@seld.be>
* @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;
}
}

View File

@ -1,128 +0,0 @@
<?php
/**
* Loops over an array and moves the scope into each value, allowing for shorter loop constructs
*
* Note that to access the array key within a loop block, you have to use the {$_key} variable,
* you can not specify it yourself.
* <pre>
* * 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
* </pre>
* Example :
*
* instead of a foreach block such as :
*
* <code>
* {foreach $variable value}
* {$value.foo} {$value.bar}
* {/foreach}
* </code>
*
* you can do :
*
* <code>
* {loop $variable}
* {$foo} {$bar}
* {/loop}
* </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 <j.boggiano@seld.be>
* @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;
}
}

View File

@ -1,131 +0,0 @@
<?php
/**
* Compatibility plugin for smarty templates, do not use otherwise, this is deprecated.
*
* 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 <j.boggiano@seld.be>
* @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;
}
}

View File

@ -1,59 +0,0 @@
<?php
/**
* Smarty compatibility layer for block plugins, this is used internally and you should not call 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 <j.boggiano@seld.be>
* @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'];
}
}

View File

@ -1,50 +0,0 @@
<?php
/**
* Strips the spaces at the beginning and end of each line and also the line breaks
* <pre>
* * mode : sets the content being stripped, available mode are 'default' or 'js'
* for javascript, which strips the comments to prevent syntax errors
* </pre>
*
* 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 <j.boggiano@seld.be>
* @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('#(?<!:)//\s[^\r\n]*|/\*.*?\*/#s','', $content);
case 'default':
default:
}
$content = preg_replace(array("/\n/","/\r/",'/(<\?(?:php)?|<%)\s*/'), array('','','$1 '), preg_replace('#^\s*(.+?)\s*$#m', '$1', $content));
return $content;
}
}

View File

@ -1,88 +0,0 @@
<?php
/**
* Defines a sub-template that can then be called (even recursively) with the defined arguments
* <pre>
* * name : template name
* * rest : list of arguments and optional default values
* </pre>
* 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 <j.boggiano@seld.be>
* @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);
}
}

View File

@ -1,94 +0,0 @@
<?php
/**
* Formats a string to the given format, you can wrap lines at a certain
* length and indent them
* <pre>
* * 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
* </pre>
* 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 <j.boggiano@seld.be>
* @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 = '<br />';
$indent_char = $indent_char == "\t" ? '&nbsp;&nbsp;&nbsp;&nbsp;':'&nbsp;';
break;
}
$this->wrap = (int) $wrap;
$this->wrapChar = (string) $wrap_char;
$this->wrapCut = (bool) $wrap_cut;
$this->indent = (int) $indent;
$this->indChar = (string) $indent_char;
$this->indFirst = (int) $indent_first + $this->indent;
$this->assign = (string) $assign;
}
public function process()
{
// gets paragraphs
$pgs = explode("\n", str_replace(array("\r\n", "\r"), "\n", $this->buffer));
while (list($i,) = each($pgs)) {
if (empty($pgs[$i])) {
continue;
}
// removes line breaks and extensive white space
$pgs[$i] = preg_replace(array('#\s+#', '#^\s*(.+?)\s*$#m'), array(' ', '$1'), str_replace("\n", '', $pgs[$i]));
// wordwraps + indents lines
$pgs[$i] = str_repeat($this->indChar, $this->indFirst) .
wordwrap(
$pgs[$i],
max($this->wrap - $this->indent, 1),
$this->wrapChar . str_repeat($this->indChar, $this->indent),
$this->wrapCut
);
}
if ($this->assign !== '') {
$this->dwoo->assignInScope(implode($this->wrapChar . $this->wrapChar, $pgs), $this->assign);
} else {
return implode($this->wrapChar . $this->wrapChar, $pgs);
}
}
}

View File

@ -1,32 +0,0 @@
<?php
/**
* Internal plugin used to wrap the template output, do not use in your templates as it will break them
*
* 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 <j.boggiano@seld.be>
* @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();';
}
}

View File

@ -1,76 +0,0 @@
<?php
/**
* Moves the scope down into the provided variable, allowing you to use shorter
* variable names if you repeatedly access values into a single array
*
* The with block won't display anything at all if the provided scope is empty,
* so in effect it acts as {if $var}*content*{/if}
* <pre>
* * var : the variable name to move into
* </pre>
* Example :
*
* instead of the following :
*
* <code>
* {if $long.boring.prefix}
* {$long.boring.prefix.val} - {$long.boring.prefix.secondVal} - {$long.boring.prefix.thirdVal}
* {/if}
* </code>
*
* you can use :
*
* <code>
* {with $long.boring.prefix}
* {$val} - {$secondVal} - {$thirdVal}
* {/with}
* </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 <j.boggiano@seld.be>
* @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;
}
}

View File

@ -1,43 +0,0 @@
<?php
/**
* This plugin serves as a {else} block specifically for the {with} plugin.
*
* 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 <j.boggiano@seld.be>
* @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 '';
}
}

View File

@ -1,175 +0,0 @@
<?php
/**
* Formats any html output (must be valid xml where every tag opened is closed)
* using a single tab for indenting. 'pre' and other whitespace sensitive
* tags should not be affected.
*
* It is not recommended to use this on every template if you render multiple
* templates per page, you should only use it once on the main page template so that
* everything is formatted in one pass.
*
* 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 <j.boggiano@seld.be>
* @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 <textarea>, <code> and <pre> tags that must be kept intact.
* Those tags must however contain only htmlentities-escaped text for everything to work properly.
* Inline tags are presented on a single line with their content
*
* @param Dwoo $dwoo the dwoo instance rendering this
* @param string $input the xhtml to format
* @return string formatted xhtml
*/
public function process($input)
{
self::$tabCount = -1;
// auto indent all but textareas & pre (or we have weird tabs inside)
$input = preg_replace_callback("#(<[^>]+>)(\s*)([^<]*)#", array('self', 'tagDispatcher'), $input);
return $input;
}
/**
* helper function for format()'s preg_replace call
*
* @param array $input array of matches (1=>tag, 2=>whitespace(optional), 3=>additional non-html content)
* @return string the indented tag
*/
protected static function tagDispatcher($input)
{
// textarea, pre, code tags and comments are to be left alone to avoid any non-wanted whitespace inside them so it just outputs them as they were
if (substr($input[1],0,9) == "<textarea" || substr($input[1],0,4) == "<pre" || substr($input[1],0,5) == "<code" || substr($input[1],0,4) == "<!--" || substr($input[1],0,9) == "<![CDATA[") {
return $input[1] . $input[3];
}
// closing textarea, code and pre tags and self-closed tags (i.e. <br />) are printed as singleTags because we didn't use openTag for the formers and the latter is a single tag
if (substr($input[1],0,10) == "</textarea" || substr($input[1],0,5) == "</pre" || substr($input[1],0,6) == "</code" || substr($input[1],-2) == "/>") {
return self::singleTag($input[1],$input[3],$input[2]);
}
// it's the closing tag
if ($input[0][1]=="/"){
return self::closeTag($input[1],$input[3],$input[2]);
}
// opening tag
return self::openTag($input[1],$input[3],$input[2]);
}
/**
* returns an open tag and adds a tab into the auto indenting
*
* @param string $tag content of the tag
* @param string $add additional data (anything before the following tag)
* @param string $whitespace white space between the tag and the additional data
* @return string
*/
protected static function openTag($tag,$add,$whitespace)
{
$tabs = str_pad('',self::$tabCount++,"\t");
if (preg_match('#^<(a|label|option|textarea|h1|h2|h3|h4|h5|h6|strong|b|em|i|abbr|acronym|cite|span|sub|sup|u|s|title)(?: [^>]*|)>#', $tag)) {
// if it's one of those tag it's inline so it does not require a leading line break
$result = $tag . $whitespace . str_replace("\n","\n".$tabs,$add);
} elseif (substr($tag,0,9) == '<!DOCTYPE') {
// it's the doctype declaration so no line break here either
$result = $tabs . $tag;
} else {
// normal block tag
$result = "\n".$tabs . $tag;
if (!empty($add)) {
$result .= "\n".$tabs."\t".str_replace("\n","\n\t".$tabs,$add);
}
}
self::$lastCallAdd = $add;
return $result;
}
/**
* returns a closing tag and removes a tab from the auto indenting
*
* @param string $tag content of the tag
* @param string $add additional data (anything before the following tag)
* @param string $whitespace white space between the tag and the additional data
* @return string
*/
protected static function closeTag($tag,$add,$whitespace)
{
$tabs = str_pad('',--self::$tabCount,"\t");
// if it's one of those tag it's inline so it does not require a leading line break
if (preg_match('#^</(a|label|option|textarea|h1|h2|h3|h4|h5|h6|strong|b|em|i|abbr|acronym|cite|span|sub|sup|u|s|title)>#', $tag)) {
$result = $tag . $whitespace . str_replace("\n","\n".$tabs,$add);
} else {
$result = "\n".$tabs.$tag;
if (!empty($add)) {
$result .= "\n".$tabs."\t".str_replace("\n","\n\t".$tabs,$add);
}
}
self::$lastCallAdd = $add;
return $result;
}
/**
* returns a single tag with auto indenting
*
* @param string $tag content of the tag
* @param string $add additional data (anything before the following tag)
* @return string
*/
protected static function singleTag($tag,$add,$whitespace)
{
$tabs = str_pad('',self::$tabCount,"\t");
// if it's img, br it's inline so it does not require a leading line break
// if it's a closing textarea, code or pre tag, it does not require a leading line break either or it creates whitespace at the end of those blocks
if (preg_match('#^<(img|br|/textarea|/pre|/code)(?: [^>]*|)>#', $tag)) {
$result = $tag.$whitespace;
if (!empty($add)) {
$result .= str_replace("\n","\n".$tabs,$add);
}
} else {
$result = "\n".$tabs.$tag;
if (!empty($add)) {
$result .= "\n".$tabs.str_replace("\n","\n".$tabs,$add);
}
}
self::$lastCallAdd = $add;
return $result;
}
}

View File

@ -1,23 +0,0 @@
<?php
/**
* Assigns a value to a variable
* <pre>
* * value : the value that you want to save
* * var : the variable name (without the leading $)
* </pre>
* 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 <j.boggiano@seld.be>
* @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_assign_compile(Dwoo_Compiler $compiler, $value, $var)
{
return '$this->assignInScope('.$value.', '.$var.')';
}

View File

@ -1,38 +0,0 @@
<?php
/**
* Capitalizes the first letter of each word
* <pre>
* * value : the string to capitalize
* * numwords : if true, the words containing numbers are capitalized as well
* </pre>
* 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 <j.boggiano@seld.be>
* @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
*/
function Dwoo_Plugin_capitalize(Dwoo $dwoo, $value, $numwords=false)
{
if ($numwords || preg_match('#^[^0-9]+$#',$value))
{
return mb_convert_case((string) $value,MB_CASE_TITLE, $dwoo->getCharset());
} else {
$bits = explode(' ', (string) $value);
$out = '';
while (list(,$v) = each($bits)) {
if (preg_match('#^[^0-9]+$#', $v)) {
$out .= ' '.mb_convert_case($v, MB_CASE_TITLE, $dwoo->getCharset());
} else {
$out .= ' '.$v;
}
}
return substr($out, 1);
}
}

View File

@ -1,22 +0,0 @@
<?php
/**
* Concatenates any number of variables or strings fed into it
* <pre>
* * rest : two or more strings that will be merged into one
* </pre>
* 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 <j.boggiano@seld.be>
* @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_cat_compile(Dwoo_Compiler $compiler, $value, array $rest)
{
return '('.$value.').('.implode(').(', $rest).')';
}

View File

@ -1,27 +0,0 @@
<?php
/**
* Counts the characters in a string
* <pre>
* * value : the string to process
* * count_spaces : if true, the white-space characters are counted as well
* </pre>
* 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 <j.boggiano@seld.be>
* @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_count_characters_compile(Dwoo_Compiler $compiler, $value, $count_spaces=false)
{
if ($count_spaces==='false') {
return 'preg_match_all(\'#[^\s\pZ]#u\', '.$value.', $tmp)';
} else {
return 'mb_strlen('.$value.', $this->charset)';
}
}

View File

@ -1,22 +0,0 @@
<?php
/**
* Counts the paragraphs in a string
* <pre>
* * value : the string to process
* </pre>
* 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 <j.boggiano@seld.be>
* @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_count_paragraphs_compile(Dwoo_Compiler $compiler, $value)
{
return '(preg_match_all(\'#[\r\n]+#\', '.$value.', $tmp)+1)';
}

View File

@ -1,22 +0,0 @@
<?php
/**
* Counts the sentences in a string
* <pre>
* * value : the string to process
* </pre>
* 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 <j.boggiano@seld.be>
* @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_count_sentences_compile(Dwoo_Compiler $compiler, $value)
{
return "preg_match_all('#[\w\pL]\.(?![\w\pL])#u', $value, \$tmp)";
}

View File

@ -1,22 +0,0 @@
<?php
/**
* Counts the words in a string
* <pre>
* * value : the string to process
* </pre>
* 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 <j.boggiano@seld.be>
* @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_count_words_compile(Dwoo_Compiler $compiler, $value)
{
return 'preg_match_all(strcasecmp($this->charset, \'utf-8\')===0 ? \'#[\w\pL]+#u\' : \'#\w+#\', '.$value.', $tmp)';
}

View File

@ -1,76 +0,0 @@
<?php
/**
* Initiates a counter that is incremented every time you call it
* <pre>
* * name : the counter name, define it if you want to have multiple concurrent counters
* * start : the start value, if it's set, it will reset the counter to this value, defaults to 1
* * skip : the value to add to the counter at each call, defaults to 1
* * direction : "up" (default) or "down" to define whether the counter increments or decrements
* * print : if false, the counter will not output the current count, defaults to true
* * assign : if set, the counter is saved into the given variable and does not output anything, overriding the print parameter
* </pre>
* 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 <j.boggiano@seld.be>
* @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_counter extends Dwoo_Plugin
{
protected $counters = array();
public function process($name = 'default', $start = null, $skip = null, $direction = null, $print = null, $assign = null)
{
// init counter
if (!isset($this->counters[$name])) {
$this->counters[$name] = array
(
'count' => $start===null ? 1 : (int) $start,
'skip' => $skip===null ? 1 : (int) $skip,
'print' => $print===null ? true : (bool) $print,
'assign' => $assign===null ? null : (string) $assign,
'direction' => strtolower($direction)==='down' ? -1 : 1,
);
}
// increment
else
{
// override setting if present
if ($skip !== null) {
$this->counters[$name]['skip'] = (int) $skip;
}
if ($direction !== null) {
$this->counters[$name]['direction'] = strtolower($direction)==='down' ? -1 : 1;
}
if ($print !== null) {
$this->counters[$name]['print'] = (bool) $print;
}
if ($assign !== null) {
$this->counters[$name]['assign'] = (string) $assign;
}
if ($start !== null) {
$this->counters[$name]['count'] = (int) $start;
} else {
$this->counters[$name]['count'] += ($this->counters[$name]['skip'] * $this->counters[$name]['direction']);
}
}
$out = $this->counters[$name]['count'];
if ($this->counters[$name]['assign'] !== null) {
$this->dwoo->assignInScope($out, $this->counters[$name]['assign']);
} elseif ($this->counters[$name]['print'] === true) {
return $out;
}
}
}

View File

@ -1,68 +0,0 @@
<?php
/**
* Cycles between several values and returns one of them on each call
* <pre>
* * name : the cycler name, specify if you need to have multiple concurrent cycles running
* * values : an array of values or a string of values delimited by $delimiter
* * print : if false, the pointer will go to the next one but not print anything
* * advance : if false, the pointer will not advance to the next value
* * delimiter : the delimiter used to split values if they are provided as a string
* * assign : if set, the value is saved in that variable instead of being output
* * reset : if true, the pointer is reset to the first value
* </pre>
* 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 <j.boggiano@seld.be>
* @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_cycle extends Dwoo_Plugin
{
protected $cycles = array();
public function process($name = 'default', $values = null, $print = true, $advance = true, $delimiter = ',', $assign = null, $reset = false)
{
if ($values !== null) {
if (is_string($values)) {
$values = explode($delimiter, $values);
}
if (!isset($this->cycles[$name]) || $this->cycles[$name]['values'] !== $values) {
$this->cycles[$name]['index'] = 0;
}
$this->cycles[$name]['values'] = array_values($values);
} elseif (isset($this->cycles[$name])) {
$values = $this->cycles[$name]['values'];
}
if ($reset) {
$this->cycles[$name]['index'] = 0;
}
if ($print) {
$out = $values[$this->cycles[$name]['index']];
} else {
$out = null;
}
if ($advance) {
if ($this->cycles[$name]['index'] >= count($values)-1) {
$this->cycles[$name]['index'] = 0;
} else {
$this->cycles[$name]['index']++;
}
}
if ($assign === null) {
return $out;
}
$this->dwoo->assignInScope($out, $assign);
}
}

View File

@ -1,54 +0,0 @@
<?php
/**
* Formats a date
* <pre>
* * value : the date, as a unix timestamp, mysql datetime or whatever strtotime() can parse
* * format : output format, see {@link http://php.net/strftime} for details
* * default : a default timestamp value, if the first one is empty
* </pre>
* 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 <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://dwoo.org/LICENSE Modified BSD License
* @link http://dwoo.org/
* @version 1.0.1
* @date 2008-12-24
* @package Dwoo
*/
function Dwoo_Plugin_date_format(Dwoo $dwoo, $value, $format='%b %e, %Y', $default=null)
{
if (!empty($value)) {
// convert if it's not a valid unix timestamp
if (preg_match('#^-?\d{1,10}$#', $value)===0) {
$value = strtotime($value);
}
} elseif (!empty($default)) {
// convert if it's not a valid unix timestamp
if (preg_match('#^-?\d{1,10}$#', $default)===0) {
$value = strtotime($default);
} else {
$value = $default;
}
} else {
return '';
}
// Credits for that windows compat block to Monte Ohrt who made smarty's date_format plugin
if (DIRECTORY_SEPARATOR == '\\') {
$_win_from = array('%D', '%h', '%n', '%r', '%R', '%t', '%T');
$_win_to = array('%m/%d/%y', '%b', "\n", '%I:%M:%S %p', '%H:%M', "\t", '%H:%M:%S');
if (strpos($format, '%e') !== false) {
$_win_from[] = '%e';
$_win_to[] = sprintf('%\' 2d', date('j', $value));
}
if (strpos($format, '%l') !== false) {
$_win_from[] = '%l';
$_win_to[] = sprintf('%\' 2d', date('h', $value));
}
$format = str_replace($_win_from, $_win_to, $format);
}
return strftime($format, $value);
}

View File

@ -1,23 +0,0 @@
<?php
/**
* Returns a variable or a default value if it's empty
* <pre>
* * value : the variable to check
* * default : fallback value if the first one is empty
* </pre>
* 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 <j.boggiano@seld.be>
* @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_default_compile(Dwoo_Compiler $compiler, $value, $default='')
{
return '(($tmp = '.$value.')===null||$tmp===\'\' ? '.$default.' : $tmp)';
}

View File

@ -1,173 +0,0 @@
<?php
/**
* Dumps values of the given variable, or the entire data if nothing provided
* <pre>
* * var : the variable to display
* * show_methods : if set to true, the public methods of any object encountered are also displayed
* </pre>
* 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 <j.boggiano@seld.be>
* @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_dump extends Dwoo_Plugin
{
protected $outputObjects;
protected $outputMethods;
public function process($var = '$', $show_methods = false)
{
$this->outputMethods = $show_methods;
if ($var === '$') {
$var = $this->dwoo->getData();
$out = '<div style="background:#aaa; padding:5px; margin:5px; color:#000;">data';
} else {
$out = '<div style="background:#aaa; padding:5px; margin:5px; color:#000;">dump';
}
$this->outputObjects = array();
if (!is_array($var)) {
if (is_object($var)) {
return $this->exportObj('', $var);
} else {
return $this->exportVar('', $var);
}
}
$scope = $this->dwoo->getScope();
if ($var === $scope) {
$out .= ' (current scope): <div style="background:#ccc;">';
} else {
$out .= ':<div style="padding-left:20px;">';
}
$out .= $this->export($var, $scope);
return $out .'</div></div>';
}
protected function export($var, $scope)
{
$out = '';
foreach ($var as $i=>$v) {
if (is_array($v) || (is_object($v) && $v instanceof Iterator)) {
$out .= $i.' ('.(is_array($v) ? 'array':'object: '.get_class($v)).')';
if ($v===$scope) {
$out .= ' (current scope):<div style="background:#ccc;padding-left:20px;">'.$this->export($v, $scope).'</div>';
} else {
$out .= ':<div style="padding-left:20px;">'.$this->export($v, $scope).'</div>';
}
} elseif (is_object($v)) {
$out .= $this->exportObj($i.' (object: '.get_class($v).'):', $v);
} else {
$out .= $this->exportVar($i.' = ', $v);
}
}
return $out;
}
protected function exportVar($i, $v)
{
if (is_string($v) || is_bool($v) || is_numeric($v)) {
return $i.htmlentities(var_export($v, true)).'<br />';
} elseif (is_null($v)) {
return $i.'null<br />';
} elseif (is_resource($v)) {
return $i.'resource('.get_resource_type($v).')<br />';
} else {
return $i.htmlentities(var_export($v, true)).'<br />';
}
}
protected function exportObj($i, $obj)
{
if (array_search($obj, $this->outputObjects, true) !== false) {
return $i . ' [recursion, skipped]<br />';
}
$this->outputObjects[] = $obj;
$list = (array) $obj;
$protectedLength = strlen(get_class($obj)) + 2;
$out = array();
if ($this->outputMethods) {
$ref = new ReflectionObject($obj);
foreach ($ref->getMethods() as $method) {
if (!$method->isPublic()) {
continue;
}
if (empty($out['method'])) {
$out['method'] = '';
}
$params = array();
foreach ($method->getParameters() as $param) {
$params[] = ($param->isPassedByReference() ? '&':'') . '$'.$param->getName() . ($param->isOptional() ? ' = '.var_export($param->getDefaultValue(), true) : '');
}
$out['method'] .= '(method) ' . $method->getName() .'('.implode(', ', $params).')<br />';
}
}
foreach ($list as $attributeName => $attributeValue) {
if(property_exists($obj, $attributeName)) {
$key = 'public';
} elseif(substr($attributeName, 0, 3) === "\0*\0") {
$key = 'protected';
$attributeName = substr($attributeName, 3);
} else {
$key = 'private';
$attributeName = substr($attributeName, $protectedLength);
}
if (empty($out[$key])) {
$out[$key] = '';
}
$out[$key] .= '('.$key.') ';
if (is_array($attributeValue)) {
$out[$key] .= $attributeName.' (array):<br />
<div style="padding-left:20px;">'.$this->export($attributeValue, false).'</div>';
} elseif (is_object($attributeValue)) {
$out[$key] .= $this->exportObj($attributeName.' (object: '.get_class($attributeValue).'):', $attributeValue);
} else {
$out[$key] .= $this->exportVar($attributeName.' = ', $attributeValue);
}
}
$return = $i . '<br /><div style="padding-left:20px;">';
if (!empty($out['method'])) {
$return .= $out['method'];
}
if (!empty($out['public'])) {
$return .= $out['public'];
}
if (!empty($out['protected'])) {
$return .= $out['protected'];
}
if (!empty($out['private'])) {
$return .= $out['private'];
}
return $return . '</div>';
}
}

View File

@ -1,20 +0,0 @@
<?php
/**
* Returns the correct end of line character(s) for the current operating system
*
* 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 <j.boggiano@seld.be>
* @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_eol_compile(Dwoo_Compiler $compiler)
{
return 'PHP_EOL';
}

View File

@ -1,61 +0,0 @@
<?php
/**
* Applies various escaping schemes on the given string
* <pre>
* * value : the string to process
* * format : escaping format to use, valid formats are : html, htmlall, url, urlpathinfo, quotes, hex, hexentity, javascript and mail
* * charset : character set to use for the conversion (applies to some formats only), defaults to the current Dwoo charset
* </pre>
* 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 <j.boggiano@seld.be>
* @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_escape(Dwoo $dwoo, $value='', $format='html', $charset=null)
{
if ($charset === null) {
$charset = $dwoo->getCharset();
}
switch($format)
{
case 'html':
return htmlspecialchars((string) $value, ENT_QUOTES, $charset);
case 'htmlall':
return htmlentities((string) $value, ENT_QUOTES, $charset);
case 'url':
return rawurlencode((string) $value);
case 'urlpathinfo':
return str_replace('%2F', '/', rawurlencode((string) $value));
case 'quotes':
return preg_replace("#(?<!\\\\)'#", "\\'", (string) $value);
case 'hex':
$out = '';
$cnt = strlen((string) $value);
for ($i=0; $i < $cnt; $i++) {
$out .= '%' . bin2hex((string) $value[$i]);
}
return $out;
case 'hexentity':
$out = '';
$cnt = strlen((string) $value);
for ($i=0; $i < $cnt; $i++)
$out .= '&#x' . bin2hex((string) $value[$i]) . ';';
return $out;
case 'javascript':
return strtr((string) $value, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/'));
case 'mail':
return str_replace(array('@', '.'), array('&nbsp;(AT)&nbsp;', '&nbsp;(DOT)&nbsp;'), (string) $value);
default:
return $dwoo->triggerError('Escape\'s format argument must be one of : html, htmlall, url, urlpathinfo, hex, hexentity, javascript or mail, "'.$format.'" given.', E_USER_WARNING);
}
}

View File

@ -1,41 +0,0 @@
<?php
/**
* Evaluates the given string as if it was a template
*
* Although this plugin is kind of optimized and will
* not recompile your string each time, it is still not
* a good practice to use it. If you want to have templates
* stored in a database or something you should probably use
* the Dwoo_Template_String class or make another class that
* extends it
* <pre>
* * var : the string to use as a template
* * assign : if set, the output of the template will be saved in this variable instead of being output
* </pre>
* 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 <j.boggiano@seld.be>
* @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_eval(Dwoo $dwoo, $var, $assign = null)
{
if ($var == '') {
return;
}
$tpl = new Dwoo_Template_String($var);
$out = $dwoo->get($tpl, $dwoo->readVar('_parent'));
if ($assign !== null) {
$dwoo->assignInScope($out, $assign);
} else {
return $out;
}
}

View File

@ -1,134 +0,0 @@
<?php
/**
* Extends another template, read more about template inheritance at {@link http://wiki.dwoo.org/index.php/TemplateInheritance}
* <pre>
* * file : the template to extend
* </pre>
* 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 <j.boggiano@seld.be>
* @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_extends extends Dwoo_Plugin implements Dwoo_ICompilable
{
protected static $childSource;
protected static $l;
protected static $r;
protected static $lastReplacement;
public static function compile(Dwoo_Compiler $compiler, $file)
{
list($l, $r) = $compiler->getDelimiters();
self::$l = preg_quote($l,'/');
self::$r = preg_quote($r,'/');
if ($compiler->getLooseOpeningHandling()) {
self::$l .= '\s*';
self::$r = '\s*'.self::$r;
}
$inheritanceTree = array(array('source'=>$compiler->getTemplateSource()));
$curPath = dirname($compiler->getDwoo()->getTemplate()->getResourceIdentifier()) . DIRECTORY_SEPARATOR;
$curTpl = $compiler->getDwoo()->getTemplate();
while (!empty($file)) {
if ($file === '""' || $file === "''" || (substr($file, 0, 1) !== '"' && substr($file, 0, 1) !== '\'')) {
throw new Dwoo_Compilation_Exception($compiler, 'Extends : The file name must be a non-empty string');
return;
}
if (preg_match('#^["\']([a-z]{2,}):(.*?)["\']$#i', $file, $m)) {
// resource:identifier given, extract them
$resource = $m[1];
$identifier = $m[2];
} else {
// get the current template's resource
$resource = $curTpl->getResourceName();
$identifier = substr($file, 1, -1);
}
try {
$parent = $compiler->getDwoo()->templateFactory($resource, $identifier, null, null, null, $curTpl);
} catch (Dwoo_Security_Exception $e) {
throw new Dwoo_Compilation_Exception($compiler, 'Extends : Security restriction : '.$e->getMessage());
} catch (Dwoo_Exception $e) {
throw new Dwoo_Compilation_Exception($compiler, 'Extends : '.$e->getMessage());
}
if ($parent === null) {
throw new Dwoo_Compilation_Exception($compiler, 'Extends : Resource "'.$resource.':'.$identifier.'" not found.');
} elseif ($parent === false) {
throw new Dwoo_Compilation_Exception($compiler, 'Extends : Resource "'.$resource.'" does not support extends.');
}
$curTpl = $parent;
$newParent = array('source'=>$parent->getSource(), 'resource'=>$resource, 'identifier'=>$parent->getResourceIdentifier(), 'uid'=>$parent->getUid());
if (array_search($newParent, $inheritanceTree, true) !== false) {
throw new Dwoo_Compilation_Exception($compiler, 'Extends : Recursive template inheritance detected');
}
$inheritanceTree[] = $newParent;
if (preg_match('/^'.self::$l.'extends\s+(?:file=)?\s*((["\']).+?\2|\S+?)'.self::$r.'/i', $parent->getSource(), $match)) {
$curPath = dirname($identifier) . DIRECTORY_SEPARATOR;
if (isset($match[2]) && $match[2] == '"') {
$file = '"'.str_replace('"', '\\"', substr($match[1], 1, -1)).'"';
} elseif (isset($match[2]) && $match[2] == "'") {
$file = '"'.substr($match[1], 1, -1).'"';
} else {
$file = '"'.$match[1].'"';
}
} else {
$file = false;
}
}
while (true) {
$parent = array_pop($inheritanceTree);
$child = end($inheritanceTree);
self::$childSource = $child['source'];
self::$lastReplacement = count($inheritanceTree) === 1;
if (!isset($newSource)) {
$newSource = $parent['source'];
}
// TODO parse blocks tree for child source and new source
// TODO replace blocks that are found in the child and in the parent recursively
$newSource = preg_replace_callback('/'.self::$l.'block (["\']?)(.+?)\1'.self::$r.'(?:\r?\n?)(.*?)(?:\r?\n?)'.self::$l.'\/block'.self::$r.'/is', array('Dwoo_Plugin_extends', 'replaceBlock'), $newSource);
$newSource = $l.'do extendsCheck("'.$parent['resource'].':'.$parent['identifier'].'")'.$r.$newSource;
if (self::$lastReplacement) {
break;
}
}
$compiler->setTemplateSource($newSource);
$compiler->recompile();
}
protected static function replaceBlock(array $matches)
{
if (preg_match('/'.self::$l.'block (["\']?)'.preg_quote($matches[2],'/').'\1'.self::$r.'(?:\r?\n?)(.*?)(?:\r?\n?)'.self::$l.'\/block'.self::$r.'/is', self::$childSource, $override)) {
$l = stripslashes(self::$l);
$r = stripslashes(self::$r);
if (self::$lastReplacement) {
return preg_replace('/'.self::$l.'\$dwoo\.parent'.self::$r.'/is', $matches[3], $override[2]);
} else {
return $l.'block '.$matches[1].$matches[2].$matches[1].$r.preg_replace('/'.self::$l.'\$dwoo\.parent'.self::$r.'/is', $matches[3], $override[2]).$l.'/block'.$r;
}
} else {
if (self::$lastReplacement) {
return $matches[3];
} else {
return $matches[0];
}
}
}
}

View File

@ -1,52 +0,0 @@
<?php
/**
* Checks whether an extended file has been modified, and if so recompiles the current template. This is for internal use only, do not use.
*
* 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 <j.boggiano@seld.be>
* @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
*/
function Dwoo_Plugin_extendsCheck_compile(Dwoo_Compiler $compiler, $file)
{
preg_match('#^["\']([a-z]{2,}):(.*?)["\']$#i', $file, $m);
$resource = $m[1];
$identifier = $m[2];
$tpl = $compiler->getDwoo()->templateFactory($resource, $identifier);
if ($tpl === null) {
throw new Dwoo_Compilation_Exception($compiler, 'Load Templates : Resource "'.$resource.':'.$identifier.'" not found.');
} elseif ($tpl === false) {
throw new Dwoo_Compilation_Exception($compiler, 'Load Templates : Resource "'.$resource.'" does not support includes.');
}
$out = '\'\';// checking for modification in '.$resource.':'.$identifier."\r\n";
$modCheck = $tpl->getIsModifiedCode();
if ($modCheck) {
$out .= 'if (!('.$modCheck.')) { ob_end_clean(); return false; }';
} else {
$out .= 'try {
$tpl = $this->templateFactory("'.$resource.'", "'.$identifier.'");
} catch (Dwoo_Exception $e) {
$this->triggerError(\'Load Templates : Resource <em>'.$resource.'</em> was not added to Dwoo, can not extend <em>'.$identifier.'</em>\', E_USER_WARNING);
}
if ($tpl === null)
$this->triggerError(\'Load Templates : Resource "'.$resource.':'.$identifier.'" was not found.\', E_USER_WARNING);
elseif ($tpl === false)
$this->triggerError(\'Load Templates : Resource "'.$resource.'" does not support extends.\', E_USER_WARNING);
if ($tpl->getUid() != "'.$tpl->getUid().'") { ob_end_clean(); return false; }';
}
return $out;
}

View File

@ -1,50 +0,0 @@
<?php
/**
* Reads a file
* <pre>
* * file : path or URI of the file to read (however reading from another website is not recommended for performance reasons)
* * assign : if set, the file will be saved in this variable instead of being output
* </pre>
* 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 <j.boggiano@seld.be>
* @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
*/
function Dwoo_Plugin_fetch(Dwoo $dwoo, $file, $assign = null)
{
if ($file === '') {
return;
}
if ($policy = $dwoo->getSecurityPolicy()) {
while (true) {
if (preg_match('{^([a-z]+?)://}i', $file)) {
return $dwoo->triggerError('The security policy prevents you to read files from external sources.', E_USER_WARNING);
}
$file = realpath($file);
$dirs = $policy->getAllowedDirectories();
foreach ($dirs as $dir=>$dummy) {
if (strpos($file, $dir) === 0) {
break 2;
}
}
return $dwoo->triggerError('The security policy prevents you to read <em>'.$file.'</em>', E_USER_WARNING);
}
}
$file = str_replace(array("\t", "\n", "\r"), array('\\t', '\\n', '\\r'), $file);
$out = file_get_contents($file);
if ($assign === null) {
return $out;
}
$dwoo->assignInScope($out, $assign);
}

View File

@ -1,77 +0,0 @@
<?php
/**
* Inserts another template into the current one
* <pre>
* * file : the resource name of the template
* * cache_time : cache length in seconds
* * cache_id : cache identifier for the included template
* * compile_id : compilation identifier for the included template
* * data : data to feed into the included template, it can be any array and will default to $_root (the current data)
* * assign : if set, the output of the included template will be saved in this variable instead of being output
* * rest : any additional parameter/value provided will be added to the data array
* </pre>
* 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 <j.boggiano@seld.be>
* @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
*/
function Dwoo_Plugin_include(Dwoo $dwoo, $file, $cache_time = null, $cache_id = null, $compile_id = null, $data = '_root', $assign = null, array $rest = array())
{
if ($file === '') {
return;
}
if (preg_match('#^([a-z]{2,}):(.*)$#i', $file, $m)) {
// resource:identifier given, extract them
$resource = $m[1];
$identifier = $m[2];
} else {
// get the current template's resource
$resource = $dwoo->getTemplate()->getResourceName();
$identifier = $file;
}
try {
if (!is_numeric($cache_time)) {
$cache_time = null;
}
$include = $dwoo->templateFactory($resource, $identifier, $cache_time, $cache_id, $compile_id);
} catch (Dwoo_Security_Exception $e) {
return $dwoo->triggerError('Include : Security restriction : '.$e->getMessage(), E_USER_WARNING);
} catch (Dwoo_Exception $e) {
return $dwoo->triggerError('Include : '.$e->getMessage(), E_USER_WARNING);
}
if ($include === null) {
return $dwoo->triggerError('Include : Resource "'.$resource.':'.$identifier.'" not found.', E_USER_WARNING);
} elseif ($include === false) {
return $dwoo->triggerError('Include : Resource "'.$resource.'" does not support includes.', E_USER_WARNING);
}
if ($dwoo->isArray($data)) {
$vars = $data;
} elseif ($dwoo->isArray($cache_time)) {
$vars = $cache_time;
} else {
$vars = $dwoo->readVar($data);
}
if (count($rest)) {
$vars = $rest + $vars;
}
$out = $dwoo->get($include, $vars);
if ($assign !== null) {
$dwoo->assignInScope($out, $assign);
} else {
return $out;
}
}

View File

@ -1,24 +0,0 @@
<?php
/**
* Indents every line of a text by the given amount of characters
* <pre>
* * value : the string to indent
* * by : how many characters should be inserted before each line
* * char : the character(s) to insert
* </pre>
* 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 <j.boggiano@seld.be>
* @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_indent_compile(Dwoo_Compiler $compiler, $value, $by=4, $char=' ')
{
return "preg_replace('#^#m', '".str_repeat(substr($char, 1, -1), trim($by, '"\''))."', $value)";
}

View File

@ -1,22 +0,0 @@
<?php
/**
* Checks whether a variable is not null
* <pre>
* * var : variable to check
* </pre>
* 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 <j.boggiano@seld.be>
* @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_isset_compile(Dwoo_Compiler $compiler, $var)
{
return '('.$var.' !== null)';
}

View File

@ -1,74 +0,0 @@
<?php
/**
* Loads sub-templates contained in an external file
* <pre>
* * file : the resource name of the file to load
* </pre>
* 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 <j.boggiano@seld.be>
* @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
*/
function Dwoo_Plugin_load_templates_compile(Dwoo_Compiler $compiler, $file)
{
$file = substr($file, 1, -1);
if ($file === '') {
return;
}
if (preg_match('#^([a-z]{2,}):(.*)$#i', $file, $m)) {
// resource:identifier given, extract them
$resource = $m[1];
$identifier = $m[2];
} else {
// get the current template's resource
$resource = $compiler->getDwoo()->getTemplate()->getResourceName();
$identifier = $file;
}
$tpl = $compiler->getDwoo()->templateFactory($resource, $identifier);
if ($tpl === null) {
throw new Dwoo_Compilation_Exception($compiler, 'Load Templates : Resource "'.$resource.':'.$identifier.'" not found.');
} elseif ($tpl === false) {
throw new Dwoo_Compilation_Exception($compiler, 'Load Templates : Resource "'.$resource.'" does not support includes.');
}
$cmp = clone $compiler;
$cmp->compile($compiler->getDwoo(), $tpl);
foreach ($cmp->getTemplatePlugins() as $template=>$args) {
$compiler->addTemplatePlugin($template, $args['params'], $args['uuid'], $args['body']);
}
foreach ($cmp->getUsedPlugins() as $plugin=>$type) {
$compiler->addUsedPlugin($plugin, $type);
}
$out = '\'\';// checking for modification in '.$resource.':'.$identifier."\r\n";
$modCheck = $tpl->getIsModifiedCode();
if ($modCheck) {
$out .= 'if (!('.$modCheck.')) { ob_end_clean(); return false; }';
} else {
$out .= 'try {
$tpl = $this->templateFactory("'.$resource.'", "'.$identifier.'");
} catch (Dwoo_Exception $e) {
$this->triggerError(\'Load Templates : Resource <em>'.$resource.'</em> was not added to Dwoo, can not extend <em>'.$identifier.'</em>\', E_USER_WARNING);
}
if ($tpl === null)
$this->triggerError(\'Load Templates : Resource "'.$resource.':'.$identifier.'" was not found.\', E_USER_WARNING);
elseif ($tpl === false)
$this->triggerError(\'Load Templates : Resource "'.$resource.'" does not support extends.\', E_USER_WARNING);
if ($tpl->getUid() != "'.$tpl->getUid().'") { ob_end_clean(); return false; }';
}
return $out;
}

View File

@ -1,22 +0,0 @@
<?php
/**
* Makes the input string lower cased
* <pre>
* * value : the string to process
* </pre>
* 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 <j.boggiano@seld.be>
* @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_lower_compile(Dwoo_Compiler $compiler, $value)
{
return 'mb_strtolower((string) '.$value.', $this->charset)';
}

View File

@ -1,117 +0,0 @@
<?php
/**
* Outputs a mailto link with optional spam-proof (okay probably not) encoding
* <pre>
* * address : target email address
* * text : display text to show for the link, defaults to the address if not provided
* * subject : the email subject
* * encode : one of the available encoding (none, js, jscharcode or hex)
* * cc : address(es) to carbon copy, comma separated
* * bcc : address(es) to blind carbon copy, comma separated
* * newsgroups : newsgroup(s) to post to, comma separated
* * followupto : address(es) to follow up, comma separated
* * extra : additional attributes to add to the &lt;a&gt; tag
* </pre>
* 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 <j.boggiano@seld.be>
* @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
*/
function Dwoo_Plugin_mailto(Dwoo $dwoo, $address, $text=null, $subject=null, $encode=null, $cc=null, $bcc=null, $newsgroups=null, $followupto=null, $extra=null)
{
if (empty($address)) {
return '';
}
if (empty($text)) {
$text = $address;
}
// build address string
$address .= '?';
if (!empty($subject)) {
$address .= 'subject='.rawurlencode($subject).'&';
}
if (!empty($cc)) {
$address .= 'cc='.rawurlencode($cc).'&';
}
if (!empty($bcc)) {
$address .= 'bcc='.rawurlencode($bcc).'&';
}
if (!empty($newsgroups)) {
$address .= 'newsgroups='.rawurlencode($newsgroups).'&';
}
if (!empty($followupto)) {
$address .= 'followupto='.rawurlencode($followupto).'&';
}
$address = rtrim($address, '?&');
// output
switch($encode)
{
case 'none':
case null:
return '<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>';
case 'js':
case 'javascript':
$str = 'document.write(\'<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>\');';
$len = strlen($str);
$out = '';
for ($i=0; $i<$len; $i++) {
$out .= '%'.bin2hex($str[$i]);
}
return '<script type="text/javascript">eval(unescape(\''.$out.'\'));</script>';
break;
case 'javascript_charcode':
case 'js_charcode':
case 'jscharcode':
case 'jschar':
$str = '<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>';
$len = strlen($str);
$out = '<script type="text/javascript">'."\n<!--\ndocument.write(String.fromCharCode(";
for ($i=0; $i<$len; $i++) {
$out .= ord($str[$i]).',';
}
return rtrim($out, ',') . "));\n-->\n</script>\n";
break;
case 'hex':
if (strpos($address, '?') !== false) {
return $dwoo->triggerError('Mailto: Hex encoding is not possible with extra attributes, use one of : <em>js, jscharcode or none</em>.', E_USER_WARNING);
}
$out = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;';
$len = strlen($address);
for ($i=0; $i<$len; $i++) {
if (preg_match('#\w#', $address[$i])) {
$out .= '%'.bin2hex($address[$i]);
} else {
$out .= $address[$i];
}
}
$out .= '" '.$extra.'>';
$len = strlen($text);
for ($i=0; $i<$len; $i++) {
$out .= '&#x'.bin2hex($text[$i]);
}
return $out.'</a>';
default:
return $dwoo->triggerError('Mailto: <em>encode</em> argument is invalid, it must be one of : <em>none (= no value), js, js_charcode or hex</em>', E_USER_WARNING);
}
}

View File

@ -1,130 +0,0 @@
<?php
/**
* Computes a mathematical equation
* <pre>
* * equation : the equation to compute, it can include normal variables with $foo or special math variables without the dollar sign
* * format : output format, see {@link http://php.net/sprintf} for details
* * assign : if set, the output is assigned into the given variable name instead of being output
* * rest : all math specific variables that you use must be defined, see the example
* </pre>
* Example :
*
* <code>
* {$c=2}
* {math "(a+b)*$c/4" a=3 b=5}
*
* output is : 4 ( = (3+5)*2/4)
* </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 <j.boggiano@seld.be>
* @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_math_compile(Dwoo_Compiler $compiler, $equation, $format='', $assign='', array $rest=array())
{
/**
* Holds the allowed function, characters, operators and constants
*/
$allowed = array
(
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'+', '-', '/', '*', '.', ' ', '<<', '>>', '%', '&', '^', '|', '~',
'abs(', 'ceil(', 'floor(', 'exp(', 'log10(',
'cos(', 'sin(', 'sqrt(', 'tan(',
'M_PI', 'INF', 'M_E',
);
/**
* Holds the functions that can accept multiple arguments
*/
$funcs = array
(
'round(', 'log(', 'pow(',
'max(', 'min(', 'rand(',
);
$equation = $equationSrc = str_ireplace(array('pi', 'M_PI()', 'inf', ' e '), array('M_PI', 'M_PI', 'INF', ' M_E '), $equation);
$delim = $equation[0];
$open = $delim.'.';
$close = '.'.$delim;
$equation = substr($equation, 1, -1);
$out = '';
$ptr = 1;
$allowcomma = 0;
while (strlen($equation) > 0) {
$substr = substr($equation, 0, $ptr);
if (array_search($substr, $allowed) !== false) {
// allowed string
$out.=$substr;
$equation = substr($equation, $ptr);
$ptr = 0;
} elseif (array_search($substr, $funcs) !== false) {
// allowed func
$out.=$substr;
$equation = substr($equation, $ptr);
$ptr = 0;
$allowcomma++;
if ($allowcomma === 1) {
$allowed[] = ',';
}
} elseif (isset($rest[$substr])) {
// variable
$out.=$rest[$substr];
$equation = substr($equation, $ptr);
$ptr = 0;
} elseif ($substr === $open) {
// pre-replaced variable
preg_match('#.*\((?:[^()]*?|(?R))\)'.str_replace('.', '\\.', $close).'#', substr($equation, 2), $m);
if (empty($m)) {
preg_match('#.*?'.str_replace('.', '\\.', $close).'#', substr($equation, 2), $m);
}
$out.=substr($m[0], 0, -2);
$equation = substr($equation, strlen($m[0])+2);
$ptr = 0;
} elseif ($substr==='(') {
// opening parenthesis
if ($allowcomma>0) {
$allowcomma++;
}
$out.=$substr;
$equation = substr($equation, $ptr);
$ptr = 0;
} elseif ($substr===')') {
// closing parenthesis
if ($allowcomma>0) {
$allowcomma--;
if ($allowcomma===0) {
array_pop($allowed);
}
}
$out.=$substr;
$equation = substr($equation, $ptr);
$ptr = 0;
} elseif ($ptr >= strlen($equation)) {
// parse error if we've consumed the entire equation without finding anything valid
throw new Dwoo_Compilation_Exception($compiler, 'Math : Syntax error or variable undefined in equation '.$equationSrc.' at '.$substr);
return;
} else {
// nothing special, advance
$ptr++;
}
}
if ($format !== '\'\'') {
$out = 'sprintf('.$format.', '.$out.')';
}
if ($assign !== '\'\'') {
return '($this->assignInScope('.$out.', '.$assign.'))';
}
return '('.$out.')';
}

View File

@ -1,22 +0,0 @@
<?php
/**
* Converts line breaks into <br /> tags
* <pre>
* * value : the string to process
* </pre>
* 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 <j.boggiano@seld.be>
* @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_nl2br_compile(Dwoo_Compiler $compiler, $value)
{
return 'nl2br((string) '.$value.')';
}

View File

@ -1,23 +0,0 @@
<?php
/**
* Prints out a variable without any notice if it doesn't exist
*
* <pre>
* * value : the variable to print
* </pre>
* 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 <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://dwoo.org/LICENSE Modified BSD License
* @link http://dwoo.org/
* @version 1.1.1
* @date 2009-10-18
* @package Dwoo
*/
function Dwoo_Plugin_optional_compile(Dwoo_Compiler $compiler, $value)
{
return $value;
}

View File

@ -1,38 +0,0 @@
<?php
/**
* Replaces the search string by the replace string using regular expressions
* <pre>
* * value : the string to search into
* * search : the string to search for, must be a complete regular expression including delimiters
* * replace : the string to use as a replacement, must be a complete regular expression including delimiters
* </pre>
* 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 <j.boggiano@seld.be>
* @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_regex_replace(Dwoo $dwoo, $value, $search, $replace)
{
$search = (array) $search;
$cnt = count($search);
for ($i = 0; $i < $cnt; $i++) {
// Credits for this to Monte Ohrt who made smarty's regex_replace modifier
if (($pos = strpos($search[$i], "\0")) !== false) {
$search[$i] = substr($search[$i], 0, $pos);
}
if (preg_match('#[a-z\s]+$#is', $search[$i], $m) && (strpos($m[0], 'e') !== false)) {
$search[$i] = substr($search[$i], 0, -strlen($m[0])) . str_replace(array('e', ' '), '', $m[0]);
}
}
return preg_replace($search, $replace, $value);
}

View File

@ -1,28 +0,0 @@
<?php
/**
* Replaces the search string by the replace string
* <pre>
* * value : the string to search into
* * search : the string to search for
* * replace : the string to use as a replacement
* </pre>
* 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 <j.boggiano@seld.be>
* @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_replace_compile(Dwoo_Compiler $compiler, $value, $search, $replace, $case_sensitive = true)
{
if ($case_sensitive == 'false' || (bool)$case_sensitive === false) {
return 'str_ireplace('.$search.', '.$replace.', '.$value.')';
} else {
return 'str_replace('.$search.', '.$replace.', '.$value.')';
}
}

View File

@ -1,34 +0,0 @@
<?php
/**
* Reverses a string or an array
* <pre>
* * value : the string or array to reverse
* * preserve_keys : if value is an array and this is true, then the array keys are left intact
* </pre>
* 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 <j.boggiano@seld.be>
* @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_reverse(Dwoo $dwoo, $value, $preserve_keys=false)
{
if (is_array($value)) {
return array_reverse($value, $preserve_keys);
} elseif(($charset=$dwoo->getCharset()) === 'iso-8859-1') {
return strrev((string) $value);
} else {
$strlen = mb_strlen($value);
$out = '';
while ($strlen--) {
$out .= mb_substr($value, $strlen, 1, $charset);
}
return $out;
}
}

View File

@ -1,22 +0,0 @@
<?php
/**
* Marks the variable as safe and removes the auto-escape function, only useful if you turned auto-escaping on
* <pre>
* * var : the variable to pass through untouched
* </pre>
* 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 <j.boggiano@seld.be>
* @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_safe_compile(Dwoo_Compiler $compiler, $var)
{
return preg_replace('#\(is_string\(\$tmp=(.+)\) \? htmlspecialchars\(\$tmp, ENT_QUOTES, \$this->charset\) : \$tmp\)#', '$1', $var);
}

Some files were not shown because too many files have changed in this diff Show More