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,47 @@
<?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 controller
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfConsoleController.class.php 3204 2007-01-09 18:50:08Z fabien $
*/
class sfConsoleController extends sfController
{
/**
* Dispatches a request.
*
* @param string A module name
* @param string An action name
* @param array An associative array of parameters to be set
*/
public function dispatch($moduleName, $actionName, $parameters = array())
{
try
{
// set parameters
$this->getContext()->getRequest()->getParameterHolder()->add($parameters);
// make the first request
$this->forward($moduleName, $actionName);
}
catch (sfException $e)
{
$e->printStackTrace();
}
catch (Exception $e)
{
// wrap non symfony exceptions
$sfException = new sfException();
$sfException->printStackTrace($e);
}
}
}

View File

@ -0,0 +1,644 @@
<?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.
*/
/**
* sfController directs application flow.
*
* @package symfony
* @subpackage controller
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <skerr@mojavi.org>
* @version SVN: $Id: sfController.class.php 3221 2007-01-11 07:33:23Z fabien $
*/
abstract class sfController
{
protected
$context = null,
$controllerClasses = array(),
$maxForwards = 5,
$renderMode = sfView::RENDER_CLIENT,
$viewCacheClassName = null;
/**
* Indicates whether or not a module has a specific component.
*
* @param string A module name
* @param string An component name
*
* @return bool true, if the component exists, otherwise false
*/
public function componentExists($moduleName, $componentName)
{
return $this->controllerExists($moduleName, $componentName, 'component', false);
}
/**
* Indicates whether or not a module has a specific action.
*
* @param string A module name
* @param string An action name
*
* @return bool true, if the action exists, otherwise false
*/
public function actionExists($moduleName, $actionName)
{
return $this->controllerExists($moduleName, $actionName, 'action', false);
}
/**
* Looks for a controller and optionally throw exceptions if existence is required (i.e.
* in the case of {@link getController()}).
*
* @param string The name of the module
* @param string The name of the controller within the module
* @param string Either 'action' or 'component' depending on the type of controller to look for
* @param boolean Whether to throw exceptions if the controller doesn't exist
*
* @throws sfConfigurationException thrown if the module is not enabled
* @throws sfControllerException thrown if the controller doesn't exist and the $throwExceptions parameter is set to true
*
* @return boolean true if the controller exists, false otherwise
*/
protected function controllerExists($moduleName, $controllerName, $extension, $throwExceptions)
{
$dirs = sfLoader::getControllerDirs($moduleName);
foreach ($dirs as $dir => $checkEnabled)
{
// plugin module enabled?
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);
}
// one action per file or one file for all actions
$classFile = strtolower($extension);
$classSuffix = ucfirst(strtolower($extension));
$file = $dir.'/'.$controllerName.$classSuffix.'.class.php';
if (is_readable($file))
{
// action class exists
require_once($file);
$this->controllerClasses[$moduleName.'_'.$controllerName.'_'.$classSuffix] = $controllerName.$classSuffix;
return true;
}
$module_file = $dir.'/'.$classFile.'s.class.php';
if (is_readable($module_file))
{
// module class exists
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;
}
// action is defined in this class?
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;
}
}
// send an exception if debug
if ($throwExceptions && sfConfig::get('sf_debug'))
{
$dirs = array_keys($dirs);
// remove sf_root_dir from 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;
}
/**
* Forwards the request to another action.
*
* @param string A module name
* @param string An action name
*
* @throws <b>sfConfigurationException</b> If an invalid configuration setting has been found
* @throws <b>sfForwardException</b> If an error occurs while forwarding the request
* @throws <b>sfInitializationException</b> If the action could not be initialized
* @throws <b>sfSecurityException</b> If the action requires security but the user implementation is not of type sfSecurityUser
*/
public function forward($moduleName, $actionName)
{
// replace unwanted characters
$moduleName = preg_replace('/[^a-z0-9\-_]+/i', '', $moduleName);
$actionName = preg_replace('/[^a-z0-9\-_]+/i', '', $actionName);
if ($this->getActionStack()->getSize() >= $this->maxForwards)
{
// let's kill this party before it turns into cpu cycle hell
$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'))
{
// application is unavailable
$moduleName = sfConfig::get('sf_unavailable_module');
$actionName = sfConfig::get('sf_unavailable_action');
if (!$this->actionExists($moduleName, $actionName))
{
// cannot find unavailable module/action
$error = 'Invalid configuration settings: [sf_unavailable_module] "%s", [sf_unavailable_action] "%s"';
$error = sprintf($error, $moduleName, $actionName);
throw new sfConfigurationException($error);
}
}
// check for a module generator config file
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))
{
// the requested action doesn't exist
if (sfConfig::get('sf_logging_enabled'))
{
$this->getContext()->getLogger()->info('{sfController} action does not exist');
}
// track the requested module so we have access to the data in the error 404 page
$this->context->getRequest()->setAttribute('requested_action', $actionName);
$this->context->getRequest()->setAttribute('requested_module', $moduleName);
// switch to error 404 action
$moduleName = sfConfig::get('sf_error_404_module');
$actionName = sfConfig::get('sf_error_404_action');
if (!$this->actionExists($moduleName, $actionName))
{
// cannot find unavailable module/action
$error = 'Invalid configuration settings: [sf_error_404_module] "%s", [sf_error_404_action] "%s"';
$error = sprintf($error, $moduleName, $actionName);
throw new sfConfigurationException($error);
}
}
// create an instance of the action
$actionInstance = $this->getAction($moduleName, $actionName);
// add a new action stack entry
$this->getActionStack()->addEntry($moduleName, $actionName, $actionInstance);
// include module configuration
require(sfConfigCache::getInstance()->checkConfig(sfConfig::get('sf_app_module_dir_name').'/'.$moduleName.'/'.sfConfig::get('sf_app_module_config_dir_name').'/module.yml'));
// check if this module is internal
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'))
{
// module is enabled
// check for a module config.php
$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);
}
// initialize the action
if ($actionInstance->initialize($this->context))
{
// create a new filter chain
$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);
}
}
// change i18n message source directory to our module
if (sfConfig::get('sf_i18n'))
{
$this->context->getI18N()->setMessageSourceDir(sfLoader::getI18NDir($moduleName), $this->context->getUser()->getCulture());
}
// process the filter chain
$filterChain->execute();
}
else
{
// action failed to initialize
$error = 'Action initialization failed for module "%s", action "%s"';
$error = sprintf($error, $moduleName, $actionName);
throw new sfInitializationException($error);
}
}
else
{
// module is disabled
$moduleName = sfConfig::get('sf_module_disabled_module');
$actionName = sfConfig::get('sf_module_disabled_action');
if (!$this->actionExists($moduleName, $actionName))
{
// cannot find mod disabled module/action
$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);
}
}
/**
* Retrieves an sfAction implementation instance.
*
* @param string A module name
* @param string An action name
*
* @return sfAction An sfAction implementation instance, if the action exists, otherwise null
*/
public function getAction($moduleName, $actionName)
{
return $this->getController($moduleName, $actionName, 'action');
}
/**
* Retrieves a sfComponent implementation instance.
*
* @param string A module name
* @param string A component name
*
* @return sfComponent A sfComponent implementation instance, if the component exists, otherwise null
*/
public function getComponent($moduleName, $componentName)
{
return $this->getController($moduleName, $componentName, 'component');
}
/**
* Retrieves a controller implementation instance.
*
* @param string A module name
* @param string A component name
* @param string Either 'action' or 'component' depending on the type of controller to look for
*
* @return object A controller implementation instance, if the controller exists, otherwise null
*
* @see getComponent(), getAction()
*/
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];
// fix for same name classes
$moduleClass = $moduleName.'_'.$class;
if (class_exists($moduleClass, false))
{
$class = $moduleClass;
}
return new $class();
}
/**
* Retrieves the action stack.
*
* @return sfActionStack An sfActionStack instance, if the action stack is enabled, otherwise null
*/
public function getActionStack()
{
return $this->context->getActionStack();
}
/**
* Retrieves the current application context.
*
* @return sfContext A sfContext instance
*/
public function getContext()
{
return $this->context;
}
/**
* Retrieves the presentation rendering mode.
*
* @return int One of the following:
* - sfView::RENDER_CLIENT
* - sfView::RENDER_VAR
*/
public function getRenderMode()
{
return $this->renderMode;
}
/**
* Retrieves a sfView implementation instance.
*
* @param string A module name
* @param string An action name
* @param string A view name
*
* @return sfView A sfView implementation instance, if the view exists, otherwise null
*/
public function getView($moduleName, $actionName, $viewName)
{
// user view exists?
$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';
// fix for same name classes
$moduleClass = $moduleName.'_'.$class;
if (class_exists($moduleClass, false))
{
$class = $moduleClass;
}
}
else
{
// view class (as configured in module.yml or defined in action)
$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();
}
/**
* Initializes this controller.
*
* @param sfContext A sfContext implementation instance
*/
public function initialize($context)
{
$this->context = $context;
if (sfConfig::get('sf_logging_enabled'))
{
$this->context->getLogger()->info('{sfController} initialization');
}
// set max forwards
$this->maxForwards = sfConfig::get('sf_max_forwards');
}
/**
* Retrieves a new sfController implementation instance.
*
* @param string A sfController class name
*
* @return sfController A sfController implementation instance
*
* @throws sfFactoryException If a new controller implementation instance cannot be created
*/
public static function newInstance($class)
{
try
{
// the class exists
$object = new $class();
if (!($object instanceof sfController))
{
// the class name is of the wrong type
$error = 'Class "%s" is not of the type sfController';
$error = sprintf($error, $class);
throw new sfFactoryException($error);
}
return $object;
}
catch (sfException $e)
{
$e->printStackTrace();
}
}
/**
* Sends and email from the current action.
*
* This methods calls a module/action with the sfMailView class.
*
* @param string A module name
* @param string An action name
*
* @return string The generated mail content
*
* @see sfMailView, getPresentationFor(), sfController
*/
public function sendEmail($module, $action)
{
return $this->getPresentationFor($module, $action, 'sfMail');
}
/**
* Returns the rendered view presentation of a given module/action.
*
* @param string A module name
* @param string An action name
* @param string A View class name
*
* @return string The generated content
*/
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.'")');
}
// get original render mode
$renderMode = $this->getRenderMode();
// set render mode to var
$this->setRenderMode(sfView::RENDER_VAR);
// grab the action stack
$actionStack = $this->getActionStack();
// grab this next forward's action stack index
$index = $actionStack->getSize();
// set viewName if needed
if ($viewName)
{
$this->getContext()->getRequest()->setAttribute($module.'_'.$action.'_view_name', $viewName, 'symfony/action/view');
}
// forward to the mail action
$this->forward($module, $action);
// grab the action entry from this forward
$actionEntry = $actionStack->getEntry($index);
// get raw email content
$presentation =& $actionEntry->getPresentation();
// put render mode back
$this->setRenderMode($renderMode);
// remove the action entry
$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);
}
}
// remove viewName
if ($viewName)
{
$this->getContext()->getRequest()->getAttributeHolder()->remove($module.'_'.$action.'_view_name', 'symfony/action/view');
}
return $presentation;
}
/**
* Sets the presentation rendering mode.
*
* @param int A rendering mode
*
* @throws sfRenderException If an invalid render mode has been set
*/
public function setRenderMode($mode)
{
if ($mode == sfView::RENDER_CLIENT || $mode == sfView::RENDER_VAR || $mode == sfView::RENDER_NONE)
{
$this->renderMode = $mode;
return;
}
// invalid rendering mode type
$error = 'Invalid rendering mode: %s';
$error = sprintf($error, $mode);
throw new sfRenderException($error);
}
/**
* Indicates whether or not we were called using the CLI version of PHP.
*
* @return bool true, if using cli, otherwise false.
*/
public function inCLI()
{
return 0 == strncasecmp(PHP_SAPI, 'cli', 3);
}
/**
* Loads application nad module filters.
*
* @param sfFilterChain A sfFilterChain instance
* @param sfAction A sfAction instance
*/
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'));
}
/**
* Calls methods defined via the sfMixer class.
*
* @param string The method name
* @param array The method arguments
*
* @return mixed The returned value of the called method
*
* @see sfMixer
*/
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);
}
}

