AppController.php 19.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
<?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', 'getDateGarantie'])) 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é à 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('sn')[0].' '.$this->LdapAuth->user('givenname')[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);
        
        $this->set('idGmNa', TableRegistry::get('GroupesMetiers')->find()->where(['nom =' => 'N/A'])->first()['id']);
        $this->set('idGtNa', TableRegistry::get('GroupesThematiques')->find()->where(['nom =' => 'N/A'])->first()['id']);
        
        $displayElement = function ($nom, $valeur, $params="") {
        	$balise = ($params != "") ? '<td '.$params.'>' : '<td>';
        	// Ca c'est parce que sinon y'a au moins deux tests qui passent pas, a cause de l'espace dans la balise ...
        	if ($valeur != "")
        		echo '<tr><td><strong>'.$nom.' </strong></td>'.$balise.$valeur.'</td></tr>';
        };
        $this->set('displayElement', $displayElement);
        
    }
    
    // "le materiel", "le suivi"...
    protected function getArticle() {
    	return "Le ";
    }
    
    /**
     * @param string $subject
     * @param string $message
     * @param string[] $to
     */
//     public function sendEmailTo($subject, $message, $to = null) {
    	 
//     	$configuration = TableRegistry::get('Configurations')->find()->where(['id =' => 1])->first();
    	
//     	if ($to != null && !$configuration->test) {
    		
//     		for($i = 0; $i < sizeof($to); $i++) {
    
    		
//     			if (filter_var($to[$i], 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[$i])
//     					->subject("[LabInvent] ".$subject)
//     					->send($message);
//     				} else {
//     					$email->transport('default')
//     					->from([$configuration->sender_mail => $etiquetteFrom[0]])
//     					->to($to[$i])
//     					->subject("[LabInvent] ".$subject)
//     					->send($message);
//     				}
//     			}
    
//     		}
//     	}
    
