diff --git a/core/includes/common.inc b/core/includes/common.inc index 60f57f2..917c77a 100644 --- a/core/includes/common.inc +++ b/core/includes/common.inc @@ -10,6 +10,7 @@ use Drupal\Core\Cache\CacheBackendInterface; use Drupal\Core\Datetime\DrupalDateTime; use Drupal\Core\Database\Database; +use Drupal\Core\Routing\PathGeneratorNotInitializedException; use Drupal\Core\SystemListingInfo; use Drupal\Core\Template\Attribute; @@ -477,42 +478,12 @@ function drupal_get_query_array($query) { /** * Parses an array into a valid, rawurlencoded query string. * - * This differs from http_build_query() as we need to rawurlencode() (instead of - * urlencode()) all query parameters. - * - * @param $query - * The query parameter array to be processed, e.g. $_GET. - * @param $parent - * Internal use only. Used to build the $query array key for nested items. - * - * @return - * A rawurlencoded string which can be used as or appended to the URL query - * string. - * + * @see \Drupal\Core\Routing\PathBasedGeneratorInterface::httpBuildQuery() * @see drupal_get_query_parameters() * @ingroup php_wrappers */ function drupal_http_build_query(array $query, $parent = '') { - $params = array(); - - foreach ($query as $key => $value) { - $key = ($parent ? $parent . '[' . rawurlencode($key) . ']' : rawurlencode($key)); - - // Recurse into children. - if (is_array($value)) { - $params[] = drupal_http_build_query($value, $key); - } - // If a query parameter value is NULL, only append its key. - elseif (!isset($value)) { - $params[] = $key; - } - else { - // For better readability of paths in query strings, we decode slashes. - $params[] = $key . '=' . str_replace('%2F', '/', rawurlencode($value)); - } - } - - return implode('&', $params); + return Drupal::Service('router.generator')->httpBuildQuery($query, $parent); } /** @@ -543,7 +514,7 @@ function drupal_get_destination() { } else { $path = current_path(); - $query = drupal_http_build_query(drupal_get_query_parameters()); + $query = Drupal::Service('router.generator')->httpBuildQuery(drupal_get_query_parameters()); if ($query != '') { $path .= '?' . $query; } @@ -704,8 +675,7 @@ function drupal_goto($path = '', array $options = array(), $http_response_code = // The 'Location' HTTP header must be absolute. $options['absolute'] = TRUE; - $url = url($path, $options); - + $url = Drupal::service('router.generator')->generateFromPath($path, $options); header('Location: ' . $url, TRUE, $http_response_code); // The "Location" header sends a redirect status code to the HTTP daemon. In @@ -1213,49 +1183,12 @@ function valid_number_step($value, $step, $offset = 0.0) { * Drupal\Core\Template\Attribute, or another function that will call * check_plain() separately. * - * @param $uri - * A plain-text URI that might contain dangerous protocols. - * - * @return - * A plain-text URI stripped of dangerous protocols. As with all plain-text - * strings, this return value must not be output to an HTML page without - * check_plain() being called on it. However, it can be passed to functions - * expecting plain-text strings. - * + * @see \Drupal\Core\Routing\PathBasedGeneratorInterface::stripDisallowedProtocols() * @see check_url() */ function drupal_strip_dangerous_protocols($uri) { - static $allowed_protocols; - - if (!isset($allowed_protocols)) { - // filter_xss_admin() is called by the installer and update.php, in which - // case the configuration may not exist (yet). Provide a minimal default set - // of allowed protocols for these cases. - $allowed_protocols = array_flip(config('system.filter')->get('protocols') ?: array('http', 'https')); - } - - // Iteratively remove any invalid protocol found. - do { - $before = $uri; - $colonpos = strpos($uri, ':'); - if ($colonpos > 0) { - // We found a colon, possibly a protocol. Verify. - $protocol = substr($uri, 0, $colonpos); - // If a colon is preceded by a slash, question mark or hash, it cannot - // possibly be part of the URL scheme. This must be a relative URL, which - // inherits the (safe) protocol of the base document. - if (preg_match('![/?#]!', $protocol)) { - break; - } - // Check if this is a disallowed protocol. Per RFC2616, section 3.2.3 - // (URI Comparison) scheme comparison must be case-insensitive. - if (!isset($allowed_protocols[strtolower($protocol)])) { - $uri = substr($uri, $colonpos + 1); - } - } - } while ($before != $uri); - - return $uri; + $allowed_protocols = array_flip(config('system.filter')->get('protocols') ?: array('http', 'https')); + return Drupal::Service('router.generator')->stripDisallowedProtocols($uri, $allowed_protocols); } /** @@ -1990,153 +1923,21 @@ function datetime_default_format_type() { * When creating links in modules, consider whether l() could be a better * alternative than url(). * - * @param $path - * (optional) The internal path or external URL being linked to, such as - * "node/34" or "http://example.com/foo". The default value is equivalent to - * passing in ''. A few notes: - * - If you provide a full URL, it will be considered an external URL. - * - If you provide only the path (e.g. "node/34"), it will be - * considered an internal link. In this case, it should be a system URL, - * and it will be replaced with the alias, if one exists. Additional query - * arguments for internal paths must be supplied in $options['query'], not - * included in $path. - * - If you provide an internal path and $options['alias'] is set to TRUE, the - * path is assumed already to be the correct path alias, and the alias is - * not looked up. - * - The special string '' generates a link to the site's base URL. - * - If your external URL contains a query (e.g. http://example.com/foo?a=b), - * then you can either URL encode the query keys and values yourself and - * include them in $path, or use $options['query'] to let this function - * URL encode them. - * @param $options - * (optional) An associative array of additional options, with the following - * elements: - * - 'query': An array of query key/value-pairs (without any URL-encoding) to - * append to the URL. - * - 'fragment': A fragment identifier (named anchor) to append to the URL. - * Do not include the leading '#' character. - * - 'absolute': Defaults to FALSE. Whether to force the output to be an - * absolute link (beginning with http:). Useful for links that will be - * displayed outside the site, such as in an RSS feed. - * - 'alias': Defaults to FALSE. Whether the given path is a URL alias - * already. - * - 'external': Whether the given path is an external URL. - * - 'language': An optional language object. If the path being linked to is - * internal to the site, $options['language'] is used to look up the alias - * for the URL. If $options['language'] is omitted, the language will be - * obtained from language(LANGUAGE_TYPE_URL). - * - 'https': Whether this URL should point to a secure location. If not - * defined, the current scheme is used, so the user stays on HTTP or HTTPS - * respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but HTTPS can - * only be enforced when the variable 'https' is set to TRUE. - * - 'base_url': Only used internally, to modify the base URL when a language - * dependent URL requires so. - * - 'prefix': Only used internally, to modify the path when a language - * dependent URL requires so. - * - 'script': Added to the URL between the base path and the path prefix. - * Defaults to empty string when clean URLs are in effect, and to - * 'index.php/' when they are not. - * - 'entity_type': The entity type of the object that called url(). Only - * set if url() is invoked by Drupal\Core\Entity\Entity::uri(). - * - 'entity': The entity object (such as a node) for which the URL is being - * generated. Only set if url() is invoked by Drupal\Core\Entity\Entity::uri(). - * - * @return - * A string containing a URL to the given path. + * @see \Drupal\Core\Routing\PathBasedGeneratorInterface::generateFromPath(). */ function url($path = NULL, array $options = array()) { - // Merge in defaults. - $options += array( - 'fragment' => '', - 'query' => array(), - 'absolute' => FALSE, - 'alias' => FALSE, - 'prefix' => '', - 'script' => $GLOBALS['script_path'], - ); - - if (!isset($options['external'])) { - // Return an external link if $path contains an allowed absolute URL. Only - // call the slow drupal_strip_dangerous_protocols() if $path contains a ':' - // before any / ? or #. Note: we could use url_is_external($path) here, but - // that would require another function call, and performance inside url() is - // critical. - $colonpos = strpos($path, ':'); - $options['external'] = ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && drupal_strip_dangerous_protocols($path) == $path); - } - - // Preserve the original path before altering or aliasing. - $original_path = $path; - - // Allow other modules to alter the outbound URL and options. - drupal_alter('url_outbound', $path, $options, $original_path); - - if (isset($options['fragment']) && $options['fragment'] !== '') { - $options['fragment'] = '#' . $options['fragment']; - } - - if ($options['external']) { - // Split off the fragment. - if (strpos($path, '#') !== FALSE) { - list($path, $old_fragment) = explode('#', $path, 2); - // If $options contains no fragment, take it over from the path. - if (isset($old_fragment) && !$options['fragment']) { - $options['fragment'] = '#' . $old_fragment; - } - } - // Append the query. - if ($options['query']) { - $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($options['query']); - } - if (isset($options['https']) && variable_get('https', FALSE)) { - if ($options['https'] === TRUE) { - $path = str_replace('http://', 'https://', $path); - } - elseif ($options['https'] === FALSE) { - $path = str_replace('https://', 'http://', $path); - } - } - // Reassemble. - return $path . $options['fragment']; - } - - global $base_url, $base_secure_url, $base_insecure_url; - - // The base_url might be rewritten from the language rewrite in domain mode. - if (!isset($options['base_url'])) { - if (isset($options['https']) && variable_get('https', FALSE)) { - if ($options['https'] === TRUE) { - $options['base_url'] = $base_secure_url; - $options['absolute'] = TRUE; - } - elseif ($options['https'] === FALSE) { - $options['base_url'] = $base_insecure_url; - $options['absolute'] = TRUE; - } - } - else { - $options['base_url'] = $base_url; - } - } - - // The special path '' links to the default front page. - if ($path == '') { - $path = ''; - } - elseif (!empty($path) && !$options['alias']) { - $langcode = isset($options['language']) && isset($options['language']->langcode) ? $options['language']->langcode : ''; - $alias = drupal_container()->get('path.alias_manager')->getPathAlias($original_path, $langcode); - if ($alias != $original_path) { - $path = $alias; - } - } - - $base = $options['absolute'] ? $options['base_url'] . '/' : base_path(); - $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix']; - - $path = drupal_encode_path($prefix . $path); - $query = $options['query'] ? ('?' . drupal_http_build_query($options['query'])) : ''; - return $base . $options['script'] . $path . $query . $options['fragment']; + $generator = Drupal::service('router.generator'); + try { + $url = $generator->generateFromPath($path, $options); + } + catch (PathGeneratorNotInitializedException $e) { + global $base_url, $base_path, $script_path; + $generator->setBasePath($base_path); + $generator->setBaseUrl($base_url . '/'); + $generator->setScriptPath($script_path); + $url = $generator->generateFromPath($path, $options); + } + return $url; } /** diff --git a/core/includes/form.inc b/core/includes/form.inc index 27f450e..4198bae 100644 --- a/core/includes/form.inc +++ b/core/includes/form.inc @@ -1323,7 +1323,8 @@ function drupal_redirect_form($form_state) { $function($form_state['redirect']); } } - drupal_goto(current_path(), array('query' => drupal_container()->get('request')->query->all())); + $request = Drupal::service('request'); + drupal_goto($request->attributes->get('system_path'), array('query' => $request->query->all())); } } diff --git a/core/includes/install.core.inc b/core/includes/install.core.inc index bf8ef66..f3cf5dd 100644 --- a/core/includes/install.core.inc +++ b/core/includes/install.core.inc @@ -379,6 +379,8 @@ function install_begin_request(&$install_state) { )) ->addMethodCall('setUserAgent', array('Drupal (+http://drupal.org/)')); + $container->register('router.generator', 'Drupal\Core\Routing\NullGenerator'); + Drupal::setContainer($container); } diff --git a/core/lib/Drupal/Core/CoreBundle.php b/core/lib/Drupal/Core/CoreBundle.php index 09fe145..d051366 100644 --- a/core/lib/Drupal/Core/CoreBundle.php +++ b/core/lib/Drupal/Core/CoreBundle.php @@ -353,13 +353,18 @@ protected function registerRouting(ContainerBuilder $container) { ->addMethodCall('setFinalMatcher', array(new Reference('router.matcher.final_matcher'))); $container->register('router.generator', 'Drupal\Core\Routing\UrlGenerator') ->addArgument(new Reference('router.route_provider')) - ->addArgument(new Reference('path.alias_manager.cached')); + ->addArgument(new Reference('path_processor_manager')) + ->addArgument(NULL) + ->addArgument(new Reference('config.factory')) + ->addMethodCall('setRequest', array(new Reference('request', ContainerInterface::NULL_ON_INVALID_REFERENCE, false))) + ->addTag('persist'); $container->register('router.dynamic', 'Symfony\Cmf\Component\Routing\DynamicRouter') ->addArgument(new Reference('router.request_context')) ->addArgument(new Reference('router.matcher')) ->addArgument(new Reference('router.generator')); - $container->register('legacy_generator', 'Drupal\Core\Routing\NullGenerator'); + $container->register('legacy_generator', 'Drupal\Core\Routing\NullGenerator') + ->addArgument(new Reference('config.factory')); $container->register('legacy_url_matcher', 'Drupal\Core\LegacyUrlMatcher'); $container->register('legacy_router', 'Symfony\Cmf\Component\Routing\DynamicRouter') ->addArgument(new Reference('router.request_context')) @@ -415,11 +420,13 @@ protected function registerPathProcessors(ContainerBuilder $container) { // Register the processor that resolves the front page. $container->register('path_processor_front', 'Drupal\Core\PathProcessor\PathProcessorFront') ->addArgument(new Reference('config.factory')) - ->addTag('path_processor_inbound', array('priority' => 200)); + ->addTag('path_processor_inbound', array('priority' => 200)) + ->addTag('path_processor_outbound', array('priority' => 200)); // Register the alias path processor. $container->register('path_processor_alias', 'Drupal\Core\PathProcessor\PathProcessorAlias') ->addArgument(new Reference('path.alias_manager')) - ->addTag('path_processor_inbound', array('priority' => 100)); + ->addTag('path_processor_inbound', array('priority' => 100)) + ->addTag('path_processor_outbound', array('priority' => 300)); // Add the compiler pass that will process the tagged services. $container->addCompilerPass(new RegisterPathProcessorsPass()); diff --git a/core/lib/Drupal/Core/DependencyInjection/Compiler/RegisterPathProcessorsPass.php b/core/lib/Drupal/Core/DependencyInjection/Compiler/RegisterPathProcessorsPass.php index 6e298da..70de42d 100644 --- a/core/lib/Drupal/Core/DependencyInjection/Compiler/RegisterPathProcessorsPass.php +++ b/core/lib/Drupal/Core/DependencyInjection/Compiler/RegisterPathProcessorsPass.php @@ -27,9 +27,15 @@ public function process(ContainerBuilder $container) { return; } $manager = $container->getDefinition('path_processor_manager'); + // Add inbound path processors. foreach ($container->findTaggedServiceIds('path_processor_inbound') as $id => $attributes) { $priority = isset($attributes[0]['priority']) ? $attributes[0]['priority'] : 0; $manager->addMethodCall('addInbound', array(new Reference($id), $priority)); } + // Add outbound path processors. + foreach ($container->findTaggedServiceIds('path_processor_outbound') as $id => $attributes) { + $priority = isset($attributes[0]['priority']) ? $attributes[0]['priority'] : 0; + $manager->addMethodCall('addOutbound', array(new Reference($id), $priority)); + } } } diff --git a/core/lib/Drupal/Core/EventSubscriber/PathSubscriber.php b/core/lib/Drupal/Core/EventSubscriber/PathSubscriber.php index 5915d4b..669db82 100644 --- a/core/lib/Drupal/Core/EventSubscriber/PathSubscriber.php +++ b/core/lib/Drupal/Core/EventSubscriber/PathSubscriber.php @@ -9,6 +9,7 @@ use Drupal\Core\CacheDecorator\AliasManagerCacheDecorator; use Drupal\Core\PathProcessor\InboundPathProcessorInterface; +use Drupal\Core\Routing\PathBasedGeneratorInterface; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\HttpKernel\Event\GetResponseEvent; @@ -22,6 +23,7 @@ class PathSubscriber extends PathListenerBase implements EventSubscriberInterfac protected $aliasManager; protected $pathProcessor; + protected $generator; public function __construct(AliasManagerCacheDecorator $alias_manager, InboundPathProcessorInterface $path_processor) { $this->aliasManager = $alias_manager; diff --git a/core/lib/Drupal/Core/Language/LanguageManager.php b/core/lib/Drupal/Core/Language/LanguageManager.php index fa94205..c6b337c 100644 --- a/core/lib/Drupal/Core/Language/LanguageManager.php +++ b/core/lib/Drupal/Core/Language/LanguageManager.php @@ -134,7 +134,7 @@ public function reset($type = NULL) { * @return bool * TRUE if more than one language is enabled, FALSE otherwise. */ - protected function isMultilingual() { + public function isMultilingual() { return variable_get('language_count', 1) > 1; } diff --git a/core/lib/Drupal/Core/PathProcessor/OutboundPathProcessorInterface.php b/core/lib/Drupal/Core/PathProcessor/OutboundPathProcessorInterface.php new file mode 100644 index 0000000..d96fa6e --- /dev/null +++ b/core/lib/Drupal/Core/PathProcessor/OutboundPathProcessorInterface.php @@ -0,0 +1,32 @@ +langcode : NULL; + $path = $this->aliasManager->getPathAlias($path, $langcode); + return $path; + } } diff --git a/core/lib/Drupal/Core/PathProcessor/PathProcessorFront.php b/core/lib/Drupal/Core/PathProcessor/PathProcessorFront.php index 872885a..d03d19b 100644 --- a/core/lib/Drupal/Core/PathProcessor/PathProcessorFront.php +++ b/core/lib/Drupal/Core/PathProcessor/PathProcessorFront.php @@ -13,7 +13,7 @@ /** * Processes the inbound path by resolving it to the front page if empty. */ -class PathProcessorFront implements InboundPathProcessorInterface { +class PathProcessorFront implements InboundPathProcessorInterface, OutboundPathProcessorInterface { /** * A config factory for retrieving required config settings. @@ -45,4 +45,15 @@ public function processInbound($path, Request $request) { return $path; } + /** + * Implements Drupal\Core\PathProcessor\OutboundPathProcessorInterface::processOutbound(). + */ + public function processOutbound($path, &$options = array(), Request $request = NULL) { + // The special path '' links to the default front page. + if ($path == '') { + $path = ''; + } + return $path; + } + } diff --git a/core/lib/Drupal/Core/PathProcessor/PathProcessorManager.php b/core/lib/Drupal/Core/PathProcessor/PathProcessorManager.php index 1d0adff..db8b799 100644 --- a/core/lib/Drupal/Core/PathProcessor/PathProcessorManager.php +++ b/core/lib/Drupal/Core/PathProcessor/PathProcessorManager.php @@ -7,7 +7,6 @@ namespace Drupal\Core\PathProcessor; -use Drupal\Core\PathProcessor\InboundPathProcessorInterface; use Symfony\Component\HttpFoundation\Request; /** @@ -16,10 +15,10 @@ * Holds an array of path processor objects and uses them to sequentially process * a path, in order of processor priority. */ -class PathProcessorManager implements InboundPathProcessorInterface { +class PathProcessorManager implements InboundPathProcessorInterface, OutboundPathProcessorInterface { /** - * Holds the array of processors to cycle through. + * Holds the array of inbound processors to cycle through. * * @var array * An array whose keys are priorities and whose values are arrays of path @@ -28,13 +27,31 @@ class PathProcessorManager implements InboundPathProcessorInterface { protected $inboundProcessors = array(); /** - * Holds the array of processors, sorted by priority. + * Holds the array of inbound processors, sorted by priority. * * @var array * An array of path processor objects. */ protected $sortedInbound = array(); + + /** + * Holds the array of outbound processors to cycle through. + * + * @var array + * An array whose keys are priorities and whose values are arrays of path + * processor objects. + */ + protected $outboundProcessors = array(); + + /** + * Holds the array of outbound processors, sorted by priority. + * + * @var array + * An array of path processor objects. + */ + protected $sortedOutbound = array(); + /** * Adds an inbound processor object to the $inboundProcessors property. * @@ -74,6 +91,46 @@ protected function getInbound() { return $this->sortedInbound; } + + /** + * Adds an outbound processor object to the $outboundProcessors property. + * + * @param \Drupal\Core\PathProcessor\OutboundPathProcessorInterface $processor + * The processor object to add. + * + * @param int $priority + * The priority of the processor being added. + */ + public function addOutbound(OutboundPathProcessorInterface $processor, $priority = 0) { + $this->outboundProcessors[$priority][] = $processor; + $this->sortedOutbound = array(); + } + + /** + * Implements Drupal\Core\PathProcessor\OutboundPathProcessorInterface::processOutbound(). + */ + public function processOutbound($path, &$options = array(), Request $request = NULL) { + $processors = $this->getOutbound(); + foreach ($processors as $processor) { + $path = $processor->processOutbound($path, $options, $request); + } + return $path; + } + + /** + * Returns the sorted array of outbound processors. + * + * @return array + * An array of processor objects. + */ + protected function getOutbound() { + if (empty($this->sortedOutbound)) { + $this->sortedOutbound = $this->sortProcessors('outboundProcessors'); + } + + return $this->sortedOutbound; + } + /** * Sorts the processors according to priority. * diff --git a/core/lib/Drupal/Core/Routing/NullGenerator.php b/core/lib/Drupal/Core/Routing/NullGenerator.php index 7228514..83ef075 100644 --- a/core/lib/Drupal/Core/Routing/NullGenerator.php +++ b/core/lib/Drupal/Core/Routing/NullGenerator.php @@ -6,6 +6,8 @@ */ namespace Drupal\Core\Routing; + +use Drupal\Core\Config\ConfigFactory; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\Exception\RouteNotFoundException; @@ -13,17 +15,25 @@ /** * No-op implementation of a Url Generator, needed for backward compatibility. */ -class NullGenerator implements UrlGeneratorInterface { +class NullGenerator extends UrlGenerator { + + public $serverVariablesInitialized = TRUE; + + /** + * Override the parent constructor. + */ + public function __construct() { + } /** - * Implements Symfony\Component\Routing\Generator\UrlGeneratorInterface::generate(); + * Overrides Drupal\Core\Routing\UrlGenerator::generate(); */ public function generate($name, $parameters = array(), $absolute = FALSE) { throw new RouteNotFoundException(); } /** - * Implements Symfony\Component\Routing\RequestContextAwareInterface::setContext(); + * Overrides Drupal\Core\Routing\UrlGenerator::setContext(); */ public function setContext(RequestContext $context) { } @@ -33,4 +43,11 @@ public function setContext(RequestContext $context) { */ public function getContext() { } + + /** + * Overrides Drupal\Core\Routing\UrlGenerator::processPath(). + */ + protected function processPath($path, &$options = array()) { + return $path; + } } diff --git a/core/lib/Drupal/Core/Routing/PathBasedGeneratorInterface.php b/core/lib/Drupal/Core/Routing/PathBasedGeneratorInterface.php new file mode 100644 index 0000000..53b7d63 --- /dev/null +++ b/core/lib/Drupal/Core/Routing/PathBasedGeneratorInterface.php @@ -0,0 +1,108 @@ +'. A few notes: + * - If you provide a full URL, it will be considered an external URL. + * - If you provide only the path (e.g. "node/34"), it will be + * considered an internal link. In this case, it should be a system URL, + * and it will be replaced with the alias, if one exists. Additional query + * arguments for internal paths must be supplied in $options['query'], not + * included in $path. + * - If you provide an internal path and $options['alias'] is set to TRUE, the + * path is assumed already to be the correct path alias, and the alias is + * not looked up. + * - The special string '' generates a link to the site's base URL. + * - If your external URL contains a query (e.g. http://example.com/foo?a=b), + * then you can either URL encode the query keys and values yourself and + * include them in $path, or use $options['query'] to let this function + * URL encode them. + * @param $options + * (optional) An associative array of additional options, with the following + * elements: + * - 'query': An array of query key/value-pairs (without any URL-encoding) to + * append to the URL. + * - 'fragment': A fragment identifier (named anchor) to append to the URL. + * Do not include the leading '#' character. + * - 'absolute': Defaults to FALSE. Whether to force the output to be an + * absolute link (beginning with http:). Useful for links that will be + * displayed outside the site, such as in an RSS feed. + * - 'alias': Defaults to FALSE. Whether the given path is a URL alias + * already. + * - 'external': Whether the given path is an external URL. + * - 'language': An optional language object. If the path being linked to is + * internal to the site, $options['language'] is used to look up the alias + * for the URL. If $options['language'] is omitted, the language will be + * obtained from language(LANGUAGE_TYPE_URL). + * - 'https': Whether this URL should point to a secure location. If not + * defined, the current scheme is used, so the user stays on HTTP or HTTPS + * respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but HTTPS can + * only be enforced when the variable 'https' is set to TRUE. + * - 'base_url': Only used internally, to modify the base URL when a language + * dependent URL requires so. + * - 'prefix': Only used internally, to modify the path when a language + * dependent URL requires so. + * - 'script': Added to the URL between the base path and the path prefix. + * Defaults to empty string when clean URLs are in effect, and to + * 'index.php/' when they are not. + * - 'entity_type': The entity type of the object that called url(). Only + * set if url() is invoked by Drupal\Core\Entity\Entity::uri(). + * - 'entity': The entity object (such as a node) for which the URL is being + * generated. Only set if url() is invoked by Drupal\Core\Entity\Entity::uri(). + * + * @return + * A string containing a URL to the given path. + */ + public function generateFromPath($path = NULL, $options = array()); + + /** + * Sets the $request property. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * The HttpRequest object representing the current request. + */ + public function setRequest(Request $request); + + /** + * Sets the baseUrl property. + * + * @var string $url + * The base url to use for url generation. + */ + public function setBaseUrl($url); + + /** + * Sets the basePath property. + * + * @var string $path + * The base path to use for url generation. + */ + public function setBasePath($path); + + /** + * Sets the scriptPath property. + * + * @var string $path + * The script path to use for url generation. + */ + public function setScriptPath($path); + +} diff --git a/core/lib/Drupal/Core/Routing/PathGeneratorNotInitializedException.php b/core/lib/Drupal/Core/Routing/PathGeneratorNotInitializedException.php new file mode 100644 index 0000000..3f2b688 --- /dev/null +++ b/core/lib/Drupal/Core/Routing/PathGeneratorNotInitializedException.php @@ -0,0 +1,14 @@ +aliasManager = $alias_manager; + $this->pathProcessor = $path_processor; + $this->allowedProtocols = array_flip($config->get('system.filter')->get('protocols')); + } + + /** + * Implements \Drupal\Core\Routing\PathBasedGeneratorInterface::setRequest(). + */ + public function setRequest(Request $request) { + $this->request = $request; + // Set some properties, based on the request, that are used during url + // generation. + $this->basePath = $request->getBasePath() . '/'; + $this->baseUrl = $request->getSchemeAndHttpHost() . $this->basePath; + $this->scriptPath = ''; + $base_path_with_script = $request->getBaseUrl(); + $script_name = $request->getScriptName(); + if (!empty($base_path_with_script) && strpos($base_path_with_script, $script_name) !== FALSE) { + $length = strlen($this->basePath); + $this->scriptPath = ltrim(substr($script_name, $length), '/') . '/'; + } } /** - * Implements Symfony\Component\Routing\Generator\UrlGeneratorInterface::generate(); + * Implements Symfony\Component\Routing\Generator\UrlGeneratorInterface::generate(). */ public function generate($name, $parameters = array(), $absolute = FALSE) { $path = parent::generate($name, $parameters, $absolute); + $path = $this->processPath($path); + + return $path; + } + + /** + * Implements \Drupal\Core\Routing\PathBasedGeneratorInterface::generateFromPath(). + * + * @throws \Drupal\Core\Routing\PathGeneratorNotInitializedException. + */ + public function generateFromPath($path = NULL, $options = array()) { + + if (!$this->initialized()) { + throw new PathGeneratorNotInitializedException(); + } + + // Merge in defaults. + $options += array( + 'fragment' => '', + 'query' => array(), + 'absolute' => FALSE, + 'prefix' => '', + ); + + if (!isset($options['external'])) { + // Return an external link if $path contains an allowed absolute URL. Only + // call the slow drupal_strip_dangerous_protocols() if $path contains a ':' + // before any / ? or #. Note: we could use url_is_external($path) here, but + // that would require another function call, and performance inside url() is + // critical. + $colonpos = strpos($path, ':'); + $options['external'] = ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && $this->stripDisallowedProtocols($path, $this->allowedProtocols) == $path); + } + + if (isset($options['fragment']) && $options['fragment'] !== '') { + $options['fragment'] = '#' . $options['fragment']; + } + + if ($options['external']) { + // Split off the fragment. + if (strpos($path, '#') !== FALSE) { + list($path, $old_fragment) = explode('#', $path, 2); + // If $options contains no fragment, take it over from the path. + if (isset($old_fragment) && !$options['fragment']) { + $options['fragment'] = '#' . $old_fragment; + } + } + // Append the query. + if ($options['query']) { + $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . $this->httpBuildQuery($options['query']); + } + if (isset($options['https']) && variable_get('https', FALSE)) { + if ($options['https'] === TRUE) { + $path = str_replace('http://', 'https://', $path); + } + elseif ($options['https'] === FALSE) { + $path = str_replace('https://', 'http://', $path); + } + } + // Reassemble. + return $path . $options['fragment']; + } + else { + $path = ltrim($this->processPath($path, $options), '/'); + } + + if (!isset($options['script'])) { + $options['script'] = $this->scriptPath; + } + // The base_url might be rewritten from the language rewrite in domain mode. + if (!isset($options['base_url'])) { + if (isset($options['https']) && variable_get('https', FALSE)) { + if ($options['https'] === TRUE) { + $options['base_url'] = str_replace('http://', 'https://', $this->baseUrl); + $options['absolute'] = TRUE; + } + elseif ($options['https'] === FALSE) { + $options['base_url'] = str_replace('https://', 'http://', $this->baseUrl); + $options['absolute'] = TRUE; + } + } + else { + $options['base_url'] = $this->baseUrl; + } + } + elseif (rtrim($options['base_url'], '/') == $options['base_url']) { + $options['base_url'] .= '/'; + } + $base = $options['absolute'] ? $options['base_url'] : $this->basePath; + $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix']; + + $path = str_replace('%2F', '/', rawurlencode($prefix . $path)); + $query = $options['query'] ? ('?' . $this->httpBuildQuery($options['query'])) : ''; + return $base . $options['script'] . $path . $query . $options['fragment']; + } + + /** + * Implements \Drupal\Core\Routing\PathBasedGeneratorInterface::setBaseUrl(). + */ + public function setBaseUrl($url) { + $this->baseUrl = $url; + } + + /** + * Implements \Drupal\Core\Routing\PathBasedGeneratorInterface::setBasePath(). + */ + public function setBasePath($path) { + $this->basePath = $path; + } + + /** + * Implements \Drupal\Core\Routing\PathBasedGeneratorInterface::setScriptPath(). + */ + public function setScriptPath($path) { + $this->scriptPath = $path; + } + + /** + * Strips dangerous protocols (e.g. 'javascript:') from a URI. + * + * @param $uri + * A plain-text URI that might contain dangerous protocols. + * + * @return + * A plain-text URI stripped of dangerous protocols. As with all plain-text + * strings, this return value must not be output to an HTML page without + * check_plain() being called on it. However, it can be passed to functions + * expecting plain-text strings. + * + */ + public function stripDisallowedProtocols($uri, $protocols) { + // Iteratively remove any invalid protocol found. + do { + $before = $uri; + $colonpos = strpos($uri, ':'); + if ($colonpos > 0) { + // We found a colon, possibly a protocol. Verify. + $protocol = substr($uri, 0, $colonpos); + // If a colon is preceded by a slash, question mark or hash, it cannot + // possibly be part of the URL scheme. This must be a relative URL, which + // inherits the (safe) protocol of the base document. + if (preg_match('![/?#]!', $protocol)) { + break; + } + // Check if this is a disallowed protocol. Per RFC2616, section 3.2.3 + // (URI Comparison) scheme comparison must be case-insensitive. + if (!isset($protocols[strtolower($protocol)])) { + $uri = substr($uri, $colonpos + 1); + } + } + } while ($before != $uri); - // This method is expected to return a path with a leading /, whereas - // the alias manager has no leading /. - $path = '/' . $this->aliasManager->getPathAlias(trim($path, '/')); + return $uri; + } + + /** + * Parses an array into a valid, rawurlencoded query string. + * + * This differs from http_build_query() as we need to rawurlencode() (instead of + * urlencode()) all query parameters. + * + * @param $query + * The query parameter array to be processed, e.g. $_GET. + * @param $parent + * Internal use only. Used to build the $query array key for nested items. + * + * @return + * A rawurlencoded string which can be used as or appended to the URL query + * string. + * + * @see drupal_get_query_parameters() + * @ingroup php_wrappers + */ + public function httpBuildQuery(array $query, $parent = '') { + $params = array(); + + foreach ($query as $key => $value) { + $key = ($parent ? $parent . '[' . rawurlencode($key) . ']' : rawurlencode($key)); + + // Recurse into children. + if (is_array($value)) { + $params[] = $this->httpBuildQuery($value, $key); + } + // If a query parameter value is NULL, only append its key. + elseif (!isset($value)) { + $params[] = $key; + } + else { + // For better readability of paths in query strings, we decode slashes. + $params[] = $key . '=' . str_replace('%2F', '/', rawurlencode($value)); + } + } + return implode('&', $params); + } + + /** + * Passes the path to a processor manager to allow alterations. + */ + protected function processPath($path, &$options = array()) { + // Router-based paths may have a querystring on them. + if ($query_pos = strpos($path, '?')) { + // We don't need to do a strict check here because position 0 would mean we + // have no actual path to work with. + $actual_path = substr($path, 0, $query_pos); + $query_string = substr($path, $query_pos); + } + else { + $actual_path = $path; + $query_string = ''; + } + $path = '/' . $this->pathProcessor->processOutbound(trim($actual_path, '/'), $options, $this->request); + $path .= $query_string; return $path; } + /** + * Returns whether or not the url generator has been initialized. + * + * @return bool + * Returns TRUE if the server variables have been set, FALSE otherwise. + */ + protected function initialized() { + return isset($this->basePath) && isset($this->baseUrl) && isset($this->scriptPath); + } + } diff --git a/core/modules/file/lib/Drupal/file/Tests/DownloadTest.php b/core/modules/file/lib/Drupal/file/Tests/DownloadTest.php index 0763507..d40e5b9 100644 --- a/core/modules/file/lib/Drupal/file/Tests/DownloadTest.php +++ b/core/modules/file/lib/Drupal/file/Tests/DownloadTest.php @@ -7,6 +7,8 @@ namespace Drupal\file\Tests; +use Symfony\Component\HttpFoundation\Request; + /** * Tests for download/file transfer functions. */ @@ -84,7 +86,6 @@ function testPrivateFileTransfer() { * Test file_create_url(). */ function testFileCreateUrl() { - global $base_url, $script_path; // Tilde (~) is excluded from this test because it is encoded by // rawurlencode() in PHP 5.2 but not in PHP 5.3, as per RFC 3986. @@ -100,12 +101,18 @@ function testFileCreateUrl() { // generated by url(), whereas private files should be served by Drupal, so // their URLs should be generated by url(). The difference is most apparent // when $script_path is not empty (i.e., when not using clean URLs). - $script_path_original = $script_path; - foreach (array('', 'index.php/') as $script_path) { - $this->checkUrl('public', '', $basename, $base_url . '/' . file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath() . '/' . $basename_encoded); - $this->checkUrl('private', '', $basename, $base_url . '/' . $script_path . 'system/files/' . $basename_encoded); + $clean_url_settings = array( + 'clean' => '', + 'unclean' => 'index.php/', + ); + $generator = $this->container->get('router.generator'); + foreach ($clean_url_settings as $clean_url_setting => $script_path) { + $clean_urls = $clean_url_setting == 'clean'; + $request = $this->prepareRequestForGenerator($clean_urls); + $base_path = $request->getSchemeAndHttpHost() . $request->getBasePath(); + $this->checkUrl('public', '', $basename, $base_path . '/' . file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath() . '/' . $basename_encoded); + $this->checkUrl('private', '', $basename, $base_path . '/' . $script_path . 'system/files/' . $basename_encoded); } - $script_path = $script_path_original; } /** diff --git a/core/modules/forum/lib/Drupal/forum/Tests/ForumTest.php b/core/modules/forum/lib/Drupal/forum/Tests/ForumTest.php index c08ce70..6b7cb0e 100644 --- a/core/modules/forum/lib/Drupal/forum/Tests/ForumTest.php +++ b/core/modules/forum/lib/Drupal/forum/Tests/ForumTest.php @@ -463,7 +463,7 @@ function testForumWithNewPost() { // Login as the first user. $this->drupalLogin($this->admin_user); // Create a forum container. - $this->container = $this->createForum('container'); + $this->forumContainer = $this->createForum('container'); // Create a forum. $this->forum = $this->createForum('forum'); // Create a topic. diff --git a/core/modules/image/image.module b/core/modules/image/image.module index b2816de..a770f5d 100644 --- a/core/modules/image/image.module +++ b/core/modules/image/image.module @@ -807,7 +807,16 @@ function image_style_url($style_name, $path) { // with the script path. If the file does not exist, use url() to ensure // that it is included. Once the file exists it's fine to fall back to the // actual file path, this avoids bootstrapping PHP once the files are built. - if ($GLOBALS['script_path'] && file_uri_scheme($uri) == 'public' && !file_exists($uri)) { + $request = Drupal::service('request'); + $script_path = ''; + $base_path_with_script = $request->getBaseUrl(); + $script_name = $request->getScriptName(); + if (!empty($base_path_with_script) && strpos($base_path_with_script, $script_name) !== FALSE) { + $length = strlen($request->getBasePath()); + $script_path = ltrim(substr($script_name, $length), '/') . '/'; + } + + if ($script_path && file_uri_scheme($uri) == 'public' && !file_exists($uri)) { $directory_path = file_stream_wrapper_get_instance_by_uri($uri)->getDirectoryPath(); return url($directory_path . '/' . file_uri_target($uri), array('absolute' => TRUE, 'query' => $token_query)); } diff --git a/core/modules/image/lib/Drupal/image/Tests/ImageStylesPathAndUrlTest.php b/core/modules/image/lib/Drupal/image/Tests/ImageStylesPathAndUrlTest.php index f755ba0..eca58ac 100644 --- a/core/modules/image/lib/Drupal/image/Tests/ImageStylesPathAndUrlTest.php +++ b/core/modules/image/lib/Drupal/image/Tests/ImageStylesPathAndUrlTest.php @@ -8,6 +8,7 @@ namespace Drupal\image\Tests; use Drupal\simpletest\WebTestBase; +use Symfony\Component\HttpFoundation\Request; /** * Tests the functions for generating paths and URLs for image styles. @@ -94,8 +95,7 @@ function testImageStyleUrlExtraSlash() { * Tests image_style_url(). */ function _testImageStyleUrlAndPath($scheme, $clean_url = TRUE, $extra_slash = FALSE) { - $script_path_original = $GLOBALS['script_path']; - $GLOBALS['script_path'] = $clean_url ? '' : 'index.php/'; + $request = $this->prepareRequestForGenerator($clean_url); // Make the default scheme neither "public" nor "private" to verify the // functions work for other than the default scheme. @@ -129,9 +129,10 @@ function _testImageStyleUrlAndPath($scheme, $clean_url = TRUE, $extra_slash = FA $this->assertNotEqual($original_uri, $modified_uri, 'An extra slash was added to the generated file URI.'); $generate_url = image_style_url($this->style_name, $modified_uri); } - - if ($GLOBALS['script_path']) { - $this->assertTrue(strpos($generate_url, $GLOBALS['script_path']) !== FALSE, 'When using non-clean URLS, the system path contains the script name.'); + $script_path = ''; + if (!$clean_url) { + $script_path = 'index.php/'; + $this->assertTrue(strpos($generate_url, $script_path) !== FALSE, 'When using non-clean URLS, the system path contains the script name.'); } // Add some extra chars to the token. $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url)); @@ -184,12 +185,10 @@ function _testImageStyleUrlAndPath($scheme, $clean_url = TRUE, $extra_slash = FA $this->assertNoRaw( chr(137) . chr(80) . chr(78) . chr(71) . chr(13) . chr(10) . chr(26) . chr(10), 'No PNG signature found in the response body.'); } } - elseif (!$GLOBALS['script_path']) { + elseif (empty($script_path)) { // Add some extra chars to the token. $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url)); $this->assertResponse(200, 'Existing image was accessible at the URL wih an invalid token.'); } - - $GLOBALS['script_path'] = $script_path_original; } } diff --git a/core/modules/language/language.module b/core/modules/language/language.module index 1c20695..e1465a2 100644 --- a/core/modules/language/language.module +++ b/core/modules/language/language.module @@ -641,7 +641,6 @@ function language_language_negotiation_info() { 'callbacks' => array( 'negotiation' => 'language_from_url', 'language_switch' => 'language_switcher_url', - 'url_rewrite' => 'language_url_rewrite_url', ), 'file' => $file, 'weight' => -8, @@ -778,56 +777,6 @@ function language_preprocess_block(&$variables) { } /** - * Implements hook_url_outbound_alter(). - * - * Rewrite outbound URLs with language based prefixes. - */ -function language_url_outbound_alter(&$path, &$options, $original_path) { - // Only modify internal URLs. - if (!$options['external'] && language_multilingual()) { - static $drupal_static_fast; - if (!isset($drupal_static_fast)) { - $drupal_static_fast['callbacks'] = &drupal_static(__FUNCTION__); - } - $callbacks = &$drupal_static_fast['callbacks']; - - if (!isset($callbacks)) { - $callbacks = array(); - include_once DRUPAL_ROOT . '/core/includes/language.inc'; - - foreach (language_types_get_configurable() as $type) { - // Get URL rewriter callbacks only from enabled language methods. - $negotiation = variable_get("language_negotiation_$type", array()); - - foreach ($negotiation as $method_id => $method) { - if (isset($method['callbacks']['url_rewrite'])) { - if (isset($method['file'])) { - require_once DRUPAL_ROOT . '/' . $method['file']; - } - // Avoid duplicate callback entries. - $callbacks[$method['callbacks']['url_rewrite']] = TRUE; - } - } - } - - $callbacks = array_keys($callbacks); - } - - // No language dependent path allowed in this mode. - if (empty($callbacks)) { - unset($options['language']); - return; - } - - foreach ($callbacks as $callback) { - if (function_exists($callback)) { - $callback($path, $options); - } - } - } -} - -/** * Returns language mappings between browser and Drupal language codes. * * @return array diff --git a/core/modules/language/language.negotiation.inc b/core/modules/language/language.negotiation.inc index 6565c6d..252bf47 100644 --- a/core/modules/language/language.negotiation.inc +++ b/core/modules/language/language.negotiation.inc @@ -423,85 +423,6 @@ function language_switcher_session($type, $path) { } /** - * Rewrite URLs for the URL language negotiation method. - */ -function language_url_rewrite_url(&$path, &$options) { - static $drupal_static_fast; - if (!isset($drupal_static_fast)) { - $drupal_static_fast['languages'] = &drupal_static(__FUNCTION__); - } - $languages = &$drupal_static_fast['languages']; - - if (!isset($languages)) { - $languages = language_list(); - $languages = array_flip(array_keys($languages)); - } - - // Language can be passed as an option, or we go for current URL language. - if (!isset($options['language'])) { - $language_url = language(LANGUAGE_TYPE_URL); - $options['language'] = $language_url; - } - // We allow only enabled languages here. - elseif (is_object($options['language']) && !isset($languages[$options['language']->langcode])) { - unset($options['language']); - return; - } - - if (isset($options['language'])) { - switch (config('language.negotiation')->get('url.source')) { - case LANGUAGE_NEGOTIATION_URL_DOMAIN: - $domains = language_negotiation_url_domains(); - if (is_object($options['language']) && !empty($domains[$options['language']->langcode])) { - global $is_https; - - // Save the original base URL. If it contains a port, we need to - // retain it below. - if (!empty($options['base_url'])) { - // The colon in the URL scheme messes up the port checking below. - $normalized_base_url = str_replace(array('https://', 'http://'), '', $options['base_url']); - - } - - // Ask for an absolute URL with our modified base URL. - $url_scheme = ($is_https) ? 'https://' : 'http://'; - $options['absolute'] = TRUE; - $options['base_url'] = $url_scheme . $domains[$options['language']->langcode]; - - // In case either the original base URL or the HTTP host contains a - // port, retain it. - $http_host = $_SERVER['HTTP_HOST']; - if (isset($normalized_base_url) && strpos($normalized_base_url, ':') !== FALSE) { - list($host, $port) = explode(':', $normalized_base_url); - $options['base_url'] .= ':' . $port; - } - elseif (strpos($http_host, ':') !== FALSE) { - list($host, $port) = explode(':', $http_host); - $options['base_url'] .= ':' . $port; - } - - if (isset($options['https']) && variable_get('https', FALSE)) { - if ($options['https'] === TRUE) { - $options['base_url'] = str_replace('http://', 'https://', $options['base_url']); - } - elseif ($options['https'] === FALSE) { - $options['base_url'] = str_replace('https://', 'http://', $options['base_url']); - } - } - } - break; - - case LANGUAGE_NEGOTIATION_URL_PREFIX: - $prefixes = language_negotiation_url_prefixes(); - if (is_object($options['language']) &&!empty($prefixes[$options['language']->langcode])) { - $options['prefix'] = $prefixes[$options['language']->langcode] . '/'; - } - break; - } - } -} - -/** * Reads language prefixes and uses the langcode if no prefix is set. */ function language_negotiation_url_prefixes() { diff --git a/core/modules/language/lib/Drupal/language/HttpKernel/PathProcessorLanguage.php b/core/modules/language/lib/Drupal/language/HttpKernel/PathProcessorLanguage.php index ad16ac6..32a2385 100644 --- a/core/modules/language/lib/Drupal/language/HttpKernel/PathProcessorLanguage.php +++ b/core/modules/language/lib/Drupal/language/HttpKernel/PathProcessorLanguage.php @@ -7,31 +7,164 @@ namespace Drupal\language\HttpKernel; -use Drupal\Core\Extension\ModuleHandlerInterface; +use Drupal\Core\Config\ConfigFactory; +use Drupal\Core\Language\LanguageManager; use Drupal\Core\PathProcessor\InboundPathProcessorInterface; +use Drupal\Core\PathProcessor\OutboundPathProcessorInterface; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpFoundation\Request; /** * Processes the inbound path using path alias lookups. */ -class PathProcessorLanguage implements InboundPathProcessorInterface { +class PathProcessorLanguage implements InboundPathProcessorInterface, OutboundPathProcessorInterface { - protected $moduleHandler; + /** + * A config factory for retrieving required config settings. + * + * @var \Drupal\Core\Config\ConfigFactory + */ + protected $config; + + /** + * Language manager for retrieving the url language type. + * + * @var \Drupal\Core\Language\LanguageManager + */ + protected $languageManager; + + + /** + * A request object. + * + * @var \Symfony\Component\HttpFoundation\Request + */ + protected $request; + + /** + * The url scheme to use for urls. + * + * @var string + */ + protected $urlScheme = 'http'; - public function __construct(ModuleHandlerInterface $module_handler) { - $this->moduleHandler = $module_handler; + /** + * The host to use for urls. + * + * @var string + */ + protected $httpHost; + + /** + * The port to use for urls. + * + * @var string + */ + protected $port = 80; + + public function __construct(ConfigFactory $config, LanguageManager $language_manager) { + $this->config = $config; + $this->languageManager = $language_manager; + $this->languages = language_list(); + } + + /** + * Sets the request and request-related properties. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * The HttpRequest object representing the current request. + */ + public function setRequest(Request $request) { + $this->request = $request; + $this->urlScheme = $request->getScheme(); + $this->port = $request->getPort(); } /** * Implements Drupal\Core\PathProcessor\InboundPathProcessorInterface::processInbound(). */ public function processInbound($path, Request $request) { - include_once DRUPAL_ROOT . '/core/includes/language.inc'; - $this->moduleHandler->loadInclude('language', 'inc', 'language.negotiation'); - $languages = language_list(); - list($language, $path) = language_url_split_prefix($path, $languages); + $this->setRequest($request); + if (!empty($path)) { + $args = explode('/', $path); + $prefix = array_shift($args); + + // Search prefix within enabled languages. + $prefixes = $this->config->get('language.negotiation')->get('url.prefixes'); + foreach ($this->languages as $language) { + if (isset($prefixes[$language->langcode]) && $prefixes[$language->langcode] == $prefix) { + // Rebuild $path with the language removed. + return implode('/', $args); + } + } + } return $path; } + /** + * Implements Drupal\Core\PathProcessor\InboundPathProcessorInterface::processOutbound(). + */ + public function processOutbound($path, &$options = array(), Request $request = NULL) { + if (!$this->languageManager->isMultilingual()) { + return $path; + } + if ($request && $request !== $this->request) { + $this->setRequest($request); + } + $languages = array_flip(array_keys($this->languages)); + // Language can be passed as an option, or we go for current URL language. + if (!isset($options['language'])) { + $language_url = $this->languageManager->getLanguage(LANGUAGE_TYPE_URL); + $options['language'] = $language_url; + } + // We allow only enabled languages here. + elseif (is_object($options['language']) && !isset($languages[$options['language']->langcode])) { + return $path; + } + $url_source = $this->config->get('language.negotiation')->get('url.source'); + // @todo Go back to using a constant instead of the string 'path_prefix' once we can use a class + // constant. + if ($url_source == 'path_prefix') { + $prefixes = $this->config->get('language.negotiation')->get('url.prefixes'); + if (is_object($options['language']) && !empty($prefixes[$options['language']->langcode])) { + return empty($path) ? $prefixes[$options['language']->langcode] : $prefixes[$options['language']->langcode] . '/' . $path; + } + } + elseif ($url_source == 'domain') { + $domains = $this->config->get('language.negotiation')->get('url.domains'); + if (is_object($options['language']) && !empty($domains[$options['language']->langcode])) { + + // Save the original base URL. If it contains a port, we need to + // retain it below. + if (!empty($options['base_url'])) { + // The colon in the URL scheme messes up the port checking below. + $normalized_base_url = str_replace(array('https://', 'http://'), '', $options['base_url']); + } + + // Ask for an absolute URL with our modified base URL. + $options['absolute'] = TRUE; + $options['base_url'] = $this->urlScheme . '://' . $domains[$options['language']->langcode]; + + // In case either the original base URL or the HTTP host contains a + // port, retain it. + if (isset($normalized_base_url) && strpos($normalized_base_url, ':') !== FALSE) { + list($host, $port) = explode(':', $normalized_base_url); + $options['base_url'] .= ':' . $port; + } + elseif ($this->port != 80) { + $options['base_url'] .= ':' . $this->port; + } + + if (isset($options['https']) && variable_get('https', FALSE)) { + if ($options['https'] === TRUE) { + $options['base_url'] = str_replace('http://', 'https://', $options['base_url']); + } + elseif ($options['https'] === FALSE) { + $options['base_url'] = str_replace('https://', 'http://', $options['base_url']); + } + } + } + } + return $path; + } } diff --git a/core/modules/language/lib/Drupal/language/LanguageBundle.php b/core/modules/language/lib/Drupal/language/LanguageBundle.php index 1e788aa..a0a76f5 100644 --- a/core/modules/language/lib/Drupal/language/LanguageBundle.php +++ b/core/modules/language/lib/Drupal/language/LanguageBundle.php @@ -22,8 +22,10 @@ class LanguageBundle extends Bundle { public function build(ContainerBuilder $container) { // Register the language-based path processor. $container->register('path_processor_language', 'Drupal\language\HttpKernel\PathProcessorLanguage') - ->addArgument(new Reference('module_handler')) - ->addTag('path_processor_inbound', array('priority' => 300)); + ->addArgument(new Reference('config.factory')) + ->addArgument(new Reference('language_manager')) + ->addTag('path_processor_inbound', array('priority' => 300)) + ->addTag('path_processor_outbound', array('priority' => 100)); } } diff --git a/core/modules/language/lib/Drupal/language/Tests/LanguagePathMonolingualTest.php b/core/modules/language/lib/Drupal/language/Tests/LanguagePathMonolingualTest.php index 89a1bd6..d9f703b 100644 --- a/core/modules/language/lib/Drupal/language/Tests/LanguagePathMonolingualTest.php +++ b/core/modules/language/lib/Drupal/language/Tests/LanguagePathMonolingualTest.php @@ -40,15 +40,18 @@ function setUp() { $edit = array(); $edit['predefined_langcode'] = 'fr'; $this->drupalPost('admin/config/regional/language/add', $edit, t('Add language')); + $this->rebuildContainer(); // Make French the default language. $edit = array( 'site_default_language' => 'fr', ); $this->drupalpost('admin/config/regional/settings', $edit, t('Save configuration')); + $this->rebuildContainer(); // Delete English. $this->drupalPost('admin/config/regional/language/delete/en', array(), t('Delete')); + $this->rebuildContainer(); // Verify that French is the only language. $this->assertFalse(language_multilingual(), 'Site is mono-lingual'); @@ -57,7 +60,7 @@ function setUp() { // Set language detection to URL. $edit = array('language_interface[enabled][language-url]' => TRUE); $this->drupalPost('admin/config/regional/language/detection', $edit, t('Save settings')); - + $this->rebuildContainer(); // Force languages to be initialized. drupal_language_initialize(); } diff --git a/core/modules/language/lib/Drupal/language/Tests/LanguageUILanguageNegotiationTest.php b/core/modules/language/lib/Drupal/language/Tests/LanguageUILanguageNegotiationTest.php index e614da2..c45056b 100644 --- a/core/modules/language/lib/Drupal/language/Tests/LanguageUILanguageNegotiationTest.php +++ b/core/modules/language/lib/Drupal/language/Tests/LanguageUILanguageNegotiationTest.php @@ -9,6 +9,7 @@ use Drupal\simpletest\WebTestBase; use Drupal\Core\Language\Language; +use Symfony\Component\HttpFoundation\Request; /** * Test UI language negotiation @@ -414,7 +415,8 @@ function testUrlLanguageFallback() { // Check that the language switcher active link matches the given browser // language. - $args = array(':id' => 'block-test-language-block', ':url' => base_path() . $GLOBALS['script_path'] . $langcode_browser_fallback); + $url = base_path() . $GLOBALS['script_path'] . $langcode_browser_fallback; + $args = array(':id' => 'block-test-language-block', ':url' => $url); $fields = $this->xpath('//div[@id=:id]//a[@class="language-link active" and starts-with(@href, :url)]', $args); $this->assertTrue($fields[0] == $languages[$langcode_browser_fallback]->name, 'The browser language is the URL active language'); @@ -448,6 +450,7 @@ function testLanguageDomain() { 'domain[it]' => 'it.example.com', ); $this->drupalPost('admin/config/regional/language/detection/url', $edit, t('Save configuration')); + $this->rebuildContainer(); // Build the link we're going to test. $link = 'it.example.com/admin'; @@ -463,17 +466,19 @@ function testLanguageDomain() { // Test HTTPS via options. variable_set('https', TRUE); + $this->rebuildContainer(); + $italian_url = url('admin', array('https' => TRUE, 'language' => $languages['it'], 'script' => '')); $correct_link = 'https://' . $link; $this->assertTrue($italian_url == $correct_link, format_string('The url() function returns the right HTTPS URL (via options) (@url) in accordance with the chosen language', array('@url' => $italian_url))); variable_set('https', FALSE); // Test HTTPS via current URL scheme. - $temp_https = $is_https; - $is_https = TRUE; + $generator = $this->container->get('router.generator'); + $request = Request::create('', 'GET', array(), array(), array(), array('HTTPS' => 'on')); + $generator->setRequest($request); $italian_url = url('admin', array('language' => $languages['it'], 'script' => '')); $correct_link = 'https://' . $link; $this->assertTrue($italian_url == $correct_link, format_string('The url() function returns the right URL (via current URL scheme) (@url) in accordance with the chosen language', array('@url' => $italian_url))); - $is_https = $temp_https; } } diff --git a/core/modules/language/lib/Drupal/language/Tests/LanguageUrlRewritingTest.php b/core/modules/language/lib/Drupal/language/Tests/LanguageUrlRewritingTest.php index 3effed4..197a163 100644 --- a/core/modules/language/lib/Drupal/language/Tests/LanguageUrlRewritingTest.php +++ b/core/modules/language/lib/Drupal/language/Tests/LanguageUrlRewritingTest.php @@ -8,6 +8,7 @@ namespace Drupal\language\Tests; use Drupal\simpletest\WebTestBase; +use Symfony\Component\HttpFoundation\Request; /** * Test that URL rewriting works as expected. @@ -47,8 +48,6 @@ function setUp() { // Reset static caching. drupal_static_reset('language_list'); - drupal_static_reset('language_url_outbound_alter'); - drupal_static_reset('language_url_rewrite_url'); } /** @@ -60,6 +59,7 @@ function testUrlRewritingEdgeCases() { $non_existing->langcode = $this->randomName(); $this->checkUrl($non_existing, 'Path language is ignored if language is not installed.', 'URL language negotiation does not work with non-installed languages'); + $request = $this->prepareRequestForGenerator(); // Check that URL rewriting is not applied to subrequests. $this->drupalGet('language_test/subrequest'); $this->assertText($this->web_user->name, 'Page correctly retrieved'); @@ -109,6 +109,9 @@ function testDomainNameNegotiationPort() { 'domain[fr]' => $language_domain ); $this->drupalPost('admin/config/regional/language/detection/url', $edit, t('Save configuration')); + // Rebuild the container so that the new language gets picked up by services + // that hold the list of languages. + $this->rebuildContainer(); // Enable domain configuration. config('language.negotiation') @@ -117,17 +120,13 @@ function testDomainNameNegotiationPort() { // Reset static caching. drupal_static_reset('language_list'); - drupal_static_reset('language_url_outbound_alter'); drupal_static_reset('language_url_rewrite_url'); // In case index.php is part of the URLs, we need to adapt the asserted // URLs as well. $index_php = strpos(url('', array('absolute' => TRUE)), 'index.php') !== FALSE; - // Remember current HTTP_HOST. - $http_host = $_SERVER['HTTP_HOST']; - // Fake a different port. - $_SERVER['HTTP_HOST'] .= ':88'; + $request = $this->prepareRequestForGenerator(TRUE, array('SERVER_PORT' => '88')); // Create an absolute French link. $language = language_load('fr'); @@ -137,22 +136,18 @@ function testDomainNameNegotiationPort() { )); $expected = $index_php ? 'http://example.fr:88/index.php/' : 'http://example.fr:88/'; - $this->assertEqual($url, $expected, 'The right port is used.'); // If we set the port explicitly in url(), it should not be overriden. $url = url('', array( 'absolute' => TRUE, 'language' => $language, - 'base_url' => $GLOBALS['base_url'] . ':90', + 'base_url' => $request->getBaseUrl() . ':90', )); $expected = $index_php ? 'http://example.fr:90/index.php/' : 'http://example.fr:90/'; - $this->assertEqual($url, $expected, 'A given port is not overriden.'); - // Restore HTTP_HOST. - $_SERVER['HTTP_HOST'] = $http_host; } } diff --git a/core/modules/language/tests/language_test/language_test.module b/core/modules/language/tests/language_test/language_test.module index cb97937..a93a6d9 100644 --- a/core/modules/language/tests/language_test/language_test.module +++ b/core/modules/language/tests/language_test/language_test.module @@ -117,5 +117,18 @@ function language_test_menu() { * Page callback. Uses a subrequest to retrieve the 'user' page. */ function language_test_subrequest() { - return drupal_container()->get('http_kernel')->handle(Request::create('/user'), HttpKernelInterface::SUB_REQUEST); + $request = Request::createFromGlobals(); + $server = $request->server->all(); + if (basename($server['SCRIPT_FILENAME']) != basename($server['SCRIPT_NAME'])) { + // We need this for when the test is executed by run-tests.sh. + // @todo Remove this once run-tests.sh has been converted to use a Request + // object. + $server['SCRIPT_FILENAME'] = $server['SCRIPT_NAME']; + $base_path = ltrim($server['REQUEST_URI'], '/'); + } + else { + $base_path = $request->getBasePath(); + } + $subrequest = Request::create($base_path . '/user', 'GET', $request->query->all(), $request->cookies->all(), array(), $server); + return Drupal::service('http_kernel')->handle($subrequest, HttpKernelInterface::SUB_REQUEST); } diff --git a/core/modules/locale/locale.install b/core/modules/locale/locale.install index 0bcf093..c12c235 100644 --- a/core/modules/locale/locale.install +++ b/core/modules/locale/locale.install @@ -849,6 +849,10 @@ function locale_update_8011() { * Renames language_default language negotiation method to language_selected. */ function locale_update_8013() { + // @todo We only need language.inc here because LANGUAGE_NEGOTIATION_SELECTED + // is defined there. Remove this line once that has been converted to a class + // constant. + require_once DRUPAL_ROOT . '/core/includes/language.inc'; $weight = update_variable_get('language_negotiation_methods_weight_language_interface', NULL); if ($weight !== NULL) { $weight[LANGUAGE_NEGOTIATION_SELECTED] = $weight['language-default']; diff --git a/core/modules/path/lib/Drupal/path/Tests/PathLanguageTest.php b/core/modules/path/lib/Drupal/path/Tests/PathLanguageTest.php index 455a3f6..9ee3a6c 100644 --- a/core/modules/path/lib/Drupal/path/Tests/PathLanguageTest.php +++ b/core/modules/path/lib/Drupal/path/Tests/PathLanguageTest.php @@ -95,10 +95,10 @@ function testAliasTranslation() { // Confirm that the alias is returned by url(). Languages are cached on // many levels, and we need to clear those caches. drupal_static_reset('language_list'); - drupal_static_reset('language_url_outbound_alter'); - drupal_static_reset('language_url_rewrite_url'); + $this->rebuildContainer(); $languages = language_list(); - $url = url('node/' . $french_node->nid, array('language' => $languages[$french_node->langcode])); + $url = $this->container->get('router.generator')->generateFromPath('node/' . $french_node->nid, array('language' => $languages[$french_node->langcode])); + $this->assertTrue(strpos($url, $edit['path[alias]']), 'URL contains the path alias.'); // Confirm that the alias works even when changing language negotiation diff --git a/core/modules/rdf/lib/Drupal/rdf/SiteSchema/BundleSchema.php b/core/modules/rdf/lib/Drupal/rdf/SiteSchema/BundleSchema.php index 2c92696..a20440a 100644 --- a/core/modules/rdf/lib/Drupal/rdf/SiteSchema/BundleSchema.php +++ b/core/modules/rdf/lib/Drupal/rdf/SiteSchema/BundleSchema.php @@ -49,7 +49,7 @@ public function __construct($site_schema, $entity_type, $bundle) { */ public function getUri() { $path = str_replace(array('{entity_type}', '{bundle}'), array($this->entityType, $this->bundle), static::$uriPattern); - return $this->siteSchema->getUri() . $path; + return $this->siteSchema->getUri() . '/' . $path; } /** diff --git a/core/modules/rdf/lib/Drupal/rdf/SiteSchema/EntitySchema.php b/core/modules/rdf/lib/Drupal/rdf/SiteSchema/EntitySchema.php index 48a69fc..282c904 100644 --- a/core/modules/rdf/lib/Drupal/rdf/SiteSchema/EntitySchema.php +++ b/core/modules/rdf/lib/Drupal/rdf/SiteSchema/EntitySchema.php @@ -58,7 +58,7 @@ public function getGraph() { */ public function getUri() { $path = str_replace('{entity_type}', $this->entityType , static::$uriPattern); - return $this->siteSchema->getUri() . $path; + return $this->siteSchema->getUri() . '/' . $path; } /** diff --git a/core/modules/rdf/lib/Drupal/rdf/Tests/SiteSchemaTest.php b/core/modules/rdf/lib/Drupal/rdf/Tests/SiteSchemaTest.php index 0cfe07f..986118b 100644 --- a/core/modules/rdf/lib/Drupal/rdf/Tests/SiteSchemaTest.php +++ b/core/modules/rdf/lib/Drupal/rdf/Tests/SiteSchemaTest.php @@ -47,7 +47,6 @@ function testSiteSchema() { 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' => 'http://www.w3.org/2000/01/rdf-schema#class', 'http://www.w3.org/2000/01/rdf-schema#subClassOf' => url("$schema_path$entity_type", array('absolute' => TRUE)), ); - $this->assertEqual($bundle_schema->getUri(), $bundle_uri, 'Bundle term URI is generated correctly.'); $this->assertEqual($bundle_schema->getProperties(), $bundle_properties, 'Bundle term properties are generated correctly.'); } diff --git a/core/modules/simpletest/lib/Drupal/simpletest/DrupalUnitTestBase.php b/core/modules/simpletest/lib/Drupal/simpletest/DrupalUnitTestBase.php index e5f33d4..264deec 100644 --- a/core/modules/simpletest/lib/Drupal/simpletest/DrupalUnitTestBase.php +++ b/core/modules/simpletest/lib/Drupal/simpletest/DrupalUnitTestBase.php @@ -169,6 +169,16 @@ public function containerBuild(ContainerBuilder $container) { ->register('keyvalue', 'Drupal\Core\KeyValueStore\KeyValueFactory') ->addArgument(new Reference('service_container')); } + + if ($container->hasDefinition('path_processor_alias')) { + // Prevent the alias-based path processor, which requires a url_alias db + // table, from being registered to the path processor manager. We do this + // by removing the tags that the compiler pass looks for. This means the + // url generator can safely be used within DUTB tests. + $definition = $container->getDefinition('path_processor_alias'); + $definition->clearTag('path_processor_inbound')->clearTag('path_processor_outbound'); + } + } /** diff --git a/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php b/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php index 5cca38a..ecfc982 100644 --- a/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php +++ b/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php @@ -17,6 +17,7 @@ use DOMXPath; use SimpleXMLElement; use Drupal\Core\Datetime\DrupalDateTime; +use Symfony\Component\HttpFoundation\Request; /** * Test case for typical Drupal tests. @@ -834,6 +835,10 @@ protected function setUp() { // Reset/rebuild all data structures after enabling the modules. $this->resetAll(); + // Make sure the url generator has a request object, otherwise calls to + // $this->drupalGet() will fail. + $this->container->get('router.generator')->setRequest(Request::createFromGlobals()); + // Now make sure that the file path configurations are saved. This is done // after we install the modules to override default values. foreach ($variable_groups as $config_base => $variables) { @@ -1133,7 +1138,7 @@ protected function parse() { * @param $path * Drupal path or URL to load into internal browser * @param $options - * Options to be forwarded to url(). + * Options to be forwarded to the url generator. * @param $headers * An array containing additional HTTP request headers, each formatted as * "name: value". @@ -1146,7 +1151,8 @@ protected function drupalGet($path, array $options = array(), array $headers = a // We re-using a CURL connection here. If that connection still has certain // options set, it might change the GET into a POST. Make sure we clear out // previous options. - $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers)); + $url = $this->container->get('router.generator')->generateFromPath($path, $options); + $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => $url, CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers)); $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up. // Replace original page output with new output from redirected page(s). @@ -1238,7 +1244,7 @@ protected function drupalGetAJAX($path, array $options = array(), array $headers * textfield: under these conditions, no button information is added to the * POST data. * @param $options - * Options to be forwarded to url(). + * Options to be forwarded to the url generator. * @param $headers * An array containing additional HTTP request headers, each formatted as * "name: value". @@ -1357,7 +1363,7 @@ protected function drupalPost($path, $edit, $submit, array $options = array(), a * element. In the absence of both the triggering element's Ajax path and * $ajax_path 'system/ajax' will be used. * @param $options - * (optional) Options to be forwarded to url(). + * (optional) Options to be forwarded to the url generator. * @param $headers * (optional) An array containing additional HTTP request headers, each * formatted as "name: value". Forwarded to drupalPost(). @@ -1564,7 +1570,7 @@ protected function checkForMetaRefresh() { * @param $path * Drupal path or URL to load into internal browser * @param $options - * Options to be forwarded to url(). + * Options to be forwarded to the url generator. * @param $headers * An array containing additional HTTP request headers, each formatted as * "name: value". @@ -1573,7 +1579,8 @@ protected function checkForMetaRefresh() { */ protected function drupalHead($path, array $options = array(), array $headers = array()) { $options['absolute'] = TRUE; - $out = $this->curlExec(array(CURLOPT_NOBODY => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_HTTPHEADER => $headers)); + $url = $this->container->get('router.generator')->generateFromPath($path, $options); + $out = $this->curlExec(array(CURLOPT_NOBODY => TRUE, CURLOPT_URL => $url, CURLOPT_HTTPHEADER => $headers)); $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up. return $out; } @@ -2154,7 +2161,7 @@ protected function drupalSetSettings($settings) { * @param $path * The expected system path. * @param $options - * (optional) Any additional options to pass for $path to url(). + * (optional) Any additional options to pass for $path to the url generator. * @param $message * (optional) A message to display with the assertion. Do not translate * messages: use format_string() to embed variables in the message text, not @@ -2171,11 +2178,11 @@ protected function drupalSetSettings($settings) { protected function assertUrl($path, array $options = array(), $message = '', $group = 'Other') { if (!$message) { $message = t('Current URL is @url.', array( - '@url' => var_export(url($path, $options), TRUE), + '@url' => var_export($this->container->get('router.generator')->generateFromPath($path, $options), TRUE), )); } $options['absolute'] = TRUE; - return $this->assertEqual($this->getUrl(), url($path, $options), $message, $group); + return $this->assertEqual($this->getUrl(), $this->container->get('router.generator')->generateFromPath($path, $options), $message, $group); } /** @@ -3165,4 +3172,46 @@ protected function verboseEmail($count = 1) { $this->verbose(t('Email:') . '
' . print_r($mail, TRUE) . '
'); } } + + /** + * Creates a mock request and sets is on the generator. + * + * This is used to manipulate how the generator generates paths during tests. + * + * @param bool $clean_urls + * Whether to mock the request using clean urls. + * + * @param $override_server_vars + * An array of server variables to override. + * + * @return $request + * The mocked request object. + */ + protected function prepareRequestForGenerator($clean_urls = TRUE, $override_server_vars = array()) { + $generator = $this->container->get('router.generator'); + $request = Request::createFromGlobals(); + $server = $request->server->all(); + if (basename($server['SCRIPT_FILENAME']) != basename($server['SCRIPT_NAME'])) { + // We need this for when the test is executed by run-tests.sh. + // @todo Remove this once run-tests.sh has been converted to use a Request + // object. + $cwd = getcwd(); + $server['SCRIPT_FILENAME'] = $cwd . '/' . basename($server['SCRIPT_NAME']); + $base_path = rtrim($server['REQUEST_URI'], '/'); + } + else { + $base_path = $request->getBasePath(); + } + if ($clean_urls) { + $request_path = $base_path ? $base_path . '/user' : 'user'; + } + else { + $request_path = $base_path ? $base_path . '/index.php/user' : '/index.php/user'; + } + $server = array_merge($server, $override_server_vars); + + $request = Request::create($request_path, 'GET', array(), array(), array(), $server); + $generator->setRequest($request); + return $request; + } } diff --git a/core/modules/system/lib/Drupal/system/Tests/Common/HttpRequestTest.php b/core/modules/system/lib/Drupal/system/Tests/Common/HttpRequestTest.php index b2670fc..629336d 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Common/HttpRequestTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/Common/HttpRequestTest.php @@ -152,6 +152,7 @@ function testDrupalHTTPRequestHeaders() { 'name' => 'French', )); language_save($language); + $this->rebuildContainer(); // Request front page in French and check for matching Content-language. $request = drupal_http_request(url('', array('absolute' => TRUE, 'language' => $language))); diff --git a/core/modules/system/lib/Drupal/system/Tests/Common/UrlTest.php b/core/modules/system/lib/Drupal/system/Tests/Common/UrlTest.php index eeb49cc..66cd090 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Common/UrlTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/Common/UrlTest.php @@ -8,6 +8,7 @@ namespace Drupal\system\Tests\Common; use Drupal\simpletest\WebTestBase; +use Symfony\Component\HttpFoundation\Request; /** * Tests for URL generation functions. @@ -171,50 +172,6 @@ function testDrupalParseUrl() { } /** - * Tests url() functionality. - * - * Tests url() with/without query, with/without fragment, absolute on/off and - * asserts all that works when clean URLs are on and off. - */ - function testUrl() { - global $base_url, $script_path; - - $script_path_original = $script_path; - foreach (array('', 'index.php/') as $script_path) { - foreach (array(FALSE, TRUE) as $absolute) { - // Get the expected start of the path string. - $base = ($absolute ? $base_url . '/' : base_path()) . $script_path; - $absolute_string = $absolute ? 'absolute' : NULL; - - $url = $base . 'node/123'; - $result = url('node/123', array('absolute' => $absolute)); - $this->assertEqual($url, $result, "$url == $result"); - - $url = $base . 'node/123#foo'; - $result = url('node/123', array('fragment' => 'foo', 'absolute' => $absolute)); - $this->assertEqual($url, $result, "$url == $result"); - - $url = $base . 'node/123?foo'; - $result = url('node/123', array('query' => array('foo' => NULL), 'absolute' => $absolute)); - $this->assertEqual($url, $result, "$url == $result"); - - $url = $base . 'node/123?foo=bar&bar=baz'; - $result = url('node/123', array('query' => array('foo' => 'bar', 'bar' => 'baz'), 'absolute' => $absolute)); - $this->assertEqual($url, $result, "$url == $result"); - - $url = $base . 'node/123?foo#bar'; - $result = url('node/123', array('query' => array('foo' => NULL), 'fragment' => 'bar', 'absolute' => $absolute)); - $this->assertEqual($url, $result, "$url == $result"); - - $url = $base; - $result = url('', array('absolute' => $absolute)); - $this->assertEqual($url, $result, "$url == $result"); - } - } - $script_path = $script_path_original; - } - - /** * Tests external URL handling. */ function testExternalUrls() { diff --git a/core/modules/system/lib/Drupal/system/Tests/PathProcessor/PathProcessorTest.php b/core/modules/system/lib/Drupal/system/Tests/PathProcessor/PathProcessorTest.php index 0a35e9a..96b7ef6 100644 --- a/core/modules/system/lib/Drupal/system/Tests/PathProcessor/PathProcessorTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/PathProcessor/PathProcessorTest.php @@ -48,14 +48,11 @@ function testProcessInbound() { // Create dependecies needed by various path processors. $whitelist = new AliasWhitelist('path_alias_whitelist', 'cache', $this->container->get('keyvalue'), $connection); - $alias_manager = new AliasManager($connection, $whitelist, $this->container->get('language_manager')); - $module_handler = $this->container->get('module_handler'); + $language_manager = $this->container->get('language_manager'); + $alias_manager = new AliasManager($connection, $whitelist, $language_manager); - // Create the processors. - $alias_processor = new PathProcessorAlias($alias_manager); - $decode_processor = new PathProcessorDecode(); - $front_processor = new PathProcessorFront($this->container->get('config.factory')); - $language_processor = new PathProcessorLanguage($module_handler); + $module_handler = $this->container->get('module_handler'); + $config = $this->container->get('config.factory'); // Add a url alias for testing the alias-based processor. $path_crud = new Path($connection, $alias_manager); @@ -69,6 +66,12 @@ function testProcessInbound() { $language->name = 'French'; language_save($language); + // Create the processors. + $alias_processor = new PathProcessorAlias($alias_manager); + $decode_processor = new PathProcessorDecode(); + $front_processor = new PathProcessorFront($config); + $language_processor = new PathProcessorLanguage($config, $language_manager); + // First, test the processor manager with the processors in the incorrect // order. The alias processor will run before the language processor, meaning // aliases will not be found. diff --git a/core/modules/system/lib/Drupal/system/Tests/Routing/UrlGeneratorTest.php b/core/modules/system/lib/Drupal/system/Tests/Routing/UrlGeneratorTest.php deleted file mode 100644 index 0e9f13e..0000000 --- a/core/modules/system/lib/Drupal/system/Tests/Routing/UrlGeneratorTest.php +++ /dev/null @@ -1,76 +0,0 @@ - 'UrlGenerator', - 'description' => 'Confirm that the UrlGenerator is functioning properly.', - 'group' => 'Routing', - ); - } - - function setUp() { - parent::setUp(); - - $routes = new RouteCollection(); - $routes->add('test_1', new Route('/test/one')); - $routes->add('test_2', new Route('/test/two/{narf}')); - $provider = new MockRouteProvider($routes); - - $this->aliasManager = new MockAliasManager(); - $this->aliasManager->addAlias('test/one', 'hello/world'); - - $context = new RequestContext(); - $context->fromRequest(Request::create('/some/path')); - - $generator = new UrlGenerator($provider, $this->aliasManager); - $generator->setContext($context); - - $this->generator = $generator; - } - - /** - * Confirms that generated routes will have aliased paths. - */ - public function testAliasGeneration() { - $url = $this->generator->generate('test_1'); - - $this->assertEqual($url, '/hello/world', 'Correct URL generated including alias.'); - } - - /** - * Confirms that generated routes will have aliased paths. - */ - public function testAliasGenerationWithParameters() { - $this->aliasManager->addAlias('test/two/5', 'goodbye/cruel/world'); - - $url = $this->generator->generate('test_2', array('narf' => '5')); - - $this->assertEqual($url, '/goodbye/cruel/world', 'Correct URL generated including alias and parameters.'); - } - -} diff --git a/core/modules/system/lib/Drupal/system/Tests/Upgrade/LanguageUpgradePathTest.php b/core/modules/system/lib/Drupal/system/Tests/Upgrade/LanguageUpgradePathTest.php index 6b669a5..82d2fdb 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Upgrade/LanguageUpgradePathTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/Upgrade/LanguageUpgradePathTest.php @@ -118,6 +118,11 @@ public function testLanguageUpgrade() { $this->assertTrue(isset($current_weights['language-selected']), 'Language-selected is present.'); $this->assertFalse(isset($current_weights['language-default']), 'Language-default is not present.'); + // @todo We only need language.inc here because LANGUAGE_NEGOTIATION_SELECTED + // is defined there. Remove this line once that has been converted to a class + // constant. + require_once DRUPAL_ROOT . '/core/includes/language.inc'; + // Check that negotiation callback was added to language_negotiation_language_interface. $language_negotiation_language_interface = update_variable_get('language_negotiation_language_interface', NULL); $this->assertTrue(isset($language_negotiation_language_interface[LANGUAGE_NEGOTIATION_SELECTED]['callbacks']['negotiation']), 'Negotiation callback was added to language_negotiation_language_interface.'); diff --git a/core/modules/system/tests/https.php b/core/modules/system/tests/https.php index cc2bd45..e509c15 100644 --- a/core/modules/system/tests/https.php +++ b/core/modules/system/tests/https.php @@ -3,6 +3,9 @@ /** * @file * Fake an HTTPS request, for use during testing. + * + * @todo Fix this to use a new request rather than modifying server variables, + * see http.php. */ // Set a global variable to indicate a mock HTTPS request. diff --git a/core/modules/system/tests/modules/url_alter_test/lib/Drupal/url_alter_test/PathProcessorTest.php b/core/modules/system/tests/modules/url_alter_test/lib/Drupal/url_alter_test/PathProcessorTest.php new file mode 100644 index 0000000..e649f6d --- /dev/null +++ b/core/modules/system/tests/modules/url_alter_test/lib/Drupal/url_alter_test/PathProcessorTest.php @@ -0,0 +1,61 @@ + ''); + $path = 'user/' . $account->uid . $matches[2]; + } + } + + // Rewrite community/ to forum/. + if ($path == 'community' || strpos($path, 'community/') === 0) { + $path = 'forum' . substr($path, 9); + } + + if ($path == 'url-alter-test/bar') { + $path = 'url-alter-test/foo'; + } + return $path; + } + + /** + * Implements Drupal\Core\PathProcessor\OutboundPathProcessorInterface::processOutbound(). + */ + public function processOutbound($path, &$options = array(), Request $request = NULL) { + // Rewrite user/uid to user/username. + if (preg_match('!^user/([0-9]+)(/.*)?!', $path, $matches)) { + if ($account = user_load($matches[1])) { + $matches += array(2 => ''); + $path = 'user/' . $account->name . $matches[2]; + } + } + + // Rewrite forum/ to community/. + if ($path == 'forum' || strpos($path, 'forum/') === 0) { + $path = 'community' . substr($path, 5); + } + return $path; + } + +} diff --git a/core/modules/system/tests/modules/url_alter_test/lib/Drupal/url_alter_test/UrlAlterTestBundle.php b/core/modules/system/tests/modules/url_alter_test/lib/Drupal/url_alter_test/UrlAlterTestBundle.php index cd028e8..d4a691d 100644 --- a/core/modules/system/tests/modules/url_alter_test/lib/Drupal/url_alter_test/UrlAlterTestBundle.php +++ b/core/modules/system/tests/modules/url_alter_test/lib/Drupal/url_alter_test/UrlAlterTestBundle.php @@ -21,7 +21,8 @@ class UrlAlterTestBundle extends Bundle { public function build(ContainerBuilder $container) { - $container->register('url_alter_test.path_subscriber', 'Drupal\url_alter_test\PathSubscriber') - ->addTag('event_subscriber'); + $container->register('url_alter_test.path_processor', 'Drupal\url_alter_test\PathProcessorTest') + ->addTag('path_processor_inbound', array('priority' => 50)) + ->addTag('path_processor_outbound', array('priority' => 200)); } } diff --git a/core/modules/system/tests/modules/url_alter_test/url_alter_test.module b/core/modules/system/tests/modules/url_alter_test/url_alter_test.module index 8bacb9b..a7567a3 100644 --- a/core/modules/system/tests/modules/url_alter_test/url_alter_test.module +++ b/core/modules/system/tests/modules/url_alter_test/url_alter_test.module @@ -25,21 +25,3 @@ function url_alter_test_foo() { print 'current_path=' . current_path() . ' request_path=' . request_path(); exit; } - -/** - * Implements hook_url_outbound_alter(). - */ -function url_alter_test_url_outbound_alter(&$path, &$options, $original_path) { - // Rewrite user/uid to user/username. - if (preg_match('!^user/([0-9]+)(/.*)?!', $path, $matches)) { - if ($account = user_load($matches[1])) { - $matches += array(2 => ''); - $path = 'user/' . $account->name . $matches[2]; - } - } - - // Rewrite forum/ to community/. - if ($path == 'forum' || strpos($path, 'forum/') === 0) { - $path = 'community' . substr($path, 5); - } -} diff --git a/core/modules/translation/lib/Drupal/translation/Tests/TranslationTest.php b/core/modules/translation/lib/Drupal/translation/Tests/TranslationTest.php index df2c386..e9f6fe2 100644 --- a/core/modules/translation/lib/Drupal/translation/Tests/TranslationTest.php +++ b/core/modules/translation/lib/Drupal/translation/Tests/TranslationTest.php @@ -280,8 +280,7 @@ function testTranslateOwnContentRole() { */ function resetCaches() { drupal_static_reset('language_list'); - drupal_static_reset('language_url_outbound_alter'); - drupal_static_reset('language_url_rewrite_url'); + $this->rebuildContainer(); } /** diff --git a/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationTestBase.php b/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationTestBase.php index 13e1f59..2f3e0fa 100644 --- a/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationTestBase.php +++ b/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationTestBase.php @@ -82,6 +82,10 @@ function setUp() { $this->setupTestFields(); $this->controller = translation_entity_controller($this->entityType); + + // Rebuild the container so that the new languages are picked up by services + // that hold a list of languages. + $this->rebuildContainer(); } /** diff --git a/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationWorkflowsTest.php b/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationWorkflowsTest.php index 9957552..c0044c0 100644 --- a/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationWorkflowsTest.php +++ b/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationWorkflowsTest.php @@ -67,6 +67,7 @@ protected function setupEntity() { $this->drupalLogin($this->translator); $add_translation_path = $this->controller->getBasePath($this->entity) . "/translations/add/$default_langcode/{$this->langcodes[2]}"; $this->drupalPost($add_translation_path, array(), t('Save')); + $this->rebuildContainer(); } /** diff --git a/core/scripts/run-tests.sh b/core/scripts/run-tests.sh index a736492..c732d88 100755 --- a/core/scripts/run-tests.sh +++ b/core/scripts/run-tests.sh @@ -283,8 +283,10 @@ function simpletest_script_init($server_software) { if (!empty($args['url'])) { $parsed_url = parse_url($args['url']); $host = $parsed_url['host'] . (isset($parsed_url['port']) ? ':' . $parsed_url['port'] : ''); - $path = isset($parsed_url['path']) ? $parsed_url['path'] : ''; - + $path = isset($parsed_url['path']) ? rtrim($parsed_url['path']) : ''; + if ($path == '/') { + $path = ''; + } // If the passed URL schema is 'https' then setup the $_SERVER variables // properly so that testing will run under HTTPS. if ($parsed_url['scheme'] == 'https') { diff --git a/core/tests/Drupal/Tests/Core/Routing/UrlGeneratorTest.php b/core/tests/Drupal/Tests/Core/Routing/UrlGeneratorTest.php new file mode 100644 index 0000000..82a1acc --- /dev/null +++ b/core/tests/Drupal/Tests/Core/Routing/UrlGeneratorTest.php @@ -0,0 +1,178 @@ + 'UrlGenerator', + 'description' => 'Confirm that the UrlGenerator is functioning properly.', + 'group' => 'Routing', + ); + } + + function setUp() { + parent::setUp(); + + $routes = new RouteCollection(); + $first_route = new Route('/test/one'); + $second_route = new Route('/test/two/{narf}'); + $routes->add('test_1', $first_route); + $routes->add('test_2', $second_route); + + // Create a route provider stub. + $provider = $this->getMockBuilder('Drupal\Core\Routing\RouteProvider') + ->disableOriginalConstructor() + ->getMock(); + $route_name_return_map = array( + array('test_1', array(), $first_route), + array('test_2', array('narf' => '5'), $second_route), + ); + $provider->expects($this->any()) + ->method('getRouteByName') + ->will($this->returnValueMap($route_name_return_map)); + $routes_names_return_map = array( + array(array('test_1'), array(), array($first_route)), + array(array('test_2'), array('narf' => '5'), array($second_route)), + ); + $provider->expects($this->any()) + ->method('getRoutesByNames') + ->will($this->returnValueMap($routes_names_return_map)); + + // Create an alias manager stub. + $alias_manager = $this->getMockBuilder('Drupal\Core\Path\AliasManager') + ->disableOriginalConstructor() + ->getMock(); + $alias_map = array( + array('test/one', NULL, 'hello/world'), + array('test/two/5', NULL, 'goodbye/cruel/world'), + array('node/123', NULL, 'node/123'), + ); + $alias_manager->expects($this->any()) + ->method('getPathAlias') + ->will($this->returnValueMap($alias_map)); + + $this->aliasManager = $alias_manager; + + $context = new RequestContext(); + $context->fromRequest(Request::create('/some/path')); + + $processor = new PathProcessorAlias($this->aliasManager); + $processor_manager = new PathProcessorManager(); + $processor_manager->addOutbound($processor, 1000); + + // Create a mock config factory for the system.filter config object required + // by the generator. + $config_object = $this->getMockBuilder('Drupal\Core\Config\Config') + ->disableOriginalConstructor() + ->getMock(); + $map = array( + array('protocols', array('http', 'https')) + ); + $config_object->expects($this->any()) + ->method('get') + ->will($this->returnValueMap($map)); + + $config_factory = $this->getMockBuilder('Drupal\Core\Config\ConfigFactory') + ->disableOriginalConstructor() + ->getMock(); + $map = array( + array('system.filter', $config_object), + ); + $config_factory->expects($this->any()) + ->method('get') + ->will($this->returnValueMap($map)); + + $generator = new UrlGenerator($provider, $processor_manager, NULL, $config_factory); + $generator->setContext($context); + + $this->generator = $generator; + } + + /** + * Confirms that generated routes will have aliased paths. + */ + public function testAliasGeneration() { + $url = $this->generator->generate('test_1'); + $this->assertEquals('/hello/world', $url); + } + + /** + * Confirms that generated routes will have aliased paths. + */ + public function testAliasGenerationWithParameters() { + + //$this->aliasManager->addAlias('test/two/5', 'goodbye/cruel/world'); + $url = $this->generator->generate('test_2', array('narf' => '5')); + $this->assertEquals($url, '/goodbye/cruel/world', 'Correct URL generated including alias and parameters.'); + } + + public function testPathBasedURLGeneration() { + $base_path = '/subdir'; + $base_url = 'http://www.example.com' . $base_path; + $this->generator->setBasePath($base_path . '/'); + $this->generator->setBaseUrl($base_url . '/'); + foreach (array('', 'index.php/') as $script_path) { + $this->generator->setScriptPath($script_path); + foreach (array(FALSE, TRUE) as $absolute) { + // Get the expected start of the path string. + $base = ($absolute ? $base_url . '/' : $base_path . '/') . $script_path; + $absolute_string = $absolute ? 'absolute' : NULL; + $url = $base . 'node/123'; + $result = $this->generator->generateFromPath('node/123', array('absolute' => $absolute)); + $this->assertEquals($url, $result, "$url == $result"); + + $url = $base . 'node/123#foo'; + $result = $this->generator->generateFromPath('node/123', array('fragment' => 'foo', 'absolute' => $absolute)); + $this->assertEquals($url, $result, "$url == $result"); + + $url = $base . 'node/123?foo'; + $result = $this->generator->generateFromPath('node/123', array('query' => array('foo' => NULL), 'absolute' => $absolute)); + $this->assertEquals($url, $result, "$url == $result"); + + $url = $base . 'node/123?foo=bar&bar=baz'; + $result = $this->generator->generateFromPath('node/123', array('query' => array('foo' => 'bar', 'bar' => 'baz'), 'absolute' => $absolute)); + $this->assertEquals($url, $result, "$url == $result"); + + $url = $base . 'node/123?foo#bar'; + $result = $this->generator->generateFromPath('node/123', array('query' => array('foo' => NULL), 'fragment' => 'bar', 'absolute' => $absolute)); + $this->assertEquals($url, $result, "$url == $result"); + + $url = $base; + $result = $this->generator->generateFromPath('', array('absolute' => $absolute)); + $this->assertEquals($url, $result, "$url == $result"); + } + } + } + +}