Controller.php 12 KB

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