?? GreyFile — Mystic File Browser

Current path: home/webdevt/cryptoimpot.fr/module/Application/src/Controller/



?? Go up: /home/webdevt/cryptoimpot.fr/module/Application/src

?? Viewing: UserController.php

<?php

namespace Application\Controller;

use Laminas\Form\Form;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Stdlib\ResponseInterface as Response;
use Laminas\Stdlib\Parameters;
use Laminas\View\Model\ViewModel;
use ZfcUser\Service\User as UserService;
use ZfcUser\Options\UserControllerOptionsInterface;
use Doctrine\ORM\EntityManager;
use Laminas\Crypt\Password\Bcrypt;
use Laminas\Mime;
use Laminas\Mail\Message;

class UserController extends AbstractActionController {

//    const ROUTE_REGISTER = 'accueil/inscription';
//    const ROUTE_LOGIN_PUB = 'accueil/connexion';
//    const ROUTE_RESET_PASSWORD = 'accueil/resetpassword';
//    const ROUTE_LOGOUT = 'administration/deconnexion';
//    const ROUTE_CHANGEPASSWD = 'zfcuser/changepassword';
    const ROUTE_LOGIN = 'administration/connexion';
//    const ROUTE_HOME_BOX = 'accueil'; /* Connexion avec le code box */
//    const ANCHOR_HOME_REGISTER = '#inscription'; /* Connexion avec le code box */
//    const ANCHOR_HOME_LOGIN = '#connexion'; /* Connexion avec le code box */
//    const ROUTE_ESPACE_MEMBRE_BOX = 'accueil/coaching'; /* Connexion avec le code box */
//    const ROUTE_LOGIN_BOX = 'accueil/connexion'; /* Connexion avec le code box */
//    const ROUTE_AUTO_LOGIN_BOX = 'accueil/auto-connexion';
//    const ROUTE_REGISTER_BOX = 'accueil/inscription'; /* Connexion avec le code box */
//    const ROUTE_ACTIVATION_BOX = 'accueil/confirmation-inscription'; /* Confirmation inscription code box par email */
////    const ROUTE_REGISTER = 'zfcuser/register';
//
//    const ROUTE_CHANGEEMAIL = 'zfcuser/changeemail';
//    const CONTROLLER_NAME = 'zfcuser';
//    //const CONTROLLER_NAME = 'Application\Controller\User';
//    const ROUTE_LIST = 'administration/utilisateurs/utilisateur-lister';
//    const ROUTE_LIST_PATIENT = 'administration/utilisateurs/patient-lister';
//    const ROUTE_ADD = 'administration/utilisateurs/utilisateur-ajouter';
//    const ROUTE_UPDATE = 'administration/utilisateurs/utilisateur-modifier';
//    const ROUTE_DELETE = 'administration/utilisateurs/utilisateur-supprimer';

    /**
     * @var UserService
     */
    protected $userService;

    /**
     * @var Form
     */
    protected $loginForm;

    /**
     * @var Form
     */
    protected $loginBoxForm;

    /**
     * @var Form
     */
    protected $registerForm;

    /**
     * @var Form
     */
    protected $changePasswordForm;

    /**
     * @var Form
     */
    protected $changeEmailForm;

    /**
     * @todo Make this dynamic / translation-friendly
     * @var string
     */
    protected $failedLoginMessage = 'L\'email ou le mot de passe est incorrecte.';

    /**
     * @var UserControllerOptionsInterface
     */
    protected $options;

    /**
     * @var Doctrine\ORM\EntityManager
     */
    protected $em;

    public function setEntityManager(EntityManager $em) {
        $this->em = $em;
    }

    public function getEntityManager() {
        if (null === $this->em) {
            $this->em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
        }
        return $this->em;
    }

    public function translate($str) {
        $translate = $this->getServiceLocator()->get('ViewHelperManager')->get('translate');
        return $translate($str);
    }

    /**
     * User page
     */
    public function indexAction() {
//        if (!$this->zfcUserAuthentication()->hasIdentity()) {
//            return $this->redirect()->toRoute(static::ROUTE_LOGIN);
//        }
        return new ViewModel();
    }

    /**
     * 
     * @return ViewModel
     */
    public function registerWithConfirmationAction() {


//        $this->redirect()->toRoute(self::ROUTE_HOME_BOX, array('fragment'=>'anchor'));
//        if ($this->zfcUserAuthentication()->hasIdentity()) {
//            $user = $this->zfcUserAuthentication()->getIdentity();
//        } else {
//            return $this->redirect()->toRoute(self::ROUTE_LOGIN);
//        }

        $entityManager = $this->getEntityManager();

        /* Création du formulaire */
        $form = new \Application\Form\UserForm\RegisterForm($entityManager);

        if ($this->getRequest()->isPost()) {
            /* Récupération des données du post */
            $data = array_merge_recursive(
                    $this->getRequest()->getPost()->toArray()
            );
            $form->setHydrator(new \DoctrineModule\Stdlib\Hydrator\DoctrineObject($entityManager, false))
//                    ->setObject(new \Application\Entity\User())
                    ->setInputFilter(new \Application\InputFilter\UserInputFilter\RegisterFilter());

            $form->setData($data);
//            var_dump($data);
//            var_dump($form->isValid());
//            exit;
            if ($form->isValid()) {
                //echo 'is valid'; exit;

                /* On vérifie que l'adresse email n'est pas déja enregistrée */
                $userMapper = new \Application\Mapper\UserMapper($entityManager);
                $userFind = $userMapper->findByEmail($form->getData()['email']);
                if (!empty($userFind) && $userFind->state >= 1) {
//                    $this->flashMessenger()->addErrorMessage('Un utilisateur possède déjà cet email');
                    $this->flashMessenger()->addErrorMessage($this->translate('A user already has this email'));
                    return $this->redirect()->toUrl('/#connexion');
                }

                if (!empty($userFind)) {

                    $newUser = $userFind;
                    $updateUser = true;
                } else {
                    /* Création du user */
                    $newUser = new \Application\Entity\User();

                    $userRole = $entityManager->getRepository('Application\Entity\Role')->findOneBy(array('roleId' => 'user'));
                    $newUser->addrole($userRole);
                }
                $newUser->setEmail($form->getData()['email']);
                $newUser->setUserAgent($_SERVER['HTTP_USER_AGENT']);

                $token = md5(uniqid(rand(), true));
                $newUser->setToken($token);

                $bcrypt = new Bcrypt;
                /* TODO recupérer le cost dans setting de zfc user defaut 14 */
                $cost = 14;
                $bcrypt->setCost((int) $cost);

                $passcrypt = $bcrypt->create($form->getData()['password']);
                $newUser->setPassword($passcrypt);

                /* Génération du nom affiché automatique */
//                $newUser->setDisplayName($newUser->getPrenom() . ' ' . $newUser->getNom());

                /* Activation du compte state 1 fait en cliquant sur email */
                $newUser->setState(0);
                /* @var $newUser \Application\Entity\User */

                // \Zend\Debug\Debug::dump($newUser); exit;
//exit;

                /* on insert ou update le nouvel utilisateur */
                if (!empty($updateUser)) {
                    if (!$userMapper->update($newUser)) {
                        echo 'erreur update';
                        exit;
//                        $this->flashMessenger()->addErrorMessage('Une erreur est survenue lors de l\'enregistrement de l\'utilisateur');
                        $this->flashMessenger()->addErrorMessage($this->translate('An error occurred while registering the user'));
                        return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
                    }
                } else {
                    if (!$userMapper->insert($newUser)) {
//                        echo 'erreur insert';
//                        exit;
//                        $this->flashMessenger()->addErrorMessage('Une erreur est survenue lors de l\'enregistrement de l\'utilisateur');
                        $this->flashMessenger()->addErrorMessage($this->translate('An error occurred while registering the user'));
                        return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
                    }
                }
                /* On attribut le code à l'utilisateur */





                // Envoi de l'invitation par email
                $config = $this->getServiceLocator()->get('config');
                $configInscription = $config['ledgio']['register'];

                // Expediteur / Destinataire (cf fichier config / local.php)
                /* JK - Debug 05/11/2015 */
//              $from = $configExamen['expediteur-nom'] . ' ' . $configExamen['expediteur-email'];
                $fromEmail = $configInscription['email-sender']['email'];
                $fromNom = $configInscription['email-sender']['name'];
                $to = $newUser->getEmail();

                // Sujet
                $subject = $configInscription['email-sender']['subject'];

                // Mail service
                $mailService = $this->getServiceLocator()->get('goaliomailservice_message');

                // Mail
                $uri = $this->getRequest()->getUri();
                $base = sprintf('%s://%s', $uri->getScheme(), $uri->getHost());



                $adresse = $base . $this->url()->fromRoute(\Application\Controller\UserController::ROUTE_ACTIVATION_BOX, array(
                            'token' => $newUser->getToken(),
                            'user_id' => $newUser->id
                ));
                /* analytics */
                $adresse .= '?utm_source=confirm%20account&utm_medium=email&utm_campaign=confirmation';


                $textEmail = str_replace('[ADRESSE]', $adresse, $configInscription['email-sender']['message-txt']);
                $text = new Mime\Part($textEmail);


                $text->type = Mime\Mime::TYPE_TEXT;
                $text->charset = "UTF-8";


                // HTML
                $viewTemplate = 'email/register';
//                $viewTemplate = 'email/welcome-dcf-box';
                $uri = $this->getRequest()->getUri();
                $base = sprintf('%s://%s', $uri->getScheme(), $uri->getHost());



                $values = array(
                    'adresse' => $adresse,
//                    'fullPathImgHeader' => $base . '/img/email/header-dcf.png'
//                    'email' => $newUser->getEmail(),
                );
                $serviceManager = $this->getServiceLocator();
                $renderHtml = $serviceManager->get('goaliomailservice_renderer');
//                $contentHtml = $renderHtml->render($viewTemplate, $values);
//                $renderer = $this->getServiceLocator()->get('Laminas\View\Renderer\RendererInterface');

                $viewContent = new \Laminas\View\Model\ViewModel($values);
                $viewContent->setTemplate($viewTemplate); // set in module.config.php
                $content = $renderHtml->render($viewContent);

// Email layout
//                var_dump($base . $configInscription['email-sender']['img-header-email']);
//                exit;
                $viewLayout = new \Laminas\View\Model\ViewModel(array('content' => $content, 'fullPathImgHeader' => $base . $configInscription['email-sender']['img-header-email'],));
                $viewLayout->setTemplate('email/template'); // set in module.config.php
//                $contentHtml = $renderHtml->render($viewTemplate, $values);
                $contentHtml = $renderHtml->render($viewLayout);

//                echo mb_internal_encoding();
//                echo mb_detect_encoding($contentHtml);

                $html = new Mime\Part($contentHtml);
                $html->type = Mime\Mime::TYPE_HTML;
                $html->charset = "UTF-8";
                $html->encoding = Mime\Mime::ENCODING_8BIT;

                $mimeMessage = new Mime\Message();

//                $mimeMessage->setParts(array($html, $text));
//                $mimeMessage->setParts(array($text,$html));
                $mimeMessage->setParts(array($text, $html));

                $message = new Message();

                $message->addFrom($fromEmail, $fromNom)
                        ->addTo($to)
                        ->setSubject($subject);

                //$message->setEncoding("UTF-8");
                $message->setBody($mimeMessage);

                $message->getHeaders()->get('content-type')->setType(Mime\Mime::MULTIPART_ALTERNATIVE);
                try {
                    $mailService->send($message);
                } catch (\Laminas\Mail\Protocol\Exception\RuntimeException $e) {
//                    var_dump($e->getMessage());
//                    exit;
                    $this->flashMessenger()->addErrorMessage($this->translate('An error occured. Please try again.'));
                    $this->flashMessenger()->addErrorMessage($e->getMessage());
                    return $this->redirect()->toRoute(self::ROUTE_REGISTER);
                }

                //echo 'ok';
//                $this->flashMessenger()->addSuccessMessage('Un lien de confirmation d\'inscription vient de vous être envoyé sur votre email.');
                $this->flashMessenger()->addSuccessMessage($this->translate('A confirmation link has just been sent to you.'));
//                $this->redirect()->toRoute(self::ROUTE_LOGIN_BOX);
                return $this->redirect()->toUrl('/');













//                echo 'ok insert';
//                    exit;
//                \Zend\Debug\Debug::dump($codeBoxFind->getPatient());
//                exit;
//                 echo 'update code box';
//                exit;
//                $this->flashMessenger()->addSuccessMessage('L\'utilisateur : ' . $newUser->prenom . ' ' . $newUser->nom . ' a été ajouté avec succès.');
//                return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
            } else {
                $messages = $form->getMessages();
//                var_dump($messages);
//                exit;
            }
        }

//        var_dump($messages);
//        $this->layout('layout/layout-login');
        $this->layout('layout/layout-public');
        $viewModel = new ViewModel(array('registerForm' => $form));
//        $viewModel->setTemplate('layout/layout-admin1');


        return $viewModel;
    }

