Controller.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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\ErrorException;
  10. use yii\base\Exception;
  11. use yii\base\InlineAction;
  12. use yii\helpers\Url;
  13. /**
  14. * Controller is the base class of web controllers.
  15. *
  16. * For more details and usage information on Controller, see the [guide article on controllers](guide:structure-controllers).
  17. *
  18. * @author Qiang Xue <qiang.xue@gmail.com>
  19. * @since 2.0
  20. */
  21. class Controller extends \yii\base\Controller
  22. {
  23. /**
  24. * @var bool whether to enable CSRF validation for the actions in this controller.
  25. * CSRF validation is enabled only when both this property and [[\yii\web\Request::enableCsrfValidation]] are true.
  26. */
  27. public $enableCsrfValidation = true;
  28. /**
  29. * @var array the parameters bound to the current action.
  30. */
  31. public $actionParams = [];
  32. /**
  33. * Renders a view in response to an AJAX request.
  34. *
  35. * This method is similar to [[renderPartial()]] except that it will inject into
  36. * the rendering result with JS/CSS scripts and files which are registered with the view.
  37. * For this reason, you should use this method instead of [[renderPartial()]] to render
  38. * a view to respond to an AJAX request.
  39. *
  40. * @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
  41. * @param array $params the parameters (name-value pairs) that should be made available in the view.
  42. * @return string the rendering result.
  43. */
  44. public function renderAjax($view, $params = [])
  45. {
  46. return $this->getView()->renderAjax($view, $params, $this);
  47. }
  48. /**
  49. * Send data formatted as JSON.
  50. *
  51. * This method is a shortcut for sending data formatted as JSON. It will return
  52. * the [[Application::getResponse()|response]] application component after configuring
  53. * the [[Response::$format|format]] and setting the [[Response::$data|data]] that should
  54. * be formatted. A common usage will be:
  55. *
  56. * ```php
  57. * return $this->asJson($data);
  58. * ```
  59. *
  60. * @param mixed $data the data that should be formatted.
  61. * @return Response a response that is configured to send `$data` formatted as JSON.
  62. * @since 2.0.11
  63. * @see Response::$format
  64. * @see Response::FORMAT_JSON
  65. * @see JsonResponseFormatter
  66. */
  67. public function asJson($data)
  68. {
  69. $this->response->format = Response::FORMAT_JSON;
  70. $this->response->data = $data;
  71. return $this->response;
  72. }
  73. /**
  74. * Send data formatted as XML.
  75. *
  76. * This method is a shortcut for sending data formatted as XML. It will return
  77. * the [[Application::getResponse()|response]] application component after configuring
  78. * the [[Response::$format|format]] and setting the [[Response::$data|data]] that should
  79. * be formatted. A common usage will be:
  80. *
  81. * ```php
  82. * return $this->asXml($data);
  83. * ```
  84. *
  85. * @param mixed $data the data that should be formatted.
  86. * @return Response a response that is configured to send `$data` formatted as XML.
  87. * @since 2.0.11
  88. * @see Response::$format
  89. * @see Response::FORMAT_XML
  90. * @see XmlResponseFormatter
  91. */
  92. public function asXml($data)
  93. {
  94. $this->response->format = Response::FORMAT_XML;
  95. $this->response->data = $data;
  96. return $this->response;
  97. }
  98. /**
  99. * Binds the parameters to the action.
  100. * This method is invoked by [[\yii\base\Action]] when it begins to run with the given parameters.
  101. * This method will check the parameter names that the action requires and return
  102. * the provided parameters according to the requirement. If there is any missing parameter,
  103. * an exception will be thrown.
  104. * @param \yii\base\Action $action the action to be bound with parameters
  105. * @param array $params the parameters to be bound to the action
  106. * @return array the valid parameters that the action can run with.
  107. * @throws BadRequestHttpException if there are missing or invalid parameters.
  108. */
  109. public function bindActionParams($action, $params)
  110. {
  111. if ($action instanceof InlineAction) {
  112. $method = new \ReflectionMethod($this, $action->actionMethod);
  113. } else {
  114. $method = new \ReflectionMethod($action, 'run');
  115. }
  116. $args = [];
  117. $missing = [];
  118. $actionParams = [];
  119. $requestedParams = [];
  120. foreach ($method->getParameters() as $param) {
  121. $name = $param->getName();
  122. if (array_key_exists($name, $params)) {
  123. $isValid = true;
  124. if ($param->isArray()) {
  125. $params[$name] = (array)$params[$name];
  126. } elseif (is_array($params[$name])) {
  127. $isValid = false;
  128. } elseif (
  129. PHP_VERSION_ID >= 70000 &&
  130. ($type = $param->getType()) !== null &&
  131. $type->isBuiltin() &&
  132. ($params[$name] !== null || !$type->allowsNull())
  133. ) {
  134. $typeName = PHP_VERSION_ID >= 70100 ? $type->getName() : (string)$type;
  135. switch ($typeName) {
  136. case 'int':
  137. $params[$name] = filter_var($params[$name], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
  138. break;
  139. case 'float':
  140. $params[$name] = filter_var($params[$name], FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE);
  141. break;
  142. case 'bool':
  143. $params[$name] = filter_var($params[$name], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
  144. break;
  145. }
  146. if ($params[$name] === null) {
  147. $isValid = false;
  148. }
  149. }
  150. if (!$isValid) {
  151. throw new BadRequestHttpException(Yii::t('yii', 'Invalid data received for parameter "{param}".', [
  152. 'param' => $name,
  153. ]));
  154. }
  155. $args[] = $actionParams[$name] = $params[$name];
  156. unset($params[$name]);
  157. } elseif (PHP_VERSION_ID >= 70100 && ($type = $param->getType()) !== null && !$type->isBuiltin()) {
  158. try {
  159. $this->bindInjectedParams($type, $name, $args, $requestedParams);
  160. } catch (Exception $e) {
  161. throw new ServerErrorHttpException($e->getMessage(), 0, $e);
  162. }
  163. } elseif ($param->isDefaultValueAvailable()) {
  164. $args[] = $actionParams[$name] = $param->getDefaultValue();
  165. } else {
  166. $missing[] = $name;
  167. }
  168. }
  169. if (!empty($missing)) {
  170. throw new BadRequestHttpException(Yii::t('yii', 'Missing required parameters: {params}', [
  171. 'params' => implode(', ', $missing),
  172. ]));
  173. }
  174. $this->actionParams = $actionParams;
  175. // We use a different array here, specifically one that doesn't contain service instances but descriptions instead.
  176. if (\Yii::$app->requestedParams === null) {
  177. \Yii::$app->requestedParams = array_merge($actionParams, $requestedParams);
  178. }
  179. return $args;
  180. }
  181. /**
  182. * {@inheritdoc}
  183. */
  184. public function beforeAction($action)
  185. {
  186. if (parent::beforeAction($action)) {
  187. if ($this->enableCsrfValidation && Yii::$app->getErrorHandler()->exception === null && !$this->request->validateCsrfToken()) {
  188. throw new BadRequestHttpException(Yii::t('yii', 'Unable to verify your data submission.'));
  189. }
  190. return true;
  191. }
  192. return false;
  193. }
  194. /**
  195. * Redirects the browser to the specified URL.
  196. * This method is a shortcut to [[Response::redirect()]].
  197. *
  198. * You can use it in an action by returning the [[Response]] directly:
  199. *
  200. * ```php
  201. * // stop executing this action and redirect to login page
  202. * return $this->redirect(['login']);
  203. * ```
  204. *
  205. * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
  206. *
  207. * - a string representing a URL (e.g. "http://example.com")
  208. * - a string representing a URL alias (e.g. "@example.com")
  209. * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`)
  210. * [[Url::to()]] will be used to convert the array into a URL.
  211. *
  212. * Any relative URL that starts with a single forward slash "/" will be converted
  213. * into an absolute one by prepending it with the host info of the current request.
  214. *
  215. * @param int $statusCode the HTTP status code. Defaults to 302.
  216. * See <https://tools.ietf.org/html/rfc2616#section-10>
  217. * for details about HTTP status code
  218. * @return Response the current response object
  219. */
  220. public function redirect($url, $statusCode = 302)
  221. {
  222. // calling Url::to() here because Response::redirect() modifies route before calling Url::to()
  223. return $this->response->redirect(Url::to($url), $statusCode);
  224. }
  225. /**
  226. * Redirects the browser to the home page.
  227. *
  228. * You can use this method in an action by returning the [[Response]] directly:
  229. *
  230. * ```php
  231. * // stop executing this action and redirect to home page
  232. * return $this->goHome();
  233. * ```
  234. *
  235. * @return Response the current response object
  236. */
  237. public function goHome()
  238. {
  239. return $this->response->redirect(Yii::$app->getHomeUrl());
  240. }
  241. /**
  242. * Redirects the browser to the last visited page.
  243. *
  244. * You can use this method in an action by returning the [[Response]] directly:
  245. *
  246. * ```php
  247. * // stop executing this action and redirect to last visited page
  248. * return $this->goBack();
  249. * ```
  250. *
  251. * For this function to work you have to [[User::setReturnUrl()|set the return URL]] in appropriate places before.
  252. *
  253. * @param string|array $defaultUrl the default return URL in case it was not set previously.
  254. * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
  255. * Please refer to [[User::setReturnUrl()]] on accepted format of the URL.
  256. * @return Response the current response object
  257. * @see User::getReturnUrl()
  258. */
  259. public function goBack($defaultUrl = null)
  260. {
  261. return $this->response->redirect(Yii::$app->getUser()->getReturnUrl($defaultUrl));
  262. }
  263. /**
  264. * Refreshes the current page.
  265. * This method is a shortcut to [[Response::refresh()]].
  266. *
  267. * You can use it in an action by returning the [[Response]] directly:
  268. *
  269. * ```php
  270. * // stop executing this action and refresh the current page
  271. * return $this->refresh();
  272. * ```
  273. *
  274. * @param string $anchor the anchor that should be appended to the redirection URL.
  275. * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
  276. * @return Response the response object itself
  277. */
  278. public function refresh($anchor = '')
  279. {
  280. return $this->response->redirect($this->request->getUrl() . $anchor);
  281. }
  282. }