initial commit

This commit is contained in:
Chris Sewell
2012-11-28 03:55:08 -05:00
parent 7adb399b2e
commit cf140a2e97
3247 changed files with 492437 additions and 0 deletions

View File

@ -0,0 +1,148 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Abstract class that provides an interface for escaping of output.
*
* @package symfony
* @subpackage view
* @author Mike Squire <mike@somosis.co.uk>
* @version SVN: $Id: sfOutputEscaper.class.php 4262 2007-06-19 12:27:58Z fabien $
*/
abstract class sfOutputEscaper
{
/**
* The value that is to be escaped.
*
* @var mixed
*/
protected $value;
/**
* The escaping method that is going to be applied to the value and its
* children. This is actually the name of a PHP function.
*
* @var string
*/
protected $escapingMethod;
/**
* Constructor stores the escaping method and value.
*
* Since sfOutputEscaper is an abstract class, instances cannot be created
* directly but the constructor will be inherited by sub-classes.
*
* @param string Escaping method
* @param string Escaping value
*/
public function __construct($escapingMethod, $value)
{
$this->value = $value;
$this->escapingMethod = $escapingMethod;
}
/**
* Decorates a PHP variable with something that will escape any data obtained
* from it.
*
* The following cases are dealt with:
*
* - The value is null or false: null or false is returned.
* - The value is scalar: the result of applying the escaping method is
* returned.
* - The value is an array or an object that implements the ArrayAccess
* interface: the array is decorated such that accesses to elements yield
* an escaped value.
* - The value implements the Traversable interface (either an Iterator, an
* IteratorAggregate or an internal PHP class that implements
* Traversable): decorated much like the array.
* - The value is another type of object: decorated such that the result of
* method calls is escaped.
*
* The escaping method is actually the name of a PHP callable. There are a set
* of standard escaping methods listed in the escaping helper
* (EscapingHelper.php).
*
* @param string $escapingMethod the escaping method (a PHP function) to apply to the value
* @param mixed $value the value to escape
* @param mixed the escaped value
*
* @return mixed Escaping value
*
* @throws <b>sfException</b> If the escaping fails
*/
public static function escape($escapingMethod, $value)
{
if (is_null($value) || ($value === false) || ($escapingMethod === 'esc_raw'))
{
return $value;
}
// Scalars are anything other than arrays, objects and resources.
if (is_scalar($value))
{
return call_user_func($escapingMethod, $value);
}
if (is_array($value))
{
return new sfOutputEscaperArrayDecorator($escapingMethod, $value);
}
if (is_object($value))
{
if ($value instanceof sfOutputEscaper)
{
// avoid double decoration when passing values from action template to component/partial
$copy = clone $value;
$copy->escapingMethod = $escapingMethod;
return $copy;
}
elseif ($value instanceof Traversable)
{
return new sfOutputEscaperIteratorDecorator($escapingMethod, $value);
}
else
{
return new sfOutputEscaperObjectDecorator($escapingMethod, $value);
}
}
// it must be a resource; cannot escape that.
throw new sfException(sprintf('Unable to escape value "%s"', print_r($value, true)));
}
/**
* Returns the raw value associated with this instance.
*
* Concrete instances of sfOutputEscaper classes decorate a value which is
* stored by the constructor. This returns that original, unescaped, value.
*
* @return mixed The original value used to construct the decorator
*/
public function getRawValue()
{
return $this->value;
}
/**
* Gets a value from the escaper.
*
* @param string Value to get
*
* @return mixed Value
*/
public function __get($var)
{
return $this->escape($this->escapingMethod, $this->value->$var);
}
}

View File

@ -0,0 +1,173 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
// fix for PHP 5.0 (no Countable interface)
if (!interface_exists('Countable', false))
{
interface Countable
{
public function count();
}
}
/**
* Output escaping decorator class for arrays.
*
* @see sfOutputEscaper
* @package symfony
* @subpackage view
* @author Mike Squire <mike@somosis.co.uk>
* @version SVN: $Id: sfOutputEscaperArrayDecorator.class.php 3232 2007-01-11 20:51:54Z fabien $
*/
class sfOutputEscaperArrayDecorator extends sfOutputEscaperGetterDecorator implements Iterator, ArrayAccess, Countable
{
/**
* Used by the iterator to know if the current element is valid.
*
* @var int
*/
private $count;
/**
* Reset the array to the beginning (as required for the Iterator interface).
*/
public function rewind()
{
reset($this->value);
$this->count = count($this->value);
}
/**
* Get the key associated with the current value (as required by the Iterator interface).
*
* @return string The key
*/
public function key()
{
return key($this->value);
}
/**
* Escapes and return the current value (as required by the Iterator interface).
*
* This escapes the value using {@link sfOutputEscaper::escape()} with
* whatever escaping method is set for this instance.
*
* @return mixed The escaped value
*/
public function current()
{
return sfOutputEscaper::escape($this->escapingMethod, current($this->value));
}
/**
* Moves to the next element (as required by the Iterator interface).
*/
public function next()
{
next($this->value);
$this->count --;
}
/**
* Returns true if the current element is valid (as required by the Iterator interface).
*
* The current element will not be valid if {@link next()} has fallen off the
* end of the array or if there are no elements in the array and {@link
* rewind()} was called.
*
* @return boolean The validity of the current element; true if it is valid
*/
public function valid()
{
return $this->count > 0;
}
/**
* Returns true if the supplied offset is set in the array (as required by the ArrayAccess interface).
*
* @param string The offset of the value to check existance of
*
* @return boolean true if the offset exists; false otherwise
*/
public function offsetExists($offset)
{
return array_key_exists($offset, $this->value);
}
/**
* Returns the element associated with the offset supplied (as required by the ArrayAccess interface).
*
* @param string The offset of the value to get
*
* @return mixed The escaped value
*/
public function offsetGet($offset)
{
return sfOutputEscaper::escape($this->escapingMethod, $this->value[$offset]);
}
/**
* Throws an exception saying that values cannot be set (this method is
* required for the ArrayAccess interface).
*
* This (and the other sfOutputEscaper classes) are designed to be read only
* so this is an illegal operation.
*
* @param string (ignored)
* @param string (ignored)
*
* @throws <b>sfException</b>
*/
public function offsetSet($offset, $value)
{
throw new sfException('Cannot set values.');
}
/**
* Throws an exception saying that values cannot be unset (this method is
* required for the ArrayAccess interface).
*
* This (and the other sfOutputEscaper classes) are designed to be read only
* so this is an illegal operation.
*
* @param string (ignored)
*
* @throws sfException
*/
public function offsetUnset($offset)
{
throw new sfException('Cannot unset values.');
}
/**
* Returns the size of the array (are required by the Countable interface).
*
* @return int The size of the array
*/
public function count()
{
return count($this->value);
}
/**
* Returns the (unescaped) value from the array associated with the key supplied.
*
* @param string The key into the array to use
*
* @return mixed The value
*/
public function getRaw($key)
{
return $this->value[$key];
}
}