    /* confirm registration */

    public function confirmRegisterAction() {
        
//        ini_set('display_errors', 'On');
//        error_reporting(E_ALL);
//        $i = 1;
//        echo "toto $i++";
        $tokenConfirm = $this->params()->fromRoute('token', null);
        $userId = $this->params()->fromRoute('user_id', null);

        $entityManager = $this->getEntityManager();

//         $codeBoxString = $form->getData()['codeBox'];

        if (empty($tokenConfirm)) {
//            $this->flashMessenger()->addErrorMessage('Aucun compte en attente de validation n\{a été trouvé?. Veuillez vous réinscrire.');
            $this->flashMessenger()->addErrorMessage($this->translate('No account pending validation was found? Please re-enroll.'));

            return $this->redirect()->toRoute('accueil');
        }



        $userMapper = new \Application\Mapper\UserMapper($entityManager);
        $userFind = $userMapper->findById($userId);

        if (empty($userFind)) {
//            $this->flashMessenger()->addErrorMessage('Aucun compte n\'a été trouvé. Veuillez vous réinscrire.');
            $this->flashMessenger()->addErrorMessage($this->translate('No account was found. Please re-enroll.'));

            return $this->redirect()->toRoute('accueil');
        }

        /* Il faut que le user soit en state 0 pour l'activer */

//        var_dump($userId);
//\Doctrine\Common\Util\Debug::dump($userFind->token != $tokenConfirm);
//exit;
        if ($userFind->token != $tokenConfirm) {
            $this->flashMessenger()->addErrorMessage($this->translate('Activation link has expired.'));

            return $this->redirect()->toRoute('accueil');
        }

//        var_dump($userFind->state);
//        exit;
        if ($userFind->state != 0) {
            if ($userFind->state == 1) {
//                $this->flashMessenger()->addErrorMessage('Le compte est déjà activé. Veuillez vous connecter.');
                $this->flashMessenger()->addErrorMessage($this->translate('The account is already activated. Please log in.'));

                return $this->redirect()->toRoute('accueil');
            }
            if ($userFind->state == 2) {
//                $this->flashMessenger()->addErrorMessage('Votre compte a été désactivé. Veuillez contacter le support technique.');
                $this->flashMessenger()->addErrorMessage($this->translate('Your account has been deactivated. Please contact technical support.'));

                return $this->redirect()->toRoute('accueil');
            }

//            $this->flashMessenger()->addErrorMessage('Aucun compte n\'a été trouvé. Veuillez vous réinscrire.');
            $this->flashMessenger()->addErrorMessage($this->translate('No account was found. Please re-enroll.'));
            return $this->redirect()->toRoute('inscription');
        }

        /* Mise à jour du statut du compte patient */
        $userFind->state = 1;

        $userMapper->update($userFind);

        /* Envoi de l'email de bienvenue */
        $config = $this->getServiceLocator()->get('config');
        $configInscription = $config['ledgio']['confirm'];

        $fromEmail = $configInscription['email-sender']['email'];
        $fromNom = $configInscription['email-sender']['name'];

        $to = $userFind->getEmail();

        // Sujet
        $subject = $configInscription['email-sender']['subject'];

        // Mail service
        $mailService = $this->getServiceLocator()->get('goaliomailservice_message');

        // Mail
        $uri = $this->getRequest()->getUri();
        $base = sprintf('%s://%s', $uri->getScheme(), $uri->getHost());


//        $adresse = $base . $this->url()->fromRoute(\Application\Controller\UserController::ROUTE_AUTO_LOGIN_BOX, array(
//                    'token' => $codeBoxFind->token,
//                    'user_id' => $userFind->id
//        ));

        $adresse = $base . $this->url()->fromRoute(\Application\Controller\UserController::ROUTE_LOGIN);
        $textEmail = str_replace('[ADRESSE]', $adresse, $configInscription['email-sender']['message-txt']);


        $text = new Mime\Part($textEmail);
        $text->type = Mime\Mime::TYPE_TEXT;
        $text->charset = "UTF-8";


        // HTML
        $uri = $this->getRequest()->getUri();
        $base = sprintf('%s://%s', $uri->getScheme(), $uri->getHost());

        $viewTemplate = 'wdp-front/email/confirmed-register';
        $values = array(
            'adresse' => $adresse,
//            'fullPathImgHeader' => $base . '/img/email/header-dcf.png'
//                    'email' => $newUser->getEmail(),
        );
        $serviceManager = $this->getServiceLocator();
        $renderHtml = $serviceManager->get('goaliomailservice_renderer');
//                $contentHtml = $renderHtml->render($viewTemplate, $values);
//                $renderer = $this->getServiceLocator()->get('Laminas\View\Renderer\RendererInterface');

        $viewContent = new \Laminas\View\Model\ViewModel($values);
        $viewContent->setTemplate($viewTemplate); // set in module.config.php
        $content = $renderHtml->render($viewContent);

// Email layout
        $viewLayout = new \Laminas\View\Model\ViewModel(array('content' => $content, 'fullPathImgHeader' => $base . $configInscription['email-sender']['img-header-email'],));
        $viewLayout->setTemplate('email/template'); // set in module.config.php
//                $contentHtml = $renderHtml->render($viewTemplate, $values);
        $contentHtml = $renderHtml->render($viewLayout);

//                echo mb_internal_encoding();
//                echo mb_detect_encoding($contentHtml);

        $html = new Mime\Part($contentHtml);
        $html->type = Mime\Mime::TYPE_HTML;
        $html->charset = "UTF-8";
        $html->encoding = Mime\Mime::ENCODING_8BIT;

        $mimeMessage = new Mime\Message();

//        $mimeMessage->setParts(array($html, $text));
        $mimeMessage->setParts(array($text, $html));

        $message = new Message();

        $message->addFrom($fromEmail, $fromNom)
                ->addTo($to)
                ->setSubject($subject);

        //$message->setEncoding("UTF-8");
        $message->setBody($mimeMessage);

        $message->getHeaders()->get('content-type')->setType(Mime\Mime::MULTIPART_ALTERNATIVE);
        try {
            $mailService->send($message);
        } catch (\Laminas\Mail\Protocol\Exception\RuntimeException $e) {
//                    echo 'erreur mail';
//                    exit;
            $this->flashMessenger()->addErrorMessage($this->translate('Votre inscription a bien été prise en compte.'));
            return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_LOGIN) . self::ANCHOR_HOME_REGISTER);
        }




        /* ./ Envoi de l'email de bienvenue */

        /* Si on a le même user agent on connect directement sinon on redirige vers la page de connextion */

        if (empty($userFind->getUserAgent()) || $userFind->getUserAgent() != $_SERVER['HTTP_USER_AGENT']) {
//            $this->flashMessenger()->addErrorMessage('Votre compte a bien été créé. Veuillez vous connectez.');
            $this->flashMessenger()->addErrorMessage($this->translate('Your account has been created. Please login.'));
            return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME) . self::ANCHOR_HOME_REGISTER);
        }




        /* auto login  @todo */

        //$adapter = $this->zfcUserAuthentication()->getAuthAdapter();
        /** @var \Laminas\Http\Request */
//    $fakeRequest = $this->getRequest();
//var_dump($identity);
//var_dump($credential);
//exit;
        // $this->getRequest()->getPost()->set('identity', $userFind->getEmail());
        // $this->getRequest()->getPost()->set('credential', $userFind->getPassword());
        //$auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter);




        /* O
         * 
         * 
         * 
         * 
         * n le connecte directement si user agent identique */
        // $this->zfcUserAuthentication()->getAuthAdapter()->resetAdapters();
        // $this->zfcUserAuthentication()->getAuthService()->clearIdentity();
//        $fakeRequest = $this->getRequest();
//        $fakeRequest->getPost()->set('identity', $userFind->getEmail());
//        $fakeRequest->getPost()->set('credential', $codeBoxFind->code);
        //var_dump($userFind->getEmail());
        //var_dump($userFind->getPassword());
        //return $this->forward()->dispatch(static::CONTROLLER_NAME, array('action' => 'authenticate'));
        // exit;
//        return $this->forward()->dispatch(static::CONTROLLER_NAME, array(
//                    'action' => 'authenticate',
//                    'identity' => $userFind->getEmail(),
//                    'credential' => $userFind->getPassword(),
//        ));
        $this->flashMessenger()->addSuccessMessage($this->translate('Your account has been successfully activated. You can loggin'));


        return $this->redirect()->toRoute((self::ROUTE_LOGIN_PUB));




        /* On vérifie que l'adresse email n'est pas déja enregistrée */
