BaseUrl.php 15.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\helpers;

use Yii;
Qiang Xue committed
11
use yii\base\InvalidParamException;
12 13 14 15 16 17 18 19 20 21 22

/**
 * BaseUrl provides concrete implementation for [[Url]].
 *
 * Do not use BaseUrl. Use [[Url]] instead.
 *
 * @author Alexander Makarov <sam@rmcreative.ru>
 * @since 2.0
 */
class BaseUrl
{
23
    /**
24
     * Creates a URL for the given route.
25
     *
26
     * This method will use [[\yii\web\UrlManager]] to create a URL.
27
     *
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
     * 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:
48 49
     *
     * - If the route is an empty string, the current [[\yii\web\Controller::route|route]] will be used;
50
     * - If the route contains no slashes at all (e.g. `index`), it is considered to be an action ID
51
     *   of the current controller and will be prepended with [[\yii\web\Controller::uniqueId]];
52 53 54
     * - 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]].
     *
Qiang Xue committed
55 56 57
     * Starting from version 2.0.2, a route can also be specified as an alias. In this case, the alias
     * will be converted into the actual route first before conducting the above transformation steps.
     *
58 59 60
     * Below are some examples of using this method:
     *
     * ```php
Qiang Xue committed
61
     * // /index.php?r=site/index
62 63
     * echo Url::toRoute('site/index');
     *
Qiang Xue committed
64
     * // /index.php?r=site/index&src=ref1#name
65
     * echo Url::toRoute(['site/index', 'src' => 'ref1', '#' => 'name']);
66
     *
67 68 69 70 71
     * // 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');
Qiang Xue committed
72 73 74
     *
     * // /index.php?r=post/index     assume the alias "@posts" is defined as "post/index"
     * echo Url::toRoute('@posts');
75
     * ```
76
     *
77 78 79
     * @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:
80
     *
81
     * - `false` (default): generating a relative URL.
82
     * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]].
83
     * - string: generating an absolute URL with the specified scheme (either `http` or `https`).
84
     *
85 86
     * @return string the generated URL
     * @throws InvalidParamException a relative route is given while there is no active controller
87 88 89
     */
    public static function toRoute($route, $scheme = false)
    {
Alexander Mohorev committed
90
        $route = (array) $route;
91 92
        $route[0] = static::normalizeRoute($route[0]);

93
        if ($scheme) {
94
            return Yii::$app->getUrlManager()->createAbsoluteUrl($route, is_string($scheme) ? $scheme : null);
95
        } else {
96
            return Yii::$app->getUrlManager()->createUrl($route);
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
        }
    }

