Use Acl Component in a customer Helper - cakephp

I used acl component but i need check permission in a view. create a component where instance acl component.
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
class AccessComponent extends Component
{
var $components = array('Acl');
function checkHelper($aro, $aco, $action = "*")
{
//Importa los componentes de ACL
App::import('Component', 'Acl');
// Instancia una clase del componente
$acl = new AclComponent();
// returna el resultado del check
return $acl->check($aro, $aco, $action);
}
}
then i need pass the function a AccessHelper
<?php
namespace App\View\Helper;
use Cake\View\Helper;
use Cake\Event\Event;
use Cake\ORM\TableRegistry;
class AccessHelper extends Helper
{
// var $helpers = array("Session");
var $Access;
//var $Auth;
// var $user;
function beforeRender(Event $event)
{
App::import('Component', 'AccessComponent');
// App::uses('AccessComponent', 'Controller/Component');
$this->Access = new AccessComponent();
// var_dump($this->Access);
// App::import('Component', 'Auth');
//$this->Auth = new AuthComponent();
//$this->Auth->Session = $this->Session;
//$user = $this->request->getSession()->read('Auth');
}
function check($user, $aco, $action='*')
{
if(empty($user)) return false;
// Returna el metodo del check definido en el componente Access
return $this->Access->checkHelper($user['User']['id'], $aco, $action);
}
}
?>
the helper dont found AccessComponent. Give me null ...

Related

CakePHP3 - Cookie Value not being kept

I have a problem where the value for the cookie I set is not being kept if switching to a different section (controller) with CakePHP3.
I establish the original cookie in the AppController so it is sitewide:
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\Http\Cookie\Cookie;
use Cake\Http\Cookie\CookieCollection;
class AppController extends Controller
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Cookie');
//set up initial cart cookie
$this->response = $this->response->withCookie(
(new Cookie('cart'))
->withPath('/')
->withValue(json_encode([]))
->withExpiry(new \DateTime('+1 month'))
);
}
I then have it set up in the CartController to add selected items to the cart cookie:
<?php
// src/Controller/CartController.php
namespace App\Controller;
use Cake\I18n\Time;
use Cake\Http\Cookie\Cookie;
use Cake\Http\Cookie\CookieCollection;
class CartController extends AppController
{
public function index()
{
$cart = json_decode($this->request->getCookie('cart'));
$add_cart = ($this->request->getQuery('add') == null ? [] : $this->request->getQuery('add'));
if (count($add_cart) > 0) {
foreach($add_cart as $ac) {
if(!in_array($ac, $cart)) {
$cart[] = $ac;
}
}
}
//replace cookie
$this->response = $this->response->withCookie(
(new Cookie('cart'))
->withPath('/')
->withValue(json_encode($cart))
->withExpiry(new \DateTime('+1 month'))
);
$this->loadModel('Books');
$cart_items = [];
foreach($cart as $cartp) { //'contain' => ['BookTypes'],
$book = $this->Books->get($cartp, ['fields' => array('id','name','description')]);
$cart_items[] = $book;
}
$this->set(compact('cart_items'));
}
If I stay within "Cart", the cookie keeps the value. However, as soon as I move to any other page (home page or browsing books), the cookie value is reset to empty (an empty array).
What is causing this?
I found my problem.
Had to move the initial cookie from the initialize() to beforeFilter() in AppController.php and now it seems to be working.

associated data in Mailer in CakePHP 3

I'm working on CakePHP 3.4
I have a contact_messages table to save message via form on website.
I want to send user an email whenever a new message is saved.
For that, I have created mailer class like
<?php
namespace App\Mailer;
use Cake\Mailer\Mailer;
use Cake\Event\Event;
use Cake\Datasource\EntityInterface;
class ContactMessageMailer extends Mailer
{
public function newMessage($message)
{
$this
->setProfile('no-reply')
->setTemplate('new_message')
->setLayout('message')
->setEmailFormat('html')
->setTo($user->email) // user email
->setSubject('Verify Account')
->setViewVars(['name' => $user->first_name, 'email' => $user->email, 'message' => $message->body]);
}
public function implementedEvents()
{
return [
'Model.afterSave' => 'alertMessage'
];
}
public function alertMessage(Event $event, EntityInterface $entity, \ArrayObject $options)
{
if ($entity->isNew()) {
$this->send('newMessage', [$entity]);
}
}
}
and registering event in ContactMessagesTable.php
$mailer = new UserMailer(); //use App\Mailer\UserMailer;
$this->eventManager()->on($mailer);
ContactMessages belongsTo Users and Users is having email of user whom to send the email.
How can I get users information in Mailer?
Will probably do this;
In the User table;
public function processUser($user)
{
if($this->save($user)){
$event = new Event('Model.afterSave', $this, [$entity = $user])
$this->eventManager()->dispatch($event);
return true;
}else{
return false;
}
}
In ContactMessage Table ;
public function initialize()
{
parent::intialize();
$mailer = new UserMailer(); //use App\Mailer\UserMailer;
$this->Users->eventManager()->on($mailer); //ContactMessage has to be related to User table
}
Hope I was able to communicate.

Pass variable from controller to model (beforeSave) (Upload Field) CakePHP

I really need to know this issue to finish my work.
Here I'll give a example envolving model and controller.
I want to pass $final_name from controller to beforeSave() of my model
public function admin_add() {
if($this->request->is('post')) {
if($this->data['Client']['file']['tmp_name'] != '') {
// Upload block
$tmp_file = $this->data['Client']['file']['tmp_name'];
$file = new File($tmp_file);
if($file->mime() == "image/jpeg" or "image/png") {
$ext = explode('.', $this->data['Client']['file']['name']);
$name = md5($this->data['Client']['file']['name']);
$file->copy(IMG_DIR . 'portfolio\\' . $name . '.' . end($ext));
$final_name = $name . "." . end($ext); // File name with extension
}
// If save
if($this->Client->save($this->request->data)) {
$this->Session->setFlash('Client cadastrado com sucesso!', 'admin_flash');
}
}
}
}
In my client model
public function beforeSave($options = array()) {
if($this->data['Client']['file']['name'] != null) {
$this->data['Client']['file'] = $final_name;
}
return parent::beforeSave($options);
}
In Controller
$this->request->data['Client']['final_name'] = $name . "." . end($ext);
In Model
public function beforeSave($options = array()) {
if($this->data['Client']['file']['name'] != null) {
$this->data['Client']['file'] = $this->data['Client']['final_name'];
}
return parent::beforeSave($options);
}
Update for CakePHP3
Pass variable from controller to table beforeSave, afterSave ?
// Examples
// In Controller
$this->Article->save($data, ['passVariable' => 'passedData']);
// in Table
public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options)
{
if (isset($options['passVariable'])) {
// implement your code
}
}
Read more: https://api.cakephp.org/3.8/class-Cake.ORM.Table.html#_save
But good place to modify data before save like asked in question are:
https://book.cakephp.org/3.0/en/orm/saving-data.html#before-marshal or
https://book.cakephp.org/3.0/en/orm/entities.html#accessors-mutators

