/** * 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(); }
/** * 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->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(); }
/** * Authenticate user * * @param CakeRequest $request The request object * @param CakeResponse $response response object. * @return mixed. False on login failure. An array of User data on success. */ public function authenticate(CakeRequest $request, CakeResponse $response) { $user = $this->getUser($request); if (!$user) { $response->statusCode(401); $response->send(); } return $user; }
/** * 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 _deliverMedia(CakeResponse $response, $mediaFile, $mediaInfo) { $response->sharable(true, 2592000); //$response->mustRevalidate(true); $response->expires('+30 days'); $modTime = filemtime($mediaFile); $response->modified($modTime); $response->etag(md5($mediaFile . $modTime)); //$response->header("Pragma", "cache"); $response->type($mediaInfo['ext']); $response->file($mediaFile); $response->send(); }
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 } }
/** * Handles (fakes) redirects for Ajax requests using requestAction() * * @param Controller $controller A reference to the controller * @param string|array $url A string or array containing the redirect location * @param mixed $status HTTP Status for redirect * @param boolean $exit * @return void */ public function beforeRedirect($controller, $url, $status = null, $exit = true) { if (!$this->request->is('ajax')) { return; } foreach ($_POST as $key => $val) { unset($_POST[$key]); } if (is_array($url)) { $url = Router::url($url + array('base' => false)); } if (!empty($status)) { $statusCode = $this->response->httpCodes($status); $code = key($statusCode); $this->response->statusCode($code); } $this->response->body($this->requestAction($url, array('return', 'bare' => false))); $this->response->send(); $this->_stop(); }
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(); } }
/** * Handles (fakes) redirects for Ajax requests using requestAction() * Modifies the $_POST and $_SERVER['REQUEST_METHOD'] to simulate a new GET request. * * @param Controller $controller A reference to the controller * @param string|array $url A string or array containing the redirect location * @param int|array $status HTTP Status for redirect * @param bool $exit Whether to exit script, defaults to `true`. * * @return void */ public function beforeRedirect(Controller $controller, $url, $status = NULL, $exit = TRUE) { if (!$this->request->is('ajax')) { return; } if (empty($url)) { return; } $_SERVER['REQUEST_METHOD'] = 'GET'; foreach ($_POST as $key => $val) { unset($_POST[$key]); } if (is_array($url)) { $url = Router::url($url + array('base' => FALSE)); } if (!empty($status)) { $statusCode = $this->response->httpCodes($status); $code = key($statusCode); $this->response->statusCode($code); } $this->response->body($this->requestAction($url, array('return', 'bare' => FALSE))); $this->response->send(); $this->_stop(); }
/** * Sends an asset file to the client * * @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($assetFile, $ext) { ob_start(); $compressionEnabled = Configure::read('Asset.compress') && $this->response->compress(); if ($this->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'; } $this->response->type($contentType); } $this->response->cache(filemtime($assetFile)); $this->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(); }
/** * Dispatches and invokes given Request, handing over control to the involved controller. If the controller is set * to autoRender, via Controller::$autoRender, then Dispatcher will render the view. * * Actions in CakePHP can be any public method on a controller, that is not declared in Controller. If you * want controller methods to be public and in-accessible by URL, then prefix them with a `_`. * For example `public function _loadPosts() { }` would not be accessible via URL. Private and protected methods * are also not accessible via URL. * * If no controller of given name can be found, invoke() will throw an exception. * If the controller is found, and the action is not found an exception will be thrown. * * @param CakeRequest $request Request object to dispatch. * @param CakeResponse $response Response object to put the results of the dispatch into. * @param array $additionalParams Settings array ("bare", "return") which is melded with the GET and POST params * @return string|void if `$request['return']` is set then it returns response body, null otherwise * @throws MissingControllerException When the controller is missing. */ public function dispatch(CakeRequest $request, CakeResponse $response, $additionalParams = array()) { $beforeEvent = new CakeEvent('Dispatcher.beforeDispatch', $this, compact('request', 'response', 'additionalParams')); $this->getEventManager()->dispatch($beforeEvent); $request = $beforeEvent->data['request']; if ($beforeEvent->result instanceof CakeResponse) { if (isset($request->params['return'])) { return $response->body(); } $response->send(); return; } $controller = $this->_getController($request, $response); if (!$controller instanceof Controller) { throw new MissingControllerException(array('class' => Inflector::camelize($request->params['controller']) . 'Controller', 'plugin' => empty($request->params['plugin']) ? null : Inflector::camelize($request->params['plugin']))); } $response = $this->_invoke($controller, $request, $response); if (isset($request->params['return'])) { return $response->body(); } $afterEvent = new CakeEvent('Dispatcher.afterDispatch', $this, compact('request', 'response')); $this->getEventManager()->dispatch($afterEvent); $afterEvent->data['response']->send(); }
/** * Redirects to given $url, after turning off $this->autoRender. * Script execution is halted after the redirect. * * @param mixed $url A string or array-based URL pointing to another location within the app, * or an absolute URL * @param integer $status Optional HTTP status code (eg: 404) * @param boolean $exit If true, exit() will be called after the redirect * @return mixed void if $exit = false. Terminates script if $exit = true * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::redirect */ public function redirect($url, $status = null, $exit = true) { $this->autoRender = false; if (is_array($status)) { extract($status, EXTR_OVERWRITE); } $response = $this->Components->trigger( 'beforeRedirect', array(&$this, $url, $status, $exit), array('break' => true, 'breakOn' => false, 'collectReturn' => true) ); if ($response === false) { return; } extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE); $response = $this->beforeRedirect($url, $status, $exit); if ($response === false) { return; } extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE); if (function_exists('session_write_close')) { session_write_close(); } if (!empty($status) && is_string($status)) { $codes = array_flip($this->response->httpCodes()); if (isset($codes[$status])) { $status = $codes[$status]; } } if ($url !== null) { $this->response->header('Location', Router::url($url, true)); } if (!empty($status) && ($status >= 300 && $status < 400)) { $this->response->statusCode($status); } if ($exit) { $this->response->send(); $this->_stop(); } }
/** * Redirects to given $url, after turning off $this->autoRender. * Script execution is halted after the redirect. * * @param mixed $url A string or array-based URL pointing to another location within the app, * or an absolute URL * @param integer $status Optional HTTP status code (eg: 404) * @param boolean $exit If true, exit() will be called after the redirect * @return mixed void if $exit = false. Terminates script if $exit = true * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::redirect */ public function redirect($url, $status = null, $exit = true) { $this->autoRender = false; if (is_array($status)) { extract($status, EXTR_OVERWRITE); } $event = new CakeEvent('Controller.beforeRedirect', $this, array($url, $status, $exit)); //TODO: Remove the following line when the events are fully migrated to the CakeEventManager list($event->break, $event->breakOn, $event->collectReturn) = array(true, false, true); $this->getEventManager()->dispatch($event); if ($event->isStopped()) { return; } $response = $event->result; extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE); if (function_exists('session_write_close')) { session_write_close(); } if (!empty($status) && is_string($status)) { $codes = array_flip($this->response->httpCodes()); if (isset($codes[$status])) { $status = $codes[$status]; } } if ($url !== null) { $this->response->header('Location', Router::url($url, true)); } if (!empty($status) && ($status >= 300 && $status < 400)) { $this->response->statusCode($status); } if ($exit) { $this->response->send(); $this->_stop(); } }
/** * Redirects to given $url, after turning off $this->autoRender. * Script execution is halted after the redirect. * * @param string|array $url A string or array-based URL pointing to another location within the app, * or an absolute URL * @param int|array|null $status HTTP status code (eg: 301). Defaults to 302 when null is passed. * @param bool $exit If true, exit() will be called after the redirect * @return void * @triggers Controller.beforeRedirect $this, array($url, $status, $exit) * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::redirect */ public function redirect($url, $status = null, $exit = true) { $this->autoRender = false; if (is_array($status)) { extract($status, EXTR_OVERWRITE); } $event = new CakeEvent('Controller.beforeRedirect', $this, array($url, $status, $exit)); list($event->break, $event->breakOn, $event->collectReturn) = array(true, false, true); $this->getEventManager()->dispatch($event); if ($event->isStopped()) { return; } $response = $event->result; extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE); if ($url !== null) { $this->response->header('Location', Router::url($url, true)); } if (is_string($status)) { $codes = array_flip($this->response->httpCodes()); if (isset($codes[$status])) { $status = $codes[$status]; } } if ($status === null) { $status = 302; } $this->response->statusCode($status); if ($exit) { $this->response->send(); $this->_stop(); } }
/** * 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; }