Michael RICOIS 8a7b5aef09 Use modules
2015-10-05 15:38:02 +00:00

723 lines
22 KiB
PHP

<?php
class UserController extends Zend_Controller_Action
{
protected $theme;
/**
* Return a ramdom password
* @param int $length
* Length of the string
* @param int $strength
* $strength = 1:- 0-9
* $strength = 2:- A-Z0-9
* $strength = 3:- A-Za-z0-9
* $strength = 4:- A-Za-z0-9 and # $ % &
* $strength = 5:- A-Za-z0-9 and # $ % & = > ? @
* @return string
*/
protected function randomPassword($length,$strength)
{
$char_sets=array('48-57','65-90','97-122','35-38','61-64');
$new_password='';
srand(microtime()*10000000);
for($i=0;$i<$length;$i++){
$random=rand(0,$strength-1);
list($start,$end)=explode('-',$char_sets[$random]);
$new_password.=chr(rand($start,$end));
}
return $new_password;
}
public function init()
{
// --- Theme
$this->theme = Zend_Registry::get('theme');
require_once 'Scores/WsScores.php';
}
/**
* Affiche le fomulaire d'edition des paramètres utilisateur
*/
public function indexAction()
{
$this->view->headLink()->appendStylesheet($this->theme->pathStyle.'/user.css', 'all');
$user = new Scores_Utilisateur();
if (!$user->checkPerm('MONPROFIL')){
$this->_forward('perms', 'error');
}
$this->view->assign('device_type', $user->getBrowserInfo()->mobile);
$this->view->assign('browser_info', $user->getBrowserInfo()->name.' '.$user->getBrowserInfo()->version);
$this->view->headScript()->appendFile($this->theme->pathScript.'/user.js', 'text/javascript');
$request = $this->getRequest();
$messages = '';
$isProfilUpdated = false;
$isPasswordUpdated = false;
$updateResult = false;
$login = $request->getParam('login', '');
$op = $request->getParam('op');
//Récupération des informations de l'identité
$auth = Zend_Auth::getInstance();
$identity = $auth->getIdentity();
//Save data
if ( $request->isPost() ) {
$options = $request->getParam('frmOptions', '');
$action = $options['action'];
if ($login=='') $login = $options['login'];
//Enregistrement des données new & update
if (in_array($action, array('new','update'))) {
if ( $options['changepwd'] != 1 ) {
$options['password'] = '';
}
if ( in_array($options['profil'], array('Administrateur', 'SuperAdministrateur'))
&& !in_array('monprofil', $options['droits']) ) {
$options['droits'][] = 'monprofil';
}
if( !isset($options['profil']) ) {
$options['profil'] = 'Utilisateur';
}
$ws = new WsScores();
$reponse = $ws->setInfosLogin($login, $action, $options);
$isProfilUpdated = true;
$message = 'Erreur lors de la mise à jour du compte !';
if (is_string($reponse)) {
$message = $reponse;
} elseif ($reponse){
$updateResult = true;
$message = 'Compte mis à jour.';
}
}
// --- Write change in session
if ($identity->idClient == $options['idClient'] && $identity->username == $login) {
// --- Modification lors du changement de mot de passe
if ($options['changepwd']==1 && $updateResult) {
$identity->password = md5($login.'|'.$options['password']);
$auth->getStorage()->write($identity);
}
// --- Mise à jour du profil
if ($isProfilUpdated && $updateResult) {
$ws = new Scores_Ws_Client('gestion', '0.3');
$adressIp = $_SERVER['REMOTE_ADDR'];
$parameters = new stdClass();
$parameters->login = $identity->username;
$parameters->ipUtilisateur = $adressIp;
$parameters->from = null;
$InfosLogin = $ws->getInfosLogin($parameters);
$identity = $user->updateProfil($InfosLogin);
$auth->getStorage()->write($identity);
}
// --- Gestion mode edition en SESSION
if ($action=='update') {
$modeEdition = $request->getParam('modeEdition', false);
if ( $modeEdition ) {
$identity->modeEdition = true;
$auth->getStorage()->write($identity);
}
}
}
}
if ( $isProfilUpdated || $isPasswordUpdated ) {
$this->view->assign('message', $message);
}
$isAdmin = false;
if ( $identity->profil == 'Administrateur'
|| $identity->profil == 'SuperAdministrateur' ) {
$isAdmin = true;
}
$this->view->assign('isAdmin', $isAdmin);
$isSuperAdmin = false;
if ($identity->profil == 'SuperAdministrateur') {
$isSuperAdmin = true;
}
$this->view->assign('isSuperAdmin', $isSuperAdmin);
if ($op=='new')
{
$idClient = $request->getParam('idClient', '');
if ($idClient == '') {
$idClient = $identity->idClient;
}
$ws = new WsScores();
$reponse = $ws->getNextLogin($idClient);
$options->idClient = $idClient;
if ($identity->idClient!=1 && $identity->profil!='SuperAdministrateur') {
$options->profil = 'Utilisateur';
}
$this->view->assign('options', $options);
$this->view->assign('password', $this->randomPassword(10, 3));
$this->view->assign('loginNew', $reponse->result->racine);
$this->view->assign('droitsClients', explode(' ', strtolower($reponse->result->droitsClients)));
$this->view->assign('action', 'new');
$this->view->assign('pref', array());
}
elseif (!empty($op) || $op!='new')
{
if ( !empty($login) && $identity->username != $login ) {
$ws = new Scores_Ws_Client('gestion', '0.3');
$adressIp = $_SERVER['REMOTE_ADDR'];
$parameters = new stdClass();
$parameters->login = $login;
$parameters->ipUtilisateur = $adressIp;
$parameters->from = null;
$reponse = $ws->getInfosLogin($parameters);
$this->view->assign('options', $reponse->result);
$this->view->assign('loginVu', $reponse->result->login);
$this->view->assign('droits', explode(' ', strtolower($reponse->result->droits)));
$this->view->assign('droitsClients', explode(' ', strtolower($reponse->result->droitsClients)));
} else {
$this->view->assign('options', $identity);
$this->view->assign('loginVu', $identity->username);
$this->view->assign('droits', explode(' ', strtolower($identity->droits)));
$this->view->assign('droitsClients', explode(' ', strtolower($identity->droitsClients)));
}
$this->view->assign('loginNew', '');
$this->view->assign('action', 'update');
$this->view->assign('pref', explode(' ',$identity->pref));
}
$ws = new WsScores();
//Liste des catégories des accès
$reponse = $ws->getCategory();
$wscategory = $reponse->item;
$this->view->assign('wscategory', $wscategory);
//Liste de tous les droits
$listeDroits = $ws->getListeDroits();
$droitsLib = array();
foreach($listeDroits->item as $droit) {
$droitsLib[strtoupper($droit->code)] = $droit->desc;
}
$this->view->assign('droitsLib', $droitsLib);
//Liste de toutes les préférences
$listePrefs = $ws->getListePrefs();
$prefsLib = array();
foreach($listePrefs->item as $pref) {
$prefsLib[strtoupper($pref->code)] = $pref->desc;
}
$this->view->assign('prefsLib', $prefsLib);
}
/**
* Display box to enter emails
* One main email and two secondary
* Email length 80 * 3 = 240
* 255 chars is the length to store emails (email1;email2;email3)
*/
public function emailAction()
{
$this->_helper->layout()->disableLayout();
$request = $this->getRequest();
$check = $request->getParam('check');
$email = $request->getParam('q');
if ( $check == 1) {
$this->view->assign('checkemail', true);
$valid = false;
$this->view->assign('msg', 'Email invalide !');
if (null !== $email) {
$validateur = new Zend_Validate_EmailAddress();
$valid = $validateur->isValid($email);
if ( $valid ) {
$this->view->assign('msg', 'Modification effectué.');
$this->view->assign('email', $email);
}
}
} else {
$this->view->assign('email', $email);
}
}
public function emailsecondaryAction()
{
$this->_helper->layout()->disableLayout();
$request = $this->getRequest();
$user = new Scores_Utilisateur();
$mode = $request->getParam('mode');
$this->view->assign('mode', $mode);
$email = $request->getParam('email');
$login = $request->getParam('login', $user->getLogin());
$this->view->assign('login', $login);
$idClient = $request->getParam('client', $user->getIdClient());
if ( $mode === null ) {
$ws = new WsScores();
$result = $ws->getGestionEmail($login);
$emails = array();
if (count($result->item)>0) {
$emails = $result->item;
}
$this->view->assign('emails', $emails);
} elseif ( $mode == 'set' ) {
$this->view->assign('msg', 'Email invalide !');
if (null !== $email) {
$validateur = new Zend_Validate_EmailAddress();
$valid = $validateur->isValid($email);
if ( $valid ) {
$ws = new WsScores();
$result = $ws->setGestionEmail($email, $login);
if ( $result ) {
$this->view->assign('msg', 'Modification effectué.');
$this->view->assign('email', $email);
}
}
}
} elseif ( $mode == 'del' ) {
$this->view->assign('msg', 'Erreur lors de la suppression !');
$id = $request->getParam('id');
$ws = new WsScores();
$result = $ws->setGestionEmail($email, $login, $id, $mode);
if ( $result ) {
$this->view->assign('msg', 'Adresse email supprimé.');
}
}
}
/**
* Téléchargement de la consommation au format CSV
*/
public function consoAction()
{
$this->view->headScript()->appendFile($this->theme->pathScript.'/conso.js', 'text/javascript');
$user = new Scores_Utilisateur();
$request = $this->getRequest();
$idClient = $request->getParam('idClient', $user->getIdClient());
$login = $request->getParam('login', '');
$this->view->assign('idClient', $idClient);
$this->view->assign('login', $login);
$this->view->assign('profil', $user->getProfil());
}
/**
* Renvoi vers le formulaire utilisateur avec les paramètres de la requete
*/
public function editAction()
{
$params = $this->getRequest()->getParams();
$this->_forward('index', 'user', null, $params);
}
/**
* Suppression d'un utilisateur
*/
public function deleteAction()
{
$request = $this->getRequest();
$login = $request->getParam('login');
$action = 'delete';
$ws = new WsScores();
$ws->setInfosLogin($login, $action);
//Redirect
$this->_forward('liste');
}
/**
* Activation d'un utilisateur
*/
public function enableAction()
{
$request = $this->getRequest();
$login = $request->getParam('login');
$action = 'enable';
$ws = new WsScores();
$ws->setInfosLogin($login, $action);
//Redirect
$this->_forward('liste');
}
/**
* Désactivation d'un utilisateur
*/
public function disableAction()
{
$request = $this->getRequest();
$login = $request->getParam('login');
$action = 'disable';
$ws = new WsScores();
$ws->setInfosLogin($login, $action);
//Redirect
$this->_forward('liste');
}
/**
* Méthode AJAX pour modifier le password d'un utilisateur
*/
public function changepwdAction()
{
//Redirect
}
/**
* Affiche la liste des utiliateurs
*/
public function listeAction()
{
$user = new Scores_Utilisateur();
$request = $this->getRequest();
$idClient = $request->getParam('idClient', $user->getIdClient());
if (!$user->isSuperAdmin() && !$user->isAdmin()) {
$this->renderScript('error/perms.phtml');
}
if ($user->isAdmin()){
$idClient = $user->getIdClient();
}
$ws = new WsScores();
$infos = $ws->getListeUtilisateurs($user->getLogin(), $idClient);
$utilisateurs = $infos->result->item;
$this->view->assign('utilisateurs', $utilisateurs);
$this->view->assign('idClient', $idClient);
}
/**
* Gestion de l'authentification
*/
public function loginAction()
{
$this->_helper->layout()->disableLayout();
$this->view->headTitle()->append('Connexion');
$form = new Application_Form_Login();
$this->view->form = $form;
$request = $this->getRequest();
if ( $request->isPost() ) {
$formData = $request->getPost();
if ($form->isValid($formData)) {
$login = $form->getValue('login');
$pass = $form->getValue('pass');
$auth = Zend_Auth::getInstance();
$authAdapter = new Scores_Auth_Adapter_Ws($login, $pass);
$result = $auth->authenticate($authAdapter);
//Auth is valid
if ( $result->isValid() ) {
//Save browser information
$screenSize = $request->getParam('screenSize', 'unknow');
$user = new Scores_Utilisateur();
$info = get_browser();
$isMobile = ($info->ismobiledevice==1) ? 1 : 0;
$user->setBrowserInfo($info->platform, $info->browser, $info->version, $isMobile, $screenSize);
//Get previous url if user has been disconnected
$url = '';
if (Zend_Session::namespaceIsset('login')){
$session = new Zend_Session_Namespace('login');
if (isset($session->url)) {
$url = $session->url;
}
}
if (!empty($url) && $url!='/user/login' && $url!='/user/logout' && $url!='/localauth'){
$this->_redirect($url);
}
$this->_redirect('/');
}
//Auth error
else {
$this->view->message = '';
Zend_Registry::get('firebug')->info($result);
foreach ($result->getMessages() as $message) {
$this->view->message.= $message."<br/>";
}
}
}
}
}
/**
* Gestion de la déconnexion
*/
public function logoutAction()
{
Zend_Auth::getInstance()->clearIdentity();
$session = new Zend_Session_Namespace('wcheck');
$session->unsetAll();
$this->_helper->layout()->disableLayout();
$request = $this->getRequest();
$message = $request->getParam('message');
$this->view->assign('message', $message);
$ajax = $request->getParam('ajax', 0);
$this->view->assign('ajax', $ajax);
$refresh = 5;
$url = 'http://'.$_SERVER['SERVER_NAME'].$this->view->url(array(
'controller' => 'user',
'action' => 'login',
), 'default', true);
$this->view->assign('url', $url);
if ( $ajax == 0 ) {
$this->view->assign('refresh', $refresh);
$this->view->headMeta()->appendHttpEquiv('refresh', $refresh.'; url='.$url);
}
}
/**
* Mettre à jour le mode edition en session sans refresh de la page
*/
public function editionsessionAction()
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$request = $this->getRequest();
$mode = $request->getParam('mode', 'false');
$auth = Zend_Auth::getInstance();
$identity = $auth->getIdentity();
if ($identity->idClient == 1) {
if ($mode == 'false') {
$identity->modeEdition = false;
echo 0;
} else {
$identity->modeEdition = true;
echo 1;
}
$auth->getStorage()->write($identity);
} else {
echo 0;
}
}
/**
* Override email in surveillance portfolio
*/
public function emailsurveillanceAction()
{
$this->_helper->layout()->disableLayout();
$request = $this->getRequest();
$user = new Scores_Utilisateur();
//Execute webservice operation
if ( $request->isPost() ) {
$email = trim($request->getParam('email'));
if ($user->isAdmin() || $user->isSuperAdmin()) {
$login = $request->getParam('login');
}
if (empty($email)) {
$result = "Aucun email défini!";
} else if (empty($login)) {
$result = "Aucun utilisateur défini!";
} else {
$ws = new WsScores();
$result = $ws->setSurveillancesMail($login, $email);
}
$this->view->assign('result', $result);
}
//Display form in dialog
else {
if ($user->isAdmin() || $user->isSuperAdmin()) {
$login = $request->getParam('login');
} else {
$login = $user->getLogin();
}
$this->view->assign('login', $login);
$this->view->assign('dialog',true);
}
}
/**
* Changer la langue de l'utilisateur
*/
public function langAction()
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$lang = $this->getRequest()->getParam('lang', null);
$auth = Zend_Auth::getInstance();
$identity = $auth->getIdentity();
$identity->langtmp = $lang;
$auth->getStorage()->write($identity);
}
/**
* Changer le theme de l'utilisateur
*/
public function changethemeAction()
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$request = $this->getRequest();
$nom = $request->getParam('nom', 'default');
$auth = Zend_Auth::getInstance();
$identity = $auth->getIdentity();
$identity->theme = $nom;
$auth->getStorage()->write($identity);
//Rediriger vers l'écran de recherche
$this->_redirect('/');
}
/**
* Display browser informations on a simple page
*/
public function browserAction()
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
//Load bootstrap
$bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
//Get useragent and device informations
$userAgent = $bootstrap->getResource('useragent');
$device = $userAgent->getDevice();
//Display
echo "<pre>";
print_r(get_browser());
print_r($device->getAllFeatures());
echo "</pre>";
}
/**
* Sends email to the specific client, who requests for forgotten password
*/
public function motpasseAction()
{
$request = $this->getRequest();
$name = 'Identifiants oubliés ?';
$params = array(
'identifiant' => '',
'telephone' => '',
'email' => '',
'nom' => '',
'prenom' => '',
'fonction' => '',
'service' => '',
'rsociale' => '',
);
$this->_helper->layout()->disableLayout();
if ( $request->isPost() ) {
$params = $request->getParams();
$message = '';
$paramlist = array(
'telephone' => 'Numéro de téléphone direct',
'email' => 'Adresse email',
'nom' => 'Nom',
'prenom' => 'Prénom',
'fonction' => 'Fonction',
'service' => 'Service',
'rsociale' => 'Sociale',
);
foreach ($paramlist as $item => $val) {
if (!isset($params[$item])) {
$message .= "Champs $val vide !<br/>";
}
}
$validator = new Zend_Validate_EmailAddress();
if (isset($params['email'])){
if (!$validator->isValid($params['email'])) {
$message .="Adresse email invalide ! <br/>";
}
}
if ($message == '') {
$mailbody = '<style type="text/css">table {font-family:Arial, Helvetica, sans-serif; font-size: 12px; width: 550px; border: none;}table td{padding: 4px 8px;}</style>';
$mailbody .= "Demande d'envoi des identifiants.<br /><br />";
$mailbody .= "L'un de nos clients a égaré son(ses) identifiant(s).<br />";
$mailbody .= "Via notre lien -identifiants oubliés- il a effectué une demande de transmission de ces codes.<br />";
$mailbody .= "<p>A l'aide des informations ci-dessous, merci de retrouver ces codes et les lui envoyer par email.</p>";
$mailbody .= "<table><tr bgcolor='#eeeeee'><td width='200px'><strong>Identifiant :</strong></td><td>".$params['identifiant']."</td></tr>";
$mailbody .= "<tr><td><strong>Adresse email:</strong></td><td>".$params['email']."</td></tr>";
$mailbody .= "<tr bgcolor='#eeeeee'><td><strong>Numéro de téléphone direct:</strong></td><td>".$params['telephone']."</td></tr>";
$mailbody .= "<tr><td><strong>Nom:</strong></td><td>".$params['nom']."</td></tr>";
$mailbody .= "<tr bgcolor='#eeeeee'><td><strong>Prénom:</strong></td><td>".$params['prenom']."</td></tr>";
$mailbody .= "<tr><td><strong>Fonction:</strong></td><td>".$params['fonction']."</td></tr>";
$mailbody .= "<tr bgcolor='#eeeeee'><td><strong>Service:</strong></td><td>".$params['service']."</td></tr>";
$mailbody .= "<tr><td><strong>Dénomination Sociale:</strong></td><td>".$params['rsociale']."</td></tr></table>";
$mailbody .= "<p>Si les informations fournies ne permettent pas d'identifier correctement l'utilisateur, ";
$mailbody .= "merci d'émettre un message sur le mail communiquer en précisant que \"Les éléments confiés ne permettent pas d'identifier l'utilisateur ";
$mailbody .= "et par conséquence de vous délivrer les codes d'accès demandés\".<br />";
$mailbody .= "Aussi nous vous invitons à vous rapprocher de votre interlocuteur commercial habituel ";
$mailbody .= "ou de votre responsable suivi relations Scores & Décisions au sein de votre société.</p>";
$mail = new Scores_Mail_Method();
$mail->setSubject("Demande d'envoi des identifiants");
$mail->setBodyHtmlC($mailbody);
$mail->setFromKey('support');
$mail->addToKey('support');
$mail->setReplyTo($params['email']);
try {
$mail->execute();
$this->view->assign('sendEmail' , true);
}
catch ( Zend_Mail_Transport_Exception $e ){
$message = $e->getMessage();
}
}
$this->view->assign('message', $message);
}
}
}