PHP Class cake\controller\ Controller Code Examples

PHP cake\controller\Controller - 30 examples found. These are the top rated real world PHP examples of class cake\controller\Controller extracted from open source projects. You can rate examples to help us improve the quality of examples
Provides basic functionality, such as rendering views inside layouts, automatic model availability, redirection, callbacks, and more. Controllers should provide a number of 'action' methods. These are public methods on a controller that are not inherited from Controller. Each action serves as an endpoint for performing a specific action on a resource or collection of resources. For example adding or editing a new object, or listing a set of objects. You can access request parameters, using $this->request. The request object contains all the POST, GET and FILES that were part of the request. After performing the required action, controllers are responsible for creating a response. This usually takes the form of a generated View, or possibly a redirection to another URL. In either case $this->response allows you to manipulate all aspects of the response. Controllers are created by Dispatcher based on request parameters and routing. By default controllers and actions use conventional names. For example /posts/index maps to PostsController::index(). You can re-map URLs using Router::connect() or RouterBuilder::connect(). ### Life cycle callbacks CakePHP fires a number of life cycle callbacks during each request. By implementing a method you can receive the related events. The available callbacks are: - beforeFilter(Event $event) Called before each action. This is a good place to do general logic that applies to all actions. - beforeRender(Event $event) Called before the view is rendered. - beforeRedirect(Event $event, $url, Response $response) Called before a redirect is done. - afterFilter(Event $event) Called after each action is complete and after the view is rendered.
Inheritance: implements Cake\Event\EventListenerInterface, implements Cake\Event\EventDispatcherInterface, use trait Cake\Event\EventDispatcherTrait, use trait Cake\ORM\Locator\LocatorAwareTrait, use trait Cake\Log\LogTrait, use trait Cake\Utility\MergeVariablesTrait, use trait Cake\Datasource\ModelAwareTrait, use trait Cake\Routing\RequestActionTrait, use trait Cake\View\ViewVarsTrait
 /**
  * Constructor.
  *
  * @param \Cake\Controller\Controller $Controller Controller instance.
  */
 public function __construct(Controller $Controller = null)
 {
     if ($Controller) {
         $this->_Controller = $Controller;
         $this->eventManager($Controller->eventManager());
     }
 }