    /**
     * Normalizes route and makes it suitable for UrlManager. Absolute routes are staying as is
     * while relative routes are converted to absolute ones.
     *
     * A relative route is a route without a leading slash, such as "view", "post/view".
     *
     * - 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
     *   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.
     *
112 113 114
     * Starting from version 2.0.2, a route can also be specified as an alias. In this case, the alias
     * will be converted into the actual route first before conducting the above transformation steps.
     *
115
     * @param string $route the route. This can be either an absolute route or a relative route.
116
     * @return string normalized route suitable for UrlManager
117
     * @throws InvalidParamException a relative route is given while there is no active controller
118
     */
119
    protected static function normalizeRoute($route)
120
    {
121
        $route = Yii::getAlias((string) $route);
122 123 124 125 126 127 128 129 130 131
        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.");
        }

132 133
        if (strpos($route, '/') === false) {
            // empty or an action ID
134 135
            return $route === '' ? Yii::$app->controller->getRoute() : Yii::$app->controller->getUniqueId() . '/' . $route;
        } else {
136
            // relative to module
137
            return ltrim(Yii::$app->controller->module->getUniqueId() . '/' . $route, '/');
138 139 140 141
        }
    }

    /**
142
     * Creates a URL based on the given parameters.
143
     *
144
     * This method is very similar to [[toRoute()]]. The only difference is that this method
145
     * requires a route to be specified as an array only. If a string is given, it will be treated as a URL.
146
     * In particular, if `$url` is
147
     *
148 149 150
     * - 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.
151 152
     * - a string with a leading `@`: it is treated as an alias, and the corresponding aliased string
     *   will be returned.
153
     * - an empty string: the currently requested URL will be returned;
154
     * - a normal string: it will be returned as is.
155
     *
156 157 158
     * When `$scheme` is specified (either a string or true), an absolute URL with host info (obtained from
     * [[\yii\web\UrlManager::hostInfo]]) will be returned. If `$url` is already an absolute URL, its scheme
     * will be replaced with the specified one.
159 160 161 162
     *
     * Below are some examples of using this method:
     *
     * ```php
Qiang Xue committed
163
     * // /index.php?r=site/index
164 165
     * echo Url::to(['site/index']);
     *
Qiang Xue committed
166
     * // /index.php?r=site/index&src=ref1#name
167
     * echo Url::to(['site/index', 'src' => 'ref1', '#' => 'name']);
168
     *
Qiang Xue committed
169 170 171
     * // /index.php?r=post/index     assume the alias "@posts" is defined as "/post/index"
     * echo Url::to(['@posts']);
     *
172 173
     * // the currently requested URL
     * echo Url::to();
174
     *
175
     * // /images/logo.gif
176 177 178
     * echo Url::to('@web/images/logo.gif');
     *
     * // images/logo.gif
179
     * echo Url::to('images/logo.gif');
180
     *
181 182
     * // http://www.example.com/images/logo.gif
     * echo Url::to('@web/images/logo.gif', true);
183
     *
184 185
     * // https://www.example.com/images/logo.gif
     * echo Url::to('@web/images/logo.gif', 'https');
186 187 188 189 190 191 192
     * ```
     *
     *
     * @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.
193
     * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]].
194 195 196 197
     * - 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
198 199 200 201 202
     */
    public static function to($url = '', $scheme = false)
    {
        if (is_array($url)) {
            return static::toRoute($url, $scheme);
203 204
        }

205
        $url = Yii::getAlias($url);
206 207 208 209
        if ($url === '') {
            $url = Yii::$app->getRequest()->getUrl();
        }

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
        if (!$scheme) {
            return $url;
        }

        if (strncmp($url, '//', 2) === 0) {
            // e.g. //hostname/path/to/resource
            return is_string($scheme) ? "$scheme:$url" : $url;
        }

        if (($pos = strpos($url, ':')) == false || !ctype_alpha(substr($url, 0, $pos))) {
            // turn relative URL into absolute
            $url = Yii::$app->getUrlManager()->getHostInfo() . '/' . ltrim($url, '/');
        }

        if (is_string($scheme) && ($pos = strpos($url, ':')) !== false) {
            // replace the scheme with the specified one
            $url = $scheme . substr($url, $pos);
227 228 229 230 231 232
        }

        return $url;
    }

    /**
233 234
     * Returns the base URL of the current request.
     * @param boolean|string $scheme the URI scheme to use in the returned base URL:
235
     *
236
     * - `false` (default): returning the base URL without host info.
237
     * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]].
238 239 240 241 242
     * - string: returning an absolute base URL with the specified scheme (either `http` or `https`).
     * @return string
     */
    public static function base($scheme = false)
    {
243
        $url = Yii::$app->getUrlManager()->getBaseUrl();
244
        if ($scheme) {
245
            $url = Yii::$app->getUrlManager()->getHostInfo() . $url;
246 247 248 249 250 251 252 253 254 255 256 257 258 259
            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]].
