/** * Execute the request * * @param RequestInterface $request * @param ResponseInterface $response (Default: null) * @return \Zend\Http\PhpEnvironment\Response */ public function dispatch(RequestInterface $request, ResponseInterface $response = null) { // the config hash $config = $this->getServiceLocator()->get('Config'); $config = $config['TpMinify']; // some important stuff $config['serveOptions']['quiet'] = true; // the time correction Minify::$uploaderHoursBehind = $config['uploaderHoursBehind']; // the cache engine Minify::setCache($config['cachePath'] ?: '', $config['cacheFileLocking']); // doc root corrections if ($config['documentRoot']) { $_SERVER['DOCUMENT_ROOT'] = $config['documentRoot']; Minify::$isDocRootSet = true; } // check for URI versioning if (preg_match('~&\\d~', $request->getUriString())) { $config['serveOptions']['maxAge'] = 31536000; } // minify result as array of information $result = Minify::serve('MinApp', $config['serveOptions']); // some corrections if (isset($result['headers']['_responseCode'])) { unset($result['headers']['_responseCode']); } // the headers set $headers = new Headers(); $headers->addHeaders($result['headers']); // final output return $response->setHeaders($headers)->setStatusCode($result['statusCode'])->setContent($result['content']); }
public function detect(DetectorConfig $config, RequestInterface $request) { $domains = $config->getDomains(); $host = $request->getUri()->getHost(); $matched = null; if (null === $domains || empty($domains)) { throw new Exception\InvalidArgumentException('No domains where configured'); } foreach ($domains as $domain) { if (strpos($domain, self::LOCALE_KEY) === false) { throw new Exception\InvalidArgumentException(sprintf('The domain %s must contain a locale key part "%s"', $domain, self::LOCALE_KEY)); } $pattern = str_replace(self::LOCALE_KEY, '([a-zA-Z-_.]+)', $domain); $pattern = sprintf('@%s@', $pattern); $result = preg_match($pattern, $host, $matches); if ($result) { $matched = $matches; } } $locale = $matched[1]; $aliases = $config->getAliases(); if (null !== $aliases && array_key_exists($locale, $aliases)) { $locale = $aliases[$locale]; } return $locale; }
/** * @param string $param * @param mixed $default * @return mixed */ public function fromQuery($param = null, $default = null) { if ($param === null) { return $this->request->getQuery($param, $default)->toArray(); } return $this->request->getPost($param, $default); }
/** * Match a given request. Run Symfony if it wants the route. * * @param Request $request * @return RouteMatch|null */ public function match(Request $request) { try { self::$routeCollection->match($request->getUri()->getPath()); } catch (ResourceNotFoundException $e) { return null; } $dispatcher = new SymfonyDispatcher(); $dispatcher->dispatchRouteToSymfony(); }
public function detect(DetectorConfig $config, RequestInterface $request) { $base = $this->getBasePath(); $locale = $this->getFirstSegmentInPath($request->getUri(), $base); $aliases = $config->getAliases(); if (null !== $aliases && array_key_exists($locale, $aliases)) { $locale = $aliases[$locale]; } return $locale; }
/** * @param RequestInterface $request * * @return bool */ public function isAllowed(RequestInterface $request) { if (!$request instanceof Http\Request) { return false; } if ($this->authService->hasIdentity()) { return true; } $path = $request->getUri()->getPath(); return in_array($path, ['', '/']); }
public function match(Request $request) { if (!$request instanceof ConsoleRequest) { return null; } $params = $request->getParams()->toArray(); if (!isset($params[0]) || !$this->application->has($params[0])) { return null; } return new RouteMatch($this->defaults); }
/** * match(): defined by Route interface. * * @see \Zend\Router\Route::match() * @param Request $request * @param null|int $pathOffset * @return RouteMatch */ public function match(Request $request, $pathOffset = null) { if (!$request instanceof ConsoleRequest) { return; } $params = $request->getParams()->toArray(); $matches = $this->matcher->match($params); if (null !== $matches) { return new RouteMatch($matches); } return; }
/** * Match a given request. * * @param Request $request * @return RouteMatch|null */ public function match(Request $request) { try { //This line is odd but prevents a warning // self::$routeCollection->request = $request; $params = self::$routeCollection->match($request->getUri()->getPath()); } catch (ResourceNotFoundException $e) { return null; } $dispatcher = new SymfonyDispatcher(); $dispatcher->dispatchRouteToSymfony($params); }
/** * Grabs a param from cookie. * * @param string $param * @param mixed $default * @return mixed */ public function __invoke($param = null, $default = null) { if ($this->request instanceof HttpRequest) { $cookie = $this->request->getCookie(); if ($param === null) { return $cookie; } if ($cookie->offsetExists($param)) { return $cookie->get($param); } return $default; } }
/** * Override moveUploadedFile * * If the request is not HTTP, or not a PUT or PATCH request, delegates to * the parent functionality. * * Otherwise, does a `rename()` operation, and returns the status of the * operation. * * @param string $sourceFile * @param string $targetFile * @return bool * @throws FilterRuntimeException in the event of a warning */ protected function moveUploadedFile($sourceFile, $targetFile) { if (null === $this->request || !method_exists($this->request, 'isPut') || !$this->request->isPut() && !$this->request->isPatch()) { return parent::moveUploadedFile($sourceFile, $targetFile); } ErrorHandler::start(); $result = rename($sourceFile, $targetFile); $warningException = ErrorHandler::stop(); if (false === $result || null !== $warningException) { throw new FilterRuntimeException(sprintf('File "%s" could not be renamed. An error occurred while processing the file.', $sourceFile), 0, $warningException); } return $result; }
/** * Match a given request. * * @param RequestInterface $request * @param int $pathOffset * @return null|RouteMatch|\Zend\Mvc\Router\RouteMatch */ public function match(RequestInterface $request, $pathOffset = null) { /** @var string $path */ $path = trim(substr($request->getUri()->getPath(), $pathOffset), '/'); /** @var \Msingi\Cms\Entity\Page $page */ $page = $this->loadPage($path); if ($page == null) { return null; } /** @var array $routeParams */ $routeParams = array_merge($this->defaults, array('cms_page' => $page, 'path' => $page->getPath())); $routeMatch = new RouteMatch($routeParams, strlen($page->getPath())); return $routeMatch; }
/** * Check if request has certain content/Accept type of RestApi * * @param Request $request * @return bool */ public function requestCheckEventType(Request $request) { $headers = $request->getHeaders(); if (!$headers->has('Accept')) { // can't determine what we can accept return false; } $accept = $headers->get('Accept')->toString(); if (stripos($accept, 'application/json') == false) { // does not match JSON return false; } return true; }
/** {@inheritdoc} */ public function dispatch(\Zend\Stdlib\RequestInterface $request, \Zend\Stdlib\ResponseInterface $response = null) { // Fetch group with given name for actions referring to a particular group $action = $this->getEvent()->getRouteMatch()->getParam('action'); if ($action != 'index' and $action != 'add') { try { $this->_currentGroup = $this->_groupManager->getGroup($request->getQuery('name')); } catch (\RuntimeException $e) { // Group does not exist - may happen when URL has become stale. $this->flashMessenger()->addErrorMessage('The requested group does not exist.'); return $this->redirectToRoute('group', 'index'); } } return parent::dispatch($request, $response); }
public function match(RequestInterface $request, $pathOffset = 0) { if (!$request instanceof HttpRequest) { return; } $virtualUrl = substr($request->getUri()->getPath(), $pathOffset); if (!isset($virtualUrl[0]) || $virtualUrl[0] !== '/') { return; } if (!($page = $this->urlMapper->findByUrl(substr($virtualUrl, 1)))) { return; } $this->assembledParams = ['page' => $page]; return new RouteMatch(['page' => $page, 'controller' => UrlController::class, 'action' => 'index'], strlen($virtualUrl)); }
/** * Match a given request. * * @param Request $request Request to match * * @return RouteMatch */ public function match(Request $request) { // Get command line arguments and present working directory from // server superglobal: $filename = $request->getScriptName(); $pwd = CLI_DIR; // Convert base filename (minus .php extension and underscores) and // containing directory name into action and controller, respectively: $baseFilename = str_replace('_', '', basename($filename)); $baseFilename = substr($baseFilename, 0, strlen($baseFilename) - 4); $baseDirname = basename(dirname(realpath($pwd . '/' . $filename))); $routeMatch = new RouteMatch(array('controller' => $baseDirname, 'action' => $baseFilename), 1); // Override standard routing: $routeMatch->setMatchedRouteName('default'); return $routeMatch; }
/** * @inheritdoc */ public function match(Request $request) { /** @var \Zend\Http\Request $request */ $path = $request->getUri()->getPath(); $segments = preg_split('@/@', $path); if (count($segments) < 1) { return false; } $id = array_pop($segments); $className = trim(implode('\\', $segments), '\\'); if (!class_exists($className)) { return false; } $routeMatch = new RouteMatch(['id' => $id, 'className' => $className, '_isNakedObject' => true, 'controller' => 'NakedObjectController']); return $routeMatch; }
/** * Dispatch a request * * @events dispatch.pre, dispatch.post * @param Request $request * @param null|Response $response * @return Response|mixed */ public function dispatch(Request $request, Response $response = null) { $this->request = $request; $this->getDataResourceCreator()->setData(array_merge_recursive($this->params()->fromPost(), $request->getFiles()->toArray())); if (!$this->getDataResourceCreator()->isValid()) { if ($this->disableDefaultErrorHandler) { $response = $response ?: new HttpResponse(); $this->getEventManager()->clearListeners(MvcEvent::EVENT_DISPATCH); $this->getEvent()->setResult(false); $response->setStatusCode(400); } else { $this->getEventManager()->clearListeners(MvcEvent::EVENT_DISPATCH); $this->uploaderModel->setMessages($this->getDataResourceCreator()); $this->getEvent()->setResult($this->uploaderModel); } } parent::dispatch($request, $response); }
/** * @param string $name Name of the route * @param array $params Parameters for the link * @param array|Traversable $options Options for the route * @param bool $reuseMatchedParams Whether to reuse matched parameters * @return string Url For the link href attribute */ public function __invoke($name = null, $params = [], $options = [], $reuseMatchedParams = false) { $referer = $this->request->getHeader('Referer'); if ($referer) { $refererUrl = $referer->uri()->getPath(); // referer url $refererHost = $referer->uri()->getHost(); // referer host $host = $this->request->getUri()->getHost(); // current host // only redirect to previous page if request comes from same host if ($refererUrl && $refererHost == $host) { return $refererUrl; } } // redirect to home if no referer or from another page return $this->view->url($name, $params, $options, $reuseMatchedParams); }
/** * Verifica permissao de acesso. * * @param RequestInterface $request * @return type */ public function checkAccess(Request $request) { // True porque por padrao eh checado o acesso de accessDeniedAction (nao tem acesso) $result = true; // Validação do parametro MODULO $module = $request->getQuery('module', 'application'); $this->validate('module', $module, array('NotEmpty')); $session = new Session(self::ACCESS_CONTROL_NAMESPACE); // Parametro Module não encontrado, assim não sabemos // que tipo de login ele tem. if (!$this->isAllValid()) { $this->setError(MsgType::DANGER, "Acesso Negado"); $session->view = $this->view; $result = false; // Agora verificamos se o usuario tem permissao de acesso // configurado pelo banco de dados } else { if ($this->getActionName() != 'access-denied') { // Puxa configuracoes de acessos do banco de dados $accessControl = AccessControl::getInstance($module); $accessControl->setupPermissions($this->getLogin() ? $this->getLogin()->getFkRole() : Config::getZf2libConfig('roleDefault'), $module); // Setor do sistema $permission = array('module' => $this->getModuleName(), 'controller' => $this->getControllerName(), 'action' => $this->getActionName()); // Quando a acao nao existir na tabela action // assumimos que ela eh uma acao de leitura (read) $actionBOClass = Config::getZf2libConfig('actionBusinessClass', $module); $actionBO = new $actionBOClass(); $action = $actionBO->get($permission['action']); if (!$action) { $permission['action'] = Config::getZf2libConfig('actionRead'); } // Verifica se usuario tem acesso $allowed = AccessControl::allowed(implode('.', $permission)); if (!$allowed) { $this->setError(MsgType::DANGER, "Acesso Negado"); $session->view = $this->view; $result = false; } } } return $result; }
/** * Dispatch a request * * @events dispatch.pre, dispatch.post * @param Request $request * @param null|Response $response * @return Response|mixed */ public function dispatch(Request $request, Response $response = null) { if ($this->requiredLogin) { $user = $this->getCurrentUser(); if (!$user) { $msg = $this->getTranslator()->translate("You must login in order to process this page."); $this->flashMessenger()->addErrorMessage($msg); /** @var \Zend\Uri\Http $url */ $uri = $request->getUri(); $langArr = explode('/', $uri->getPath()); $lang = $langArr[1]; $requestUri = $uri->getPath() . ($uri->getQuery() ? "?" . $uri->getQuery() : ""); $requestUriArr = explode('/', $requestUri); unset($requestUriArr[1]); $requestUri = implode($requestUriArr, '/'); return $this->redirect()->toUrl("/{$lang}/user/login?next=" . $requestUri); } } return parent::dispatch($request, $response); }
/** * Overrides isValid() * * If the reason for failure is self::ATTACK, we can assume that * is_uploaded_file() has failed -- which is * * @param mixed $value * @return void */ public function isValid($value) { if (null === $this->request || !method_exists($this->request, 'isPut') || !$this->request->isPut() && !$this->request->isPatch()) { // In absence of a request object, an HTTP request, or a PATCH/PUT // operation, just use the parent logic. return parent::isValid($value); } $result = parent::isValid($value); if ($result !== false) { return $result; } if (!isset($this->abstractOptions['messages'][static::ATTACK])) { return $result; } if (count($this->abstractOptions['messages']) > 1) { return $result; } unset($this->abstractOptions['messages'][static::ATTACK]); return true; }
/** * @param \Zend\ServiceManager\ServiceLocatorInterface $serviceLocator * @param \Zend\StdLib\RequestInterface $request * @param \Phpro\SmartCrud\Controller\CrudController $controller * @param \Zend\Mvc\Controller\Plugin\Params $params */ protected function mockServiceLocator($serviceLocator, $request, $controller, $params) { $prophet = new Prophet(); $app = $prophet->prophesize('\\Zend\\Mvc\\Application'); $event = $prophet->prophesize('\\Zend\\Mvc\\MvcEvent'); if ($controller) { $controller->plugin('params')->willReturn($params->getWrappedObject()); $controller = $controller->getWrappedObject(); } // mock routeMatch $routeMatch = $prophet->prophesize('Zend\\Mvc\\Router\\Http\\RouteMatch'); $routeMatch->getParam('controller')->willReturn('DummyControllerSlag'); // Mock controller manager $controllerManager = $prophet->prophesize('Zend\\Mvc\\Controller\\ControllerManager'); $controllerManager->get('DummyControllerSlag')->willReturn($controller); $serviceLocator->get('controllerLoader')->willReturn($controllerManager); // Add application data to mvc event $event->getRequest()->willReturn($request->getWrappedObject()); $event->getRouteMatch()->willReturn($routeMatch); $app->getMvcEvent()->willReturn($event); $serviceLocator->get('application')->willReturn($app); }
/** * match * * @param RequestInterface $request * @param int $pathOffset * * @return bool|null|RouteMatch */ public function match(RequestInterface $request, $pathOffset = 0) { if (!$request instanceof Request) { return null; } $pageUrl = substr($request->getUri()->getPath(), $pathOffset); $type = $this->getPageType(); $pageParams = $this->parseUrl($pageUrl); if (empty($pageParams)) { return null; } try { $page = $this->getPage($pageParams['pageName'], $type); } catch (\Exception $e) { return null; } if (empty($page)) { return false; } $cms_params = array('page' => $page, 'controller' => $this->getController($type), 'action' => $this->getAction($type), 'revision' => $pageParams['revision']); return new RouteMatch($cms_params, strlen($pageUrl)); }
/** * Mimics zf1 Request::getParam behavior * * Route match -> GET -> POST */ public static function staticGetParam(RouteMatch $routeMatch, Request $request, $param = null, $default = null) { if ($param === null) { $params = (array) $routeMatch->getParams(); if ($request instanceof ConsoleRequest) { return $params + (array) $request->getParams(); } return $params + $request->getQuery()->toArray() + $request->getPost()->toArray(); } if ($request instanceof ConsoleRequest) { $default = $request->getParam($param, $default); } else { $default = $request->getQuery($param, $request->getPost($param, $default)); } return $routeMatch->getParam($param, $default); }
/** * Resolve the request to a file. * * @param RequestInterface $request * * @return mixed false when not found, AssetInterface when resolved. */ protected function resolve(RequestInterface $request) { if (!$request instanceof Request) { return false; } /* @var $request Request */ /* @var $uri \Zend\Uri\UriInterface */ $uri = $request->getUri(); $fullPath = $uri->getPath(); $path = substr($fullPath, strlen($request->getBasePath()) + 1); $this->path = $path; $asset = $this->getResolver()->resolve($path); if (!$asset instanceof AssetInterface) { return false; } return $asset; }
/** * Retrieve the identifier, if any * * Attempts to see if an identifier was passed in either the URI or the * query string, returning if if found. Otherwise, returns a boolean false. * * @param \Zend\Mvc\Router\RouteMatch $routeMatch * @param Request $request * @return false|mixed */ protected function getIdentifier($routeMatch, $request) { $id = $routeMatch->getParam('id', false); if ($id) { return $id; } $id = $request->getQuery()->get('id', false); if ($id) { return $id; } return false; }
/** * match(): defined by Route interface. * * @see Route::match() * @param Request $request * @param null|int $pathOffset * @return RouteMatch */ public function match(Request $request, $pathOffset = null) { if (!$request instanceof ConsoleRequest) { return null; } /** @var $request ConsoleRequest */ /** @var $params \Zend\Stdlib\Parameters */ $params = $request->getParams()->toArray(); $matches = array(); /** * Extract positional and named parts */ $positional = $named = array(); foreach ($this->parts as &$part) { if ($part['positional']) { $positional[] =& $part; } else { $named[] =& $part; } } /** * Scan for named parts inside Console params */ foreach ($named as &$part) { /** * Prepare match regex */ if (isset($part['alternatives'])) { // an alternative of flags $regex = '/^\\-+(?P<name>'; $regex .= join('|', $part['alternatives']); if ($part['hasValue']) { $regex .= ')(?:\\=(?P<value>.*?)$)?$/'; } else { $regex .= ')$/i'; } } else { // a single named flag if ($part['short'] === true) { // short variant if ($part['hasValue']) { $regex = '/^\\-' . $part['name'] . '(?:\\=(?P<value>.*?)$)?$/i'; } else { $regex = '/^\\-' . $part['name'] . '$/i'; } } elseif ($part['short'] === false) { // long variant if ($part['hasValue']) { $regex = '/^\\-{2,}' . $part['name'] . '(?:\\=(?P<value>.*?)$)?$/i'; } else { $regex = '/^\\-{2,}' . $part['name'] . '$/i'; } } } /** * Look for param */ $value = $param = null; for ($x = 0, $count = count($params); $x < $count; $x++) { if (preg_match($regex, $params[$x], $m)) { // found param $param = $params[$x]; // prevent further scanning of this param array_splice($params, $x, 1); if (isset($m['value'])) { $value = $m['value']; } if (isset($m['name'])) { $matchedName = $m['name']; } break; } } if (!$param) { /** * Drop out if that was a mandatory param */ if ($part['required']) { return null; } else { continue; } } /** * Value for flags is always boolean */ if ($param && !$part['hasValue']) { $value = true; } /** * Try to retrieve value if it is expected */ if ((null === $value || "" === $value) && $part['hasValue']) { if ($x < count($params) + 1 && isset($params[$x])) { // retrieve value from adjacent param $value = $params[$x]; // prevent further scanning of this param array_splice($params, $x, 1); } else { // there are no more params available return null; } } /** * Validate the value against constraints */ if ($part['hasValue'] && isset($this->constraints[$part['name']])) { if (!preg_match($this->constraints[$part['name']], $value)) { // constraint failed return null; } } /** * Store the value */ if ($part['hasValue']) { $matches[$part['name']] = $value; } else { $matches[$part['name']] = true; } /** * If there are alternatives, fill them */ if (isset($part['alternatives'])) { if ($part['hasValue']) { foreach ($part['alternatives'] as $alt) { if ($alt === $matchedName && !isset($matches[$alt])) { $matches[$alt] = $value; } elseif (!isset($matches[$alt])) { $matches[$alt] = null; } } } else { foreach ($part['alternatives'] as $alt) { if ($alt === $matchedName && !isset($matches[$alt])) { $matches[$alt] = isset($this->defaults[$alt]) ? $this->defaults[$alt] : true; } elseif (!isset($matches[$alt])) { $matches[$alt] = false; } } } } } /** * Scan for left-out flags that should result in a mismatch */ foreach ($params as $param) { if (preg_match('#^\\-+#', $param)) { return null; // there is an unrecognized flag } } /** * Go through all positional params */ $argPos = 0; foreach ($positional as &$part) { /** * Check if param exists */ if (!isset($params[$argPos])) { if ($part['required']) { // cannot find required positional param return null; } else { // stop matching break; } } $value = $params[$argPos]; /** * Check if literal param matches */ if ($part['literal']) { if (isset($part['alternatives']) && !in_array($value, $part['alternatives']) || !isset($part['alternatives']) && $value != $part['name']) { return null; } } /** * Validate the value against constraints */ if ($part['hasValue'] && isset($this->constraints[$part['name']])) { if (!preg_match($this->constraints[$part['name']], $value)) { // constraint failed return null; } } /** * Store the value */ if ($part['hasValue']) { $matches[$part['name']] = $value; } elseif (isset($part['alternatives'])) { // from all alternativesm set matching parameter to TRUE and the rest to FALSE foreach ($part['alternatives'] as $alt) { if ($alt == $value) { $matches[$alt] = isset($this->defaults[$alt]) ? $this->defaults[$alt] : true; } else { $matches[$alt] = false; } } // set alternatives group value $matches[$part['name']] = $value; } elseif (!$part['required']) { // set optional parameter flag $name = $part['name']; $matches[$name] = isset($this->defaults[$name]) ? $this->defaults[$name] : true; } /** * Advance to next argument */ $argPos++; } /** * Check if we have consumed all positional parameters */ if ($argPos < count($params)) { return null; // there are extraneous params that were not consumed } /** * Any optional flags that were not entered have value false */ foreach ($this->parts as &$part) { if (!$part['required'] && !$part['hasValue']) { if (!isset($matches[$part['name']])) { $matches[$part['name']] = false; } // unset alternatives also should be false if (isset($part['alternatives'])) { foreach ($part['alternatives'] as $alt) { if (!isset($matches[$alt])) { $matches[$alt] = false; } } } } } return new RouteMatch(array_replace($this->defaults, $matches)); }
/** * Retrieve the identifier, if any * * Attempts to see if an identifier was passed in either the URI or the * query string, returning it if found. Otherwise, returns a boolean false. * * @param \Zend\Mvc\Router\RouteMatch $routeMatch * @param Request $request * @return false|mixed */ protected function getIdentifier($routeMatch, $request) { $identifier = $this->getIdentifierName(); $id = $routeMatch->getParam($identifier, false); if ($id !== false) { return $id; } $id = $request->getQuery()->get($identifier, false); if ($id !== false) { return $id; } return false; }
/** * Extracts the directory paths from a CLI request * * Uses format of a URL query * * @param RequestInterface $request * @return array */ private function extractFromCli(RequestInterface $request) { if (!($request instanceof Request)) { return []; } $bootstrapParam = new ComplexParameter(self::BOOTSTRAP_PARAM); foreach ($request->getContent() as $paramStr) { $result = $bootstrapParam->getFromString($paramStr); if (!empty($result)) { return $result; } } return []; }