Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

386 lines
15KB

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