/**
     * @return string
     */
    protected function validateToU()
    {
        if( !self::user() )
            return false;

        self::user()->toUValidated(true);

        $context = ContextTool::instance()->backUrl();
        $context = isset( $_POST['context'] ) ? $_POST['context'] : '/';

        // @todo: update ESB by sending validation status
        $esbResult = new ESBResult();
        $userService = ESBFactory::getUserService();

        if(SolrSafeOperatorHelper::featureIsActive('UUMP'))
        {
            
            $result = $userService->read(self::user()->attribute('uuid'));
            ServiceLoginUUMP::populateESBResult($esbResult, $result);
        }
        else
        {
            $result = ServiceLogin::readCall(self::user()->attribute('uuid'), $esbResult);
            ServiceLogin::populateESBResult($esbResult, $result);
        }

        $esbResult->userName = self::user()->attribute('uuid');
        $esbResult->termsOfUse = 'Y';
        $esbResult->privacyPolicy = 'Y';

        if( SolrSafeOperatorHelper::featureIsActive('UUMP') || (ClusterTool::clusterIdentifier() == "cluster_at") )
        {
            $esbResult->termsOfUse = '1';
            $esbResult->privacyPolicy = '1';
        }
        $esbResult->countryOfRegistration = self::user()->attribute( 'country' );

        $userService->write($esbResult->toServiceAgreementTicket());

        // if the ESB call fails, we still validate the user input to let him access the content
        $esbResult->forceToUValidated = true;
        $esbResult->sessionID = $_COOKIE[self::iniMerck()->variable('TIBCOCookieSettings', 'TIBCOCookieName')];

        $loginResult = MMUserLogin::esbLogin( self::user()->attribute('uuid'), $esbResult, false, $context );
        if ( $loginResult )
        {
            // Stringify params
            $strParams = json_encode( $loginResult['params'] );

            // Encrypts params
            $encryptedParams = MMUserLogin::encryptText( $strParams );
            // Redirect to PHP-ESI
            $redirectURL = ContextTool::instance()->domain()."/loginActions.php?context=" . urlencode( $loginResult['destUrl'] ) . "&params=" . urlencode( $encryptedParams );
        
            return $redirectURL;
        }
    }
    /**
     * Relog the user if rememberme is checked and not logged in
     * @param bool $try
     * @throws Exception
     * @return boolean
     */
    public static function relog($try = false)
    {
        $out = array('session_lifetime' => intval(eZINI::instance('merck.ini')->variable('WSMobile', 'SessionLifetime')));

        $backendUrl = eZINI::instance('merck.ini')->variable('WSMobile', 'BackEndUrl');
        $c = curl_init();
        curl_setopt($c, CURLOPT_URL, $backendUrl.'/mobile.php');
        curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($c, CURLOPT_NOBODY, true);
        curl_setopt($c, CURLOPT_HEADER, true);
                        
        if ( eZINI::instance('merck.ini')->hasVariable('WSMobile', 'BackEndHeader') )
        {
            /* @type $headers array */
            $headersList = array();
            $headers = eZINI::instance('merck.ini')->variable('WSMobile', 'BackEndHeader');
            foreach ( $headers as $header => $value )
            {
                $headersList[] = sprintf('%s: %s', $header, $value);
            }
            curl_setopt($c, CURLOPT_HTTPHEADER, $headersList);
        }
        $headers = getallheaders();
        if( isset($headers['Cookie']) )
            curl_setopt($c, CURLOPT_COOKIE, $headers['Cookie']);

        $result = curl_exec($c);
        $errno = curl_errno($c);
        $error = curl_error($c);
        curl_close($c);
        
        $loggedOnBackend = true;
        if(    preg_match( '#^HTTP/1.1 302 Found#', $result )
               || (
                   preg_match( '#Set-Cookie: .*BSESSIONID=(?P<baksess>.*?);#m', $result, $m )
                && isset( $_COOKIE['BESSIONID'] )
                && $_COOKIE['BESSIONID'] != $m['baksess']
               )
        ){
            $loggedOnBackend = false;
        }
        
        if ( self::isLogged() && $loggedOnBackend )
        {
            return $out;
        }
        
        if ( isset($_COOKIE['remember_me']) )
        {
            $db = MMDB::instance();
            $corQuery = "SELECT r.code
            FROM bo_reference r
            JOIN bo_cluster_has_reference chr ON chr.cluster_identifier = '%s'
            WHERE r.type = 'country' AND r.id = chr.reference_id";
            $cor = $db->arrayQuery( sprintf( $corQuery, ClusterTool::clusterIdentifier() ) );
            if( count( $cor ) > 0 )
                $countryOfRegistration = $cor[0]['code'];
            else
                $countryOfRegistration = eZINI::instance('site.ini')->variable('RegionalSettings', 'CountryOfRegistration');

            $uuid = MMUserLogin::uncryptTicket($_COOKIE['remember_me']);
            $context = isset( $_REQUEST['context'] ) ? $_REQUEST['context'] : ContextTool::instance()->domain() . '/';
            $readService = ESBFactory::getUserService();
            $parameters  = $readService->getFormParameters($uuid);
            $datas       = $readService->read( $parameters, $uuid );
            $esbResult   = new ESBResult();

            $isPopulated = ServiceLoginUUMP::populateESBResult( $esbResult, $datas );
            
            if ( !$isPopulated )
            {
                // error log caught on WS stack
                return null;
            }

            $loginResult = MMUserLogin::esbLogin( $uuid, $esbResult, true, $context );
            
            if( is_null( $loginResult ))
            {
                $out['status'] = 'failed';
                $out['errorCode'] = 9; 
                $out['msg'] = 'User not found.';
                return $out;
            }
            
            $user = MMUsers::fetchByIdAndCountry($loginResult['params']['Username'], $countryOfRegistration);

            $loginResult['params']['mmSettings']       = $user->getMMSettings();
            $loginResult['params']['unorderedAppList'] = $user->getApplicationList();
            $loginResult['params']['alterboxMsgReset'] = $user->hasPreference('alterboxMsgReset') ? $user->getPreferences('alterboxMsgReset') : true;

            $logged = self::backendLog($loginResult['params']);

            if ( $logged )
            {
                return $out;
            }
        }

        if ( $try !== true )
        {
            throw new Exception('Missing "remember_me" cookie', 30);
        }

        return false;
    }
    /**
     * Reset password
     *
     * @return array
     */
    public function r()
    {
        $http = BlockDefault::http();
        $tokenData = self::decryptToken($http->postVariable('Token'));
        $token = $tokenData['token'];
        $userId = $tokenData['userId'];
        $expirationDate = strtotime('+1day',(integer)($tokenData['expirationDate'] / 1000));
        $password = $http->postVariable('new_password');
        $confirmedPassword = $http->postVariable('new_password_check');
        $now = time();
        $isConsult = (bool) $http->postVariable('consult');

        if ($now > $expirationDate)
        {
            if ( $isConsult )
            {
                $redirectUrl = $this->getCustomParameter('ConsultExpiredUrl');  
            }
            else
            {
                $redirectUrl = $this->getCustomParameter('ExpiredUrl');  
            }
            return array(
                'errorCode' => ResponseError::ERROR_TOKEN_EXPIRED,
                'redirectUrl' => $redirectUrl
            );
        }

        $esbClient = self::getEsbClient();
        $isTokenValid = $esbClient->checkToken($userId, $token, $tokenData['expirationDate']);

        if (!$isTokenValid)
        {
            if ( $isConsult )
            {
                $redirectUrl = $this->getCustomParameter('ConsultAlreadyChangedUrl');  
            }
            else
            {
                $redirectUrl = $this->getCustomParameter('AlreadyChangedUrl');  
            }
            return array(
                'errorCode' => ResponseError::ERROR_INVALID_TOKEN,
                'redirectUrl' => $redirectUrl
            );
        }

        try
        {
            $response = $esbClient->changePassword($userId, $password, $confirmedPassword);
            if ($response === true)
            {
                if( SolrSafeOperatorHelper::featureIsActive( 'ExactTarget' ) && SolrSafeOperatorHelper::featureIsActive( 'UUMP' ) )
                {
                    self::sendSuccessMail($tokenData['email'], $userId, $isConsult);
                }
                else
                {
                    self::sendSuccessMail($tokenData['userId'], $userId);
                }
            }

            $esbResult = new ESBResult();
            $userService = ESBFactory::getUserService();
            $result = $userService->read(null, $userId);
            ServiceLoginUUMP::populateESBResult($esbResult, $result);
            $loginResult = MMUserLogin::esbLogin($userId, $esbResult);

            if ( $isConsult )
            {
                $redirectUrl = $this->getCustomParameter('ConsultSuccessUrl');  
            }
            else
            {
                $redirectUrl = $this->getCustomParameter('SuccessUrl');  
            }
            $params = array(
                'uuid' => $userId,
                'h' => sha1( eZINI::instance( 'merck.ini' )->variable( 'TicketLogin', 'DESKey' ) . $userId ),
                'context' => $redirectUrl
            );

            //CookieTool::setCookie('h', sha1( eZINI::instance( 'merck.ini' )->variable( 'TicketLogin', 'DESKey' ) . $userId ), time() + 3600);

            $url = '/service/relog?' . http_build_query($params);
            return array(
                'errorCode' => ResponseError::SUCCESS,
                'redirectUrl' => $url,
            );
        }
        catch (\Exception $e)
        {
            return array(
                'errorCode' => ResponseError::ERROR_REQUEST_EXECUTION,
                'msg' => $e->getMessage()
            );
        }
    }
    public function relog()
    {
        $uuid       = isset( $this->_input['uuid'] ) ? $this->_input['uuid'] : null;
        //$h          = isset( $_COOKIE['h'] ) ? $_COOKIE['h'] : null;
        $h          = isset( $this->_input['h'] ) ? $this->_input['h'] : null;
        $context    = isset( $this->_input['context'] ) ? $this->_input['context'] : ContextTool::instance()->domain().'/';

        //delete session id cookie
        //unset($_COOKIE['h']);

        if ( is_null( $uuid ) || is_null( $h ) )
        {
            MMUserLogin::logError( $uuid, null, null, 'Empty uuid or hash given on Relog' );
            return $this->relogError();
        }

        if ( $h != sha1( eZINI::instance( 'merck.ini' )->variable( 'TicketLogin', 'DESKey' ) . $uuid ) )
        {
            MMUserLogin::logError( $uuid, null, null, 'Invalid hash given on Relog' );
            return $this->relogError();
        }

        UserLog::instance()->action( 'rememberme' )->uuid( $uuid )->step( 'received' )->store();

        $esbResult = new ESBResult();
        
        if ( !SolrSafeOperatorHelper::featureIsActive('UUMP') )
        {
            $datas = static::readCall( $uuid, $esbResult );
        }
        else
        {
            $readService = ESBFactory::getUserService();
            $parameters  = $readService->getFormParameters($uuid);
            $datas       = $readService->read( $parameters, $uuid );
        }

        $isPopulated = static::populateESBResult( $esbResult, $datas );
        $this->_esbResult = $esbResult;
        
        if ( !$isPopulated )
        {
            // error log caught on WS stack
            return $this->relogError();
        }
        
        $esbResult->login = ( $esbResult->userId === $uuid );
        

        if ( !$isPopulated )
        {
            // error log caught on WS stack
            return $this->relogError();
        }

        $loginResult = MMUserLogin::esbLogin( $uuid, $esbResult, true, $context );

        if ( $loginResult )
        {
            $this->_isLoginSuccessful = true;
            $this->_destUrl = $loginResult['destUrl'];

            UserLog::instance()
                ->uuid( $uuid )
                ->esb_status( 'Accepted' )
                ->store();

            $user = MMUsers::getCurrentUserObject();

            $sl = SystemLocale::fetchByClusterAndSystem( ClusterTool::clusterIdentifier(), 'esb_language' );
            $customerLanguage = !is_null( $sl ) ? $sl : eZINI::instance()->variable( 'RegionalSettings', 'ContentObjectLocale' );

            if( SolrSafeOperatorHelper::featureIsActive( 'AsynchronousAnalyticsLoginCall' ) && SolrSafeOperatorHelper::feature( 'AsynchronousAnalyticsLoginCall', 'GoogleAnalytics' ) )
            {
                $amq = new ActiveMQManager();
                $domains = eZINI::instance( 'merck.ini' )->variable( 'DomainMappingSettings', 'ClusterDomains' );
                $domain  = isset( $domains[ClusterTool::clusterIdentifier()] ) ? $domains[ClusterTool::clusterIdentifier()] : 'unidentified.univadis.com';
                $gasl = SystemLocale::fetchByClusterAndSystem( ClusterTool::clusterIdentifier(), 'ga_visitor_country' );
                $gaCountry = !is_null( $gasl ) ? $gasl : $user->attribute( 'country' );
                $gaParams = array(
                    'v'   => 1,
                    'tid' => 'UA-41415675-6',
                    'uid' => $uuid,
                    't'   => 'event',
                    'ec'  => 'esb',
                    'ea'  => 'login',
                    'ni'  => 1,
                    'cd1' => $uuid,
                    'cd2' => 'logged',
                    'cd7' => $gaCountry,
                    'dh'  => preg_replace( '#^.*?\.#', '', $domain ),
                );
                $gaParams = 'https://ssl.google-analytics.com/collect?' . http_build_query( $gaParams );
                $amq->sendMessageToQueue( 'portail.analytics.google', $gaParams );
            }

            // Stringify params
            $loginResult['params'][AppBarControl::COOKIE_UNORDERED_APPLIST_KEY] = $user->getApplicationList();
            $loginResult['params'][MMUsers::COOKIE_KEY] = $user->getMMSettings();
            $strParams = json_encode( $loginResult['params'] );

            // Encrypts params
            $encryptedParams = MMUserLogin::encryptText( $strParams );
            // Redirect to PHP-ESI
            $redirectURL = "/loginActions.php?context=" . urlencode( $loginResult['destUrl'] ) . "&params=" . urlencode( $encryptedParams );
            if ( !MMUsers::checkCookieLaw() && SolrSafeOperatorHelper::feature('CookieLaw', 'Mode') == MMUsers::COOKIE_LAW_ACTIVE_VERSION_KEY)
            {
                $cookieLawPage = SolrSafeOperatorHelper::feature( 'CookieLaw', 'CookieLawPage' );
                $redirectURL   = ( $cookieLawPage ? $cookieLawPage : '/page/cookie-law' );
            }

            // Branding reconsent check, done only if:
            // 1. feature ToUPPPopin enabled
            // 2. Always on WEB with this feature
            // 3. Only on mobile, whne setting showOnMobile is ON.
            if
            (
                SolrSafeOperatorHelper::featureIsActive( 'ToUPPPopin')
                &&
                (
                    !ContextTool::instance()->isMobile()
                    ||
                    ( ContextTool::instance()->isMobile() && SolrSafeOperatorHelper::feature('ToUPPPopin','showOnMobile') )
                )
            )
            {
                $displayReconsent = $this->checkTouPPPopin( $datas );
                // if we need to ask user for reconsent ($displayReconsent - taken fromESB response) we decide if we want page below if:
                // 1. On WEB and useDedicatedPage setting is ON
                // 2. On mobile and useDedicatedPageMobile setting is ON
                if (
                    $displayReconsent
                    &&
                    (
                        ( !ContextTool::instance()->isMobile() && SolrSafeOperatorHelper::feature( 'ToUPPPopin', 'useDedicatedPage' ) )
                        ||
                        ( ContextTool::instance()->isMobile() && SolrSafeOperatorHelper::feature( 'ToUPPPopin', 'useDedicatedPageMobile' ) )
                    )
                )
                {
                    CookieTool::destroyCookie( 'displayToUPPPopin' );
                    CookieTool::destroyCookie( 'displayToUPPPopin', '/', null );
                    CookieTool::setCookie( 'displayToUPPPage', 1, time() + ( 2 * 24 * 60 * 60 ) );
                    $touPpPageUrl = eZINI::instance( 'site.ini' )->variable( 'SiteSettings', 'ToUPPPageUrl' ) . "/#?tpc=" . urlencode( $loginResult['destUrl'] );
                    $redirectURL = "/loginActions.php?context=" . urlencode( $touPpPageUrl ) . "&params=" . urlencode( $encryptedParams );
                }
            }

            $this->response( $redirectURL );
        }
    }