View File

@ -0,0 +1,54 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Abstract output escaping decorator class for "getter" objects.
*
* @see sfOutputEscaper
* @package symfony
* @subpackage view
* @author Mike Squire <mike@somosis.co.uk>
* @version SVN: $Id: sfOutputEscaperGetterDecorator.class.php 3232 2007-01-11 20:51:54Z fabien $
*/
abstract class sfOutputEscaperGetterDecorator extends sfOutputEscaper
{
/**
* Returns the raw, unescaped value associated with the key supplied.
*
* The key might be an index into an array or a value to be passed to the
* decorated object's get() method.
*
* @param string The key to retrieve
*
* @return mixed The value
*/
public abstract function getRaw($key);
/**
* Returns the escaped value associated with the key supplied.
*
* Typically (using this implementation) the raw value is obtained using the
* {@link getRaw()} method, escaped and the result returned.
*
* @param string The key to retieve
* @param string The escaping method (a PHP function) to use
*
* @return mixed The escaped value
*/
public function get($key, $escapingMethod = null)
{
if (!$escapingMethod)
{
$escapingMethod = $this->escapingMethod;
}
return sfOutputEscaper::escape($escapingMethod, $this->getRaw($key));
}
}

View File

@ -0,0 +1,170 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Output escaping iterator decorator.
*
* This takes an object that implements the Traversable interface and turns it
* into an iterator with each value escaped.
*
* Note: Prior to PHP 5.1, the IteratorIterator class was not implemented in the
* core of PHP. This means that although it will still work with classes that
* implement Iterator or IteratorAggregate, internal PHP classes that only
* implement the Traversable interface will cause the constructor to throw an
* exception.
*
* @see sfOutputEscaper
* @package symfony
* @subpackage view
* @author Mike Squire <mike@somosis.co.uk>
* @version SVN: $Id: sfOutputEscaperIteratorDecorator.class.php 3232 2007-01-11 20:51:54Z fabien $
*/
class sfOutputEscaperIteratorDecorator extends sfOutputEscaperObjectDecorator implements Iterator, Countable, ArrayAccess
{
/**
* The iterator to be used.
*
* @var IteratorIterator
*/
private $iterator;
/**
* Constructs a new escaping iteratoror using the escaping method and value supplied.
*
* @param string The escaping method to use
* @param Traversable The iterator to escape
*/
public function __construct($escapingMethod, Traversable $value)
{
// Set the original value for __call(). Set our own iterator because passing
// it to IteratorIterator will lose any other method calls.
parent::__construct($escapingMethod, $value);
$this->iterator = new IteratorIterator($value);
}
/**
* Resets the iterator (as required by the Iterator interface).
*
* @return boolean true, if the iterator rewinds successfully otherwise false
*/
public function rewind()
{
return $this->iterator->rewind();
}
/**
* Escapes and gets the current element (as required by the Iterator interface).
*
* @return mixed The escaped value
*/
public function current()
{
return sfOutputEscaper::escape($this->escapingMethod, $this->iterator->current());
}
/**
* Gets the current key (as required by the Iterator interface).
*
* @return string Iterator key
*/
public function key()
{
return $this->iterator->key();
}
/**
* Moves to the next element in the iterator (as required by the Iterator interface).
*/
public function next()
{
return $this->iterator->next();
}
/**
* Returns whether the current element is valid or not (as required by the
* Iterator interface).
*
* @return boolean true if the current element is valid; false otherwise
*/
public function valid()
{
return $this->iterator->valid();
}
/**
* Returns true if the supplied offset is set in the array (as required by
* the ArrayAccess interface).
*
* @param string The offset of the value to check existance of
*
* @return boolean true if the offset exists; false otherwise
*/
public function offsetExists($offset)
{
return array_key_exists($offset, $this->value);
}
/**
* Returns the element associated with the offset supplied (as required by the ArrayAccess interface).
*
* @param string The offset of the value to get
*
* @return mixed The escaped value
*/
public function offsetGet($offset)
{
return sfOutputEscaper::escape($this->escapingMethod, $this->value[$offset]);
}
/**
* Throws an exception saying that values cannot be set (this method is
* required for the ArrayAccess interface).
*
* This (and the other sfOutputEscaper classes) are designed to be read only
* so this is an illegal operation.
*
* @param string (ignored)
* @param string (ignored)
*
* @throws <b>sfException</b>
*/
public function offsetSet($offset, $value)
{
throw new sfException('Cannot set values.');
}
/**
* Throws an exception saying that values cannot be unset (this method is
* required for the ArrayAccess interface).
*
* This (and the other sfOutputEscaper classes) are designed to be read only
* so this is an illegal operation.
*
* @param string (ignored)
*
* @throws <b>sfException</b>
*/
public function offsetUnset($offset)
{
throw new sfException('Cannot unset values.');
}
/**
* Returns the size of the array (are required by the Countable interface).
*
* @return int The size of the array
*/
public function count()
{
return count($this->value);
}
}

View File