260 261 262 263
     * @see previous()
     */
    public static function remember($url = '', $name = null)
    {
264
        $url = static::to($url);
265 266 267 268 269 270 271 272 273 274 275

        if ($name === null) {
            Yii::$app->getUser()->setReturnUrl($url);
        } else {
            Yii::$app->getSession()->set($name, $url);
        }
    }

    /**
     * Returns the URL previously [[remember()|remembered]].
     *
276
     * @param string $name the named associated with the URL that was remembered previously.
277 278
     * 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.
279 280 281 282 283 284 285 286 287 288 289 290 291
     * @see remember()
     */
    public static function previous($name = null)
    {
        if ($name === null) {
            return Yii::$app->getUser()->getReturnUrl();
        } else {
            return Yii::$app->getSession()->get($name);
        }
    }

    /**
     * Returns the canonical URL of the currently requested page.
292 293
     * 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
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
     * about canonical URL:
     *
     * ```php
     * $this->registerLinkTag(['rel' => 'canonical', 'href' => Url::canonical()]);
     * ```
     *
     * @return string the canonical URL of the currently requested page
     */
    public static function canonical()
    {
        $params = Yii::$app->controller->actionParams;
        $params[0] = Yii::$app->controller->getRoute();

        return Yii::$app->getUrlManager()->createAbsoluteUrl($params);
    }

    /**
     * Returns the home URL.
     *
313
     * @param boolean|string $scheme the URI scheme to use for the returned URL:
314
     *
315
     * - `false` (default): returning a relative URL.
316
     * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]].
317
     * - string: returning an absolute URL with the specified scheme (either `http` or `https`).
318 319 320 321 322
     *
     * @return string home URL
     */
    public static function home($scheme = false)
    {
323 324
        $url = Yii::$app->getHomeUrl();

325
        if ($scheme) {
326
            $url = Yii::$app->getUrlManager()->getHostInfo() . $url;
327
            if (is_string($scheme) && ($pos = strpos($url, '://')) !== false) {
328 329 330 331 332 333
                $url = $scheme . substr($url, $pos);
            }
        }

        return $url;
    }
Qiang Xue committed
334 335 336 337 338 339 340 341 342 343 344

    /**
     * Returns a value indicating whether a URL is relative.
     * A relative URL does not have host info part.
     * @param string $url the URL to be checked
     * @return boolean whether the URL is relative
     */
    public static function isRelative($url)
    {
        return strncmp($url, '//', 2) && strpos($url, '://') === false;
    }
345 346

    /**
347
     * Creates a URL by using the current route and the GET parameters.
348
     *
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
     * You may modify or remove some of the GET parameters, or add additional query parameters through
     * the `$params` parameter. In particular, if you specify a parameter to be null, then this parameter
     * will be removed from the existing GET parameters; all other parameters specified in `$params` will
     * be merged with the existing GET parameters. For example,
     *
     * ```php
     * // assume $_GET = ['id' => 123, 'src' => 'google'], current route is "post/view"
     *
     * // /index.php?r=post/view&id=123&src=google
     * echo Url::current();
     *
     * // /index.php?r=post/view&id=123
     * echo Url::current(['src' => null]);
     *
     * // /index.php?r=post/view&id=100&src=google
     * echo Url::current(['id' => 100]);
     * ```
     *
     * @param array $params an associative array of parameters that will be merged with the current GET parameters.
     * If a parameter value is null, the corresponding GET parameter will be removed.
369 370 371 372 373 374 375
     * @param boolean|string $scheme the URI scheme to use in the generated URL:
     *
     * - `false` (default): generating a relative URL.
     * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]].
     * - string: generating an absolute URL with the specified scheme (either `http` or `https`).
     *
     * @return string the generated URL
Qiang Xue committed
376
     * @since 2.0.3
377 378 379
     */
    public static function current(array $params = [], $scheme = false)
    {
380
        $currentParams = Yii::$app->getRequest()->getQueryParams();
Qiang Xue committed
381
        $currentParams[0] = '/' . Yii::$app->controller->getRoute();
382
        $route = ArrayHelper::merge($currentParams, $params);
383 384
        return static::toRoute($route, $scheme);
    }
385
}