View File

@ -0,0 +1,78 @@
<?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.
*/
/**
* sfFrontWebController allows you to centralize your entry point in your web
* application, but at the same time allow for any module and action combination
* to be requested.
*
* @package symfony
* @subpackage controller
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <skerr@mojavi.org>
* @version SVN: $Id: sfFrontWebController.class.php 3502 2007-02-18 18:28:28Z fabien $
*/
class sfFrontWebController extends sfWebController
{
/**
* Dispatches a request.
*
* This will determine which module and action to use by request parameters specified by the user.
*/
public function dispatch()
{
try
{
if (sfConfig::get('sf_logging_enabled'))
{
$this->getContext()->getLogger()->info('{sfController} dispatch request');
}
// reinitialize filters (needed for unit and functional tests)
sfFilter::$filterCalled = array();
// determine our module and action
$request = $this->getContext()->getRequest();
$moduleName = $request->getParameter('module');
$actionName = $request->getParameter('action');
// make the first request
$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
{
// wrap non symfony exceptions
$sfException = new sfException();
$sfException->printStackTrace($e);
}
catch (Exception $e)
{
header('HTTP/1.0 500 Internal Server Error');
}
}
}
}

View File

@ -0,0 +1,633 @@
<?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.
*/
/**
* sfRouting class controls the creation of URLs and parses URLs. It maps an array of parameters to URLs definition.
* Each map is called a route.
* It implements the Singleton pattern.
*
* Routing can be disabled when [sf_routing] is set to false.
*
* This class is based on the Routes class of Cake framework.
*
* @package symfony
* @subpackage controller
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfRouting.class.php 4228 2007-06-15 13:43:24Z francois $
*/
class sfRouting
{
protected static
$instance = null;
protected
$current_route_name = '',
$routes = array();
/**
* Retrieve the singleton instance of this class.
*
* @return sfRouting The sfRouting implementation instance
*/
public static function getInstance()
{
if (!isset(self::$instance))
{
self::$instance = new sfRouting();
}
return self::$instance;
}
/**
* Sets the current route name.
*
* @param string The route name
*/
protected function setCurrentRouteName($name)
{
$this->current_route_name = $name;
}
/**
* Gets the current route name.
*
* @return string The route name
*/
public function getCurrentRouteName()
{
return $this->current_route_name;
}
/**
* Gets the internal URI for the current request.
*
* @param boolean Whether to give an internal URI with the route name (@route)
* or with the module/action pair
*
* @return string The current internal URI
*/
public function getCurrentInternalUri($with_route_name = false)
{
if ($this->current_route_name)
{
list($url, $regexp, $names, $names_hash, $defaults, $requirements, $suffix) = $this->routes[$this->current_route_name];
$request = sfContext::getInstance()->getRequest();
if ($with_route_name)
{
$internal_uri = '@'.$this->current_route_name;
}
else
{
$internal_uri = $request->getParameter('module', isset($defaults['module']) ? $defaults['module'] : '').'/'.$request->getParameter('action', isset($defaults['action']) ? $defaults['action'] : '');
}
$params = array();
// add parameters
foreach ($names as $name)
{
if ($name == 'module' || $name == 'action') continue;
$params[] = $name.'='.$request->getParameter($name, isset($defaults[$name]) ? $defaults[$name] : '');
}
// add * parameters if needed
if (strpos($url, '*'))
{
foreach ($request->getParameterHolder()->getAll() as $key => $value)
{
if ($key == 'module' || $key == 'action' || in_array($key, $names))
{
continue;
}
$params[] = $key.'='.$value;
}
}
// sort to guaranty unicity
sort($params);
return $internal_uri.($params ? '?'.implode('&', $params) : '');
}
}
/**
* Gets the current compiled route array.
*
* @return array The route array
*/
public function getRoutes()
{
return $this->routes;
}
/**
* Sets the compiled route array.
*
* @param array The route array
*
* @return array The route array
*/
public function setRoutes($routes)
{
return $this->routes = $routes;
}
/**
* Returns true if this instance has some routes.
*
* @return boolean
*/
public function hasRoutes()
{
return count($this->routes) ? true : false;
}
/**
* Returns true if the route name given is defined.
*
* @param string The route name
*
* @return boolean
*/
public function hasRouteName($name)
{
return isset($this->routes[$name]) ? true : false;
}
/**
* Gets a route by its name.
*
* @param string The route name
*
* @return array A route array
*/
public function getRouteByName($name)
{
if ($name[0] == '@')
{
$name = substr($name, 1);
}
if (!isset($this->routes[$name]))
{
$error = 'The route "%s" does not exist';
$error = sprintf($error, $name);
throw new sfConfigurationException($error);
}
return $this->routes[$name];
}
/**
* Clears all current routes.
*/
public function clearRoutes()
{
if (sfConfig::get('sf_logging_enabled'))
{
sfLogger::getInstance()->info('{sfRouting} clear all current routes');
}
$this->routes = array();
}
/**
* Adds a new route at the beginning of the current list of routes.
*
* @see connect
*/
public function prependRoute($name, $route, $default = array(), $requirements = array())
{
$routes = $this->routes;
$this->routes = array();
$newroutes = $this->connect($name, $route, $default, $requirements);
$this->routes = array_merge($newroutes, $routes);
return $this->routes;
}
/**
* Adds a new route.
*
* Alias for the connect method.
*
* @see connect
*/
public function appendRoute($name, $route, $default = array(), $requirements = array())
{
return $this->connect($name, $route, $default, $requirements);
}
/**
* Adds a new route at the end of the current list of routes.
*
* A route string is a string with 2 special constructions:
* - :string: :string denotes a named paramater (available later as $request->getParameter('string'))
* - *: * match an indefinite number of parameters in a route
*
* Here is a very common rule in a symfony project:
*
* <code>
* $r->connect('/:module/:action/*');
* </code>
*
* @param string The route name
* @param string The route string
* @param array The default parameter values
* @param array The regexps parameters must match
*
* @return array current routes
*/
public function connect($name, $route, $default = array(), $requirements = array())
{
// route already exists?
if (isset($this->routes[$name]))
{
$error = 'This named route already exists ("%s").';
$error = sprintf($error, $name);
throw new sfConfigurationException($error);
}
$parsed = array();
$names = array();
$suffix = (($sf_suffix = sfConfig::get('sf_suffix')) == '.') ? '' : $sf_suffix;
// used for performance reasons
$names_hash = array();
$r = null;
if (($route == '') || ($route == '/'))
{
$regexp = '/^[\/]*$/';
$this->routes[$name] = array($route, $regexp, array(), array(), $default, $requirements, $suffix);
}
else
{
$elements = array();
foreach (explode('/', $route) as $element)
{
if (trim($element))
{
$elements[] = $element;
}
}
if (!isset($elements[0]))
{
return false;
}
// specific suffix for this route?
// or /$ directory
if (preg_match('/^(.+)(\.\w*)$/i', $elements[count($elements) - 1], $matches))
{
$suffix = ($matches[2] == '.') ? '' : $matches[2];
$elements[count($elements) - 1] = $matches[1];
$route = '/'.implode('/', $elements);
}
else if ($route{strlen($route) - 1} == '/')
{
$suffix = '/';
}
$regexp_suffix = preg_quote($suffix);
foreach ($elements as $element)
{
if (preg_match('/^:(.+)$/', $element, $r))
{
$element = $r[1];
// regex is [^\/]+ or the requirement regex
if (isset($requirements[$element]))
{
$regex = $requirements[$element];
if (0 === strpos($regex, '^'))
{
$regex = substr($regex, 1);
}
if (strlen($regex) - 1 === strpos($regex, '$'))
{
$regex = substr($regex, 0, -1);
}
}
else
{
$regex = '[^\/]+';
}
$parsed[] = '(?:\/('.$regex.'))?';
$names[] = $element;
$names_hash[$element] = 1;
}
elseif (preg_match('/^\*$/', $element, $r))
{
$parsed[] = '(?:\/(.*))?';
}
else
{
$parsed[] = '/'.$element;
}
}
$regexp = '#^'.join('', $parsed).$regexp_suffix.'$#';
$this->routes[$name] = array($route, $regexp, $names, $names_hash, $default, $requirements, $suffix);
}
if (sfConfig::get('sf_logging_enabled'))
{
sfLogger::getInstance()->info('{sfRouting} connect "'.$route.'"'.($suffix ? ' ("'.$suffix.'" suffix)' : ''));
}
return $this->routes;
}
/**
* Generates a valid URLs for parameters.
*
* @param array The parameter values
* @param string The divider between key/value pairs
* @param string The equal sign to use between key and value
*
* @return string The generated URL
*/
public function generate($name, $params, $querydiv = '/', $divider = '/', $equals = '/')
{
$global_defaults = sfConfig::get('sf_routing_defaults', null);
// named route?
if ($name)
{
if (!isset($this->routes[$name]))
{
$error = 'The route "%s" does not exist.';
$error = sprintf($error, $name);
throw new sfConfigurationException($error);
}
list($url, $regexp, $names, $names_hash, $defaults, $requirements, $suffix) = $this->routes[$name];
if ($global_defaults !== null)
{
$defaults = array_merge($defaults, $global_defaults);
}
// all params must be given
foreach ($names as $tmp)
{
if (!isset($params[$tmp]) && !isset($defaults[$tmp]))
{
throw new sfException(sprintf('Route named "%s" have a mandatory "%s" parameter', $name, $tmp));
}
}
}
else
{
// find a matching route
$found = false;
foreach ($this->routes as $name => $route)
{
list($url, $regexp, $names, $names_hash, $defaults, $requirements, $suffix) = $route;
if ($global_defaults !== null)
{
$defaults = array_merge($defaults, $global_defaults);
}
$tparams = array_merge($defaults, $params);
// we must match all names (all $names keys must be in $params array)
foreach ($names as $key)
{
if (!isset($tparams[$key])) continue 2;
}
// we must match all defaults with value except if present in names
foreach ($defaults as $key => $value)
{
if (isset($names_hash[$key])) continue;
if (!isset($tparams[$key]) || $tparams[$key] != $value) continue 2;
}
// we must match all requirements for rule
foreach ($requirements as $req_param => $req_regexp)
{
if (!preg_match('/'.str_replace('/', '\\/', $req_regexp).'/', $tparams[$req_param]))
{
continue 2;
}
}
// we must have consumed all $params keys if there is no * in route
if (!strpos($url, '*'))
{
if (count(array_diff(array_keys($tparams), $names, array_keys($defaults))))
{
continue;
}
}
// match found
$found = true;
break;
}
if (!$found)
{
$error = 'Unable to find a matching routing rule to generate url for params "%s".';
$error = sprintf($error, var_export($params));
throw new sfConfigurationException($error);
}
}
$params = array_merge($defaults, $params);
$real_url = preg_replace('/\:([^\/]+)/e', 'urlencode($params["\\1"])', $url);
// we add all other params if *
if (strpos($real_url, '*'))
{
$tmp = array();
foreach ($params as $key => $value)
{
if (isset($names_hash[$key]) || isset($defaults[$key])) continue;
if (is_array($value))
{
foreach ($value as $v)
{
$tmp[] = $key.$equals.urlencode($v);
}
}
else
{
$tmp[] = urlencode($key).$equals.urlencode($value);
}
}
$tmp = implode($divider, $tmp);
if (strlen($tmp) > 0)
{
$tmp = $querydiv.$tmp;
}
$real_url = preg_replace('/\/\*(\/|$)/', "$tmp$1", $real_url);
}
// strip off last divider character
if (strlen($real_url) > 1)
{
$real_url = rtrim($real_url, $divider);
}
if ($real_url != '/')
{
$real_url .= $suffix;
}
return $real_url;
}
/**
* Parses a URL to find a matching route.
*
* Returns null if no route match the URL.
*
* @param string URL to be parsed
*
* @return array An array of parameters
*/
public function parse($url)
{
// an URL should start with a '/', mod_rewrite doesn't respect that, but no-mod_rewrite version does.
if ($url && ('/' != $url[0]))
{
$url = '/'.$url;
}
// we remove the query string
if ($pos = strpos($url, '?'))
{
$url = substr($url, 0, $pos);
}
// we remove multiple /
$url = preg_replace('#/+#', '/', $url);
foreach ($this->routes as $route_name => $route)
{
$out = array();
$r = null;
list($route, $regexp, $names, $names_hash, $defaults, $requirements, $suffix) = $route;
$break = false;
if (preg_match($regexp, $url, $r))
{
$break = true;
// remove the first element, which is the url
array_shift($r);
// hack, pre-fill the default route names
foreach ($names as $name)
{
$out[$name] = null;
}
// defaults
foreach ($defaults as $name => $value)
{
if (preg_match('#[a-z_\-]#i', $name))
{
$out[$name] = urldecode($value);
}
else
{
$out[$value] = true;
}
}
$pos = 0;
foreach ($r as $found)
{
// if $found is a named url element (i.e. ':action')
if (isset($names[$pos]))
{
$out[$names[$pos]] = urldecode($found);
}
// unnamed elements go in as 'pass'
else
{
$pass = explode('/', $found);
$found = '';
for ($i = 0, $max = count($pass); $i < $max; $i += 2)
{
if (!isset($pass[$i + 1])) continue;
$found .= $pass[$i].'='.$pass[$i + 1].'&';
}
parse_str($found, $pass);
foreach ($pass as $key => $value)
{
// we add this parameters if not in conflict with named url element (i.e. ':action')
if (!isset($names_hash[$key]))
{
$out[$key] = $value;
}
}
}
$pos++;
}
// we must have found all :var stuffs in url? except if default values exists
foreach ($names as $name)
{
if ($out[$name] == null)
{
$break = false;
}
}
if ($break)
{
// we store route name
$this->setCurrentRouteName($route_name);
if (sfConfig::get('sf_logging_enabled'))
{
sfLogger::getInstance()->info('{sfRouting} match route ['.$route_name.'] "'.$route.'"');
}
break;
}
}
}
// no route found
if (!$break)
{
if (sfConfig::get('sf_logging_enabled'))
{
sfLogger::getInstance()->info('{sfRouting} no matching route found');
}
return null;
}
return $out;
}
}

