public function beforeDispatch(Event $event) { $event->stopPropagation(); $response = new Response(['body' => $this->config('message')]); $response->httpCodes([429 => 'Too Many Requests']); $response->statusCode(429); return $response; }
public function beforeSave(Event $event, Officer $officer, \ArrayObject $options) { if ($officer->isNew()) { return true; } if (!$officer->dirty('member_id')) { return true; } //Ensure no UI screwup tried to move "officer" record to different club $originalMemberId = $officer->getOriginal('member_id'); $memberId = $officer->get('member_id'); try { $originalMember = $this->Members->get($originalMemberId); $member = $this->Members->get($memberId); } catch (RecordNotFoundException $e) { $event->stopPropagation(); return false; } if ($originalMember->club_id != $member->club_id) { //Somehow messed up and attempting to switch Officer record to different club $event->stopPropagation(); return false; } return true; }
/** * Tests the event propagation stopping property * * @return void * @triggers fake.event */ public function testPropagation() { $event = new Event('fake.event'); $this->assertFalse($event->isStopped()); $event->stopPropagation(); $this->assertTrue($event->isStopped()); }
/** * Checks if deletion is allowed * * @param \Cake\Event\Event $event The beforeDelete event that was fired * @param \Cake\ORM\Entity $entity The entity that is going to be deleted * @param \ArrayObject $options the options passed to the delete method * @return void|false */ public function beforeDelete(Event $event, Entity $entity, ArrayObject $options) { if ($this->config('preventDeletion') === true || is_array($this->config('preventDeletion')) && in_array($entity->{$this->config('fields.key')}, $this->config('preventDeletion'))) { $event->stopPropagation(); return false; } }
/** * Checks if request is for a compiled asset, otherwise skip any operation * * @param Event $event containing the request and response object * @throws \Cake\Network\Exception\NotFoundException * @return \Cake\Network\Response|null Response if the client is requesting a recognized asset, null otherwise */ public function beforeDispatch(Event $event) { $request = $event->data['request']; $response = $event->data['response']; $config = $this->_getConfig(); $production = !Configure::read('debug'); if ($production && !$config->general('alwaysEnableController')) { return null; } // Make sure the request looks like an asset. $targetName = $this->getName($config, $request->url); if (!$targetName) { return null; } if (isset($request->query['theme'])) { $config->theme($request->query['theme']); } $factory = new Factory($config); $assets = $factory->assetCollection(); if (!$assets->contains($targetName)) { return null; } $build = $assets->get($targetName); try { $compiler = $factory->cachedCompiler(); $contents = $compiler->generate($build); } catch (Exception $e) { throw new NotFoundException($e->getMessage()); } $response->type($build->ext()); $response->body($contents); $event->stopPropagation(); return $response; }
/** * Checks whether the response was cached and set the body accordingly. * * @param \Cake\Event\Event $event containing the request and response object * @return \Cake\Network\Response with cached content if found, null otherwise */ public function beforeDispatch(Event $event) { if (Configure::read('Cache.check') !== true) { return; } $path = $event->data['request']->here(); if ($path === '/') { $path = 'home'; } $prefix = Configure::read('Cache.viewPrefix'); if ($prefix) { $path = $prefix . '_' . $path; } $path = strtolower(Inflector::slug($path)); $filename = CACHE . 'views/' . $path . '.php'; if (!file_exists($filename)) { $filename = CACHE . 'views/' . $path . '_index.php'; } if (file_exists($filename)) { $controller = null; $view = new View($controller); $view->response = $event->data['response']; $result = $view->renderCache($filename, microtime(true)); if ($result !== false) { $event->stopPropagation(); $event->data['response']->body($result); return $event->data['response']; } } }
/** * Checks if a requested cache file exists and sends it to the browser * * @param \Cake\Event\Event $event containing the request and response object * * @return \Cake\Network\Response|null Response if the client is requesting a recognized cache file, null otherwise */ public function beforeDispatch(Event $event) { if (Configure::read('Cache.check') === false) { return null; } /* @var \Cake\Network\Request $request */ $request = $event->data['request']; $url = $request->here(); $url = str_replace($request->base, '', $url); $file = $this->getFile($url); if ($file === null) { return null; } $cacheContent = $this->extractCacheContent($file); $cacheInfo = $this->extractCacheInfo($cacheContent); $cacheTime = $cacheInfo['time']; if ($cacheTime < time() && $cacheTime != 0) { unlink($file); return null; } /* @var \Cake\Network\Response $response */ $response = $event->data['response']; $event->stopPropagation(); $response->modified(filemtime($file)); if ($response->checkNotModified($request)) { return $response; } $pathSegments = explode('.', $file); $ext = array_pop($pathSegments); $this->_deliverCacheFile($request, $response, $file, $ext); return $response; }
public function beforeDispatch(Event $event) { if ($event->data['request']->url !== 'robots.txt') { return; } $event->stopPropagation(); return new Response(['body' => "User-Agent: *\nDisallow: /", 'status' => 200, 'type' => 'txt']); }
public function matchRoute(Event $event, array $url) { if (!isset($url['model']) || $url['model'] !== 'Wasabi/Cms.Pages') { return; } $RoutesTable = TableRegistry::get('Wasabi/Core.Routes'); $route = $RoutesTable->find()->select(['url'])->where(['model' => $url['model'], 'foreign_key' => $url['foreign_key'] ?? 0, 'language_id' => $url['language_id'] ?? 0, 'redirect_to IS' => null])->hydrate(false)->first(); if (!empty($route)) { $event->result = $route['url']; $event->stopPropagation(); } }
/** * beforeDispatch. * * @param Cake\Event\Event $event Event instance * @return mixed Cake\Network\Response when limit is reached, void otherwise */ public function beforeDispatch(Event $event) { $this->_setIdentifier($event->data['request']); $this->_initCache(); $this->_count = $this->_touch($event->data['request']); // client has not exceeded rate limit if ($this->_count <= $this->config('limit')) { $this->_setHeaders($event->data['response']); return; } // client has reached rate limit $event->stopPropagation(); $response = new Response(['body' => $this->config('message')]); $response->httpCodes([429 => 'Too Many Requests']); $response->statusCode(429); return $response; }
/** * MaintenanceMode::beforeDispatch() * * @param \Cake\Event\Event $event * @return \Cake\Network\Response|null */ public function beforeDispatch(Event $event) { /* @var \Cake\Http\ServerRequest $request */ $request = $event->data['request']; $ip = $request->clientIp(); $Maintenance = new Maintenance(); if (!$Maintenance->isMaintenanceMode($ip)) { return null; } $body = __d('setup', 'Maintenance work'); $body = $this->_body(); $event->data['response']->header('Retry-After', HOUR); $event->data['response']->statusCode(503); $event->data['response']->body($body); $event->stopPropagation(); return $event->data['response']; }
/** * Handler method that applies before dispatch. * * @param \Cake\Event\Event $event The event instance. * @return mixed */ public function handle(Event $event) { if (is_file(MAINTENANCE_CONFIG_FILE) && is_readable(MAINTENANCE_CONFIG_FILE)) { // stop event $event->stopPropagation(); $request = $event->data['request']; $response = $event->data['response']; $config = (require MAINTENANCE_CONFIG_FILE); $viewClass = $config['viewClass']; $view = new $viewClass($request, $response); $view->templatePath($config['templatePath']); $view->template($config['templateFile']); $view->layout($config['templateLayout']); $view->set('startAt', \Cake\I18n\Time::createFromFormat('YmdHis', $config['startAt'])); $view->set('endAt', \Cake\I18n\Time::createFromFormat('YmdHis', $config['endAt'])); $response->body($view->render()); return $response; } }
/** * Applies Routing and additionalParameters to the request to be dispatched. * If Routes have not been loaded they will be loaded, and config/routes.php will be run. * * @param \Cake\Event\Event $event containing the request, response and additional params * @return \Cake\Network\Response|null A response will be returned when a redirect route is encountered. */ public function beforeDispatch(Event $event) { $request = $event->data['request']; if (Router::getRequest(true) !== $request) { Router::setRequestInfo($request); } try { if (empty($request->params['controller'])) { $params = Router::parse($request->url, $request->method()); $request->addParams($params); } } catch (RedirectException $e) { $event->stopPropagation(); $response = $event->data['response']; $response->statusCode($e->getCode()); $response->header('Location', $e->getMessage()); return $response; } }
/** * Checks if a requested asset exists and sends it to the browser * * @param \Cake\Event\Event $event Event containing the request and response object * @return \Cake\Network\Response|null If the client is requesting a recognized asset, null otherwise * @throws \Cake\Network\Exception\NotFoundException When asset not found */ public function beforeDispatch(Event $event) { $request = $event->data['request']; $url = urldecode($request->url); if (strpos($url, '..') !== false || strpos($url, '.') === false) { return null; } $assetFile = $this->_getAssetFile($url); if ($assetFile === null || !file_exists($assetFile)) { return null; } $response = $event->data['response']; $event->stopPropagation(); $response->modified(filemtime($assetFile)); if ($response->checkNotModified($request)) { return $response; } $pathSegments = explode('.', $url); $ext = array_pop($pathSegments); return $this->_deliverAsset($request, $response, $assetFile, $ext); }
public function beforeUsersControllerSignIn(Event $event) { $controller = $event->subject(); $active = true; if ($controller->request->is('post')) { $userName = ''; if ($controller->request->data('username')) { $userName = $controller->request->data('username'); } if ($controller->request->data('email')) { $userName = $controller->request->data('email'); } if ($userName) { $active = $controller->Users->find('all', ['conditions' => ['Users.active' => true, 'OR' => ['Users.email' => $userName, 'Users.username' => $userName]]])->count(); } } if (!$active) { $event->stopPropagation(); return __d('passengers', 'Sorry, but your account has been not activated yet.'); } }
/** * Checks if a requested cache file exists and sends it to the browser * * @param \Cake\Event\Event $event containing the request and response object * @return \Cake\Network\Response if the client is requesting a recognized cache file, null otherwise */ public function beforeDispatch(Event $event) { if (Configure::read('Cache.check') === false) { return; } $request = $event->data['request']; $url = $request->here(); $file = $this->getFile($url); if ($file === null) { return; } $response = $event->data['response']; $event->stopPropagation(); $response->modified(filemtime($file)); if ($response->checkNotModified($request)) { return $response; } $pathSegments = explode('.', $file); $ext = array_pop($pathSegments); $this->_deliverCacheFile($request, $response, $file, $ext); return $response; }
/** * Delete file on server represented by entity being deleted */ public function beforeDelete(Event $event, Entity $entity, \ArrayObject $options) { Configure::load('UploadManager.uploads', 'default'); $storagePath = Configure::read('Uploads.storagePath'); $file = new File($entity->path); $folder = $file->Folder(); // Check for empty directories on successful delete if ($file->delete()) { // Delete type folder if empty if (!$folder->find()) { $oldFolder = $folder; $folder->cd($folder->realpath($folder->pwd() . DS . '..')); $oldFolder->delete(); // Check for other possible empty parent (owner storage) if ($folder->pwd() !== $storagePath) { if (!$folder->find()) { $folder->delete(); } } } } else { $event->stopPropagation(); } }
/** * Auxiliary function to help in stopPropagation testing * * @param \Cake\Event\Event $event * @return void */ public function stopListener($event) { $event->stopPropagation(); }
/** * Callback to never really delete a record but instead mark it as `trashed`. * * @param \Cake\Event\Event $event The beforeDelete event that was fired. * @param \Cake\Datasource\EntityInterface $entity The entity to be deleted. * @param \ArrayObject $options Options. * @return true * @throws \RuntimeException if fails to mark entity as `trashed`. */ public function beforeDelete(Event $event, EntityInterface $entity, ArrayObject $options) { if (!$this->trash($entity)) { throw new RuntimeException(); } $event->stopPropagation(); $event->subject()->dispatchEvent('Model.afterDelete', ['entity' => $entity, 'options' => $options]); return true; }
/** * Main execution method. Handles redirecting of invalid users, and processing * of login form data. * * @param \Cake\Event\Event $event The startup event. * @return void|\Cake\Network\Response */ public function startup(Event $event) { $controller = $event->subject(); $action = strtolower($controller->request->params['action']); if (!$controller->isAction($action)) { return; } $this->_setDefaults(); if ($this->_isAllowed($controller)) { return; } if (!$this->_getUser()) { $result = $this->_unauthenticated($controller); if ($result instanceof Response) { $event->stopPropagation(); } return $result; } if ($this->_isLoginAction($controller) || empty($this->_config['authorize']) || $this->isAuthorized($this->user())) { return; } $event->stopPropagation(); return $this->_unauthorized($controller); }
/** * beforeDelete callback * * @param \Cake\Event\Event $event * @param \Cake\Datasource\EntityInterface $entity * @param \ArrayAccess $options */ public function beforeDelete(Event $event, EntityInterface $entity, ArrayAccess $options) { if ($this->_deleteAllowed($entity)) { return true; } else { $event->stopPropagation(); return false; } }
/** * test * * @return void */ public function testLoginBeforeLoginReturningStoppedEvent() { $event = new Event('event'); $event->result = '/'; $event->stopPropagation(); $this->Trait->expects($this->at(0))->method('dispatchEvent')->with(UsersAuthComponent::EVENT_BEFORE_LOGIN)->will($this->returnValue($event)); $this->Trait->expects($this->once())->method('redirect')->with('/'); $this->Trait->login(); }
/** * @param \Cake\Event\Event $event The beforeSave event that was fired * @param \Cake\ORM\Entity $entity The entity that is going to be saved * @param \ArrayObject $options the options passed to the save method * @return void */ public function beforeSave(Event $event, Entity $entity, ArrayObject $options) { if ($this->_config['on'] === 'beforeSave') { if (!$this->geocode($entity)) { $event->stopPropagation(); } } }
/** * beforeDelete callback. * * @param \Cake\Event\Event $event Event. * @param \Cake\Datasource\EntityInterface $entity Entity. * @return bool */ public function beforeDelete(Event $event, EntityInterface $entity) { $discriminatorField = $this->_config['discriminatorField']; if ($entity->has($discriminatorField) && !$this->isAcceptedDiscriminator($entity->get($discriminatorField))) { $event->stopPropagation(); return false; } }
public function beforeDispatch(Event $event) { $event->data['response']->statusCode(500); $event->stopPropagation(); return $event->data['response']; }
/** * setFlash * * An API request doesn't need flash messages - so stop them being processed * * @param \Cake\Event\Event $event Event * @return void */ public function setFlash(Event $event) { if (!$this->config('setFlash')) { $event->stopPropagation(); } }
public function beforeExecute(Event $event, Job $job) { if ($this->_worker && ($this->_worker->status === WorkersTable::STATUS_SHUTDOWN || $this->_worker->status === WorkersTable::STATUS_TO_KILL)) { $event->stopPropagation(); return false; } cli_set_process_title(sprintf('DJ Worker :: %s :: Working %s', $this->_workerId, $job->getId())); $this->out(__('<success>Starting job:</success> {0} :: ', $job->getId()), 1, Shell::VERBOSE); $this->out(sprintf(' - <info>%s</info>', $job->getWorker()), 1, Shell::VERBOSE); $this->out(' - Executing job', 1, Shell::VERBOSE); $job->setHostName($this->_hostName); pcntl_signal_dispatch(); $this->_timeLastJob = microtime(true); return true; }
public function isMenuItemActive(Event $event, Request $request) { /** @var MenuItem $menuItem */ $menuItem = $event->subject(); $pageId = $menuItem->get('Pages')['id'] ?? null; if ($menuItem->foreign_model !== 'Wasabi/Cms.Pages' || $pageId === null) { return; } if ((int) $pageId === WasabiCms::page()->id) { $event->result = true; $event->stopPropagation(); } }
/** * Main execution method, handles initial authentication check and redirection * of invalid users. * * The auth check is done when event name is same as the one configured in * `checkAuthIn` config. * * @param \Cake\Event\Event $event Event instance. * @return \Cake\Network\Response|null */ public function authCheck(Event $event) { if ($this->_config['checkAuthIn'] !== $event->name()) { return null; } /* @var \Cake\Controller\Controller $controller */ $controller = $event->subject(); $action = strtolower($controller->request->params['action']); if (!$controller->isAction($action)) { return null; } $this->_setDefaults(); if ($this->_isAllowed($controller)) { return null; } $isLoginAction = $this->_isLoginAction($controller); if (!$this->_getUser()) { if ($isLoginAction) { return null; } $result = $this->_unauthenticated($controller); if ($result instanceof Response) { $event->stopPropagation(); } return $result; } if ($isLoginAction || empty($this->_config['authorize']) || $this->isAuthorized($this->user())) { return null; } $event->stopPropagation(); return $this->_unauthorized($controller); }
/** * Called before Controller::redirect(). Allows you to replace the URL that will * be redirected to with a new URL. * * @param \Cake\Event\Event $event Event * @param string|array $url Either the string or URL array that is being redirected to. * @param \Cake\Network\Response $response * @return void */ public function beforeRedirect(Event $event, $url, Response $response) { if (!$this->respondAsAjax || !$this->_config['resolveRedirect']) { return; } $url = Router::url($url, true); $status = $response->statusCode(); $response->statusCode(200); $this->Controller->autoRender = true; $this->Controller->set('_redirect', compact('url', 'status')); $serializeKeys = ['_redirect']; if (!empty($this->Controller->viewVars['_serialize'])) { $serializeKeys = array_merge($serializeKeys, $this->Controller->viewVars['_serialize']); } $this->Controller->set('_serialize', $serializeKeys); $event->stopPropagation(); }