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 afterCasAuthenticate(Event $event) { $user = $event->data(); if (empty($user['username'])) { return null; } if (!array_key_exists('id', $user)) { $user['id'] = $user['username']; } $localUser = TableRegistry::get('Users')->findOrCreateByNetid($user['username'], true); //force PersonSummary update check if (empty($localUser)) { return null; } $user['id'] = $localUser->id; if (empty($user['name']) && !empty($localUser->name)) { $user['name'] = $localUser->name; } if (empty($user['byuId']) && !empty($localUser->byu_id)) { $user['byuId'] = $localUser->byu_id; } $user['officers'] = TableRegistry::get('Officers')->listUserActive($localUser->id); $user['advisors'] = TableRegistry::get('Advisors')->listUserApproved($localUser->id); $user['members'] = TableRegistry::get('Members')->listActiveClubs($localUser->id); $user['roles'] = TableRegistry::get('Roles')->listByUser($localUser->id); $user['roles']['dean'] = TableRegistry::get('Departments')->listByDean($user['username']); $homePrefixes = ['admin', 'dean', 'risk', 'review']; //roles that have a default home, in descending preference order foreach ($homePrefixes as $prefix) { if (!empty($user['roles'][$prefix])) { $user['default_home'] = ['prefix' => $prefix, 'controller' => 'clubs', 'action' => 'index']; } } return $user; }
/** * Send an activation link on success registered user * @param Event $event */ public function onSuccessRegister(Event $event) { $controller = $event->subject(); $user = $event->data['user']; $controller->_sendActivationEmail($user)->template('Bazibartar.register')->subject('فعال سازی حساب کاربری')->send(); $controller->Flash->success(__d('users', 'you are success register, and an activation email has been send, check your email')); }
/** * 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; }
/** * Startup callback. * * @param Event $event */ public function startup(Event $event) { if (!$event->subject()->isAdmin()) { $this->__setForLayout(); $this->__createModules(); } }
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; }
/** * Data collection callback. * * @param \Cake\Event\Event $event The shutdown event. * @return void */ public function shutdown(Event $event) { /* @var Controller $controller */ $controller = $event->subject(); $request = $controller->request; $this->_data = ['params' => $request->params, 'query' => $request->query, 'data' => $request->data, 'cookie' => $request->cookies, 'get' => $_GET, 'matchedRoute' => $request->param('_matchedRoute'), 'headers' => ['response' => headers_sent($file, $line), 'file' => $file, 'line' => $line]]; }
/** * beforeFilter initTabsItems * * @param Cake/Event/Event $event Event * @return void */ public function beforeFiler(Event $event) { $this->setController($event->subject()); if (method_exists($this->Controller, 'initTabsItems')) { $this->Controller->initTabsItems($event); } }
/** * Method that adds footer element to the Layout. * * @param Cake\Event\Event $event Event object * @return void */ public function getFooter(Event $event) { if (!$event->subject()->elementExists(static::ELEMENT_FOOTER)) { return; } $event->result = $event->subject()->element(static::ELEMENT_FOOTER); }
/** * Callback * * @param \Cake\Event\Event $event * @return \Cake\Network\Response|array|null */ public function beforeFilter(Event $event) { $this->Controller = $event->subject(); if (!$this->config('enabled')) { return null; } if ($actions = $this->config('actions')) { $action = !empty($this->Controller->request->params['action']) ? $this->Controller->request->params['action'] : ''; if (!in_array($action, $actions)) { return null; } } $this->Controller->request->params['isJson'] = isset($this->Controller->request->params['url']['_ext']) && $this->Controller->request->params['url']['_ext'] === 'json'; $modelName = $this->config('modelName'); if (empty($modelName)) { $modelName = $this->Controller->modelClass; } list(, $modelName) = pluginSplit($modelName); $this->config('modelName', $modelName); if (!$this->Controller->{$modelName}->behaviors()->has('Ratable')) { $this->Controller->{$modelName}->behaviors()->load('Ratings.Ratable', $this->_config); } $this->Controller->helpers[] = 'Ratings.Rating'; $params = $this->request->data + $this->request->query + $this->_config['params']; if (!method_exists($this->Controller, 'rate')) { if (isset($params['rate']) && isset($params['rating'])) { $userId = $this->config('userId') ?: $this->Controller->Auth->user($this->config('userIdField')); return $this->rate($params['rate'], $params['rating'], $userId, $params['redirect']); } } }
/** * 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()); }
/** * Shutdown event * * @param \Cake\Event\Event $event The event * @return void */ public function shutdown(Event $event) { $controller = $event->subject(); $errors = []; array_walk_recursive($controller->viewVars, function (&$item) { // Execute queries so we can show the results in the toolbar. if ($item instanceof Query) { $item = $item->all(); } if ($item instanceof Closure || $item instanceof PDO || $item instanceof SimpleXmlElement) { $item = 'Unserializable object - ' . get_class($item); } if ($item instanceof Exception) { $item = sprintf('Unserializable object - %s. Error: %s in %s, line %s', get_class($item), $item->getMessage(), $item->getFile(), $item->getLine()); } return $item; }); foreach ($controller->viewVars as $k => $v) { // Get the validation errors for Entity if ($v instanceof EntityInterface) { $errors[$k] = $this->_getErrors($v); } elseif ($v instanceof Form) { $formError = $v->errors(); if (!empty($formError)) { $errors[$k] = $formError; } } } $this->_data = ['content' => $controller->viewVars, 'errors' => $errors]; }
public function injectEditor(Event $event, $layoutFile) { $_view = $event->subject(); $content = $_view->fetch('content'); if (Configure::read('Editorial.autoload')) { $searchClass = Configure::read('Editorial.autoload'); if (empty($searchClass)) { $searchClass = 'editor'; } $plugin = Configure::read('Editorial.editor'); list($vendor, $class) = $this->vendorSplit($plugin); $searchRegex = '/(<textarea.*class\\=\\".*' . Configure::read('Editorial.class') . '.*\\"[^>]*>.*<\\/textarea>)/isU'; //preg_match_all($searchRegex, $content, $matches); //debug($matches); if (Plugin::loaded($plugin) !== false && preg_match_all($searchRegex, $content, $matches)) { if (!$_view->helpers()->has('Editor')) { $options['className'] = $class . '.' . $class; if ($vendor) { $options['className'] = $vendor . '/' . $options['className']; } $options['options'] = $plugin . '.defaults'; if ($editorDefaults = Configure::read('Editorial.' . $class . '.defaults')) { $options['options'] = $editorDefaults; } $_view->loadHelper('Editor', $options); $_view->Editor->initialize(); } $_view->Editor->connect($content); } } }
/** * Hook admin actions * @param Event $event */ public function onBeforeAdminTemplateStructure(Event $event) { $this->_View = $view = $event->subject(); $this->__hookAdminActions(); $this->__hookAdminBoxes(); $this->__hookAdminForms(); }
/** * Data collection callback. * * @param \Cake\Event\Event $event The shutdown event. * @return void */ public function shutdown(Event $event) { $controller = $event->subject(); /* @var \Cake\Network\Request $request */ $request = $controller ? $controller->request : null; $this->_data = ['matchedRoute' => $request ? $request->param('_matchedRoute') : null]; }
/** * 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; }
/** * shutdown callback * * @param \Cake\Event\Event $event The event * @return array */ public function shutdown(Event $event) { $request = $event->subject()->request; if ($request) { $this->_data = ['content' => $request->session()->read()]; } }
/** * Check * * @param \Cake\Event\Event $event The beforeFind event that was fired. * @param \Cake\ORM\Query $query Query * @param \ArrayObject $options The options for the query * @return void */ public function checkRecordAccess(Event $event, Query $query, ArrayObject $options) { $table = TableRegistry::get('RolesCapabilities.Capabilities'); // current request parameters $request = $table->getCurrentRequest(); // skip if current model does not match request's model if (array_diff(pluginSplit($event->subject()->registryAlias()), [$request['plugin'], $request['controller']])) { return; } // get capability owner type identifier $type = $table->getTypeOwner(); // get user's action capabilities $userActionCapabilities = $table->getUserActionCapabilities(); // skip if no user's action capabilities found or no user's action // owner specific capabilities found for current request's action if (empty($userActionCapabilities)) { return; } if (!isset($userActionCapabilities[$request['plugin']][$request['controller']][$request['action']][$type])) { return; } // set query where clause based on user's owner capabilities assignment fields foreach ($userActionCapabilities[$request['plugin']][$request['controller']][$request['action']][$type] as $userActionCapability) { $query->where([$userActionCapability->getField() => $table->getCurrentUser('id')]); } }
/** * Method that prepares entity to run through pretiffy logic. * * @param \Cake\ORM\Entity $entity Entity * @param \Cake\Event\Event $event Event instance * @return void */ protected function _prettifyEntity(Entity $entity, Event $event) { if (!in_array($event->subject()->request->query('format'), [static::FORMAT_PRETTY])) { return; } $this->_prettify($entity, $event->subject()->{$event->subject()->name}, []); }
/** * Shutdown event * * @param \Cake\Event\Event $event The event * @return void */ public function shutdown(Event $event) { $controller = $event->subject(); $errors = []; $walker = function (&$item) use(&$walker) { if ($item instanceof Query || $item instanceof ResultSet) { $item = $item->toArray(); } elseif ($item instanceof Closure || $item instanceof PDO || $item instanceof SimpleXmlElement) { $item = 'Unserializable object - ' . get_class($item); } elseif ($item instanceof Exception) { $item = sprintf('Unserializable object - %s. Error: %s in %s, line %s', get_class($item), $item->getMessage(), $item->getFile(), $item->getLine()); } elseif (is_object($item) && method_exists($item, '__debugInfo')) { // Convert objects into using __debugInfo. $item = array_map($walker, $item->__debugInfo()); } return $item; }; // Copy so viewVars is not mutated. $vars = $controller->viewVars; array_walk_recursive($vars, $walker); foreach ($vars as $k => $v) { // Get the validation errors for Entity if ($v instanceof EntityInterface) { $errors[$k] = $this->_getErrors($v); } elseif ($v instanceof Form) { $formError = $v->errors(); if (!empty($formError)) { $errors[$k] = $formError; } } } $this->_data = ['content' => $vars, 'errors' => $errors]; }
/** * 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; } }
/** * On setup application. * * @param CakeEvent $event * @return void */ public function onSetup(CakeEvent $event) { /** @var \Union\Core\Controller\AppController $controller */ $controller = $event->subject(); if ($controller->App->isAdmin()) { $this->_onSetupAdmin(); } }
/** * On plugin config action. * * @param Event $event * @return void */ public function onConfig(Event $event) { /** @var AppController $controller */ $controller = $event->subject(); /** @var \Union\Community\Model\Table\RolesTable $roleTable */ $roleTable = TableRegistry::get('Union/Community.Roles'); $controller->set('roles', $roleTable->getTreeList()); }
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 afterRules(Cake\Event\Event $event, Cat $entity, \ArrayObject $options, $result, $operation) { Log::write("debug", "afterRules"); Log::write("debug", $event->name()); Log::write("debug", "entity " . $entity); Log::write("debug", $options); Log::write("debug", "result " . $result); Log::write("debug", "operation " . $operation); }
/** * There is only one event handler, it can be configured to be called for any event * * @param \Cake\Event\Event $event Event instance. * @param \Cake\Datasource\EntityInterface $entity Entity instance. * @throws \UnexpectedValueException if a field's when value is misdefined * @return true (irrespective of the behavior logic, the save will not be prevented) * @throws \UnexpectedValueException When the value for an event is not 'always', 'new' or 'existing' */ public function handleEvent(Event $event, EntityInterface $entity) { $eventName = $event->name(); $events = $this->_config['events']; if ($events[$eventName] === true) { $this->_purify($entity); } return true; }
public function construct(Event $event) { // @codingStandardsIgnoreEnd // @codingStandardsIgnoreStart // CakePHP specific tags $event->subject()->getTwig()->addTokenParser(new TokenParser\Cell()); $event->subject()->getTwig()->addTokenParser(new TokenParser\Element()); // @codingStandardsIgnoreEnd }
/** * getMyHead method * * In case we're operating with dynamic CSV tables, * we want to overwrite the page title to be used as moduleAlias(). * * @param Cake\Event\Event $event used for getting reports * @return void */ public function getMyHead(Event $event) { $table = TableRegistry::get($event->subject()->request['controller']); if ($table) { if (method_exists($table, 'moduleAlias') && is_callable([$table, 'moduleAlias'])) { $event->subject()->assign('title', $table->moduleAlias()); } } }
/** * Shutdown callback * * @param \Cake\Event\Event $event The event. * * @return void */ public function shutdown(Event $event) { /** * @var $controller Controller; */ $controller = $event->subject(); if ($controller instanceof RequestsController) { $this->_injectScriptsAndStyles($controller->response); } }