Controller.php 15 KB

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