/**
     * Creates a profile
     *
     * @return array
     */
    public function create()
    {
        if( SolrSafeOperatorHelper::featureIsActive( 'RegistrationSettings' ) && SolrSafeOperatorHelper::feature( 'RegistrationSettings', 'DisableRegistration' ) == true ) {
            return array( 'data' => array( 'errorCode'=> 9 ) ); 
        }

        // 1st step - Checks fields
        $r = $this->checkUsername();
        if ( $r !== true )
        {
            return $r;
        }

        $r = $this->checkEmail();
        if ( $r !== true )
        {
            return $r;
        }
        $isHtmlEntitiesAlowed = self::isAddressEncodeAllowedOnCluster();

        // 2nd step - Process fields
        $addressLine1 = $this->getBusinessNameMapping( 'addressLine1' );
        if ( isset( $_POST[$addressLine1] ) && !empty( $_POST[$addressLine1] ) && $isHtmlEntitiesAlowed )
        {
            $_POST[$addressLine1] = htmlentities( $_POST[$addressLine1], ENT_QUOTES, 'UTF-8' );
        }

        $addressLine2 = $this->getBusinessNameMapping( 'addressLine2' );
        if ( isset( $_POST[$addressLine2] ) && !empty( $_POST[$addressLine2] ) && $isHtmlEntitiesAlowed  )
        {
            $_POST[$addressLine2] = htmlentities( $_POST[$addressLine2], ENT_QUOTES, 'UTF-8' );
        }

        /* @type $createParams array */
        $params       = array();
        $createParams = SolrSafeOperatorHelper::clusterIni('EsbSettings', 'CreateParamsTypes', 'merck.ini' );
        foreach ( $createParams as $key => $value )
        {
            if ( isset( $_POST[$key] ) )
            {
                $params[$key] = ( trim( $value ) == 'int' ) ? intval( $_POST[$key] ) : $_POST[$key];
            }            
        }

        $actId = $this->getBusinessNameMapping( 'actId' );
        if ( isset( $_REQUEST[$actId] ) )
        {
            $params[$actId] = $_REQUEST[$actId];
        }

        if ( $this instanceof ServiceUserUUMP )
        {
            $params['privacyPolicyDate'] = date('Ymdhis');
        }

        // managing validation status cases
        // 1. Override taken from cluster settings.
        $defaultValidationStatus = SolrSafeOperatorHelper::clusterIni('DefaultValidationStatus', 'DefaultValidationStatus', 'merck.ini' );
        $defaultValidationStatus = !empty( $defaultValidationStatus ) && isset( $defaultValidationStatus ) ? $defaultValidationStatus : 'PV' ;
        if( $this instanceof ServiceUserUUMP && !empty( $defaultValidationStatus ) && isset( $defaultValidationStatus ) )
        {
            $params['validationStatus'] = $defaultValidationStatus;
        }

        // 2. Russian helpdesk-register validates user by default.
        if( isset( $_POST['register-helpdesk']) && $_POST['register-helpdesk'] == 1 && !isset( $_POST['termsOfUse'] ))
        {
            $params['validationStatus'] = 'VP';

            $params['termsOfUse'] = isset( $_POST['helpdeskTermsOfUse']) ? 1 : 0;
            $params['privacyPolicy'] = isset( $_POST['helpdeskPrivacyPolicy']) ? 1 : 0;
        }

        // 3. German "kontakt" validation result.
        if ( $this instanceof ServiceUserUUMP && isset( $params['WEB_SERVICE_AJAX_FIELD_1'] ) )
        {
            if( $params['WEB_SERVICE_AJAX_FIELD_1'] == "kontakt" )
            {
                $params['validationStatus'] = 'PV';
            }
            unset( $params['WEB_SERVICE_AJAX_FIELD_1'] );            
        }

        // 4. German "DocCheck" validation result.
        if ( $this instanceof ServiceUserUUMP && ( isset( $params['DocCheck_username'] ) && $params['DocCheck_username'] != "" ) && ( isset( $params['Password_doccheck'] ) && $params['Password_doccheck'] != "" ) )
        {
            $params['validationStatus'] = 'VP';
            unset( $params['DocCheck_username'] );
            unset( $params['Password_doccheck'] );
        }

        // 5. US 1.8 if user is validated by eshcp we have crmMemberId field stored, so we also must validate user with VP
        if ( SolrSafeOperatorHelper::featureIsActive( "Univadis18Redesign" ) && isset($params['crmMemberId']) && $params['crmMemberId'] != "" )
        {
            $params['validationStatus'] = 'VP';
        }

        // 3rd step - ESB Create
        $sl = SystemLocale::fetchByClusterAndSystem( ClusterTool::clusterIdentifier(), 'esb_language' );
        if( !is_null( $sl ) )
        {
            $language = $sl;
        }
        else
        {
            $language = eZINI::instance( 'site.ini' )->variable( 'RegionalSettings', 'ContentObjectLocale' );
            $merckIni = eZINI::instance( 'merck.ini' );
            if ( $merckIni->hasVariable( 'EsbSettings', 'Language' ) )
            {
                $language = $merckIni->variable( 'EsbSettings', 'Language' );
            }
        }

        $apps = array();
        $appsIds = CountryAppsBar::fetchAppsBarApplicationIds( $_POST[$this->getBusinessNameMapping( 'customerType' )] );
        foreach ( $appsIds as $key => $value )
        {
            $apps[] = array(
                $this->getBusinessNameMapping( 'appId' )    => $value,
                $this->getBusinessNameMapping( 'appOrder' ) => $key + 1
            );
        }

        $subsUni = $this->getUnivadisSubscriptions();
        $subsMsd = $this->getMsdSubscriptions();
        $subsSun = $this->getSunshineAct();

        $consents = array_merge( $subsUni, $subsMsd );
        if(!empty($subsSun))
        {
            $consents = array_merge( $consents, $subsSun );
        }

        if( $createParams[self::SUBSCRIPTION_PHONE_CONSENT] )
        {
            $consents[] = array(
                'consentCode'       => self::SUBSCRIPTION_PHONE_CONSENT,
                'consentStatus'     => !empty( $_POST[self::SUBSCRIPTION_PHONE_CONSENT] ) ? self::SUBSCRIPTION_STATUS_SUBSCRIBED : self::SUBSCRIPTION_STATUS_UNSUBSCRIBED,
                'consentLastUpdate' => time(),
            );
            unset( $params[self::SUBSCRIPTION_PHONE_CONSENT] );
        }

        // Add terms of use, private policies and OptIn consents
        if ( SolrSafeOperatorHelper::featureIsActive( 'ToUPPPopin' ) && ( $this instanceof ServiceUserUUMP ) )
        {
            $touVersion = SolrSafeOperatorHelper::feature( 'ToUPPPopin', 'currentToUConsentVersion' );
            $ppVersion  = SolrSafeOperatorHelper::feature( 'ToUPPPopin', 'currentPPConsentVersion' );

            $consents[] = array(
                'consentCode'       => 'termsOfUse_v' . $touVersion,
                'consentStatus'     => 'S',
                'consentLastUpdate' => time(),
            );

            $consents[] = array(
                'consentCode'       => 'privacyPolicy_v' . $ppVersion,
                'consentStatus'     => 'S',
                'consentLastUpdate' => time()
            );

            $subsOptIn = $this->getOptInSubscriptions();
            if ( !empty( $subsOptIn ) )
            {
                $consents = array_merge( $consents, $subsOptIn );
            }
        }

        $username = $this->getUsername();

        $userSpecialty = $_POST[$this->getBusinessNameMapping( 'userSpecialty' )];
        $mainSpecialty = UserSpecialityContentSpeciality::getContentSpeciality( $userSpecialty );


        $unifiedParameters = array(
            $this->getBusinessNameMapping( 'emailAddress' )          => $_POST[$this->getBusinessNameMapping( 'emailAddress' )],
            $this->getBusinessNameMapping( 'password' )              => $_POST[$this->getBusinessNameMapping( 'password' )],
            $this->getBusinessNameMapping( 'firstName' )             => $_POST[$this->getBusinessNameMapping( 'firstName' )],
            $this->getBusinessNameMapping( 'lastName' )              => $_POST[$this->getBusinessNameMapping( 'lastName' )],
            $this->getBusinessNameMapping( 'language' )              => $language,
            $this->getBusinessNameMapping( 'userSpecialty' )         => $userSpecialty,
            $this->getBusinessNameMapping( 'customerType' )          => $_POST[$this->getBusinessNameMapping( 'customerType' )],
            $this->getBusinessNameMapping( 'apps' )                  => $apps,
            $this->getBusinessNameMapping( 'consents' )              => $consents,
            $this->getBusinessNameMapping( 'additionalSpecialties' ) => MMUserLogin::getAddSpecialties( $mainSpecialty ),
            $this->getBusinessNameMapping( 'countryOfRegistration' ) => $this->getCountryOfRegistration(),
            $this->getBusinessNameMapping( 'countryOfResidence' )    => $_POST[$this->getBusinessNameMapping( 'countryOfResidence' )],
        );

        if ( isset( $_POST[$this->getBusinessNameMapping( 'secondName' )] ) )
        {
            $unifiedParameters[$this->getBusinessNameMapping( 'secondName' )] = $_POST[$this->getBusinessNameMapping( 'secondName' )];
        }

        if ( !is_null($username))
            $unifiedParameters[$this->getBusinessNameMapping( 'userName' )] = $username;

        if ( $this instanceof ServiceUserUUMP )
        {

            $parameters = array(
                'data' => array(
                    'profile' => $unifiedParameters
                )
            );

            $formatDate                 = SolrSafeOperatorHelper::clusterIni('EsbDateConvert', 'FormatDate', 'merck.ini' );
            $availableDateParams        = SolrSafeOperatorHelper::clusterIni('EsbDateConvert', 'AvailableDateParams', 'merck.ini' );
            $skipParametersIfEmptyValue = SolrSafeOperatorHelper::clusterIni('SkipParametersIfEmptyValue', 'SkipParameter', 'merck.ini' );
           
            foreach ( $params as $key => $value )
            {                
                if ( array_key_exists( $key, $parameters['data']['profile'] ) )
                {
                    unset( $params[$key] );
                }
                if( !empty( $availableDateParams ) && isset( $availableDateParams[$key] ) && !empty($value)  )
                {
                    $params[$key] = $this->convertDateforUUMP( $value, $formatDate );
                }
                if( !empty( $skipParametersIfEmptyValue ) && isset( $skipParametersIfEmptyValue[$key] ) && empty($value) )
                {
                    unset( $params[$key] );
                }
            }
            $parameters['data']['profile'] = array_merge( $parameters['data']['profile'], $params );

            $sl = SystemLocale::fetchByClusterAndSystem( ClusterTool::clusterIdentifier(), 'esb_locale' );
            if ( !is_null( $sl ) )
            {
                $parameters['data']['profile']['locale'] = $sl;
            }
        }
        else
        {
            $parameters = array(
                'Data' => array_merge( $unifiedParameters, array( 'Params' => $params ) ),
                'cr'   => $this->getCountryOfRegistration()
            );
        }

        //LOG for locale field UUMP #36428
        if ( $this instanceof ServiceUserUUMP )
        {
            if( empty( $parameters['data']['profile']['locale'] ) )
            {
                $errorLocalMsg =  "\n\nEMPTY LOCALE:\nVALUES: " . json_encode( $parameters );
                \eZLog::write( $errorLocalMsg, 'esb_uump_locale.log');
            }
        }
        $result = $this->callWSHandler( $this->getEsbInterface( 'create' ), $parameters );

        if( SolrSafeOperatorHelper::featureIsActive('RegistrationAutologin') && SolrSafeOperatorHelper::feature('RegistrationAutologin', 'DisallowPendingUsers') == true && !isset( $_POST['register-helpdesk'] ))
        {
            if( $result['data']['profile']['validationStatus'] == 'PV' )
            {
                $result['RedirectPending'] = true;
                $result['RedirectPendingHref'] = eZINI::instance( 'site.ini' )->variable( 'SiteSettings', 'PendingUserStaticPage' );
                return $result;
            }
        }

        // if the registration was successful, we need to log the user on eZ + Backend side too
        if ( $this instanceof ServiceUserUUMP )
        {
            $noErrorOnCreate = ( isset( $result['data']['errorCode'] ) && $result['data']['errorCode'] == 0 );
        }
        else
        {
            $noErrorOnCreate = ( isset( $result['Data']['ErrorCode'] ) && $result['Data']['ErrorCode'] == 0 );
        }

        if ( $noErrorOnCreate )
        {
            $allowRedirect            = false;
            $availableRedirectContext = SolrSafeOperatorHelper::feature( 'RegistrationSettings', 'AvailableContextList' );
            $context                  = $_POST['context'] != '' ? $_POST['context'] : null;

            if ( $context !== null && !empty( $availableRedirectContext ) )
            {
                if ( is_array( $availableRedirectContext ) && in_array( $context, $availableRedirectContext ) )
                {
                    $allowRedirect = true;
                }
            }

            // BUT only there is no pending validation needed
            // OR if we are on that local validation page
            if ( ( !SolrSafeOperatorHelper::featureIsActive( 'OverrideWSHandler' ) || self::verifyHash() ) && !isset( $_POST['register-helpdesk'] ))
            {
                if ( $this instanceof ServiceUserUUMP )
                {
                    $userName   = isset( $result['data']['profile']['userName'] ) ? $result['data']['profile']['userName'] : null;
                    $userId     = $result['data']['profile']['userId'];
                    $userSpecialty = isset( $result['data']['profile']['userSpecialty'] ) ? preg_replace('#^A#', '', $result['data']['profile']['userSpecialty']) : null;
                }
                else
                {
                    $readValues = $this->read( array( "User_specialty" ), $result['Data']['Username'] );
                    $parameters = $parameters['Data']['Params'];
                    $userName = isset( $result['Data']['Username'] ) ? $result['Data']['Username'] : null;
                    $userSpecialty = isset( $readValues['Data']['Params']['User_specialty'] ) ? $readValues['Data']['Params']['User_specialty'] : null;
                }

                $businessNames = $this->getBusinessNamesForTicket();
                $ticketParams  = array();
                foreach ( $businessNames as $ticketParam => $businessName )
                {
                    if ( isset( $parameters['data']['profile'][$businessName] ) )
                    {
                        $ticketParams[$ticketParam] = $parameters['data']['profile'][$businessName];
                    }
                    elseif ( isset( $_POST[$businessName] ) )
                    {
                        $ticketParams[$ticketParam] = $_POST[$businessName];
                    }
                    elseif ( $businessName == $this->getBusinessNameMapping( 'countryOfRegistration' ) )
                    {
                        $ticketParams[$ticketParam] = $this->getCountryOfRegistration();
                    }
                    else
                    {
                        eZDebug::writeError( 'Could not get registration param: ' . $businessName );
                    }
                }

                if( $this instanceof ServiceUserUUMP )
                {
                    $ticketParams['Username'] = $userId;
                }
                elseif ( !empty($userName) )
                {
                    $ticketParams['Username'] = $userName;
                }
                
                if ( !empty($userSpecialty) )
                {
                    $ticketParams['User_specialty'] = $userSpecialty;
                }
                
                // used in response to log to the php backend
                $result['AllowRedirect'] = $allowRedirect;

                $ticketParams['toUValidated'] = true;

                MMUserLogin::loginUser( $ticketParams );
                $mmUser = MMUsers::getCurrentUserObject();
                $ticketParams['mmSettings']       = $mmUser->getMMSettings();
                $ticketParams['unorderedAppList'] = $mmUser->getApplicationList();
                $ticketParams['alterboxMsgReset'] = $mmUser->hasPreference('alterboxMsgReset') ? $mmUser->getPreferences('alterboxMsgReset') : true;
                $result['Ticket'] = MMUserLogin::encryptText( json_encode( $ticketParams ) );

            }
        }
        // Consult Popin for France | mobile check disabled - it fails on STG
        if (/* ContextTool::instance()->isMobile() && */ in_array(ClusterTool::clusterIdentifier(), array('cluster_france'))) 
        {
            CookieTool::destroyCookie('displayConsultMobile');
            CookieTool::destroyCookie('displayConsultMobile', '/', null);
            CookieTool::setCookie('displayConsultMobile', $mmUser->getConsult(), time() + ( 2 * 24 * 60 * 60 ));
        }

        if( isset( $_POST['register-helpdesk'] ))
        {
            $result['helpdeskRegister'] = '1';
        }


        return $result;
    }
    public function run()
    {
        $cluster = ClusterTool::clusterIdentifier();

        if ( !$cluster )
        {
            $this->debug( 'MMLyrisUserImportHandler : Used siteaccess is not a cluster, run the cronjob with a cluster siteaccess', 'Lyris' );
            return;
        }

        $db = eZDB::instance();
        /* @type $clusterMapping array */
        $clusterMapping = eZINI::instance( 'merck.ini' )->variable( 'ClusterSettings', 'CountryMapping' );

        try
        {
            $this->debug( 'MMLyrisUserImportHandler : BEGIN', 'Lyris' );

            $countries = array_keys( $clusterMapping, $cluster );

            foreach ( $countries as $currentCountryLanguage )
            {
                list( $currentCountry, $currentLanguage ) = explode( '|', $currentCountryLanguage );

                $this->debug( "MMLyrisUserImportHandler : Now treating country '$currentCountry' with language '$currentLanguage' (could be empty)", 'Lyris' );

                $userImportList = MMLyrisUserImport::fetchUnprocessedListByCountryLanguage( $currentCountry, $currentLanguage, null, false );

                foreach ( $userImportList as &$item )
                {
                    $username = trim( $item['username'] );
                    $country = trim( $item['country_registration'] );

                    $this->debug( 'Importing <' . $username . ' -- ' . $country . '>... ', 'Lyris' );
                    $db->begin();

                    $mainSpecialty = trim( $item['specialty'] );

                    $mmUser = MMUsers::fetchByIdAndCountry( $username, $country );
                    if ( empty( $mmUser ) )
                    {
                        $m = array();
                        if ( preg_match('#^216\.#', $mainSpecialty, $m) )
                        {
                            $contentSpecialty = UserSpecialityContentSpeciality::getContentSpeciality ( $mainSpecialty );
                            $specialties = MMUserLogin::getAddSpecialties( $contentSpecialty );
                        }
                        else
                            $specialties = MMUserLogin::getAddSpecialties( $mainSpecialty );

                        $applications = CountryAppsBar::fetchAppsBarApplicationIds( $item['customer_type'], $mainSpecialty, $country );
                        $customerType = $item['customer_type'];
                    }
                    else
                    {
                        $applications = $mmUser->getApplicationList();
                        $country = trim( $mmUser->attribute( 'country' ) );
                        $mainSpecialty = trim( $mmUser->userSpecialityId() );
                        $mSpe = trim( $mmUser->mainSpecialityId() );
                        $specialties = $mmUser->getSpecialities();

                        if ( ($i = array_search($mSpe, $specialties)) !== false )
                        {
                            unset($specialties[$i]);
                        }

                        $customerType = $mmUser->customerTypeId();
                    }

                    $mmUserExport = MMLyrisUserExport::fetchByUsernameAndCountry( $username, $country );

                    // Remove old entry to be sure NULL values will be set :
                    if ( !empty( $mmUserExport ) )
                    {
                        $mmUserExport->remove();
                    }
                    $mmUserExport = new MMLyrisUserExport( array(
                        'username' => $username
                    ) );
                    $mmUserExport->setAttribute( 'processed', 0 );
                    $mmUserExport->setAttribute( 'country_registration', empty( $country ) ? null : $country );
                    $mmUserExport->setAttribute( 'user_specialty', empty( $mainSpecialty ) ? null : $mainSpecialty );
                    $additionalSpecialties = trim( implode( ',', $specialties ) );
                    $mmUserExport->setAttribute( 'additional_specialties', empty( $additionalSpecialties ) ? null : $additionalSpecialties );
                    $mmUserExport->setAttribute( 'apps', $this->createXML( $applications ) );
                    $mmUserExport->setAttribute( 'customer_type', $customerType );

                    $mmUserExport->store();

                    $mmUserImport = MMLyrisUserImport::fetchByUsernameAndCountry( $username, $country );

                    if ( $mmUserImport instanceof MMLyrisUserImport )
                    {
                        $mmUserImport->setAttribute( 'processed', 1 );
                        $mmUserImport->store();
                    }
                    else
                    {
                        $this->debug( "User '$username' does not exist in '$country' !!!", 'LYRIS IMPORT ERROR', eZDebug::LEVEL_ERROR );
                    }

                    $db->commit();
                    $this->debug( '... DONE.', 'Lyris' );

                }
                $this->debug( count( $userImportList ) . ' items treated', 'MMLyrisUserImportHandler : END' );
            }
        }
        catch ( Exception $e )
        {
            $this->debug( $e, 'LYRIS IMPORT ERROR', eZDebug::LEVEL_ERROR );
            $db->rollback();
        }
    }
