/**
     * @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;
        }
    }
    /**
     * @return array
     */
    public static function applicationList()
    {
        # Hotfix #23450 note-8
        if ( !isset($_COOKIE['remember_me']) )
        {
            $cookieExpiration = time() + eZINI::instance('merck.ini')->variable('TIBCOCookieSettings', 'TIBCOCookieExpiration');
            $uuid = MMUsers::getCurrentUserId();
            setcookie('remember_me', MMUserLogin::encryptText(json_encode($uuid)), $cookieExpiration, '/', CookieTool::getCookieDomain());
        }

        $out = array('applicationList' => array());
        $host = 'http://' . self::host();

        if ( isset($_POST['application']) )
        {
            $applicationIdList = array((int) $_POST['application']);
        }
        else
        {
            $applicationIdList = AppBarControl::instance()->applicationIds();
        }

        foreach ( $applicationIdList as $applicationId )
        {
            if ( !is_numeric($applicationId) )
            {
                continue;
            }
            $applicationLocalized = CacheApplicationTool::buildLocalizedApplicationByApplication($applicationId);
            $application = ($applicationLocalized) ? $applicationLocalized->applicationObject() : null;

            if ( $applicationLocalized )
            {
                $application = $applicationLocalized->applicationObject();
            }

            if ( isset($application) )
            {
                $applicationType = $application->applicationType();

                $icons = array(
                    'icon' => array(
                        'path' => '',
                        'md5' => '',
                        'file' => 'ico.png',
                    ),
                    'icon_hd' => array(
                        'path' => '',
                        'md5' => '',
                        'file' => 'ico_notext_hd.png',
                    ),
                    'icon_active' => array(
                        'path' => '',
                        'md5' => '',
                        'file' => 'ico_notext_active.png',
                    ),
                    'icon_active_hd' => array(
                        'path' => '',
                        'md5' => '',
                        'file' => 'ico_notext_active_hd.png'
                    ),
                );

                foreach($icons as $key => $iconData)
                {
                    $path = sprintf('apps/%s/%s', $application->attribute('identifier'), $iconData['file']);
                    $fullPath = StaticData::clusterFilePath(ClusterTool::clusterIdentifier(), $path);
                    if ($fullPath)
                    {
                        $icons[$key]['path'] = StaticData::externalUrl(ClusterTool::clusterIdentifier(), $path);
                        $icons[$key]['md5'] = md5_file($fullPath);
                    }
                }

                $path = '/' . $applicationLocalized->attribute('url');
                $url = $host . $path;
                if ( $application->isPureExternal() )
                {
                    $url = $applicationLocalized->attribute("external_url");
                }

                $outApplicationListArray = array(
                    'id'         => $applicationId,
                    'identifier' => $application->attribute('identifier'),
                    'name'       => $applicationLocalized->attribute('name'),
                    'headline'   => $applicationLocalized->attribute('headline'),
                    'type'       => $applicationType->attribute('internal_type'),
                    'url'        => $url,
                    'path'       => $path,
                    'javascript' => self::getJavascript($application->attribute('identifier'), 'application'));

                foreach($icons as $key => $icon)
                {
                    $outApplicationListArray[$key] = array(
                        '100' => array('path' => $icon['path'], $icon['md5']),
                    );
                }
                $out['applicationList'][] = $outApplicationListArray;
            }
        }
        return $out;
    }
    /**
     * @param array $token
     * @return string
     */
    protected static function encryptToken($token)
    {
        $encryptedToken = MMUserLogin::encryptText(json_encode($token));

        return str_replace(array('+', '/'), array('|', '_'), $encryptedToken);
    }
    /**
     * @param array $params
     * @return array
     */
    public function writeUnmapped($params = null)
    {
        if (!$params && !is_array($params))
        {
            $params = array();
            foreach ($_POST as $k => $v)
            {
                $params[$k] = $v;
            }
        }

        $esbParams = $this->getWriteParameters($params);
        $result = $this->callEsbWrite($esbParams);

        $uuid = MMUsers::getCurrentUserId();
        $ticketParams = array(
            'Username' => $uuid,
            'Country_of_registration' => $this->getCountryOfRegistration(),
        );

        $ticketParams = array_merge($params, $ticketParams);

        $result['Ticket'] = MMUserLogin::encryptText( json_encode( $ticketParams ) );

        return $result;
    }
    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 );
        }
    }