You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

402 lines
16KB

  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 boolean|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` or `https`).
  86. *
  87. * @return string the generated URL
  88. * @throws InvalidParamException a relative route is given while there is no active controller
  89. */
  90. public static function toRoute($route, $scheme = false)
  91. {
  92. $route = (array) $route;
  93. $route[0] = static::normalizeRoute($route[0]);
  94. if ($scheme) {
  95. return static::getUrlManager()->createAbsoluteUrl($route, is_string($scheme) ? $scheme : null);
  96. } else {
  97. return static::getUrlManager()->createUrl($route);
  98. }
  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 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. 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 InvalidParamException("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. } else {
  134. // relative to module
  135. return ltrim(Yii::$app->controller->module->getUniqueId() . '/' . $route, '/');
  136. }
  137. }
  138. /**
  139. * Creates a URL based on the given parameters.
  140. *
  141. * This method is very similar to [[toRoute()]]. The only difference is that this method
  142. * requires a route to be specified as an array only. If a string is given, it will be treated as a URL.
  143. * In particular, if `$url` is
  144. *
  145. * - an array: [[toRoute()]] will be called to generate the URL. For example:
  146. * `['site/index']`, `['post/index', 'page' => 2]`. Please refer to [[toRoute()]] for more details
  147. * on how to specify a route.
  148. * - a string with a leading `@`: it is treated as an alias, and the corresponding aliased string
  149. * will be returned.
  150. * - an empty string: the currently requested URL will be returned;
  151. * - a normal string: it will be returned as is.
  152. *
  153. * When `$scheme` is specified (either a string or true), an absolute URL with host info (obtained from
  154. * [[\yii\web\UrlManager::hostInfo]]) will be returned. If `$url` is already an absolute URL, its scheme
  155. * will be replaced with the specified one.
  156. *
  157. * Below are some examples of using this method:
  158. *
  159. * ```php
  160. * // /index.php?r=site%2Findex
  161. * echo Url::to(['site/index']);
  162. *
  163. * // /index.php?r=site%2Findex&src=ref1#name
  164. * echo Url::to(['site/index', 'src' => 'ref1', '#' => 'name']);
  165. *
  166. * // /index.php?r=post%2Findex assume the alias "@posts" is defined as "/post/index"
  167. * echo Url::to(['@posts']);
  168. *
  169. * // the currently requested URL
  170. * echo Url::to();
  171. *
  172. * // /images/logo.gif
  173. * echo Url::to('@web/images/logo.gif');
  174. *
  175. * // images/logo.gif
  176. * echo Url::to('images/logo.gif');
  177. *
  178. * // http://www.example.com/images/logo.gif
  179. * echo Url::to('@web/images/logo.gif', true);
  180. *
  181. * // https://www.example.com/images/logo.gif
  182. * echo Url::to('@web/images/logo.gif', 'https');
  183. * ```
  184. *
  185. *
  186. * @param array|string $url the parameter to be used to generate a valid URL
  187. * @param boolean|string $scheme the URI scheme to use in the generated URL:
  188. *
  189. * - `false` (default): generating a relative URL.
  190. * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]].
  191. * - string: generating an absolute URL with the specified scheme (either `http` or `https`).
  192. *
  193. * @return string the generated URL
  194. * @throws InvalidParamException a relative route is given while there is no active controller
  195. */
  196. public static function to($url = '', $scheme = false)
  197. {
  198. if (is_array($url)) {
  199. return static::toRoute($url, $scheme);
  200. }
  201. $url = Yii::getAlias($url);
  202. if ($url === '') {
  203. $url = Yii::$app->getRequest()->getUrl();
  204. }
  205. if (!$scheme) {
  206. return $url;
  207. }
  208. if (strncmp($url, '//', 2) === 0) {
  209. // e.g. //hostname/path/to/resource
  210. return is_string($scheme) ? "$scheme:$url" : $url;
  211. }
  212. if (($pos = strpos($url, ':')) === false || !ctype_alpha(substr($url, 0, $pos))) {
  213. // turn relative URL into absolute
  214. $url = static::getUrlManager()->getHostInfo() . '/' . ltrim($url, '/');
  215. }
  216. if (is_string($scheme) && ($pos = strpos($url, ':')) !== false) {
  217. // replace the scheme with the specified one
  218. $url = $scheme . substr($url, $pos);
  219. }
  220. return $url;
  221. }
  222. /**
  223. * Returns the base URL of the current request.
  224. * @param boolean|string $scheme the URI scheme to use in the returned base URL:
  225. *
  226. * - `false` (default): returning the base URL without host info.
  227. * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]].
  228. * - string: returning an absolute base URL with the specified scheme (either `http` or `https`).
  229. * @return string
  230. */
  231. public static function base($scheme = false)
  232. {
  233. $url = static::getUrlManager()->getBaseUrl();
  234. if ($scheme) {
  235. $url = static::getUrlManager()->getHostInfo() . $url;
  236. if (is_string($scheme) && ($pos = strpos($url, '://')) !== false) {
  237. $url = $scheme . substr($url, $pos);
  238. }
  239. }
  240. return $url;
  241. }
  242. /**
  243. * Remembers the specified URL so that it can be later fetched back by [[previous()]].
  244. *
  245. * @param string|array $url the URL to remember. Please refer to [[to()]] for acceptable formats.
  246. * If this parameter is not specified, the currently requested URL will be used.
  247. * @param string $name the name associated with the URL to be remembered. This can be used
  248. * later by [[previous()]]. If not set, it will use [[\yii\web\User::returnUrlParam]].
  249. * @see previous()
  250. */
  251. public static function remember($url = '', $name = null)
  252. {
  253. $url = static::to($url);
  254. if ($name === null) {
  255. Yii::$app->getUser()->setReturnUrl($url);
  256. } else {
  257. Yii::$app->getSession()->set($name, $url);
  258. }
  259. }
  260. /**
  261. * Returns the URL previously [[remember()|remembered]].
  262. *
  263. * @param string $name the named associated with the URL that was remembered previously.
  264. * If not set, it will use [[\yii\web\User::returnUrlParam]].
  265. * @return string the URL previously remembered. Null is returned if no URL was remembered with the given name.
  266. * @see remember()
  267. */
  268. public static function previous($name = null)
  269. {
  270. if ($name === null) {
  271. return Yii::$app->getUser()->getReturnUrl();
  272. } else {
  273. return Yii::$app->getSession()->get($name);
  274. }
  275. }
  276. /**
  277. * Returns the canonical URL of the currently requested page.
  278. * The canonical URL is constructed using the current controller's [[\yii\web\Controller::route]] and
  279. * [[\yii\web\Controller::actionParams]]. You may use the following code in the layout view to add a link tag
  280. * about canonical URL:
  281. *
  282. * ```php
  283. * $this->registerLinkTag(['rel' => 'canonical', 'href' => Url::canonical()]);
  284. * ```
  285. *
  286. * @return string the canonical URL of the currently requested page
  287. */
  288. public static function canonical()
  289. {
  290. $params = Yii::$app->controller->actionParams;
  291. $params[0] = Yii::$app->controller->getRoute();
  292. return static::getUrlManager()->createAbsoluteUrl($params);
  293. }
  294. /**
  295. * Returns the home URL.
  296. *
  297. * @param boolean|string $scheme the URI scheme to use for the returned URL:
  298. *
  299. * - `false` (default): returning a relative URL.
  300. * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]].
  301. * - string: returning an absolute URL with the specified scheme (either `http` or `https`).
  302. *
  303. * @return string home URL
  304. */
  305. public static function home($scheme = false)
  306. {
  307. $url = Yii::$app->getHomeUrl();
  308. if ($scheme) {
  309. $url = static::getUrlManager()->getHostInfo() . $url;
  310. if (is_string($scheme) && ($pos = strpos($url, '://')) !== false) {
  311. $url = $scheme . substr($url, $pos);
  312. }
  313. }
  314. return $url;
  315. }
  316. /**
  317. * Returns a value indicating whether a URL is relative.
  318. * A relative URL does not have host info part.
  319. * @param string $url the URL to be checked
  320. * @return boolean whether the URL is relative
  321. */
  322. public static function isRelative($url)
  323. {
  324. return strncmp($url, '//', 2) && strpos($url, '://') === false;
  325. }
  326. /**
  327. * Creates a URL by using the current route and the GET parameters.
  328. *
  329. * You may modify or remove some of the GET parameters, or add additional query parameters through
  330. * the `$params` parameter. In particular, if you specify a parameter to be null, then this parameter
  331. * will be removed from the existing GET parameters; all other parameters specified in `$params` will
  332. * be merged with the existing GET parameters. For example,
  333. *
  334. * ```php
  335. * // assume $_GET = ['id' => 123, 'src' => 'google'], current route is "post/view"
  336. *
  337. * // /index.php?r=post%2Fview&id=123&src=google
  338. * echo Url::current();
  339. *
  340. * // /index.php?r=post%2Fview&id=123
  341. * echo Url::current(['src' => null]);
  342. *
  343. * // /index.php?r=post%2Fview&id=100&src=google
  344. * echo Url::current(['id' => 100]);
  345. * ```
  346. *
  347. * @param array $params an associative array of parameters that will be merged with the current GET parameters.
  348. * If a parameter value is null, the corresponding GET parameter will be removed.
  349. * @param boolean|string $scheme the URI scheme to use in the generated URL:
  350. *
  351. * - `false` (default): generating a relative URL.
  352. * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]].
  353. * - string: generating an absolute URL with the specified scheme (either `http` or `https`).
  354. *
  355. * @return string the generated URL
  356. * @since 2.0.3
  357. */
  358. public static function current(array $params = [], $scheme = false)
  359. {
  360. $currentParams = Yii::$app->getRequest()->getQueryParams();
  361. $currentParams[0] = '/' . Yii::$app->controller->getRoute();
  362. $route = ArrayHelper::merge($currentParams, $params);
  363. return static::toRoute($route, $scheme);
  364. }
  365. /**
  366. * @return \yii\web\UrlManager URL manager used to create URLs
  367. * @since 2.0.8
  368. */
  369. protected static function getUrlManager()
  370. {
  371. return static::$urlManager ?: Yii::$app->getUrlManager();
  372. }
  373. }