Example #2
0
 /**
  * Set the language for the user.
  *
  * @return void
  */
 public function setLanguage()
 {
     if ($this->_controller->Auth->user()) {
         //The user has already a valid language defined in the database.
         if ($this->_session->read('Auth.User.language') && isset($this->_locales[$this->_session->read('Auth.User.language')])) {
             //If the user has not the cookie, we set the cookie.
             if (!$this->_cookie->check('language') || $this->_cookie->read('language') != $this->_session->read('Auth.User.language')) {
                 $this->_cookie->write('language', $this->_session->read('Auth.User.language'));
             }
             //Stock the locale of the user.
             $this->_locale = $this->_session->read('Auth.User.language');
         }
     } else {
         //The user has a valid cookie.
         if ($this->_cookie->check('language') && isset($this->_locales[$this->_cookie->read('language')])) {
             $this->_locale = $this->_cookie->read('language');
         }
     }
     //The user want to change his language.
     if (isset($this->_controller->request->params['lang']) && isset($this->_locales[$this->_controller->request->params['lang']])) {
         //If the user is connected, we need to save the new language in the database and refresh his session.
         if ($this->_controller->Auth->user()) {
             $this->_controller->loadModel('Users');
             $user = $this->_controller->Users->find()->where(['id' => $this->_session->read('Auth.User.id')])->first();
             $user->language = $this->_controller->request->params['lang'];
             $this->_controller->Users->save($user);
             $this->_session->write('Auth.User.language', $this->_controller->request->params['lang']);
         }
         //Save the new language in the cookie.
         $this->_cookie->write('language', $this->_controller->request->params['lang']);
         $this->_locale = $this->_controller->request->params['lang'];
     }
     //Set the locale.
     I18n::locale($this->_locale);
 }
 /**
  * Constructor.
  *
  * @param \Cake\Controller\Controller $Controller
  */
 public function __construct(Controller $Controller = null)
 {
     if ($Controller) {
         $this->_Controller = $Controller;
         $this->_eventManager = $Controller->getEventManager();
     } else {
         $this->_eventManager = new EventManager();
     }
 }
 /**
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     Configure::write('App.namespace', 'TestApp');
     $this->Controller = new CacheComponentTestController();
     $this->Controller->startupProcess();
     $this->Controller->request->session()->delete('CacheMessage');
     $this->Controller->Cache->config('debug', true);
 }
Example #5
0
 /**
  * test that component components are not enabled in the collection.
  *
  * @return void
  */
 public function testInnerComponentsAreNotEnabled()
 {
     $mock = $this->getMock('Cake\\Event\\EventManager');
     $controller = new Controller();
     $controller->eventManager($mock);
     $mock->expects($this->once())->method('on')->with($this->isInstanceOf('TestApp\\Controller\\Component\\AppleComponent'));
     $Collection = new ComponentRegistry($controller);
     $Apple = $Collection->load('Apple');
     $this->assertInstanceOf('TestApp\\Controller\\Component\\OrangeComponent', $Apple->Orange, 'class is wrong');
 }
 /**
  * @return void
  */
 public function testPaginate()
 {
     Configure::write('Paginator.limit', 2);
     $ToolsUser = TableRegistry::get('ToolsUsers');
     $count = $ToolsUser->find('count');
     $this->assertTrue($count > 3);
     $this->Controller->loadModel('ToolsUsers');
     $result = $this->Controller->paginate('ToolsUsers');
     $this->assertSame(2, count($result->toArray()));
 }
 protected function _createSitemap($type)
 {
     $this->_type = $type;
     //$this->controller->autoRender = false;
     $this->controller->viewClass = 'Sitemap.SitemapXml';
     $this->controller->viewBuilder()->autoLayout(false);
     //@TODO Set response parameters from SitemapXml view
     $this->controller->response->type('application/xml');
     $this->controller->response->cache(mktime(0, 0, 0, date('m'), date('d'), date('Y')), $this->cache);
 }
 /**
  * maintenance redirect logic
  *
  * @return mixed|void
  */
 public function beforeFilter()
 {
     if (defined('PHPUNIT_TESTSUITE')) {
         return;
     }
     $maintenancePage = Environment::read('MAINTENANCE_PAGE_REDIRECT_URL');
     $currentUrl = $this->request->here;
     $accessibleUrls = explode('|', Environment::read('MAINTENANCE_ACCESSIBLE_URLS'));
     $accessibleUrls[] = $maintenancePage;
     if (!self::isMaintenanceActive()) {
         // if maintenance is not active but maintenance page is requested -> redirect to default page
         if (in_array($currentUrl, $accessibleUrls) && substr($maintenancePage, -strlen($currentUrl)) === $currentUrl) {
             $maintenanceBasePage = Environment::read('MAINTENANCE_BASE_URL');
             return $this->_controller->redirect($maintenanceBasePage);
         }
         return;
     }
     $cookieName = Environment::read('MAINTENANCE_COOKIE_NAME');
     $cookieExists = $this->_controller->Cookie->read($cookieName) != null;
     if ($cookieExists) {
         return;
     }
     $headerActive = Environment::read('MAINTENANCE_HEADER_ACTIVE');
     $headerName = Environment::read('MAINTENANCE_HEADER_NAME');
     $headerValue = Environment::read('MAINTENANCE_HEADER_VALUE');
     $successUrl = Environment::read('MAINTENANCE_PASSWORD_SUCCESS_URL');
     if ($headerActive && !empty($this->request->header($headerName)) && $this->request->header($headerName) == $headerValue) {
         $this->_controller->Cookie->write($cookieName, true);
         return $this->_controller->redirect($successUrl);
     }
     $passwordUrl = Environment::read('MAINTENANCE_PASSWORD_URL');
     $accessibleUrls[] = $passwordUrl;
     if (!in_array($currentUrl, $accessibleUrls)) {
         return $this->_controller->redirect($maintenancePage);
     } elseif ($currentUrl != $passwordUrl) {
         return;
     }
     $user = Environment::read('MAINTENANCE_USER');
     $password = Environment::read('MAINTENANCE_PASSWORD');
     if ($currentUrl == $passwordUrl) {
         if (!isset($_SERVER['PHP_AUTH_USER'])) {
             header('WWW-Authenticate: Basic realm="Maintenance Realm"');
             header('HTTP/1.0 401 Unauthorized');
             echo 'Unauthorized';
             exit;
         } else {
             if ($_SERVER['PHP_AUTH_USER'] == $user && $_SERVER['PHP_AUTH_PW'] == $password) {
                 $this->_controller->Cookie->write($cookieName, true);
                 return $this->_controller->redirect($successUrl);
             }
             return $this->_controller->redirect($maintenancePage);
         }
     }
     return $this->_controller->redirect($maintenancePage);
 }