//        $codeBoxFind = $codeBoxMapper->findById(2);
////        \Zend\Debug\Debug::dump($codeBoxFind);
//        var_dump(empty($codeBoxFind));
//        echo 'toto';
//        exit;
//        if (empty($codeBoxFind)) {
//            $this->flashMessenger()->addErrorMessage('Aucun compte utilisateur n\'est associé à ce code');
//            return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
//            exit;
//        }
//        /* @var $codeBoxFind \Application\Entity\CodeBox */
//                \Zend\Debug\Debug::dump($tokenConfirm);
//                \Zend\Debug\Debug::dump($codeBoxFind);
//               exit;
//        if ($codeBoxFind->getStatut()->id != 2) {
//            $this->flashMessenger()->addErrorMessage('Veuillez vous réinscrire.');
//            return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
//        }
//
//        /* On vérifie si le compte du patient est déjà activé */
//        $userMapper = new \Application\Mapper\UserMapper($entityManager);
//        $userFind = $userMapper->findById($codeBoxFind->getPatient()->id);
//        /* @var $userFind \Application\Entity\User */
//        if (empty($userFind)) {
//            $this->flashMessenger()->addErrorMessage('Aucun compte utilisateur n\'est associé à ce code');
//            return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
//        }
//
//        if ($userFind->state != 0) {
//            if ($userFind->state == 1) {
//                $this->flashMessenger()->addErrorMessage('Le compte utilisateur est déjà activé.');
//                return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
//            } elseif ($userFind->state == 2) {
//                $this->flashMessenger()->addErrorMessage('Le compte utilisateur a été désactivé.');
//                return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
//            }
//        }
//
//
//
//        
//         /* clear adapters */
//        
//        
//       
//        
//         $this->zfcUserAuthentication()->getAuthAdapter()->resetAdapters();
//        $this->zfcUserAuthentication()->getAuthService()->clearIdentity();
//        
//        
//         $fakeRequest = $this->getRequest();
//    $fakeRequest->getPost()->set('identity', $userFind->getEmail());
//    $fakeRequest->getPost()->set('credential', $codeBoxFind->code);
//
//        $result = $this->zfcUserAuthentication()->getAuthAdapter()->prepareForAuthentication($fakeRequest);
//        if ($result instanceof Response) {
//            return $result;
//        }
//
//        $adapter = $this->zfcUserAuthentication()->getAuthAdapter();
//        $auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter);
//
//        if (!$auth->isValid()) {
//            $this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
//            $adapter->resetAdapters();
//            return $this->redirect()->toRoute(static::ROUTE_LOGIN_BOX); 
//            
////            $this->redirect()->toUrl($this->url()->fromRoute(static::ROUTE_LOGIN_BOX)
////                            . ($redirect ? '?redirect=' . rawurlencode($redirect) : ''));
//        }
//        
//         return $this->redirect()->toRoute('accueil/coaching');
    }

    /* forgot password for public login */

    public function forgotAction() {



        $request = $this->getRequest();
        $form = new \Application\Form\UserForm\ForgotForm();

        if ($this->getRequest()->isPost()) {
            $form->setData($this->getRequest()->getPost());
            $entityManager = $this->getEntityManager();
            $form
                    ->setHydrator(new \DoctrineModule\Stdlib\Hydrator\DoctrineObject($entityManager, false))
//                    ->setObject(new \Application\Entity\User())
                    ->setInputFilter(new \Application\InputFilter\ZfcUser\ForgotInputFilter());

            if ($form->isValid()) {

                $userService = $this->getUserService();

                //$email = $this->getRequest()->getPost()->get('email');
                $email = $form->get('email')->getValue();
                $user = $userService->getUserMapper()->findByEmail($email);
                /* @var $user \Entity\User */
                //only send request when email is found
                if (empty($user)) {
//                    $this->flashMessenger()->addErrorMessage('Le compte n\'est pas accessible. Veuillez vous inscrire.');
                    $this->flashMessenger()->addErrorMessage($this->translate('The account is not accessible. Please register.'));
                    return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME));
                }





                $token = md5(uniqid(rand(), true));
                $user->setToken($token);

                $userService->getUserMapper()->update($user);


                // Envoi de l'invitation par email
                $config = $this->getServiceLocator()->get('config');

                $configForgot = $config['ledgio']['forgot'];

                $fromEmail = $configForgot['email-sender']['email'];
                $fromNom = $configForgot['email-sender']['name'];

                $to = $user->getEmail();

                // Sujet
                $subject = $configForgot['email-sender']['subject'];

                // Mail service
                $mailService = $this->getServiceLocator()->get('goaliomailservice_message');

                // Mail
                $uri = $this->getRequest()->getUri();
                $base = sprintf('%s://%s', $uri->getScheme(), $uri->getHost());


                $adresse = $base . $this->url()->fromRoute(\Application\Controller\UserController::ROUTE_RESET_PASSWORD, array(
                            'token' => $user->token,
                            'userId' => $user->id
                ));

                $textEmail = str_replace('[ADRESSE]', $adresse, $configForgot['email-sender']['message-txt']);

                $textEmail = str_replace('[TOKEN]', $user->token, $textEmail);




                //$textEmail = str_replace('[MAIL]', $user->email, $configForgot['text-email']);
                //$textEmail = str_replace('[CODE]', $codeBoxFind->code, $textEmail);
                //$textEmail = str_replace('[LINK]', $adresse, $textEmail);

                $text = new Mime\Part($textEmail);

                $text->type = Mime\Mime::TYPE_TEXT;
                $text->charset = "UTF-8";


                // HTML
                $uri = $this->getRequest()->getUri();
                $base = sprintf('%s://%s', $uri->getScheme(), $uri->getHost());


                $viewTemplate = 'email/forgot';

                $values = array(
                    'email' => $user->email,
                    'adresse' => $adresse,
                    'fullPathImgHeader' => $base . $configForgot['email-sender']['img-header-email'],
//                    'email' => $newUser->getEmail(),
                );
                $serviceManager = $this->getServiceLocator();
                $renderHtml = $serviceManager->get('goaliomailservice_renderer');


//                $renderer = $this->getServiceLocator()->get('Laminas\View\Renderer\RendererInterface');

                $viewContent = new \Laminas\View\Model\ViewModel($values);
                $viewContent->setTemplate($viewTemplate); // set in module.config.php
                $content = $renderHtml->render($viewContent);

// Email layout
//$viewLayout = new \Laminas\View\Model\ViewModel(array('content' => $content, 'fullPathImgHeader' => $base . '/img/email/Header-Diabeduc-600x150.jpg',));
                $viewLayout = new \Laminas\View\Model\ViewModel(array('content' => $content, 'fullPathImgHeader' => $base . $configForgot['email-sender']['img-header-email'],));
                $viewLayout->setTemplate('email/template'); // set in module.config.php
//                $contentHtml = $renderHtml->render($viewTemplate, $values);
                $contentHtml = $renderHtml->render($viewLayout);

//                echo mb_internal_encoding();
//                echo mb_detect_encoding($contentHtml);

                $html = new Mime\Part($contentHtml);
                $html->type = Mime\Mime::TYPE_HTML;
                $html->charset = "UTF-8";
                $html->encoding = Mime\Mime::ENCODING_8BIT;

                $mimeMessage = new Mime\Message();

//                $mimeMessage->setParts(array($html, $text));
                $mimeMessage->setParts(array($text, $html));

                $message = new Message();

                $message->addFrom($fromEmail, $fromNom)
                        ->addTo($to)
                        ->setSubject($subject);

                //$message->setEncoding("UTF-8");
                $message->setBody($mimeMessage);

                $message->getHeaders()->get('content-type')->setType(Mime\Mime::MULTIPART_ALTERNATIVE);
//                $message->getHeaders()->get('content-type')->setType(Mime\Mime::MULTIPART_MIXED);
                try {
                    $mailService->send($message);
                } catch (\Laminas\Mail\Protocol\Exception\RuntimeException $e) {
//                    echo 'erreur mail';
//                    exit;
//                    $this->flashMessenger()->addErrorMessage('Une erreur est survenue. Veuillez vous réinscrire.');
                    $this->flashMessenger()->addErrorMessage($this->translate('An error has occurred. Please re-enroll.'));
                    return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
                }


//                $this->flashMessenger()->addSuccessMessage('Un email contenant votre code confidentiel vient de vous être envoyé.');
                $this->flashMessenger()->addSuccessMessage($this->translate('Un email contenant un lien de réinitialisation de votre mot de passe vous a été envoyé.'));
//                $this->redirect()->toRoute(self::ROUTE_LOGIN_BOX);
                return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_LOGIN);
            } else {
                $this->flashMessenger()->setNamespace('goalioforgotpassword-forgot-form')->addMessage('Compte inexistant');

                $this->layout('layout/layout-public');
                return array(
                    'form' => $form,
                );
            }
        }
        $this->layout('layout/layout-public');
        // Render the form
        return array(
            'form' => $form,
        );
    }

    /**
     * Login form public
     */
    public function loginAction() {

        if ($this->zfcUserAuthentication()->getAuthService()->hasIdentity()) {
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }

        $request = $this->getRequest();
        $form = $this->getLoginForm();

        if ($this->getOptions()->getUseRedirectParameterIfPresent() && $request->getQuery()->get('redirect')) {
            $redirect = $request->getQuery()->get('redirect');
        } else {
            $redirect = false;
        }


        if (!$request->isPost()) {

//            $this->layout('layout/layout-login');
            $this->layout('layout/layout-public');
//            $this->layout('layout/layout-public');
            return array(
                'loginForm' => $form,
                'redirect' => $redirect,
                'enableRegistration' => $this->getOptions()->getEnableRegistration(),
            );
        }

        $form->setData($request->getPost());


        if (!$form->isValid()) {

            $this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
            return $this->redirect()->refresh() . ($redirect ? '?redirect=' . rawurlencode($redirect) : '');
        }





        /* clear adapters */
        $this->zfcUserAuthentication()->getAuthAdapter()->resetAdapters();
        $this->zfcUserAuthentication()->getAuthService()->clearIdentity();


        return $this->forward()->dispatch(static::CONTROLLER_NAME, array('action' => 'authenticate'));
    }

    public function listAction() {

        /* Array with number item authorize per page */
        $config = $this->getServiceLocator()->get('config');
        $configNumber = $config['number_per_page_authorize'];

        /* Init query option */
        $queryOption = array();

        /* Page number default page 1 this->params renvoie le parametre le mieux est d'utiliser la méthode params et fromRoute */
        //$pageNumber = (int) $this->params()->fromRoute('page', 1);
        $queryOption['page'] = $pageNumber = $this->params()->fromQuery('page', '1');

        // Display Table or List
        $queryOption['display'] = $displayState = $this->params()->fromQuery('display', 'table');

        /* Number element display per page */
        $nb_element_per_page = $this->params()->fromQuery('nb_element_per_page', '30');
        $queryOption['nb_element_per_page'] = $_SESSION['countPerPage'] = in_array($nb_element_per_page, array('30', '60', '90')) ? $nb_element_per_page : '30';

        /* List Sort by field */
        $sort_by = $this->params()->fromQuery('sort_by', 'user_id');

        $colTable = array(
            //'id' => 'Id',
            'email' => array(
                'label' => 'Email',
                'class' => 'col-sm-3',
                'allowOrder' => true,
            ),
            'nom' => array(
                'label' => 'Nom',
                'class' => 'col-sm-2',
                'allowOrder' => true,
            ),
            'prenom' => array(
                'label' => 'Prénom',
                'class' => 'col-sm-2',
                'allowOrder' => true,
            ),
            'profil' => array(
                'label' => 'Profils',
                'class' => 'col-sm-4',
                'allowOrder' => false,
            ),
            'action' => array(
                'label' => 'Action',
                'class' => 'col-sm-1',
                'allowOrder' => false,
            ),
        );

        $queryOption['sort_by'] = in_array($sort_by, array('id', 'email', 'nom', 'prenom')) ? $sort_by : 'id';

        /* List order ASC or DESC */
        $sort = $this->params()->fromQuery('sort', 'DESC');
        $queryOption['sort'] = in_array($sort, array('ASC', 'DESC')) ? $sort : 'DESC';

        $formSearch = new \Application\Form\SearchForm();

        $request = $this->getRequest();
        /* @var $request \Laminas\Http\Request */

        $filterOption = null;

        if ($request->isGet() && is_string($request->getQuery('search'))) {
            $data = $request->getQuery()->toArray();
            $formSearch->setInputFilter(new \Application\InputFilter\SearchInputFilter());
            $formSearch->setData($data);

            if ($formSearch->isValid()) {
                $donneesFiltrees = $formSearch->getData();
                $queryOption['search'] = urlencode($data['search']);
            }
        }

        $orderOption = array(
            'sort_by' => $queryOption['sort_by'],
            'sort' => $queryOption['sort'],
        );

        /* Création Paginator */
        $criteria = array('state' => 1);
        $search = '';
        if (isset($queryOption['search'])) {
            $criteria = array_merge($criteria, array('description' => "%{$queryOption['search']}%"));
            $search = $queryOption['search'];
        }
        $orderBy = array($orderOption['sort_by'] => $orderOption['sort']);

        $entityManager = $this->getEntityManager();
        /* @var $entityManager \Doctrine\ORM\EntityManager */
        $userMapper = new \Application\Mapper\UserMapper($entityManager);

        $parametersManager = array(
            'sort_by' => $queryOption['sort_by'],
            'sort' => $queryOption['sort'],
            'search' => isset($queryOption['search']) ? urldecode($queryOption['search']) : null
        );

        $paginator = $userMapper->getListSansPatient($parametersManager, true);

        /* Option affichage paginator */
        $paginator->setItemCountPerPage((int) $queryOption['nb_element_per_page']);
        $paginator->setCurrentPageNumber((int) $queryOption['page']);
        /* Verify current page < to number pages
          set is not allow after getting pages */
        $numberPages = $paginator->getPages()->pageCount;
        if ((int) $queryOption['page'] > $numberPages) {
            $queryOption['page'] = '1';
        }


        return new ViewModel(array(
            'paginator' => $paginator,
            'queryOption' => $queryOption,
            'colTable' => $colTable,
            'formSearch' => $formSearch,
        ));
    }

    public function listPatientAction() {

        /* Array with number item authorize per page */
        $config = $this->getServiceLocator()->get('config');
        $configNumber = $config['number_per_page_authorize'];

        /* Init query option */
        $queryOption = array();

        /* Page number default page 1 this->params renvoie le parametre le mieux est d'utiliser la méthode params et fromRoute */
        //$pageNumber = (int) $this->params()->fromRoute('page', 1);
        $queryOption['page'] = $pageNumber = $this->params()->fromQuery('page', '1');

        // Display Table or List
        $queryOption['display'] = $displayState = $this->params()->fromQuery('display', 'table');

        /* Number element display per page */
        $nb_element_per_page = $this->params()->fromQuery('nb_element_per_page', '30');
        $queryOption['nb_element_per_page'] = $_SESSION['countPerPage'] = in_array($nb_element_per_page, array('30', '60', '90')) ? $nb_element_per_page : '30';

        /* List Sort by field */
        $sort_by = $this->params()->fromQuery('sort_by', 'user_id');

        $colTable = array(
            //'id' => 'Id',
            'partenaire' => array(
                'label' => 'Partenaire',
                'class' => 'col-sm-3',
                'allowOrder' => true,
            ),
            'email' => array(
                'label' => 'Email patient',
                'class' => 'col-sm-3',
                'allowOrder' => true,
            ),
            'code' => array(
                'label' => 'Code',
                'class' => 'col-sm-3',
                'allowOrder' => true,
            ),
            'dateInscription' => array(
                'label' => 'Inscrit le',
                'class' => 'col-sm-3',
                'allowOrder' => true,
            ),
//            'profil' => array(
//                'label' => 'Profils',
//                'class' => 'col-sm-4',
//                'allowOrder' => false,
//            ),
            'action' => array(
                'label' => 'Action',
                'class' => 'col-sm-1',
                'allowOrder' => false,
            ),
        );

        $queryOption['sort_by'] = in_array($sort_by, array('id', 'partenaire', 'email', 'code', 'dateInscription')) ? $sort_by : 'id';

        /* List order ASC or DESC */
        $sort = $this->params()->fromQuery('sort', 'DESC');
        $queryOption['sort'] = in_array($sort, array('ASC', 'DESC')) ? $sort : 'DESC';

        $formSearch = new \Application\Form\SearchForm();

        $request = $this->getRequest();
        /* @var $request \Laminas\Http\Request */

        $filterOption = null;

        if ($request->isGet() && is_string($request->getQuery('search'))) {
            $data = $request->getQuery()->toArray();
            $formSearch->setInputFilter(new \Application\InputFilter\SearchInputFilter());
            $formSearch->setData($data);

            if ($formSearch->isValid()) {
                $donneesFiltrees = $formSearch->getData();
                $queryOption['search'] = urlencode($data['search']);
            }
        }

        $orderOption = array(
            'sort_by' => $queryOption['sort_by'],
            'sort' => $queryOption['sort'],
        );

        /* Création Paginator */
        $criteria = array('state' => 1);
        $search = '';
        if (isset($queryOption['search'])) {
            $criteria = array_merge($criteria, array('description' => "%{$queryOption['search']}%"));
            $search = $queryOption['search'];
        }
        $orderBy = array($orderOption['sort_by'] => $orderOption['sort']);

        $entityManager = $this->getEntityManager();
        /* @var $entityManager \Doctrine\ORM\EntityManager */
        $codeBoxMapper = new \Application\Mapper\CodeBoxMapper($entityManager);

        $parametersManager = array(
            'sort_by' => $queryOption['sort_by'],
            'sort' => $queryOption['sort'],
            'search' => isset($queryOption['search']) ? urldecode($queryOption['search']) : null
        );
        $paginator = $codeBoxMapper->getListPatient($parametersManager, true);

        /* Option affichage paginator */
        $paginator->setItemCountPerPage((int) $queryOption['nb_element_per_page']);
        $paginator->setCurrentPageNumber((int) $queryOption['page']);
        /* Verify current page < to number pages
          set is not allow after getting pages */
        $numberPages = $paginator->getPages()->pageCount;
        if ((int) $queryOption['page'] > $numberPages) {
            $queryOption['page'] = '1';
        }


        return new ViewModel(array(
            'paginator' => $paginator,
            'queryOption' => $queryOption,
            'colTable' => $colTable,
            'formSearch' => $formSearch,
        ));
    }

    public function importUsersAction() {
        set_time_limit(0);
        $nb = 0;
        // $roleMapper = new \BjyAuthorize\Acl\Role($entityManager);
        $em = $this->getEntityManager();
        $userRole = $em->getRepository('Application\Entity\Role')->findOneBy(array('id' => 8));
// echo '<pre>';
//                \Doctrine\Common\Util\Debug::dump($userRole);
//                echo '</pre>';
        $row = 0;
        $role = new \Application\Entity\Role();
        $entityManager = $this->getEntityManager();
        if (($handle = fopen("./data/imports/liste_collab.csv", "r")) !== FALSE) {
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                if ($row > 0) :
                    //$num = count($data);
                    $newUser = new \Application\Entity\User();

                    //echo "<p> $num champs à la ligne $row: <br /></p>\n";
                    //$row++;
                    $newUser->nom = $data[0];
                    $newUser->prenom = $data[1];
                    $newUser->email = $data[2];
                    //$newUser->addRole($role);
                    $newUser->addrole($userRole);
                    $pass = $data[3];


                    $bcrypt = new Bcrypt;
                    /* TODO recupérer le cost dans setting de zfc user defaut 14 */
                    $cost = 14;
                    $bcrypt->setCost((int) $cost);

                    $passcrypt = $bcrypt->create(trim($pass));
                    $newUser->setPassword($passcrypt);

                    /* Génération du nom affiché automatique */
                    $newUser->setDisplayName($newUser->getPrenom() . ' ' . $newUser->getNom());

                    /* Activation du compte state 1 */
                    $newUser->setState(1);
                    /* @var $newUser \Application\Entity\User */

//                echo '<pre>';
//                \Doctrine\Common\Util\Debug::dump($newUser);
//                echo '</pre>';
//                exit;

                    $userMapper = new \Application\Mapper\UserMapper($entityManager);

                    /* On vérifie que l'adresse email n'est pas déja enregistrée */
                    $userFind = $userMapper->findByEmail($newUser->email);
                    if (!$userFind) {
                        if ($userMapper->insert($newUser)) {
                            $nb++;
                        }
                    }

                /* on insert le nouvel utilisateur */



//                for ($c = 0; $c < $num; $c++) {
//
//                    echo $data[$c] . "<br />\n";
//                }
                endif;
                $row++;
            }
            echo $nb;
            fclose($handle);
        }
    }

    public function addAction() {
//        if ($this->zfcUserAuthentication()->hasIdentity()) {
//            $user = $this->zfcUserAuthentication()->getIdentity();
//        } else {
//            return $this->redirect()->toRoute(self::ROUTE_LOGIN);
//        }

        $entityManager = $this->getEntityManager();

        /* Création du formulaire */
        $form = new \Application\Form\UserForm\CreateUserForm($entityManager);

        if ($this->getRequest()->isPost()) {
            /* Récupération des données du post */
            $data = array_merge_recursive(
                    $this->getRequest()->getPost()->toArray()
            );
            $form->setHydrator(new \DoctrineModule\Stdlib\Hydrator\DoctrineObject($entityManager, false))
                    ->setObject(new \Application\Entity\User())
                    ->setInputFilter(new \Application\InputFilter\UserInputFilter());

            $form->setData($data);
            if ($form->isValid()) {



                $codeBoxString = $data['code'];
                if (!empty($codeBoxString)) {

                    $codeBoxMapper = new \Application\Mapper\CodeBoxMapper($entityManager);
                    $codeBoxFind = $codeBoxMapper->findByCodeBox($codeBoxString);
                    /* @var $codeBoxFind \Application\Entity\CodeBox */
//                var_dump($codeBoxString);
//                \Doctrine\Common\Util\Debug::dump($codeBoxFind);
//               exit;
                    if (empty($codeBoxFind)) {
//                    exit;
//                        $this->flashMessenger()->addErrorMessage('Le code n\'est pas valide.');
                        $this->flashMessenger()->addErrorMessage($this->translate('The code is not valid.'));
//                    return $this->redirect()->toRoute(self::ROUTE_HOME_BOX, array('fragment'=>'inscription'));
                        return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
//                    return $this->redirect()->toUrl('/#inscription');
                    }
                }




                /* Récupération des données filtrées par le UserInputFilter */
                $newUser = $form->getData();
                $form->bind($newUser);

                /* Génération du mot de passe automatique */
//                $pass = strtolower(
//                        substr($newUser->getPrenom(), 0, 1)
//                        . substr($newUser->getPrenom(), -1, 1)
//                        . substr($newUser->getNom(), 0, 1)
//                        . substr($newUser->getNom(), -1, 1));


                $bcrypt = new Bcrypt;
                /* TODO recupérer le cost dans setting de zfc user defaut 14 */
                $cost = 14;
                $bcrypt->setCost((int) $cost);




                $passNonCrypt = !empty($newUser->getPassword()) ? $newUser->getPassword() : $codeBoxString;


//                $passcrypt = $bcrypt->create($newUser->getPassword());
                $passcrypt = $bcrypt->create($passNonCrypt);


                $newUser->setPassword($passcrypt);

                /* Génération du nom affiché automatique */
//                $newUser->setDisplayName($newUser->getPrenom() . ' ' . $newUser->getNom());

                /* Activation du compte state 1 */
                $newUser->setState(1);
                /* @var $newUser \Application\Entity\User */

                $userMapper = new \Application\Mapper\UserMapper($entityManager);

                /* On vérifie que l'adresse email n'est pas déja enregistrée */
                $userFind = $userMapper->findByEmail($newUser->email);
                if ($userFind) {
//                    $this->flashMessenger()->addErrorMessage('Un utilisateur possède déjà cet email');
                    $this->flashMessenger()->addErrorMessage($this->translate('A user already has this email'));
                    $this->redirect()->toRoute(self::ROUTE_ADD);
                }



                /* on insert le nouvel utilisateur */
                if (!in_array('patient', $newUser->rolesToArray())) {
                    if (!$userMapper->insert($newUser)) {
//                    $this->flashMessenger()->addErrorMessage('Une erreur est survenue lors de l\'enregistrement de l\'utilisateur');
                        $this->flashMessenger()->addErrorMessage($this->translate('An error occurred while registering the user'));

                        $this->redirect()->toRoute(self::ROUTE_ADD);
                    }
                }

                if (in_array('patient', $newUser->rolesToArray())) {
                    /* Trouver le codebox */

                    if (empty($codeBoxString)) {
                        $this->flashMessenger()->addErrorMessage($this->translate('The code is not valid.'));
//                  
                    }

//                var_dump($codeBoxString);
//                exit;
                    // codebox existe 
                    $codeBoxMapper = new \Application\Mapper\CodeBoxMapper($entityManager);

//                    var_dump($passNonCrypt);
//                    exit;
                    /* On vérifie que l'adresse email n'est pas déja enregistrée */
//                    $codeBoxFind = $codeBoxMapper->findByCodeBox($passNonCrypt);
                    $codeBoxFind = $codeBoxMapper->findByCodeBox($codeBoxString);
                    /* @var $codeBoxFind \Application\Entity\CodeBox */
//                var_dump($codeBoxString);
//                \Doctrine\Common\Util\Debug::dump($codeBoxFind);
//               exit;
                    if (empty($codeBoxFind)) {
//                    exit;
//                        $this->flashMessenger()->addErrorMessage('Le code n\'est pas valide.');
                        $this->flashMessenger()->addErrorMessage($this->translate('The code is not valid.'));
//                    return $this->redirect()->toRoute(self::ROUTE_HOME_BOX, array('fragment'=>'inscription'));
                        return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
//                    return $this->redirect()->toUrl('/#inscription');
                    }

                    if ($codeBoxFind && $codeBoxFind->getStatut()->id > 2) {
//                        $this->flashMessenger()->addErrorMessage('Le code box est déjà activé.');
                        $this->flashMessenger()->addErrorMessage($this->translate('The box code is already activated.'));
                        return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_LOGIN);
//                    return $this->redirect()->toUrl('/#connexion');
                    }
                    if ($codeBoxFind && $codeBoxFind->getStatut()->id != 1) {
                        $this->flashMessenger()->addErrorMessage('Le code box est déjà utilisé.');
                        return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_LOGIN);
//                    return $this->redirect()->toUrl('/#connexion');
                    }


                    if (!$userMapper->insert($newUser)) {
//                    $this->flashMessenger()->addErrorMessage('Une erreur est survenue lors de l\'enregistrement de l\'utilisateur');
                        $this->flashMessenger()->addErrorMessage($this->translate('An error occurred while registering the user'));

                        $this->redirect()->toRoute(self::ROUTE_ADD);
                    }



                    $codeBoxFind->setPatient($newUser);
                    $codeBoxFind->setDateInscription(new \DateTime());


                    $codeBoxStatutMapper = new \Application\Mapper\CodeBoxStatutMapper($entityManager);
//                $codeBoxStatut = $codeBoxStatutMapper->findByStatut('en attente');
                    $codeBoxStatut = $codeBoxStatutMapper->findByStatut('utilisé');


//                var_dump($codeBoxStatut);
//
//                exit;
                    $codeBoxFind->setStatut($codeBoxStatut);

                    $codeBoxMapper->update($codeBoxFind);

//                    var_dump($codeBoxFind->getStatut()->id);
//                    exit;
                }



//                $this->flashMessenger()->addSuccessMessage('L\'utilisateur : ' . $newUser->prenom . ' ' . $newUser->nom . ' a été ajouté avec succès.');
                $this->flashMessenger()->addSuccessMessage(str_replace('PRENOM_NOM', $newUser->prenom . ' ' . $newUser->nom, $this->translate('The user : PRENOM_NOM was added successfully.')));

                $this->redirect()->toRoute(self::ROUTE_LIST);
            } else {
                $messages = $form->getMessages();
            }
        }
        return new ViewModel(array('form' => $form));
    }

    public function updateAction() {

//        if ($this->zfcUserAuthentication()->hasIdentity()) {
//            $user = $this->zfcUserAuthentication()->getIdentity();
//        } else {
//            return $this->redirect()->toRoute(self::ROUTE_LOGIN);
//        }

        /* Récupération de l'id utilisateur */
        $idUser = (int) $this->params()->fromRoute('id', null);

        if (!isset($idUser)) {
            return $this->redirect()->toRoute(self::ROUTE_LIST);
        }

        /* Récupération des données de l'utilisateur */
        $entityManager = $this->getEntityManager();
        $userMapper = new \Application\Mapper\UserMapper($entityManager);
//        var_dump($idUser);
//        exit;
        $userUpdate = $userMapper->findById($idUser);
//        \Doctrine\Common\Util\Debug::dump($userUpdate);
//        exit;
        /* Création du formulaire */
        $form = new \Application\Form\UserForm\UpdateUserForm($entityManager);
        $hydrator = new \DoctrineModule\Stdlib\Hydrator\DoctrineObject($entityManager);
        $form->setHydrator($hydrator)
                ->setObject(new \Application\Entity\User())
                ->setInputFilter(new \Application\InputFilter\UserUpdateInputFilter());

        $form->bind($userUpdate);

        if ($this->getRequest()->isPost()) {
            /* Récupération des données du post */
            $data = array_merge_recursive(
                    $this->getRequest()->getPost()->toArray()
            );


            $newPassword = $data['newPassword'];
            unset($data['newPassword']);

            $form->setData($data);
//            var_dump($form->isValid());
//            exit;

            if ($form->isValid()) {
                $userMapper = new \Application\Mapper\UserMapper($entityManager);

                /* On vérifie que l'adresse email n'est pas déja enregistrée */
                $userFind = $userMapper->findByEmail($userUpdate->email);
                if ($userFind && $userFind->id != $userUpdate->id) {
//                    $this->flashMessenger()->addErrorMessage('Un utilisateur possède déjà cet email.');
                    $this->flashMessenger()->addErrorMessage($this->translate('A user already has this email'));
                    $this->redirect()->toRoute(self::ROUTE_LIST);
                }

                /* Mise à jour du display name */
                $userUpdate->displayName = $userUpdate->prenom . ' ' . $userUpdate->nom;

                /* password */

//                var_dump($newPassword);
//                exit;

                if (!empty($newPassword)) {

                    $bcrypt = new Bcrypt;
                    //                /* TODO recupérer le cost dans setting de zfc user defaut 14 */
                    $cost = 14;
                    $bcrypt->setCost((int) $cost);
                    //
                    $passcrypt = $bcrypt->create($newPassword);
                    $userUpdate->setPassword($passcrypt);
                }


                if (!$userMapper->update($userUpdate)) {
//                    $this->flashMessenger()->addErrorMessage('Une erreur est survenue lors de la mise à jour de l\'utilisateur.');
                    $this->flashMessenger()->addErrorMessage($this->translate('Une erreur est survenue lors de la mise à jour de l\'utilisateur.'));

                    $this->redirect()->toRoute(self::ROUTE_ADD);
                }
                $this->flashMessenger()->addSuccessMessage('L\'utilisateur' . $userUpdate->email . ' a été mis à jour avec succès.');
                $this->redirect()->toRoute(self::ROUTE_LIST);
            } else {
                $messages = $form->getMessages();
//echo 'toto';
//                var_dump($messages);
//                exit;
            }
        }
        return new ViewModel(array('form' => $form));
    }

    public function deleteAction() {
        /* Récupération de l'id de l'utilisateur */
        $idUser = (int) $this->params()->fromRoute('id', null);

        if (!$idUser) {
            return $this->redirect()->toRoute(self::ROUTE_LIST);
        }
        $entityManager = $this->getEntityManager();

        $userMapper = new \Application\Mapper\UserMapper($entityManager);
        $userToDelete = $userMapper->findById($idUser);
        $nomUser = $userToDelete->prenom . ' ' . $userToDelete->nom . ' (' . $userToDelete->email . ')';
        if (!$userMapper->delete($userToDelete)) {
//            $this->flashMessenger()->addErrorMessage('Une erreur est survenue lors de la suppression de l\'utilisateur');
            $this->flashMessenger()->addErrorMessage($this->translate('Une erreur est survenue lors de la suppression de l\'utilisateur'));
            $this->redirect()->toRoute(self::ROUTE_LIST);
        }
//        $this->flashMessenger()->addSuccessMessage('L\'utilisateur : ' . $nomUser . ' a été supprimé avec succès.');
        $this->flashMessenger()->addSuccessMessage(str_replace('NOM', $nomUser, $this->translate('The user : NOM has been deleted successfully.')));

        $this->redirect()->toRoute(self::ROUTE_LIST);
    }

    public function autoLoginWithTokenAction() {

        $tokenConfirm = $this->params()->fromRoute('token', null);
        $userId = $this->params()->fromRoute('user_id', null);

        $entityManager = $this->getEntityManager();

        if (empty($tokenConfirm)) {
//            $this->flashMessenger()->addErrorMessage('Le lien a expiré. Veuillez vous connecter à l\'aide de vos identifiants.');
            $this->flashMessenger()->addErrorMessage($this->translate('The link has expired. Please login with your login.'));
            return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_LOGIN);
        }

        /* Recherche du code box utilisé */
        $codeBoxMapper = new \Application\Mapper\CodeBoxMapper($entityManager);

        /* On vérifie que l'adresse email n'est pas déja enregistrée */
        $codeBoxFind = $codeBoxMapper->findByToken($tokenConfirm);
        /* @var $codeBoxFind \Application\Entity\CodeBox */


        if (empty($codeBoxFind)) {
//            $this->flashMessenger()->addErrorMessage('Le compte n\'est pas accessible. Veuillez vous réinscrire.');
            $this->flashMessenger()->addErrorMessage($this->translate('The account is not accessible. Please re-enroll.'));
            return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
        }
        $userMapper = new \Application\Mapper\UserMapper($entityManager);
        $userFind = $userMapper->findById($userId);

        if (empty($userFind)) {
//            $this->flashMessenger()->addErrorMessage('Aucun compte n\'a été trouvé. Veuillez vous réinscrire.');
            $this->flashMessenger()->addErrorMessage($this->translate('No account was found. Please re-enroll.'));
            return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
        }

        /* Il faut que le user soit en state 0 pour l'activer */
        if ($userFind->state != 1) {
            if ($userFind->state == 0) {
//                $this->flashMessenger()->addErrorMessage('Le compte n\'est pas activé. Veuillez confirmer votre compte en cliquant sur le lien qui vous a été envoyé.');
                $this->flashMessenger()->addErrorMessage($this->translate('The account is not activated. Please confirm your account by clicking on the link sent to you.'));
            }
            if ($userFind->state == 2) {
//                $this->flashMessenger()->addErrorMessage('Votre compte a été désactivé. Veuillez contacter le support technique.');
                $this->flashMessenger()->addErrorMessage($this->translate('Your account has been deactivated. Please contact technical support.'));
            }

//            $this->flashMessenger()->addErrorMessage('Aucun compte n\'a été trouvé. Veuillez vous réinscrire.');
            $this->flashMessenger()->addErrorMessage($this->translate('No account was found. Please re-enroll.'));
            return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
        }

        /* Si on a le même user agent on connect directement sinon on redirige vers la page de connextion */

