v7‰PNG  IHDR Ÿ f Õ†C1 sRGB ®Îé gAMA ± üa pHYs à ÃÇo¨d GIDATx^íÜL”÷ð÷Yçªö("Bh_ò«®¸¢§q5kÖ*:þ0A­ºšÖ¥]VkJ¢M»¶f¸±8\k2íll£1]q®ÙÔ‚ÆT Helper/Url.php000064400000007666152101613010007243 0ustar00request; if (null === $controller) { $controller = $request->getControllerName(); } if (null === $module) { $module = $request->getModuleName(); } $url = $controller . '/' . $action; if ($module != 'default') { $url = $module . '/' . $url; } if (defined('REL_ROOT_URL')) { $url = REL_ROOT_URL . '/' . $url; } if (null !== $params) { $paramPairs = array(); foreach ($params as $key => $value) { $paramPairs[] = urlencode($key) . '/' . urlencode($value); } $paramString = implode('/', $paramPairs); $url .= '/' . $paramString; } $url = '/' . ltrim($url, '/'); return $url; } /** * Assembles a URL based on a given route * * This method will typically be used for more complex operations, as it * ties into the route objects registered with the router. * * @param array $urlOptions Options passed to the assemble method of the Route object. * @param mixed $name The name of a Route to use. If null it will use the current Route * @param boolean $reset * @param boolean $encode * @return string Url for the link href attribute. */ public function url($urlOptions = array(), $name = null, $reset = false, $encode = true) { $router = Am_Di::getInstance()->router; return $router->assemble($urlOptions, $name, $reset, $encode); } /** * Perform helper when called as $this->_helper->overrideUrl() from an action controller * * Proxies to {@link simple()} * * @param string $action * @param string $controller * @param string $module * @param array $params * @return string */ public function direct($action, $controller = null, $module = null, array $params = null) { return $this->simple($action, $controller, $module, $params); } public function rurl($path, $params = null, $encode = true) { return call_user_func(Am_Di::getInstance()->url, $path, $params, $encode, 2); } public function surl($path, $params = null, $encode = true) { return call_user_func(Am_Di::getInstance()->url, $path, $params, $encode, 1); } /** * Return URL for given path like 'cart/view-basket' * @param array|string $path if array passed, it will call vsprintf for array * @param type $params GET params to add into path * @param type $encode HTML-encode resulting string * @param type $absolute If true, it will return ROOT_SURL, if false -> REL_ROOT_URL, if 2 -> ROOT_URL */ function __invoke($path, $params = null, $encode = true, $absolute = false) { if (is_bool($params)) { $encode = $params; } switch ((int)$absolute) { case 2: $root = ROOT_URL; break; case 1: $root = ROOT_SURL; break; default: $root = REL_ROOT_URL; } if (is_array($path)) { $p = array_shift($path); $path = vsprintf($p, $path); } $url = $root; if ($path) $url .= '/' . $path; if (is_array($params)) $params = http_build_query($params, '', '&'); if (is_string($params) && $params!='') $url .= '?' . $params; if ($encode) $url = Am_Html::escape($url); return $url; } }Response.php000064400000002651152101613010007045 0ustar00request->isSecure(); $url = ($secure ? 'https' : 'http') . '://' . $u['host'] . ((isset($u['port']) && $u['port'] != 80) ? ":{$u['port']}" : '') . $url; } if (AM_APPLICATION_ENV != 'testing') { header("Location: " . preg_replace('/[\r\n]+/', '', $url)); } throw new Am_Exception_Redirect($url); } function ajaxResponse($vars) { if (!empty($_GET['callback'])) { if (preg_match('/\W/', $_GET['callback'])) { // if $_GET['callback'] contains a non-word character, // this could be an XSS attack. header('HTTP/1.1 400 Bad Request'); exit(); } $ret = sprintf('%s(%s)', $_GET['callback'], json_encode($vars)); } else { $ret = json_encode($vars); } if (AM_APPLICATION_ENV == 'testing') { $this->setHeader('Content-type', 'application/json; charset=UTF-8'); $this->setBody($ret); } else { header("Content-type: application/json; charset=UTF-8"); echo $ret; } } } Router.php000064400000037171152101613010006534 0ustar00hasRoute('default')) { $request = Am_Di::getInstance()->request; //--//require_once 'Zend/Controller/Router/Route/Module.php'; $compat = new Am_Mvc_Router_Route_Module(array(), $request); $this->_routes = array('default' => $compat) + $this->_routes; } return $this; } /** * Add route to the route chain * * If route contains method setRequest(), it is initialized with a request object * * @param string $name Name of the route * @param Am_Mvc_Router_Route_Interface $route Instance of the route * @return Am_Mvc_Router_Rewrite */ public function addRoute($name, Am_Mvc_Router_Route_Interface $route) { if (method_exists($route, 'setRequest')) { $route->setRequest(Am_Di::getInstance()->request); } $this->_routes[$name] = $route; return $this; } /** * Add routes to the route chain * * @param array $routes Array of routes with names as keys and routes as values * @return Am_Mvc_Router_Rewrite */ public function addRoutes($routes) { foreach ($routes as $name => $route) { $this->addRoute($name, $route); } return $this; } /** * Create routes out of Zend_Config configuration * * Example INI: * routes.archive.route = "archive/:year/*" * routes.archive.defaults.controller = archive * routes.archive.defaults.action = show * routes.archive.defaults.year = 2000 * routes.archive.reqs.year = "\d+" * * routes.news.type = "Am_Mvc_Router_Route_Static" * routes.news.route = "news" * routes.news.defaults.controller = "news" * routes.news.defaults.action = "list" * * And finally after you have created a Zend_Config with above ini: * $router = new Am_Mvc_Router_Rewrite(); * $router->addConfig($config, 'routes'); * * @param Zend_Config $config Configuration object * @param string $section Name of the config section containing route's definitions * @throws Am_Mvc_Router_Exception * @return Am_Mvc_Router_Rewrite */ public function addConfig(Zend_Config $config, $section = null) { if ($section !== null) { if ($config->{$section} === null) { //--//require_once 'Zend/Controller/Router/Exception.php'; throw new Am_Mvc_Router_Exception("No route configuration in section '{$section}'"); } $config = $config->{$section}; } foreach ($config as $name => $info) { $route = $this->_getRouteFromConfig($info); if ($route instanceof Am_Mvc_Router_Route_Chain) { if (!isset($info->chain)) { //--//require_once 'Zend/Controller/Router/Exception.php'; throw new Am_Mvc_Router_Exception("No chain defined"); } if ($info->chain instanceof Zend_Config) { $childRouteNames = $info->chain; } else { $childRouteNames = explode(',', $info->chain); } foreach ($childRouteNames as $childRouteName) { $childRoute = $this->getRoute(trim($childRouteName)); $route->chain($childRoute); } $this->addRoute($name, $route); } elseif (isset($info->chains) && $info->chains instanceof Zend_Config) { $this->_addChainRoutesFromConfig($name, $route, $info->chains); } else { $this->addRoute($name, $route); } } return $this; } /** * Get a route frm a config instance * * @param Zend_Config $info * @return Am_Mvc_Router_Route_Interface */ protected function _getRouteFromConfig(Zend_Config $info) { $class = (isset($info->type)) ? $info->type : 'Am_Mvc_Router_Route'; if (!class_exists($class)) { //--//require_once 'Zend/Loader.php'; Zend_Loader::loadClass($class); } $route = call_user_func(array($class, 'getInstance'), $info); if (isset($info->abstract) && $info->abstract && method_exists($route, 'isAbstract')) { $route->isAbstract(true); } return $route; } /** * Add chain routes from a config route * * @param string $name * @param Am_Mvc_Router_Route_Interface $route * @param Zend_Config $childRoutesInfo * @return void */ protected function _addChainRoutesFromConfig($name, Am_Mvc_Router_Route_Interface $route, Zend_Config $childRoutesInfo) { foreach ($childRoutesInfo as $childRouteName => $childRouteInfo) { if (is_string($childRouteInfo)) { $childRouteName = $childRouteInfo; $childRoute = $this->getRoute($childRouteName); } else { $childRoute = $this->_getRouteFromConfig($childRouteInfo); } if ($route instanceof Am_Mvc_Router_Route_Chain) { $chainRoute = clone $route; $chainRoute->chain($childRoute); } else { $chainRoute = $route->chain($childRoute); } $chainName = $name . $this->_chainNameSeparator . $childRouteName; if (isset($childRouteInfo->chains)) { $this->_addChainRoutesFromConfig($chainName, $chainRoute, $childRouteInfo->chains); } else { $this->addRoute($chainName, $chainRoute); } } } /** * Remove a route from the route chain * * @param string $name Name of the route * @throws Am_Mvc_Router_Exception * @return Am_Mvc_Router_Rewrite */ public function removeRoute($name) { if (!isset($this->_routes[$name])) { //--//require_once 'Zend/Controller/Router/Exception.php'; throw new Am_Mvc_Router_Exception("Route $name is not defined"); } unset($this->_routes[$name]); return $this; } /** * Remove all standard default routes * * @param Am_Mvc_Router_Route_Interface Route * @return Am_Mvc_Router_Rewrite */ public function removeDefaultRoutes() { $this->_useDefaultRoutes = false; return $this; } /** * Check if named route exists * * @param string $name Name of the route * @return boolean */ public function hasRoute($name) { return isset($this->_routes[$name]); } /** * Retrieve a named route * * @param string $name Name of the route * @throws Am_Mvc_Router_Exception * @return Am_Mvc_Router_Route_Interface Route object */ public function getRoute($name) { if (!isset($this->_routes[$name])) { //--//require_once 'Zend/Controller/Router/Exception.php'; throw new Am_Mvc_Router_Exception("Route $name is not defined"); } return $this->_routes[$name]; } /** * Retrieve a currently matched route * * @throws Am_Mvc_Router_Exception * @return Am_Mvc_Router_Route_Interface Route object */ public function getCurrentRoute() { if (!isset($this->_currentRoute)) { //--//require_once 'Zend/Controller/Router/Exception.php'; throw new Am_Mvc_Router_Exception("Current route is not defined"); } return $this->getRoute($this->_currentRoute); } /** * Retrieve a name of currently matched route * * @throws Am_Mvc_Router_Exception * @return Am_Mvc_Router_Route_Interface Route object */ public function getCurrentRouteName() { if (!isset($this->_currentRoute)) { //--//require_once 'Zend/Controller/Router/Exception.php'; throw new Am_Mvc_Router_Exception("Current route is not defined"); } return $this->_currentRoute; } /** * Retrieve an array of routes added to the route chain * * @return array All of the defined routes */ public function getRoutes() { return $this->_routes; } /** * Find a matching route to the current PATH_INFO and inject * returning values to the Request object. * * @throws Am_Mvc_Router_Exception * @return Am_Mvc_Request Request object */ public function route(Am_Mvc_Request $request) { if ($this->_useDefaultRoutes) { $this->addDefaultRoutes(); } // Find the matching route $routeMatched = false; foreach (array_reverse($this->_routes, true) as $name => $route) { // TODO: Should be an interface method. Hack for 1.0 BC if (method_exists($route, 'isAbstract') && $route->isAbstract()) { continue; } // TODO: Should be an interface method. Hack for 1.0 BC if (!method_exists($route, 'getVersion') || $route->getVersion() == 1) { $match = $request->getPathInfo(); } else { $match = $request; } if ($params = $route->match($match)) { $this->_setRequestParams($request, $params); $this->_currentRoute = $name; $routeMatched = true; break; } } if (!$routeMatched) { //--//require_once 'Zend/Controller/Router/Exception.php'; throw new Am_Mvc_Router_Exception('No route matched the request', 404); } if($this->_useCurrentParamsAsGlobal) { $params = $request->getParams(); foreach($params as $param => $value) { $this->setGlobalParam($param, $value); } } return $request; } protected function _setRequestParams($request, $params) { foreach ($params as $param => $value) { $request->setParam($param, $value); if ($param === $request->getModuleKey()) { $request->setModuleName($value); } if ($param === $request->getControllerKey()) { $request->setControllerName($value); } if ($param === $request->getActionKey()) { $request->setActionName($value); } } } /** * Generates a URL path that can be used in URL creation, redirection, etc. * * @param array $userParams Options passed by a user used to override parameters * @param mixed $name The name of a Route to use * @param bool $reset Whether to reset to the route defaults ignoring URL params * @param bool $encode Tells to encode URL parts on output * @throws Am_Mvc_Router_Exception * @return string Resulting absolute URL path */ public function assemble($userParams, $name = null, $reset = false, $encode = true) { if (!is_array($userParams)) { //--//require_once 'Zend/Controller/Router/Exception.php'; throw new Am_Mvc_Router_Exception('userParams must be an array'); } if ($name == null) { try { $name = $this->getCurrentRouteName(); } catch (Am_Mvc_Router_Exception $e) { $name = 'default'; } } // Use UNION (+) in order to preserve numeric keys $params = $userParams + $this->_globalParams; $route = $this->getRoute($name); $url = $route->assemble($params, $reset, $encode); if (!preg_match('|^[a-z]+://|', $url)) { $url = rtrim(REL_ROOT_URL, self::URI_DELIMITER) . self::URI_DELIMITER . $url; } return $url; } /** * Set a global parameter * * @param string $name * @param mixed $value * @return Am_Mvc_Router_Rewrite */ public function setGlobalParam($name, $value) { $this->_globalParams[$name] = $value; return $this; } /** * Set the separator to use with chain names * * @param string $separator The separator to use * @return Am_Mvc_Router_Rewrite */ public function setChainNameSeparator($separator) { $this->_chainNameSeparator = $separator; return $this; } /** * Get the separator to use for chain names * * @return string */ public function getChainNameSeparator() { return $this->_chainNameSeparator; } /** * Determines/returns whether to use the request parameters as global parameters. * * @param boolean|null $use * Null/unset when you want to retrieve the current state. * True when request parameters should be global, false otherwise * @return boolean|Am_Mvc_Router_Rewrite * Returns a boolean if first param isn't set, returns an * instance of Am_Mvc_Router_Rewrite otherwise. * */ public function useRequestParametersAsGlobal($use = null) { if($use === null) { return $this->_useCurrentParamsAsGlobal; } $this->_useCurrentParamsAsGlobal = (bool) $use; return $this; } function setFrontController() { } } Router/Abstract.php000064400000007171152101613010010274 0ustar00setParams($params); } /** * Add or modify a parameter to use when instantiating an action controller * * @param string $name * @param mixed $value * @return Am_Mvc_Router */ public function setParam($name, $value) { $name = (string) $name; $this->_invokeParams[$name] = $value; return $this; } /** * Set parameters to pass to action controller constructors * * @param array $params * @return Am_Mvc_Router */ public function setParams(array $params) { $this->_invokeParams = array_merge($this->_invokeParams, $params); return $this; } /** * Retrieve a single parameter from the controller parameter stack * * @param string $name * @return mixed */ public function getParam($name) { if(isset($this->_invokeParams[$name])) { return $this->_invokeParams[$name]; } return null; } /** * Retrieve action controller instantiation parameters * * @return array */ public function getParams() { return $this->_invokeParams; } /** * Clear the controller parameter stack * * By default, clears all parameters. If a parameter name is given, clears * only that parameter; if an array of parameter names is provided, clears * each. * * @param null|string|array single key or array of keys for params to clear * @return Am_Mvc_Router */ public function clearParams($name = null) { if (null === $name) { $this->_invokeParams = array(); } elseif (is_string($name) && isset($this->_invokeParams[$name])) { unset($this->_invokeParams[$name]); } elseif (is_array($name)) { foreach ($name as $key) { if (is_string($key) && isset($this->_invokeParams[$key])) { unset($this->_invokeParams[$key]); } } } return $this; } } Router/Interface.php000064400000007035152101613010010430 0ustar00_urlDelimiter); $this->_defaults = (array) $defaults; $this->_requirements = (array) $reqs; $this->_translator = $translator; $this->_locale = $locale; if ($route !== '') { foreach (explode($this->_urlDelimiter, $route) as $pos => $part) { if (substr($part, 0, 1) == $this->_urlVariable && substr($part, 1, 1) != $this->_urlVariable) { $name = substr($part, 1); if (substr($name, 0, 1) === '@' && substr($name, 1, 1) !== '@') { $name = substr($name, 1); $this->_translatable[] = $name; $this->_isTranslated = true; } $this->_parts[$pos] = (isset($reqs[$name]) ? $reqs[$name] : $this->_defaultRegex); $this->_variables[$pos] = $name; } else { if (substr($part, 0, 1) == $this->_urlVariable) { $part = substr($part, 1); } if (substr($part, 0, 1) === '@' && substr($part, 1, 1) !== '@') { $this->_isTranslated = true; } $this->_parts[$pos] = $part; if ($part !== '*') { $this->_staticCount++; } } } } } /** * Matches a user submitted path with parts defined by a map. Assigns and * returns an array of variables on a successful match. * * @param string $path Path used to match against this routing map * @return array|false An array of assigned values or a false on a mismatch */ public function match($path, $partial = false) { $pathStaticCount = 0; $values = array(); $matchedPath = ''; if (!$partial) { $path = trim($path, $this->_urlDelimiter); } if ($path !== '') { $path = explode($this->_urlDelimiter, $path); foreach ($path as $pos => $pathPart) { // Path is longer than a route, it's not a match if (!array_key_exists($pos, $this->_parts)) { if ($partial) { break; } else { return false; } } $matchedPath .= $pathPart . $this->_urlDelimiter; // If it's a wildcard, get the rest of URL as wildcard data and stop matching if ($this->_parts[$pos] == '*') { $count = count($path); for($i = $pos; $i < $count; $i+=2) { $var = urldecode($path[$i]); if (!isset($this->_wildcardData[$var]) && !isset($this->_defaults[$var]) && !isset($values[$var])) { $this->_wildcardData[$var] = (isset($path[$i+1])) ? urldecode($path[$i+1]) : null; } } $matchedPath = implode($this->_urlDelimiter, $path); break; } $name = isset($this->_variables[$pos]) ? $this->_variables[$pos] : null; $pathPart = urldecode($pathPart); // Translate value if required $part = $this->_parts[$pos]; if ($this->_isTranslated && (substr($part, 0, 1) === '@' && substr($part, 1, 1) !== '@' && $name === null) || $name !== null && in_array($name, $this->_translatable)) { if (substr($part, 0, 1) === '@') { $part = substr($part, 1); } if (($originalPathPart = array_search($pathPart, $translateMessages)) !== false) { $pathPart = $originalPathPart; } } if (substr($part, 0, 2) === '@@') { $part = substr($part, 1); } // If it's a static part, match directly if ($name === null && $part != $pathPart) { return false; } // If it's a variable with requirement, match a regex. If not - everything matches if ($part !== null && !preg_match($this->_regexDelimiter . '^' . $part . '$' . $this->_regexDelimiter . 'iu', $pathPart)) { return false; } // If it's a variable store it's value for later if ($name !== null) { $values[$name] = $pathPart; } else { $pathStaticCount++; } } } // Check if all static mappings have been matched if ($this->_staticCount != $pathStaticCount) { return false; } $return = $values + $this->_wildcardData + $this->_defaults; // Check if all map variables have been initialized foreach ($this->_variables as $var) { if (!array_key_exists($var, $return)) { return false; } elseif ($return[$var] == '' || $return[$var] === null) { // Empty variable? Replace with the default value. $return[$var] = $this->_defaults[$var]; } } $this->setMatchedPath(rtrim($matchedPath, $this->_urlDelimiter)); $this->_values = $values; return $return; } /** * Assembles user submitted parameters forming a URL path defined by this route * * @param array $data An array of variable and value pairs used as parameters * @param boolean $reset Whether or not to set route defaults with those provided in $data * @return string Route path with user submitted parameters */ public function assemble($data = array(), $reset = false, $encode = false, $partial = false) { $url = array(); $flag = false; foreach ($this->_parts as $key => $part) { $name = isset($this->_variables[$key]) ? $this->_variables[$key] : null; $useDefault = false; if (isset($name) && array_key_exists($name, $data) && $data[$name] === null) { $useDefault = true; } if (isset($name)) { if (isset($data[$name]) && !$useDefault) { $value = $data[$name]; unset($data[$name]); } elseif (!$reset && !$useDefault && isset($this->_values[$name])) { $value = $this->_values[$name]; } elseif (!$reset && !$useDefault && isset($this->_wildcardData[$name])) { $value = $this->_wildcardData[$name]; } elseif (array_key_exists($name, $this->_defaults)) { $value = $this->_defaults[$name]; } else { //--//require_once 'Zend/Controller/Router/Exception.php'; throw new Am_Mvc_Router_Exception($name . ' is not specified'); } if ($this->_isTranslated && in_array($name, $this->_translatable)) { $url[$key] = $translator->translate($value, $locale); } else { $url[$key] = $value; } } elseif ($part != '*') { if ($this->_isTranslated && substr($part, 0, 1) === '@') { if (substr($part, 1, 1) !== '@') { $url[$key] = $translator->translate(substr($part, 1), $locale); } else { $url[$key] = substr($part, 1); } } else { if (substr($part, 0, 2) === '@@') { $part = substr($part, 1); } $url[$key] = $part; } } else { if (!$reset) $data += $this->_wildcardData; $defaults = $this->getDefaults(); foreach ($data as $var => $value) { if ($value !== null && (!isset($defaults[$var]) || $value != $defaults[$var])) { $url[$key++] = $var; $url[$key++] = $value; $flag = true; } } } } $return = ''; foreach (array_reverse($url, true) as $key => $value) { $defaultValue = null; if (isset($this->_variables[$key])) { $defaultValue = $this->getDefault($this->_variables[$key]); if ($this->_isTranslated && $defaultValue !== null && isset($this->_translatable[$this->_variables[$key]])) { $defaultValue = $translator->translate($defaultValue, $locale); } } if ($flag || $value !== $defaultValue || $partial) { if ($encode) $value = urlencode($value); $return = $this->_urlDelimiter . $value . $return; $flag = true; } } return trim($return, $this->_urlDelimiter); } /** * Return a single parameter of route's defaults * * @param string $name Array key of the parameter * @return string Previously set default */ public function getDefault($name) { if (isset($this->_defaults[$name])) { return $this->_defaults[$name]; } return null; } /** * Return an array of defaults * * @return array Route defaults */ public function getDefaults() { return $this->_defaults; } /** * Get all variables which are used by the route * * @return array */ public function getVariables() { return $this->_variables; } public static function getInstance(Zend_Config $config) { $reqs = ($config->reqs instanceof Zend_Config) ? $config->reqs->toArray() : array(); $defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array(); return new self($config->route, $defs, $reqs); } } Router/Route/Regex.php000064400000021216152101613010010675 0ustar00defaults instanceof Zend_Config) ? $config->defaults->toArray() : array(); $map = ($config->map instanceof Zend_Config) ? $config->map->toArray() : array(); $reverse = (isset($config->reverse)) ? $config->reverse : null; return new self($config->route, $defs, $map, $reverse); } public function __construct($route, $defaults = array(), $map = array(), $reverse = null) { $this->_regex = $route; $this->_defaults = (array) $defaults; $this->_map = (array) $map; $this->_reverse = $reverse; } public function getVersion() { return 1; } /** * Matches a user submitted path with a previously defined route. * Assigns and returns an array of defaults on a successful match. * * @param string $path Path used to match against this routing map * @return array|false An array of assigned values or a false on a mismatch */ public function match($path, $partial = false) { if (!$partial) { $path = trim(urldecode($path), self::URI_DELIMITER); $regex = '#^' . $this->_regex . '$#i'; } else { $regex = '#^' . $this->_regex . '#i'; } $res = preg_match($regex, $path, $values); if ($res === 0) { return false; } if ($partial) { $this->setMatchedPath($values[0]); } // array_filter_key()? Why isn't this in a standard PHP function set yet? :) foreach ($values as $i => $value) { if (!is_int($i) || $i === 0) { unset($values[$i]); } } $this->_values = $values; $values = $this->_getMappedValues($values); $defaults = $this->_getMappedValues($this->_defaults, false, true); $return = $values + $defaults; return $return; } /** * Maps numerically indexed array values to it's associative mapped counterpart. * Or vice versa. Uses user provided map array which consists of index => name * parameter mapping. If map is not found, it returns original array. * * Method strips destination type of keys form source array. Ie. if source array is * indexed numerically then every associative key will be stripped. Vice versa if reversed * is set to true. * * @param array $values Indexed or associative array of values to map * @param boolean $reversed False means translation of index to association. True means reverse. * @param boolean $preserve Should wrong type of keys be preserved or stripped. * @return array An array of mapped values */ protected function _getMappedValues($values, $reversed = false, $preserve = false) { if (count($this->_map) == 0) { return $values; } $return = array(); foreach ($values as $key => $value) { if (is_int($key) && !$reversed) { if (array_key_exists($key, $this->_map)) { $index = $this->_map[$key]; } elseif (false === ($index = array_search($key, $this->_map))) { $index = $key; } $return[$index] = $values[$key]; } elseif ($reversed) { $index = $key; if (!is_int($key)) { if (array_key_exists($key, $this->_map)) { $index = $this->_map[$key]; } else { $index = array_search($key, $this->_map, true); } } if (false !== $index) { $return[$index] = $values[$key]; } } elseif ($preserve) { $return[$key] = $value; } } return $return; } /** * Assembles a URL path defined by this route * * @param array $data An array of name (or index) and value pairs used as parameters * @return string Route path with user submitted parameters */ public function assemble($data = array(), $reset = false, $encode = false, $partial = false) { if ($this->_reverse === null) { //--//require_once 'Zend/Controller/Router/Exception.php'; throw new Am_Mvc_Router_Exception('Cannot assemble. Reversed route is not specified.'); } $defaultValuesMapped = $this->_getMappedValues($this->_defaults, true, false); $matchedValuesMapped = $this->_getMappedValues($this->_values, true, false); $dataValuesMapped = $this->_getMappedValues($data, true, false); // handle resets, if so requested (By null value) to do so if (($resetKeys = array_search(null, $dataValuesMapped, true)) !== false) { foreach ((array) $resetKeys as $resetKey) { if (isset($matchedValuesMapped[$resetKey])) { unset($matchedValuesMapped[$resetKey]); unset($dataValuesMapped[$resetKey]); } } } // merge all the data together, first defaults, then values matched, then supplied $mergedData = $defaultValuesMapped; $mergedData = $this->_arrayMergeNumericKeys($mergedData, $matchedValuesMapped); $mergedData = $this->_arrayMergeNumericKeys($mergedData, $dataValuesMapped); if ($encode) { foreach ($mergedData as $key => &$value) { $value = urlencode($value); } } ksort($mergedData); $return = @vsprintf($this->_reverse, $mergedData); if ($return === false) { //--//require_once 'Zend/Controller/Router/Exception.php'; throw new Am_Mvc_Router_Exception('Cannot assemble. Too few arguments?'); } return $return; } /** * Return a single parameter of route's defaults * * @param string $name Array key of the parameter * @return string Previously set default */ public function getDefault($name) { if (isset($this->_defaults[$name])) { return $this->_defaults[$name]; } } /** * Return an array of defaults * * @return array Route defaults */ public function getDefaults() { return $this->_defaults; } /** * Get all variables which are used by the route * * @return array */ public function getVariables() { $variables = array(); foreach ($this->_map as $key => $value) { if (is_numeric($key)) { $variables[] = $value; } else { $variables[] = $key; } } return $variables; } /** * _arrayMergeNumericKeys() - allows for a strict key (numeric's included) array_merge. * php's array_merge() lacks the ability to merge with numeric keys. * * @param array $array1 * @param array $array2 * @return array */ protected function _arrayMergeNumericKeys(Array $array1, Array $array2) { $returnArray = $array1; foreach ($array2 as $array2Index => $array2Value) { $returnArray[$array2Index] = $array2Value; } return $returnArray; } } Router/Route/Static.php000064400000007414152101613010011056 0ustar00defaults instanceof Zend_Config) ? $config->defaults->toArray() : array(); return new self($config->route, $defs); } /** * Prepares the route for mapping. * * @param string $route Map used to match with later submitted URL path * @param array $defaults Defaults for map variables with keys as variable names */ public function __construct($route, $defaults = array()) { $this->_route = trim($route, self::URI_DELIMITER); $this->_defaults = (array) $defaults; } /** * Matches a user submitted path with a previously defined route. * Assigns and returns an array of defaults on a successful match. * * @param string $path Path used to match against this routing map * @return array|false An array of assigned values or a false on a mismatch */ public function match($path, $partial = false) { if ($partial) { if ((empty($path) && empty($this->_route)) || (substr($path, 0, strlen($this->_route)) === $this->_route) ) { $this->setMatchedPath($this->_route); return $this->_defaults; } } else { if (trim($path, self::URI_DELIMITER) == $this->_route) { return $this->_defaults; } } return false; } /** * Assembles a URL path defined by this route * * @param array $data An array of variable and value pairs used as parameters * @return string Route path with user submitted parameters */ public function assemble($data = array(), $reset = false, $encode = false, $partial = false) { return $this->_route; } /** * Return a single parameter of route's defaults * * @param string $name Array key of the parameter * @return string Previously set default */ public function getDefault($name) { if (isset($this->_defaults[$name])) { return $this->_defaults[$name]; } return null; } /** * Return an array of defaults * * @return array Route defaults */ public function getDefaults() { return $this->_defaults; } } Router/Route/Abstract.php000064400000005455152101613010011375 0ustar00_matchedPath = $path; } /** * Get partially matched path * * @return string */ public function getMatchedPath() { return $this->_matchedPath; } /** * Check or set wether this is an abstract route or not * * @param boolean $flag * @return boolean */ public function isAbstract($flag = null) { if ($flag !== null) { $this->_isAbstract = $flag; } return $this->_isAbstract; } /** * Create a new chain * * @param Am_Mvc_Router_Route_Abstract $route * @param string $separator * @return Am_Mvc_Router_Route_Chain */ public function chain(Am_Mvc_Router_Route_Abstract $route, $separator = '/') { //--//require_once 'Zend/Controller/Router/Route/Chain.php'; $chain = new Am_Mvc_Router_Route_Chain(); $chain->chain($this)->chain($route, $separator); return $chain; } } Router/Route/Interface.php000064400000002316152101613010011523 0ustar00defaults instanceof Zend_Config) ? $config->defaults->toArray() : array(); return new self($config->route, $defs); } /** * Add a route to this chain * * @param Am_Mvc_Router_Route_Abstract $route * @param string $separator * @return Am_Mvc_Router_Route_Chain */ public function chain(Am_Mvc_Router_Route_Abstract $route, $separator = self::URI_DELIMITER) { $this->_routes[] = $route; $this->_separators[] = $separator; return $this; } /** * Matches a user submitted path with a previously defined route. * Assigns and returns an array of defaults on a successful match. * * @param Am_Mvc_Request_Http $request Request to get the path info from * @param null $partial * @return array|false An array of assigned values or a false on a mismatch */ public function match($request, $partial = null) { $path = trim($request->getPathInfo(), self::URI_DELIMITER); $subPath = $path; $values = array(); $numRoutes = count($this->_routes); $matchedPath = null; foreach ($this->_routes as $key => $route) { if ($key > 0 && $matchedPath !== null && $subPath !== '' && $subPath !== false ) { $separator = substr($subPath, 0, strlen($this->_separators[$key])); if ($separator !== $this->_separators[$key]) { return false; } $subPath = substr($subPath, strlen($separator)); } // TODO: Should be an interface method. Hack for 1.0 BC if (!method_exists($route, 'getVersion') || $route->getVersion() == 1) { $match = $subPath; } else { $request->setPathInfo($subPath); $match = $request; } $res = $route->match($match, true, ($key == $numRoutes - 1)); if ($res === false) { return false; } $matchedPath = $route->getMatchedPath(); if ($matchedPath !== null) { $subPath = substr($subPath, strlen($matchedPath)); $separator = substr($subPath, 0, strlen($this->_separators[$key])); } $values = $res + $values; } $request->setPathInfo($path); if ($subPath !== '' && $subPath !== false) { return false; } return $values; } /** * Assembles a URL path defined by this route * * @param array $data An array of variable and value pairs used as parameters * @param bool $reset * @param bool $encode * @return string Route path with user submitted parameters */ public function assemble($data = array(), $reset = false, $encode = false) { $value = ''; $numRoutes = count($this->_routes); foreach ($this->_routes as $key => $route) { if ($key > 0) { $value .= $this->_separators[$key]; } $value .= $route->assemble($data, $reset, $encode, (($numRoutes - 1) > $key)); if (method_exists($route, 'getVariables')) { $variables = $route->getVariables(); foreach ($variables as $variable) { $data[$variable] = null; } } } return $value; } /** * Set the request object for this and the child routes * * @param Am_Mvc_Request|null $request * @return void */ public function setRequest(Am_Mvc_Request $request = null) { $this->_request = $request; foreach ($this->_routes as $route) { if (method_exists($route, 'setRequest')) { $route->setRequest($request); } } } /** * Return a single parameter of route's defaults * * @param string $name Array key of the parameter * @return string Previously set default */ public function getDefault($name) { $default = null; foreach ($this->_routes as $route) { if (method_exists($route, 'getDefault')) { $current = $route->getDefault($name); if (null !== $current) { $default = $current; } } } return $default; } /** * Return an array of defaults * * @return array Route defaults */ public function getDefaults() { $defaults = array(); foreach ($this->_routes as $route) { if (method_exists($route, 'getDefaults')) { $defaults = array_merge($defaults, $route->getDefaults()); } } return $defaults; } } Router/Route/Module.php000064400000020213152101613010011044 0ustar00defaults instanceof Zend_Config) ? $config->defaults->toArray() : array(); $request = Am_Di::getInstance()->request; return new self($defs, $request); } /** * Constructor * * @param array $defaults Defaults for map variables with keys as variable names * @param Am_Mvc_Request $request Request object */ public function __construct(array $defaults = array(), Am_Mvc_Request $request = null) { $this->_defaults = $defaults; if (isset($request)) { $this->_request = $request; } } /** * Set request keys based on values in request object * * @return void */ protected function _setRequestKeys() { if (null !== $this->_request) { $this->_moduleKey = $this->_request->getModuleKey(); $this->_controllerKey = $this->_request->getControllerKey(); $this->_actionKey = $this->_request->getActionKey(); } $this->_defaults += array( $this->_controllerKey => 'index', $this->_actionKey => 'index', $this->_moduleKey => 'default', ); $this->_keysSet = true; } /** * Matches a user submitted path. Assigns and returns an array of variables * on a successful match. * * If a request object is registered, it uses its setModuleName(), * setControllerName(), and setActionName() accessors to set those values. * Always returns the values as an array. * * @param string $path Path used to match against this routing map * @return array An array of assigned values or a false on a mismatch */ public function match($path, $partial = false) { $this->_setRequestKeys(); $values = array(); $params = array(); if (!$partial) { $path = trim($path, self::URI_DELIMITER); } else { $matchedPath = $path; } if ($path != '') { $path = explode(self::URI_DELIMITER, $path); if (($path[0] == 'default') || in_array($path[0], Am_Di::getInstance()->modules->getEnabled())) { $values[$this->_moduleKey] = array_shift($path); $this->_moduleValid = true; } if (count($path) && !empty($path[0])) { $values[$this->_controllerKey] = array_shift($path); } if (count($path) && !empty($path[0])) { $values[$this->_actionKey] = array_shift($path); } if ($numSegs = count($path)) { for ($i = 0; $i < $numSegs; $i = $i + 2) { $key = urldecode($path[$i]); $val = isset($path[$i + 1]) ? urldecode($path[$i + 1]) : null; $params[$key] = (isset($params[$key]) ? (array_merge((array) $params[$key], array($val))): $val); } } } if ($partial) { $this->setMatchedPath($matchedPath); } $this->_values = $values + $params; return $this->_values + $this->_defaults; } /** * Assembles user submitted parameters forming a URL path defined by this route * * @param array $data An array of variable and value pairs used as parameters * @param bool $reset Weither to reset the current params * @return string Route path with user submitted parameters */ public function assemble($data = array(), $reset = false, $encode = true, $partial = false) { if (!$this->_keysSet) { $this->_setRequestKeys(); } $params = (!$reset) ? $this->_values : array(); foreach ($data as $key => $value) { if ($value !== null) { $params[$key] = $value; } elseif (isset($params[$key])) { unset($params[$key]); } } $params += $this->_defaults; $url = ''; if ($this->_moduleValid || array_key_exists($this->_moduleKey, $data)) { if ($params[$this->_moduleKey] != $this->_defaults[$this->_moduleKey]) { $module = $params[$this->_moduleKey]; } } unset($params[$this->_moduleKey]); $controller = $params[$this->_controllerKey]; unset($params[$this->_controllerKey]); $action = $params[$this->_actionKey]; unset($params[$this->_actionKey]); foreach ($params as $key => $value) { $key = ($encode) ? urlencode($key) : $key; if (is_array($value)) { foreach ($value as $arrayValue) { $arrayValue = ($encode) ? urlencode($arrayValue) : $arrayValue; $url .= self::URI_DELIMITER . $key; $url .= self::URI_DELIMITER . $arrayValue; } } else { if ($encode) $value = urlencode($value); $url .= self::URI_DELIMITER . $key; $url .= self::URI_DELIMITER . $value; } } if (!empty($url) || $action !== $this->_defaults[$this->_actionKey]) { if ($encode) $action = urlencode($action); $url = self::URI_DELIMITER . $action . $url; } if (!empty($url) || $controller !== $this->_defaults[$this->_controllerKey]) { if ($encode) $controller = urlencode($controller); $url = self::URI_DELIMITER . $controller . $url; } if (isset($module)) { if ($encode) $module = urlencode($module); $url = self::URI_DELIMITER . $module . $url; } return ltrim($url, self::URI_DELIMITER); } /** * Return a single parameter of route's defaults * * @param string $name Array key of the parameter * @return string Previously set default */ public function getDefault($name) { if (isset($this->_defaults[$name])) { return $this->_defaults[$name]; } } /** * Return an array of defaults * * @return array Route defaults */ public function getDefaults() { return $this->_defaults; } } Router/Exception.php000064400000002076152101613010010466 0ustar00view = $invokeArgs['di']->view; parent::__construct($request, $response, $invokeArgs); } /** @return Am_Di */ function getDi() { return $this->_invokeArgs['di']; } /** * Return variable from aMember config * @param string $key * @return mixed */ function getConfig($key, $default = null) { return $this->_invokeArgs['di']->config->get($key, $default); } /** @return Am_View */ function getView() { return $this->view; } public function _checkPermissions() { if (stripos($this->_request->getControllerName(), 'admin') === 0) { if ($this instanceof AdminAuthController) return; $admin = $this->getDi()->authAdmin->getUser(); if (!$admin) throw new Am_Exception_InternalError("Visitor has got access to admin controller without admin authentication!"); if (!$this->checkAdminPermissions($admin)) throw new Am_Exception_AccessDenied("Admin [{$admin->login}] has no permissions to do selected operation in " . get_class($this)); } } public function setActiveMenu($id) { $this->getView()->headScript()->appendScript('window.amActiveMenuID = "' . $id . '";'); } /** * * @param Admin $admin */ public function checkAdminPermissions(Admin $admin) { throw new Am_Exception_NotImplemented(__FUNCTION__ . " must be implemented in " . get_class($this)); } /** * Call required action * @param $actionName */ public function dispatch($action) { // Notify helpers of action preDispatch state $this->_helper->notifyPreDispatch(); $this->_checkPermissions(); try { $this->preDispatch(); } catch (Am_Exception_Redirect $e) { $this->postDispatch(); $this->_helper->notifyPostDispatch(); return; } if (!$this->isProcessed()) { if ($this->getRequest()->isDispatched()) { if (null === $this->_classMethods) { $this->_classMethods = get_class_methods($this); } // preDispatch() didn't change the action, so we can continue try { if ($this->getInvokeArg('useCaseSensitiveActions') || in_array($action, $this->_classMethods)) { if ($this->getInvokeArg('useCaseSensitiveActions')) { trigger_error('Using case sensitive actions without word separators is deprecated; please do not rely on this "feature"'); } $this->_runAction($action); } else { $this->__call($action, array()); } } catch (Am_Exception_Redirect $e) { // all ok, we just called it for GOTO } $this->postDispatch(); } } // whats actually important here is that this action controller is // shutting down, regardless of dispatching; notify the helpers of this // state $this->_helper->notifyPostDispatch(); } /** * After running this function $this->_response must be filled-in * @param string $action */ public function _runAction($action) { ob_start(); $this->$action(); $this->getResponse()->appendBody(ob_get_clean()); } public function _setInvokeArgs(array $args = array()) { return parent::_setInvokeArgs($args); } public function __call($methodName, $args) { // deprecated functions switch ($methodName) { case 'getJson': return json_encode($args[0]); case 'isAjax': return $this->_request->isXmlHttpRequest(); case 'ajaxResponse': return call_user_func_array(array($this->_response, 'ajaxResponse'), $args); } require_once 'Zend/Controller/Action/Exception.php'; if ('Action' == substr($methodName, -6)) { $action = substr($methodName, 0, strlen($methodName) - 6); throw new Zend_Controller_Action_Exception(sprintf('Action "%s" does not exist in %s and was not trapped in __call()', $action, get_class($this)), 404); } throw new Zend_Controller_Action_Exception(sprintf('Method "%s" does not exist and was not trapped in __call()', $methodName), 500); } /** * Run htmlentities() for the string * @param string string to escape * @return string escaped string * @deprecated do not call it in static context! */ function escape($string) { return htmlentities($string, ENT_QUOTES, 'UTF-8', false); } /** * @deprecated Please do not call these functions ! * @param type $name * @param type $arguments */ public static function __callStatic($name, $arguments) { $replaceMap = array( 'getJson' => 'json_encode', 'escape' => array('Am_Html', 'escape'), 'renderOptions' => array('Am_Html', 'renderOptions'), 'renderArrayAsInputHiddens' => array('Am_Html', 'renderArrayAsInputHiddens'), 'getArrayOfInputHiddens' => array('Am_Html', 'getArrayOfInputHiddens'), 'setCookie' => array('Am_Cookie', 'set'), 'redirectLocation' => array(Am_Di::getInstance()->response, 'redirectLocation'), 'ajaxResponse' => array(Am_Di::getInstance()->response, 'ajaxResponse'), 'getFullUrl' => array(Am_Di::getInstance()->request, 'getFullUrl'), ); if ($name == 'decodeJson') return json_decode($arguments[0], true); elseif (!empty($replaceMap[$name])) return call_user_func_array($replaceMap[$name], $arguments); else throw new Exception("Static method [$name] does not exists in " . __CLASS__); } public function isProcessed() { return $this->processed; } /** call this to stop request processing */ public function setProcessed($flag = true) { $this->processed = (bool) $flag; } public function isPost() { return $this->_request->isPost(); } public function isGet() { return $this->_request->isGet(); } /** @return mixed request parameter of if not exists in request, then $default value */ function getParam($key, $default=null) { return $this->_request->getParam($key, $default); } /** @return int the same as get param but with intval(...) applied */ function getInt($key, $default=0) { return $this->_request->getInt($key, $default); } /** @return string request parameter with removed chars except the a-zA-Z0-9-_ */ function getFiltered($key, $default=null) { return $this->_request->getFiltered($key, $default); } /** @return string request parameter with htmlentities(..) applied */ function getEscaped($key, $default=null) { return $this->_request->getEscaped($key, $default); } /** * Redirect customer to new url * @param $targetTop useful when doing a redirect in AJAX generated html */ function redirectHtml($url, $text='', $title='Redirecting...', $targetTop=false, $proccessed = null, $total = null) { $this->view->assign('title', $title); $this->view->assign('text', $text); $this->view->assign('url', $url); if (!is_null($total)) { $width = (100 * $proccessed) / $total; $this->view->width = min(100, round($width)); $this->view->showProgressBar = true; $this->view->total = $total; $this->view->proccessed = $proccessed; } if ($targetTop) $this->view->assign('target', '_top'); if (ob_get_level ()) ob_end_clean(); $this->getResponse()->setBody($this->view->render(defined('AM_ADMIN') ? 'admin/redirect.phtml' : 'redirect.phtml')); throw new Am_Exception_Redirect($url); // exit gracefully } function getUrl($controller = null, $action = null, $module = null, $params = null) { return call_user_func_array(array($this->getDi()->request, 'makeUrl'), func_get_args()); } function url($path, $params = null, $encode = true, $absolute = false) { return call_user_func_array(array($this->getDi(), 'url'), func_get_args()); } function rurl($path, $params = null, $encode = true) { return call_user_func_array(array($this->getDi(), 'rurl'), func_get_args()); } function surl($path, $params = null, $encode = true) { return call_user_func_array(array($this->getDi(), 'surl'), func_get_args()); } /** * @return Zend_Session_Namespace */ public function getSession() { return $this->getDi()->session; } /** @return Am_Module|null */ public function getModule() { $module = $this->_request->getModuleName(); if ($module == 'default') return null; return $this->getDi()->modules->get($module); } protected function _redirect($url, array $options = array()) { if (!preg_match('#^(//|http)#', $url) || !empty($options['prependBase'])) $url = $this->getDi()->url($url, false); $this->_helper->redirector->setExit(false); $options['prependBase'] = false; parent::_redirect($url, $options); throw new Am_Exception_Redirect($url); } } Request.php000064400000033172152101613010006701 0ustar00_vars instead of _GET and _POST */ const USE_VARS = 'vars'; protected $_vars = array(); protected $_remoteAddr = array(); protected $_method; protected $_scheme; protected $_host; protected $_baseUrl, $_pathInfo; function __construct(array $vars=null, $method=null, $uri = null) { if (is_string($uri)) { $saved = $_SERVER['REQUEST_URI']; $_SERVER['REQUEST_URI'] = $uri; parent::__construct(null); $_SERVER['REQUEST_URI'] = $saved; } else parent::__construct (); if ($method!==null) $this->_method = $method; $this->setParamSources(array($this->getMethod() == self::METHOD_POST ? '_POST' : '_GET')); if ($vars !== null) { if ($vars instanceof Am_Mvc_Request) throw new Am_Exception_InternalError("Could not initialize Am_Mvc_Request with Am_Mvc_Request, use clone()"); $this->_vars = (array)$vars; $this->setParamSources(array(self::USE_VARS)); } elseif (get_magic_quotes_gpc()) // array $vars must be already escaped if we get it above if ($this->getMethod() == self::METHOD_POST) $_POST = self::ss($_POST); else $_GET = self::ss($_GET); } function getHttpHost() { return $this->_host ? $this->_host : parent::getHttpHost(); } public function getMethod() { return $this->_method ? $this->_method : parent::getMethod(); } public function getScheme() { return $this->_scheme ? $this->_scheme : parent::getScheme(); } public function isPost() { return $this->getMethod() == self::METHOD_POST; } public function isGet() { return $this->getMethod() == self::METHOD_GET; } public function getPost($k = null, $default = null) { if (in_array('vars', $this->getParamSources())) { if (!$this->isPost()) return $k === null ? array() : null; if ($k === null) return $this->_vars; else return isset($this->_vars[$k]) ? $this->_vars[$k] : $default; } return parent::getPost($k, $default); } public function getQuery($k = null, $default = null) { if (in_array('vars', $this->getParamSources())) { if (!$this->isGet()) return $k === null ? array() : null; if ($k === null) return $this->_vars; else return isset($this->_vars[$k]) ? $this->_vars[$k] : $default; } else return parent::getQuery($k, $default); } function set($key, $value) { $this->setParam($key, $value); } /** aliases for @see getParam */ function get($key, $default=null) { return $this->getParam($key, $default); } /** @return int the same as get param but with intval(...) applied */ function getInt($key, $default=0) { $ret = $this->getParam($key, $default); if ($ret === null) return null; return intval($ret); } /** @return string request parameter with removed chars except the a-zA-Z0-9-_ */ function getFiltered($key, $default=null){ $ret = $this->getParam($key, $default); if ($ret === null) return null; return preg_replace('/[^a-zA-Z0-9_-]/', '', $ret); } /** @return string request parameter with htmlentities(..) applied */ function getEscaped($key, $default=null){ $ret = $this->getParam($key, $default); if ($ret === null) return null; return Am_Html::escape($ret); } function toArray() { return $this->getRequestOnlyParams(); } function fromArray(array $vars){ $this->setParams($vars); } public function offsetSet($offset, $value) { throw new Am_Exception_InternalError("Am_Mvc_Request::ArrayAccess interface does not allow setting values, use set() method instead"); } /** * Remove quotes added by 'magic_quotes_gpc' * @param mixed $value * @return mixed */ static function ss($value) { if ($value instanceof Am_Mvc_Request) return $value; // already escaped $value = is_array($value) ? array_map(array(__CLASS__, 'ss'), $value) : stripslashes($value); return $value; } /** for HTML_QuickForm2_Datasource interface * @todo optimize? - remove toArray() from here */ public function getValue($name) { if (strpos($name, '[')) { $tokens = explode('[', str_replace(']', '', $name)); $value = $this->toArray(); do { $token = array_shift($tokens); if (!is_array($value) || !isset($value[$token])) { return null; } $value = $value[$token]; } while (!empty($tokens)); return $value; } else { return $this->get($name); } } public function getUpload($name) { $_fileKeys = array('name', 'type', 'size', 'tmp_name', 'error'); if (empty($_FILES)) { return null; } if (false !== ($pos = strpos($name, '['))) { $tokens = explode('[', str_replace(']', '', $name)); $base = array_shift($tokens); $value = array(); if (!isset($_FILES[$base]['name'])) { return null; } foreach ($_fileKeys as $key) { $value[$key] = $_FILES[$base][$key]; } do { $token = array_shift($tokens); if (!isset($value['name'][$token])) { return null; } foreach ($_fileKeys as $key) { $value[$key] = $value[$key][$token]; } } while (!empty($tokens)); return $value; } elseif(isset($_FILES[$name])) { return $_FILES[$name]; } else { return null; } } /** * return only parameters coming with $_POST/$_GET requests * not include current * @return array */ public function getRequestOnlyParams() { $x = $this->_params; $this->_params = array(); $ret = $this->getParams(); $this->_params = $x; return $ret; } public function __toString() { return print_r($this->getRequestOnlyParams(), true); } /** @return dummy object just for usage when it is formally required */ static function createEmpty() { return new self(array(), self::METHOD_GET, null); } public function serialize() { $arr = get_object_vars($this); unset($arr['_paramSources']); $arr['_vars'] = $this->getRequestOnlyParams(); $arr['_method'] = $this->getMethod(); $arr['_schemeAndHost'] = $this->getScheme() . '://' . $this->getHttpHost(); $arr['_remoteAddr'] = $this->getClientIp(false); foreach ($arr as $k => $v) if (empty($v)) unset($arr[$k]); return serialize($arr); } public function unserialize($serialized) { $arr = unserialize($serialized); @$this->__construct($arr['_vars'], $arr['_method']); foreach (array('_remoteAddr', '_requestUri', '_params', '_moduleKey', '_module', '_controllerKey', '_controller', '_actionKey', '_action') as $k) $this->$k = @$arr[$k]; } public function getParams() { $ret = parent::getParams(); if (in_array(self::USE_VARS, $this->_paramSources) && is_array($this->_vars)) $ret += $this->_vars; return $ret; } public function getParam($key, $default = null) { $keyName = (null !== ($alias = $this->getAlias($key))) ? $alias : $key; $paramSources = $this->getParamSources(); if (isset($this->_params[$keyName])) { return $this->_params[$keyName]; } elseif (in_array('_GET', $paramSources) && (isset($_GET[$keyName]))) { return $_GET[$keyName]; } elseif (in_array('_POST', $paramSources) && (isset($_POST[$keyName]))) { return $_POST[$keyName]; } elseif (in_array(self::USE_VARS, $paramSources) && (isset($this->_vars[$keyName]))) { return $this->_vars[$keyName]; } return $default; } public function __get($key) { switch (true) { case isset($this->_params[$key]): return $this->_params[$key]; case isset($this->_vars[$key]): return $this->_vars[$key]; } return parent::__get($key); } public function getClientIp($checkProxy = false) { if (!empty($this->_remoteAddr)) return $this->_remoteAddr; return parent::getClientIp($checkProxy); } public function getPathInfo() { if (!empty($this->_pathInfo)) return $this->_pathInfo; return parent::getPathInfo(); } /** * Assemble url based on http host,port,method, and GET params * @return string full url */ public function assembleUrl($noHost = false, $noQuery = false) { $ret = ""; if (!$noHost) { $ret .= $this->isSecure() ? 'https://' : 'http://'; $ret .= $this->getHttpHost(); } $ret .= $this->getBaseUrl(); $ret .= $this->getPathInfo(); if (!$noQuery && ($query = $this->getQuery())) $ret .= '?' . http_build_query($query, '', '&'); return $ret; } function makeUrl($controller=null, $action=null, $module=null, $params = null) { $args = func_get_args(); for ($i=0;$i<=2;$i++) if (!isset($args[$i])) $args[$i] = null; if ($args[0] === null) $args[0] = $this->getControllerName(); if ($args[1] === null) $args[1] = $this->getActionName(); if ($args[2] === null && $this->getModuleName() != 'default') $args[2] = $this->getModuleName(); $res = ($args[2] ? '/'.$args[2] : "") . '/' . Am_Html::escape($args[0]) . '/' . Am_Html::escape($args[1]); $res = ltrim($res, '/'); $get = array(); if (count($args) > 3) { for ($i=3;$iurl($res, $get, false); } /** * Because libxml access UTF-8 data only, we have to check incoming stings and make sure they are UTF-8 * **/ protected function toUTF8($v){ if(!mb_check_encoding($v, 'UTF-8')) return mb_convert_encoding($v, 'UTF-8'); return $v; } function toXml(XmlWriter $x) { $x->startElement('url'); $x->startElement('method'); $x->text($this->getMethod()); $x->endElement(); $x->startElement('scheme'); $x->text($this->getScheme()); $x->endElement(); $x->startElement('base_url'); $x->text($this->getBaseUrl(true)); $x->endElement(); $x->startElement('path_info'); $x->text($this->getPathInfo()); $x->endElement(); $x->startElement('host'); $x->text($this->getHttpHost()); $x->endElement(); $x->startElement('remote_addr'); $x->text($this->getClientIp(false)); $x->endElement(); $x->endElement(); $x->startElement('params'); $count = 0; foreach ($this->getRequestOnlyParams() as $k => $v) { $count++; $x->startElement('param'); $x->writeAttribute('name', $this->toUTF8($k)); if (is_array($v) || is_object($v)) { $v = json_encode($v); $x->writeAttribute("serialized", "json"); $x->writeCdata($this->toUTF8($v)); } else { $x->text($this->toUTF8($v)); } $x->endElement(); } $x->endElement(); if (!$count) { $x->startElement('raw-body'); $x->writeCdata($this->getRawBody()); $x->endElement(); } } static function fromXml($xmlString) { $vars = array(); if ($xmlString->params) foreach ($xmlString->params->param as $p) { $v = (string)$p; if ((string)$p['serialized'] == 'json') $v = json_decode($p, true); $vars[(string)$p['name']] = $v; } $url = $xmlString->url; $uri = (string)$url->scheme . '://' . (string)$url->host . (string)$url->base_url . (string)$url->path_info; $r = new Am_Mvc_Request($vars, (string)$url->method, $uri ); $r->_baseUrl = (string)$url->base_url; $r->_pathInfo = (string)$url->path_info; $r->_remoteAddr = (string)$url->remote_addr; $r->_scheme = (string)$url->scheme; $r->_host = (string)$url->host; if ($xmlString->{'raw-body'}) { $r->setRawBody((string)$xmlString->{'raw-body'}); } return $r; } /** @access private */ function setRawBody($content) { $this->_rawBody = $content; } }Controller/AdminCategory.php000064400000003300152101613010012110 0ustar00view->isAjax = $this->_request->isXmlHttpRequest(); if (!$this->_request->isXmlHttpRequest()) { $this->view->title = $this->getTitle(); } $this->view->note = $this->getNote(); $this->view->nodes = $this->getTable()->getTree(); $this->view->tmpl = $this->getTable()->createRecord(); $this->view->display('admin/category.phtml'); } function saveAction() { $id = $this->getInt('id'); if ($id) { $c = $this->getTable()->load($id); } else { $c = $this->getTable()->createRecord(); } $c->title = $this->getParam('title'); $c->description = $this->getParam('description'); if (!is_null($code = $this->getParam('code'))) $c->code = $code; $c->parent_id = $this->getInt('parent_id'); $c->sort_order = $this->getInt('sort_order'); $c->save(); return $this->_response->ajaxResponse($c->toArray() + array('id' => $c->pk())); } function delAction() { $id = $this->getInt('id'); if (!$id) throw new Am_Exception_InputError(___('Wrong id')); $c = $this->getTable()->load($id); $this->getTable()->moveNodes($c->pk(), $c->parent_id); $c->delete(); echo 'OK'; } function optionsAction() { return $this->_response->ajaxResponse($this->getTable()->getOptions()); } protected function getNote() { return ''; } } Controller/Action/Helper/SendFile.php000064400000022426152101613010013521 0ustar00getResponse(); $cacheControl = array(); if (isset($options['public']) && $options['public']) { $cacheControl[] = 'public'; } if (isset($options['no-cache']) && $options['no-cache']) { $cacheControl[] = 'no-cache'; } if (isset($options['no-store']) && $options['no-store']) { $cacheControl[] = 'no-store'; } if (isset($options['must-revalidate']) && $options['must-revalidate']) { $cacheControl[] = 'must-revalidate'; } if (isset($options['proxy-validation']) && $options['proxy-validation']) { $cacheControl[] = 'proxy-validation'; } if (isset($options['max-age'])) { $cacheControl[] = 'max-age=' . (int) $options['max-age']; $response->setHeader('Expires', gmdate('r', time() + $options['max-age']), true); } if (isset($options['s-maxage'])) { $cacheControl[] = 's-maxage=' . (int) $options['s-maxage']; } $response->setHeader('Cache-Control', implode(',', $cacheControl), true); $response->setHeader('Pragma', 'public', true); } /** * Validate the cache using the If-Modified-Since request header * * @param int $modified When the file was last modified as a unix timestamp * @return bool */ protected function notModifiedSince($modified) { if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $modified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { // Send a 304 Not Modified header $response = $this->getResponse(); $response->setHttpResponseCode(304); $response->sendHeaders(); return true; } return false; } /** * Check whether it is range request using the HTTP_RANGE request header * * @param int $modified When the file was last modified as a unix timestamp * @return bool */ protected function isRangeRequest() { return isset($_SERVER['HTTP_RANGE']); } /** * Send a file for download * * @param string $path Path to the file * @param string $type The mime-type of the file * @param array $options * @return bool Whether the headers and file were sent */ public function sendFile($path, $type, $options = array()) { while (@ob_end_clean()); Zend_Session::writeClose(); $response = $this->getResponse(); if (!is_readable($path)) throw new Am_Exception_InternalError("File [$path] does not exists"); if (!$response->canSendHeaders()) throw new Am_Exception_InternalError("Headers are already sent"); // Set the cache-control if (isset($options['cache'])) { $this->setCacheHeaders($options['cache']); } // Get the last modified time if (isset($options['modified'])) { $modified = (int) $options['modified']; } else { $modified = filemtime($path); } // Validate the cache if (!isset($options['cache']['no-store']) && $this->notModifiedSince($modified)) { return true; } // Set the file name if (isset($options['filename']) && !empty($options['filename'])) { $filename = $options['filename']; } else { $filename = basename($path); } // Set the content disposition if (isset($options['disposition']) && $options['disposition'] == 'inline') { $disposition = 'inline'; } else { $disposition = 'attachment'; } $response->setHeader('Content-Type', $type, true); $response->setHeader('Content-Disposition', $disposition . '; filename="' . $filename . '"', true); $response->setHeader('Last-Modified', gmdate('r', $modified), true); $response->setHeader('Accept-Ranges', 'bytes', true); // Do we want to use the X-Sendfile header or stream the file if (isset($options['xsendfile']) && $options['xsendfile']) { $response->setHeader('X-Sendfile', $path); $response->sendHeaders(); return true; } if ($this->isRangeRequest()) { return $this->sendFileRange($path); } $response->setHttpResponseCode(200); $response->setHeader('Content-Length', filesize($path), true); $response->sendHeaders(); readfile($path); exit(); } /** * Send file data as a download * * @param string $path Path to the file * @param string $type The mime-type of the file * @param string $filename The filename to send the file as, if null then use the base name of the path * @param array $options * @return bool Whether the headers and file were sent */ public function sendData($data, $type, $filename, $options = array()) { $response = $this->getResponse(); if (!$response->canSendHeaders()) { return false; } // Set the cache-control if (isset($options['cache'])) { $this->setCacheHeaders($options['cache']); } if (isset($options['modified'])) { // Validate the cache if (!isset($options['cache']['no-store']) && $this->notModifiedSince($options['modified'])) { return true; } $response->setHeader('Last-Modified', gmdate('r', $options['modified']), true); } // Set the content disposition if (isset($options['disposition']) && $options['disposition'] == 'inline') { $disposition = 'inline'; } else { $disposition = 'attachment'; } $response->setHttpResponseCode(200); $response->setHeader('Content-Type', $type, true); $response->setHeader('Content-Disposition', $disposition . '; filename="' . $filename . '"', true); $response->setHeader('Content-Length', strlen($data), true); $response->setBody($data); } /** * Proxy method for sendFile * * @param string $path Path to the file * @param string $type The mime-type of the file * @param array $options * @return bool Whether the headers and file were sent */ public function direct($path, $type, $options = array()) { return $this->sendFile($path, $type, $options); } /** * Send a file range for download * http://tools.ietf.org/html/rfc2616#section-14.35 * * @param string $path */ protected function sendFileRange($path) { $response = $this->getResponse(); $filesize = filesize($path); preg_match('/bytes=(.*)/', $_SERVER['HTTP_RANGE'], $matches); $ranges = $this->_parseRange($matches[1], $filesize); //we process only first range now foreach ($ranges as $first_byte => $last_byte) break; $length = $last_byte - $first_byte + 1; $file = fopen($path, 'r'); fseek($file, $first_byte); $response->setHttpResponseCode(206); $response->setHeader('Content-Range', 'bytes ' . $first_byte . '-' . $last_byte . '/' . $filesize, true); $response->setHeader('Content-Length', $length, true); $response->sendHeaders(); $chunk = 1024*1024; for($i=$first_byte; $i<$last_byte; $i+=$chunk) print fread($file, min($chunk,$last_byte-$i+1)); fclose($file); exit(); } public function _parseRange($range_spec, $filesize) { $ranges = array(); foreach (explode(',', $range_spec) as $range) { list($first_byte, $last_byte) = explode('-', $range); if ($first_byte == '') { //bytes=-500 *last 500 bytes $first_byte = $filesize - $last_byte; $last_byte = $filesize-1; } else { //bytes=500-999 *500 bytes range //bytes=9500- *from 9500 up to the end $first_byte = intval($first_byte); $last_byte = min(($filesize-1), (($last_byte == '') ? ($filesize-1) : intval($last_byte))); } if ($first_byte > $last_byte) continue; $ranges[$first_byte] = isset($ranges[$first_byte]) ? max($ranges[$first_byte], $last_byte) : $last_byte; } ksort($ranges); $collapsed = array(); $prev = -1000; //just value that is always less foreach ($ranges as $first => $last) { if ($first <= ($prev + 1)) { $prev = $last; } else { $collapsed[$first] = $last; $prev = & $collapsed[$first]; } } return $collapsed; } }Controller/Plugin.php000064400000004743152101613010010634 0ustar00di = $di; } public function preDispatch(Zend_Controller_Request_Abstract $request) { // check if we need to handle admin auth if (stripos($this->getRequest()->getControllerName(), 'admin')===0) { defined('AM_ADMIN') || define('AM_ADMIN', true); if (($this->di->authAdmin->getUserId() <= 0) && $request->getControllerName() != 'admin-auth') { $request->setControllerName('admin-auth')->setActionName('index')->setModuleName('default'); } // check for maintenance mode } elseif ($msg = $this->di->config->get('maintenance')) { if (!$this->di->authAdmin->getUserId()) return amMaintenance($msg); } // check if we are accessing disabled module $module = $request->getModuleName(); if ($module != 'default') { if (!$this->di->modules->isEnabled($module)) throw new Am_Exception_InputError(___('You are trying to access disabled module [%s]', htmlentities($module))); } if ($request->getModuleName() == 'default' && $request->getControllerName() == 'upload' && $request->getActionName() == 'get') return; //exception for theme logo if ($request->getModuleName() == 'default' && $request->getControllerName() == 'direct' && $request->getParam('plugin_id') == 'avatar') return; //exception for avatar if ($request->getModuleName() == 'default' && $request->getControllerName() == 'login' && $request->getActionName() == 'logout') return; //exception for logout if (!$this->di->authAdmin->getUserId() && $this->di->config->get('force_change_password')) { if ($this->di->auth->getUserId() && $this->di->auth->getUser()->pass_dattm < sqlTime(sprintf('-%d day', $this->di->config->get('force_change_password_period', 30)))) { $request->setControllerName('login') ->setActionName('change-pass') ->setModuleName('default'); } } } }Controller/Auth.php000064400000016656152101613010010305 0ustar00session) $this->session = new Zend_Session_Namespace('login-controller'); if (!$this->session->login_attempt_id) { $this->session->login_attempt_id = array(); } } public function onLogin() { if ($login_attempt_id = $this->_request->getParam('login_attempt_id')) { $this->session->login_attempt_id[] = $login_attempt_id; } return $this->redirectOk(); } public function logoutAction() { $this->getAuth()->logout(); unset($this->getSession()->signup_member_id); unset($this->getSession()->signup_member_login); $this->redirectLogout(); } public function getLogin() { return $this->getParam($this->loginField); } public function getPass() { return $this->isPost() ? $this->getParam($this->passField) : null; } public function indexAction() { if (null != $this->getAuth()->getUsername()) return $this->redirectOk(); $authResult = null; $authError = null; if ($this->getRequest()->isPost()) { $e = new Am_Event(Am_Event::AUTH_CONTROLLER_HANDLER); $e->setReturn(array($this, 'doLogin')); $this->getDi()->hook->call($e); $authResult = call_user_func($e->getReturn(), $this->getAuth(), $this->getRequest()); if ($authResult->isValid()) { return $this->onLogin(); } elseif (!$authResult->isContinue()) $authError = array($authResult->getMessage()); } $this->view->loginFieldValue = $this->getLogin(); $this->view->loginFieldName = $this->loginField; $this->view->passFieldName = $this->passField; $this->view->hidden = $this->getHiddenVars(); $this->view->error = $authError; $showRecaptcha = Am_Recaptcha::isConfigured() && ( ($authResult && ($authResult->getCode() == Am_Auth_Result::FAILURE_ATTEMPTS_VIOLATION)) || $this->getDi()->config->get($this->configPrefix . 'recaptcha') ); $this->view->showRecaptcha = $showRecaptcha; $e = new Am_Event(Am_Event::AUTH_CONTROLLER_HTML, array('request' => $this->getRequest(), 'hiddenVars' => $this->getHiddenVars())); $e->setReturn($this->renderLoginForm($authResult)); $this->getDi()->hook->call($e); $html = $e->getReturn(); if ($this->_request->isXmlHttpRequest() && $this->getRequest()->isPost()) { $ret = array( 'ok' => $authResult ? $authResult->isValid() : false, 'error' => $authError, 'code' => $authResult ? $authResult->getCode() : null, 'html' => $html ); if ($showRecaptcha) { $ret['recaptcha_key'] = $this->getDi()->recaptcha->getPublicKey(); } return $this->_response->ajaxResponse($ret); } echo $this->renderLoginPage($html); } /** * @return array of key=>value to pass between requests */ public function getHiddenVars() { return array( 'login_attempt_id' => $this->_request->getParam('login_attempt_id', time()) ); } /** @return Am_Auth_Result */ public function doLogin(Am_Auth_Abstract $auth, Am_Mvc_Request $r) { //we can check captcha only once, //it return false for subsequent requests $isCaptchaValid = false; if (($rr = $r->getParam('g-recaptcha-response')) && Am_Recaptcha::isConfigured() && $this->getDi()->recaptcha->validate($rr)) { $isCaptchaValid = true; $this->getProtector()->deleteRecord($r->getClientIp()); } if ($this->getDi()->config->get($this->configPrefix . 'recaptcha') && !$isCaptchaValid) { return new Am_Auth_Result(Am_Auth_Result::INVALID_INPUT, ___('Anti Spam check failed')); } if ($login_attempt_id = $r->getParam('login_attempt_id')) if (in_array($login_attempt_id, $this->session->login_attempt_id)) return new Am_Auth_Result(Am_Auth_Result::INVALID_INPUT, ___('Session expired, please enter username and password again')); $bp = $this->getProtector(); $wait = $bp->loginAllowed($r->getClientIp()); $ip = $r->getClientIp(); if (null !== $wait) { // this customer have to wait before next attempt do { if (!$this->getDi()->config->get('bruteforce_notify')) break; if ($this->getDi()->store->get('bruteforce-' . $ip)) break; //action already done $this->getDi()->store->set('bruteforce-' . $ip, 1, '+20 minutes'); $et = Am_Mail_Template::load('bruteforce_notify'); if (!$et) break; $et->setIp($ip); $et->setLogin($this->getLogin()); $et->sendAdmin(); } while (false); $fail = new Am_Auth_Result(Am_Auth_Result::FAILURE_ATTEMPTS_VIOLATION, ___('Please wait %d seconds before next login attempt', $wait)); $fail->wait = $wait; return $fail; } $adapter = $this->createAdapter(); $that = $this; $res = $auth->login($adapter, $r->getClientIp(), true, function($user, $ip) use ($auth, $that) { $e = new Am_Event(Am_Event::AUTH_CONTROLLER_SET_USER, array('ip' => $ip)); $e->setReturn($user); $that->getDi()->hook->call($e); if ($user = $e->getReturn()) { $auth->setUser($user, $ip); } }); if (!$res->isValid()) { $bp->reportFailure($r->getClientIp(), $this->getLogin()); } return $res; } public function filterUrl($url) { return strip_tags($url); } abstract public function getLogoutUrl(); abstract public function getOkUrl(); public function redirectOk() { $this->_response->redirectLocation($this->filterUrl($this->getOkUrl())); } public function redirectLogout() { $this->_response->redirectLocation($this->filterUrl($this->getLogoutUrl())); } public function getProtector() { if (null == $this->protector) { $this->protector = new Am_Auth_BruteforceProtector( $this->getDi()->db, $this->getDi()->config->get($this->configPrefix . 'bruteforce_count', 5), $this->getDi()->config->get($this->configPrefix . 'bruteforce_delay', 120), $this->loginType); } return $this->protector; } }Controller/Grid.php000064400000001455152101613010010260 0ustar00grid = $this->createGrid(); parent::preDispatch(); } abstract function createGrid(); public function indexAction() { if (is_null($this->layout)) { echo $this->grid->run(); } else { $this->grid->runWithLayout($this->layout); } } function renderTd($s, $escape = true) { return '' . ($escape ? $this->escape($s) : $s) . '' . PHP_EOL; } }Controller/Pages.php000064400000012005152101613010010423 0ustar00id = $id; $this->title = $title; $this->callback = $callback; } public function getId() { return $this->id; } public function getTitle() { return $this->title; } public function getPerformer(Am_Mvc_Controller_Pages $controller) { $callback = $this->callback; if (is_string($callback)) $page = new $callback($controller->getRequest(), $controller->view); else $page = call_user_func($callback, $this->id, $this->title, $controller); if (!is_object($page)) throw new Am_Exception_InternalError("Could not ".__METHOD__."({$this->id}) - not an object"); return $page; } } /** * This class represents a controller with several tabs * every page is a separate and rendered by a widget * In most common case it is an Am_Grid * * @see Am_Mvc_Controller_Pages_Page * @package Am_Mvc_Controller */ abstract class Am_Mvc_Controller_Pages extends Am_Mvc_Controller { protected $pages = array(); protected $pageId = null; protected $defaultPageId = null; protected $layout = 'admin/layout.phtml'; public function init() { $this->initPages(); $this->getDi()->hook->call(Am_Event::INIT_CONTROLLER_PAGES, array('controller' => $this)); parent::init(); } public function __call($methodName, $args) { if (preg_match('/^([a-zA-Z0-9_-]+)Action$/', $methodName, $regs)) { $this->pageId = $this->getPageId(); if (!$this->getPage($this->pageId)) { throw new Am_Exception_InternalError("Could not find page[$id]"); } return $this->renderPage($this->getActivePage()); } //if ($this->) return parent::__call($methodName, $args); } abstract function initPages(); public function addPage($callbackOrPage, $id=null, $title=null) { if (is_object($callbackOrPage)) $page = $callbackOrPage; else $page = new Am_Mvc_Controller_Pages_Page($id, $title, $callbackOrPage); $this->pages[$page->getId()] = $page; if ($this->defaultPageId === null) $this->defaultPageId = $page->getId(); return $this; } public function setDefault($id) { $this->defaultPageId = $id; } public function getPageId() { if (empty($this->pageId)) { $this->pageId = filterId($this->_request->getParam('page_id', 'index')); if (!array_key_exists($this->pageId, $this->pages)) $this->pageId = $this->defaultPageId; if (!$this->pageId) throw new Am_Exception_InternalError("Could not find page id for request : [" . $this->_request->getActionName() . "]"); } return $this->pageId; } public function getPage($id) { $id = filterId($id); if (!array_key_exists($id, $this->pages)) throw new Am_Exception_InternalError("Could not find page[$id]"); return $this->pages[$id]; } /** @return Am_Mvc_Controller_Pages_Page */ public function getActivePage() { return $this->getPage($this->getPageId()); } public function renderPage(Am_Mvc_Controller_Pages_Page $page) { $performer = $page->getPerformer($this); if ($performer instanceof Zend_Controller_Action) $performer->run ($this->_request, $this->_response); else $performer->run($this->getResponse()); if ($this->getResponse()->isRedirect() || $this->_request->isXmlHttpRequest()) return; $content = $this->renderTabs($this->pageId) . $this->getResponse()->getBody(); $this->getResponse()->clearBody(); $this->view->title = $this->getActivePage()->getTitle(); $this->view->layoutNoTitle = true; $this->view->content = $content; $this->view->display($this->layout); } public function renderTabs() { $n = new Am_Navigation_Container; foreach ($this->pages as $page) { $p = new Am_Navigation_Page_Mvc(array( 'module' => $this->_request->getModuleName(), 'action' => 'index', 'controller' => $this->_request->getControllerName(), 'label' => $page->getTitle(), 'params' => array ( 'page_id' => $page->getId() ), 'route' => 'inside-pages' )); $p->setActive($this->getPageId() == $page->getId()); $n->addPage($p); } $h = new Am_View_Helper_AdminTabs; $h->setView($this->view); return $h->adminTabs($n); } }Controller/Echeck.php000064400000010322152101666600010563 0ustar00plugin = $plugin; } /** * Process the validated form and if ok, display thanks page, * if not ok, return false */ public function processEcheck() { $echeck = $this->getDi()->echeckRecordRecord; $this->form->toEcheckRecord($echeck); $echeck->user_id = $this->invoice->user_id; $result = $this->plugin->doBill($this->invoice, true, $echeck); if ($result->isSuccess()) { if (($this->invoice->rebill_times > 0) && !$echeck->pk()) $this->plugin->storeEcheck($echeck, new Am_Paysystem_Result); $this->_response->redirectLocation($this->plugin->getReturnUrl()); return true; } elseif ($result->isAction() && ($result->getAction() instanceof Am_Paysystem_Action_Redirect)) { $result->getAction()->process($this); // throws Am_Exception_Redirect (!) } else { $this->view->error = $result->getErrorMessages(); } } public function setInvoice(Invoice $invoice) { $this->invoice = $invoice; } public function echeckAction() { // invoice must be set to this point by the plugin if (!$this->invoice) throw new Am_Exception_InternalError('Empty invoice - internal error!'); $this->form = $this->createForm(); if ($this->form->isSubmitted() && $this->form->validate() && $this->processEcheck()) return; $this->view->form = $this->form; $this->view->invoice = $this->invoice; $this->view->display_receipt = true; $this->view->layoutNoMenu = true; $this->view->display('echeck/info.phtml'); } public function createForm() { $form = $this->plugin->createForm($this->_request->getActionName(), $this->invoice); $form->setDataSources(array( $this->_request, new HTML_QuickForm2_DataSource_Array($form->getDefaultValues($this->invoice->getUser())) )); $form->addHidden(Am_Mvc_Controller::ACTION_KEY)->setValue($this->_request->getActionName()); $form->addHidden('id')->setValue($this->getFiltered('id')); return $form; } public function preDispatch() { if (!$this->plugin) throw new Am_Exception_InternalError("Payment plugin is not passed to " . __CLASS__); } public function createUpdateForm() { $form = new Am_Form_Echeck($this->plugin, Am_Form_CreditCard::USER_UPDATE); $user = $this->getDi()->auth->getUser(true); if (!$user) throw new Am_Exception_InputError("You are not logged-in"); $echeck = $this->getDi()->echeckRecordTable->findFirstByUserId($user->user_id); if (!$echeck) $echeck = $this->getDi()->echeckRecordRecord; $arr = $echeck->toArray(); unset($arr['echeck_ban']); $form->setDataSources(array( $this->_request, new HTML_QuickForm2_DataSource_Array($arr) )); return $form; } public function updateAction() { $this->form = $this->createUpdateForm(); if ($this->form->isSubmitted() && $this->form->validate()) { $echeck = $this->getDi()->echeckRecordRecord; $this->form->toEcheckRecord($echeck); $echeck->user_id = $this->getDi()->auth->getUserId(); $result = new Am_Paysystem_Result(); $this->plugin->storeEcheck($echeck, $result); if ($result->isSuccess()) { return $this->_response->redirectLocation($this->getDi()->url('member',null,false)); } else { $this->form->getElementById('echeck_ban-0')->setError($result->getLastError()); } } $this->view->form = $this->form; $this->view->invoice = null; $this->view->display_receipt = false; $this->view->display('echeck/info.phtml'); } } Controller/CreditCard.php000064400000011111152101666600011402 0ustar00plugin = $plugin; } /** * Process the validated form and if ok, display thanks page, * if not ok, return false */ public function processCc() { $cc = $this->getDi()->ccRecordRecord; $this->form->toCcRecord($cc); $cc->user_id = $this->invoice->user_id; if($this->plugin->getConfig('use_maxmind')) { $checkresult = $this->plugin->doMaxmindCheck($this->invoice, $cc); if (!$checkresult->isSuccess()) { $this->view->error = $checkresult->getErrorMessages(); return; } } $result = $this->plugin->doBill($this->invoice, true, $cc); if ($result->isSuccess()) { if (($this->invoice->rebill_times > 0) && !$cc->pk()) $this->plugin->storeCreditCard($cc, new Am_Paysystem_Result); $this->_response->redirectLocation($this->plugin->getReturnUrl()); return true; } elseif ($result->isAction() && ($result->getAction() instanceof Am_Paysystem_Action_Redirect)) { $result->getAction()->process($this); // throws Am_Exception_Redirect (!) } else { $this->view->error = $result->getErrorMessages(); } } public function setInvoice(Invoice $invoice) { $this->invoice = $invoice; } public function ccAction() { // invoice must be set to this point by the plugin if (!$this->invoice) throw new Am_Exception_InternalError('Empty invoice - internal error!'); $this->form = $this->createForm(); $this->getDi()->hook->call(Bootstrap_Cc::EVENT_CC_FORM, array('form' => $this->form)); if ($this->form->isSubmitted() && $this->form->validate()) { if ($this->processCc()) return; } $this->view->form = $this->form; $this->view->invoice = $this->invoice; $this->view->display_receipt = true; $this->view->layoutNoMenu = true; $this->view->display('cc/info.phtml'); } public function createForm() { $form = $this->plugin->createForm($this->_request->getActionName(), $this->invoice); $form->setDataSources(array( $this->_request, new HTML_QuickForm2_DataSource_Array($form->getDefaultValues($this->invoice->getUser())) )); $form->addHidden(Am_Mvc_Controller::ACTION_KEY)->setValue($this->_request->getActionName()); $form->addHidden('id')->setValue($this->getFiltered('id')); return $form; } public function preDispatch() { if (!$this->plugin) throw new Am_Exception_InternalError("Payment plugin is not passed to " . __CLASS__); } public function createUpdateForm() { $form = new Am_Form_CreditCard($this->plugin, Am_Form_CreditCard::USER_UPDATE); $user = $this->getDi()->auth->getUser(true); if (!$user) throw new Am_Exception_InputError("You are not logged-in"); $cc = $this->getDi()->ccRecordTable->findFirstByUserId($user->user_id); if (!$cc) $cc = $this->getDi()->ccRecordRecord; $arr = $cc->toArray(); unset($arr['cc_number']); $form->setDataSources(array( $this->_request, new HTML_QuickForm2_DataSource_Array($arr) )); return $form; } public function updateAction() { $this->form = $this->createUpdateForm(); if ($this->form->isSubmitted() && $this->form->validate()) { $cc = $this->getDi()->ccRecordRecord; $this->form->toCcRecord($cc); $cc->user_id = $this->getDi()->auth->getUserId(); $result = new Am_Paysystem_Result(); $this->plugin->storeCreditCard($cc, $result); if ($result->isSuccess()) { return $this->_response->redirectLocation($this->getDi()->url('member',array('_msg'=>___('Your card details have been updated.')),false)); } else { $this->form->getElementById('cc_number-0')->setError($result->getLastError()); } } $this->view->form = $this->form; $this->view->invoice = null; $this->view->display_receipt = false; $this->view->display('cc/info.phtml'); } }