/**
     * @param string $username
     * @param ESBResult $esbResult
     * @return array
     */
    public static function readCall( $username, $esbResult )
    {
        $countryOfRegistration = self::getCountryOfRegistration();
        $params = eZINI::instance('merck.ini')->variable( 'EsbSettings', 'AvailableParams' );

        if ( !isset( $params ) || !is_array( $params ) )
        {
            MMUserLogin::logError( $username, null, $esbResult->toTicket(), 'Missing esb login parameters. Check merck.ini configuration.' );
            return;
        }

        if( !in_array( 'Registration_date', $params ) && SolrSafeOperatorHelper::featureIsActive( 'GoogleAnalytics' ) )
        {
            $params[] = 'Registration_date';
        }
        
        // List of needed profile information
        $readParameters = array(
            'Data' => array(
                'Username' => $username,
                'Params' => $params
            ),
            'cr' => $countryOfRegistration
        );

        // Fires a request to get user profile data
        return WSHelper::call( "read", $readParameters );
    }
    /**
     * Logs the user in eZPublish taking the data from the ESB
     * /!\ Does not check login / password. This check needs to be done before!!!!!
     *
     * @param string $uuid
     * @param ESBResult $esbResult
     * @param boolean $rememberMe
     * @param boolean $context
     * @return array destUrl or null if error
     */
    public static function esbLogin( $uuid, $esbResult, $rememberMe = false, $context = false )
    {
        $localizedLoginApplication = CacheApplicationTool::buildLocalizedApplicationByIdentifier( 'login' );

        $validationStatus = $esbResult->getValidationStatus();
        if ( $validationStatus == 'PV' && $localizedLoginApplication->getCustomParameter( 'RestrictPendingUsers' ) == 1 )
        {
            UserLog::instance()->esb_status('Pending')->store();
            
            $redirectURL = eZINI::instance( 'site.ini' )->variable( 'SiteSettings', 'PendingUserStaticPage' );
            if( SolrSafeOperatorHelper::featureIsActive( 'GoogleAnalytics' ) )
            {
                $redirectURL = $redirectURL . '#?vs=PV';
            }
            header( "Location: $redirectURL" );
            eZExecution::cleanExit();
        }
        else if ( $validationStatus == 'RP' && $localizedLoginApplication->getCustomParameter( 'RestrictRejectedUsers' ) == 1 )
        {
            UserLog::instance()->esb_status('Rejected')->store();
            
            $redirectURL = eZINI::instance( 'site.ini' )->variable( 'SiteSettings', 'RejectedUserStaticPage' );
            if( SolrSafeOperatorHelper::featureIsActive( 'GoogleAnalytics' ) )
            {
                $redirectURL = $redirectURL . '#?vs=RP';
            }
            header( "Location: $redirectURL" );
            eZExecution::cleanExit();
        }

        if( is_null($esbResult->countryOfRegistration))
            $esbResult->countryOfRegistration = eZINI::instance()->variable( 'RegionalSettings', 'CountryOfRegistration' );

        if( is_null($esbResult->userSpecialty) )
        {
            self::logError( $uuid, null, $esbResult->toTicket(), 'Missing main specialty' );
            return null;
        }

        if( is_null( $esbResult->customerType ) )
        {
            self::logError( $uuid, null, $esbResult->toTicket(), 'Missing Customer type' );
            return null;
        }

        // temporary fix to parse forced string prepended with A
        $userSpeciality = $esbResult->userSpecialty = preg_replace( '#^A#', '', $esbResult->userSpecialty );
        $customerType = $esbResult->customerType = preg_replace( '#^A#', '', $esbResult->customerType );

        if( !preg_match('#^216\.#', $userSpeciality) )
        {
            self::logError( $uuid, null, $esbResult->toTicket(), "Invalid User specialty: $userSpeciality" );
            return null;
        }
        if( !preg_match( '#^102\.#', $customerType ) )
        {
            self::logError( $uuid, null, $esbResult->toTicket(), "Invalid Customer type: $customerType" );
            return null;
        }

        $esbResult->userName = $uuid;
        $esbResult->rememberMe = $rememberMe;
        $decodedContext = urldecode(urldecode($context));

        // If we need to check the Terms of Use for the cluster, we need to skip my-newsletters app for legal reasons (1-click unsubscribe).
        $toUToCheck = (    eZINI::instance( 'merck.ini')->hasVariable( 'LoginSettings', 'ToUCheck')
            && eZINI::instance( 'merck.ini' )->variable( 'LoginSettings', 'ToUCheck') == 'enabled'
            && !strpos($decodedContext, 'my-newsletters')
        );

        if( $toUToCheck ){
            $toUValidated = ( $esbResult->termsOfUse );
            $toUValidated &= ( $esbResult->privacyPolicy );

            if( $esbResult->forceToUValidated )
                $toUValidated = true;

            $esbResult->toUValidated = (bool)$toUValidated;
        }

        // Check if we need to check the autologin status for the cluster
        if( SolrSafeOperatorHelper::featureIsActive('RestrictAutologgedInUsers') && SolrSafeOperatorHelper::feature('RestrictAutologgedInUsers', 'Restricted')
            && in_array( $esbResult->autologin, array( 1, "yes" ) ))
        {
            $esbResult->autologin = true;
        }
        else
        {
            $esbResult->autologin = false;
        }

        if ( self::loginUser( $esbResult->toTicket() ) )
        {
            $user = MMUsers::getCurrentUserObject();

            $destUrl = ContextTool::instance()->contextUrl( $context );

            if( $toUToCheck && !$user->toUValidated() )
            {
                if( preg_match('#^(?:https?://[^/]+)'.eZINI::instance()->variable('SiteSettings', 'ToUAgreementPage').'?#', $destUrl) )
                    $destUrl = '/';
                $destUrl = preg_replace('#^https?://([^?]+)//#', '\1', $destUrl);
                $destUrl = eZINI::instance()->variable('SiteSettings', 'ToUAgreementPage')
                    .'?context='.urlencode($destUrl);
            }

            // Store user action in mm_front_user_action table
            $mmFrontUserAction = MMFrontUserAction::fetchByUsername( $esbResult->userName );
            if ( $mmFrontUserAction instanceof MMFrontUserAction )
            {
                $mmFrontUserAction->LastVisitDate = date( 'Y-m-d H:i:s' );
                $mmFrontUserAction->Processed = MMFrontUserAction::PROCESSED;
                $mmFrontUserAction->store(array('processed', 'last_visit_date'));
            }
            else
            {
                $mmFrontUserAction = MMFrontUserAction::create( array(
                        'id' => null,
                        'username' => $esbResult->userName,
                        'country_registration' => $esbResult->countryOfRegistration,
                        'processed' => MMFrontUserAction::PROCESSED,
                        'last_visit_date' => date( 'Y-m-d H:i:s' ),
                ) );
                $mmFrontUserAction->store();
            }

            if ( $rememberMe )
            {
                $userKey = !is_null($esbResult->userId) ? $esbResult->userId : $uuid;
                $cookieExpiration = time() + eZINI::instance( 'merck.ini' )->variable( 'TIBCOCookieSettings', 'TIBCOCookieExpiration' );
               
                //fix to remove the old cookie for new sso cluster #39800
                $splitDepth = eZINI::instance('merck.ini')->variable( 'CookieSettings', 'CookieDomainSplitDepth' );
                $splitDepth= 0;
                if( $splitDepth == 0 ) {
                    $cookieDomain = preg_replace('#^(https?://)?([^.]+.){1}#', '', contextTool::instance()->domain() );
                    $cookieExpirationToDelete = time() - 2000;
                    setcookie( 'remember_me', '', self::encryptText(json_encode($userKey)), $cookieExpirationToDelete, '/', $cookieDomain );
                }//end fix
                setcookie( 'remember_me', self::encryptText(json_encode($userKey)), $cookieExpiration, '/', CookieTool::getCookieDomain() );
            }
            else
            {
                $cookieExpiration = 0;
            }

            // Set cookie
            $esbSessionId = $esbResult->sessionID;
            $countryCode = '';
            if ( !empty( $esbSessionId ) )
            {
                $cookieName   = eZINI::instance( 'merck.ini' )->variable( 'TIBCOCookieSettings', 'TIBCOCookieName' );
                $esbSessionId = str_replace( ' ', '+', '"'.urldecode($esbSessionId).'"' );
                setrawcookie( $cookieName, $esbSessionId, $cookieExpiration, '/', CookieTool::getCookieDomain() );
            }
            
            // set residenceCountry country code for google tag manager
            $countryOfResidence = $esbResult->othersParams['countryOfResidence'] ? $esbResult->othersParams['countryOfResidence'] : ($esbResult->othersParams['Country_of_residence'] ? $esbResult->othersParams['Country_of_residence'] : null );
            if($countryOfResidence)
            {
                if($countryOfResidence > 2)
                {
                    $countries = SolrSafeOperatorHelper::clusterIni('CountryCode','CountryCode','merck.ini');
                    $countryCode = $countries[$esbResult->othersParams['Country_of_residence']];
                }
            }
            else
            {
                $countryCode = $esbResult->countryOfRegistration;
            }
            
            $esbResult -> setResidenceCountry($countryCode);
              
            return array(
                'destUrl' => $destUrl,
                'params'  => $esbResult->toTicket(),
            );
        }

        return null;
    }
    protected function response( $uri )
    {
        switch( self::redirectMode() )
        {
            case self::LOGIN_REDIRECT_MODE_HTTP:
                header( "Location: $uri" );
                break;
            case self::LOGIN_REDIRECT_MODE_JS:
                header( "Content-type: application/json");
                if ( SolrSafeOperatorHelper::featureIsActive( 'UUMP' ) )
                {
                    header( "Accept: application/json");
                }
                echo json_encode( $uri );
                break;
            case self::LOGIN_REDIRECT_MODE_JSON:
                header('Content-type: application/json');

                $result = array();

                $result['status']           = $this->_isLoginSuccessful ? 0 : 1;
                $result['LoginRedirect']    = $this->_isLoginSuccessful ? $this->_destUrl : $uri;

                $mmUser = MMUsers::getCurrentUserObject();

                if ( $this->_isLoginSuccessful )
                {
                    $result['User']                     = $this->_esbResult->toArray();
                    $result['User']['mmSettings']       = $mmUser->getMMSettings();
                    $result['User']['unorderedAppList'] = $mmUser->getApplicationList();
                    $result['User']['alterboxMsgReset'] = $mmUser->hasPreference('alterboxMsgReset') ? $mmUser->getPreferences('alterboxMsgReset') : true;
                    
                    $result['cookies'] = CookieTool::setCookies();

                    $salutations    = SolrSafeOperatorHelper::clusterIni('Salutations', 'Salutation', 'merck.ini' );
                    $localeMap      = SolrSafeOperatorHelper::clusterIni('ESBSettings', 'ESBLocaleMap', 'merck.ini' );
                    $locale         = $this->_esbResult->language;
                    if ( isset($localeMap[$locale]) )
                        $locale = $localeMap[$locale];

                    $result['commonauth']       = array(
                        'user_id'           => $this->_esbResult->userName,
                        'MSDID'             => ( isset( $this->_esbResult->othersParams['crmMemberId'] ) && !empty($this->_esbResult->othersParams['crmMemberId']) ) ? $this->_esbResult->othersParams['crmMemberId'] : $this->_esbResult->countryOfRegistration.'000000X',
                        'userId'            => $this->_esbResult->userId,
                        'UUMPID'            => $this->_esbResult->userId,
                        'UVDSPam'           => null,
                        'ValidationStatus'  => $this->_esbResult->getValidationStatus(),
                        'ODMNum'            => null,
                        'ValidationDate'    => ($this->_esbResult->registrationDate) ? date('d-M-y', strtotime($this->_esbResult->registrationDate)) : null,
                        'TVFCode'           => 'MSD',
                        'Email'             => $this->_esbResult->emailAddress,
                        'cc'                => $this->_esbResult->countryOfRegistration,
                        'PhoneNum'          => isset($this->_esbResult->othersParams['phoneNumber']) ? $this->_esbResult->othersParams['phoneNumber'] : null,
                        'ZipCode'           => $this->_esbResult->postalCode,
                        'zipCode'           => $this->_esbResult->postalCode,
                        'Salutation'        => isset($salutations[$this->_esbResult->othersParams['salutation']]) ? $salutations[$this->_esbResult->othersParams['salutation']] : null,
                        'City'              => $this->_esbResult->city,
                        'Street'            => isset($this->_esbResult->othersParams['addressLine2']) ? $this->_esbResult->othersParams['addressLine2'] : null,
                        'Address'           => isset($this->_esbResult->othersParams['addressLine1']) ? $this->_esbResult->othersParams['addressLine1'] : null,
                        'Country'           => $this->_esbResult->countryOfRegistration,
                        'CustomerType'      => $this->_esbResult->customerType,
                        'SiteCRMStatus'     => null,
                        'LastName'          => $this->_esbResult->lastName,
                        'FirstName'         => $this->_esbResult->firstName,
                        'specialty'         => $this->_esbResult->userSpecialty,
                        'lng'               => LocaleTool::languageISO639Code($locale).'_'.LocaleTool::countryISO3166Code($locale),
                        'hostName'          => preg_replace('#^https?://#', '', ContextTool::instance()->domain()),
                        'LicenseNumber'     => isset($this->_esbResult->othersParams['licenseNumber']) ? $this->_esbResult->othersParams['licenseNumber'] : null,
                    );

                }
                echo json_encode($result);
                break;
        }
        eZExecution::cleanExit();
    }