blic function getLayout() { return $this->getResponse()->getParameter($this->getModuleName().'_'.$this->getActionName().'_layout', null, 'symfony/action/view'); } public function setViewClass($class) { sfConfig::set('mod_'.strtolower($this->getModuleName()).'_view_class', $class); } } abstract class sfActions extends sfAction { public function execute() { $actionToRun = 'execute'.ucfirst($this->getActionName()); if (!is_callable(array($this, $actionToRun))) { $error = 'sfAction initialization failed for module "%s", action "%s". You must create a "%s" method.'; $error = sprintf($error, $this->getModuleName(), $this->getActionName(), $actionToRun); throw new sfInitializationException($error); } if (sfConfig::get('sf_logging_enabled')) { $this->getContext()->getLogger()->info('{sfAction} call "'.get_class($this).'->'.$actionToRun.'()'.'"'); } $ret = $this->$actionToRun(); return $ret; } } class sfActionStack { protected $stack = array(); public function addEntry($moduleName, $actionName, $actionInstance) { $actionEntry = new sfActionStackEntry($moduleName, $actionName, $actionInstance); $this->stack[] = $actionEntry; return $actionEntry; } public function getEntry($index) { $retval = null; if ($index > -1 && $index < count($this->stack)) { $retval = $this->stack[$index]; } return $retval; } public function popEntry() { return array_pop($this->stack); } public function getFirstEntry() { $retval = null; if (isset($this->stack[0])) { $retval = $this->stack[0]; } return $retval; } public function getLastEntry() { $count = count($this->stack); $retval = null; if (isset($this->stack[0])) { $retval = $this->stack[$count - 1]; } return $retval; } public function getSize() { return count($this->stack); } } class sfActionStackEntry { protected $actionInstance = null, $actionName = null, $moduleName = null, $presentation = null, $viewInstance = null; public function __construct($moduleName, $actionName, $actionInstance) { $this->actionName = $actionName; $this->actionInstance = $actionInstance; $this->moduleName = $moduleName; } public function getActionName() { return $this->actionName; } public function getActionInstance() { return $this->actionInstance; } public function getViewInstance() { return $this->viewInstance; } public function setViewInstance($viewInstance) { $this->viewInstance = $viewInstance; } public function getModuleName() { return $this->moduleName; } public function & getPresentation() { return $this->presentation; } public function setPresentation(&$presentation) { $this->presentation =& $presentation; } } abstract class sfController { protected $context = null, $controllerClasses = array(), $maxForwards = 5, $renderMode = sfView::RENDER_CLIENT, $viewCacheClassName = null; public function componentExists($moduleName, $componentName) { return $this->controllerExists($moduleName, $componentName, 'component', false); } public function actionExists($moduleName, $actionName) { return $this->controllerExists($moduleName, $actionName, 'action', false); } protected function controllerExists($moduleName, $controllerName, $extension, $throwExceptions) { $dirs = sfLoader::getControllerDirs($moduleName); foreach ($dirs as $dir => $checkEnabled) { if ($checkEnabled && !in_array($moduleName, sfConfig::get('sf_enabled_modules')) && is_readable($dir)) { $error = 'The module "%s" is not enabled.'; $error = sprintf($error, $moduleName); throw new sfConfigurationException($error); } $classFile = strtolower($extension); $classSuffix = ucfirst(strtolower($extension)); $file = $dir.'/'.$controllerName.$classSuffix.'.class.php'; if (is_readable($file)) { require_once($file); $this->controllerClasses[$moduleName.'_'.$controllerName.'_'.$classSuffix] = $controllerName.$classSuffix; return true; } $module_file = $dir.'/'.$classFile.'s.class.php'; if (is_readable($module_file)) { require_once($module_file); if (!class_exists($moduleName.$classSuffix.'s', false)) { if ($throwExceptions) { throw new sfControllerException(sprintf('There is no "%s" class in your action file "%s".', $moduleName.$classSuffix.'s', $module_file)); } return false; } if (!in_array('execute'.ucfirst($controllerName), get_class_methods($moduleName.$classSuffix.'s'))) { if ($throwExceptions) { throw new sfControllerException(sprintf('There is no "%s" method in your action class "%s"', 'execute'.ucfirst($controllerName), $moduleName.$classSuffix.'s')); } return false; } $this->controllerClasses[$moduleName.'_'.$controllerName.'_'.$classSuffix] = $moduleName.$classSuffix.'s'; return true; } } if ($throwExceptions && sfConfig::get('sf_debug')) { $dirs = array_keys($dirs); foreach ($dirs as &$dir) { $dir = str_replace(sfConfig::get('sf_root_dir'), '%SF_ROOT_DIR%', $dir); } throw new sfControllerException(sprintf('{sfController} controller "%s/%s" does not exist in: %s', $moduleName, $controllerName, implode(', ', $dirs))); } return false; } public function forward($moduleName, $actionName) { $moduleName = preg_replace('/[^a-z0-9\-_]+/i', '', $moduleName); $actionName = preg_replace('/[^a-z0-9\-_]+/i', '', $actionName); if ($this->getActionStack()->getSize() >= $this->maxForwards) { $error = 'Too many forwards have been detected for this request (> %d)'; $error = sprintf($error, $this->maxForwards); throw new sfForwardException($error); } $rootDir = sfConfig::get('sf_root_dir'); $app = sfConfig::get('sf_app'); $env = sfConfig::get('sf_environment'); if (!sfConfig::get('sf_available') || sfToolkit::hasLockFile($rootDir.'/'.$app.'_'.$env.'.clilock')) { $moduleName = sfConfig::get('sf_unavailable_module'); $actionName = sfConfig::get('sf_unavailable_action'); if (!$this->actionExists($moduleName, $actionName)) { $error = 'Invalid configuration settings: [sf_unavailable_module] "%s", [sf_unavailable_action] "%s"'; $error = sprintf($error, $moduleName, $actionName); throw new sfConfigurationException($error); } } sfConfigCache::getInstance()->import(sfConfig::get('sf_app_module_dir_name').'/'.$moduleName.'/'.sfConfig::get('sf_app_module_config_dir_name').'/generator.yml', true, true); if (!$this->actionExists($moduleName, $actionName)) { if (sfConfig::get('sf_logging_enabled')) { $this->getContext()->getLogger()->info('{sfController} action does not exist'); } $this->context->getRequest()->setAttribute('requested_action', $actionName); $this->context->getRequest()->setAttribute('requested_module', $moduleName); $moduleName = sfConfig::get('sf_error_404_module'); $actionName = sfConfig::get('sf_error_404_action'); if (!$this->actionExists($moduleName, $actionName)) { $error = 'Invalid configuration settings: [sf_error_404_module] "%s", [sf_error_404_action] "%s"'; $error = sprintf($error, $moduleName, $actionName); throw new sfConfigurationException($error); } } $actionInstance = $this->getAction($moduleName, $actionName); $this->getActionStack()->addEntry($moduleName, $actionName, $actionInstance); require(sfConfigCache::getInstance()->checkConfig(sfConfig::get('sf_app_module_dir_name').'/'.$moduleName.'/'.sfConfig::get('sf_app_module_config_dir_name').'/module.yml')); if ($this->getActionStack()->getSize() == 1 && sfConfig::get('mod_'.strtolower($moduleName).'_is_internal') && !sfConfig::get('sf_test')) { $error = 'Action "%s" from module "%s" cannot be called directly'; $error = sprintf($error, $actionName, $moduleName); throw new sfConfigurationException($error); } if (sfConfig::get('mod_'.strtolower($moduleName).'_enabled')) { $moduleConfig = sfConfig::get('sf_app_module_dir').'/'.$moduleName.'/'.sfConfig::get('sf_app_module_config_dir_name').'/config.php'; if (is_readable($moduleConfig)) { require_once($moduleConfig); } if ($actionInstance->initialize($this->context)) { $filterChain = new sfFilterChain(); $this->loadFilters($filterChain, $actionInstance); if ($moduleName == sfConfig::get('sf_error_404_module') && $actionName == sfConfig::get('sf_error_404_action')) { $this->getContext()->getResponse()->setStatusCode(404); $this->getContext()->getResponse()->setHttpHeader('Status', '404 Not Found'); foreach (sfMixer::getCallables('sfController:forward:error404') as $callable) { call_user_func($callable, $this, $moduleName, $actionName); } } if (sfConfig::get('sf_i18n')) { $this->context->getI18N()->setMessageSourceDir(sfLoader::getI18NDir($moduleName), $this->context->getUser()->getCulture()); } $filterChain->execute(); } else { $error = 'Action initialization failed for module "%s", action "%s"'; $error = sprintf($error, $moduleName, $actionName); throw new sfInitializationException($error); } } else { $moduleName = sfConfig::get('sf_module_disabled_module'); $actionName = sfConfig::get('sf_module_disabled_action'); if (!$this->actionExists($moduleName, $actionName)) { $error = 'Invalid configuration settings: [sf_module_disabled_module] "%s", [sf_module_disabled_action] "%s"'; $error = sprintf($error, $moduleName, $actionName); throw new sfConfigurationException($error); } $this->forward($moduleName, $actionName); } } public function getAction($moduleName, $actionName) { return $this->getController($moduleName, $actionName, 'action'); } public function getComponent($moduleName, $componentName) { return $this->getController($moduleName, $componentName, 'component'); } protected function getController($moduleName, $controllerName, $extension) { $classSuffix = ucfirst(strtolower($extension)); if (!isset($this->controllerClasses[$moduleName.'_'.$controllerName.'_'.$classSuffix])) { $this->controllerExists($moduleName, $controllerName, $extension, true); } $class = $this->controllerClasses[$moduleName.'_'.$controllerName.'_'.$classSuffix]; $moduleClass = $moduleName.'_'.$class; if (class_exists($moduleClass, false)) { $class = $moduleClass; } return new $class(); } public function getActionStack() { return $this->context->getActionStack(); } public function getContext() { return $this->context; } public function getRenderMode() { return $this->renderMode; } public function getView($moduleName, $actionName, $viewName) { $file = sfConfig::get('sf_app_module_dir').'/'.$moduleName.'/'.sfConfig::get('sf_app_module_view_dir_name').'/'.$actionName.$viewName.'View.class.php'; if (is_readable($file)) { require_once($file); $class = $actionName.$viewName.'View'; $moduleClass = $moduleName.'_'.$class; if (class_exists($moduleClass, false)) { $class = $moduleClass; } } else { $viewName = $this->getContext()->getRequest()->getAttribute($moduleName.'_'.$actionName.'_view_name', sfConfig::get('mod_'.strtolower($moduleName).'_view_class'), 'symfony/action/view'); $class = sfCore::getClassPath($viewName.'View') ? $viewName.'View' : 'sfPHPView'; } return new $class(); } public function initialize($context) { $this->context = $context; if (sfConfig::get('sf_logging_enabled')) { $this->context->getLogger()->info('{sfController} initialization'); } $this->maxForwards = sfConfig::get('sf_max_forwards'); } public static function newInstance($class) { try { $object = new $class(); if (!($object instanceof sfController)) { $error = 'Class "%s" is not of the type sfController'; $error = sprintf($error, $class); throw new sfFactoryException($error); } return $object; } catch (sfException $e) { $e->printStackTrace(); } } public function sendEmail($module, $action) { return $this->getPresentationFor($module, $action, 'sfMail'); } public function getPresentationFor($module, $action, $viewName = null) { if (sfConfig::get('sf_logging_enabled')) { $this->getContext()->getLogger()->info('{sfController} get presentation for action "'.$module.'/'.$action.'" (view class: "'.$viewName.'")'); } $renderMode = $this->getRenderMode(); $this->setRenderMode(sfView::RENDER_VAR); $actionStack = $this->getActionStack(); $index = $actionStack->getSize(); if ($viewName) { $this->getContext()->getRequest()->setAttribute($module.'_'.$action.'_view_name', $viewName, 'symfony/action/view'); } $this->forward($module, $action); $actionEntry = $actionStack->getEntry($index); $presentation =& $actionEntry->getPresentation(); $this->setRenderMode($renderMode); $nb = $actionStack->getSize() - $index; while ($nb-- > 0) { $actionEntry = $actionStack->popEntry(); if ($actionEntry->getModuleName() == sfConfig::get('sf_login_module') && $actionEntry->getActionName() == sfConfig::get('sf_login_action')) { $error = 'Your mail action is secured but the user is not authenticated.'; throw new sfException($error); } else if ($actionEntry->getModuleName() == sfConfig::get('sf_secure_module') && $actionEntry->getActionName() == sfConfig::get('sf_secure_action')) { $error = 'Your mail action is secured but the user does not have access.'; throw new sfException($error); } } if ($viewName) { $this->getContext()->getRequest()->getAttributeHolder()->remove($module.'_'.$action.'_view_name', 'symfony/action/view'); } return $presentation; } public function setRenderMode($mode) { if ($mode == sfView::RENDER_CLIENT || $mode == sfView::RENDER_VAR || $mode == sfView::RENDER_NONE) { $this->renderMode = $mode; return; } $error = 'Invalid rendering mode: %s'; $error = sprintf($error, $mode); throw new sfRenderException($error); } public function inCLI() { return 0 == strncasecmp(PHP_SAPI, 'cli', 3); } public function loadFilters($filterChain, $actionInstance) { $moduleName = $this->context->getModuleName(); require(sfConfigCache::getInstance()->checkConfig(sfConfig::get('sf_app_module_dir_name').'/'.$moduleName.'/'.sfConfig::get('sf_app_module_config_dir_name').'/filters.yml')); } public function __call($method, $arguments) { if (!$callable = sfMixer::getCallable('sfController:'.$method)) { throw new sfException(sprintf('Call to undefined method sfController::%s', $method)); } array_unshift($arguments, $this); return call_user_func_array($callable, $arguments); } } class sfDatabaseManager { protected $databases = array(); public function getDatabase($name = 'default') { if (isset($this->databases[$name])) { return $this->databases[$name]; } $error = 'Database "%s" does not exist'; $error = sprintf($error, $name); throw new sfDatabaseException($error); } public function initialize() { $database = new sfPropelDatabase(); $database->initialize(array ( 'dsn' => 'mysql://ted_dev:PH54PHBa@192.168.1.119/ted_dev', ), 'propel'); $this->databases['propel'] = $database; } public function shutdown() { foreach ($this->databases as $database) { $database->shutdown(); } } } abstract class sfFilter { protected $parameterHolder = null, $context = null; public static $filterCalled = array(); protected function isFirstCall() { $class = get_class($this); if (isset(self::$filterCalled[$class])) { return false; } else { self::$filterCalled[$class] = true; return true; } } public final function getContext() { return $this->context; } public function initialize($context, $parameters = array()) { $this->context = $context; $this->parameterHolder = new sfParameterHolder(); $this->parameterHolder->add($parameters); return true; } public function getParameterHolder() { return $this->parameterHolder; } public function getParameter($name, $default = null, $ns = null) { return $this->parameterHolder->get($name, $default, $ns); } public function hasParameter($name, $ns = null) { return $this->parameterHolder->has($name, $ns); } public function setParameter($name, $value, $ns = null) { return $this->parameterHolder->set($name, $value, $ns); } } class sfCommonFilter extends sfFilter { public function execute($filterChain) { $filterChain->execute(); $response = $this->getContext()->getResponse(); $content = $response->getContent(); if (false !== ($pos = strpos($content, ''))) { sfLoader::loadHelpers(array('Tag', 'Asset')); $html = ''; if (!$response->getParameter('javascripts_included', false, 'symfony/view/asset')) { $html .= get_javascripts($response); } if (!$response->getParameter('stylesheets_included', false, 'symfony/view/asset')) { $html .= get_stylesheets($response); } if ($html) { $response->setContent(substr($content, 0, $pos).$html.substr($content, $pos)); } } $response->setParameter('javascripts_included', false, 'symfony/view/asset'); $response->setParameter('stylesheets_included', false, 'symfony/view/asset'); } } class sfExecutionFilter extends sfFilter { public function execute($filterChain) { $context = $this->getContext(); $controller = $context->getController(); $actionEntry = $controller->getActionStack()->getLastEntry(); $actionInstance = $actionEntry->getActionInstance(); $moduleName = $context->getModuleName(); $actionName = $context->getActionName(); $method = $context->getRequest()->getMethod(); $viewName = null; if (sfConfig::get('sf_cache')) { $uri = sfRouting::getInstance()->getCurrentInternalUri(); if (null !== $context->getResponse()->getParameter($uri.'_action', null, 'symfony/cache')) { $viewName = sfView::SUCCESS; } } if (!$viewName) { if (($actionInstance->getRequestMethods() & $method) != $method) { $viewName = $actionInstance->getDefaultView(); } else { $validated = true; $validationConfig = $moduleName.'/'.sfConfig::get('sf_app_module_validate_dir_name').'/'.$actionName.'.yml'; if (null !== $validateFile = sfConfigCache::getInstance()->checkConfig(sfConfig::get('sf_app_module_dir_name').'/'.$validationConfig, true)) { $validatorManager = new sfValidatorManager(); $validatorManager->initialize($context); require($validateFile); $validated = $validatorManager->execute(); } $validateToRun = 'validate'.ucfirst($actionName); $manualValidated = method_exists($actionInstance, $validateToRun) ? $actionInstance->$validateToRun() : $actionInstance->validate(); $validated = ($manualValidated && $validated) || ($manualValidated && !$validated && !$context->getRequest()->hasErrors()); if (null !== ($parameters = $context->getRequest()->getAttribute('fillin', null, 'symfony/filter'))) { $this->registerFillInFilter($filterChain, $parameters); } if ($validated) { if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) { $timer = sfTimerManager::getTimer(sprintf('Action "%s/%s"', $moduleName, $actionName)); } $actionInstance->preExecute(); $viewName = $actionInstance->execute(); if ($viewName == '') { $viewName = sfView::SUCCESS; } $actionInstance->postExecute(); if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) { $timer->addTime(); } } else { if (sfConfig::get('sf_logging_enabled')) { $this->context->getLogger()->info('{sfFilter} action validation failed'); } $handleErrorToRun = 'handleError'.ucfirst($actionName); $viewName = method_exists($actionInstance, $handleErrorToRun) ? $actionInstance->$handleErrorToRun() : $actionInstance->handleError(); if ($viewName == '') { $viewName = sfView::ERROR; } } } } if ($viewName == sfView::HEADER_ONLY) { $context->getResponse()->setHeaderOnly(true); $filterChain->execute(); } else if ($viewName != sfView::NONE) { if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) { $timer = sfTimerManager::getTimer(sprintf('View "%s" for "%s/%s"', $viewName, $moduleName, $actionName)); } $viewInstance = $controller->getView($moduleName, $actionName, $viewName); $viewInstance->initialize($context, $moduleName, $actionName, $viewName); $viewInstance->execute(); $viewData = $viewInstance->render(); if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) { $timer->addTime(); } if ($controller->getRenderMode() == sfView::RENDER_VAR) { $actionEntry->setPresentation($viewData); } else { $filterChain->execute(); } } } protected function registerFillInFilter($filterChain, $parameters) { if (isset($parameters['enabled']) && $parameters['enabled'] && !$filterChain->hasFilter('sfFillInFormFilter')) { $fillInFormFilter = new sfFillInFormFilter(); $fillInFormFilter->initialize($this->context, isset($parameters['param']) ? $parameters['param'] : array()); $filterChain->register($fillInFormFilter); } } } class sfRenderingFilter extends sfFilter { public function execute($filterChain) { $filterChain->execute(); if (sfConfig::get('sf_logging_enabled')) { $this->getContext()->getLogger()->info('{sfFilter} render to client'); } $response = $this->getContext()->getResponse(); $response->sendHttpHeaders(); $response->sendContent(); if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) { $logger = $this->getContext()->getLogger(); foreach (sfTimerManager::getTimers() as $name => $timer) { $logger->info(sprintf('{sfTimerManager} %s %.2f ms (%d)', $name, $timer->getElapsedTime() * 1000, $timer->getCalls())); } } } } class sfFilterChain { protected $chain = array(), $index = -1; public function execute() { ++$this->index; if ($this->index < count($this->chain)) { if (sfConfig::get('sf_logging_enabled')) { sfContext::getInstance()->getLogger()->info(sprintf('{sfFilter} executing filter "%s"', get_class($this->chain[$this->index]))); } $this->chain[$this->index]->execute($this); } } public function hasFilter($class) { foreach ($this->chain as $filter) { if ($filter instanceof $class) { return true; } } return false; } public function register($filter) { $this->chain[] = $filter; } } abstract class sfRequest { const GET = 2; const NONE = 1; const POST = 4; const PUT = 5; const DELETE = 6; const HEAD = 7; protected $errors = array(), $context = null, $method = null, $parameterHolder = null, $config = null, $attributeHolder = null; public function & extractParameters($names) { $array = array(); $parameters =& $this->parameterHolder->getAll(); foreach ($parameters as $key => &$value) { if (in_array($key, $names)) { $array[$key] =& $value; } } return $array; } public function getError($name, $catalogue = 'messages') { $retval = null; if (isset($this->errors[$name])) { $retval = $this->errors[$name]; } if (sfConfig::get('sf_i18n')) { $retval = $this->context->getI18N()->__($retval, null, $catalogue); } return $retval; } public function getErrorNames() { return array_keys($this->errors); } public function getErrors() { return $this->errors; } public function getMethod() { return $this->method; } public function hasError($name) { return isset($this->errors[$name]); } public function hasErrors() { return (count($this->errors) > 0); } public function initialize($context, $parameters = array(), $attributes = array()) { $this->context = $context; $this->parameterHolder = new sfParameterHolder(); $this->attributeHolder = new sfParameterHolder(); $this->parameterHolder->add($parameters); $this->attributeHolder->add($attributes); } public function getContext() { return $this->context; } public static function newInstance($class) { $object = new $class(); if (!($object instanceof sfRequest)) { $error = 'Class "%s" is not of the type sfRequest'; $error = sprintf($error, $class); throw new sfFactoryException($error); } return $object; } public function & removeError($name) { $retval = null; if (isset($this->errors[$name])) { $retval =& $this->errors[$name]; unset($this->errors[$name]); } return $retval; } public function setError($name, $message) { if (sfConfig::get('sf_logging_enabled')) { $this->getContext()->getLogger()->info('{sfRequest} error in form for parameter "'.$name.'" (with message "'.$message.'")'); } $this->errors[$name] = $message; } public function setErrors($errors) { $this->errors = array_merge($this->errors, $errors); } public function setMethod($methodCode) { $available_methods = array(self::GET, self::POST, self::PUT, self::DELETE, self::HEAD, self::NONE); if (in_array($methodCode, $available_methods)) { $this->method = $methodCode; return; } $error = 'Invalid request method: %s'; $error = sprintf($error, $methodCode); throw new sfException($error); } public function getParameterHolder() { return $this->parameterHolder; } public function getAttributeHolder() { return $this->attributeHolder; } public function getAttribute($name, $default = null, $ns = null) { return $this->attributeHolder->get($name, $default, $ns); } public function hasAttribute($name, $ns = null) { return $this->attributeHolder->has($name, $ns); } public function setAttribute($name, $value, $ns = null) { $this->attributeHolder->set($name, $value, $ns); } public function getParameter($name, $default = null, $ns = null) { return $this->parameterHolder->get($name, $default, $ns); } public function hasParameter($name, $ns = null) { return $this->parameterHolder->has($name, $ns); } public function setParameter($name, $value, $ns = null) { $this->parameterHolder->set($name, $value, $ns); } abstract function shutdown(); public function __call($method, $arguments) { if (!$callable = sfMixer::getCallable('sfRequest:'.$method)) { throw new sfException(sprintf('Call to undefined method sfRequest::%s', $method)); } array_unshift($arguments, $this); return call_user_func_array($callable, $arguments); } } abstract class sfResponse { protected $parameterHolder = null, $context = null, $content = ''; public function initialize($context, $parameters = array()) { $this->context = $context; $this->parameterHolder = new sfParameterHolder(); $this->parameterHolder->add($parameters); } public function setContext($context) { $this->context = $context; } public function getContext() { return $this->context; } public static function newInstance($class) { $object = new $class(); if (!($object instanceof sfResponse)) { $error = 'Class "%s" is not of the type sfResponse'; $error = sprintf($error, $class); throw new sfFactoryException($error); } return $object; } public function setContent($content) { $this->content = $content; } public function getContent() { return $this->content; } public function sendContent() { if (sfConfig::get('sf_logging_enabled')) { $this->getContext()->getLogger()->info('{sfResponse} send content ('.strlen($this->content).' o)'); } echo $this->content; } public function getParameterHolder() { return $this->parameterHolder; } public function getParameter($name, $default = null, $ns = null) { return $this->parameterHolder->get($name, $default, $ns); } public function hasParameter($name, $ns = null) { return $this->parameterHolder->has($name, $ns); } public function setParameter($name, $value, $ns = null) { $this->parameterHolder->set($name, $value, $ns); } abstract function shutdown(); public function __call($method, $arguments) { if (!$callable = sfMixer::getCallable('sfResponse:'.$method)) { throw new sfException(sprintf('Call to undefined method sfResponse::%s', $method)); } array_unshift($arguments, $this); return call_user_func_array($callable, $arguments); } } abstract class sfStorage { protected $parameterHolder = null, $context = null; public function getContext() { return $this->context; } public function initialize($context, $parameters = array()) { $this->context = $context; $this->parameterHolder = new sfParameterHolder(); $this->getParameterHolder()->add($parameters); } public static function newInstance($class) { $object = new $class(); if (!($object instanceof sfStorage)) { $error = 'Class "%s" is not of the type sfStorage'; $error = sprintf($error, $class); throw new sfFactoryException($error); } return $object; } abstract function & read($key); abstract function & remove($key); abstract function shutdown(); abstract function write($key, &$data); public function getParameterHolder() { return $this->parameterHolder; } public function getParameter($name, $default = null, $ns = null) { return $this->parameterHolder->get($name, $default, $ns); } public function hasParameter($name, $ns = null) { return $this->parameterHolder->has($name, $ns); } public function setParameter($name, $value, $ns = null) { return $this->parameterHolder->set($name, $value, $ns); } } class sfUser { const ATTRIBUTE_NAMESPACE = 'symfony/user/sfUser/attributes'; const CULTURE_NAMESPACE = 'symfony/user/sfUser/culture'; protected $parameterHolder = null, $attributeHolder = null, $culture = null, $context = null; public function getContext() { return $this->context; } public function initialize($context, $parameters = array()) { $this->context = $context; $this->parameterHolder = new sfParameterHolder(); $this->parameterHolder->add($parameters); $this->attributeHolder = new sfParameterHolder(self::ATTRIBUTE_NAMESPACE); $attributes = $context->getStorage()->read(self::ATTRIBUTE_NAMESPACE); if (is_array($attributes)) { foreach ($attributes as $namespace => $values) { $this->attributeHolder->add($values, $namespace); } } if (!($culture = $context->getRequest()->getParameter('sf_culture'))) { if (null === ($culture = $context->getStorage()->read(self::CULTURE_NAMESPACE))) { $culture = sfConfig::get('sf_i18n_default_culture', 'en'); } } $this->setCulture($culture); } public static function newInstance($class) { $object = new $class(); if (!($object instanceof sfUser)) { $error = 'Class "%s" is not of the type sfUser'; $error = sprintf($error, $class); throw new sfFactoryException($error); } return $object; } public function setCulture($culture) { if ($this->culture != $culture) { $this->culture = $culture; if (sfConfig::get('sf_i18n')) { $this->context->getI18N()->setCulture($culture); } sfConfig::set('sf_routing_defaults', array_merge((array) sfConfig::get('sf_routing_defaults'), array('sf_culture' => $culture))); } } public function getCulture() { return $this->culture; } public function getParameterHolder() { return $this->parameterHolder; } public function getAttributeHolder() { return $this->attributeHolder; } public function getAttribute($name, $default = null, $ns = null) { return $this->attributeHolder->get($name, $default, $ns); } public function hasAttribute($name, $ns = null) { return $this->attributeHolder->has($name, $ns); } public function setAttribute($name, $value, $ns = null) { return $this->attributeHolder->set($name, $value, $ns); } public function getParameter($name, $default = null, $ns = null) { return $this->parameterHolder->get($name, $default, $ns); } public function hasParameter($name, $ns = null) { return $this->parameterHolder->has($name, $ns); } public function setParameter($name, $value, $ns = null) { return $this->parameterHolder->set($name, $value, $ns); } public function shutdown() { $storage = $this->getContext()->getStorage(); $attributes = array(); foreach ($this->attributeHolder->getNamespaces() as $namespace) { $attributes[$namespace] = $this->attributeHolder->getAll($namespace); } $storage->write(self::ATTRIBUTE_NAMESPACE, $attributes); $storage->write(self::CULTURE_NAMESPACE, $this->culture); session_write_close(); } public function __call($method, $arguments) { if (!$callable = sfMixer::getCallable('sfUser:'.$method)) { throw new sfException(sprintf('Call to undefined method sfUser::%s', $method)); } array_unshift($arguments, $this); return call_user_func_array($callable, $arguments); } } class sfContext { protected $actionStack = null, $controller = null, $databaseManager = null, $request = null, $response = null, $storage = null, $viewCacheManager = null, $i18n = null, $logger = null, $user = null; protected static $instance = null; public static function removeInstance() { self::$instance = null; } protected function initialize() { $this->logger = sfLogger::getInstance(); if (sfConfig::get('sf_logging_enabled')) { $this->logger->info('{sfContext} initialization'); } if (sfConfig::get('sf_use_database')) { $this->databaseManager = new sfDatabaseManager(); $this->databaseManager->initialize(); } $this->actionStack = new sfActionStack(); $this->controller = sfController::newInstance(sfConfig::get('sf_factory_controller', 'sfFrontWebController')); $this->request = sfRequest::newInstance(sfConfig::get('sf_factory_request', 'sfWebRequest')); $this->response = sfResponse::newInstance(sfConfig::get('sf_factory_response', 'sfWebResponse')); $this->storage = sfStorage::newInstance(sfConfig::get('sf_factory_storage', 'sfMySQLSessionStorage')); $this->user = sfUser::newInstance(sfConfig::get('sf_factory_user', 'sfGuardSecurityUser')); $this->controller->initialize($this); $this->request->initialize($this, sfConfig::get('sf_factory_request_parameters', NULL), sfConfig::get('sf_factory_request_attributes', array())); $this->response->initialize($this, sfConfig::get('sf_factory_response_parameters', NULL)); $this->storage->initialize($this, sfConfig::get('sf_factory_storage_parameters', array ( 'session_name' => 'symfony', 'database' => 'propel', 'session_cookie_domain' => '.ted.com', 'db_table' => 'session_storage', 'db_data_col' => 'session_data', 'db_id_col' => 'session_id', 'db_time_col' => 'session_time', ))); $this->user->initialize($this, sfConfig::get('sf_factory_user_parameters', NULL)); if (sfConfig::get('sf_cache')) { $this->viewCacheManager = new sfViewCacheManager(); $this->viewCacheManager->initialize($this, sfConfig::get('sf_factory_view_cache', 'sfMemcacheCache'), sfConfig::get('sf_factory_view_cache_parameters', array ( 'automaticCleaningFactor' => 0, 'cacheDir' => '/var/www/vhosts/ted.com/httpdocs/cache/frontend/prod/template', ))); } register_shutdown_function(array($this, 'shutdown')); } public static function getInstance() { if (!isset(self::$instance)) { $class = __CLASS__; self::$instance = new $class(); self::$instance->initialize(); } return self::$instance; } public static function hasInstance() { return isset(self::$instance); } public function getActionName() { if ($this->actionStack && $lastEntry = $this->actionStack->getLastEntry()) { return $lastEntry->getActionName(); } } public function getActionStack() { return $this->actionStack; } public function getController() { return $this->controller; } public function getLogger() { return $this->logger; } public function getDatabaseConnection($name = 'default') { if ($this->databaseManager != null) { return $this->databaseManager->getDatabase($name)->getConnection(); } return null; } public function retrieveObjects($class, $peerMethod) { $retrievingClass = 'sf'.ucfirst(sfConfig::get('sf_orm', 'propel')).'DataRetriever'; return call_user_func(array($retrievingClass, 'retrieveObjects'), $class, $peerMethod); } public function getDatabaseManager() { return $this->databaseManager; } public function getModuleDirectory() { if ($this->actionStack && $lastEntry = $this->actionStack->getLastEntry()) { return sfConfig::get('sf_app_module_dir').'/'.$lastEntry->getModuleName(); } } public function getModuleName() { if ($this->actionStack && $lastEntry = $this->actionStack->getLastEntry()) { return $lastEntry->getModuleName(); } } public function getCurrentViewInstance() { if ($this->actionStack && $lastEntry = $this->actionStack->getLastEntry()) { return $lastEntry->getViewInstance(); } } public function getRequest() { return $this->request; } public function getResponse() { return $this->response; } public function setResponse($response) { $this->response = $response; } public function getStorage() { return $this->storage; } public function getViewCacheManager() { return $this->viewCacheManager; } public function getI18N() { if (!$this->i18n && sfConfig::get('sf_i18n')) { $this->i18n = sfI18N::getInstance(); $this->i18n->initialize($this); } return $this->i18n; } public function getUser() { return $this->user; } public function shutdown() { $this->getUser()->shutdown(); $this->getStorage()->shutdown(); $this->getRequest()->shutdown(); $this->getResponse()->shutdown(); if (sfConfig::get('sf_logging_enabled')) { $this->getLogger()->shutdown(); } if (sfConfig::get('sf_use_database')) { $this->getDatabaseManager()->shutdown(); } if (sfConfig::get('sf_cache')) { $this->getViewCacheManager()->shutdown(); } } } class sfValidatorManager { protected $groups = array(), $names = array(), $request = null; public function clear() { $this->groups = null; $this->groups = array(); $this->names = null; $this->names = array(); } public function execute() { if (sfConfig::get('sf_logging_enabled')) { sfContext::getInstance()->getLogger()->info('{sfValidator} validation execution'); } $retval = true; $pass = 1; while (true) { foreach ($this->names as $name => &$data) { if (isset($data['_is_parent'])) { foreach ($data as $subname => &$subdata) { if ($subname == '_is_parent') { continue; } if ($subdata['validation_status'] == true && !$this->validate($subname, $subdata, $name)) { $retval = false; } } } else { if ($data['validation_status'] == true && !$this->validate($name, $data, null)) { $retval = false; } } } if (count($this->groups) == 0 || $pass == 2) { break; } ++$pass; } return $retval; } public function initialize($context) { $this->request = $context->getRequest(); } public function registerName($name, $required = true, $message = 'Required', $parent = null, $group = null, $isFile = false) { $entry = array(); $entry['group'] = null; $entry['is_file'] = $isFile; $entry['required'] = $required; $entry['required_msg'] = $message; $entry['validation_status'] = true; $entry['validators'] = array(); if ($parent != null) { if (!isset($this->names[$parent])) { $this->names[$parent] = array('_is_parent' => true); } $this->names[$parent][$name] =& $entry; } else { $this->names[$name] =& $entry; } if ($group != null) { if (!isset($this->groups[$group])) { $this->groups[$group] = array('_force' => false); } $this->groups[$group][] = $name; $entry['group'] =& $this->groups[$group]; } } public function registerValidator($name, $validator, $parent = null) { if ($parent != null) { $this->names[$parent][$name]['validators'][] = $validator; } else { $this->names[$name]['validators'][] = $validator; } } protected function validate(&$name, &$data, $parent) { $error = null; $errorName = null; $force = null !== $data['group'] ? $data['group']['_force'] : false; $retval = true; $value = null; if ($parent == null) { $errorName = $name; if ($data['is_file']) { $value = $this->request->getFile($name); } else { $value = $this->request->getParameterHolder()->get($name); } } else { $errorName = $parent.'{'.$name.'}'; if ($data['is_file']) { $parent = $this->request->getFile($parent.'['.$name.']'); if ($parent != null) { $value = $parent; } } else { $parent = $this->request->getParameterHolder()->get($parent); if ($parent != null && isset($parent[$name])) { $value = $parent[$name]; } } } if ( ($data['is_file'] && !$value['name']) || (!$data['is_file'] && (is_array($value) ? sfToolkit::isArrayValuesEmpty($value) : ($value == null || strlen($value) == 0))) ) { if ($data['required'] || $force) { $error = $data['required_msg']; $retval = false; } else { $retval = true; } } else { $error = null; if ($data['group'] != null) { $data['group']['_force'] = true; } if (count($data['validators']) > 0) { foreach ($data['validators'] as $validator) { if (!$validator->execute($value, $error)) { $retval = false; break; } } } } if (!$retval) { $data['validation_status'] = false; $this->request->setError($errorName, $error); } return $retval; } } abstract class sfView { const ALERT = 'Alert'; const ERROR = 'Error'; const INPUT = 'Input'; const NONE = 'None'; const SUCCESS = 'Success'; const HEADER_ONLY = 'Headers'; const RENDER_CLIENT = 2; const RENDER_NONE = 1; 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'; abstract function execute(); abstract function configure(); public final function getContext() { return $this->context; } public function getDecoratorDirectory() { return $this->decoratorDirectory; } public function getDecoratorTemplate() { return $this->decoratorTemplate; } public function getDirectory() { return $this->directory; } abstract function getEngine(); public function getTemplate() { return $this->template; } public function getEscaping() { return null === $this->escaping ? sfConfig::get('sf_escaping_strategy') : $this->escaping; } 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); } public function importAttributes($names, $files = false, $errors = true, $stripTags = true, $specialChars = true) { $request = $this->context->getRequest(); if ($files) { $array =& $request->getFiles(); } else { $array =& $request->getParameterHolder()->getAll(); } foreach ($names as &$name) { if (preg_match('/^([a-z0-9\-_]+)\{([a-z0-9\s\-_]+)\}$/i', $name, $match)) { $parent = $match[1]; $subname = $match[2]; 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 { $this->setAttribute($name, ''); } } else { if (isset($array[$name])) { $value = $array[$name]; if ($stripTags) $value = strip_tags($value); if ($specialChars) $value = htmlspecialchars($value); $this->setAttribute($name, $value); } else { $this->setAttribute($name, ''); } } if ($errors) { if ($request->hasError($name)) { $this->setAttribute($name.'_error', $request->getError($name)); } else { $this->setAttribute($name.'_error', ''); } } } } 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'); $this->configure(); return true; } public function getAttributeHolder() { return $this->attributeHolder; } public function getAttribute($name, $default = null, $ns = null) { return $this->attributeHolder->get($name, $default, $ns); } public function hasAttribute($name, $ns = null) { return $this->attributeHolder->has($name, $ns); } public function setAttribute($name, $value, $ns = null) { $this->attributeHolder->set($name, $value, $ns); } public function getParameterHolder() { return $this->parameterHolder; } public function getParameter($name, $default = null, $ns = null) { return $this->parameterHolder->get($name, $default, $ns); } public function hasParameter($name, $ns = null) { return $this->parameterHolder->has($name, $ns); } public function setParameter($name, $value, $ns = null) { $this->parameterHolder->set($name, $value, $ns); } public function isDecorator() { return $this->decorator; } public function setDecorator($boolean) { $this->decorator = (boolean) $boolean; } protected function preRenderCheck() { if ($this->template == null) { $error = 'A template has not been set'; throw new sfRenderException($error); } $template = $this->directory.'/'.$this->template; if (!is_readable($template)) { throw new sfRenderException(sprintf('The template "%s" does not exist in: %s', $template, $this->directory)); } if ($this->decorator) { $template = $this->decoratorDirectory.'/'.$this->decoratorTemplate; if (!is_readable($template)) { $error = 'The decorator template "%s" does not exist or is unreadable'; $error = sprintf($error, $template); throw new sfRenderException($error); } } } abstract function render($templateVars = null); public function setDecoratorDirectory($directory) { $this->decoratorDirectory = $directory; } public function setEscaping($escaping) { $this->escaping = $escaping; } public function setEscapingMethod($method) { $this->escapingMethod = $method; } 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(); } $this->decorator = true; } public function setDirectory($directory) { $this->directory = $directory; } public function setComponentSlot($attributeName, $moduleName, $componentName) { $this->componentSlots[$attributeName] = array(); $this->componentSlots[$attributeName]['module_name'] = $moduleName; $this->componentSlots[$attributeName]['component_name'] = $componentName; } public function hasComponentSlot($name) { return isset($this->componentSlots[$name]); } 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; } public function setTemplate($template) { if (sfToolkit::isPathAbsolute($template)) { $this->directory = dirname($template); $this->template = basename($template); } else { $this->template = $template; } } public function getExtension() { return $this->extension; } public function setExtension($ext) { $this->extension = $ext; } 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); } } abstract class sfWebController extends sfController { public function genUrl($parameters = array(), $absolute = false) { if (!is_array($parameters) && preg_match('#^[a-z]+\://#', $parameters)) { return $parameters; } if (!is_array($parameters) && $parameters == '#') { return $parameters; } $url = ''; if (!($sf_no_script_name = sfConfig::get('sf_no_script_name'))) { $url = $this->getContext()->getRequest()->getScriptName(); } else if (($sf_relative_url_root = $this->getContext()->getRequest()->getRelativeUrlRoot()) && $sf_no_script_name) { $url = $sf_relative_url_root; } $route_name = ''; $fragment = ''; if (!is_array($parameters)) { if (false !== ($pos = strpos($parameters, '#'))) { $fragment = substr($parameters, $pos + 1); $parameters = substr($parameters, 0, $pos); } list($route_name, $parameters) = $this->convertUrlStringToParameters($parameters); } if (sfConfig::get('sf_url_format') == 'PATH') { $divider = '/'; $equals = '/'; $querydiv = '/'; } else { $divider = ini_get('arg_separator.output'); $equals = '='; $querydiv = '?'; } if (!isset($parameters['module'])) { $parameters['module'] = sfConfig::get('sf_default_module'); } if (!isset($parameters['action'])) { $parameters['action'] = sfConfig::get('sf_default_action'); } $r = sfRouting::getInstance(); if ($r->hasRoutes() && $generated_url = $r->generate($route_name, $parameters, $querydiv, $divider, $equals)) { $url .= $generated_url; } else { $query = http_build_query($parameters); if (sfConfig::get('sf_url_format') == 'PATH') { $query = strtr($query, ini_get('arg_separator.output').'=', '/'); } $url .= $query; } if ($absolute) { $request = $this->getContext()->getRequest(); $url = 'http'.($request->isSecure() ? 's' : '').'://'.$request->getHost().$url; } if ($fragment) { $url .= '#'.$fragment; } return $url; } public function convertUrlStringToParameters($url) { $params = array(); $query_string = ''; $route_name = ''; if (!$url) { $url = '/'; } if ($pos = strpos($url, '?')) { $query_string = substr($url, $pos + 1); $url = substr($url, 0, $pos); } if ($url[0] == '/') { $url = substr($url, 1); } if ($url[0] == '@') { $route_name = substr($url, 1); } else { $tmp = explode('/', $url); $params['module'] = $tmp[0]; $params['action'] = isset($tmp[1]) ? $tmp[1] : sfConfig::get('sf_default_action'); } if ($query_string) { $matched = preg_match_all('/ ([^&=]+) # key = # = (.*?) # value (?: (?=&[^&=]+=) | $ # followed by another key= or the end of the string ) /x', $query_string, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE); foreach ($matches as $match) { $params[$match[1][0]] = $match[2][0]; } if (!$matched) { throw new sfParseException(sprintf('Unable to parse query string "%s".', $query_string)); } } return array($route_name, $params); } public function redirect($url, $delay = 0, $statusCode = 302) { $response = $this->getContext()->getResponse(); $response->clearHttpHeaders(); $response->setStatusCode($statusCode); $response->setHttpHeader('Location', $url); $response->setContent(sprintf('', $delay, htmlentities($url, ENT_QUOTES, sfConfig::get('sf_charset')))); if (!sfConfig::get('sf_test')) { $response->sendHttpHeaders(); } $response->sendContent(); } } class sfFrontWebController extends sfWebController { public function dispatch() { try { if (sfConfig::get('sf_logging_enabled')) { $this->getContext()->getLogger()->info('{sfController} dispatch request'); } sfFilter::$filterCalled = array(); $request = $this->getContext()->getRequest(); $moduleName = $request->getParameter('module'); $actionName = $request->getParameter('action'); $this->forward($moduleName, $actionName); } catch (sfException $e) { if (sfConfig::get('sf_test')) { throw $e; } $e->printStackTrace(); } catch (Exception $e) { if (sfConfig::get('sf_test')) { throw $e; } try { $sfException = new sfException(); $sfException->printStackTrace($e); } catch (Exception $e) { header('HTTP/1.0 500 Internal Server Error'); } } } } class sfWebRequest extends sfRequest { protected $languages = null; protected $charsets = null; protected $acceptableContentTypes = null; protected $pathInfoArray = null; protected $relativeUrlRoot = null; public function getFile($name) { return ($this->hasFile($name) ? $this->getFileValues($name) : null); } public function getFileError($name) { return ($this->hasFile($name) ? $this->getFileValue($name, 'error') : UPLOAD_ERR_NO_FILE); } public function getFileName($name) { return ($this->hasFile($name) ? $this->getFileValue($name, 'name') : null); } public function getFileNames() { return array_keys($_FILES); } public function getFiles() { return $_FILES; } public function getFilePath($name) { return ($this->hasFile($name) ? $this->getFileValue($name, 'tmp_name') : null); } public function getFileSize($name) { return ($this->hasFile($name) ? $this->getFileValue($name, 'size') : null); } public function getFileType($name) { return ($this->hasFile($name) ? $this->getFileValue($name, 'type') : null); } public function hasFile($name) { if (preg_match('/^(.+?)\[(.+?)\]$/', $name, $match)) { return isset($_FILES[$match[1]]['name'][$match[2]]); } else { return isset($_FILES[$name]); } } public function hasFileError($name) { return ($this->hasFile($name) ? ($this->getFileValue($name, 'error') != UPLOAD_ERR_OK) : false); } public function hasFileErrors() { foreach ($this->getFileNames() as $name) { if ($this->hasFileError($name) === true) { return true; } } return false; } public function hasFiles() { return (count($_FILES) > 0); } public function getFileValue($name, $key) { if (preg_match('/^(.+?)\[(.+?)\]$/', $name, $match)) { return $_FILES[$match[1]][$key][$match[2]]; } else { return $_FILES[$name][$key]; } } public function getFileValues($name) { if (preg_match('/^(.+?)\[(.+?)\]$/', $name, $match)) { return array( 'name' => $_FILES[$match[1]]['name'][$match[2]], 'type' => $_FILES[$match[1]]['type'][$match[2]], 'tmp_name' => $_FILES[$match[1]]['tmp_name'][$match[2]], 'error' => $_FILES[$match[1]]['error'][$match[2]], 'size' => $_FILES[$match[1]]['size'][$match[2]], ); } else { return $_FILES[$name]; } } public function getFileExtension($name) { $fileType = $this->getFileType($name); if (!$fileType) { return '.bin'; } $mimeTypes = unserialize(file_get_contents(sfConfig::get('sf_symfony_data_dir').'/data/mime_types.dat')); return isset($mimeTypes[$fileType]) ? '.'.$mimeTypes[$fileType] : '.bin'; } public function initialize($context, $parameters = array(), $attributes = array()) { parent::initialize($context, $parameters, $attributes); if (isset($_SERVER['REQUEST_METHOD'])) { switch ($_SERVER['REQUEST_METHOD']) { case 'GET': $this->setMethod(self::GET); break; case 'POST': $this->setMethod(self::POST); break; case 'PUT': $this->setMethod(self::PUT); break; case 'DELETE': $this->setMethod(self::DELETE); break; case 'HEAD': $this->setMethod(self::HEAD); break; default: $this->setMethod(self::GET); } } else { $this->setMethod(self::GET); } $this->loadParameters(); } protected function getPathInfoArray() { if (!$this->pathInfoArray) { switch (sfConfig::get('sf_path_info_array')) { case 'SERVER': $this->pathInfoArray =& $_SERVER; break; case 'ENV': default: $this->pathInfoArray =& $_ENV; } } return $this->pathInfoArray; } public function getUri() { $pathArray = $this->getPathInfoArray(); if ($this->isAbsUri()) { return $pathArray['REQUEST_URI']; } return $this->getUriPrefix().$pathArray['REQUEST_URI']; } public function isAbsUri() { $pathArray = $this->getPathInfoArray(); return preg_match('/^http/', $pathArray['REQUEST_URI']); } public function getUriPrefix() { $pathArray = $this->getPathInfoArray(); if ($this->isSecure()) { $standardPort = '443'; $proto = 'https'; } else { $standardPort = '80'; $proto = 'http'; } $port = $pathArray['SERVER_PORT'] == $standardPort || !$pathArray['SERVER_PORT'] ? '' : ':'.$pathArray['SERVER_PORT']; return $proto.'://'.$pathArray['SERVER_NAME'].$port; } public function getPathInfo() { $pathInfo = ''; $pathArray = $this->getPathInfoArray(); $sf_path_info_key = sfConfig::get('sf_path_info_key'); if (!isset($pathArray[$sf_path_info_key]) || !$pathArray[$sf_path_info_key]) { if (isset($pathArray['REQUEST_URI'])) { $script_name = $this->getScriptName(); $uri_prefix = $this->isAbsUri() ? $this->getUriPrefix() : ''; $pathInfo = preg_replace('/^'.preg_quote($uri_prefix, '/').'/','',$pathArray['REQUEST_URI']); $pathInfo = preg_replace('/^'.preg_quote($script_name, '/').'/', '', $pathInfo); $prefix_name = preg_replace('#/[^/]+$#', '', $script_name); $pathInfo = preg_replace('/^'.preg_quote($prefix_name, '/').'/', '', $pathInfo); $pathInfo = preg_replace('/'.preg_quote($pathArray['QUERY_STRING'], '/').'$/', '', $pathInfo); } } else { $pathInfo = $pathArray[$sf_path_info_key]; if ($sf_relative_url_root = $this->getRelativeUrlRoot()) { $pathInfo = preg_replace('/^'.str_replace('/', '\\/', $sf_relative_url_root).'\//', '', $pathInfo); } } if (isset($_SERVER['SERVER_SOFTWARE']) && false !== stripos($_SERVER['SERVER_SOFTWARE'], 'iis') && $pos = stripos($pathInfo, '.php')) { $pathInfo = substr($pathInfo, $pos + 4); } if (!$pathInfo) { $pathInfo = '/'; } return $pathInfo; } protected function loadParameters() { if (get_magic_quotes_gpc()) { $_GET = sfToolkit::stripslashesDeep($_GET); } $this->getParameterHolder()->addByRef($_GET); $pathInfo = $this->getPathInfo(); if ($pathInfo) { $r = sfRouting::getInstance(); if ($r->hasRoutes()) { $results = $r->parse($pathInfo); if ($results !== null) { $this->getParameterHolder()->addByRef($results); } else { $this->setParameter('module', sfConfig::get('sf_error_404_module')); $this->setParameter('action', sfConfig::get('sf_error_404_action')); } } else { $array = explode('/', trim($pathInfo, '/')); $count = count($array); for ($i = 0; $i < $count; $i++) { if ($count > ($i + 1)) { $this->getParameterHolder()->setByRef($array[$i], $array[++$i]); } } } } if (get_magic_quotes_gpc()) { $_POST = sfToolkit::stripslashesDeep((array) $_POST); } $this->getParameterHolder()->addByRef($_POST); foreach ($this->getParameterHolder()->getAll() as $key => $value) { if (0 === stripos($key, '_sf_')) { $this->getParameterHolder()->remove($key); $this->setParameter($key, $value, 'symfony/request/sfWebRequest'); unset($_GET[$key]); } } if (sfConfig::get('sf_logging_enabled')) { $this->getContext()->getLogger()->info(sprintf('{sfRequest} request parameters %s', str_replace("\n", '', var_export($this->getParameterHolder()->getAll(), true)))); } } public function moveFile($name, $file, $fileMode = 0666, $create = true, $dirMode = 0777) { if ($this->hasFile($name) && $this->getFileValue($name, 'error') == UPLOAD_ERR_OK && $this->getFileValue($name, 'size') > 0) { $directory = dirname($file); if (!is_readable($directory)) { $fmode = 0777; if ($create && !@mkdir($directory, $dirMode, true)) { $error = 'Failed to create file upload directory "%s"'; $error = sprintf($error, $directory); throw new sfFileException($error); } @chmod($directory, $dirMode); } else if (!is_dir($directory)) { $error = 'File upload path "%s" exists, but is not a directory'; $error = sprintf($error, $directory); throw new sfFileException($error); } else if (!is_writable($directory)) { $error = 'File upload path "%s" is not writable'; $error = sprintf($error, $directory); throw new sfFileException($error); } if (@move_uploaded_file($this->getFileValue($name, 'tmp_name'), $file)) { @chmod($file, $fileMode); return true; } } return false; } public function getReferer() { $pathArray = $this->getPathInfoArray(); return isset($pathArray['HTTP_REFERER']) ? $pathArray['HTTP_REFERER'] : ''; } public function getHost() { $pathArray = $this->getPathInfoArray(); return isset($pathArray['HTTP_X_FORWARDED_HOST']) ? $pathArray['HTTP_X_FORWARDED_HOST'] : (isset($pathArray['HTTP_HOST']) ? $pathArray['HTTP_HOST'] : ''); } public function getScriptName() { $pathArray = $this->getPathInfoArray(); return isset($pathArray['SCRIPT_NAME']) ? $pathArray['SCRIPT_NAME'] : (isset($pathArray['ORIG_SCRIPT_NAME']) ? $pathArray['ORIG_SCRIPT_NAME'] : ''); } public function getMethodName() { $pathArray = $this->getPathInfoArray(); return isset($pathArray['REQUEST_METHOD']) ? $pathArray['REQUEST_METHOD'] : 'GET'; } public function getLanguages() { if ($this->languages) { return $this->languages; } if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { return array(); } $languages = $this->splitHttpAcceptHeader($_SERVER['HTTP_ACCEPT_LANGUAGE']); foreach ($languages as $lang) { if (strstr($lang, '-')) { $codes = explode('-', $lang); if ($codes[0] == 'i') { if (count($codes) > 1) { $lang = $codes[1]; } } else { for ($i = 0, $max = count($codes); $i < $max; $i++) { if ($i == 0) { $lang = strtolower($codes[0]); } else { $lang .= '_'.strtoupper($codes[$i]); } } } } $this->languages[] = $lang; } return $this->languages; } public function getCharsets() { if ($this->charsets) { return $this->charsets; } if (!isset($_SERVER['HTTP_ACCEPT_CHARSET'])) { return array(); } $this->charsets = $this->splitHttpAcceptHeader($_SERVER['HTTP_ACCEPT_CHARSET']); return $this->charsets; } public function getAcceptableContentTypes() { if ($this->acceptableContentTypes) { return $this->acceptableContentTypes; } if (!isset($_SERVER['HTTP_ACCEPT'])) { return array(); } $this->acceptableContentTypes = $this->splitHttpAcceptHeader($_SERVER['HTTP_ACCEPT']); return $this->acceptableContentTypes; } public function isXmlHttpRequest() { return ($this->getHttpHeader('X_REQUESTED_WITH') == 'XMLHttpRequest'); } public function getHttpHeader($name, $prefix = 'http') { if ($prefix) { $prefix = strtoupper($prefix).'_'; } $name = $prefix.strtoupper(strtr($name, '-', '_')); $pathArray = $this->getPathInfoArray(); return isset($pathArray[$name]) ? stripslashes($pathArray[$name]) : null; } public function getCookie($name, $defaultValue = null) { $retval = $defaultValue; if (isset($_COOKIE[$name])) { $retval = get_magic_quotes_gpc() ? stripslashes($_COOKIE[$name]) : $_COOKIE[$name]; } return $retval; } public function isSecure() { $pathArray = $this->getPathInfoArray(); return ( (isset($pathArray['HTTPS']) && strtolower($pathArray['HTTPS']) == 'on') || (isset($pathArray['HTTP_X_FORWARDED_PROTO']) && strtolower($pathArray['HTTP_X_FORWARDED_PROTO']) == 'https') ); } public function getRelativeUrlRoot() { if ($this->relativeUrlRoot === null) { $this->relativeUrlRoot = sfConfig::get('sf_relative_url_root', preg_replace('#/[^/]+\.php5?$#', '', $this->getScriptName())); } return $this->relativeUrlRoot; } public function setRelativeUrlRoot($value) { $this->relativeUrlRoot = $value; } public function shutdown() { } public function splitHttpAcceptHeader($header) { $values = array(); foreach (array_filter(explode(',', $header)) as $value) { if ($pos = strpos($value, ';')) { $q = (float) trim(substr($value, $pos + 3)); $value = trim(substr($value, 0, $pos)); } else { $q = 1; } $values[$value] = $q; } arsort($values); return array_keys($values); } } class sfWebResponse extends sfResponse { protected $cookies = array(), $statusCode = 200, $statusText = 'OK', $statusTexts = array(), $headerOnly = false; public function initialize($context, $parameters = array()) { parent::initialize($context, $parameters); if ('HEAD' == $context->getRequest()->getMethodName()) { $this->setHeaderOnly(true); } $this->statusTexts = array( '100' => 'Continue', '101' => 'Switching Protocols', '200' => 'OK', '201' => 'Created', '202' => 'Accepted', '203' => 'Non-Authoritative Information', '204' => 'No Content', '205' => 'Reset Content', '206' => 'Partial Content', '300' => 'Multiple Choices', '301' => 'Moved Permanently', '302' => 'Found', '303' => 'See Other', '304' => 'Not Modified', '305' => 'Use Proxy', '306' => '(Unused)', '307' => 'Temporary Redirect', '400' => 'Bad Request', '401' => 'Unauthorized', '402' => 'Payment Required', '403' => 'Forbidden', '404' => 'Not Found', '405' => 'Method Not Allowed', '406' => 'Not Acceptable', '407' => 'Proxy Authentication Required', '408' => 'Request Timeout', '409' => 'Conflict', '410' => 'Gone', '411' => 'Length Required', '412' => 'Precondition Failed', '413' => 'Request Entity Too Large', '414' => 'Request-URI Too Long', '415' => 'Unsupported Media Type', '416' => 'Requested Range Not Satisfiable', '417' => 'Expectation Failed', '500' => 'Internal Server Error', '501' => 'Not Implemented', '502' => 'Bad Gateway', '503' => 'Service Unavailable', '504' => 'Gateway Timeout', '505' => 'HTTP Version Not Supported', ); } public function setHeaderOnly($value = true) { $this->headerOnly = (boolean) $value; } public function isHeaderOnly() { return $this->headerOnly; } public function setCookie($name, $value, $expire = null, $path = '/', $domain = '', $secure = false, $httpOnly = false) { if ($expire !== null) { if (is_numeric($expire)) { $expire = (int) $expire; } else { $expire = strtotime($expire); if ($expire === false || $expire == -1) { throw new sfException('Your expire parameter is not valid.'); } } } $this->cookies[] = array( 'name' => $name, 'value' => $value, 'expire' => $expire, 'path' => $path, 'domain' => $domain, 'secure' => $secure ? true : false, 'httpOnly' => $httpOnly, ); } public function setStatusCode($code, $name = null) { $this->statusCode = $code; $this->statusText = null !== $name ? $name : $this->statusTexts[$code]; } public function getStatusCode() { return $this->statusCode; } public function setHttpHeader($name, $value, $replace = true) { $name = $this->normalizeHeaderName($name); if ('Content-Type' == $name) { if ($replace || !$this->getHttpHeader('Content-Type', null)) { $this->setContentType($value); } return; } if (!$replace) { $current = $this->getParameter($name, '', 'symfony/response/http/headers'); $value = ($current ? $current.', ' : '').$value; } $this->setParameter($name, $value, 'symfony/response/http/headers'); } public function getHttpHeader($name, $default = null) { return $this->getParameter($this->normalizeHeaderName($name), $default, 'symfony/response/http/headers'); } public function hasHttpHeader($name) { return $this->hasParameter($this->normalizeHeaderName($name), 'symfony/response/http/headers'); } public function setContentType($value) { if (false === stripos($value, 'charset')) { $value .= '; charset='.sfConfig::get('sf_charset'); } $this->setParameter('Content-Type', $value, 'symfony/response/http/headers'); } public function getContentType() { return $this->getHttpHeader('Content-Type', 'text/html; charset='.sfConfig::get('sf_charset')); } public function sendHttpHeaders() { $status = 'HTTP/1.0 '.$this->statusCode.' '.$this->statusText; header($status); if (sfConfig::get('sf_logging_enabled')) { $this->getContext()->getLogger()->info('{sfResponse} send status "'.$status.'"'); } foreach ($this->getParameterHolder()->getAll('symfony/response/http/headers') as $name => $value) { header($name.': '.$value); if (sfConfig::get('sf_logging_enabled') && $value != '') { $this->getContext()->getLogger()->info('{sfResponse} send header "'.$name.'": "'.$value.'"'); } } foreach ($this->cookies as $cookie) { if (version_compare(phpversion(), '5.2', '>=')) { setrawcookie($cookie['name'], $cookie['value'], $cookie['expire'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httpOnly']); } else { setrawcookie($cookie['name'], $cookie['value'], $cookie['expire'], $cookie['path'], $cookie['domain'], $cookie['secure']); } if (sfConfig::get('sf_logging_enabled')) { $this->getContext()->getLogger()->info('{sfResponse} send cookie "'.$cookie['name'].'": "'.$cookie['value'].'"'); } } } public function sendContent() { if (!$this->headerOnly) { parent::sendContent(); } } protected function normalizeHeaderName($name) { return preg_replace('/\-(.)/e', "'-'.strtoupper('\\1')", strtr(ucfirst(strtolower($name)), '_', '-')); } public function getDate($timestamp, $type = 'rfc1123') { $type = strtolower($type); if ($type == 'rfc1123') { return substr(gmdate('r', $timestamp), 0, -5).'GMT'; } else if ($type == 'rfc1036') { return gmdate('l, d-M-y H:i:s ', $timestamp).'GMT'; } else if ($type == 'asctime') { return gmdate('D M j H:i:s', $timestamp); } else { $error = 'The second getDate() method parameter must be one of: rfc1123, rfc1036 or asctime'; throw new sfParameterException($error); } } public function addVaryHttpHeader($header) { $vary = $this->getHttpHeader('Vary'); $currentHeaders = array(); if ($vary) { $currentHeaders = split('/\s*,\s*/', $vary); } $header = $this->normalizeHeaderName($header); if (!in_array($header, $currentHeaders)) { $currentHeaders[] = $header; $this->setHttpHeader('Vary', implode(', ', $currentHeaders)); } } public function addCacheControlHttpHeader($name, $value = null) { $cacheControl = $this->getHttpHeader('Cache-Control'); $currentHeaders = array(); if ($cacheControl) { foreach (split('/\s*,\s*/', $cacheControl) as $tmp) { $tmp = explode('=', $tmp); $currentHeaders[$tmp[0]] = isset($tmp[1]) ? $tmp[1] : null; } } $currentHeaders[strtr(strtolower($name), '_', '-')] = $value; $headers = array(); foreach ($currentHeaders as $key => $value) { $headers[] = $key.(null !== $value ? '='.$value : ''); } $this->setHttpHeader('Cache-Control', implode(', ', $headers)); } public function getHttpMetas() { return $this->getParameterHolder()->getAll('helper/asset/auto/httpmeta'); } public function addHttpMeta($key, $value, $replace = true) { $key = $this->normalizeHeaderName($key); $this->setHttpHeader($key, $value, $replace); if ('Content-Type' == $key) { $value = $this->getContentType(); } if (!$replace) { $current = $this->getParameter($key, '', 'helper/asset/auto/httpmeta'); $value = ($current ? $current.', ' : '').$value; } $this->setParameter($key, $value, 'helper/asset/auto/httpmeta'); } public function getMetas() { return $this->getParameterHolder()->getAll('helper/asset/auto/meta'); } public function addMeta($key, $value, $replace = true, $escape = true) { $key = strtolower($key); if (sfConfig::get('sf_i18n')) { $value = $this->getContext()->getI18N()->__($value); } if ($escape) { $value = htmlentities($value, ENT_QUOTES, sfConfig::get('sf_charset')); } if ($replace || !$this->getParameter($key, null, 'helper/asset/auto/meta')) { $this->setParameter($key, $value, 'helper/asset/auto/meta'); } } public function getTitle() { return $this->getParameter('title', '', 'helper/asset/auto/meta'); } public function setTitle($title, $escape = true) { $this->addMeta('title', $title, true, $escape); } public function getStylesheets($position = '') { return $this->getParameterHolder()->getAll('helper/asset/auto/stylesheet'.($position ? '/'.$position : '')); } public function addStylesheet($css, $position = '', $options = array()) { $this->setParameter($css, $options, 'helper/asset/auto/stylesheet'.($position ? '/'.$position : '')); } public function getJavascripts($position = '') { return $this->getParameterHolder()->getAll('helper/asset/auto/javascript'.($position ? '/'.$position : '')); } public function addJavascript($js, $position = '') { $this->setParameter($js, $js, 'helper/asset/auto/javascript'.($position ? '/'.$position : '')); } public function getCookies() { $cookies = array(); foreach ($this->cookies as $cookie) { $cookies[$cookie['name']] = $cookie; } return $cookies; } public function getHttpHeaders() { return $this->getParameterHolder()->getAll('symfony/response/http/headers'); } public function clearHttpHeaders() { $this->getParameterHolder()->removeNamespace('symfony/response/http/headers'); } public function mergeProperties($response) { $this->parameterHolder = clone $response->getParameterHolder(); } public function __sleep() { return array('content', 'statusCode', 'statusText', 'parameterHolder'); } public function __wakeup() { } public function shutdown() { } } class sfSessionStorage extends sfStorage { public function initialize($context, $parameters = null) { parent::initialize($context, $parameters); $sessionName = $this->getParameterHolder()->get('session_name', 'symfony'); session_name($sessionName); $use_cookies = (boolean) ini_get('session.use_cookies'); if (!$use_cookies) { $sessionId = $context->getRequest()->getParameter($sessionName, ''); if ($sessionId != '') { session_id($sessionId); } } $cookieDefaults = session_get_cookie_params(); $lifetime = $this->getParameter('session_cookie_lifetime', $cookieDefaults['lifetime']); $path = $this->getParameter('session_cookie_path', $cookieDefaults['path']); $domain = $this->getParameter('session_cookie_domain', $cookieDefaults['domain']); $secure = $this->getParameter('session_cookie_secure', $cookieDefaults['secure']); $httpOnly = $this->getParameter('session_cookie_httponly', isset($cookieDefaults['httponly']) ? $cookieDefaults['httponly'] : false); if (version_compare(phpversion(), '5.2', '>=')) { session_set_cookie_params($lifetime, $path, $domain, $secure, $httpOnly); } else { session_set_cookie_params($lifetime, $path, $domain, $secure); } if ($this->getParameter('auto_start', true)) { session_start(); } } public function & read($key) { $retval = null; if (isset($_SESSION[$key])) { $retval =& $_SESSION[$key]; } return $retval; } public function & remove($key) { $retval = null; if (isset($_SESSION[$key])) { $retval =& $_SESSION[$key]; unset($_SESSION[$key]); } return $retval; } public function write($key, &$data) { $_SESSION[$key] =& $data; } public function shutdown() { } } class sfPHPView extends sfView { public function execute() { } 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; } 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); } 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; } } } ob_start(); ob_implicit_flush(0); require($_sfFile); return ob_get_clean(); } public function getEngine() { return null; } public function configure() { $actionStackEntry = $this->getContext()->getActionStack()->getLastEntry(); if (!$actionStackEntry->getViewInstance()) { $actionStackEntry->setViewInstance($this); } $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)); if (!$this->directory) { $this->setDirectory(sfLoader::getTemplateDir($this->moduleName, $this->getTemplate())); } } protected function decorate($content) { $template = $this->getDecoratorDirectory().'/'.$this->getDecoratorTemplate(); if (sfConfig::get('sf_logging_enabled')) { $this->getContext()->getLogger()->info('{sfView} decorate content with "'.$template.'"'); } $this->attributeHolder->set('sf_content', $content); $this->attributeHolder->set('content', $content); $retval = $this->renderFile($template); return $retval; } public function render($templateVars = null) { $context = $this->getContext(); $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']); } } $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()); } if ($templateVars === null) { $actionInstance = $context->getActionStack()->getLastEntry()->getActionInstance(); $templateVars = $actionInstance->getVarHolder()->getAll(); } $this->attributeHolder->add($this->getGlobalVars()); $this->attributeHolder->add($retval !== null ? $vars : $templateVars); if ($retval === null) { $this->preRenderCheck(); $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); } } } if ($this->isDecorator()) { $retval = $this->decorate($retval); } if ($mode == sfView::RENDER_CLIENT) { $context->getResponse()->setContent($retval); } return $retval; } } abstract class sfOutputEscaper { protected $value; protected $escapingMethod; public function __construct($escapingMethod, $value) { $this->value = $value; $this->escapingMethod = $escapingMethod; } public static function escape($escapingMethod, $value) { if (is_null($value) || ($value === false) || ($escapingMethod === 'esc_raw')) { return $value; } 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) { $copy = clone $value; $copy->escapingMethod = $escapingMethod; return $copy; } elseif ($value instanceof Traversable) { return new sfOutputEscaperIteratorDecorator($escapingMethod, $value); } else { return new sfOutputEscaperObjectDecorator($escapingMethod, $value); } } throw new sfException(sprintf('Unable to escape value "%s"', print_r($value, true))); } public function getRawValue() { return $this->value; } public function __get($var) { return $this->escape($this->escapingMethod, $this->value->$var); } } if (!interface_exists('Countable', false)) { interface Countable { public function count(); } } class sfOutputEscaperArrayDecorator extends sfOutputEscaperGetterDecorator implements Iterator, ArrayAccess, Countable { private $count; public function rewind() { reset($this->value); $this->count = count($this->value); } public function key() { return key($this->value); } public function current() { return sfOutputEscaper::escape($this->escapingMethod, current($this->value)); } public function next() { next($this->value); $this->count --; } public function valid() { return $this->count > 0; } public function offsetExists($offset) { return array_key_exists($offset, $this->value); } public function offsetGet($offset) { return sfOutputEscaper::escape($this->escapingMethod, $this->value[$offset]); } public function offsetSet($offset, $value) { throw new sfException('Cannot set values.'); } public function offsetUnset($offset) { throw new sfException('Cannot unset values.'); } public function count() { return count($this->value); } public function getRaw($key) { return $this->value[$key]; } } abstract class sfOutputEscaperGetterDecorator extends sfOutputEscaper { public abstract function getRaw($key); public function get($key, $escapingMethod = null) { if (!$escapingMethod) { $escapingMethod = $this->escapingMethod; } return sfOutputEscaper::escape($escapingMethod, $this->getRaw($key)); } } class sfOutputEscaperIteratorDecorator extends sfOutputEscaperObjectDecorator implements Iterator, Countable, ArrayAccess { private $iterator; public function __construct($escapingMethod, Traversable $value) { parent::__construct($escapingMethod, $value); $this->iterator = new IteratorIterator($value); } public function rewind() { return $this->iterator->rewind(); } public function current() { return sfOutputEscaper::escape($this->escapingMethod, $this->iterator->current()); } public function key() { return $this->iterator->key(); } public function next() { return $this->iterator->next(); } public function valid() { return $this->iterator->valid(); } public function offsetExists($offset) { return array_key_exists($offset, $this->value); } public function offsetGet($offset) { return sfOutputEscaper::escape($this->escapingMethod, $this->value[$offset]); } public function offsetSet($offset, $value) { throw new sfException('Cannot set values.'); } public function offsetUnset($offset) { throw new sfException('Cannot unset values.'); } public function count() { return count($this->value); } } class sfOutputEscaperObjectDecorator extends sfOutputEscaperGetterDecorator { 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); } 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); } 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))); } } }