Ejemplo n.º 3
0
    /**
     * @return string
     */
    public function mainSpecialityId()
    {
        if( is_null($this->_mainSpecialityId) )
        {
            $userSpeciality = $this->userSpecialityId();

            if ( $userSpeciality )
            {
                $this->_mainSpecialityId = UserSpecialityContentSpeciality::getContentSpeciality ( $userSpeciality );
            }
        }

        return $this->_mainSpecialityId;
    }
    /**
     * @return array[]
     */
    static function getMapping()
    {
        if ( !empty($_mapping) )
        {
            return self::$_mapping;
        }
        
        $mapping = CacheTool::dailyValue('userSpeMapping');
        
        if ( $mapping === false || is_null($mapping) )
        {
            $conditionList = ClusterTool::clusterOverride( array( 'is_available' => '1' ) );

            foreach ($conditionList as $condition)
            {
                $mapping = self::fetchObjectList(self::definition(), null, $condition, false);
    
                if ( is_array($mapping) && count($mapping) > 0 )
                {
                    break;
                }
            }
            
            $mapping = self::flattenMapping($mapping);

            self::$_mapping = $mapping;

            CacheTool::dailyValue('userSpeMapping', $mapping);
        }
        else
        {
            self::$_mapping = $mapping;
        }
        
        return $mapping;
    }
