First public release of MyAAC

This commit is contained in:
slawkens1
2017-05-01 20:02:45 +02:00
parent 31172b4883
commit b5362d0654
2016 changed files with 114481 additions and 0 deletions

View File

@@ -0,0 +1,196 @@
<?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

@@ -0,0 +1,27 @@
// ------------------------
// 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

@@ -0,0 +1,32 @@
<?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

@@ -0,0 +1,54 @@
<?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

@@ -0,0 +1,33 @@
// 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

@@ -0,0 +1,143 @@
<?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

@@ -0,0 +1,36 @@
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

@@ -0,0 +1,12 @@
<?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

@@ -0,0 +1,16 @@
<?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

@@ -0,0 +1,172 @@
<?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

@@ -0,0 +1,31 @@
{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

@@ -0,0 +1,57 @@
<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

@@ -0,0 +1,96 @@
<?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

@@ -0,0 +1,32 @@
// ------------------------
// 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

@@ -0,0 +1,512 @@
<?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

@@ -0,0 +1,103 @@
<?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

@@ -0,0 +1,38 @@
<?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

@@ -0,0 +1,250 @@
<?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

@@ -0,0 +1,19 @@
<?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

@@ -0,0 +1,44 @@
<?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

@@ -0,0 +1,26 @@
<?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

@@ -0,0 +1,21 @@
<?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

@@ -0,0 +1,49 @@
<?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

@@ -0,0 +1,25 @@
<?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

@@ -0,0 +1,24 @@
<?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

@@ -0,0 +1,30 @@
<?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

@@ -0,0 +1,65 @@
<?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

@@ -0,0 +1,150 @@
<?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

@@ -0,0 +1,147 @@
<?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

@@ -0,0 +1,85 @@
<?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

@@ -0,0 +1,44 @@
<?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

@@ -0,0 +1,19 @@
<?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

@@ -0,0 +1,199 @@
<?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

@@ -0,0 +1,518 @@
<?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

@@ -0,0 +1,270 @@
<?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

@@ -0,0 +1,497 @@
<?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);
}
}
}
}