BaseUrl.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\helpers;
  8. use Yii;
  9. use yii\base\InvalidParamException;
  10. /**
  11. * BaseUrl provides concrete implementation for [[Url]].
  12. *
  13. * Do not use BaseUrl. Use [[Url]] instead.
  14. *
  15. * @author Alexander Makarov <sam@rmcreative.ru>
  16. * @since 2.0
  17. */
  18. class BaseUrl
  19. {
  20. /**
  21. * @var \yii\web\UrlManager URL manager to use for creating URLs
  22. * @since 2.0.8
  23. */
  24. public static $urlManager;
  25. /**
  26. * Creates a URL for the given route.
  27. *
  28. * This method will use [[\yii\web\UrlManager]] to create a URL.
  29. *
  30. * You may specify the route as a string, e.g., `site/index`. You may also use an array
  31. * if you want to specify additional query parameters for the URL being created. The
  32. * array format must be:
  33. *
  34. * ```php
  35. * // generates: /index.php?r=site/index&param1=value1&param2=value2
  36. * ['site/index', 'param1' => 'value1', 'param2' => 'value2']
  37. * ```
  38. *
  39. * If you want to create a URL with an anchor, you can use the array format with a `#` parameter.
  40. * For example,
  41. *
  42. * ```php
  43. * // generates: /index.php?r=site/index&param1=value1#name
  44. * ['site/index', 'param1' => 'value1', '#' => 'name']
  45. * ```
  46. *
  47. * A route may be either absolute or relative. An absolute route has a leading slash (e.g. `/site/index`),
  48. * while a relative route has none (e.g. `site/index` or `index`). A relative route will be converted
  49. * into an absolute one by the following rules:
  50. *
  51. * - If the route is an empty string, the current [[\yii\web\Controller::route|route]] will be used;
  52. * - If the route contains no slashes at all (e.g. `index`), it is considered to be an action ID
  53. * of the current controller and will be prepended with [[\yii\web\Controller::uniqueId]];
  54. * - If the route has no leading slash (e.g. `site/index`), it is considered to be a route relative
  55. * to the current module and will be prepended with the module's [[\yii\base\Module::uniqueId|uniqueId]].
  56. *
  57. * Starting from version 2.0.2, a route can also be specified as an alias. In this case, the alias
  58. * will be converted into the actual route first before conducting the above transformation steps.
  59. *
  60. * Below are some examples of using this method:
  61. *
  62. * ```php
  63. * // /index.php?r=site%2Findex
  64. * echo Url::toRoute('site/index');
  65. *
  66. * // /index.php?r=site%2Findex&src=ref1#name
  67. * echo Url::toRoute(['site/index', 'src' => 'ref1', '#' => 'name']);
  68. *
  69. * // http://www.example.com/index.php?r=site%2Findex
  70. * echo Url::toRoute('site/index', true);
  71. *
  72. * // https://www.example.com/index.php?r=site%2Findex
  73. * echo Url::toRoute('site/index', 'https');
  74. *
  75. * // /index.php?r=post%2Findex assume the alias "@posts" is defined as "post/index"
  76. * echo Url::toRoute('@posts');
  77. * ```
  78. *
  79. * @param string|array $route use a string to represent a route (e.g. `index`, `site/index`),
  80. * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
  81. * @param bool|string $scheme the URI scheme to use in the generated URL:
  82. *
  83. * - `false` (default): generating a relative URL.
  84. * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::$hostInfo]].
  85. * - string: generating an absolute URL with the specified scheme (either `http`, `https` or empty string
  86. * for protocol-relative URL).
  87. *
  88. * @return string the generated URL
  89. * @throws InvalidParamException a relative route is given while there is no active controller
  90. */
  91. public static function toRoute($route, $scheme = false)
  92. {
  93. $route = (array) $route;
  94. $route[0] = static::normalizeRoute($route[0]);
  95. if ($scheme !== false) {
  96. return static::getUrlManager()->createAbsoluteUrl($route, is_string($scheme) ? $scheme : null);
  97. } else {
  98. return static::getUrlManager()->createUrl($route);
  99. }
  100. }
  101. /**
  102. * Normalizes route and makes it suitable for UrlManager. Absolute routes are staying as is
  103. * while relative routes are converted to absolute ones.
  104. *
  105. * A relative route is a route without a leading slash, such as "view", "post/view".
  106. *
  107. * - If the route is an empty string, the current [[\yii\web\Controller::route|route]] will be used;
  108. * - If the route contains no slashes at all, it is considered to be an action ID
  109. * of the current controller and will be prepended with [[\yii\web\Controller::uniqueId]];
  110. * - If the route has no leading slash, it is considered to be a route relative
  111. * to the current module and will be prepended with the module's uniqueId.
  112. *
  113. * Starting from version 2.0.2, a route can also be specified as an alias. In this case, the alias
  114. * will be converted into the actual route first before conducting the above transformation steps.
  115. *
  116. * @param string $route the route. This can be either an absolute route or a relative route.
  117. * @return string normalized route suitable for UrlManager
  118. * @throws InvalidParamException a relative route is given while there is no active controller
  119. */
  120. protected static function normalizeRoute($route)
  121. {
  122. $route = Yii::getAlias((string) $route);
  123. if (strncmp($route, '/', 1) === 0) {
  124. // absolute route
  125. return ltrim($route, '/');
  126. }
  127. // relative route
  128. if (Yii::$app->controller === null) {
  129. throw new InvalidParamException("Unable to resolve the relative route: $route. No active controller is available.");
  130. }
  131. if (strpos($route, '/') === false) {
  132. // empty or an action ID
  133. return $route === '' ? Yii::$app->controller->getRoute() : Yii::$app->controller->getUniqueId() . '/' . $route;
  134. } else {
  135. // relative to module
  136. return ltrim(Yii::$app->controller->module->getUniqueId() . '/' . $route, '/');
  137. }
  138. }
  139. /**
  140. * Creates a URL based on the given parameters.
  141. *
  142. * This method is very similar to [[toRoute()]]. The only difference is that this method
  143. * requires a route to be specified as an array only. If a string is given, it will be treated as a URL.
  144. * In particular, if `$url` is
  145. *
  146. * - an array: [[toRoute()]] will be called to generate the URL. For example:
  147. * `['site/index']`, `['post/index', 'page' => 2]`. Please refer to [[toRoute()]] for more details
  148. * on how to specify a route.
  149. * - a string with a leading `@`: it is treated as an alias, and the corresponding aliased string
  150. * will be returned.
  151. * - an empty string: the currently requested URL will be returned;
  152. * - a normal string: it will be returned as is.
  153. *
  154. * When `$scheme` is specified (either a string or `true`), an absolute URL with host info (obtained from
  155. * [[\yii\web\UrlManager::$hostInfo]]) will be returned. If `$url` is already an absolute URL, its scheme
  156. * will be replaced with the specified one.
  157. *
  158. * Below are some examples of using this method:
  159. *
  160. * ```php
  161. * // /index.php?r=site%2Findex
  162. * echo Url::to(['site/index']);
  163. *
  164. * // /index.php?r=site%2Findex&src=ref1#name
  165. * echo Url::to(['site/index', 'src' => 'ref1', '#' => 'name']);
  166. *
  167. * // /index.php?r=post%2Findex assume the alias "@posts" is defined as "/post/index"
  168. * echo Url::to(['@posts']);
  169. *
  170. * // the currently requested URL
  171. * echo Url::to();
  172. *
  173. * // /images/logo.gif
  174. * echo Url::to('@web/images/logo.gif');
  175. *
  176. * // images/logo.gif
  177. * echo Url::to('images/logo.gif');
  178. *
  179. * // http://www.example.com/images/logo.gif
  180. * echo Url::to('@web/images/logo.gif', true);
  181. *
  182. * // https://www.example.com/images/logo.gif
  183. * echo Url::to('@web/images/logo.gif', 'https');
  184. *
  185. * // //www.example.com/images/logo.gif
  186. * echo Url::to('@web/images/logo.gif', '');
  187. * ```
  188. *
  189. *
  190. * @param array|string $url the parameter to be used to generate a valid URL
  191. * @param bool|string $scheme the URI scheme to use in the generated URL:
  192. *
  193. * - `false` (default): generating a relative URL.
  194. * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::$hostInfo]].
  195. * - string: generating an absolute URL with the specified scheme (either `http`, `https` or empty string
  196. * for protocol-relative URL).
  197. *
  198. * @return string the generated URL
  199. * @throws InvalidParamException a relative route is given while there is no active controller
  200. */
  201. public static function to($url = '', $scheme = false)
  202. {
  203. if (is_array($url)) {
  204. return static::toRoute($url, $scheme);
  205. }
  206. $url = Yii::getAlias($url);
  207. if ($url === '') {
  208. $url = Yii::$app->getRequest()->getUrl();
  209. }
  210. if ($scheme === false) {
  211. return $url;
  212. }
  213. if (static::isRelative($url)) {
  214. // turn relative URL into absolute
  215. $url = static::getUrlManager()->getHostInfo() . '/' . ltrim($url, '/');
  216. }
  217. return static::ensureScheme($url, $scheme);
  218. }
  219. /**
  220. * Normalize URL by ensuring that it use specified scheme.
  221. *
  222. * If URL is relative or scheme is not string, normalization is skipped.
  223. *
  224. * @param string $url the URL to process
  225. * @param string $scheme the URI scheme used in URL (e.g. `http` or `https`). Use empty string to
  226. * create protocol-relative URL (e.g. `//example.com/path`)
  227. * @return string the processed URL
  228. * @since 2.0.11
  229. */
  230. public static function ensureScheme($url, $scheme)
  231. {
  232. if (static::isRelative($url) || !is_string($scheme)) {
  233. return $url;
  234. }
  235. if (substr($url, 0, 2) === '//') {
  236. // e.g. //example.com/path/to/resource
  237. return $scheme === '' ? $url : "$scheme:$url";
  238. }
  239. if (($pos = strpos($url, '://')) !== false) {
  240. if ($scheme === '') {
  241. $url = substr($url, $pos + 1);
  242. } else {
  243. $url = $scheme . substr($url, $pos);
  244. }
  245. }
  246. return $url;
  247. }
  248. /**
  249. * Returns the base URL of the current request.
  250. * @param bool|string $scheme the URI scheme to use in the returned base URL:
  251. *
  252. * - `false` (default): returning the base URL without host info.
  253. * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::$hostInfo]].
  254. * - string: returning an absolute base URL with the specified scheme (either `http`, `https` or empty string
  255. * for protocol-relative URL).
  256. * @return string
  257. */
  258. public static function base($scheme = false)
  259. {
  260. $url = static::getUrlManager()->getBaseUrl();
  261. if ($scheme !== false) {
  262. $url = static::getUrlManager()->getHostInfo() . $url;
  263. $url = static::ensureScheme($url, $scheme);
  264. }
  265. return $url;
  266. }
  267. /**
  268. * Remembers the specified URL so that it can be later fetched back by [[previous()]].
  269. *
  270. * @param string|array $url the URL to remember. Please refer to [[to()]] for acceptable formats.
  271. * If this parameter is not specified, the currently requested URL will be used.
  272. * @param string $name the name associated with the URL to be remembered. This can be used
  273. * later by [[previous()]]. If not set, it will use [[\yii\web\User::returnUrlParam]].
  274. * @see previous()
  275. */
  276. public static function remember($url = '', $name = null)
  277. {
  278. $url = static::to($url);
  279. if ($name === null) {
  280. Yii::$app->getUser()->setReturnUrl($url);
  281. } else {
  282. Yii::$app->getSession()->set($name, $url);
  283. }
  284. }
  285. /**
  286. * Returns the URL previously [[remember()|remembered]].
  287. *
  288. * @param string $name the named associated with the URL that was remembered previously.
  289. * If not set, it will use [[\yii\web\User::returnUrlParam]].
  290. * @return string|null the URL previously remembered. Null is returned if no URL was remembered with the given name.
  291. * @see remember()
  292. */
  293. public static function previous($name = null)
  294. {
  295. if ($name === null) {
  296. return Yii::$app->getUser()->getReturnUrl();
  297. } else {
  298. return Yii::$app->getSession()->get($name);
  299. }
  300. }
  301. /**
  302. * Returns the canonical URL of the currently requested page.
  303. * The canonical URL is constructed using the current controller's [[\yii\web\Controller::route]] and
  304. * [[\yii\web\Controller::actionParams]]. You may use the following code in the layout view to add a link tag
  305. * about canonical URL:
  306. *
  307. * ```php
  308. * $this->registerLinkTag(['rel' => 'canonical', 'href' => Url::canonical()]);
  309. * ```
  310. *
  311. * @return string the canonical URL of the currently requested page
  312. */
  313. public static function canonical()
  314. {
  315. $params = Yii::$app->controller->actionParams;
  316. $params[0] = Yii::$app->controller->getRoute();
  317. return static::getUrlManager()->createAbsoluteUrl($params);
  318. }
  319. /**
  320. * Returns the home URL.
  321. *
  322. * @param bool|string $scheme the URI scheme to use for the returned URL:
  323. *
  324. * - `false` (default): returning a relative URL.
  325. * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::$hostInfo]].
  326. * - string: returning an absolute URL with the specified scheme (either `http`, `https` or empty string
  327. * for protocol-relative URL).
  328. *
  329. * @return string home URL
  330. */
  331. public static function home($scheme = false)
  332. {
  333. $url = Yii::$app->getHomeUrl();
  334. if ($scheme !== false) {
  335. $url = static::getUrlManager()->getHostInfo() . $url;
  336. $url = static::ensureScheme($url, $scheme);
  337. }
  338. return $url;
  339. }
  340. /**
  341. * Returns a value indicating whether a URL is relative.
  342. * A relative URL does not have host info part.
  343. * @param string $url the URL to be checked
  344. * @return bool whether the URL is relative
  345. */
  346. public static function isRelative($url)
  347. {
  348. return strncmp($url, '//', 2) && strpos($url, '://') === false;
  349. }
  350. /**
  351. * Creates a URL by using the current route and the GET parameters.
  352. *
  353. * You may modify or remove some of the GET parameters, or add additional query parameters through
  354. * the `$params` parameter. In particular, if you specify a parameter to be null, then this parameter
  355. * will be removed from the existing GET parameters; all other parameters specified in `$params` will
  356. * be merged with the existing GET parameters. For example,
  357. *
  358. * ```php
  359. * // assume $_GET = ['id' => 123, 'src' => 'google'], current route is "post/view"
  360. *
  361. * // /index.php?r=post%2Fview&id=123&src=google
  362. * echo Url::current();
  363. *
  364. * // /index.php?r=post%2Fview&id=123
  365. * echo Url::current(['src' => null]);
  366. *
  367. * // /index.php?r=post%2Fview&id=100&src=google
  368. * echo Url::current(['id' => 100]);
  369. * ```
  370. *
  371. * Note that if you're replacing array parameters with `[]` at the end you should specify `$params` as nested arrays.
  372. * For a `PostSearchForm` model where parameter names are `PostSearchForm[id]` and `PostSearchForm[src]` the syntax
  373. * would be the following:
  374. *
  375. * ```php
  376. * // index.php?r=post%2Findex&PostSearchForm%5Bid%5D=100&PostSearchForm%5Bsrc%5D=google
  377. * echo Url::current([
  378. * $postSearch->formName() => ['id' => 100, 'src' => 'google'],
  379. * ]);
  380. * ```
  381. *
  382. * @param array $params an associative array of parameters that will be merged with the current GET parameters.
  383. * If a parameter value is null, the corresponding GET parameter will be removed.
  384. * @param bool|string $scheme the URI scheme to use in the generated URL:
  385. *
  386. * - `false` (default): generating a relative URL.
  387. * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::$hostInfo]].
  388. * - string: generating an absolute URL with the specified scheme (either `http`, `https` or empty string
  389. * for protocol-relative URL).
  390. *
  391. * @return string the generated URL
  392. * @since 2.0.3
  393. */
  394. public static function current(array $params = [], $scheme = false)
  395. {
  396. $currentParams = Yii::$app->getRequest()->getQueryParams();
  397. $currentParams[0] = '/' . Yii::$app->controller->getRoute();
  398. $route = ArrayHelper::merge($currentParams, $params);
  399. return static::toRoute($route, $scheme);
  400. }
  401. /**
  402. * @return \yii\web\UrlManager URL manager used to create URLs
  403. * @since 2.0.8
  404. */
  405. protected static function getUrlManager()
  406. {
  407. return static::$urlManager ?: Yii::$app->getUrlManager();
  408. }
  409. }