BaseUrl.php 17 KB

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