View File

@ -0,0 +1,227 @@
<?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.
*/
/**
* sfWebController provides web specific methods to sfController such as, url redirection.
*
* @package symfony
* @subpackage controller
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <skerr@mojavi.org>
* @version SVN: $Id: sfWebController.class.php 4763 2007-07-31 11:52:49Z fabien $
*/
abstract class sfWebController extends sfController
{
/**
* Generates an URL from an array of parameters.
*
* @param mixed An associative array of URL parameters or an internal URI as a string.
* @param boolean Whether to generate an absolute URL
*
* @return string A URL to a symfony resource
*/
public function genUrl($parameters = array(), $absolute = false)
{
// absolute URL or symfony URL?
if (!is_array($parameters) && preg_match('#^[a-z]+\://#', $parameters))
{
return $parameters;
}
if (!is_array($parameters) && $parameters == '#')
{
return $parameters;
}
$url = '';
if (!sfConfig::get('sf_no_script_name'))
{
$url = $this->getContext()->getRequest()->getScriptName();
}
else if ($sf_relative_url_root = $this->getContext()->getRequest()->getRelativeUrlRoot())
{
$url = $sf_relative_url_root;
}
$route_name = '';
$fragment = '';
if (!is_array($parameters))
{
// strip fragment
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')
{
// use PATH format
$divider = '/';
$equals = '/';
$querydiv = '/';
}
else
{
// use GET format
$divider = ini_get('arg_separator.output');
$equals = '=';
$querydiv = '?';
}
// default module
if (!isset($parameters['module']))
{
$parameters['module'] = sfConfig::get('sf_default_module');
}
// default action
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;
}
/**
* Converts an internal URI string to an array of parameters.
*
* @param string An internal URI
*
* @return array An array of parameters
*/
public function convertUrlStringToParameters($url)
{
$params = array();
$query_string = '';
$route_name = '';
// empty url?
if (!$url)
{
$url = '/';
}
// we get the query string out of the url
if ($pos = strpos($url, '?'))
{
$query_string = substr($url, $pos + 1);
$url = substr($url, 0, $pos);
}
// 2 url forms
// @route_name?key1=value1&key2=value2...
// module/action?key1=value1&key2=value2...
// first slash optional
if ($url[0] == '/')
{
$url = substr($url, 1);
}
// route_name?
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');
}
// split the query string
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];
}
// check that all string is matched
if (!$matched)
{
throw new sfParseException(sprintf('Unable to parse query string "%s".', $query_string));
}
}
return array($route_name, $params);
}
/**
* Redirects the request to another URL.
*
* @param string An existing URL
* @param int A delay in seconds before redirecting. This is only needed on
* browsers that do not support HTTP headers
* @param int The status code
*/
public function redirect($url, $delay = 0, $statusCode = 302)
{
$response = $this->getContext()->getResponse();
// redirect
$response->clearHttpHeaders();
$response->setStatusCode($statusCode);
$response->setHttpHeader('Location', $url);
$response->setContent(sprintf('<html><head><meta http-equiv="refresh" content="%d;url=%s"/></head></html>', $delay, htmlentities($url, ENT_QUOTES, sfConfig::get('sf_charset'))));
if (!sfConfig::get('sf_test'))
{
$response->sendHttpHeaders();
}
$response->sendContent();
}
}