@ -0,0 +1,109 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Output escaping object decorator that intercepts all method calls and escapes
* their return values.
*
* @see sfOutputEscaper
* @package symfony
* @subpackage view
* @author Mike Squire <mike@somosis.co.uk>
* @version SVN: $Id: sfOutputEscaperObjectDecorator.class.php 3232 2007-01-11 20:51:54Z fabien $
*/
class sfOutputEscaperObjectDecorator extends sfOutputEscaperGetterDecorator
{
/**
* Magic PHP method that intercepts method calls, calls them on the objects
* that is being escaped and escapes the result.
*
* The calling of the method is changed slightly to accommodate passing a
* specific escaping strategy. An additional parameter is appended to the
* argument list which is the escaping strategy. The decorator will remove
* and use this parameter as the escaping strategy if it begins with 'esc_'
* (the prefix all escaping helper functions have).
*
* For example if an object, $o, implements methods a() and b($arg):
*
* $o->a() // Escapes the return value of a()
* $o->a(ESC_RAW) // Uses the escaping method ESC_RAW with a()
* $o->b('a') // Escapes the return value of b('a')
* $o->b('a', ESC_RAW); // Uses the escaping method ESC_RAW with b('a')
*
* @param string The method on the object to be called
* @param array An array of arguments to be passed to the method
*
* @return mixed The escaped value returned by the method
*/
public function __call($method, $args)
{
if (count($args) > 0)
{
$escapingMethod = $args[count($args) - 1];
if (is_string($escapingMethod) && substr($escapingMethod, 0, 4) === 'esc_')
{
array_pop($args);
}
else
{
$escapingMethod = $this->escapingMethod;
}
}
else
{
$escapingMethod = $this->escapingMethod;
}
$value = call_user_func_array(array($this->value, $method), $args);
return sfOutputEscaper::escape($escapingMethod, $value);
}
/**
* Returns the result of calling the get() method on the object, bypassing
* any escaping, if that method exists.
*
* If there is not a callable get() method this will throw an exception.
*
* @param string The parameter to be passed to the get() get method
*
* @return mixed The unescaped value returned
*
* @throws <b>sfException</b> if the object does not have a callable get() method
*/
public function getRaw($key)
{
if (!is_callable(array($this->value, 'get')))
{
throw new sfException('Object does not have a callable get() method.');
}
return $this->value->get($key);
}
/**
* Try to call decorated object __toString() method if exists.
*
* @return string
*
* @throws <b>sfException</b>
*/
public function __toString()
{
if (method_exists($this->value, '__toString'))
{
return $this->value->__toString();
}
else
{
throw new sfException(sprintf('Object of class "%s" cannot be converted to string (Please create a __toString() method)', get_class($this->value)));
}
}
}

View File

@ -0,0 +1,146 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
*
* @package symfony
* @subpackage view
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfMailView.class.php 3232 2007-01-11 20:51:54Z fabien $
*/
class sfMailView extends sfPHPView
{
/**
* Retrieves the template engine associated with this view.
*
* @return string sfMail
*/
public function getEngine()
{
return 'sfMail';
}
/**
* Configures template for this view.
*
* @throws <b>sfActionException</b> If the configure fails
*/
public function configure()
{
// view.yml configure
parent::configure();
// require our configuration
$moduleName = $this->moduleName;
require(sfConfigCache::getInstance()->checkConfig(sfConfig::get('sf_app_module_dir_name').'/'.$this->moduleName.'/'.sfConfig::get('sf_app_module_config_dir_name').'/mailer.yml'));
}
/**
* Renders the presentation and send the email to the client.
*
* @return mixed Raw data of the mail
*/
public function render($templateVars = null)
{
$template = $this->getDirectory().'/'.$this->getTemplate();
$actionStackEntry = $this->getContext()->getActionStack()->getLastEntry();
$actionInstance = $actionStackEntry->getActionInstance();
$retval = null;
// execute pre-render check
$this->preRenderCheck();
if (sfConfig::get('sf_logging_enabled'))
{
$this->getContext()->getLogger()->info('{sfView} render "'.$template.'"');
}
// get sfMail object from action
$mail = $actionInstance->getVarHolder()->get('mail');
if (!$mail)
{
$error = 'You must define a sfMail object named $mail ($this->mail) in your action to be able to use a sfMailView.';
throw new sfActionException($error);
}
// assigns some variables to the template
$this->attributeHolder->add($this->getGlobalVars());
$this->attributeHolder->add($actionInstance->getVarHolder()->getAll());
// render main template
$retval = $this->renderFile($template);
// render main and alternate templates
$all_template_dir = dirname($template);
$all_template_regex = preg_replace('/\\.php$/', '\..+\.php', basename($template));
$all_templates = sfFinder::type('file')->name('/^'.$all_template_regex.'$/')->in($all_template_dir);
$all_retvals = array();
foreach ($all_templates as $templateFile)
{
if (preg_match('/\.([^.]+?)\.php$/', $templateFile, $matches))
{
$all_retvals[$matches[1]] = $this->renderFile($templateFile);
}
}
// send email
if (sfConfig::get('sf_logging_enabled'))
{
$this->getContext()->getLogger()->info('{sfView} send email to client');
}
// configuration prefix
$config_prefix = 'sf_mailer_'.strtolower($this->moduleName).'_';
$vars = array(
'mailer',
'priority', 'content_type', 'charset', 'encoding', 'wordwrap',
'hostname', 'port', 'domain', 'username', 'password'
);
$defaultMail = new sfMail();
foreach ($vars as $var)
{
$setter = 'set'.sfInflector::camelize($var);
$getter = 'get'.sfInflector::camelize($var);
$value = $mail->$getter() !== $defaultMail->$getter() ? $mail->$getter() : sfConfig::get($config_prefix.strtolower($var));
$mail->$setter($value);
}
$mail->setBody($retval);
// alternate bodies
$i = 0;
foreach ($all_retvals as $type => $retval)
{
if ($type == 'altbody' && !$mail->getAltBody())
{
$mail->setAltBody($retval);
}
else
{
++$i;
$mail->addStringAttachment($retval, 'file'.$i, 'base64', 'text/'.$type);
}
}
// preparing email to be sent
$mail->prepare();
// send e-mail
if (sfConfig::get($config_prefix.'deliver'))
{
$mail->send();
}
return $mail->getRawHeader().$mail->getRawBody();
}
}

View File