Example #9
0
 protected function _render($name, $view, $layout, $viewVars)
 {
     $request = new Request();
     $response = new Response();
     $controller = new Controller($request, $response);
     $controller->name = $name;
     $controller->layout = $layout;
     $controller->viewPath = $name;
     $controller->viewClass = 'Gourmet\\Liquid\\View\\View';
     $controller->set($viewVars);
     return $controller->createView()->render($view);
 }
 protected function _getView($viewVars = [])
 {
     $Request = new Request();
     $Response = new Response();
     $Controller = new Controller($Request, $Response);
     $builder = $Controller->viewBuilder();
     $builder->className('JsonApi\\View\\JsonApiView');
     if ($viewVars) {
         $Controller->set($viewVars);
     }
     return $Controller->createView();
 }
 /**
  * {@inheritDoc}
  */
 protected function _getController()
 {
     if (!($request = Router::getRequest(true))) {
         $request = new Request();
     }
     $response = new Response();
     try {
         $controller = new TestAppsErrorController($request, $response);
         $controller->viewBuilder()->layout('banana');
     } catch (\Exception $e) {
         $controller = new Controller($request, $response);
         $controller->viewBuilder()->templatePath('Error');
     }
     return $controller;
 }
Example #12
0
 /**
  * Initialization hook method.
  *
  * Use this method to add common initialization code like loading components.
  *
  * e.g. `$this->loadComponent('Security');`
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     $this->loadComponent('RequestHandler');
     $this->loadComponent('Flash');
     $this->loadComponent('Auth', ['loginAction' => ['controller' => 'Users', 'action' => 'login'], 'authError' => 'Did you really think you are allowed to see that?', 'authenticate' => ['Form' => []], 'storage' => 'Session']);
 }
Example #13
0
 /**
  * Initialization hook method.
  *
  * Use this method to add common initialization code like loading components.
  *
  * e.g. `$this->loadComponent('Security');`
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     $this->loadComponent('RequestHandler');
     $this->loadComponent('Flash');
     $this->loadComponent('Auth', ['authorize' => ['Controller'], 'authenticate' => ['Form' => ['fields' => ['username' => 'email', 'password' => 'password'], 'finder' => 'auth']], 'loginAction' => ['controller' => 'Users', 'action' => 'login'], 'authError' => 'Ingrese sus datos', 'loginRedirect' => ['controller' => 'Users', 'action' => 'home'], 'logoutRedirect' => ['controller' => 'Users', 'action' => 'login'], 'unauthorizedRedirect' => $this->referer()]);
 }
Example #14
0
 /**
  * Initialization hook method.
  *
  * Use this method to add common initialization code like loading components.
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     $this->helpers[] = 'Shrink.Shrink';
     $this->loadComponent('Auth', ['authorize' => 'Controller', 'authenticate' => ['Form' => ['fields' => ['username' => 'email', 'password' => 'password']]], 'loginAction' => ['controller' => 'CustomStaticPages', 'action' => 'index'], 'logoutAction' => ['controller' => 'CustomStaticPages', 'action' => 'index']]);
     //$this->Auth->allow();
 }
Example #15
0
 public function initialize()
 {
     parent::initialize();
     $this->loadComponent('RequestHandler');
     $this->loadComponent('Flash');
     $this->loadComponent('Auth', ['authorize' => ['Controller'], 'loginRedirect' => ['controller' => 'Associations', 'action' => 'init'], 'logoutRedirect' => ['controller' => 'Pages', 'action' => 'home']]);
 }
Example #16
0
 /**
  * Initialization hook method.
  *
  * Use this method to add common initialization code like loading components.
  *
  * e.g. `$this->loadComponent('Security');`
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     $this->loadComponent('RequestHandler');
     $this->loadComponent('Flash');
     $this->loadComponent('Auth', ['authorize' => ['Controller'], 'loginRedirect' => ['prefix' => false, 'controller' => 'Home', 'action' => 'index'], 'logoutRedirect' => ['prefix' => false, 'controller' => 'Users', 'action' => 'login']]);
 }
Example #17
0
 /**
  * Initialization hook method.
  *
  * Use this method to add common initialization code like loading components.
  *
  * e.g. `$this->loadComponent('Security');`
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     $this->loadComponent('RequestHandler');
     $this->loadComponent('Flash');
     $this->initConfiguration();
 }
Example #18
0
 /**
  * Initialization hook method.
  *
  * Use this method to add common initialization code like loading components.
  *
  * e.g. `$this->loadComponent('Security');`
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     // $this->loadComponent('RequestHandler');
     $this->loadComponent('Flash');
     $this->loadComponent('Auth', ['authorize' => ['Controller'], 'loginRedirect' => ['controller' => 'IndocreatorAdmin', 'action' => 'index'], 'logoutRedirect' => ['controller' => 'IndocreatorAdmin', 'action' => 'display', 'home']]);
 }
 /**
  * Initialization hook method.
  *
  * Use this method to add common initialization code like loading components.
  *
  * e.g. `$this->loadComponent('Security');`
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     $this->loadComponent('RequestHandler');
     $this->loadComponent('Flash');
     $this->loadComponent('Auth', ['loginRedirect' => '/admin', 'authError' => 'Você possivelmente digitou suas credenciais erradas!', 'logoutRedirect' => ['prefix' => false, 'controller' => 'Pages', 'action' => 'display', 'home']]);
 }
 public function beforeFilter(Event $event)
 {
     parent::beforeFilter($event);
     $this->Auth->config('authError', "Désolé, vous n'êtes pas autorisés à accéder à cette zone.");
     $this->Auth->allow(['add', 'login']);
     $this->set('dataUser', $this->Auth->user());
 }
 /**
  * SetupComponent::log404()
  *
  * @param bool $notifyAdminOnInternalErrors
  * @return void
  */
 public function log404($notifyAdminOnInternalErrors = false)
 {
     if ($this->Controller->name === 'CakeError') {
         $referer = $this->Controller->referer();
         $this->Controller->log('REF: ' . $referer . ' - URL: ' . $this->Controller->request->url, '404');
     }
 }
