Controller.php 12 KB

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