Controller.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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\web;
  8. use Yii;
  9. use yii\base\InlineAction;
  10. use yii\helpers\Html;
  11. /**
  12. * Controller is the base class of web controllers.
  13. *
  14. * @property string $canonicalUrl The canonical URL of the currently requested page. This property is
  15. * read-only.
  16. *
  17. * @author Qiang Xue <[email protected]>
  18. * @since 2.0
  19. */
  20. class Controller extends \yii\base\Controller
  21. {
  22. /**
  23. * @var boolean whether to enable CSRF validation for the actions in this controller.
  24. * CSRF validation is enabled only when both this property and [[Request::enableCsrfValidation]] are true.
  25. */
  26. public $enableCsrfValidation = true;
  27. /**
  28. * @var array the parameters bound to the current action. This is mainly used by [[getCanonicalUrl()]].
  29. */
  30. public $actionParams = [];
  31. /**
  32. * Binds the parameters to the action.
  33. * This method is invoked by [[Action]] when it begins to run with the given parameters.
  34. * This method will check the parameter names that the action requires and return
  35. * the provided parameters according to the requirement. If there is any missing parameter,
  36. * an exception will be thrown.
  37. * @param \yii\base\Action $action the action to be bound with parameters
  38. * @param array $params the parameters to be bound to the action
  39. * @return array the valid parameters that the action can run with.
  40. * @throws HttpException if there are missing or invalid parameters.
  41. */
  42. public function bindActionParams($action, $params)
  43. {
  44. if ($action instanceof InlineAction) {
  45. $method = new \ReflectionMethod($this, $action->actionMethod);
  46. } else {
  47. $method = new \ReflectionMethod($action, 'run');
  48. }
  49. $args = [];
  50. $missing = [];
  51. $actionParams = [];
  52. foreach ($method->getParameters() as $param) {
  53. $name = $param->getName();
  54. if (array_key_exists($name, $params)) {
  55. if ($param->isArray()) {
  56. $args[] = $actionParams[$name] = is_array($params[$name]) ? $params[$name] : [$params[$name]];
  57. } elseif (!is_array($params[$name])) {
  58. $args[] = $actionParams[$name] = $params[$name];
  59. } else {
  60. throw new BadRequestHttpException(Yii::t('yii', 'Invalid data received for parameter "{param}".', [
  61. 'param' => $name,
  62. ]));
  63. }
  64. unset($params[$name]);
  65. } elseif ($param->isDefaultValueAvailable()) {
  66. $args[] = $actionParams[$name] = $param->getDefaultValue();
  67. } else {
  68. $missing[] = $name;
  69. }
  70. }
  71. if (!empty($missing)) {
  72. throw new BadRequestHttpException(Yii::t('yii', 'Missing required parameters: {params}', [
  73. 'params' => implode(', ', $missing),
  74. ]));
  75. }
  76. $this->actionParams = $actionParams;
  77. return $args;
  78. }
  79. /**
  80. * @inheritdoc
  81. */
  82. public function beforeAction($action)
  83. {
  84. if (parent::beforeAction($action)) {
  85. if ($this->enableCsrfValidation && Yii::$app->exception === null && !Yii::$app->getRequest()->validateCsrfToken()) {
  86. throw new BadRequestHttpException(Yii::t('yii', 'Unable to verify your data submission.'));
  87. }
  88. return true;
  89. } else {
  90. return false;
  91. }
  92. }
  93. /**
  94. * Normalizes route making it suitable for UrlManager. Absolute routes are staying as is
  95. * while relative routes are converted to absolute routes.
  96. *
  97. * A relative route is a route without a leading slash, such as "view", "post/view".
  98. *
  99. * - If the route is an empty string, the current [[route]] will be used;
  100. * - If the route contains no slashes at all, it is considered to be an action ID
  101. * of the current controller and will be prepended with [[uniqueId]];
  102. * - If the route has no leading slash, it is considered to be a route relative
  103. * to the current module and will be prepended with the module's uniqueId.
  104. *
  105. * @param string $route the route. This can be either an absolute route or a relative route.
  106. * @return string normalized route suitable for UrlManager
  107. */
  108. protected function getNormalizedRoute($route)
  109. {
  110. if (strpos($route, '/') === false) {
  111. // empty or an action ID
  112. $route = $route === '' ? $this->getRoute() : $this->getUniqueId() . '/' . $route;
  113. } elseif ($route[0] !== '/') {
  114. // relative to module
  115. $route = ltrim($this->module->getUniqueId() . '/' . $route, '/');
  116. }
  117. return $route;
  118. }
  119. /**
  120. * Creates a relative URL using the given route and parameters.
  121. *
  122. * This method enhances [[UrlManager::createUrl()]] by supporting relative routes.
  123. * A relative route is a route without a leading slash, such as "view", "post/view".
  124. *
  125. * - If the route is an empty string, the current [[route]] will be used;
  126. * - If the route contains no slashes at all, it is considered to be an action ID
  127. * of the current controller and will be prepended with [[uniqueId]];
  128. * - If the route has no leading slash, it is considered to be a route relative
  129. * to the current module and will be prepended with the module's uniqueId.
  130. *
  131. * After this route conversion, the method calls [[UrlManager::createUrl()]] to create a URL.
  132. *
  133. * @param string $route the route. This can be either an absolute route or a relative route.
  134. * @param array $params the parameters (name-value pairs) to be included in the generated URL
  135. * @return string the created relative URL
  136. */
  137. public function createUrl($route, $params = [])
  138. {
  139. $route = $this->getNormalizedRoute($route);
  140. return Yii::$app->getUrlManager()->createUrl($route, $params);
  141. }
  142. /**
  143. * Creates an absolute URL using the given route and parameters.
  144. *
  145. * This method enhances [[UrlManager::createAbsoluteUrl()]] by supporting relative routes.
  146. * A relative route is a route without a leading slash, such as "view", "post/view".
  147. *
  148. * - If the route is an empty string, the current [[route]] will be used;
  149. * - If the route contains no slashes at all, it is considered to be an action ID
  150. * of the current controller and will be prepended with [[uniqueId]];
  151. * - If the route has no leading slash, it is considered to be a route relative
  152. * to the current module and will be prepended with the module's uniqueId.
  153. *
  154. * After this route conversion, the method calls [[UrlManager::createUrl()]] to create a URL.
  155. *
  156. * @param string $route the route. This can be either an absolute route or a relative route.
  157. * @param array $params the parameters (name-value pairs) to be included in the generated URL
  158. * @return string the created absolute URL
  159. */
  160. public function createAbsoluteUrl($route, $params = [])
  161. {
  162. $route = $this->getNormalizedRoute($route);
  163. return Yii::$app->getUrlManager()->createAbsoluteUrl($route, $params);
  164. }
  165. /**
  166. * Returns the canonical URL of the currently requested page.
  167. * The canonical URL is constructed using [[route]] and [[actionParams]]. You may use the following code
  168. * in the layout view to add a link tag about canonical URL:
  169. *
  170. * ~~~
  171. * $this->registerLinkTag(['rel' => 'canonical', 'href' => Yii::$app->controller->canonicalUrl]);
  172. * ~~~
  173. *
  174. * @return string the canonical URL of the currently requested page
  175. */
  176. public function getCanonicalUrl()
  177. {
  178. return Yii::$app->getUrlManager()->createAbsoluteUrl($this->getRoute(), $this->actionParams);
  179. }
  180. /**
  181. * Redirects the browser to the specified URL.
  182. * This method is a shortcut to [[Response::redirect()]].
  183. *
  184. * You can use it in an action by returning the [[Response]] directly:
  185. *
  186. * ```php
  187. * // stop executing this action and redirect to login page
  188. * return $this->redirect(['login']);
  189. * ```
  190. *
  191. * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
  192. *
  193. * - a string representing a URL (e.g. "http://example.com")
  194. * - a string representing a URL alias (e.g. "@example.com")
  195. * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`)
  196. * [[Html::url()]] will be used to convert the array into a URL.
  197. *
  198. * Any relative URL will be converted into an absolute one by prepending it with the host info
  199. * of the current request.
  200. *
  201. * @param integer $statusCode the HTTP status code. Defaults to 302.
  202. * See <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>
  203. * for details about HTTP status code
  204. * @return Response the current response object
  205. */
  206. public function redirect($url, $statusCode = 302)
  207. {
  208. return Yii::$app->getResponse()->redirect(Html::url($url), $statusCode);
  209. }
  210. /**
  211. * Redirects the browser to the home page.
  212. *
  213. * You can use this method in an action by returning the [[Response]] directly:
  214. *
  215. * ```php
  216. * // stop executing this action and redirect to home page
  217. * return $this->goHome();
  218. * ```
  219. *
  220. * @return Response the current response object
  221. */
  222. public function goHome()
  223. {
  224. return Yii::$app->getResponse()->redirect(Yii::$app->getHomeUrl());
  225. }
  226. /**
  227. * Redirects the browser to the last visited page.
  228. *
  229. * You can use this method in an action by returning the [[Response]] directly:
  230. *
  231. * ```php
  232. * // stop executing this action and redirect to last visited page
  233. * return $this->goBack();
  234. * ```
  235. *
  236. * @param string|array $defaultUrl the default return URL in case it was not set previously.
  237. * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
  238. * Please refer to [[User::setReturnUrl()]] on accepted format of the URL.
  239. * @return Response the current response object
  240. * @see User::getReturnUrl()
  241. */
  242. public function goBack($defaultUrl = null)
  243. {
  244. return Yii::$app->getResponse()->redirect(Yii::$app->getUser()->getReturnUrl($defaultUrl));
  245. }
  246. /**
  247. * Refreshes the current page.
  248. * This method is a shortcut to [[Response::refresh()]].
  249. *
  250. * You can use it in an action by returning the [[Response]] directly:
  251. *
  252. * ```php
  253. * // stop executing this action and refresh the current page
  254. * return $this->refresh();
  255. * ```
  256. *
  257. * @param string $anchor the anchor that should be appended to the redirection URL.
  258. * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
  259. * @return Response the response object itself
  260. */
  261. public function refresh($anchor = '')
  262. {
  263. return Yii::$app->getResponse()->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
  264. }
  265. }