//        if ( empty($userFind->getUserAgent()) || $userFind->getUserAgent() != $_SERVER['HTTP_USER_AGENT']) {
//            $this->flashMessenger()->addErrorMessage('Votre compte a bien été créé. Veuillez vous connectez.');
//            return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
//        }
        /* On le connecte directement si user agent identique */
        $this->zfcUserAuthentication()->getAuthAdapter()->resetAdapters();
        $this->zfcUserAuthentication()->getAuthService()->clearIdentity();

        return $this->forward()->dispatch(static::CONTROLLER_NAME, array(
                    'action' => 'authenticateWithCodeBox',
                    'identity' => $userFind->getEmail(),
                    'credential' => $codeBoxFind->getCode(),
        ));
    }

    /**
     * Login avec code box form
     */
    public function loginWithCodeBoxAction() {

        if ($this->zfcUserAuthentication()->getAuthService()->hasIdentity()) {
//            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
            return $this->redirect()->toRoute(self::ROUTE_ESPACE_MEMBRE_BOX);
        }

        $entityManager = $this->getEntityManager();

        /* Création du formulaire */
        $form = new \Application\Form\UserForm\LoginWithCodeBoxForm($entityManager);
//        $form      ->setObject(new \Application\Entity\User());
        $form->setInputFilter(new \Application\InputFilter\ZfcUser\LoginWithCodeBoxFilter());




        $redirect = '/coaching';

        $request = $this->getRequest();

        if (!$request->isPost()) {
            $this->layout('layout/layout-public');
            return array(
                'loginForm' => $form,
                'redirect' => $redirect,
                'enableRegistration' => $this->getOptions()->getEnableRegistration(),
            );
        }

        $form->setData($request->getPost());

        if (!$form->isValid()) {

            $messages = $form->getMessages();
            foreach ($messages as $typeMessageArray) {
                foreach ($typeMessageArray as $message) {

                    $this->flashMessenger()->addErrorMessage($message);
                }
            }
//            \Zend\Debug\Debug::dump($messages);
//        exit;
//            $this->flashMessenger()->addErrorMessage('Une erreur est survenue');
            return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_LOGIN);
//            $this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
            //var_dump($this->url()->fromRoute(static::ROUTE_LOGIN));
//            return $this->redirect()->toUrl(
//                    $this->url()->fromRoute(static::ROUTE_LOGIN).($redirect ? '?redirect='. rawurlencode($redirect) : ''), 
//                    array('lang' => 'it'), null, true
//                );
            //var_dump($this->redirect()->refresh());
//            return $this->redirect()->refresh() . ($redirect ? '?redirect=' . rawurlencode($redirect) : '');
//            exit;
//            return $this->redirect()->refresh() . ($redirect ? '?redirect=' . rawurlencode($redirect) : '');
        }

        $newUser = $form->getData();

