public function init() { if (!$this->route instanceof Route) { throw new RouteException(RouteException::UNKNOWN_PROPERTY, ['name' => 'route']); } $this->request = Instance::ensure($this->request, Request::className()); }
protected function getGlobalsVars() { if ($this->request->isPost() && in_array('POST', $this->verbs, true)) { return Request::post(); } if ($this->request->isGet() && in_array('GET', $this->verbs, true)) { return Request::get(); } if ($this->request->isPut() && in_array('PUT', $this->verbs, true)) { return Request::post(); } if ($this->request->isDelete() && in_array('DELETE', $this->verbs, true)) { return Request::post(); } return []; }
public function get() { if (is_array($this->filters)) { $this->filters = Sanitize::rules($this->filters); } return Request::post($this->name, $this->default, $this->filters); }
public function actionLogout(User $user, CSRF $CSRF) { $valid = $CSRF->check(Request::get($CSRF->csrfParam)); if ($valid) { $user->logout(true); } $this->redirect(Url::set()->removeAllArgs()->getAbsolute())->send(true); }
private function prepareAliases(array $aliases) { foreach ($aliases as &$alias) { $placeholders = ['self_scheme' => $this->request->getScheme(), 'self_path' => $this->request->getUrlWithoutArgs()]; foreach ($this->request->rawGet() ?: [] as $name => $placeholder) { $placeholders["self_query_{$name}"] = $placeholder; } $alias = StringHelper::replace($alias, $placeholders, false); } return $aliases; }
/** * Match ips * * @param array $ips array data of access * @return bool */ protected function matchIps(array $ips) { // all ips if (in_array('*', $ips)) { return true; } $result = $this->request->isIps($ips); if (!$result && $this->sendHeaders && $this->response instanceof \rock\response\Response) { $this->response->status403(); } return $result; }
protected function asProtect($url, $host) { if (empty($this->_allowedDomains)) { if ($_host = $this->request->getHost()) { $this->_allowedDomains = [$_host]; } } if ($this->protect && isset($this->protectLink) && !in_array($host, $this->_allowedDomains, true)) { $this->protectLink = (array) $this->protectLink; if (!isset($this->protectLink['@scheme'])) { $this->protectLink['@scheme'] = self::ABS; } return static::modify($this->protectLink) . "?r={$url}"; } return $url; }
public function actionIndex(User $user, Session $session) { $placeholders = []; if ($session->hasFlash($this->keySessionFlash)) { $placeholders['content'] = i18n::t('successActivate'); return $this->render('success', $placeholders); } elseif ($user->isGuest() && ($users = Users::activate(Request::get('token')))) { // auto-login $user->addMulti($users->toArray(['id', 'username', 'url'])); $user->login(); $session->setFlash($this->keySessionFlash); $this->response->redirect(Url::set()->removeAllArgs()->getAbsoluteUrl(true))->send(true); return null; } return $this->notPage('@frontend.views/layouts/notPage'); }
/** * Returns items limit. * @param bool $recalculate * @return int */ public function getLimit($recalculate = false) { if ($this->limit === null || $recalculate) { if ($this->request instanceof Request) { $this->limit = $this->request->get($this->limitParam, $this->defaultLimit, Sanitize::positive()->int()); } else { $this->limit = isset($_GET[$this->limitParam]) ? (int) $_GET[$this->limitParam] : $this->defaultLimit; if ($this->limit < 0) { $this->limit = $this->defaultLimit; } } if ($this->limit > $this->maxLimit) { $this->limit = $this->maxLimit; } } return $this->limit; }
/** * {@inheritdoc} */ public function getAttributes($code = null) { if (!isset($code)) { $code = Request::get('code'); } if (empty($code)) { return []; } // This was a callback request from google, get the token $this->service->requestAccessToken($code); // Send a request with it try { return Json::decode($this->service->request($this->apiUrl)); } catch (JsonException $e) { if (class_exists('\\rock\\log\\Log')) { Log::err(BaseException::convertExceptionToString($e)); } } return []; }
protected function getParam() { if (empty($this->params)) { if ($this->request instanceof Request) { return $this->request->get($this->sortParam); } return isset($_GET[$this->sortParam]) ? strip_tags($_GET[$this->sortParam]) : null; } return isset($this->params[$this->sortParam]) ? strip_tags($this->params[$this->sortParam]) : null; }
/** * For each CORS headers create the specific response * * @param Request $request * @param array $requestHeaders CORS headers we have detected * @return array CORS headers ready to be sent */ public function prepareHeaders($request, $requestHeaders) { $responseHeaders = []; // handle Origin if (isset($requestHeaders['Origin'], $this->cors['Origin'])) { if (in_array('*', $this->cors['Origin']) || in_array($requestHeaders['Origin'], $this->cors['Origin'])) { $responseHeaders['Access-Control-Allow-Origin'] = $requestHeaders['Origin']; } } $this->prepareAllowHeaders('Headers', $requestHeaders, $responseHeaders); if (isset($requestHeaders['Access-Control-Request-Method'])) { $responseHeaders['Access-Control-Allow-Methods'] = implode(', ', $this->cors['Access-Control-Request-Method']); } if (isset($this->cors['Access-Control-Allow-Credentials'])) { $responseHeaders['Access-Control-Allow-Credentials'] = $this->cors['Access-Control-Allow-Credentials'] ? 'true' : 'false'; } if (isset($this->cors['Access-Control-Max-Age']) && $request->isOptions()) { $responseHeaders['Access-Control-Max-Age'] = $this->cors['Access-Control-Max-Age']; } if (isset($this->cors['Access-Control-Expose-Headers'])) { $responseHeaders['Access-Control-Expose-Headers'] = implode(', ', $this->cors['Access-Control-Expose-Headers']); } return $responseHeaders; }
/** * Returns the URL that the browser should be redirected to after successful login. * * This method reads the return URL from the session. It is usually used by the login action which * may call this method to redirect the browser to where it goes after successful authentication. * * @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, {@see \rock\request\Request::getHomeUrl()} will be redirected to. * @return string the URL that the user should be redirected to after login. */ public function getReturnUrl($defaultUrl = null) { $url = $this->storage->get($this->returnUrlParam, $defaultUrl); return $url === null ? $this->request->getHomeUrl() : Url::modify($url); }
/** * Returns a value indicating whether the current request has sent the session ID. * * The default implementation will check cookie and $_GET using the session name. * If you send session ID via other ways, you may need to override this method * or call {@see \rock\session\Session::setHasSessionId()} to explicitly set whether the session ID is sent. * @return boolean whether the current request has sent the session ID. */ public function getHasSessionId() { if ($this->_hasSessionId === null) { $name = $this->getName(); if (ini_get('session.use_cookies') && !empty($_COOKIE[$name])) { $this->_hasSessionId = true; } elseif (!ini_get('use_only_cookies') && ini_get('use_trans_sid')) { if ($name !== null) { if (class_exists('\\rock\\request\\Request')) { $this->_hasSessionId = (bool) Request::get($name); } else { $this->_hasSessionId = isset($_GET[$name]) && strip_tags($_GET[$name]); } } } else { $this->_hasSessionId = false; } } return $this->_hasSessionId; }
return !Rock::$app->user->isGuest(); } return \rock\helpers\ArrayHelper::getValue(Rock::$app->user->getAll(), $keys); }, 'call' => function (array $call, array $params = [], Template $template) { if (!isset($call[1])) { $call[1] = null; } list($class, $method) = $call; if ($class === 'context') { $object = $template->context; $function = [$object, $method]; } elseif (function_exists($class) && !$class instanceof \Closure) { return call_user_func_array($class, $params); } else { $object = \rock\di\Container::load($class); if (!method_exists($object, $method)) { throw new \rock\base\BaseException(\rock\base\BaseException::UNKNOWN_METHOD, ['method' => "{$class}::{$method}"]); } $function = [$object, $method]; } return call_user_func_array($function, $params); }], 'title' => 'Demo', 'metaTags' => ['charset' => '<meta charset="' . Rock::$app->charset . '" />'], 'linkTags' => ['favicon' => '<link rel="Shortcut Icon" type="image/x-icon" href="/favicon.ico?10">'], 'snippets' => ['request.get' => ['class' => \rock\snippets\request\Get::className()], 'request.post' => ['class' => \rock\snippets\request\Post::className()], 'csrf' => ['class' => \rock\snippets\CSRF::className()], 'captchaView' => ['class' => \rock\snippets\CaptchaView::className()], 'activeForm' => ['class' => \rock\snippets\ActiveForm::className()]]], 'execute' => ['class' => \rock\execute\CacheExecute::className()], 'i18n' => ['class' => \rock\i18n\i18n::className(), 'pathsDicts' => ['ru' => ['@rock/messages/ru/lang.php', '@rock/messages/ru/validate.php'], 'en' => ['@rock/messages/en/lang.php', '@rock/messages/en/validate.php']], 'locale' => [\rock\LocaleProperties::className(), 'locale']], 'date' => ['class' => \rock\date\DateTime::className(), 'locale' => [\rock\LocaleProperties::className(), 'locale'], 'formats' => ['dmy' => function (\rock\date\DateTime $dateTime) { $nowYear = date('Y'); $lastYear = $dateTime->format('Y'); return $nowYear > $lastYear ? $dateTime->format('j F Y') : $dateTime->format('d F'); }, 'dmyhm' => function (\rock\date\DateTime $dateTime) { $nowYear = date('Y'); $lastYear = $dateTime->format('Y'); return $nowYear > $lastYear ? $dateTime->format('j F Y H:i') : $dateTime->format('j F H:i'); }]], 'mail' => ['class' => \rock\mail\Mail::className(), 'From' => 'support@' . (new \rock\request\Request())->getHost(), 'FromName' => 'Rock Framework'], 'url' => ['class' => \rock\url\Url::className()], 'request' => ['class' => \rock\request\Request::className(), 'locale' => [\rock\LocaleProperties::className(), 'locale']], 'response' => ['class' => \rock\response\Response::className(), 'locale' => [\rock\LocaleProperties::className(), 'locale']], 'htmlResponseFormatter' => ['class' => \rock\response\HtmlResponseFormatter::className()], 'jsonResponseFormatter' => ['class' => \rock\response\JsonResponseFormatter::className()], 'xmlResponseFormatter' => ['class' => \rock\response\XmlResponseFormatter::className()], 'rssResponseFormatter' => ['class' => \rock\response\RssResponseFormatter::className()], 'session' => ['class' => \rock\session\Session::className(), 'cookieParams' => ['httponly' => true, 'lifetime' => 60 * 60 * 24 * 60, 'setUseCookies' => \rock\session\Session::USE_ONLY_COOKIES]], 'cookie' => ['class' => \rock\cookie\Cookie::className()], 'security' => ['class' => Security::className()], 'sanitize' => ['class' => \rock\sanitize\Sanitize::className()], 'validate' => ['class' => \rock\validate\Validate::className(), 'locale' => [\rock\LocaleProperties::className(), 'locale']], 'csrf' => ['class' => \rock\csrf\CSRF::className()], 'captcha' => ['class' => \rock\captcha\Captcha::className(), 'length' => 0, 'whiteNoiseDensity' => 1 / 6, 'blackNoiseDensity' => 1 / 30], 'user' => ['class' => \rock\user\User::className(), 'container' => 'user'], 'rbac' => ['class' => \rock\rbac\DBManager::className()], 'log' => ['class' => \rock\log\Log::className()], Role::className() => ['class' => Role::className()], Permission::className() => ['class' => Permission::className()]], require __DIR__ . '/widgets.php');
protected function calculateData() { $this->data = parse_url($this->request->getAbsoluteUrl()); }
/** * Negotiates the application language. * @param Request $request * @return string the chosen language */ protected function negotiateLanguage($request) { if (!empty($this->languageParam) && ($language = Request::get($this->languageParam)) !== null) { if (isset($this->languages[$language])) { return $this->languages[$language]; } foreach ($this->languages as $key => $supported) { if (is_integer($key) && $this->isLanguageSupported($language, $supported)) { return $supported; } } return $request->getPreferredLanguage(); //reset($this->languages); } foreach ($request->getAcceptableLanguages() as $language => $params) { if (isset($this->languages[$language])) { return $this->languages[$language]; } foreach ($this->languages as $key => $supported) { if (is_integer($key) && $this->isLanguageSupported($language, $supported)) { return $supported; } } } return $request->getPreferredLanguage(); //reset($this->languages); }
/** * Redirects the browser to the specified URL. * * This method adds a "Location" header to the current response. Note that it does not send out * the header until {@see \rock\response\Response::send()} is called. In a controller action you may use this method as follows: * * ```php * return Rock::$app->response->redirect($url); * ``` * * In other places, if you want to send out the "Location" header immediately, you should use * the following code: * * ```php * Rock::$app->response->redirect($url)->send(); * return; * ``` * * In AJAX mode, this normally will not work as expected unless there are some * client-side JavaScript code handling the redirection. To help achieve this goal, * this method will send out a "X-Redirect" header instead of "Location". * * If you use the "rock" JavaScript module, it will handle the AJAX redirection as * described above. Otherwise, you should write the following JavaScript code to * handle the redirection: * * ```js * $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest' * ``` * * @param string $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") * * Any relative URL will be converted into an absolute one by prepending it with the host info * of the current request. * * @param integer $statusCode the HTTP status code. Defaults to 302. * See @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html * for details about HTTP status code * @param boolean $checkAjax whether to specially handle AJAX (and PJAX) requests. Defaults to true, * meaning if the current request is an AJAX or PJAX request, then calling this method will cause the browser * to redirect to the given URL. If this is false, a `Location` header will be sent, which when received as * an AJAX/PJAX response, may NOT cause browser redirection. * @return static the response object itself */ public function redirect($url, $statusCode = 302, $checkAjax = true) { if (strpos($url, '/') === 0 && strpos($url, '//') !== 0) { $url = $this->request->getHostInfo() . $url; } if ($checkAjax) { if ($this->request->isPjax()) { $this->getHeaders()->set('X-Pjax-Url', $url); } elseif ($this->request->isAjax()) { $this->getHeaders()->set('X-Redirect', $url); } else { $this->getHeaders()->set('Location', $url); } } else { $this->getHeaders()->set('Location', $url); } $this->setStatusCode($statusCode); return $this; }
/** * @return array the names of the requested fields. The first element is an array * representing the list of default fields requested, while the second element is * an array of the extra fields requested in addition to the default fields. * @see Model::fields() * @see Model::extraFields() */ protected function getRequestedFields() { $fields = Request::get($this->fieldsParam); $exclude = Request::get($this->excludeParam); return [preg_split('/\\s*,\\s*/', $fields, -1, PREG_SPLIT_NO_EMPTY), preg_split('/\\s*,\\s*/', $exclude, -1, PREG_SPLIT_NO_EMPTY)]; }
/** * Run mode debug. * * @param Response $response * @return Run */ protected static function debuger(Response $response = null) { $run = new Run(); if (isset($response)) { switch ($response->format) { case Response::FORMAT_JSON: $handler = new JsonResponseHandler(); break; case Response::FORMAT_XML: $handler = new XmlResponseHandler(); break; default: $request = new Request(); if ($request->isAjax() || $request->isCORS()) { $handler = new JsonResponseHandler(); } else { $handler = new PrettyPageHandler(); } } $run->setSendHttpCode(500); $response->setStatusCode(500); $response->send(); } else { $handler = new PrettyPageHandler(); } $run->pushHandler($handler); //$run->register(); return $run; }
protected function convertResponse(ResponseInterface $psrResponse, Request $request) { $request->setContentType($psrResponse->getHeaderLine('Content-Type')); $this->response->request = $request; $this->response->version = $psrResponse->getProtocolVersion(); $this->response->setStatusCode($psrResponse->getStatusCode(), $psrResponse->getReasonPhrase()); foreach ($psrResponse->getHeaders() as $name => $value) { $this->response->getHeaders()->setDefault($name, $value); } $this->response->content = $psrResponse->getBody()->getContents(); return $this->response; }