/** * Parses a string url into an array. Parsed urls will result in an automatic * redirection * * @param string $url The url to parse * @return boolean False on failure */ public function parse($url) { $params = parent::parse($url); if (!$params) { return false; } if (!$this->response) { $this->response = new CakeResponse(); } $redirect = $this->defaults; if (count($this->defaults) == 1 && !isset($this->defaults['controller'])) { $redirect = $this->defaults[0]; } if (isset($this->options['persist']) && is_array($redirect)) { $argOptions['context'] = array('action' => $redirect['action'], 'controller' => $redirect['controller']); $args = Router::getArgs($params['_args_'], $argOptions); $redirect += $args['pass']; $redirect += $args['named']; } $status = 301; if (isset($this->options['status']) && ($this->options['status'] >= 300 && $this->options['status'] < 400)) { $status = $this->options['status']; } $this->response->header(array('Location' => Router::url($redirect, true))); $this->response->statusCode($status); $this->response->send(); }
/** * Parses a string url into an array. Parsed urls will result in an automatic * redirection * * @param string $url The url to parse * @return boolean False on failure */ public function parse($url) { $params = parent::parse($url); if ($params === false) { return false; } $Domains = new Domains(); $subdomain = $Domains->getSubdomain(); $masterDomain = Configure::read('Domain.Master'); $defaultRoute = Configure::read('Domain.DefaultRoute'); $Tenant = new Tenant(); if (!$Tenant->domainExists($subdomain) && $params != $defaultRoute) { if (!$this->response) { $this->response = new CakeResponse(); } debug($this->response); die; $status = 307; $redirect = $defaultRoute; $this->response->header(array('Location' => Router::url($redirect, true))); $this->response->statusCode($status); $this->response->send(); $this->_stop(); } return $subdomain; }
/** * Parses a string url into an array. Parsed urls will result in an automatic * redirection * * @param string $url The url to parse * @return boolean False on failure */ public function parse($url) { $params = parent::parse($url); if (!$params) { return false; } if (!$this->response) { $this->response = new CakeResponse(); } $redirect = $this->redirect; if (count($this->redirect) == 1 && !isset($this->redirect['controller'])) { $redirect = $this->redirect[0]; } if (isset($this->options['persist']) && is_array($redirect)) { $redirect += array('named' => $params['named'], 'pass' => $params['pass'], 'url' => array()); $redirect = Router::reverse($redirect); } $status = 301; if (isset($this->options['status']) && ($this->options['status'] >= 300 && $this->options['status'] < 400)) { $status = $this->options['status']; } $this->response->header(array('Location' => Router::url($redirect, true))); $this->response->statusCode($status); $this->response->send(); $this->_stop(); }
public function authenticate(CakeRequest $request, CakeResponse $response) { $provider = new Stevenmaguire\OAuth2\Client\Provider\Bitbucket(array('clientId' => Configure::read('OAuth.bitbucket_consumer_key'), 'clientSecret' => Configure::read('OAuth.bitbucket_consumer_secret'), 'redirectUri' => Configure::read('OAuth.redirect_uri'))); $session = new CakeSession(); if (!isset($request->query['code'])) { $response->header('Location', $provider->getAuthorizationUrl()); } else { try { $token = $provider->getAccessToken('authorization_code', array('code' => $request->query['code'])); } catch (Exception $e) { return false; } $resourceOwner = $provider->getResourceOwner($token)->toArray(); App::uses('User', 'Model'); $User = new User(); $data = array('User' => array('account_type' => 'bitbucket', 'username' => $resourceOwner['username'], 'display_name' => $resourceOwner['display_name'], 'bitbucket_uuid' => $resourceOwner['uuid'], 'oauth_access_token' => $token->getToken(), 'oauth_refresh_token' => $token->getRefreshToken(), 'oauth_token_expires_in' => $token->getExpires())); $existingUser = $User->find('first', array('conditions' => array('User.bitbucket_uuid' => $resourceOwner['uuid']))); if (!$existingUser) { $User->create(); } else { $data['User']['id'] = $existingUser['User']['id']; } $User->save($data); return $data['User']; } return false; }
/** * Authenticate a user using basic HTTP auth. Will use the configured User model and attempt a * login using basic HTTP auth. * * @param CakeRequest $request The request to authenticate with. * @param CakeResponse $response The response to add headers to. * @return mixed Either false on failure, or an array of user data on success. */ public function authenticate(CakeRequest $request, CakeResponse $response) { $result = $this->getUser($request); if (empty($result)) { $response->header($this->loginHeaders()); $response->statusCode(401); $response->send(); return false; } return $result; }
protected function _fetch($facebook, $access_oauth_token, CakeResponse $response) { try { // get user infomation from Facebook $user_id = $facebook->getUser(); $me = $facebook->api('/me'); $user = $this->_Collection->Auth->user(); $user['Member']["user_id"] = $me['id']; $user['Member']["user_name"] = $me['name']; $user['Member']["access_oauth_token"] = $access_oauth_token; if ($this->_Collection->Auth->login($user)) { $loginRedirect = $this->_Collection->Auth->loginRedirect; $response->header('Location', $loginRedirect); $response->send(); } } catch (OAuthException $E) { //you can catch OAuth exception } }
/** * * @param CakeRequest $request * @param CakeResponse $response * @return boolean */ public function authenticate(CakeRequest $request, CakeResponse $response) { $oauth = ClassRegistry::init('Twim.TwimOauth'); /* @var $oauth TwimOauth */ if (!empty($request->data['Twitter']['login'])) { // redirect to twitter $requestToken = $oauth->getRequestToken(); $redirectUrl = $this->settings['authenticate'] ? $oauth->getAuthenticateUrl($requestToken) : $oauth->getAuthorizeUrl($requestToken); $response->header('Location', $redirectUrl); } elseif (isset($request->query['oauth_token']) && isset($request->query['oauth_verifier'])) { // get access token $verifier = array_intersect_key($request->query, array('oauth_token' => true, 'oauth_verifier' => true)); $accessToken = $oauth->getAccessToken($verifier); if ($this->settings['userModel'] === false) { return $accessToken; } // save user data return $this->saveToModel($accessToken); } return false; }
protected function _deliver(CakeResponse $response, Asset $asset) { ob_start(); $compressionEnabled = Configure::read('Asset.compress') && $response->compress(); if ($response->type($asset->extension()) == $asset->extension()) { $contentType = 'application/octet-stream'; $agent = env('HTTP_USER_AGENT'); if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) { $contentType = 'application/octetstream'; } $response->type($contentType); } if (!$compressionEnabled) { $response->header('Content-Length', $asset->size()); } $response->cache(filemtime($asset->file)); $response->send(); ob_clean(); echo $asset->content(); if ($compressionEnabled) { ob_end_flush(); } }
protected function _getController($exception) { if (!($request = Router::getRequest(true))) { $request = new CakeRequest(); } $response = new CakeResponse(); if (method_exists($exception, 'responseHeader')) { $response->header($exception->responseHeader()); } try { $controller = new AppErrorController($request, $response); $controller->startupProcess(); } catch (Exception $e) { if (!empty($controller) && $controller->Components->enabled('RequestHandler')) { $controller->RequestHandler->startup($controller); } } if (empty($controller)) { $controller = new Controller($request, $response); $controller->viewPath = 'Errors'; } return $controller; }
/** * Sends an asset file to the client * * @param CakeResponse $response The response object to use. * @param string $assetFile Path to the asset file in the file system * @param string $ext The extension of the file to determine its mime type * @return void */ protected function _deliverAsset(CakeResponse $response, $assetFile, $ext) { ob_start(); $compressionEnabled = Configure::read('Asset.compress') && $response->compress(); if ($response->type($ext) == $ext) { $contentType = 'application/octet-stream'; $agent = env('HTTP_USER_AGENT'); if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) { $contentType = 'application/octetstream'; } $response->type($contentType); } if (!$compressionEnabled) { $response->header('Content-Length', filesize($assetFile)); } $response->cache(filemtime($assetFile)); $response->send(); ob_clean(); if ($ext === 'css' || $ext === 'js') { include $assetFile; } else { readfile($assetFile); } if ($compressionEnabled) { ob_end_flush(); } }
/** * Tests setting of public/private Cache-Control directives * * @return void */ public function testSharable() { $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); $this->assertNull($response->sharable()); $response->sharable(true); $headers = $response->header(); $this->assertEquals('public', $headers['Cache-Control']); $response->expects($this->at(1))->method('_sendHeader')->with('Cache-Control', 'public'); $response->send(); $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); $response->sharable(false); $headers = $response->header(); $this->assertEquals('private', $headers['Cache-Control']); $response->expects($this->at(1))->method('_sendHeader')->with('Cache-Control', 'private'); $response->send(); $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); $response->sharable(true); $headers = $response->header(); $this->assertEquals('public', $headers['Cache-Control']); $response->sharable(false); $headers = $response->header(); $this->assertEquals('private', $headers['Cache-Control']); $response->expects($this->at(1))->method('_sendHeader')->with('Cache-Control', 'private'); $response->send(); $this->assertFalse($response->sharable()); $response->sharable(true); $this->assertTrue($response->sharable()); $response = new CakeResponse(); $response->sharable(true, 3600); $headers = $response->header(); $this->assertEquals('public, s-maxage=3600', $headers['Cache-Control']); $response = new CakeResponse(); $response->sharable(false, 3600); $headers = $response->header(); $this->assertEquals('private, max-age=3600', $headers['Cache-Control']); $response->send(); }
/** * Tests the download method * */ public function testDownload() { $response = new CakeResponse(); $expected = array( 'Content-Disposition' => 'attachment; filename="myfile.mp3"' ); $response->download('myfile.mp3'); $this->assertEquals($response->header(), $expected); }
/** * Get the controller instance to handle the exception. * Override this method in subclasses to customize the controller used. * This method returns the built in `CakeErrorController` normally, or if an error is repeated * a bare controller will be used. * * @param Exception $exception The exception to get a controller for. * @return Controller */ protected function _getController($exception) { App::uses('AppController', 'Controller'); App::uses('CakeErrorController', 'Controller'); if (!($request = Router::getRequest(true))) { $request = new CakeRequest(); } $response = new CakeResponse(); if (method_exists($exception, 'responseHeader')) { $response->header($exception->responseHeader()); } if (class_exists('AppController')) { try { $controller = new CakeErrorController($request, $response); $controller->startupProcess(); $startup = true; } catch (Exception $e) { $startup = false; } // Retry RequestHandler, as another aspect of startupProcess() // could have failed. Ignore any exceptions out of startup, as // there could be userland input data parsers. if ($startup === false && !empty($controller) && $controller->Components->enabled('RequestHandler')) { try { $controller->RequestHandler->startup($controller); } catch (Exception $e) { } } } if (empty($controller)) { $controller = new Controller($request, $response); $controller->viewPath = 'Errors'; } return $controller; }
/** * Display or download the given file * * @param string $view Not used * @param string $layout Not used * @return mixed * @throws NotFoundException */ public function render($view = null, $layout = null) { $name = $download = $extension = $id = $modified = $path = $cache = $mimeType = $compress = null; extract($this->viewVars, EXTR_OVERWRITE); if (is_dir($path)) { $path = $path . $id; } else { $path = APP . $path . $id; } if (!is_file($path)) { if (Configure::read('debug')) { throw new NotFoundException(sprintf('The requested file %s was not found', $path)); } throw new NotFoundException('The requested file was not found'); } if (is_array($mimeType)) { $this->response->type($mimeType); } if (isset($extension) && $this->_isActive()) { $extension = strtolower($extension); $chunkSize = 8192; $buffer = ''; $fileSize = @filesize($path); $handle = fopen($path, 'rb'); if ($handle === false) { return false; } if (!empty($modified) && !is_numeric($modified)) { $modified = strtotime($modified, time()); } else { $modified = time(); } if ($this->response->type($extension) === false) { $download = true; } if ($cache) { $this->response->cache($modified, $cache); } else { $this->response->header(array('Date' => gmdate('D, d M Y H:i:s', time()) . ' GMT', 'Expires' => '0', 'Cache-Control' => 'private, must-revalidate, post-check=0, pre-check=0', 'Pragma' => 'no-cache')); } if ($download) { $agent = env('HTTP_USER_AGENT'); if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent)) { $contentType = 'application/octetstream'; } else { if (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) { $contentType = 'application/force-download'; } } if (!empty($contentType)) { $this->response->type($contentType); } if (is_null($name)) { $name = $id; } $this->response->download($name); $this->response->header(array('Accept-Ranges' => 'bytes')); $httpRange = env('HTTP_RANGE'); if (isset($httpRange)) { list($toss, $range) = explode('=', $httpRange); $size = $fileSize - 1; $length = $fileSize - $range; $this->response->header(array('Content-Length' => $length, 'Content-Range' => 'bytes ' . $range . $size . '/' . $fileSize)); $this->response->statusCode(206); fseek($handle, $range); } else { $this->response->header('Content-Length', $fileSize); } } else { $this->response->header(array('Content-Length' => $fileSize)); } $this->_clearBuffer(); if ($compress) { $this->_compressionEnabled = $this->response->compress(); } $this->response->send(); return $this->_sendFile($handle); } return false; }
/** * Get the controller instance to handle the exception. * Override this method in subclasses to customize the controller used. * This method returns the built in `CakeErrorController` normally, or if an error is repeated * a bare controller will be used. * * @param Exception $exception The exception to get a controller for. * @return Controller */ protected function _getController($exception) { App::uses('CakeErrorController', 'Controller'); if (!($request = Router::getRequest(true))) { $request = new CakeRequest(); } $response = new CakeResponse(); if (method_exists($exception, 'responseHeader')) { $response->header($exception->responseHeader()); } try { if (class_exists('AppController')) { $controller = new CakeErrorController($request, $response); } } catch (Exception $e) { } if (empty($controller)) { $controller = new Controller($request, $response); $controller->viewPath = 'Errors'; } return $controller; }
/** * Convenience and object wrapper method for CakeResponse::header(). * * @param string $status The header message that is being set. * @return void * @deprecated 3.0.0 Will be removed in 3.0. Use CakeResponse::header(). */ public function header($status) { $this->response->header($status); }
public function unauthenticated(CakeRequest $request, CakeResponse $response) { $response->header('location: ' . $request->base . "/pages/login"); }