AppController.php 11.7 KB
<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link      http://cakephp.org CakePHP(tm) Project
 * @since     0.2.9
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\ORM\TableRegistry;
use Cake\Mailer\Email;
use Cake\Core\Configure;

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @link http://book.cakephp.org/3.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller
{

    /**
     * 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('LdapAuth', [
        		'authorize' => ['Controller'],
        		'loginRedirect' => [
        				'controller' => 'Pages',
        				'action' => 'home'
        		],
        		'logoutRedirect' => [
        				'controller' => 'Pages',
        				'action' => 'home',
        		]
        ]);
    }
    
    
    /**
     * @param $user
     * 
     * Give authorization in general
     * 
     * @return boolean
     */
    public function isAuthorized($user)
    {
    	$configuration = TableRegistry::get('Configurations')->find()->where(['id =' => 1])->first();
    	$role = TableRegistry::get('Users')->find()->where(['username' => $user[$configuration->authentificationType_ldap][0]])->first()['role'];
    	
    	$action = $this->request->params['action'];
    	
    	//error_log($action);
    	
    	// Super-Admin peut accéder à chaque action
    	if($role == 'Super Administrateur') return true;
    
    	//Pour tout le monde
    	if (in_array($action, ['index', 'find', 'view', 'creer', 'add', 'getNextDate'])) return true;
    	
    	
    	// Par défaut refuser
    	return false;
    }
    
    function userHasRole($roleDefine) {
    	
    	$configuration = TableRegistry::get('Configurations')->find()->where(['id =' => 1])->first();
    	$role = TableRegistry::get('Users')->find()->where(['username' => $this->LdapAuth->user($configuration->authentificationType_ldap)[0]])->first()['role'];
    	
    	$isAuthorized = false;
    	
    	switch($roleDefine) {
    		case 'Super Administrateur':
				if(in_array($role, ['Super Administrateur'])) $isAuthorized = true;
    			break;
    			
    		case 'Administration Plus':
    			if(in_array($role, ['Administration Plus', 'Super Administrateur'])) $isAuthorized = true;
    			break;
    			
    		case 'Administration':
    			if(in_array($role, ['Administration', 'Administration Plus', 'Super Administrateur'])) $isAuthorized = true;
    			break;
    				
    		case 'Responsable':
    			if(in_array($role, ['Responsable', 'Administration', 'Administration Plus', 'Super Administrateur'])) $isAuthorized = true;
    			break;
    					
    		case 'Utilisateur':
    			if(in_array($role, ['Utilisateur', 'Responsable', 'Administration', 'Administration Plus', 'Super Administrateur'])) $isAuthorized = true;
    			break;
    	}
    	
    	return $isAuthorized;
    }
    

    /**
     * {@inheritDoc}
     * @see \Cake\Controller\Controller::beforeFilter()
     */
    public function beforeFilter(Event $event)
    {
    	//!!! Ne jamais autoriser l'action 'login', sinon cela va créer des problèmes sur le fonctionnement normal de AuthComponent (cf doc) !!!
    	
    	$configuration = TableRegistry::get('Configurations')->find()->where(['id =' => 1])->first();
    	
    	if($configuration->mode_install) {
    		$this->LdapAuth->allow(['display', 'add', 'edit', 'installOff']);
    	}
    	else {
    		$this->LdapAuth->allow(['display']);
    	}
    	
    	$this->LdapAuth->config('authError', "Désolé, vous n'êtes pas autorisés à accéder à cette zone.");
    }
    
    public function afterFilter(Event $event)
    {  
        if(in_array($this->request->params['action'], ['edit', 'add'])) {
        	$this->request->session()->write("retourForm1", true);
        }  
        else if($this->request->params['action'] != 'creer') {
        	$this->request->session()->write("retourForm1", false);
        }
    }
    
    /**
     * Before render callback.
     *
     * @param \Cake\Event\Event $event The beforeRender event.
     * @return void
     */
    public function beforeRender(Event $event)
    {
        if (!array_key_exists('_serialize', $this->viewVars) &&
            in_array($this->response->type(), ['application/json', 'application/xml'])
        ) {
            $this->set('_serialize', true);
        }
        $this->set('username', $this->LdapAuth->user('givenname')[0].' '.$this->LdapAuth->user('sn')[0]);
        
        
        
        
        $configuration = TableRegistry::get('Configurations')->find()->where(['id =' => 1])->first();
        $this->set('configuration', $configuration);
        $this->request->session()->write("authType", $configuration->authentificationType_ldap);
        
        $user = TableRegistry::get('Users')->find()->where(['username' => $this->LdapAuth->user($configuration->authentificationType_ldap)[0]])->first();
        
        $role = $user['role'];
        if($role == null) $role = 'Utilisateur';
        $this->set('role', $role);
        
        $this->set('userConnected', $user);
        
        $displayElement = function ($nom, $valeur) {
        	if ($valeur != "")
        		echo '<tr><td><strong>'.$nom.' </strong></td><td>'.$valeur.'</td></tr>';
        };
        $this->set('displayElement', $displayElement);
        
    }
    
    // "le materiel", "le suivi"...
    protected function getArticle() {
    	return "Le ";
    }
    
    /**
     * Envoi d'un email à la gestion (et aux devs) pour prévenir qu'un matériel a été créé ou modifié
     * (cf howto dans http://book.cakephp.org/2.0/fr/core-utility-libraries/email.html)
     * @param string $subject
     * @param string $message
     */
    public function sendEmailToManagementWith($subject, $message) {
    	
    	$configuration = TableRegistry::get('Configurations')->find()->where(['id =' => 1])->first();
    	
    	for($i = 1; $i < 11; $i++) {
    		$t = 'emailGuest'.$i;
    		$to = $configuration->$t;

    		if ($to != null && !$configuration->test) {
    			if (filter_var($to, FILTER_VALIDATE_EMAIL)) {
    				$email = new Email();
    		
    				$etiquetteFrom = explode("@", $configuration->sender_mail);
    				
    				if($configuration->envoi_mail_management_dev) {
    					$email->transport('dev')
    					->from([$configuration->sender_mail => $etiquetteFrom[0]])
    					->to($to)
    					->subject("[LabInvent] ".$subject)
    					->send($message);
    				} else {
    					$email->transport('default')
    					->from([$configuration->sender_mail => $etiquetteFrom[0]])
    					->to($to)
    					->subject("[LabInvent] ".$subject)
    					->send($message);
    				}
    			}
    		
    		}
    	} 	

    }
    public function sendEmailToManagement($idObj = null) {

    	$configuration = TableRegistry::get('Configurations')->find()->where(['id =' => 1])->first();
    		
    	$userAuth = $this->LdapAuth->user($configuration->authentificationType_ldap)[0]; 
    	$controller = substr($this->request->params['controller'], 0, -1); // materiel
    	$action = $this->request->params['action']; // add or edit or delete or ...
    	$userName = $this->LdapAuth->user('givenname')[0].' '.$this->LdapAuth->user('sn')[0];
    	$userEmail = $this->LdapAuth->user('mail')[0];
    	$role = TableRegistry::get('Users')->find()->where(['username' => $this->LdapAuth->user($configuration->authentificationType_ldap)[0]])->first()['role'];
    	if($role == null) $role = 'Utilisateur';
    	
    	$modelName = $this->modelClass; // 'Materiels'
    	$id = $idObj; 

    	switch ($action) {
    		case 'add':
    			$actionFrench = ['Création', 'créé'];
    			break;
    		case 'edit':
    			$actionFrench = ['Modification', 'modifié'];
    			break;
    		case 'delete':
    			$actionFrench = ['Suppression', 'supprimé'];
    			break;
    		case 'statusValidated':
    			$actionFrench = ['Validation', 'validé'];
    			break;
    		case 'statusToBeArchived':
    			$actionFrench = ['Demande Archivage', 'demandé pour archivage'];
    			break;
    		case 'statusArchived':
    			$actionFrench = ['Archivage', 'archivé'];
    			break;
    		default:
    			$actionFrench = [$action, $action];
    			break;
    	}
    	$doneBy = $userName." (".$userEmail.", login=".$userAuth.", profil=".$role.").";
    
    	$subject = $actionFrench[0]." d'un " .$controller;
    
    	if($id != null) {
    		$entityName = TableRegistry::get($modelName)->find('all')->where(['id =' => $id])->first();
    		
    		if($modelName == 'Materiels') {
    			$entityName = $entityName['designation'];
    		}
    		else if ($modelName == 'Suivis' || $modelName == 'Emprunts') {
    			$entityName = $entityName['id'];
    		}
    		else {
    			$entityName = $entityName['nom'];
    		}
    	}
    	else {
    		$entityName = NULL;
    	}
    
    	$message = $this->getArticle().$controller." ".$entityName." (id=".$id.") a été ".$actionFrench[1]." par ".$doneBy;
    
    	$this->sendEmailToManagementWith($subject, $message);
    	
    }
    
    /**
     * Envoi d'un email au propriétaire pour prévenir qu'un matériel a été créé
     * @param string $subject
     * @param string $message
     */
    public function sendEmailToCreate($idObj = null) {
    	 
    	$id = $idObj;
    	
    	$configuration = TableRegistry::get('Configurations')->find()->where(['id =' => 1])->first();
    	$materiel = TableRegistry::get('Materiels')->find()->where(['id =' => $id])->first();
    	
    	$createurName = $this->LdapAuth->user('givenname')[0].' '.$this->LdapAuth->user('sn')[0];
    	$createurEmail = $this->LdapAuth->user('mail')[0];
    	$toEmail = $materiel->email_responsable;
    	
    	$role = TableRegistry::get('Users')->find()->where(['username' => $this->LdapAuth->user($configuration->authentificationType_ldap)[0]])->first()['role'];
    	if($role == null) $role = 'Utilisateur';
    	
    	$subject = 'Ajout d\'un matériel';
    	$message = $createurName.' (email = '.$createurEmail.', role = '.$role.') a ajouté le matériel "'.$materiel->designation.'" et vous a nommé propriétaire de ce matériel.';
    	
    	if ($toEmail != null && !$configuration->test) {
    		if (filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
    			$email = new Email();
    
    			if($configuration->envoi_mail_management_dev) {
    				$email->transport('dev')
    				->from(["labinvent2@".$configuration->from_mail => "Labinvent2"])
    				->to($toEmail)
    				->subject("[LabInvent] ".$subject)
    				->send($message);
    			} else {
    				$email->transport('default')
    				->from(["labinvent2@".$configuration->from_mail => "Labinvent2"])
    				->to($toEmail)
    				->subject("[LabInvent] ".$subject)
    				->send($message);
    			}
    		}
    
    	}
    	
    
    }
    
    
    static function isLabinventDebugMode() {
    	return TableRegistry::get('Configurations')->find()->where(['id =' => 1])->first()->mode_debug;
    }
    function myDebug($arg, $stop=false) {
    	if ($this->isLabinventDebugMode()) {
    		Configure::write('debug', true);
    		debug($arg);
    		if ($stop) exit;
    	}
    }
    
}