Ejemplo n.º 5
0
    /**
     * @param array $uncrytedTicket
     * @return MMUsers
     */
    public static function createOrUpdateMMUser( $uncrytedTicket )
    {
        $userId = $uncrytedTicket['uuid'];
        $customerType = $uncrytedTicket['customerType'];
        if ( isset($uncrytedTicket['userSpeciality']) )
        {
            $userSpeciality = $uncrytedTicket['userSpeciality'];
        }
        else
        {
            $userSpeciality = $uncrytedTicket['mainSpeciality'];
        }
        $state = $uncrytedTicket['state'];
        $country = eZIni::instance('site.ini')->variable('RegionalSettings','CountryOfRegistration');
        $language = $uncrytedTicket['language'];
        /**
         * @todo: check $language entry format and parse it if needed to get an iso code on 2 chars
         */
        $iniMapping = eZINI::instance('mercktaxonomymapping.ini');
        $taxonomyType = $iniMapping->variable( 'Taxonomy', 'SpecialtiesTaxonomyType');

        $specialtiesMappingINI = $iniMapping->variable( 'Taxonomy', 'Specialties' );
        $customerTypesMappingINI = $iniMapping->variable( 'Taxonomy', 'CustomerTypes' );

        if($taxonomyType != "transitive")
        {
            if ( isset( $customerTypesMappingINI[$customerType] ) )
            {
                $customerType = $customerTypesMappingINI[$customerType];
            }
            else
            {
                $customerType = $customerTypesMappingINI['Default'];
                self::updateDBWithEmptyValue( 'empty-CT', $userId, $country );
            }

            if ( isset( $specialtiesMappingINI[$userSpeciality] ) )
            {
                $userSpeciality = $specialtiesMappingINI[$userSpeciality];
            }
            else
            {
                $userSpeciality = $specialtiesMappingINI['Default'];
                self::updateDBWithEmptyValue( 'empty-SPE', $userId, $country );
            }
        }
        else
        {
            $customerTypesMapping = SolrSafeOperatorHelper::getCustomerTypes();
            if ( !isset( $customerTypesMapping["$customerType"] ) )
            {
                // fill with default value
                $customerType = $customerTypesMappingINI['Default'];
                self::updateDBWithEmptyValue( 'empty-CT', $userId, $country );
            }

            $specialtiesMapping = SolrSafeOperatorHelper::getUserSpecialities();
            if ( !isset( $specialtiesMapping[(string)$userSpeciality] ) )
            {
                // fill with default value
                $userSpeciality = $specialtiesMappingINI['Default'];
                self::updateDBWithEmptyValue( 'empty-SPE', $userId, $country );
            }
        }

        /** @var MMUsers $user */
        $user = MMUsers::fetchByIdAndCountry( $userId, $country );
        $isModifiedUser = false;

        if ( $user )
        {
            if ( $customerType != $user->attribute('customer_type') )
            {
                $user->setAttribute('customer_type', $customerType);
                $isModifiedUser = true;
            }
            if ( $userSpeciality !== $user->attribute('user_speciality') )
            {
                $mainSpeciality = UserSpecialityContentSpeciality::getContentSpeciality ( $userSpeciality );
                $defaultAdditionalSpecialities = MMUserLogin::getAddSpecialties($mainSpeciality);

                $user->setAttribute('user_speciality', $userSpeciality);

                // mapping main_spe additional spe
                $preferences = $user->getPreferences();
                $userAditionalSpecialities = $preferences['specialities'];
                array_shift($userAditionalSpecialities);
                $tmp = array_diff( $userAditionalSpecialities, $defaultAdditionalSpecialities );
                if( empty( $tmp ) )    // we don't modify the user spes if he has changed his selection
                {
                    $preferences["specialities"] = MMUserLogin::getAddSpecialties($mainSpeciality);
                    $user->setPreferences($preferences);
                }
                $user->setPreferences($preferences);

                // The user specialty has been modified, we need to update it for Quiz-type applications of the current cluster
                if( CacheApplicationTool::buildLocalizedApplicationByIdentifier('train-the-brain') instanceof ApplicationLocalized)
                {
                    $playerScoring = QuizPlayerScoring::fetchOneBy( array( 'application_id' => (int)$app->applicationObject->id, 'uuid' => $user->attribute( 'uuid' ) ) );
                    // Checking if the current user has scored at least once for the application
                    if( $playerScoring )
                    {
                        foreach( FacetFilteringTool::getTaxoTranslationWithIDs( 'user_specialty' ) as $k => $t )
                        {
                            if( ($k . "") === ($userSpeciality . "") )
                            {
                                // Updating the user specialty id in the player scoring table
                                $playerScoring->setAttribute( 'user_specialty', $t['id'] );
                                $playerScoring->store();
                            }
                        }
                        // Scheduling a ranking update
                        QuizPendingRankingUpdate::add( $playerScoring->attribute( 'global_ranking' ), $app->applicationObject->id );
                    }
                }

                $isModifiedUser = true;
            }

            if ( $country != $user->attribute('country') )
            {
                $user->setAttribute('country', $country);
                $isModifiedUser = true;
            }

            if( $language != $user->attribute( 'language' ) )
            {
                $user->setAttribute('language', $language );
                $isModifiedUser = true;
            }

            if ( $state != $user->attribute('state') )
            {
                $user->setAttribute('state', $state);
                $isModifiedUser = true;
            }

            if ( $isModifiedUser )
            {
                $user->setAttribute('date_update', time());
                $user->store();
            }

            // set gpnotebook hand shake data in preferences
            if($user->getGPNotebookHS())
            {
                SolrSafeOperatorHelper::getAndStoreGPNotebookHS();
            }
        }
        else
        {
            $mainSpeciality = UserSpecialityContentSpeciality::getContentSpeciality ( $userSpeciality );
            $insertedArray = array (
                'uuid' => $userId,
                'customer_type' => $customerType,
                'user_speciality' => $userSpeciality,
                'country' => $country,
                'language' => $language,
                'date_update' => time(),
                'state' => $state,
            );

            $user = new MMUsers ($insertedArray);
            $user->store();

            // mapping main_spe additional spe
            $preferences = $user->getPreferences();
            $preferences["specialities"] = MMUserLogin::getAddSpecialties($mainSpeciality);
            $user->setPreferences($preferences);

            $isModifiedUser = true;
        }

        if ( $isModifiedUser )
        {
            // Tag Lyris user to be reimported :
            $user->tagLyrisToProcess();
        }

        return $user;
    }
    /**
     * @param array[] $esbData
     * @return array
     * @throws Exception
     * @throws ezcLogWriterException
     */
    private static function mapESBDataToWS($esbData)
    {
        $postData = array(
            'data' => array(
                'Username'                  => $esbData['Data']['Username'],
                'Password'                  => $esbData['Data']['Password'],
                'Email_address'             => $esbData['Data']['Email_address'],
                'Firstname'                 => $esbData['Data']['Firstname'],
                'Lastname'                  => $esbData['Data']['Lastname'],
                'Customer_type'             => $esbData['Data']['Customer_type'],
                'Country_of_registration'   => $esbData['Data']['Country_of_registration'],
                'Language'                  => $esbData['Data']['Language'],
                'Params'                    => array(
                    'count'          => $esbData['Data']['Params']['count'],
                    'Address_Line_1' => $esbData['Data']['Params']['Address_Line_1'],
                    'Address_Line_2' => isset($esbData['Data']['Params']['Address_Line_2']) ? $esbData['Data']['Params']['Address_Line_2'] : "",
                    'License_number' => $esbData['Data']['Params']['License_number']
                ),
                'Secret_question'           => $esbData['Data']['Params']['Secret_question'],
                'Secret_answer'             => $esbData['Data']['Params']['Secret_answer'],
                'Salutation'                => $esbData['Data']['Params']['Salutation'],
                'Gender'                    => $esbData['Data']['Params']['Gender'],
                'Birth_date'                => $esbData['Data']['Params']["Birth_date"],
                'Postal_code'               => $esbData['Data']['Params']['Postal_Code'],
                'City'                      => $esbData['Data']['Params']['City'],
                'Phone_number'              => $esbData['Data']['Params']['Phone_number'],
                'Referral'                  => $esbData['Data']['Params']['Referral'],
                'Referral_specify'          => $esbData['Data']['Params']['Referral_specify'],
                'User_specialty'            => $esbData['Data']['User_specialty'],
                'Terms_of_use'              => $esbData['Data']['Params']['Terms_of_use'],
                'Privacy_policy'            => $esbData['Data']['Params']['Privacy_policy']
            )
        );

        if(isset($_POST['Uni__email_optin']))
        {
            $postData['data']['Uni__email_optin'] = $_POST['Uni__email_optin'];
        }

        if(isset($_POST['Msd__email_optin']))
        {
            $postData['data']['Uni__email_optin'] = $_POST['Msd__email_optin'];
        }

        if(isset($_POST['Automated_registration']))
        {
            $postData['data']['Automated_registration'] = $_POST['Automated_registration'];
        }

        $mapping = UserSpecialityContentSpeciality::getMapping();
        if(array_key_exists($postData['data']['User_specialty'], $mapping))
        {
            $postData['data']['Main_specialty'] = $mapping[$postData['data']['User_specialty']]['c_spe'];
        }

        self::instance()->logger->log(json_encode($postData), ezcLog::INFO);
        return $postData;
    }