Controller.php 7.92 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7 8 9
 * @license http://www.yiiframework.com/license/
 */

namespace yii\web;

10
use Yii;
11
use yii\base\InlineAction;
12
use yii\helpers\Html;
13

Qiang Xue committed
14
/**
15
 * Controller is the base class of web controllers.
Qiang Xue committed
16
 *
Carsten Brandt committed
17 18
 * @property string $canonicalUrl The canonical URL of the currently requested page. This property is
 * read-only.
19
 *
Qiang Xue committed
20 21 22 23 24
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Controller extends \yii\base\Controller
{
25 26 27 28 29
	/**
	 * @var boolean whether to enable CSRF validation for the actions in this controller.
	 * CSRF validation is enabled only when both this property and [[Request::enableCsrfValidation]] are true.
	 */
	public $enableCsrfValidation = true;
30 31 32 33
	/**
	 * @var array the parameters bound to the current action. This is mainly used by [[getCanonicalUrl()]].
	 */
	public $actionParams = [];
34

35 36 37 38 39 40 41 42 43
	/**
	 * Binds the parameters to the action.
	 * This method is invoked by [[Action]] when it begins to run with the given parameters.
	 * This method will check the parameter names that the action requires and return
	 * the provided parameters according to the requirement. If there is any missing parameter,
	 * an exception will be thrown.
	 * @param \yii\base\Action $action the action to be bound with parameters
	 * @param array $params the parameters to be bound to the action
	 * @return array the valid parameters that the action can run with.
44
	 * @throws HttpException if there are missing or invalid parameters.
45 46 47 48 49 50 51 52 53
	 */
	public function bindActionParams($action, $params)
	{
		if ($action instanceof InlineAction) {
			$method = new \ReflectionMethod($this, $action->actionMethod);
		} else {
			$method = new \ReflectionMethod($action, 'run');
		}

Alexander Makarov committed
54 55
		$args = [];
		$missing = [];
56
		$actionParams = [];
57 58 59
		foreach ($method->getParameters() as $param) {
			$name = $param->getName();
			if (array_key_exists($name, $params)) {
60 61 62 63 64
				if ($param->isArray()) {
					$args[] = $actionParams[$name] = is_array($params[$name]) ? $params[$name] : [$params[$name]];
				} elseif (!is_array($params[$name])) {
					$args[] = $actionParams[$name] = $params[$name];
				} else {
65
					throw new BadRequestHttpException(Yii::t('yii', 'Invalid data received for parameter "{param}".', [
66 67 68
						'param' => $name,
					]));
				}
69 70
				unset($params[$name]);
			} elseif ($param->isDefaultValueAvailable()) {
71
				$args[] = $actionParams[$name] = $param->getDefaultValue();
72 73 74 75 76 77
			} else {
				$missing[] = $name;
			}
		}

		if (!empty($missing)) {
78
			throw new BadRequestHttpException(Yii::t('yii', 'Missing required parameters: {params}', [
79
				'params' => implode(', ', $missing),
Alexander Makarov committed
80
			]));
81
		}
82

83
		$this->actionParams = $actionParams;
84 85 86 87

		return $args;
	}

88
	/**
Qiang Xue committed
89
	 * @inheritdoc
90 91 92 93
	 */
	public function beforeAction($action)
	{
		if (parent::beforeAction($action)) {
94
			if ($this->enableCsrfValidation && Yii::$app->exception === null && !Yii::$app->getRequest()->validateCsrfToken()) {
95
				throw new BadRequestHttpException(Yii::t('yii', 'Unable to verify your data submission.'));
Qiang Xue committed
96 97
			}
			return true;
98 99 100 101 102
		} else {
			return false;
		}
	}

103 104 105 106
	/**
	 * Creates a URL using the given route and parameters.
	 *
	 * This method enhances [[UrlManager::createUrl()]] by supporting relative routes.
107
	 * A relative route is a route without a leading slash, such as "view", "post/view".
108
	 *
109 110 111 112 113 114 115
	 * - If the route is an empty string, the current [[route]] will be used;
	 * - If the route contains no slashes at all, it is considered to be an action ID
	 *   of the current controller and will be prepended with [[uniqueId]];
	 * - If the route has no leading slash, it is considered to be a route relative
	 *   to the current module and will be prepended with the module's uniqueId.
	 *
	 * After this route conversion, the method calls [[UrlManager::createUrl()]] to create a URL.
116 117 118 119 120
	 *
	 * @param string $route the route. This can be either an absolute route or a relative route.
	 * @param array $params the parameters (name-value pairs) to be included in the generated URL
	 * @return string the created URL
	 */
Alexander Makarov committed
121
	public function createUrl($route, $params = [])
122 123
	{
		if (strpos($route, '/') === false) {
124
			// empty or an action ID
125
			$route = $route === '' ? $this->getRoute() : $this->getUniqueId() . '/' . $route;
126 127 128
		} elseif ($route[0] !== '/') {
			// relative to module
			$route = ltrim($this->module->getUniqueId() . '/' . $route, '/');
129 130 131
		}
		return Yii::$app->getUrlManager()->createUrl($route, $params);
	}
132

133 134 135 136 137 138 139 140 141
	/**
	 * Returns the canonical URL of the currently requested page.
	 * The canonical URL is constructed using [[route]] and [[actionParams]]. You may use the following code
	 * in the layout view to add a link tag about canonical URL:
	 *
	 * ~~~
	 * $this->registerLinkTag(['rel' => 'canonical', 'href' => Yii::$app->controller->canonicalUrl]);
	 * ~~~
	 *
Carsten Brandt committed
142
	 * @return string the canonical URL of the currently requested page
143 144 145 146 147 148
	 */
	public function getCanonicalUrl()
	{
		return Yii::$app->getUrlManager()->createAbsoluteUrl($this->getRoute(), $this->actionParams);
	}

149 150 151 152
	/**
	 * Redirects the browser to the specified URL.
	 * This method is a shortcut to [[Response::redirect()]].
	 *
153 154 155 156 157 158 159
	 * You can use it in an action by returning the [[Response]] directly:
	 *
	 * ```php
	 * // stop executing this action and redirect to login page
	 * return $this->redirect(['login']);
	 * ```
	 *
Qiang Xue committed
160 161 162 163
	 * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
	 *
	 * - a string representing a URL (e.g. "http://example.com")
	 * - a string representing a URL alias (e.g. "@example.com")
Alexander Makarov committed
164
	 * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`)
Qiang Xue committed
165 166 167 168 169
	 *   [[Html::url()]] will be used to convert the array into a URL.
	 *
	 * Any relative URL will be converted into an absolute one by prepending it with the host info
	 * of the current request.
	 *
170
	 * @param integer $statusCode the HTTP status code. Defaults to 302.
171 172
	 * See [[http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html]]
	 * for details about HTTP status code
Qiang Xue committed
173
	 * @return Response the current response object
174
	 */
175
	public function redirect($url, $statusCode = 302)
176
	{
177
		return Yii::$app->getResponse()->redirect(Html::url($url), $statusCode);
178 179
	}

Qiang Xue committed
180 181
	/**
	 * Redirects the browser to the home page.
182 183 184 185 186 187 188 189
	 *
	 * You can use this method in an action by returning the [[Response]] directly:
	 *
	 * ```php
	 * // stop executing this action and redirect to home page
	 * return $this->goHome();
	 * ```
	 *
Qiang Xue committed
190 191 192 193 194 195 196
	 * @return Response the current response object
	 */
	public function goHome()
	{
		return Yii::$app->getResponse()->redirect(Yii::$app->getHomeUrl());
	}

197 198
	/**
	 * Redirects the browser to the last visited page.
199 200 201 202 203 204 205 206
	 *
	 * You can use this method in an action by returning the [[Response]] directly:
	 *
	 * ```php
	 * // stop executing this action and redirect to last visited page
	 * return $this->goBack();
	 * ```
	 *
207 208 209 210 211 212 213 214 215 216 217
	 * @param string|array $defaultUrl the default return URL in case it was not set previously.
	 * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
	 * Please refer to [[User::setReturnUrl()]] on accepted format of the URL.
	 * @return Response the current response object
	 * @see User::getReturnUrl()
	 */
	public function goBack($defaultUrl = null)
	{
		return Yii::$app->getResponse()->redirect(Yii::$app->getUser()->getReturnUrl($defaultUrl));
	}

218 219 220
	/**
	 * Refreshes the current page.
	 * This method is a shortcut to [[Response::refresh()]].
221 222 223 224 225 226 227 228
	 *
	 * You can use it in an action by returning the [[Response]] directly:
	 *
	 * ```php
	 * // stop executing this action and refresh the current page
	 * return $this->refresh();
	 * ```
	 *
229 230 231 232 233 234 235 236
	 * @param string $anchor the anchor that should be appended to the redirection URL.
	 * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
	 * @return Response the response object itself
	 */
	public function refresh($anchor = '')
	{
		return Yii::$app->getResponse()->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
	}
Zander Baldwin committed
237
}