//     }
    
    /**
     * 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('sn')[0].' '.$this->LdapAuth->user('givenname')[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 d\'un ', 'été créé'];
//     			break;
//     		case 'edit':
//     			$actionFrench = ['Modification d\'un ', 'été modifié'];
//     			break;
//     		case 'delete':
//     			$actionFrench = ['Suppression d\'un ', 'été supprimé'];
//     			break;
//     		case 'statusValidated':
//     			$actionFrench = ['Validation d\'un ', 'été validé'];
//     			break;
//     		case 'statusToBeArchived':
//     			$actionFrench = ['Demande Archivage d\'un ', 'été demandé pour archivage'];
//     			break;
//     		case 'statusArchived':
//     			$actionFrench = ['Archivage d\'un ', 'été archivé'];
//     			break;
//     		case 'setLabelIsPlaced':
//     			$actionFrench = ['Etiquette posé sur un ', 'reçu une étiquette'];
//     			break;
//     		default:
//     			$actionFrench = [$action.' d\'un ', 'été '.$action];
//     			break;
//     	}
//     	$doneBy = $userName." (".$userEmail.", login=".$userAuth.", profil=".$role.").";
    
//     	$subject = $actionFrench[0].$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 ".$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('sn')[0].' '.$this->LdapAuth->user('givenname')[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.'" ('.$materiel->numero_laboratoire.') 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();
    			
//     			$etiquetteFrom = explode("@", $configuration->sender_mail);
    			
//     			if($configuration->envoi_mail_management_dev) {
//     				$email->transport('dev')
//     				->from([$configuration->sender_mail => $etiquetteFrom[0]])
//     				->to($toEmail)
//     				->subject("[LabInvent] ".$subject)
//     				->send($message);
//     			} else {
//     				$email->transport('default')
//     				->from([$configuration->sender_mail => $etiquetteFrom[0]])
//     				->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;
    	}
    }
    
    /**
     * Envoie un mail avec un sujet, contenant un message à destination d'une liste de mails, selon l'action effectuée.
     * @param string $subject -> Sujet du mail
     * @param string $msg -> Message à envoyer
     * @param array $listMails -> Liste des mails des destinataires
     * @param id $idObj -> ID du matériel créé, modifié, supprimé ...
     */
    public function sendEmail($subject, $msg, $listMails, $idObj = null) {
    	
    	$configuration = TableRegistry::get('Configurations')->find()->where(['id =' => 1])->first();
    	
    	//if(!$configuration['envoi_mail_management_dev']) {
	    	foreach($listMails as $mail){
	    		$mailInTable = TableRegistry::get('Users')->find()->select('email')->where(['email =' => $mail])->first();
	    		if ($mailInTable!= null) { // Tous les utilisateurs privilégiés, si le mode LDAP est activé, sinon tout le monde
	    			$roleInTable = TableRegistry::get('Users')->find()->select('role')->where(['email =' => $mail])->first();
	    			Switch ($roleInTable){
	    				case 'Super Administrateur':
	    					$this->sendEmailToSuperAdmin($subject, $msg, $mail, $idObj, $configuration);
	    					break;
	    				case 'Administration Plus':
	    					// Role useless, mais il existe dans BD ...
	    					break;
	    				case 'Administration':
	    					$this->sendEmailToManagement($subject, $msg, $mail, $idObj, $configuration);
	    					break;
	    				case 'Responsable':
	    					$this->sendEmailToResponsable($subject, $msg, $mail, $idObj, $configuration);
	    					break;
	    				case 'Utilisateur':
	    					$this->sendEmailToUser($subject, $msg, $mail, $idObj, $configuration);
	    					break;
	    				default :
	    					break;
	    			}
	    		} else { // Si on utilise le LDAP, les seuls utilisateurs qui ne sont pas dans la BD du site sont les utilisateurs normaux
	    			$this->sendEmailToUser($subject, $msg, $mail, $idObj, $configuration); // <--
	    		}
	    	}
    	//}
    	
    }
    
    private function sendEmailToResponsable($subject, $msg, $mail, $idObj = null, $config) {
    	
    	// Rajouter la vérif sur la colone adéquate de la bd
    	
    	if ($mail != null && !$config->test && false) { // flase à remplacer
    		if (filter_var($mail, FILTER_VALIDATE_EMAIL)) {
    			$email = new Email();
    			
    			$etiquetteFrom = explode("@", $config->sender_mail);
    			
    			if($config->envoi_mail_management_dev) { // <-- Si la case est cochée
    				$email->transport('dev')
    				->from([$config->sender_mail => $etiquetteFrom[0]])
    				->to($mail)
    				->subject("[LabInvent] ".$subject)
    				->send($msg);
    			} else { // <-- Si la case n'est pas cochée
    				$email->transport('default')
    				->from([$config->sender_mail => $etiquetteFrom[0]])
    				->to($mail)
    				->subject("[LabInvent] ".$subject)
    				->send($msg);
    			}
    		}
    		
    	}
    }
    
    private function sendEmailToUser($subject, $msg, $mail, $idObj = null, $config) {
    	
    	// Rajouter la vérif sur la colone adéquate de la bd
    	var_dump($mail);
    	if ($mail != null && !$config->test && true) { // flase à remplacer
    		if (filter_var($mail, FILTER_VALIDATE_EMAIL)) {
    			$email = new Email();
    			
    			$etiquetteFrom = explode("@", $config->sender_mail);
    			
    			if($config->envoi_mail_management_dev) {
    				$email->transport('dev')
    				->from([$config->sender_mail => $etiquetteFrom[0]])
    				->to($mail)
    				->subject("[LabInvent] ".$subject)
    				->send($msg);
    			} else {
    				$email->transport('default')
    				->from([$config->sender_mail => $etiquetteFrom[0]])
    				->to($mail)
    				->subject("[LabInvent] ".$subject)
    				->send($msg);
    			}
    		}
    		
    	}
    }
    
    private function sendEmailToSuperAdmin($subject, $msg, $mail, $idObj = null, $config) {
    	
    	// Rajouter la vérif sur la colone adéquate de la bd
    	
    	if ($mail != null && !$config->test && false) { // flase à remplacer
    		if (filter_var($mail, FILTER_VALIDATE_EMAIL)) {
    			$email = new Email();
    			
    			$etiquetteFrom = explode("@", $config->sender_mail);
    			
    			if($config->envoi_mail_management_dev) {
    				$email->transport('dev')
    				->from([$config->sender_mail => $etiquetteFrom[0]])
    				->to($mail)
    				->subject("[LabInvent] ".$subject)
    				->send($msg);
    			} else {
    				$email->transport('default')
    				->from([$config->sender_mail => $etiquetteFrom[0]])
    				->to($mail)
    				->subject("[LabInvent] ".$subject)
    				->send($msg);
    			}
    		}
    		
    	}
    }
    
    private function sendEmailToManagement($subject, $msg, $mail, $idObj = null, $config) {
    	
    	// Rajouter la vérif sur la colone adéquate de la bd
    	
    	if ($mail != null && !$config->test && false) { // flase à remplacer
    		if (filter_var($mail, FILTER_VALIDATE_EMAIL)) {
    			$email = new Email();
    			
    			$etiquetteFrom = explode("@", $config->sender_mail);
    			
    			if($config->envoi_mail_management_dev) {
    				$email->transport('dev')
    				->from([$config->sender_mail => $etiquetteFrom[0]])
    				->to($mail)
    				->subject("[LabInvent] ".$subject)
    				->send($msg);
    			} else {
    				$email->transport('default')
    				->from([$config->sender_mail => $etiquetteFrom[0]])
    				->to($mail)
    				->subject("[LabInvent] ".$subject)
    				->send($msg);
    			}
    		}
    		
    	}
    }
    
}