//var_dump();
//exit;
        /* On vérifie si le compte du patient est déjà activé */
//        $userMapper = new \Application\Mapper\UserMapper($entityManager);
//        $userFind = $userMapper->findById($codeBoxFind->getPatient()->id);
//        /* @var $userFind \Application\Entity\User */
//        if (empty($userFind)) {
//            $this->flashMessenger()->addErrorMessage('Aucun compte utilisateur n\'est associé à ce code');
//            return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
//        }
//
//        if ($userFind->state != 0) {
//            if ($userFind->state == 1) {
//                $this->flashMessenger()->addErrorMessage('Le compte utilisateur est déjà activé.');
//                return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
//            } elseif ($userFind->state == 2) {
//                $this->flashMessenger()->addErrorMessage('Le compte utilisateur a été désactivé.');
//                return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
//            }
//        }
//        $this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
        // clear adapters
        $this->zfcUserAuthentication()->getAuthAdapter()->resetAdapters();
        $this->zfcUserAuthentication()->getAuthService()->clearIdentity();

//        $fakeRequest = $this->getRequest();
//        $fakeRequest->getPost()->set('identity', $userFind->getEmail());
//        $fakeRequest->getPost()->set('credential', $codeBoxFind->code);

        return $this->forward()->dispatch(static::CONTROLLER_NAME, array(
                    'action' => 'authenticateWithCodeBox',
                    'identity' => $newUser['email'],
                    'credential' => $newUser['codeBox'],
        ));
    }

    /**
     * Logout and clear the identity
     */
    public function logoutWithCodeBoxAction() {
        $this->zfcUserAuthentication()->getAuthAdapter()->resetAdapters();
        $this->zfcUserAuthentication()->getAuthAdapter()->logoutAdapters();
        $this->zfcUserAuthentication()->getAuthService()->clearIdentity();

        $redirect = $this->params()->fromPost('redirect', $this->params()->fromQuery('redirect', false));

        if ($this->getOptions()->getUseRedirectParameterIfPresent() && $redirect) {
            return $this->redirect()->toUrl($redirect);
        }

        return $this->redirect()->toRoute(self::ROUTE_HOME_BOX);
    }

    /**
     * Logout and clear the identity
     */
    public function logoutAction() {
        $this->zfcUserAuthentication()->getAuthAdapter()->resetAdapters();
        $this->zfcUserAuthentication()->getAuthAdapter()->logoutAdapters();
        $this->zfcUserAuthentication()->getAuthService()->clearIdentity();

        $redirect = $this->params()->fromPost('redirect', $this->params()->fromQuery('redirect', false));

        if ($this->getOptions()->getUseRedirectParameterIfPresent() && $redirect) {
            return $this->redirect()->toUrl($redirect);
        }

        return $this->redirect()->toRoute($this->getOptions()->getLogoutRedirectRoute());
    }

    /**
     * General-purpose authentication action
     */
    public function authenticateWithCodeBoxAction() {

        if ($this->zfcUserAuthentication()->getAuthService()->hasIdentity()) {
//            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
            return $this->redirect()->toRoute(self::ROUTE_ESPACE_MEMBRE_BOX);
        }







        $identity = $this->params()->fromRoute('identity', false);
        $credential = $this->params()->fromRoute('credential', false);


        /* Interdire la connection des admin via le formulaire public */
        $userMapper = new \Application\Mapper\UserMapper($this->getEntityManager());

        /* On vérifie que l'adresse email n'est pas déja enregistrée */
        $userFind = $userMapper->findByEmail($identity);


        if (!empty($userFind) && !in_array('patient', $userFind->rolesToArray())) {
            $this->flashMessenger()->addErrorMessage('Veuillez vous connecter via la page de connexion administrateur.');
            return $this->redirect()->toRoute(self::ROUTE_HOME_BOX);
        }





        $adapter = $this->zfcUserAuthentication()->getAuthAdapter();
        /** @var \Laminas\Http\Request */
//    $fakeRequest = $this->getRequest();
//var_dump($identity);
//var_dump($credential);
//exit;
        $this->getRequest()->getPost()->set('identity', $identity);
        $this->getRequest()->getPost()->set('credential', $credential);
//    $fakeRequest->getPost()->set('identity', $identity);
//    $fakeRequest->getPost()->set('credential', $credential);
        $result = $adapter->prepareForAuthentication($this->getRequest());

        // Return early if an adapter returned a response
        if ($result instanceof Response) {
//            echo 'erreur';
//            exit;
//            $this->flashMessenger()->addErrorMessage('Une erreur est survenue. Veuillez vous connecter à nouveau.');
            $this->flashMessenger()->addErrorMessage($this->translate('An error has occurred. Please log in again.'));
            return $this->redirect()->toRoute(self::ROUTE_HOME_BOX);
        }

        if (empty($credential)) {
//            $this->flashMessenger()->addErrorMessage('Veuillez indiquer le code confidentiel que vous avez utilisé lors de votre inscription.');
            $this->flashMessenger()->addErrorMessage($this->translate('Please enter the PIN you used when registering.'));

            return $this->redirect()->toRoute(self::ROUTE_HOME_BOX);
        }

        /* Vérification du nombre de connexion par jour */
        $entityManager = $this->getEntityManager();
        $mapperHistorique = new \Application\Mapper\HistoriqueConnexionCodeBoxMapper($entityManager);

//$nb = 0;


        $mapperCodeBox = new \Application\Mapper\CodeBoxMapper($entityManager);
        $codeBox = $mapperCodeBox->findByCodeBox($credential);




        if (empty($codeBox)) {
//            $this->flashMessenger()->addErrorMessage('Veuillez indiquer le code confidentiel que vous avez utilisé lors de votre inscription.');
            $this->flashMessenger()->addErrorMessage($this->translate('Please enter the PIN you used when registering.'));

            return $this->redirect()->toRoute(self::ROUTE_HOME_BOX);
        }

//        var_dump($credential);
//            exit;
//            \Doctrine\Common\Util\Debug::dump($codeBox);
//        exit;
        $nb = $mapperHistorique->getNombreConnexionJourWithEmail(array('email' => $identity, 'dateLastActivation' => $codeBox->getDateLastActivation()));

//var_dump($nb);
//exit;


        $config = $this->getServiceLocator()->get('config');
        $configLock = $config['wdp-front']['lock-account'];

//            var_dump($configLock['maxNumber']);
//            var_dump($nb);
//            exit;
        if ($nb >= $configLock['maxNumber']) {
//        var_dump($nb); exit;
//            $userFind->setState(0);
            /* mapper */




//            var_dump($codeBox);
            $codeBoxStatutMapper = new \Application\Mapper\CodeBoxStatutMapper($entityManager);
//                $codeBoxStatut = $codeBoxStatutMapper->findByStatut('en attente');
            $codeBoxStatut = $codeBoxStatutMapper->findByStatut('désactivé');


            $codeBox->setStatut($codeBoxStatut);
            $mapperCodeBox->update($codeBox);
//            exit;
//             if (!$userMapper->update($userFind)) {
////                    $this->flashMessenger()->addErrorMessage('Une erreur est survenue lors de la mise à jour de l\'utilisateur.');
////                    $this->flashMessenger()->addErrorMessage($this->translate('Une erreur est survenue.'));
//
//                    
//                }
//            exit;
//            $this->flashMessenger()->addErrorMessage('Vous vous êtes connecté plus de 10 fois aujourd\'hui. Veuillez contacter l\'administarteur du site.');
            $this->flashMessenger()->addErrorMessage($this->translate('You have logged in more than 10 times today. Please contact the site administrator.'));





            /* email lock account user */

            $config = $this->getServiceLocator()->get('config');
            $configLock = $config['wdp-front']['lock-account'];
            // Expediteur / Destinataire (cf fichier config / local.php)
            /* JK - Debug 05/11/2015 */
//              $from = $configExamen['expediteur-nom'] . ' ' . $configExamen['expediteur-email'];
            $fromEmail = $configLock['expediteur-email'];
            $fromNom = $configLock['expediteur-nom'];
            $to = $userFind->getEmail();

            // Sujet
            $subject = $configLock['subject-email'];

            // Mail service
            $mailService = $this->getServiceLocator()->get('goaliomailservice_message');






            $textEmail = $configLock['text-email'];
            $today = date('d-m-Y');

            $textEmail = str_replace('[EMAIL]', $configLock['contactEmail'], $textEmail);
            $textEmail = str_replace('[DATE]', $today, $textEmail);

            $text = new Mime\Part($textEmail);

            $text->type = Mime\Mime::TYPE_TEXT;
            $text->charset = "UTF-8";


            // HTML
            // insctiption code box 1st time
//                $viewTemplate = 'email/register-dcf-box';

            $viewTemplate = 'email/lock-account';
            $uri = $this->getRequest()->getUri();
            $base = sprintf('%s://%s', $uri->getScheme(), $uri->getHost());




            $values = array(
                'emailContact' => $configLock['contactEmail'],
                'fullPathImgHeader' => $base . '/img/email/header-dcf.png',
                'today' => $today
//                    'email' => $newUser->getEmail(),
            );
            $serviceManager = $this->getServiceLocator();
            $renderHtml = $serviceManager->get('goaliomailservice_renderer');
//                $contentHtml = $renderHtml->render($viewTemplate, $values);
//                $renderer = $this->getServiceLocator()->get('Laminas\View\Renderer\RendererInterface');

            $viewContent = new \Laminas\View\Model\ViewModel($values);
            $viewContent->setTemplate($viewTemplate); // set in module.config.php
            $content = $renderHtml->render($viewContent);

// Email layout
            $viewLayout = new \Laminas\View\Model\ViewModel(array('content' => $content, 'fullPathImgHeader' => $base . '/img/email/Header-Diabeduc-600x150.jpg',));
            $viewLayout->setTemplate('email/template-dcf-patient'); // set in module.config.php
//                $contentHtml = $renderHtml->render($viewTemplate, $values);
            $contentHtml = $renderHtml->render($viewLayout);

//                echo mb_internal_encoding();
//                echo mb_detect_encoding($contentHtml);

            $html = new Mime\Part($contentHtml);
            $html->type = Mime\Mime::TYPE_HTML;
            $html->charset = "UTF-8";
            $html->encoding = Mime\Mime::ENCODING_8BIT;

            $mimeMessage = new Mime\Message();

//                $mimeMessage->setParts(array($html, $text));
            $mimeMessage->setParts(array($text, $html));

            $message = new Message();

            $message->addFrom($fromEmail, $fromNom)
                    ->addTo($to)
                    ->setSubject($subject);

            //$message->setEncoding("UTF-8");
            $message->setBody($mimeMessage);


//                var_dump($fromEmail);
//                var_dump($to);
//                exit;
            $message->getHeaders()->get('content-type')->setType(Mime\Mime::MULTIPART_ALTERNATIVE);
            try {
                $mailService->send($message);
            } catch (\Laminas\Mail\Protocol\Exception\RuntimeException $e) {
//                    echo 'erreur mail';
//                    exit;
                $this->flashMessenger()->addErrorMessage($this->translate('Votre inscription a bien été prise en compte.'));
                return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
            }




            /* ./ email lock account user */


            /* email notification admin lock account user */

            $config = $this->getServiceLocator()->get('config');
            $configLock = $config['wdp-admin']['lock-account-notification-admin'];
            // Expediteur / Destinataire (cf fichier config / local.php)
            /* JK - Debug 05/11/2015 */
//              $from = $configExamen['expediteur-nom'] . ' ' . $configExamen['expediteur-email'];
            $fromEmail = $configLock['expediteur-email'];
            $fromNom = $configLock['expediteur-nom'];
            $to = $configLock['destinataire-email'];

            // Sujet
            $subject = $configLock['subject-email'];

            // Mail service
            $mailService = $this->getServiceLocator()->get('goaliomailservice_message');






            $textEmail = $configLock['text-email'];
            $today = date('d-m-Y');

            $uri = $this->getRequest()->getUri();
            $base = sprintf('%s://%s', $uri->getScheme(), $uri->getHost());


            $linkAdmin = $base . $this->url()->fromRoute(\Application\Controller\UserController::ROUTE_LOGIN, array());




            $textEmail = str_replace('[DATE]', $today, $textEmail);
            $textEmail = str_replace('[CODE]', $codeBox->code, $textEmail);
            $textEmail = str_replace('[LINK_ADMIN]', $linkAdmin, $textEmail);

            $text = new Mime\Part($textEmail);

            $text->type = Mime\Mime::TYPE_TEXT;
            $text->charset = "UTF-8";


            // HTML
            // insctiption code box 1st time
//                $viewTemplate = 'email/register-dcf-box';

            $viewTemplate = 'email/lock-account-notification-admin';
            $uri = $this->getRequest()->getUri();
            $base = sprintf('%s://%s', $uri->getScheme(), $uri->getHost());




            $values = array(
                'code' => $codeBox->code,
                'adresseAdminHome' => $linkAdmin,
                'fullPathImgHeader' => $base . '/img/email/header-dcf.png',
                'today' => $today
//                    'email' => $newUser->getEmail(),
            );
            $serviceManager = $this->getServiceLocator();
            $renderHtml = $serviceManager->get('goaliomailservice_renderer');
//                $contentHtml = $renderHtml->render($viewTemplate, $values);
//                $renderer = $this->getServiceLocator()->get('Laminas\View\Renderer\RendererInterface');

            $viewContent = new \Laminas\View\Model\ViewModel($values);
            $viewContent->setTemplate($viewTemplate); // set in module.config.php
            $content = $renderHtml->render($viewContent);

// Email layout
            $viewLayout = new \Laminas\View\Model\ViewModel(array('content' => $content, 'fullPathImgHeader' => $base . '/img/email/Header-Diabeduc-600x150.jpg',));
            $viewLayout->setTemplate('email/template-dcf-patient'); // set in module.config.php
//                $contentHtml = $renderHtml->render($viewTemplate, $values);
            $contentHtml = $renderHtml->render($viewLayout);

//                echo mb_internal_encoding();
//                echo mb_detect_encoding($contentHtml);

            $html = new Mime\Part($contentHtml);
            $html->type = Mime\Mime::TYPE_HTML;
            $html->charset = "UTF-8";
            $html->encoding = Mime\Mime::ENCODING_8BIT;

            $mimeMessage = new Mime\Message();

//                $mimeMessage->setParts(array($html, $text));
            $mimeMessage->setParts(array($text, $html));

            $message = new Message();

            $message->addFrom($fromEmail, $fromNom)
                    ->addTo($to)
                    ->setSubject($subject);

            //$message->setEncoding("UTF-8");
            $message->setBody($mimeMessage);


//                var_dump($fromEmail);
//                var_dump($to);
//                exit;
            $message->getHeaders()->get('content-type')->setType(Mime\Mime::MULTIPART_ALTERNATIVE);
            try {
                $mailService->send($message);
            } catch (\Laminas\Mail\Protocol\Exception\RuntimeException $e) {
//                    echo 'erreur mail';
//                    exit;
                $this->flashMessenger()->addErrorMessage($this->translate('Votre inscription a bien été prise en compte.'));
                return $this->redirect()->toUrl($this->url()->fromRoute(self::ROUTE_HOME_BOX) . self::ANCHOR_HOME_REGISTER);
            }




            /* ./ email notification admin lock account user */





            return $this->redirect()->toRoute(self::ROUTE_HOME_BOX);
        }


        $auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter);

        if (!$auth->isValid()) {

            $entityManager = $this->getEntityManager();
            $userMapper = new \Application\Mapper\UserMapper($entityManager);

            /* On vérifie que l'adresse email n'est pas déja enregistrée */
            $userFind = $userMapper->findByEmail($identity);
            if (!$userFind) {
//                $this->flashMessenger()->addErrorMessage('Ce compte est inexistant. Veuillez vous inscrire.');
                $this->flashMessenger()->addErrorMessage($this->translate('This account has not been found. Please register.'));
            } else {

                // debug account error code
                if (!empty($codeBox->code)) {
//                $codeBoxMapper = new \Application\Mapper\CodeBoxMapper($entityManager);
//                    $codeBoxFind = $codeBoxMapper->findByCodeBox($codeBox->code);


                    if (!empty($codeBox->patient) && $codeBox->patient == $userFind) {


                        $bcrypt = new Bcrypt;
                        /* TODO recupérer le cost dans setting de zfc user defaut 14 */
                        $cost = 14;
                        $bcrypt->setCost((int) $cost);




                        $passNonCrypt = $codeBox->code;


//                $passcrypt = $bcrypt->create($newUser->getPassword());
                        $passcrypt = $bcrypt->create($passNonCrypt);


                        $userFind->setPassword($passcrypt);
                        $userMapper->update($userFind);


                        $this->getRequest()->getPost()->set('identity', $identity);
                        $this->getRequest()->getPost()->set('credential', $codeBox->code);
//    $fakeRequest->getPost()->set('identity', $identity);
//    $fakeRequest->getPost()->set('credential', $credential);
                        $result = $adapter->prepareForAuthentication($this->getRequest());

                        // Return early if an adapter returned a response
                        if ($result instanceof Response) {
//            echo 'erreur';
//            exit;
//            $this->flashMessenger()->addErrorMessage('Une erreur est survenue. Veuillez vous connecter à nouveau.');
                            $this->flashMessenger()->addErrorMessage($this->translate('An error has occurred. Please log in again.'));
                            return $this->redirect()->toRoute(self::ROUTE_HOME_BOX);
                        }


                        $auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter);

                        if (!$auth->isValid()) {
                            $this->flashMessenger()->addErrorMessage($this->translate('Please enter the PIN you used when registering.'));
                        } else {
                            $newHistoriqueConnexion = new \Application\Entity\HistoriqueConnexionCodeBox();
                            $newHistoriqueConnexion->createDate = new \DateTime();
                            $newHistoriqueConnexion->createDateTime = new \DateTime();
                            $newHistoriqueConnexion->useragent = $_SERVER ['HTTP_USER_AGENT'];

                            /* mapper */
                            $mapperCodeBox = new \Application\Mapper\CodeBoxMapper($entityManager);


                            $codeBox = $mapperCodeBox->findByCodeBox($credential);
                            /* @var $codeBox \Application\Entity\CodeBox */
                            if (empty($codeBox)) {
//            exit;
//                $this->flashMessenger()->addErrorMessage('Code non activé');
                                $this->flashMessenger()->addErrorMessage($this->translate('Code Not Enabled'));
                                return $this->redirect()->toRoute(self::ROUTE_HOME_BOX);
                            }


                            $codeBox->dateLastConnexion = new \DateTime();
                            $mapperCodeBox->update($codeBox);
//         var_dump($nb);
//        exit;
                            $newHistoriqueConnexion->codeBox = $codeBox;
//        \Doctrine\Common\Util\Debug::dump($newHistoriqueConnexion);
//        exit;
//        var_dump($newHistoriqueConnexion);
//        exit;
                            $mapperHistorique->insert($newHistoriqueConnexion);

                            return $this->redirect()->toRoute(self::ROUTE_ESPACE_MEMBRE_BOX);
                        }
                    }
//                    \Doctrine\Common\Util\Debug::dump($codeBox->patient);
//                    exit;
                    /* @var $codeBoxFind \Application\Entity\CodeBox */
                }
                // fin debug
//                $this->flashMessenger()->addErrorMessage('Veuillez indiquer le code confidentiel que vous avez utilisé lors de votre inscription.');
                $this->flashMessenger()->addErrorMessage($this->translate('Please enter the PIN you used when registering.'));
            }




