Commit 6e8c4602 by Qiang Xue

Fixes #2724: consistent use of absolute and relative routes.

parent 300c5a54
......@@ -9,6 +9,7 @@ namespace yii\debug;
use Yii;
use yii\base\Application;
use yii\helpers\Url;
use yii\web\View;
use yii\web\ForbiddenHttpException;
......@@ -124,7 +125,7 @@ class Module extends \yii\base\Module
if (!$this->checkAccess() || Yii::$app->getRequest()->getIsAjax()) {
return;
}
$url = Yii::$app->getUrlManager()->createUrl([$this->id . '/default/toolbar',
$url = Url::toRoute(['/' . $this->id . '/default/toolbar',
'tag' => $this->logTarget->tag,
]);
echo '<div id="yii-debug-toolbar" data-url="' . $url . '" style="display:none"></div>';
......
......@@ -9,6 +9,7 @@ namespace yii\debug;
use Yii;
use yii\base\Component;
use yii\helpers\Url;
/**
* Panel is a base class for debugger panel classes. It defines how data should be collected,
......@@ -88,7 +89,7 @@ class Panel extends Component
*/
public function getUrl()
{
return Yii::$app->getUrlManager()->createUrl([$this->module->id . '/default/view',
return Url::toRoute(['/' . $this->module->id . '/default/view',
'panel' => $this->id,
'tag' => $this->tag,
]);
......
......@@ -35,8 +35,9 @@ use yii\widgets\InputWidget;
class Captcha extends InputWidget
{
/**
* @var string the route of the action that generates the CAPTCHA images.
* @var string|array the route of the action that generates the CAPTCHA images.
* The action represented by this route must be an action of [[CaptchaAction]].
* Please refer to [[\yii\helpers\Url::toRoute()]] for acceptable formats.
*/
public $captchaAction = 'site/captcha';
/**
......@@ -81,8 +82,13 @@ class Captcha extends InputWidget
} else {
$input = Html::textInput($this->name, $this->value, $this->options);
}
$url = Yii::$app->getUrlManager()->createUrl([$this->captchaAction, 'v' => uniqid()]);
$image = Html::img($url, $this->imageOptions);
$route = $this->captchaAction;
if (is_array($route)) {
$route['v'] = uniqid();
} else {
$route = [$route, 'v' => uniqid()];
}
$image = Html::img($route, $this->imageOptions);
echo strtr($this->template, [
'{input}' => $input,
'{image}' => $image,
......
......@@ -22,46 +22,74 @@ use yii\web\Controller;
class BaseUrl
{
/**
* Returns URL for a route.
* Creates a URL for the given route.
*
* @param array|string $route route as a string or route and parameters in form of
* `['route', 'param1' => 'value1', 'param2' => 'value2']`.
* This method will use [[\yii\web\UrlManager]] to create a URL.
*
* If there is a controller running, relative routes are recognized:
* You may specify the route as a string, e.g., `site/index`. You may also use an array
* if you want to specify additional query parameters for the URL being created. The
* array format must be:
*
* ```php
* // generates: /index.php?r=site/index&param1=value1&param2=value2
* ['site/index', 'param1' => 'value1', 'param2' => 'value2']
* ```
*
* If you want to create a URL with an anchor, you can use the array format with a `#` parameter.
* For example,
*
* ```php
* // generates: /index.php?r=site/index&param1=value1#name
* ['site/index', 'param1' => 'value1', '#' => 'name']
* ```
*
* A route may be either absolute or relative. An absolute route has a leading slash (e.g. `/site/index`),
* while a relative route has none (e.g. `site/index` or `index`). A relative route will be converted
* into an absolute one by the following rules:
*
* - If the route is an empty string, the current [[\yii\web\Controller::route|route]] will be used;
* - If the route contains no slashes at all, it is considered to be an action ID
* - If the route contains no slashes at all (e.g. `index`), it is considered to be an action ID
* of the current controller and will be prepended with [[\yii\web\Controller::uniqueId]];
* - If the route has no leading slash, it is considered to be a route relative
* to the current module and will be prepended with the module's uniqueId.
* - If the route has no leading slash (e.g. `site/index`), it is considered to be a route relative
* to the current module and will be prepended with the module's [[\yii\base\Module::uniqueId|uniqueId]].
*
* Below are some examples of using this method:
*
* ```php
* // /index?r=site/index
* echo Url::toRoute('site/index');
*
* // /index?r=site/index&src=ref1#name
* echo Url::toRoute(['site/index', 'src' => 'ref1', '#' => 'name']);
*
* In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used.
* // http://www.example.com/index.php?r=site/index
* echo Url::toRoute('site/index', true);
*
* // https://www.example.com/index.php?r=site/index
* echo Url::toRoute('site/index', 'https');
* ```
*
* @param boolean|string $scheme URI scheme to use:
* @param string|array $route use a string to represent a route (e.g. `index`, `site/index`),
* or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
* @param boolean|string $scheme the URI scheme to use in the generated URL:
*
* - `false`: relative URL. Default behavior.
* - `true`: absolute URL with the current scheme.
* - string: absolute URL with string value used as scheme.
* - `false` (default): generating a relative URL.
* - `true`: generating an absolute URL whose scheme is the same as the current request.
* - string: generating an absolute URL with the specified scheme (either `http` or `https`).
*
* @return string the URL for the route
* @throws InvalidParamException if the parameter is invalid.
* @return string the generated URL
* @throws InvalidParamException a relative route is given while there is no active controller
*/
public static function toRoute($route, $scheme = false)
{
$route = (array) $route;
if (Yii::$app->controller instanceof Controller) {
$route[0] = static::getNormalizedRoute($route[0]);
}
$route = (array)$route;
$route[0] = static::normalizeRoute($route[0]);
if ($scheme) {
if ($scheme === true) {
$scheme = null;
}
$url = Yii::$app->getUrlManager()->createAbsoluteUrl($route, $scheme);
return Yii::$app->getUrlManager()->createAbsoluteUrl($route, is_string($scheme) ? $scheme : null);
} else {
$url = Yii::$app->getUrlManager()->createUrl($route);
return Yii::$app->getUrlManager()->createUrl($route);
}
return $url;
}
/**
......@@ -78,69 +106,102 @@ class BaseUrl
*
* @param string $route the route. This can be either an absolute route or a relative route.
* @return string normalized route suitable for UrlManager
* @throws InvalidParamException a relative route is given while there is no active controller
*/
private static function getNormalizedRoute($route)
private static function normalizeRoute($route)
{
$route = (string) $route;
if (strncmp($route, '/', 1) === 0) {
// absolute route
return ltrim($route, '/');
}
// relative route
if (Yii::$app->controller === null) {
throw new InvalidParamException("Unable to resolve the relative route: $route. No active controller is available.");
}
if (strpos($route, '/') === false) {
// empty or an action ID
$route = $route === '' ? Yii::$app->controller->getRoute() : Yii::$app->controller->getUniqueId() . '/' . $route;
} elseif ($route[0] !== '/') {
return $route === '' ? Yii::$app->controller->getRoute() : Yii::$app->controller->getUniqueId() . '/' . $route;
} else {
// relative to module
$route = ltrim(Yii::$app->controller->module->getUniqueId() . '/' . $route, '/');
return ltrim(Yii::$app->controller->module->getUniqueId() . '/' . $route, '/');
}
return $route;
}
/**
* Creates a URL specified by the input parameter.
* Creates a URL based on the given parameters.
*
* If the input parameter is
* This method is very similar to [[toRoute()]]. The only difference is that this method
* requires a route to be specified as an array only. If a string is given, it will be treated
* as a URL which will be prefixed with the base URL if it does not start with a slash.
* In particular, if `$url` is
*
* - an array: the first array element is considered a route, while the rest of the name-value
* pairs are treated as the parameters to be used for URL creation using [[toRoute()]].
* For example: `['post/index', 'page' => 2]`, `['index']`.
* In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used.
* - an array: [[toRoute()]] will be called to generate the URL. For example:
* `['site/index']`, `['post/index', 'page' => 2]`. Please refer to [[toRoute()]] for more details
* on how to specify a route.
* - a string with a leading `@`: it is treated as an alias and the corresponding aliased string
* will be subject to the following rules.
* - an empty string: the currently requested URL will be returned;
* - a non-empty string: it will first be processed by [[Yii::getAlias()]]. If the result
* is an absolute URL, it will be returned either without any change or, if scheme was specified, with scheme
* replaced; Otherwise, the result will be prefixed with [[\yii\web\Request::baseUrl]] and returned.
* - a string without a leading slash: it will be prefixed with [[\yii\web\Request::baseUrl]].
* - a string with a leading slash: it will be returned as is.
*
* Note that in case `$scheme` is specified (either a string or true), an absolute URL with host info
* will be returned.
*
* Below are some examples of using this method:
*
* ```php
* // /index?r=site/index
* echo Url::to(['site/index']);
*
* // /index?r=site/index&src=ref1#name
* echo Url::to(['site/index', 'src' => 'ref1', '#' => 'name']);
*
* @param array|string $url the parameter to be used to generate a valid URL
* @param boolean|string $scheme URI scheme to use:
* // the currently requested URL
* echo Url::to();
*
* - `false`: relative URL. Default behavior.
* - `true`: absolute URL with the current scheme.
* - string: absolute URL with string value used as scheme.
* // /images/logo.gif
* echo Url::to('images/logo.gif');
*
* @return string the normalized URL
* @throws InvalidParamException if the parameter is invalid.
* // http://www.example.com/index.php?r=site/index
* echo Url::to(['site/index'], true);
*
* // https://www.example.com/index.php?r=site/index
* echo Url::to(['site/index'], 'https');
* ```
*
*
* @param array|string $url the parameter to be used to generate a valid URL
* @param boolean|string $scheme the URI scheme to use in the generated URL:
*
* - `false` (default): generating a relative URL.
* - `true`: generating an absolute URL whose scheme is the same as the current request.
* - string: generating an absolute URL with the specified scheme (either `http` or `https`).
*
* @return string the generated URL
* @throws InvalidParamException a relative route is given while there is no active controller
*/
public static function to($url = '', $scheme = false)
{
if (is_array($url)) {
return static::toRoute($url, $scheme);
} elseif ($url === '') {
if ($scheme) {
$url = Yii::$app->getRequest()->getAbsoluteUrl();
} else {
$url = Yii::$app->getRequest()->getUrl();
}
} else {
$url = Yii::getAlias($url);
}
$url = (string) Yii::getAlias($url);
if ($url === '') {
$url = Yii::$app->getRequest()->getUrl();
} elseif ($url[0] !== '/' && $url[0] !== '#' && strpos($url, '://') === false) {
$url = Yii::$app->getRequest()->getBaseUrl() . '/' . $url;
}
if ($scheme) {
if (strpos($url, '://') === false) {
if ($url === '' || ($url[0] !== '/' && $url[0] !== '#' && strncmp($url, './', 2))) {
$url = Yii::$app->getRequest()->getBaseUrl() . '/' . $url;
}
if ($scheme) {
$url = Yii::$app->getRequest()->getHostInfo() . $url;
}
$url = Yii::$app->getRequest()->getHostInfo() . '/' . ltrim($url, '/');
}
}
if ($scheme && $scheme !== true) {
$pos = strpos($url, '://');
if ($pos !== false) {
if (is_string($scheme) && ($pos = strpos($url, '://')) !== false) {
$url = $scheme . substr($url, $pos);
}
}
......@@ -149,17 +210,38 @@ class BaseUrl
}
/**
* Remembers the specified URL so that it can be later fetched back.
* Returns the base URL of the current request.
* @param boolean|string $scheme the URI scheme to use in the returned base URL:
*
* @param string $url URL to remember. Default is the currently requested URL.
* @param string $name Name to use to remember URL. Defaults to [[\yii\web\User::returnUrlParam]].
* - `false` (default): returning the base URL without host info.
* - `true`: returning an absolute base URL whose scheme is the same as the current request.
* - string: returning an absolute base URL with the specified scheme (either `http` or `https`).
* @return string
*/
public static function base($scheme = false)
{
$url = Yii::$app->getRequest()->getBaseUrl();
if ($scheme) {
$url = Yii::$app->getRequest()->getHostInfo() . $url;
if (is_string($scheme) && ($pos = strpos($url, '://')) !== false) {
$url = $scheme . substr($url, $pos);
}
}
return $url;
}
/**
* Remembers the specified URL so that it can be later fetched back by [[previous()]].
*
* @param string|array $url the URL to remember. Please refer to [[to()]] for acceptable formats.
* If this parameter is not specified, the currently requested URL will be used.
* @param string $name the name associated with the URL to be remembered. This can be used
* later by [[previous()]]. If not set, it will use [[\yii\web\User::returnUrlParam]].
* @see previous()
*/
public static function remember($url = '', $name = null)
{
if ($url === '') {
$url = Yii::$app->getRequest()->getUrl();
}
$url = static::to($url);
if ($name === null) {
Yii::$app->getUser()->setReturnUrl($url);
......@@ -171,8 +253,9 @@ class BaseUrl
/**
* Returns the URL previously [[remember()|remembered]].
*
* @param string $name Name used to remember URL. Defaults to [[\yii\web\User::returnUrlParam]].
* @return string URL, or null if no such URL was remembered before.
* @param string $name the named associated with the URL that was remembered previously.
* If not set, it will use [[\yii\web\User::returnUrlParam]].
* @return string the URL previously remembered. Null is returned if no URL was remembered with the given name.
* @see remember()
*/
public static function previous($name = null)
......@@ -186,7 +269,7 @@ class BaseUrl
/**
* Returns the canonical URL of the currently requested page.
* The canonical URL is constructed using current controller's [[yii\web\Controller::route]] and
* The canonical URL is constructed using the current controller's [[yii\web\Controller::route]] and
* [[yii\web\Controller::actionParams]]. You may use the following code in the layout view to add a link tag
* about canonical URL:
*
......@@ -207,24 +290,23 @@ class BaseUrl
/**
* Returns the home URL.
*
* @param boolean|string $scheme URI scheme to use:
* @param boolean|string $scheme the URI scheme to use for the returned URL:
*
* - `false`: relative URL. Default behavior.
* - `true`: absolute URL with the current scheme.
* - string: absolute URL with string value used as scheme.
* - `false` (default): returning a relative URL.
* - `true`: returning an absolute URL whose scheme is the same as the current request.
* - string: returning an absolute URL with the specified scheme (either `http` or `https`).
*
* @return string home URL
*/
public static function home($scheme = false)
{
$url = Yii::$app->getHomeUrl();
if ($scheme) {
$url = Yii::$app->getRequest()->getHostInfo() . Yii::$app->getHomeUrl();
if ($scheme !== true) {
$pos = strpos($url, '://');
$url = Yii::$app->getRequest()->getHostInfo() . $url;
if (is_string($scheme) && ($pos = strpos($url, '://')) !== false) {
$url = $scheme . substr($url, $pos);
}
} else {
$url = Yii::$app->getHomeUrl();
}
return $url;
......
......@@ -184,7 +184,7 @@ class UrlManager extends Component
/**
* Parses the user request.
* @param Request $request the request component
* @param Request $request the request component
* @return array|boolean the route and the associated parameters. The latter is always empty
* if [[enablePrettyUrl]] is false. False is returned if the current request cannot be successfully parsed.
*/
......@@ -205,7 +205,7 @@ class UrlManager extends Component
Yii::trace('No matching URL rules. Using default URL parsing logic.', __METHOD__);
$suffix = (string) $this->suffix;
$suffix = (string)$this->suffix;
if ($suffix !== '' && $pathInfo !== '') {
$n = strlen($this->suffix);
if (substr($pathInfo, -$n) === $this->suffix) {
......@@ -228,19 +228,42 @@ class UrlManager extends Component
$route = '';
}
return [(string) $route, []];
return [(string)$route, []];
}
}
/**
* Creates a URL using the given route and parameters.
* Creates a URL using the given route and query parameters.
*
* You may specify the route as a string, e.g., `site/index`. You may also use an array
* if you want to specify additional query parameters for the URL being created. The
* array format must be:
*
* ```php
* // generates: /index.php?r=site/index&param1=value1&param2=value2
* ['site/index', 'param1' => 'value1', 'param2' => 'value2']
* ```
*
* If you want to create a URL with an anchor, you can use the array format with a `#` parameter.
* For example,
*
* ```php
* // generates: /index.php?r=site/index&param1=value1#name
* ['site/index', 'param1' => 'value1', '#' => 'name']
* ```
*
* The URL created is a relative one. Use [[createAbsoluteUrl()]] to create an absolute URL.
* @param string|array $params route as a string or route and parameters in form of ['route', 'param1' => 'value1', 'param2' => 'value2']
* @return string the created URL
*
* Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
* as an absolute route.
*
* @param string|array $params use a string to represent a route (e.g. `site/index`),
* or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
* @return string the created URL
*/
public function createUrl($params)
{
$params = (array) $params;
$params = (array)$params;
$anchor = isset($params['#']) ? '#' . $params['#'] : '';
unset($params['#'], $params[$this->routeParam]);
......@@ -283,23 +306,29 @@ class UrlManager extends Component
}
/**
* Creates an absolute URL using the given route and parameters.
* Creates an absolute URL using the given route and query parameters.
*
* This method prepends the URL created by [[createUrl()]] with the [[hostInfo]].
* @param string|array $params route as a string or route and parameters in form of ['route', 'param1' => 'value1', 'param2' => 'value2']
* @param string $schema the schema to use for the url. e.g. 'http' or 'https'. If not specified
* the schema of the current request will be used.
* @return string the created URL
*
* Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
* as an absolute route.
*
* @param string|array $params use a string to represent a route (e.g. `site/index`),
* or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
* @param string $scheme the scheme to use for the url (either `http` or `https`). If not specified
* the scheme of the current request will be used.
* @return string the created URL
* @see createUrl()
*/
public function createAbsoluteUrl($params, $schema = null)
public function createAbsoluteUrl($params, $scheme = null)
{
$params = (array) $params;
$params = (array)$params;
$url = $this->createUrl($params);
if (strpos($url, '://') === false) {
$url = $this->getHostInfo() . $url;
}
if ($schema && ($pos = strpos($url, '://')) !== false) {
$url = $schema . substr($url, $pos);
if (is_string($scheme) && ($pos = strpos($url, '://')) !== false) {
$url = $scheme . substr($url, $pos);
}
return $url;
......
......@@ -75,13 +75,11 @@ class UrlTest extends TestCase
$this->assertEquals('http://example.com/base/index.php?r=stats/user/view&id=42', Url::toRoute(['user/view', 'id' => 42], true));
$this->assertEquals('https://example.com/base/index.php?r=stats/user/view&id=42', Url::toRoute(['user/view', 'id' => 42], 'https'));
// In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used.
// In case there is no controller, an exception should be thrown for relative route
$this->removeMockedAction();
$this->assertEquals('/base/index.php?r=site/view', Url::toRoute('site/view'));
$this->assertEquals('http://example.com/base/index.php?r=site/view', Url::toRoute('site/view', true));
$this->assertEquals('https://example.com/base/index.php?r=site/view', Url::toRoute('site/view', 'https'));
$this->assertEquals('/base/index.php?r=site/view&id=37', Url::toRoute(['site/view', 'id' => 37]));
$this->setExpectedException('yii\base\InvalidParamException');
Url::toRoute('site/view');
}
public function testTo()
......@@ -101,27 +99,11 @@ class UrlTest extends TestCase
$this->assertEquals('https://example.com/base/index.php?r=page/edit', Url::to(['edit'], 'https'));
$this->assertEquals('https://example.com/base/index.php?r=page/view', Url::to([''], 'https'));
//In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used.
$this->removeMockedAction();
$this->assertEquals('/base/index.php?r=edit&id=20', Url::to(['edit', 'id' => 20]));
$this->assertEquals('/base/index.php?r=edit', Url::to(['edit']));
$this->assertEquals('/base/index.php?r=', Url::to(['']));
$this->assertEquals('http://example.com/base/index.php?r=edit&id=20', Url::to(['edit', 'id' => 20], true));
$this->assertEquals('http://example.com/base/index.php?r=edit', Url::to(['edit'], true));
$this->assertEquals('http://example.com/base/index.php?r=', Url::to([''], true));
$this->assertEquals('https://example.com/base/index.php?r=edit&id=20', Url::to(['edit', 'id' => 20], 'https'));
$this->assertEquals('https://example.com/base/index.php?r=edit', Url::to(['edit'], 'https'));
$this->assertEquals('https://example.com/base/index.php?r=', Url::to([''], 'https'));
// is an empty string: the currently requested URL will be returned;
$this->mockAction('page', 'view', null, ['id' => 10]);
$this->assertEquals('/base/index.php&r=site/current&id=42', Url::to(''));
$this->assertEquals('http://example.com/base/index.php&r=site/current&id=42', Url::to('', true));
$this->assertEquals('https://example.com/base/index.php&r=site/current&id=42', Url::to('', 'https'));
$this->removeMockedAction();
// is a non-empty string: it will first be processed by [[Yii::getAlias()]]. If the result
// is an absolute URL, it will be returned either without any change or, if schema was specified, with schema
......@@ -140,17 +122,31 @@ class UrlTest extends TestCase
$this->assertEquals('http://example.com/base/test/me2', Url::to('@web2', true));
$this->assertEquals('https://example.com/base/test/me2', Url::to('@web2', 'https'));
$this->assertEquals('/base/', Url::to('@web3'));
$this->assertEquals('http://example.com/base/', Url::to('@web3', true));
$this->assertEquals('https://example.com/base/', Url::to('@web3', 'https'));
$this->assertEquals('/base/index.php&r=site/current&id=42', Url::to('@web3'));
$this->assertEquals('http://example.com/base/index.php&r=site/current&id=42', Url::to('@web3', true));
$this->assertEquals('https://example.com/base/index.php&r=site/current&id=42', Url::to('@web3', 'https'));
$this->assertEquals('/test', Url::to('@web4'));
$this->assertEquals('http://example.com/test', Url::to('@web4', true));
$this->assertEquals('https://example.com/test', Url::to('@web4', 'https'));
$this->assertEquals('#test', Url::to('@web5'));
$this->assertEquals('http://example.com#test', Url::to('@web5', true));
$this->assertEquals('https://example.com#test', Url::to('@web5', 'https'));
$this->assertEquals('http://example.com/#test', Url::to('@web5', true));
$this->assertEquals('https://example.com/#test', Url::to('@web5', 'https'));
//In case there is no controller, throw an exception
$this->removeMockedAction();
$this->setExpectedException('yii\base\InvalidParamException');
Url::to(['site/view']);
}
public function testBase()
{
$this->mockAction('page', 'view', null, ['id' => 10]);
$this->assertEquals('/base', Url::base());
$this->assertEquals('http://example.com/base', Url::base(true));
$this->assertEquals('https://example.com/base', Url::base('https'));
}
public function testHome()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment