Controller.php 10.8 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 44 45 46 47 48 49 50 51 52

	/**
	 * Renders a view in response to an AJAX request.
	 *
	 * This method is similar to [[renderPartial()]] except that it will inject into
	 * the rendering result with JS/CSS scripts and files which are registered with the view.
	 * For this reason, you should use this method instead of [[renderPartial()]] to render
	 * a view to respond to an AJAX request.
	 *
	 * @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
	 * @param array $params the parameters (name-value pairs) that should be made available in the view.
	 * @return string the rendering result.
	 */
	public function renderAjax($view, $params = [])
	{
		return $this->getView()->renderAjax($view, $params, $this);
	}

53 54 55 56 57 58 59 60 61
	/**
	 * 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.
62
	 * @throws HttpException if there are missing or invalid parameters.
63 64 65 66 67 68 69 70 71
	 */
	public function bindActionParams($action, $params)
	{
		if ($action instanceof InlineAction) {
			$method = new \ReflectionMethod($this, $action->actionMethod);
		} else {
			$method = new \ReflectionMethod($action, 'run');
		}

Alexander Makarov committed
72 73
		$args = [];
		$missing = [];
74
		$actionParams = [];
75 76 77
		foreach ($method->getParameters() as $param) {
			$name = $param->getName();
			if (array_key_exists($name, $params)) {
78 79 80 81 82
				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 {
83
					throw new BadRequestHttpException(Yii::t('yii', 'Invalid data received for parameter "{param}".', [
84 85 86
						'param' => $name,
					]));
				}
87 88
				unset($params[$name]);
			} elseif ($param->isDefaultValueAvailable()) {
89
				$args[] = $actionParams[$name] = $param->getDefaultValue();
90 91 92 93 94 95
			} else {
				$missing[] = $name;
			}
		}

		if (!empty($missing)) {
96
			throw new BadRequestHttpException(Yii::t('yii', 'Missing required parameters: {params}', [
97
				'params' => implode(', ', $missing),
Alexander Makarov committed
98
			]));
99
		}
100

101
		$this->actionParams = $actionParams;
102 103 104 105

		return $args;
	}

106
	/**
Qiang Xue committed
107
	 * @inheritdoc
108 109 110 111
	 */
	public function beforeAction($action)
	{
		if (parent::beforeAction($action)) {
112
			if ($this->enableCsrfValidation && Yii::$app->exception === null && !Yii::$app->getRequest()->validateCsrfToken()) {
113
				throw new BadRequestHttpException(Yii::t('yii', 'Unable to verify your data submission.'));
Qiang Xue committed
114 115
			}
			return true;
116 117 118 119 120
		} else {
			return false;
		}
	}

121
	/**
122 123
	 * Normalizes route making it suitable for UrlManager. Absolute routes are staying as is
	 * while relative routes are converted to absolute routes.
124
	 *
125
	 * A relative route is a route without a leading slash, such as "view", "post/view".
126
	 *
127 128 129 130 131 132
	 * - 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.
	 *
133
	 * @param string $route the route. This can be either an absolute route or a relative route.
134
	 * @return string normalized route suitable for UrlManager
135
	 */
136
	protected function getNormalizedRoute($route)
137 138
	{
		if (strpos($route, '/') === false) {
139
			// empty or an action ID
140
			$route = $route === '' ? $this->getRoute() : $this->getUniqueId() . '/' . $route;
141 142 143
		} elseif ($route[0] !== '/') {
			// relative to module
			$route = ltrim($this->module->getUniqueId() . '/' . $route, '/');
144
		}
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
		return $route;
	}

	/**
	 * Creates a relative URL using the given route and parameters.
	 *
	 * This method enhances [[UrlManager::createUrl()]] by supporting relative routes.
	 * A relative route is a route without a leading slash, such as "view", "post/view".
	 *
	 * - 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.
	 *
162
	 * @param string|array $params route as a string or route and parameters in form of ['route', 'param1' => 'value1', 'param2' => 'value2']
163 164
	 * @return string the created relative URL
	 */
165
	public function createUrl($params)
166
	{
167
		$params = (array)$params;
168 169
		$params[0] = $this->getNormalizedRoute($params[0]);
		return Yii::$app->getUrlManager()->createUrl($params);
170
	}
171

172 173 174 175 176 177 178 179 180 181 182 183 184 185
	/**
	 * Creates an absolute URL using the given route and parameters.
	 *
	 * This method enhances [[UrlManager::createAbsoluteUrl()]] by supporting relative routes.
	 * A relative route is a route without a leading slash, such as "view", "post/view".
	 *
	 * - 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.
	 *
186
	 * @param string|array $params route as a string or route and parameters in form of ['route', 'param1' => 'value1', 'param2' => 'value2']
187 188
	 * @param string $schema the schema to use for the url. e.g. 'http' or 'https'. If not specified
	 * the schema of the current request will be used.
189 190
	 * @return string the created absolute URL
	 */
191
	public function createAbsoluteUrl($params, $schema = null)
192
	{
193
		$params = (array)$params;
194 195
		$params[0] = $this->getNormalizedRoute($params[0]);
		return Yii::$app->getUrlManager()->createAbsoluteUrl($params, $schema);
196 197
	}

198 199 200 201 202 203 204 205 206
	/**
	 * 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
207
	 * @return string the canonical URL of the currently requested page
208 209 210
	 */
	public function getCanonicalUrl()
	{
211 212 213
		$params = $this->actionParams;
		$params[0] = $this->getRoute();
		return Yii::$app->getUrlManager()->createAbsoluteUrl($params);
214 215
	}

216 217 218 219
	/**
	 * Redirects the browser to the specified URL.
	 * This method is a shortcut to [[Response::redirect()]].
	 *
220 221 222 223 224 225 226
	 * 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
227 228 229 230
	 * @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
231
	 * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`)
Qiang Xue committed
232 233 234 235 236
	 *   [[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.
	 *
237
	 * @param integer $statusCode the HTTP status code. Defaults to 302.
Carsten Brandt committed
238
	 * See <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>
239
	 * for details about HTTP status code
Qiang Xue committed
240
	 * @return Response the current response object
241
	 */
242
	public function redirect($url, $statusCode = 302)
243
	{
244
		return Yii::$app->getResponse()->redirect(Html::url($url), $statusCode);
245 246
	}

Qiang Xue committed
247 248
	/**
	 * Redirects the browser to the home page.
249 250 251 252 253 254 255 256
	 *
	 * 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
257 258 259 260 261 262 263
	 * @return Response the current response object
	 */
	public function goHome()
	{
		return Yii::$app->getResponse()->redirect(Yii::$app->getHomeUrl());
	}

264 265
	/**
	 * Redirects the browser to the last visited page.
266 267 268 269 270 271 272 273
	 *
	 * 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();
	 * ```
	 *
274 275 276 277 278 279 280 281 282 283 284
	 * @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));
	}

285 286 287
	/**
	 * Refreshes the current page.
	 * This method is a shortcut to [[Response::refresh()]].
288 289 290 291 292 293 294 295
	 *
	 * 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();
	 * ```
	 *
296 297 298 299 300 301 302 303
	 * @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
304
}