@ -0,0 +1,284 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2004-2006 Sean Kerr.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
*
* @package symfony
* @subpackage view
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <skerr@mojavi.org>
* @version SVN: $Id: sfPHPView.class.php 3308 2007-01-20 05:48:11Z fabien $
*/
class sfPHPView extends sfView
{
/**
* Executes any presentation logic for this view.
*/
public function execute()
{
}
/**
* Returns variables that will be accessible to the template.
*
* @return array Attributes from the template
*/
protected function getGlobalVars()
{
$context = $this->getContext();
$shortcuts = array(
'sf_context' => $context,
'sf_params' => $context->getRequest()->getParameterHolder(),
'sf_request' => $context->getRequest(),
'sf_user' => $context->getUser(),
'sf_view' => $this,
);
if (sfConfig::get('sf_use_flash'))
{
$sf_flash = new sfParameterHolder();
$sf_flash->add($context->getUser()->getAttributeHolder()->getAll('symfony/flash'));
$shortcuts['sf_flash'] = $sf_flash;
}
return $shortcuts;
}
/**
* Load core and standard helpers to be use in the template.
*/
protected function loadCoreAndStandardHelpers()
{
static $coreHelpersLoaded = 0;
if ($coreHelpersLoaded)
{
return;
}
$coreHelpersLoaded = 1;
$core_helpers = array('Helper', 'Url', 'Asset', 'Tag', 'Escaping');
$standard_helpers = sfConfig::get('sf_standard_helpers');
$helpers = array_unique(array_merge($core_helpers, $standard_helpers));
sfLoader::loadHelpers($helpers);
}
/**
* Renders the presentation.
*
* @param string Filename
*
* @return string File content
*/
protected function renderFile($_sfFile)
{
if (sfConfig::get('sf_logging_enabled'))
{
$this->getContext()->getLogger()->info('{sfView} render "'.$_sfFile.'"');
}
$this->loadCoreAndStandardHelpers();
$_escaping = $this->getEscaping();
if ($_escaping === false || $_escaping === 'bc')
{
extract($this->attributeHolder->getAll());
}
if ($_escaping !== false)
{
$sf_data = sfOutputEscaper::escape($this->getEscapingMethod(), $this->attributeHolder->getAll());
if ($_escaping === 'both')
{
foreach ($sf_data as $_key => $_value)
{
${$_key} = $_value;
}
}
}
// render
ob_start();
ob_implicit_flush(0);
require($_sfFile);
return ob_get_clean();
}
/**
* Retrieves the template engine associated with this view.
*
* Note: This will return null because PHP itself has no engine reference.
*
* @return null
*/
public function getEngine()
{
return null;
}
/**
* Configures template.
*
* @return void
*/
public function configure()
{
// store our current view
$actionStackEntry = $this->getContext()->getActionStack()->getLastEntry();
if (!$actionStackEntry->getViewInstance())
{
$actionStackEntry->setViewInstance($this);
}
// require our configuration
$viewConfigFile = $this->moduleName.'/'.sfConfig::get('sf_app_module_config_dir_name').'/view.yml';
require(sfConfigCache::getInstance()->checkConfig(sfConfig::get('sf_app_module_dir_name').'/'.$viewConfigFile));
// set template directory
if (!$this->directory)
{
$this->setDirectory(sfLoader::getTemplateDir($this->moduleName, $this->getTemplate()));
}
}
/**
* Loop through all template slots and fill them in with the results of
* presentation data.
*
* @param string A chunk of decorator content
*
* @return string A decorated template
*/
protected function decorate($content)
{
$template = $this->getDecoratorDirectory().'/'.$this->getDecoratorTemplate();
if (sfConfig::get('sf_logging_enabled'))
{
$this->getContext()->getLogger()->info('{sfView} decorate content with "'.$template.'"');
}
// set the decorator content as an attribute
$this->attributeHolder->set('sf_content', $content);
// for backwards compatibility with old layouts; remove at 0.8.0?
$this->attributeHolder->set('content', $content);
// render the decorator template and return the result
$retval = $this->renderFile($template);
return $retval;
}
/**
* Renders the presentation.
*
* When the controller render mode is sfView::RENDER_CLIENT, this method will
* render the presentation directly to the client and null will be returned.
*
* @return string A string representing the rendered presentation, if
* the controller render mode is sfView::RENDER_VAR, otherwise null
*/
public function render($templateVars = null)
{
$context = $this->getContext();
// get the render mode
$mode = $context->getController()->getRenderMode();
if ($mode == sfView::RENDER_NONE)
{
return null;
}
$retval = null;
$response = $context->getResponse();
if (sfConfig::get('sf_cache'))
{
$key = $response->getParameterHolder()->remove('current_key', 'symfony/cache/current');
$cache = $response->getParameter($key, null, 'symfony/cache');
if ($cache !== null)
{
$cache = unserialize($cache);
$retval = $cache['content'];
$vars = $cache['vars'];
$response->mergeProperties($cache['response']);
}
}
// decorator
$layout = $response->getParameter($this->moduleName.'_'.$this->actionName.'_layout', null, 'symfony/action/view');
if (false === $layout)
{
$this->setDecorator(false);
}
else if (null !== $layout)
{
$this->setDecoratorTemplate($layout.$this->getExtension());
}
// template variables
if ($templateVars === null)
{
$actionInstance = $context->getActionStack()->getLastEntry()->getActionInstance();
$templateVars = $actionInstance->getVarHolder()->getAll();
}
// assigns some variables to the template
$this->attributeHolder->add($this->getGlobalVars());
$this->attributeHolder->add($retval !== null ? $vars : $templateVars);
// render template if no cache
if ($retval === null)
{
// execute pre-render check
$this->preRenderCheck();
// render template file
$template = $this->getDirectory().'/'.$this->getTemplate();
$retval = $this->renderFile($template);
if (sfConfig::get('sf_cache') && $key !== null)
{
$cache = array(
'content' => $retval,
'vars' => $templateVars,
'view_name' => $this->viewName,
'response' => $context->getResponse(),
);
$response->setParameter($key, serialize($cache), 'symfony/cache');
if (sfConfig::get('sf_web_debug'))
{
$retval = sfWebDebug::getInstance()->decorateContentWithDebug($key, $retval, true);
}
}
}
// now render decorator template, if one exists
if ($this->isDecorator())
{
$retval = $this->decorate($retval);
}
// render to client
if ($mode == sfView::RENDER_CLIENT)
{
$context->getResponse()->setContent($retval);
}
return $retval;
}
}

View File

@ -0,0 +1,76 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
*
* @package symfony
* @subpackage view
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfPartialView.class.php 3232 2007-01-11 20:51:54Z fabien $
*/
class sfPartialView extends sfPHPView
{
/**
* Executes any presentation logic for this view.
*/
public function execute()
{
}
/**
* Configures template for this view.
*/
public function configure()
{
$this->setDecorator(false);
$this->setTemplate($this->actionName.$this->getExtension());
if ('global' == $this->moduleName)
{
$this->setDirectory(sfConfig::get('sf_app_template_dir'));
}
else
{
$this->setDirectory(sfLoader::getTemplateDir($this->moduleName, $this->getTemplate()));
}
}
/**
* Renders the presentation.
*
* @param array Template attributes
*
* @return string Current template content
*/
public function render($templateVars = array())
{
if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled'))
{
$timer = sfTimerManager::getTimer(sprintf('Partial "%s/%s"', $this->moduleName, $this->actionName));
}
// execute pre-render check
$this->preRenderCheck();
// assigns some variables to the template
$this->attributeHolder->add($this->getGlobalVars());
$this->attributeHolder->add($templateVars);
// render template
$retval = $this->renderFile($this->getDirectory().'/'.$this->getTemplate());
if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled'))
{
$timer->addTime();
}
return $retval;
}
}

