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.

209 lines
7.5KB

  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\Url;
  11. /**
  12. * Controller is the base class of web controllers.
  13. *
  14. * @author Qiang Xue <qiang.xue@gmail.com>
  15. * @since 2.0
  16. */
  17. class Controller extends \yii\base\Controller
  18. {
  19. /**
  20. * @var boolean whether to enable CSRF validation for the actions in this controller.
  21. * CSRF validation is enabled only when both this property and [[Request::enableCsrfValidation]] are true.
  22. */
  23. public $enableCsrfValidation = true;
  24. /**
  25. * @var array the parameters bound to the current action.
  26. */
  27. public $actionParams = [];
  28. /**
  29. * Renders a view in response to an AJAX request.
  30. *
  31. * This method is similar to [[renderPartial()]] except that it will inject into
  32. * the rendering result with JS/CSS scripts and files which are registered with the view.
  33. * For this reason, you should use this method instead of [[renderPartial()]] to render
  34. * a view to respond to an AJAX request.
  35. *
  36. * @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
  37. * @param array $params the parameters (name-value pairs) that should be made available in the view.
  38. * @return string the rendering result.
  39. */
  40. public function renderAjax($view, $params = [])
  41. {
  42. return $this->getView()->renderAjax($view, $params, $this);
  43. }
  44. /**
  45. * Binds the parameters to the action.
  46. * This method is invoked by [[\yii\base\Action]] when it begins to run with the given parameters.
  47. * This method will check the parameter names that the action requires and return
  48. * the provided parameters according to the requirement. If there is any missing parameter,
  49. * an exception will be thrown.
  50. * @param \yii\base\Action $action the action to be bound with parameters
  51. * @param array $params the parameters to be bound to the action
  52. * @return array the valid parameters that the action can run with.
  53. * @throws BadRequestHttpException if there are missing or invalid parameters.
  54. */
  55. public function bindActionParams($action, $params)
  56. {
  57. if ($action instanceof InlineAction) {
  58. $method = new \ReflectionMethod($this, $action->actionMethod);
  59. } else {
  60. $method = new \ReflectionMethod($action, 'run');
  61. }
  62. $args = [];
  63. $missing = [];
  64. $actionParams = [];
  65. foreach ($method->getParameters() as $param) {
  66. $name = $param->getName();
  67. if (array_key_exists($name, $params)) {
  68. if ($param->isArray()) {
  69. $args[] = $actionParams[$name] = (array)$params[$name];
  70. } elseif (!is_array($params[$name])) {
  71. $args[] = $actionParams[$name] = $params[$name];
  72. } else {
  73. throw new BadRequestHttpException(Yii::t('yii', 'Invalid data received for parameter "{param}".', [
  74. 'param' => $name,
  75. ]));
  76. }
  77. unset($params[$name]);
  78. } elseif ($param->isDefaultValueAvailable()) {
  79. $args[] = $actionParams[$name] = $param->getDefaultValue();
  80. } else {
  81. $missing[] = $name;
  82. }
  83. }
  84. if (!empty($missing)) {
  85. throw new BadRequestHttpException(Yii::t('yii', 'Missing required parameters: {params}', [
  86. 'params' => implode(', ', $missing),
  87. ]));
  88. }
  89. $this->actionParams = $actionParams;
  90. return $args;
  91. }
  92. /**
  93. * @inheritdoc
  94. */
  95. public function beforeAction($action)
  96. {
  97. if (parent::beforeAction($action)) {
  98. if ($this->enableCsrfValidation && Yii::$app->getErrorHandler()->exception === null && !Yii::$app->getRequest()->validateCsrfToken()) {
  99. throw new BadRequestHttpException(Yii::t('yii', 'Unable to verify your data submission.'));
  100. }
  101. return true;
  102. } else {
  103. return false;
  104. }
  105. }
  106. /**
  107. * Redirects the browser to the specified URL.
  108. * This method is a shortcut to [[Response::redirect()]].
  109. *
  110. * You can use it in an action by returning the [[Response]] directly:
  111. *
  112. * ```php
  113. * // stop executing this action and redirect to login page
  114. * return $this->redirect(['login']);
  115. * ```
  116. *
  117. * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
  118. *
  119. * - a string representing a URL (e.g. "http://example.com")
  120. * - a string representing a URL alias (e.g. "@example.com")
  121. * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`)
  122. * [[Url::to()]] will be used to convert the array into a URL.
  123. *
  124. * Any relative URL will be converted into an absolute one by prepending it with the host info
  125. * of the current request.
  126. *
  127. * @param integer $statusCode the HTTP status code. Defaults to 302.
  128. * See <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>
  129. * for details about HTTP status code
  130. * @return Response the current response object
  131. */
  132. public function redirect($url, $statusCode = 302)
  133. {
  134. return Yii::$app->getResponse()->redirect(Url::to($url), $statusCode);
  135. }
  136. /**
  137. * Redirects the browser to the home page.
  138. *
  139. * You can use this method in an action by returning the [[Response]] directly:
  140. *
  141. * ```php
  142. * // stop executing this action and redirect to home page
  143. * return $this->goHome();
  144. * ```
  145. *
  146. * @return Response the current response object
  147. */
  148. public function goHome()
  149. {
  150. return Yii::$app->getResponse()->redirect(Yii::$app->getHomeUrl());
  151. }
  152. /**
  153. * Redirects the browser to the last visited page.
  154. *
  155. * You can use this method in an action by returning the [[Response]] directly:
  156. *
  157. * ```php
  158. * // stop executing this action and redirect to last visited page
  159. * return $this->goBack();
  160. * ```
  161. *
  162. * For this function to work you have to [[User::setReturnUrl()|set the return URL]] in appropriate places before.
  163. *
  164. * @param string|array $defaultUrl the default return URL in case it was not set previously.
  165. * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
  166. * Please refer to [[User::setReturnUrl()]] on accepted format of the URL.
  167. * @return Response the current response object
  168. * @see User::getReturnUrl()
  169. */
  170. public function goBack($defaultUrl = null)
  171. {
  172. return Yii::$app->getResponse()->redirect(Yii::$app->getUser()->getReturnUrl($defaultUrl));
  173. }
  174. /**
  175. * Refreshes the current page.
  176. * This method is a shortcut to [[Response::refresh()]].
  177. *
  178. * You can use it in an action by returning the [[Response]] directly:
  179. *
  180. * ```php
  181. * // stop executing this action and refresh the current page
  182. * return $this->refresh();
  183. * ```
  184. *
  185. * @param string $anchor the anchor that should be appended to the redirection URL.
  186. * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
  187. * @return Response the response object itself
  188. */
  189. public function refresh($anchor = '')
  190. {
  191. return Yii::$app->getResponse()->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
  192. }
  193. }