Create and save in component , from different controller to diffrent model.non-object error

TagController
public function view($id = null) {
if ($this->request->data != null) {
$this->Common->replyarticleAdd($this);
}
}
CommonComponent
/*
App::uses('Link', 'Model');
App::uses('User', 'Model');
App::uses('AppController', 'Controller');*/
I think , I should write it and it loads model but not effect.
ClassRegistry::init('Article');
App::uses('Article', 'Model');
ClassRegistry::init('Article');
App::uses('Article', 'Model');
class CommonComponent extends Component {
var $uses = array('Article');
public function replyarticleAdd($that = null) { // $this error can not re-assign.
debug($that->request->params['pass'][0]);
if ($that->request->params['pass'][0] != null) {
$this->Article->create(); // that is no effect
Error Call to a member function create() on a non-object
File: G:\pleiades\xampp\htdocs\cakephp\app\Controller\Component\CommonComponent.php
Line: 13 = $this->Article->create();
In controller create is ok but in component it cant. How can I do this?
In the component, try to work with the models this way:
App::uses('Article', 'Model');
$Article = new Article();
$Article->create();
Components do not have the $uses property, like controllers.
You can also use:
$Article = ClassRegistry::init('Article');
$Article->create();

Using session component in custom component

I'm trying to use Session component in custom component (CakePHP 2.3) but when I call Session component functions I get: Fatal error: Call to a member function read() on a non-object in ...\app\Controller\Component\CartComponent.php on line 7
My CartComponent looks like that:
<?php
App::uses('Component', 'Controller');
class CartComponent extends Component {
public $components = array('Session');
function hasItems() {
$cart = $this->Session->read('Cart');
return $cart != null && count($cart) > 0;
}
}
?>
And I use it in controller:
<?php
class OrdersController extends AppController {
public $name = 'Orders';
public $components = array('Cart', 'Email');
function beforeFilter() {
parent::beforeFilter();
if ($this->Cart->hasItems()) {
$this->Auth->allow('add_item', 'remove_item', 'cart');
} else {
$this->Auth->allow('add_item', 'remove_item', 'cart', 'make');
}
}
}
?>
For using session inside the custom component I tried with
public $components = array('Session');
and then called it by using
$this->Session->read('Cart');
but I cant able to use it and I start to use
CakeSession::read('Cart')
Now it works Hope it will used for you note I used in cake php version > 2
If you want to use Session in your Component Use-
$test = CakeSession::read('user');
print_r($test);
You should use as bellow
class YourComponent extends Component {
public function initialize(Controller $controller){
$this->controller = $controller;
if (!isset($this->controller->presetVars)) {
$this->controller->presetVars = true;
}
$model = $this->controller->modelClass;
if (!empty($settings['model'])) {
$model = $settings['model'];
}
if ($this->controller->presetVars === true) {
// auto-set the presetVars based on search definitions in model
$this->controller->presetVars = array();
$filterArgs = array();
if (!empty($this->controller->$model->filterArgs)) {
$filterArgs = $this->controller->$model->filterArgs;
}
foreach ($filterArgs as $key => $arg) {
if ($args = $this->_parseFromModel($arg, $key)) {
$this->controller->presetVars[] = $args;
}
}
}
foreach ($this->controller->presetVars as $key => $field) {
if ($field === true) {
if (isset($this->controller->$model->filterArgs[$key])) {
$field = $this->_parseFromModel($this->controller->$model->filterArgs[$key], $key);
} else {
$field = array('type' => 'value');
}
}
if (!isset($field['field'])) {
$field['field'] = $key;
}
$this->controller->presetVars[$key] = $field;
}
/* now you can use Component existing in your Component :) */
public function sayHello(){
$this->controller->Session->setFlash(__('Hello you'));
}
}

Resources