669
lib/symfony/view/sfView.class.php Executable file
View File

@ -0,0 +1,669 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2004-2006 Sean Kerr.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
*
* A view represents the presentation layer of an action. Output can be
* customized by supplying attributes, which a template can manipulate and
* display.
*
* @package symfony
* @subpackage view
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <skerr@mojavi.org>
* @version SVN: $Id: sfView.class.php 3250 2007-01-12 20:09:11Z fabien $
*/
abstract class sfView
{
/**
* Show an alert view.
*/
const ALERT = 'Alert';
/**
* Show an error view.
*/
const ERROR = 'Error';
/**
* Show a form input view.
*/
const INPUT = 'Input';
/**
* Skip view execution.
*/
const NONE = 'None';
/**
* Show a success view.
*/
const SUCCESS = 'Success';
/**
* Skip view rendering but output http headers
*/
const HEADER_ONLY = 'Headers';
/**
* Render the presentation to the client.
*/
const RENDER_CLIENT = 2;
/**
* Do not render the presentation.
*/
const RENDER_NONE = 1;
/**
* Render the presentation to a variable.
*/
const RENDER_VAR = 4;
protected
$context = null,
$decorator = false,
$decoratorDirectory = null,
$decoratorTemplate = null,
$directory = null,
$componentSlots = array(),
$template = null,
$escaping = null,
$escapingMethod = null,
$attributeHolder = null,
$parameterHolder = null,
$moduleName = '',
$actionName = '',
$viewName = '',
$extension = '.php';
/**
* Executes any presentation logic and set template attributes.
*/
abstract function execute();
/**
* Configures template.
*/
abstract function configure();
/**
* Retrieves the current application context.
*
* @return sfContext The current sfContext instance
*/
public final function getContext()
{
return $this->context;
}
/**
* Retrieves this views decorator template directory.
*
* @return string An absolute filesystem path to this views decorator template directory
*/
public function getDecoratorDirectory()
{
return $this->decoratorDirectory;
}
/**
* Retrieves this views decorator template.
*
* @return string A template filename, if a template has been set, otherwise null
*/
public function getDecoratorTemplate()
{
return $this->decoratorTemplate;
}
/**
* Retrieves this view template directory.
*
* @return string An absolute filesystem path to this views template directory
*/
public function getDirectory()
{
return $this->directory;
}
/**
* Retrieves the template engine associated with this view.
*
* Note: This will return null for PHPView instances.
*
* @return mixed A template engine instance
*/
abstract function getEngine();
/**
* Retrieves this views template.
*
* @return string A template filename, if a template has been set, otherwise null
*/
public function getTemplate()
{
return $this->template;
}
/**
* Gets the default escaping strategy associated with this view.
*
* The escaping strategy specifies how the variables get passed to the view.
*
* @return string the escaping strategy
*/
public function getEscaping()
{
return null === $this->escaping ? sfConfig::get('sf_escaping_strategy') : $this->escaping;
}
/**
* Returns the name of the function that is to be used as the escaping method.
*
* If the escaping method is empty, then that is returned. The default value
* specified by the sub-class will be used. If the method does not exist (in
* the sense there is no define associated with the method) and exception is
* thrown.
*
* @return string The escaping method as the name of the function to use
*
* @throws <b>sfException</b> If the method does not exist
*/
public function getEscapingMethod()
{
$method = null === $this->escapingMethod ? sfConfig::get('sf_escaping_method') : $this->escapingMethod;
if (empty($method))
{
return $method;
}
if (!defined($method))
{
throw new sfException(sprintf('Escaping method "%s" is not available; perhaps another helper needs to be loaded in?', $method));
}
return constant($method);
}
/**
* Imports parameter values and error messages from the request directly as view attributes.
*
* @param array An indexed array of file/parameter names
* @param boolean Is this a list of files?
* @param boolean Import error messages too?
* @param boolean Run strip_tags() on attribute value?
* @param boolean Run htmlspecialchars() on attribute value?
*/
public function importAttributes($names, $files = false, $errors = true, $stripTags = true, $specialChars = true)
{
// alias $request to keep the code clean
$request = $this->context->getRequest();
// get our array
if ($files)
{
// file names
$array =& $request->getFiles();
}
else
{
// parameter names
$array =& $request->getParameterHolder()->getAll();
}
// loop through our parameter names and import them
foreach ($names as &$name)
{
if (preg_match('/^([a-z0-9\-_]+)\{([a-z0-9\s\-_]+)\}$/i', $name, $match))
{
// we have a parent
$parent = $match[1];
$subname = $match[2];
// load the file/parameter value for this attribute if one exists
if (isset($array[$parent]) && isset($array[$parent][$subname]))
{
$value = $array[$parent][$subname];
if ($stripTags)
$value = strip_tags($value);
if ($specialChars)
$value = htmlspecialchars($value);
$this->setAttribute($name, $value);
}
else
{
// set an empty value
$this->setAttribute($name, '');
}
}
else
{
// load the file/parameter value for this attribute if one exists
if (isset($array[$name]))
{
$value = $array[$name];
if ($stripTags)
$value = strip_tags($value);
if ($specialChars)
$value = htmlspecialchars($value);
$this->setAttribute($name, $value);
}
else
{
// set an empty value
$this->setAttribute($name, '');
}
}
if ($errors)
{
if ($request->hasError($name))
{
$this->setAttribute($name.'_error', $request->getError($name));
}
else
{
// set empty error
$this->setAttribute($name.'_error', '');
}
}
}
}
/**
* Initializes this view.
*
* @param sfContext The current application context
* @param string The module name for this view
* @param string The action name for this view
* @param string The view name
*
* @return boolean true, if initialization completes successfully, otherwise false
*/
public function initialize($context, $moduleName, $actionName, $viewName)
{
if (sfConfig::get('sf_logging_enabled'))
{
$context->getLogger()->info(sprintf('{sfView} initialize view for "%s/%s"', $moduleName, $actionName));
}
$this->moduleName = $moduleName;
$this->actionName = $actionName;
$this->viewName = $viewName;
$this->context = $context;
$this->attributeHolder = new sfParameterHolder();
$this->parameterHolder = new sfParameterHolder();
$this->parameterHolder->add(sfConfig::get('mod_'.strtolower($moduleName).'_view_param', array()));
$this->decoratorDirectory = sfConfig::get('sf_app_template_dir');
// include view configuration
$this->configure();
return true;
}
/**
* Retrieves attributes for the current view.
*
* @return sfParameterHolder The attribute parameter holder
*/
public function getAttributeHolder()
{
return $this->attributeHolder;
}
/**
* Retrieves an attribute for the current view.
*
* @param string Name of the attribute
* @param string Value of the attribute
* @param string The current namespace
*
* @return mixed Attribute
*/
public function getAttribute($name, $default = null, $ns = null)
{
return $this->attributeHolder->get($name, $default, $ns);
}
/**
* Returns true if the view have attributes.
*
* @param string Name of the attribute
* @param string Namespace for the current view
*
* @return mixed Attribute of the view
*/
public function hasAttribute($name, $ns = null)
{
return $this->attributeHolder->has($name, $ns);
}
/**
* Sets an attribute of the view.
*
* @param string Attribute name
* @param string Value for the attribute
* @param string Namespace for the current
*/
public function setAttribute($name, $value, $ns = null)
{
$this->attributeHolder->set($name, $value, $ns);
}
/**
* Retrieves the parameters for the current view.
*
* @return sfParameterHolder The parameter holder
*/
public function getParameterHolder()
{
return $this->parameterHolder;
}
/**
* Retrieves a parameter from the current view.
*
* @param string Parameter name
* @param string Default parameter value
* @param string Namespace for the current view
*
* @return mixed A parameter value
*/
public function getParameter($name, $default = null, $ns = null)
{
return $this->parameterHolder->get($name, $default, $ns);
}
/**
* Indicates whether or not a parameter exist for the current view.
*
* @param string Name of the paramater
* @param string Namespace for the current view
*
* @return boolean true, if the parameter exists otherwise false
*/
public function hasParameter($name, $ns = null)
{
return $this->parameterHolder->has($name, $ns);
}
/**
* Sets a parameter for the view.
*
* @param string Name of the parameter
* @param string The parameter value
* @param string Namespace for the current view
*/
public function setParameter($name, $value, $ns = null)
{
$this->parameterHolder->set($name, $value, $ns);
}
/**
* Indicates that this view is a decorating view.
*
* @return boolean true, if this view is a decorating view, otherwise false
*/
public function isDecorator()
{
return $this->decorator;
}
/**
* Sets the decorating mode for the current view.
*
* @param boolean Set the decorating mode for the view
*/
public function setDecorator($boolean)
{
$this->decorator = (boolean) $boolean;
}
/**
* Executes a basic pre-render check to verify all required variables exist
* and that the template is readable.
*
* @throws <b>sfRenderException</b> If the pre-render check fails
*/
protected function preRenderCheck()
{
if ($this->template == null)
{
// a template has not been set
$error = 'A template has not been set';
throw new sfRenderException($error);
}
$template = $this->directory.'/'.$this->template;
if (!is_readable($template))
{
// the template isn't readable
throw new sfRenderException(sprintf('The template "%s" does not exist in: %s', $template, $this->directory));
}
// check to see if this is a decorator template
if ($this->decorator)
{
$template = $this->decoratorDirectory.'/'.$this->decoratorTemplate;
if (!is_readable($template))
{
// the decorator template isn't readable
$error = 'The decorator template "%s" does not exist or is unreadable';
$error = sprintf($error, $template);
throw new sfRenderException($error);
}
}
}
/**
* Renders the presentation.
*
* When the controller render mode is sfView::RENDER_CLIENT, this method will
* render the presentation directly to the client and null will be returned.
*
* @param array An array with variables that will be extracted for the template
* If empty, the current actions var holder will be extracted
* @return string A string representing the rendered presentation, if
* the controller render mode is sfView::RENDER_VAR, otherwise null
*/
abstract function render($templateVars = null);
/**
* Sets the decorator template directory for this view.
*
* @param string An absolute filesystem path to a template directory
*/
public function setDecoratorDirectory($directory)
{
$this->decoratorDirectory = $directory;
}
/**
* Sets the escape caracter mode.
*
* @param string Escape code
*/
public function setEscaping($escaping)
{
$this->escaping = $escaping;
}
/**
* Sets the escaping method for the current view.
*
* @param string Method for escaping
*/
public function setEscapingMethod($method)
{
$this->escapingMethod = $method;
}
/**
* Sets the decorator template for this view.
*
* If the template path is relative, it will be based on the currently
* executing module's template sub-directory.
*
* @param string An absolute or relative filesystem path to a template
*/
public function setDecoratorTemplate($template)
{
if (sfToolkit::isPathAbsolute($template))
{
$this->decoratorDirectory = dirname($template);
$this->decoratorTemplate = basename($template);
}
else
{
$this->decoratorTemplate = $template;
}
if (!strpos($this->decoratorTemplate, '.'))
{
$this->decoratorTemplate .= $this->getExtension();
}
// set decorator status
$this->decorator = true;
}
/**
* Sets the template directory for this view.
*
* @param string An absolute filesystem path to a template directory
*/
public function setDirectory($directory)
{
$this->directory = $directory;
}
/**
* Sets the module and action to be executed in place of a particular template attribute.
*
* @param string A template attribute name
* @param string A module name
* @param string A component name
*/
public function setComponentSlot($attributeName, $moduleName, $componentName)
{
$this->componentSlots[$attributeName] = array();
$this->componentSlots[$attributeName]['module_name'] = $moduleName;
$this->componentSlots[$attributeName]['component_name'] = $componentName;
}
/**
* Indicates whether or not a component slot exists.
*
* @param string The component slot name
*
* @return boolean true, if the component slot exists, otherwise false
*/
public function hasComponentSlot($name)
{
return isset($this->componentSlots[$name]);
}
/**
* Gets a component slot
*
* @param string The component slot name
*
* @return array The component slot
*/
public function getComponentSlot($name)
{
if (isset($this->componentSlots[$name]) && $this->componentSlots[$name]['module_name'] && $this->componentSlots[$name]['component_name'])
{
return array($this->componentSlots[$name]['module_name'], $this->componentSlots[$name]['component_name']);
}
return null;
}
/**
* Sets the template for this view.
*
* If the template path is relative, it will be based on the currently
* executing module's template sub-directory.
*
* @param string An absolute or relative filesystem path to a template
*/
public function setTemplate($template)
{
if (sfToolkit::isPathAbsolute($template))
{
$this->directory = dirname($template);
$this->template = basename($template);
}
else
{
$this->template = $template;
}
}
/**
* Retrieves the current view extension.
*
* @return string The extension for current view.
*/
public function getExtension()
{
return $this->extension;
}
/**
* Sets an extension for the current view.
*
* @param string The extension name.
*/
public function setExtension($ext)
{
$this->extension = $ext;
}
/**
* Overloads a given method
*
* @param string Method name
* @param string Method arguments
*
* @return mixed User function callback
*
* @throws <b>sfException</b> If the call fails
*/
public function __call($method, $arguments)
{
if (!$callable = sfMixer::getCallable('sfView:'.$method))
{
throw new sfException(sprintf('Call to undefined method sfView::%s', $method));
}
array_unshift($arguments, $this);
return call_user_func_array($callable, $arguments);
}
}