//        $this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
            $adapter->resetAdapters();
            // Password does not match
//        throw new LoginException("Invalid Username or password");

            return $this->redirect()->toRoute(self::ROUTE_HOME_BOX);
        } else {
            $newHistoriqueConnexion = new \Application\Entity\HistoriqueConnexionCodeBox();
            $newHistoriqueConnexion->createDate = new \DateTime();
            $newHistoriqueConnexion->createDateTime = new \DateTime();
            $newHistoriqueConnexion->useragent = $_SERVER ['HTTP_USER_AGENT'];

            /* mapper */
            $mapperCodeBox = new \Application\Mapper\CodeBoxMapper($entityManager);


            $codeBox = $mapperCodeBox->findByCodeBox($credential);
            /* @var $codeBox \Application\Entity\CodeBox */
            if (empty($codeBox)) {
//            exit;
//                $this->flashMessenger()->addErrorMessage('Code non activé');
                $this->flashMessenger()->addErrorMessage($this->translate('Code Not Enabled'));
                return $this->redirect()->toRoute(self::ROUTE_HOME_BOX);
            }


            $codeBox->dateLastConnexion = new \DateTime();
            $mapperCodeBox->update($codeBox);
//         var_dump($nb);
//        exit;
            $newHistoriqueConnexion->codeBox = $codeBox;
//        \Doctrine\Common\Util\Debug::dump($newHistoriqueConnexion);
//        exit;
//        var_dump($newHistoriqueConnexion);
//        exit;
            $mapperHistorique->insert($newHistoriqueConnexion);
//        \Doctrine\Common\Util\Debug::dump($newHistoriqueConnexion,3);
//        exit;
        }

        return $this->redirect()->toRoute(self::ROUTE_ESPACE_MEMBRE_BOX);
    }

    /**
     * General-purpose authentication action
     */
    public function authenticateAction() {

        if ($this->zfcUserAuthentication()->getAuthService()->hasIdentity()) {
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }

        $adapter = $this->zfcUserAuthentication()->getAuthAdapter();


        $redirect = $this->params()->fromPost('redirect', $this->params()->fromQuery('redirect', false));


        $result = $adapter->prepareForAuthentication($this->getRequest());
        if ($result instanceof Response) {
            return $result;
        }

        $auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter);


        if (!$auth->isValid()) {

            $this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
            $adapter->resetAdapters();
            return $this->redirect()->toUrl($this->url()->fromRoute(static::ROUTE_LOGIN)
                            . ($redirect ? '?redirect=' . rawurlencode($redirect) : ''));
        }
        if ($this->getOptions()->getUseRedirectParameterIfPresent() && $redirect) {

            return $this->redirect()->toUrl($redirect);
        }

        return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
    }

    /**
     * Register new user
     */
    public function registerAction() {
        //exit;
        /* if the user is logged in, we don't need to register */
        if ($this->zfcUserAuthentication()->hasIdentity()) {
            /* redirect to the login redirect route */
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }
        
        /* if registration is disabled */
        if (!$this->getOptions()->getEnableRegistration()) {
            return array('enableRegistration' => true);
        }
//exit;
        
        $request = $this->getRequest();
        $service = $this->getUserService();
        $form = $this->getRegisterForm();
        
        if ($this->getOptions()->getUseRedirectParameterIfPresent() && $request->getQuery()->get('redirect')) {
            $redirect = $request->getQuery()->get('redirect');
        } else {
            $redirect = false;
        }

        /* modification route ajout de true pour prendre en charge le paramètre lang */
        $redirectUrl = $this->url()->fromRoute(static::ROUTE_REGISTER, array(), null, true)
                . ($redirect ? '?redirect=' . rawurlencode($redirect) : '');

        $prg = $this->prg($redirectUrl, true);
        $this->layout('layout/layout-public');
        if ($prg instanceof Response) {
            return $prg;
        } elseif ($prg === false) {

            return array(
                'registerForm' => $form,
                'enableRegistration' => $this->getOptions()->getEnableRegistration(),
                'redirect' => $redirect,
            );
        }

        $post = $prg;
        $user = $service->register($post);

        $redirect = isset($prg['redirect']) ? $prg['redirect'] : null;

        if (!$user) {
            return array(
                'registerForm' => $form,
                'enableRegistration' => $this->getOptions()->getEnableRegistration(),
                'redirect' => $redirect,
            );
        }

        if ($service->getOptions()->getLoginAfterRegistration()) {
            $identityFields = $service->getOptions()->getAuthIdentityFields();
            if (in_array('email', $identityFields)) {
                $post['identity'] = $user->getEmail();
            } elseif (in_array('username', $identityFields)) {
                $post['identity'] = $user->getUsername();
            }
            $post['credential'] = $post['password'];
            $request->setPost(new Parameters($post));
            return $this->forward()->dispatch(static::CONTROLLER_NAME, array('action' => 'authenticate'));
        }

        // TODO: Add the redirect parameter here...
        return $this->redirect()->toUrl($this->url()->fromRoute(static::ROUTE_LOGIN) . ($redirect ? '?redirect=' . rawurlencode($redirect) : ''));
    }

    /**
     * Change the users password
     */
    public function changepasswordAction() {
        /* if the user isn't logged in, we can't change password */
        if (!$this->zfcUserAuthentication()->hasIdentity()) {
            /* redirect to the login redirect route */
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }

        $form = $this->getChangePasswordForm();
        $prg = $this->prg(static::ROUTE_CHANGEPASSWD);

        $fm = $this->flashMessenger()->setNamespace('change-password')->getMessages();
        if (isset($fm[0])) {
            $status = $fm[0];
        } else {
            $status = null;
        }

        if ($prg instanceof Response) {
            return $prg;
        } elseif ($prg === false) {
            return array(
                'status' => $status,
                'changePasswordForm' => $form,
            );
        }

        $form->setData($prg);

        if (!$form->isValid()) {
            return array(
                'status' => false,
                'changePasswordForm' => $form,
            );
        }

        if (!$this->getUserService()->changePassword($form->getData())) {
            return array(
                'status' => false,
                'changePasswordForm' => $form,
            );
        }

        $this->flashMessenger()->setNamespace('change-password')->addMessage(true);
        return $this->redirect()->toRoute(static::ROUTE_CHANGEPASSWD);
    }

    public function changeEmailAction() {
        /* if the user isn't logged in, we can't change email */
        if (!$this->zfcUserAuthentication()->hasIdentity()) {
            /* redirect to the login redirect route */
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }

        $form = $this->getChangeEmailForm();
        $request = $this->getRequest();
        $request->getPost()->set('identity', $this->getUserService()->getAuthService()->getIdentity()->getEmail());

        $fm = $this->flashMessenger()->setNamespace('change-email')->getMessages();
        if (isset($fm[0])) {
            $status = $fm[0];
        } else {
            $status = null;
        }

        $prg = $this->prg(static::ROUTE_CHANGEEMAIL);
        if ($prg instanceof Response) {
            return $prg;
        } elseif ($prg === false) {
            return array(
                'status' => $status,
                'changeEmailForm' => $form,
            );
        }

        $form->setData($prg);

        if (!$form->isValid()) {
            return array(
                'status' => false,
                'changeEmailForm' => $form,
            );
        }

        $change = $this->getUserService()->changeEmail($prg);

        if (!$change) {
            $this->flashMessenger()->setNamespace('change-email')->addMessage(false);
            return array(
                'status' => false,
                'changeEmailForm' => $form,
            );
        }

        $this->flashMessenger()->setNamespace('change-email')->addMessage(true);
        return $this->redirect()->toRoute(static::ROUTE_CHANGEEMAIL);
    }

    /**
     * Getters/setters for DI stuff
     */
    public function getUserService() {
        if (!$this->userService) {
            $this->userService = $this->getServiceLocator()->get('zfcuser_user_service');
        }
        return $this->userService;
    }

    public function setUserService(UserService $userService) {
        $this->userService = $userService;
        return $this;
    }

    public function getRegisterForm() {
        if (!$this->registerForm) {
            $this->setRegisterForm($this->getServiceLocator()->get('zfcuser_register_form'));
        }
        return $this->registerForm;
    }

    public function setRegisterForm(Form $registerForm) {
        $this->registerForm = $registerForm;
    }

    public function getLoginForm() {
        if (!$this->loginForm) {
            $this->setLoginForm($this->getServiceLocator()->get('zfcuser_login_form'));
        }
        return $this->loginForm;
    }

    public function getLoginBoxForm() {
        if (!$this->loginBoxForm) {
            $this->setLoginForm($this->getServiceLocator()->get('zfcuser_login_box_form'));
        }
        return $this->loginBoxForm;
    }

    public function setLoginForm(Form $loginForm) {
        $this->loginForm = $loginForm;
        $fm = $this->flashMessenger()->setNamespace('zfcuser-login-form')->getMessages();
        if (isset($fm[0])) {
            $this->loginForm->setMessages(
                    array('identity' => array($fm[0]))
            );
        }
        return $this;
    }

    public function getChangePasswordForm() {
        if (!$this->changePasswordForm) {
            $this->setChangePasswordForm($this->getServiceLocator()->get('zfcuser_change_password_form'));
        }
        return $this->changePasswordForm;
    }

    public function setChangePasswordForm(Form $changePasswordForm) {
        $this->changePasswordForm = $changePasswordForm;
        return $this;
    }

    /**
     * set options
     *
     * @param UserControllerOptionsInterface $options
     * @return UserController
     */
    public function setOptions(UserControllerOptionsInterface $options) {
        $this->options = $options;
        return $this;
    }

    /**
     * get options
     *
     * @return UserControllerOptionsInterface
     */
    public function getOptions() {
        if (!$this->options instanceof UserControllerOptionsInterface) {
            $this->setOptions($this->getServiceLocator()->get('zfcuser_module_options'));
        }
        return $this->options;
    }

    /**
     * Get changeEmailForm.
     *
     * @return changeEmailForm.
     */
    public function getChangeEmailForm() {
        if (!$this->changeEmailForm) {
            $this->setChangeEmailForm($this->getServiceLocator()->get('zfcuser_change_email_form'));
        }
        return $this->changeEmailForm;
    }

    /**
     * Set changeEmailForm.
     *
     * @param changeEmailForm the value to set.
     */
    public function setChangeEmailForm($changeEmailForm) {
        $this->changeEmailForm = $changeEmailForm;
        return $this;
    }

}


??

??