Example #22
0
 /**
  * Initialization hook method.
  *
  * Use this method to add common initialization code like loading components.
  *
  * e.g. `$this->loadComponent('Security');`
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     $this->loadComponent('RequestHandler');
     $this->loadComponent('Flash');
     $this->loadComponent('Auth', ['authenticate' => ['Form' => ['userModel' => 'Users']]]);
 }
Example #23
0
 /**
  * Initialization hook method.
  *
  * Use this method to add common initialization code like loading components.
  *
  * e.g. `$this->loadComponent('Security');`
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     $this->loadComponent('RequestHandler');
     $this->loadComponent('Flash');
     $this->loadComponent('Auth', ['loginRedirect' => ['controller' => 'Articles', 'action' => 'index'], 'logoutRedirect' => ['controller' => 'Pages', 'action' => 'display', 'home']]);
 }
Example #24
0
 /**
  * Initialization hook method.
  *
  * Use this method to add common initialization code like loading components.
  *
  * e.g. `$this->loadComponent('Security');`
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     $this->loadComponent('RequestHandler');
     $this->loadComponent('Flash');
     $this->loadComponent('Auth', ['authorize' => ['Controller'], 'authenticate' => ['Form' => ['fields' => ['username' => 'username', 'password' => 'password']]], 'loginRedirect' => ['controller' => 'Projects', 'action' => 'index'], 'logoutRedirect' => ['controller' => 'Projects', 'action' => 'index']]);
 }
Example #25
0
 /**
  * Initialization hook method.
  *
  * Use this method to add common initialization code like loading components.
  *
  * e.g. `$this->loadComponent('Security');`
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     $this->loadComponent('RequestHandler');
     $this->loadComponent('Flash');
     $this->loadComponent('Auth', ['authenticate' => ['Form' => ['fields' => ['username' => 'username', 'password' => 'password'], 'userModel' => 'usuario']], 'loginAction' => ['controller' => 'Usuario', 'action' => 'login'], 'loginRedirect' => ['controller' => 'Usuario', 'action' => 'index'], 'logoutRedirect' => ['controller' => 'Usuario', 'action' => 'logout'], 'authError' => "Debes ingresar con tu cuenta de usuario."]);
 }
 /**
  * Initialization hook method.
  *
  * Use this method to add common initialization code like loading components.
  *
  * e.g. `$this->loadComponent('Security');`
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     $this->loadComponent('RequestHandler');
     $this->loadComponent('Flash');
     $this->loadComponent('CakeDC/Users.UsersAuth');
 }
Example #27
0
 public function beforeFilter(Event $event)
 {
     parent::beforeFilter($event);
     $authUser = $this->Auth->user();
     $this->set(compact('authUser'));
     $this->Auth->allow(['index', 'login', 'logout', 'register']);
 }
 /**
  * Creates a validation object on the fly.
  *
  * @return \Cake\Validation\Validator
  */
 protected function _createValidator()
 {
     $config = $this->config();
     if ($config['validator'] instanceof Validator) {
         return $config['validator'];
     }
     $this->_controller->loadModel('Comment.Comments');
     if ($this->_controller->request->is('userLoggedIn')) {
         // logged user posting
         $validator = $this->_controller->Comments->validationDefault(new Validator());
         $validator->requirePresence('user_id')->notEmpty('user_id', __d('comment', 'Invalid user.'))->add('user_id', 'checkUserId', ['rule' => function ($value, $context) {
             if (!empty($value)) {
                 $valid = TableRegistry::get('User.Users')->find()->where(['Users.id' => $value, 'Users.status' => 1])->count() === 1;
                 return $valid;
             }
             return false;
         }, 'message' => __d('comment', 'Invalid user, please try again.'), 'provider' => 'table']);
     } elseif ($this->config('settings.allow_anonymous')) {
         // anonymous user posting
         $validator = $this->_controller->Comments->validator('anonymous');
     } else {
         // other case
         $validator = new Validator();
     }
     if ($this->config('settings.use_captcha')) {
         $validator->add('body', 'humanCheck', ['rule' => function ($value, $context) {
             return CaptchaManager::adapter()->validate($this->_controller->request);
         }, 'message' => __d('comment', 'We were not able to verify you as human. Please try again.'), 'provider' => 'table']);
     }
     return $validator;
 }
 public function beforeFilter(Event $event)
 {
     parent::beforeFilter($event);
     //$this->Auth->allow(['view', 'index', 'checkExistence', 'edit',
     //'delete', 'add', 'twit', 'twit1', 'mention','token', 'getMention', 'mentionToDB']);
     $this->Auth->allow(['token', 'getMention']);
 }
Example #30
0
 /**
  * Initialization hook method.
  *
  * Use this method to add common initialization code like loading components.
  *
  * e.g. `$this->loadComponent('Security');`
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     $this->loadComponent('RequestHandler');
     $this->loadComponent('Crud.Crud', ['actions' => ['Crud.Index', 'Crud.View', 'Crud.Add', 'Crud.Edit', 'Crud.Delete'], 'listeners' => ['Crud.Api', 'Crud.ApiPagination', 'Crud.ApiQueryLog']]);
     $this->loadComponent('Auth', ['storage' => 'Memory', 'authenticate' => ['Form' => ['scope' => ['Users.active' => 1], 'fields' => ['username' => 'email', 'password' => 'password']], 'ADmad/JwtAuth.Jwt' => ['parameter' => 'token', 'userModel' => 'Users', 'scope' => ['Users.active' => 1], 'fields' => ['username' => 'id'], 'queryDatasource' => true]], 'unauthorizedRedirect' => false, 'checkAuthIn' => 'Controller.initialize', 'authorize' => ['Controller']]);
 }