View File

@ -0,0 +1,515 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Cache class to cache the HTML results for actions and templates.
*
* This class uses $cacheClass class to store cache.
* All cache files are stored in files in the [sf_root_dir].'/cache/'.[sf_app].'/html' directory.
* To disable all caching, you can set to false [sf_cache] constant.
*
* @package symfony
* @subpackage view
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfViewCacheManager.class.php 4017 2007-05-16 11:07:18Z fabien $
*/
class sfViewCacheManager
{
protected
$cache = null,
$cacheConfig = array(),
$context = null,
$controller = null,
$loaded = array();
/**
* Initializes the cache manager.
*
* @param sfContext Current application context
* @param sfCache Type of the cache
* @param array Cache parameters
*/
public function initialize($context, $cacheClass, $cacheParameters = array())
{
$this->context = $context;
$this->controller = $context->getController();
// empty configuration
$this->cacheConfig = array();
// create cache instance
$this->cache = new $cacheClass();
$this->cache->initialize($cacheParameters);
// register a named route for our partial cache (at the end)
$r = sfRouting::getInstance();
if (!$r->hasRouteName('sf_cache_partial'))
{
$r->connect('sf_cache_partial', '/sf_cache_partial/:module/:action/:sf_cache_key.', array(), array());
}
}
/**
* Retrieves the current cache context.
*
* @return sfContext The sfContext instance
*/
public function getContext()
{
return $this->context;
}
/**
* Retrieves the current cache type.
*
* @return sfCache The current cache type
*/
public function getCache()
{
return $this->cache;
}
/**
* Generates namespaces for the cache manager
*
* @param string Internal unified resource identifier.
*
* @return array Path and filename for the current namespace
*
* @throws <b>sfException</b> if the generation fails
*/
public function generateNamespace($internalUri)
{
if ($callable = sfConfig::get('sf_cache_namespace_callable'))
{
if (!is_callable($callable))
{
throw new sfException(sprintf('"%s" cannot be called as a function.', var_export($callable, true)));
}
return call_user_func($callable, $internalUri);
}
// generate uri
// we want our URL with / only
$oldUrlFormat = sfConfig::get('sf_url_format');
sfConfig::set('sf_url_format', 'PATH');
if ($this->isContextual($internalUri))
{
list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
$uri = $this->controller->genUrl(sfRouting::getInstance()->getCurrentInternalUri()).sprintf('/%s/%s/%s', $params['module'], $params['action'], $params['sf_cache_key']);
}
else
{
$uri = $this->controller->genUrl($internalUri);
}
sfConfig::set('sf_url_format', $oldUrlFormat);
// prefix with vary headers
$varyHeaders = $this->getVary($internalUri);
if ($varyHeaders)
{
sort($varyHeaders);
$request = $this->getContext()->getRequest();
$vary = '';
foreach ($varyHeaders as $header)
{
$vary .= $request->getHttpHeader($header).'|';
}
$vary = $vary;
}
else
{
$vary = 'all';
}
// prefix with hostname
$request = $this->context->getRequest();
$hostName = $request->getHost();
$hostName = preg_replace('/[^a-z0-9]/i', '_', $hostName);
$hostName = strtolower(preg_replace('/_+/', '_', $hostName));
$uri = '/'.$hostName.'/'.$vary.'/'.$uri;
// replace multiple /
$uri = preg_replace('#/+#', '/', $uri);
return array(dirname($uri), basename($uri));
}
/**
* Adds a cache to the manager.
*
* @param string Module name
* @param string Action name
* @param array Options for the cache
*/
public function addCache($moduleName, $actionName, $options = array())
{
// normalize vary headers
foreach ($options['vary'] as $key => $name)
{
$options['vary'][$key] = strtr(strtolower($name), '_', '-');
}
$options['lifeTime'] = isset($options['lifeTime']) ? $options['lifeTime'] : 0;
if (!isset($this->cacheConfig[$moduleName]))
{
$this->cacheConfig[$moduleName] = array();
}
$this->cacheConfig[$moduleName][$actionName] = array(
'withLayout' => isset($options['withLayout']) ? $options['withLayout'] : false,
'lifeTime' => $options['lifeTime'],
'clientLifeTime' => isset($options['clientLifeTime']) && $options['clientLifeTime'] ? $options['clientLifeTime'] : $options['lifeTime'],
'contextual' => isset($options['contextual']) ? $options['contextual'] : false,
'vary' => isset($options['vary']) ? $options['vary'] : array(),
);
}
/**
* Registers configuration options for the cache.
*
* @param string Module name
*/
public function registerConfiguration($moduleName)
{
if (!isset($this->loaded[$moduleName]))
{
require(sfConfigCache::getInstance()->checkConfig(sfConfig::get('sf_app_module_dir_name').'/'.$moduleName.'/'.sfConfig::get('sf_app_module_config_dir_name').'/cache.yml'));
$this->loaded[$moduleName] = true;
}
}
/**
* Retrieves the layout from the cache option list.
*
* @param string Internal uniform resource identifier
*
* @return boolean true, if have layout otherwise false
*/
public function withLayout($internalUri)
{
return $this->getCacheConfig($internalUri, 'withLayout', false);
}
/**
* Retrieves lifetime from the cache option list.
*
* @param string Internal uniform resource identifier
*
* @return int LifeTime
*/
public function getLifeTime($internalUri)
{
return $this->getCacheConfig($internalUri, 'lifeTime', 0);
}
/**
* Retrieves client lifetime from the cache option list
*
* @param string Internal uniform resource identifier
*
* @return int Client lifetime
*/
public function getClientLifeTime($internalUri)
{
return $this->getCacheConfig($internalUri, 'clientLifeTime', 0);
}
/**
* Retrieves contextual option from the cache option list.
*
* @param string Internal uniform resource identifier
*
* @return boolean true, if is contextual otherwise false
*/
public function isContextual($internalUri)
{
return $this->getCacheConfig($internalUri, 'contextual', false);
}
/**
* Retrieves vary option from the cache option list.
*
* @param string Internal uniform resource identifier
*
* @return array Vary options for the cache
*/
public function getVary($internalUri)
{
return $this->getCacheConfig($internalUri, 'vary', array());
}
/**
* Gets a config option from the cache.
*
* @param string Internal uniform resource identifier
* @param string Option name
* @param string Default value of the option
*
* @return mixed Value of the option
*/
protected function getCacheConfig($internalUri, $key, $defaultValue = null)
{
list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
$value = $defaultValue;
if (isset($this->cacheConfig[$params['module']][$params['action']][$key]))
{
$value = $this->cacheConfig[$params['module']][$params['action']][$key];
}
else if (isset($this->cacheConfig[$params['module']]['DEFAULT'][$key]))
{
$value = $this->cacheConfig[$params['module']]['DEFAULT'][$key];
}
return $value;
}
/**
* Returns true if the current content is cacheable.
*
* @param string Internal uniform resource identifier
*
* @return boolean true, if the content is cacheable otherwise false
*/
public function isCacheable($internalUri)
{
list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
if (isset($this->cacheConfig[$params['module']][$params['action']]))
{
return ($this->cacheConfig[$params['module']][$params['action']]['lifeTime'] > 0);
}
else if (isset($this->cacheConfig[$params['module']]['DEFAULT']))
{
return ($this->cacheConfig[$params['module']]['DEFAULT']['lifeTime'] > 0);
}
return false;
}
/**
* Retrieves namespace for the current cache.
*
* @param string Internal uniform resource identifier
*
* @return string The data of the cache
*/
public function get($internalUri)
{
// no cache or no cache set for this action
if (!$this->isCacheable($internalUri) || $this->ignore())
{
return null;
}
list($namespace, $id) = $this->generateNamespace($internalUri);
$this->cache->setLifeTime($this->getLifeTime($internalUri));
$retval = $this->cache->get($id, $namespace);
if (sfConfig::get('sf_logging_enabled'))
{
$this->getContext()->getLogger()->info(sprintf('{sfViewCacheManager} cache for "%s" %s', $internalUri, ($retval !== null ? 'exists' : 'does not exist')));
}
return $retval;
}
/**
* Returns true if there is a cache.
*
* @param string Internal uniform resource identifier
*
* @return boolean true, if there is a cache otherwise false
*/
public function has($internalUri)
{
if (!$this->isCacheable($internalUri) || $this->ignore())
{
return null;
}
list($namespace, $id) = $this->generateNamespace($internalUri);
$this->cache->setLifeTime($this->getLifeTime($internalUri));
return $this->cache->has($id, $namespace);
}
/**
* Ignores the cache functionality.
*
* @return boolean true, if the cache is ignore otherwise false
*/
protected function ignore()
{
// ignore cache parameter? (only available in debug mode)
if (sfConfig::get('sf_debug') && $this->getContext()->getRequest()->getParameter('_sf_ignore_cache', false, 'symfony/request/sfWebRequest') == true)
{
if (sfConfig::get('sf_logging_enabled'))
{
$this->getContext()->getLogger()->info('{sfViewCacheManager} discard cache');
}
return true;
}
return false;
}
/**
* Sets the cache content
*
* @param string Data to put in the cache
* @param string Internal uniform resource identifier
*
* @return boolean true, if the data get set successfully otherwise false
*/
public function set($data, $internalUri)
{
if (!$this->isCacheable($internalUri))
{
return false;
}
list($namespace, $id) = $this->generateNamespace($internalUri);
try
{
$ret = $this->cache->set($id, $namespace, $data);
}
catch (Exception $e)
{
return false;
}
if (sfConfig::get('sf_logging_enabled'))
{
$this->context->getLogger()->info(sprintf('{sfViewCacheManager} save cache for "%s"', $internalUri));
}
return true;
}
/**
* Removes the cache for the current namespace.
*
* @param string Internal uniform resource identifier
*
* @return boolean true, if the remove happend otherwise false
*/
public function remove($internalUri)
{
list($namespace, $id) = $this->generateNamespace($internalUri);
if (sfConfig::get('sf_logging_enabled'))
{
$this->context->getLogger()->info(sprintf('{sfViewCacheManager} remove cache for "%s"', $internalUri));
}
if ($this->cache->has($id, $namespace))
{
$this->cache->remove($id, $namespace);
}
}
/**
* Retrieves the last modified time.
*
* @param string Internal uniform resource identifier
*
* @return string Last modified datetime for the current namespace
*/
public function lastModified($internalUri)
{
if (!$this->isCacheable($internalUri))
{
return null;
}
list($namespace, $id) = $this->generateNamespace($internalUri);
return $this->cache->lastModified($id, $namespace);
}
/**
* Starts the fragment cache.
*
* @param string Unique fragment name
* @param string Life time for the cache
* @param string Client life time for the cache
* @param array Vary options for the cache
*
* @return boolean true, if success otherwise false
*/
public function start($name, $lifeTime, $clientLifeTime = null, $vary = array())
{
$internalUri = sfRouting::getInstance()->getCurrentInternalUri();
if (!$clientLifeTime)
{
$clientLifeTime = $lifeTime;
}
// add cache config to cache manager
list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
$this->addCache($params['module'], $params['action'], array('withLayout' => false, 'lifeTime' => $lifeTime, 'clientLifeTime' => $clientLifeTime, 'vary' => $vary));
// get data from cache if available
$data = $this->get($internalUri.(strpos($internalUri, '?') ? '&' : '?').'_sf_cache_key='.$name);
if ($data !== null)
{
return $data;
}
else
{
ob_start();
ob_implicit_flush(0);
return null;
}
}
/**
* Stops the fragment cache.
*
* @param string Unique fragment name
*
* @return boolean true, if success otherwise false
*/
public function stop($name)
{
$data = ob_get_clean();
// save content to cache
$internalUri = sfRouting::getInstance()->getCurrentInternalUri();
try
{
$this->set($data, $internalUri.(strpos($internalUri, '?') ? '&' : '?').'_sf_cache_key='.$name);
}
catch (Exception $e)
{
}
return $data;
}
/**
* Executes the shutdown procedure.
*/
public function shutdown()
{
}
}