public function process(Document $document, $type) { $url = $document->getUrl(); $baseUrl = $this->requestContext->getBaseUrl(); if (empty($baseUrl) || strpos($url, $baseUrl) !== 0) { return; } $url = substr($url, strlen($baseUrl)); $document->setUrl($url); }
/** * Matches a path in the router. * * @param string $path * The request path. * @param array $exclude * An array of paths or system paths to skip. * * @return \Symfony\Component\HttpFoundation\Request * A populated request object or NULL if the path couldn't be matched. */ protected function getRequestForPath($path, array $exclude) { if (!empty($exclude[$path])) { return NULL; } // @todo Use the RequestHelper once https://drupal.org/node/2090293 is // fixed. $request = Request::create($this->context->getBaseUrl() . '/' . $path); // Performance optimization: set a short accept header to reduce overhead in // AcceptHeaderMatcher when matching the request. $request->headers->set('Accept', 'text/html'); // Find the system path by resolving aliases, language prefix, etc. $processed = $this->pathProcessor->processInbound($path, $request); if (empty($processed) || !empty($exclude[$processed])) { // This resolves to the front page, which we already add. return NULL; } $request->attributes->set('_system_path', $processed); // Attempt to match this path to provide a fully built request. try { $request->attributes->add($this->router->matchRequest($request)); return $request; } catch (ParamNotConvertedException $e) { return NULL; } catch (ResourceNotFoundException $e) { return NULL; } catch (MethodNotAllowedException $e) { return NULL; } catch (AccessDeniedHttpException $e) { return NULL; } }
/** * Decorates an URL with url context and query. * * @param string $url Relative URL * @param array $parameters An array of parameters * @param bool|string $referenceType The type of reference to be generated (one of the constants) * * @return string * * @throws \RuntimeException */ protected function decorateUrl($url, array $parameters = array(), $referenceType = self::ABSOLUTE_PATH) { if (!$this->context) { throw new \RuntimeException('No context associated to the CmsPageRouter'); } $schemeAuthority = ''; if ($this->context->getHost() && (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType)) { $port = ''; if ('http' === $this->context->getScheme() && 80 != $this->context->getHttpPort()) { $port = sprintf(':%s', $this->context->getHttpPort()); } elseif ('https' === $this->context->getScheme() && 443 != $this->context->getHttpsPort()) { $port = sprintf(':%s', $this->context->getHttpsPort()); } $schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : sprintf('%s://', $this->context->getScheme()); $schemeAuthority = sprintf('%s%s%s', $schemeAuthority, $this->context->getHost(), $port); } if (self::RELATIVE_PATH === $referenceType) { $url = $this->getRelativePath($this->context->getPathInfo(), $url); } else { $url = sprintf('%s%s%s', $schemeAuthority, $this->context->getBaseUrl(), $url); } if (count($parameters) > 0) { return sprintf('%s?%s', $url, http_build_query($parameters, '', '&')); } return $url; }
/** * Rebuild the request object from a URL with the help of the RequestContext. * * If the request context is not set, this simply returns the request object built from $uri. * * @param string $uri * * @return Request */ private function rebuildRequest($uri) { if (!$this->context) { return Request::create($uri); } $server = array(); if ($this->context->getHost()) { $server['SERVER_NAME'] = $this->context->getHost(); $server['HTTP_HOST'] = $this->context->getHost(); } if ($this->context->getBaseUrl()) { $uri = $this->context->getBaseUrl() . $uri; $server['SCRIPT_FILENAME'] = $this->context->getBaseUrl(); $server['PHP_SELF'] = $this->context->getBaseUrl(); } if ('https' === $this->context->getScheme()) { $server['HTTPS'] = 'on'; $server['SERVER_PORT'] = $this->context->getHttpsPort(); if (443 !== $this->context->getHttpsPort()) { // this is parsed from the host by symfony request // https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Request.php#L971 $server['HTTP_HOST'] .= ':' . $this->context->getHttpsPort(); } } else { $server['SERVER_PORT'] = $this->context->getHttpPort(); if (80 !== $this->context->getHttpPort()) { // this is parsed from the host by symfony request // https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Request.php#L971 $server['HTTP_HOST'] .= ':' . $this->context->getHttpPort(); } } return Request::create($uri, $this->context->getMethod(), $this->context->getParameters(), array(), array(), $server); }
/** * @param string $pathInfo * @param bool|string $referenceType * * @return string */ private function buildUrl($pathInfo, $referenceType) { $scheme = $this->getScheme(); $port = $this->getPortPart($scheme); $schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "{$scheme}://"; $schemeAuthority .= $this->context->getHost() . $port; return $schemeAuthority . $this->context->getBaseUrl() . $pathInfo; }
/** * {@inheritdoc} */ public function getBaseUrl() { $site = $this->selector->retrieve(); if ($site) { return parent::getBaseUrl() . $site->getRelativePath(); } return parent::getBaseUrl(); }
/** * Returns the Absolute URL for a given path relative to web root. By default, * the script name (index_dev.php) is added to the URL in dev_environment, use * $path_only = true to get a path without the index script. * * @param string $path the relative path * @param array $parameters An array of parameters * @param boolean $path_only if true (PATH_TO_FILE), getIndexPage() will not be added * * @return string The generated URL */ public function absoluteUrl($path, array $parameters = null, $path_only = self::WITH_INDEX_PAGE) { // Already absolute ? if (substr($path, 0, 4) != 'http') { // Prevent duplication of the subdirectory name when Thelia is installed in a subdirectory. // This happens when $path was calculated with Router::generate(), which returns an absolute URL, // starting at web server root. For example, if Thelia is installed in /thelia2, we got something like /thelia2/my/path // As base URL also contains /thelia2 (e.g. http://some.server.com/thelia2), we end up with // http://some.server.com/thelia2/thelia2/my/path, instead of http://some.server.com/thelia2/my/path // We have to compensate for this. $rcbu = $this->requestContext->getBaseUrl(); $hasSubdirectory = !empty($rcbu) && 0 === strpos($path, $rcbu); $base_url = $this->getBaseUrl($hasSubdirectory); /* Seems no longer required // TODO fix this ugly patch if (strpos($path, "index_dev.php")) { $path = str_replace('index_dev.php', '', $path); } */ // If only a path is requested, be sure to remove the script name (index.php or index_dev.php), if any. if ($path_only == self::PATH_TO_FILE) { if (substr($base_url, -3) == 'php') { $base_url = dirname($base_url); } } // Normalize the given path $base = rtrim($base_url, '/') . '/' . ltrim($path, '/'); } else { $base = $path; } $base = str_replace('&', '&', $base); $queryString = ''; $anchor = ''; if (!is_null($parameters)) { foreach ($parameters as $name => $value) { // Remove this parameter from base URL to prevent duplicate parameters $base = preg_replace('/([?&])' . $name . '=(?:[^&]*)(?:&|$)/', '$1', $base); $queryString .= sprintf("%s=%s&", urlencode($name), urlencode($value)); } } if ('' !== ($queryString = rtrim($queryString, "&"))) { // url could contain anchor $pos = strrpos($base, '#'); if ($pos !== false) { $anchor = substr($base, $pos); $base = substr($base, 0, $pos); } $base = rtrim($base, "?&"); $sepChar = strstr($base, '?') === false ? '?' : '&'; $queryString = $sepChar . $queryString; } return $base . $queryString . $anchor; }
/** * Returns base URL, with scheme, host and port, for current request context. * If no delivery URL is configured for current SiteAccess, will return base URL from current RequestContext. * * @return string */ protected function getBaseUrl() { $port = ''; if ($this->requestContext->getScheme() === 'https' && $this->requestContext->getHttpsPort() != 443) { $port = ":{$this->requestContext->getHttpsPort()}"; } if ($this->requestContext->getScheme() === 'http' && $this->requestContext->getHttpPort() != 80) { $port = ":{$this->requestContext->getHttpPort()}"; } $baseUrl = $this->requestContext->getBaseUrl(); if (substr($this->requestContext->getBaseUrl(), -4) === '.php') { $baseUrl = pathinfo($this->requestContext->getBaseurl(), PATHINFO_DIRNAME); } $baseUrl = rtrim($baseUrl, '/\\'); return sprintf('%s://%s%s%s', $this->requestContext->getScheme(), $this->requestContext->getHost(), $port, $baseUrl); }
public function testFromRequest() { $request = Request::create('https://test.com:444/foo?bar=baz'); $requestContext = new RequestContext(); $requestContext->setHttpPort(123); $requestContext->fromRequest($request); $this->assertEquals('', $requestContext->getBaseUrl()); $this->assertEquals('GET', $requestContext->getMethod()); $this->assertEquals('test.com', $requestContext->getHost()); $this->assertEquals('https', $requestContext->getScheme()); $this->assertEquals('/foo', $requestContext->getPathInfo()); $this->assertEquals('bar=baz', $requestContext->getQueryString()); $this->assertSame(123, $requestContext->getHttpPort()); $this->assertSame(444, $requestContext->getHttpsPort()); $request = Request::create('http://test.com:8080/foo?bar=baz'); $requestContext = new RequestContext(); $requestContext->setHttpsPort(567); $requestContext->fromRequest($request); $this->assertSame(8080, $requestContext->getHttpPort()); $this->assertSame(567, $requestContext->getHttpsPort()); }
/** * Decorates an URL with url context and query * * @param string $url Relative URL * @param array $parameters An array of parameters * @param boolean $absolute Whether to generate an absolute path or not * * @return string * * @throws \RuntimeException */ protected function decorateUrl($url, array $parameters = array(), $absolute = false) { if (!$this->context) { throw new \RuntimeException('No context associated to the CmsPageRouter'); } $url = sprintf('%s%s', $this->context->getBaseUrl(), $url); if ($absolute && $this->context->getHost()) { $scheme = $this->context->getScheme(); $port = ''; if ('http' === $scheme && 80 != $this->context->getHttpPort()) { $port = ':' . $this->context->getHttpPort(); } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) { $port = ':' . $this->context->getHttpsPort(); } $url = $scheme . '://' . $this->context->getHost() . $port . $url; } if (count($parameters) > 0) { return sprintf('%s?%s', $url, http_build_query($parameters, '', '&')); } return $url; }
/** * Rebuild the request object from a URL with the help of the RequestContext. * * If the request context is not set, this simply returns the request object built from $uri. * * @param string $pathinfo * * @return Request */ private function rebuildRequest($pathinfo) { if (!$this->context) { return Request::create('http://localhost' . $pathinfo); } $uri = $pathinfo; $server = array(); if ($this->context->getBaseUrl()) { $uri = $this->context->getBaseUrl() . $pathinfo; $server['SCRIPT_FILENAME'] = $this->context->getBaseUrl(); $server['PHP_SELF'] = $this->context->getBaseUrl(); } $host = $this->context->getHost() ?: 'localhost'; if ('https' === $this->context->getScheme() && 443 !== $this->context->getHttpsPort()) { $host .= ':' . $this->context->getHttpsPort(); } if ('http' === $this->context->getScheme() && 80 !== $this->context->getHttpPort()) { $host .= ':' . $this->context->getHttpPort(); } $uri = $this->context->getScheme() . '://' . $host . $uri . '?' . $this->context->getQueryString(); return Request::create($uri, $this->context->getMethod(), $this->context->getParameters(), array(), array(), $server); }
public function check_friends($event) { $context = new RequestContext(); $context->fromRequest($this->symfony_request); $baseUrl = generate_board_url(true) . $context->getBaseUrl(); $scriptName = $this->symfony_request->getScriptName(); $scriptName = substr($scriptName, -1, 1) == '/' ? '' : utf8_basename($scriptName); if ($scriptName != '') { $baseUrl = str_replace('/' . $scriptName, '', $baseUrl); } $user_id = $event['member']['user_id']; $sender_id = $this->user->data['user_id']; $request = $this->friends_model->get_request_by_sender_id($sender_id); $check_friend = $this->friends_model->check_friend(array('user_id' => $this->user->data['user_id'], 'friend_id' => $user_id)); $check_request = $this->friends_model->check_request(array('user_id' => $user_id, 'sender_id' => $this->user->data['user_id'])); $check_request_confirm = $this->friends_model->check_request(array('user_id' => $this->user->data['user_id'], 'sender_id' => $user_id)); $check_widget = true; if ($user_id == $this->user->data['user_id']) { $check_widget = false; } $this->template->assign_vars(array('U_USER_ID' => $user_id, 'U_CHECK_FRIEND' => $check_friend, 'U_CHECK_REQUEST' => $check_request, 'U_CHECK_REQUEST_CONFIRM' => $check_request_confirm, 'U_CHECK_WIDGET' => $check_widget, 'U_REQUEST_ID' => $request['request_id'], 'BASE_URL' => $baseUrl)); }
/** * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route * @throws InvalidParameterException When a parameter value for a placeholder is not correct because * it does not match the requirement */ protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array()) { $variables = array_flip($variables); $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters); // all params must be given if ($diff = array_diff_key($variables, $mergedParams)) { throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name)); } $url = ''; $optional = true; foreach ($tokens as $token) { if ('variable' === $token[0]) { if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) { // check requirement if (null !== $this->strictRequirements && !preg_match('#^' . $token[2] . '$#', $mergedParams[$token[3]])) { $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]); if ($this->strictRequirements) { throw new InvalidParameterException($message); } if ($this->logger) { $this->logger->error($message); } return; } $url = $token[1] . $mergedParams[$token[3]] . $url; $optional = false; } } else { // static text $url = $token[1] . $url; $optional = false; } } if ('' === $url) { $url = '/'; } // the contexts base URL is already encoded (see Symfony\Component\HttpFoundation\Request) $url = strtr(rawurlencode($url), $this->decodedChars); // the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3 // so we need to encode them as they are not used for this purpose here // otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route $url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/')); if ('/..' === substr($url, -3)) { $url = substr($url, 0, -2) . '%2E%2E'; } elseif ('/.' === substr($url, -2)) { $url = substr($url, 0, -1) . '%2E'; } $schemeAuthority = ''; if ($host = $this->context->getHost()) { $scheme = $this->context->getScheme(); if ($requiredSchemes) { $schemeMatched = false; foreach ($requiredSchemes as $requiredScheme) { if ($scheme === $requiredScheme) { $schemeMatched = true; break; } } if (!$schemeMatched) { $referenceType = self::ABSOLUTE_URL; $scheme = current($requiredSchemes); } } elseif (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme !== $req) { // We do this for BC; to be removed if _scheme is not supported anymore $referenceType = self::ABSOLUTE_URL; $scheme = $req; } if ($hostTokens) { $routeHost = ''; foreach ($hostTokens as $token) { if ('variable' === $token[0]) { if (null !== $this->strictRequirements && !preg_match('#^' . $token[2] . '$#i', $mergedParams[$token[3]])) { $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]); if ($this->strictRequirements) { throw new InvalidParameterException($message); } if ($this->logger) { $this->logger->error($message); } return; } $routeHost = $token[1] . $mergedParams[$token[3]] . $routeHost; } else { $routeHost = $token[1] . $routeHost; } } if ($routeHost !== $host) { $host = $routeHost; if (self::ABSOLUTE_URL !== $referenceType) { $referenceType = self::NETWORK_PATH; } } } if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) { $port = ''; if ('http' === $scheme && 80 != $this->context->getHttpPort()) { $port = ':' . $this->context->getHttpPort(); } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) { $port = ':' . $this->context->getHttpsPort(); } $schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "{$scheme}://"; $schemeAuthority .= $host . $port; } } if (self::RELATIVE_PATH === $referenceType) { $url = self::getRelativePath($this->context->getPathInfo(), $url); } else { $url = $schemeAuthority . $this->context->getBaseUrl() . $url; } // add a query string if needed $extra = array_diff_key($parameters, $variables, $defaults); if ($extra && ($query = http_build_query($extra, '', '&'))) { // "/" and "?" can be left decoded for better user experience, see // http://tools.ietf.org/html/rfc3986#section-3.4 $url .= '?' . strtr($query, array('%2F' => '/')); } return $url; }
/** * Generate a URL to a route * * @param string $route Name of the route to travel * @param array $params String or array of additional url parameters * @param bool $is_amp Is url using & (true) or & (false) * @param string|bool $session_id Possibility to use a custom session id instead of the global one * @param bool|string $reference_type The type of reference to be generated (one of the constants) * @return string The URL already passed through append_sid() */ public function route($route, array $params = array(), $is_amp = true, $session_id = false, $reference_type = UrlGeneratorInterface::ABSOLUTE_PATH) { $anchor = ''; if (isset($params['#'])) { $anchor = '#' . $params['#']; unset($params['#']); } $context = new RequestContext(); $context->fromRequest($this->symfony_request); if ($this->config['force_server_vars']) { $context->setHost($this->config['server_name']); $context->setScheme(substr($this->config['server_protocol'], 0, -3)); $context->setHttpPort($this->config['server_port']); $context->setHttpsPort($this->config['server_port']); $context->setBaseUrl(rtrim($this->config['script_path'], '/')); } $script_name = $this->symfony_request->getScriptName(); $page_name = substr($script_name, -1, 1) == '/' ? '' : utf8_basename($script_name); $base_url = $context->getBaseUrl(); // Append page name if base URL does not contain it if (!empty($page_name) && strpos($base_url, '/' . $page_name) === false) { $base_url .= '/' . $page_name; } // If enable_mod_rewrite is false we need to replace the current front-end by app.php, otherwise we need to remove it. $base_url = str_replace('/' . $page_name, empty($this->config['enable_mod_rewrite']) ? '/app.' . $this->php_ext : '', $base_url); // We need to update the base url to move to the directory of the app.php file if the current script is not app.php if ($page_name !== 'app.php' && !$this->config['force_server_vars']) { if (empty($this->config['enable_mod_rewrite'])) { $base_url = str_replace('/app.' . $this->php_ext, '/' . $this->phpbb_root_path . 'app.' . $this->php_ext, $base_url); } else { $base_url .= preg_replace(get_preg_expression('path_remove_dot_trailing_slash'), '$2', $this->phpbb_root_path); } } $base_url = $this->request->escape($this->filesystem->clean_path($base_url), true); $context->setBaseUrl($base_url); $this->router->setContext($context); $route_url = $this->router->generate($route, $params, $reference_type); if ($is_amp) { $route_url = str_replace(array('&', '&'), array('&', '&'), $route_url); } if ($reference_type === UrlGeneratorInterface::RELATIVE_PATH && empty($this->config['enable_mod_rewrite'])) { $route_url = 'app.' . $this->php_ext . '/' . $route_url; } return append_sid($route_url . $anchor, false, $is_amp, $session_id, true); }
/** * @throws MissingMandatoryParametersException When route has some missing mandatory parameters * @throws InvalidParameterException When a parameter value is not correct */ protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $absolute, $hostnameTokens) { $variables = array_flip($variables); $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters); // all params must be given if ($diff = array_diff_key($variables, $mergedParams)) { throw new MissingMandatoryParametersException(sprintf('The "%s" route has some missing mandatory parameters ("%s").', $name, implode('", "', array_keys($diff)))); } $url = ''; $optional = true; foreach ($tokens as $token) { if ('variable' === $token[0]) { if (!$optional || !array_key_exists($token[3], $defaults) || (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) { // check requirement if (null !== $this->strictRequirements && !preg_match('#^' . $token[2] . '$#', $mergedParams[$token[3]])) { $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given).', $token[3], $name, $token[2], $mergedParams[$token[3]]); if ($this->strictRequirements) { throw new InvalidParameterException($message); } if ($this->logger) { $this->logger->err($message); } return null; } $url = $token[1] . $mergedParams[$token[3]] . $url; $optional = false; } } else { // static text $url = $token[1] . $url; $optional = false; } } if ('' === $url) { $url = '/'; } // do not encode the contexts base url as it is already encoded (see Symfony\Component\HttpFoundation\Request) $url = $this->context->getBaseUrl() . strtr(rawurlencode($url), $this->decodedChars); // the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3 // so we need to encode them as they are not used for this purpose here // otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route $url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/')); if ('/..' === substr($url, -3)) { $url = substr($url, 0, -2) . '%2E%2E'; } elseif ('/.' === substr($url, -2)) { $url = substr($url, 0, -1) . '%2E'; } // add a query string if needed $extra = array_diff_key($parameters, $variables); if ($extra && ($query = http_build_query($extra, '', '&'))) { $url .= '?' . $query; } if ($host = $this->context->getHost()) { $scheme = $this->context->getScheme(); if (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme != $req) { $absolute = true; $scheme = $req; } if ($hostnameTokens) { $routeHost = ''; foreach ($hostnameTokens as $token) { if ('variable' === $token[0]) { if (null !== $this->strictRequirements && !preg_match('#^' . $token[2] . '$#', $mergedParams[$token[3]])) { $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given).', $token[3], $name, $token[2], $mergedParams[$token[3]]); if ($this->strictRequirements) { throw new InvalidParameterException($message); } if ($this->logger) { $this->logger->err($message); } return null; } $routeHost = $token[1] . $mergedParams[$token[3]] . $routeHost; } elseif ('text' === $token[0]) { $routeHost = $token[1] . $routeHost; } } if ($routeHost != $host) { $host = $routeHost; $absolute = true; } } if ($absolute) { $port = ''; if ('http' === $scheme && 80 != $this->context->getHttpPort()) { $port = ':' . $this->context->getHttpPort(); } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) { $port = ':' . $this->context->getHttpsPort(); } $url = $scheme . '://' . $host . $port . $url; } } return $url; }
/** * @param $uniqueId * * @return string */ public function getOutputFileUrl($uniqueId) { return sprintf("%s://%s%s%s/%s.html", $this->context->getScheme(), $this->context->getHost(), $this->contextBaseUrl === "" ? $this->context->getBaseUrl() : $this->contextBaseUrl, $this->config['temp_dir'], $uniqueId); }